bbgo_origin/bbgo/indicator.go

57 lines
1.0 KiB
Go
Raw Normal View History

package bbgo
import (
"math"
"time"
2020-10-05 06:25:58 +00:00
"github.com/c9s/bbgo/types"
)
type MovingAverageIndicator struct {
2020-10-09 05:21:42 +00:00
store *MarketDataStore
Period int
}
func NewMovingAverageIndicator(period int) *MovingAverageIndicator {
return &MovingAverageIndicator{
Period: period,
}
}
func (i *MovingAverageIndicator) handleUpdate(kline types.KLine) {
2020-10-09 05:21:42 +00:00
klines, ok := i.store.KLineWindows[Interval(kline.Interval)]
if !ok {
return
}
if len(klines) < i.Period {
return
}
// calculate ma
}
type IndicatorValue struct {
Value float64
2020-10-09 05:21:42 +00:00
Time time.Time
}
func calculateMovingAverage(klines types.KLineWindow, period int) (values []IndicatorValue) {
for idx := range klines[period:] {
offset := idx + period
2020-10-09 05:21:42 +00:00
sum := klines[offset-period : offset].ReduceClose()
values = append(values, IndicatorValue{
Time: klines[offset].GetEndTime(),
Value: math.Round(sum / float64(period)),
})
}
return values
}
func (i *MovingAverageIndicator) SubscribeStore(store *MarketDataStore) {
i.store = store
// register kline update callback
store.OnUpdate(i.handleUpdate)
}