2020-09-16 04:28:15 +00:00
|
|
|
package bbgo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
|
2020-10-11 08:46:15 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
2020-09-16 04:28:15 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type MovingAverageIndicator struct {
|
2020-10-09 05:21:42 +00:00
|
|
|
store *MarketDataStore
|
2020-09-16 04:28:15 +00:00
|
|
|
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)]
|
2020-09-16 04:28:15 +00:00
|
|
|
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
|
2020-09-16 04:28:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
2020-09-16 04:28:15 +00:00
|
|
|
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)
|
|
|
|
}
|