bbgo_origin/pkg/indicator/wwma.go

89 lines
1.8 KiB
Go
Raw Normal View History

2022-04-19 10:22:22 +00:00
package indicator
import (
"time"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
2022-04-19 10:22:22 +00:00
)
// Refer: Welles Wilder's Moving Average
// Refer URL: http://fxcorporate.com/help/MS/NOTFIFO/i_WMA.html
// TODO: Cannot see any difference between RMA and this
2022-04-19 10:22:22 +00:00
const MaxNumOfWWMA = 5_000
const MaxNumOfWWMATruncateSize = 100
//go:generate callbackgen -type WWMA
type WWMA struct {
types.SeriesBase
2022-04-19 10:22:22 +00:00
types.IntervalWindow
Values floats.Slice
2022-04-19 10:22:22 +00:00
LastOpenTime time.Time
UpdateCallbacks []func(value float64)
}
func (inc *WWMA) Update(value float64) {
if len(inc.Values) == 0 {
inc.SeriesBase.Series = inc
2022-04-19 10:22:22 +00:00
inc.Values.Push(value)
return
} else if len(inc.Values) > MaxNumOfWWMA {
inc.Values = inc.Values[MaxNumOfWWMATruncateSize-1:]
}
last := inc.Last(0)
2022-04-19 10:22:22 +00:00
wma := last + (value-last)/float64(inc.Window)
inc.Values.Push(wma)
}
func (inc *WWMA) Last(i int) float64 {
return inc.Values.Last(i)
2022-04-19 10:22:22 +00:00
}
func (inc *WWMA) Index(i int) float64 {
return inc.Last(i)
2022-04-19 10:22:22 +00:00
}
func (inc *WWMA) Length() int {
return len(inc.Values)
}
func (inc *WWMA) PushK(k types.KLine) {
inc.Update(k.Close.Float64())
}
func (inc *WWMA) CalculateAndUpdate(allKLines []types.KLine) {
2022-04-19 10:22:22 +00:00
if len(allKLines) < inc.Window {
// we can't calculate
return
}
doable := false
for _, k := range allKLines {
if !doable && k.StartTime.After(inc.LastOpenTime) {
doable = true
}
if doable {
inc.PushK(k)
2022-04-19 10:22:22 +00:00
inc.LastOpenTime = k.StartTime.Time()
inc.EmitUpdate(inc.Last(0))
2022-04-19 10:22:22 +00:00
}
}
}
func (inc *WWMA) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
2022-04-19 10:22:22 +00:00
}
func (inc *WWMA) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
var _ types.SeriesExtend = &WWMA{}