2020-10-28 01:13:57 +00:00
|
|
|
package indicator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type EWMA struct {
|
2020-10-28 01:43:19 +00:00
|
|
|
Interval types.Interval
|
2020-10-28 01:13:57 +00:00
|
|
|
Window int
|
|
|
|
Values Float64Slice
|
|
|
|
EndTime time.Time
|
|
|
|
}
|
|
|
|
|
2020-10-28 08:27:25 +00:00
|
|
|
func (inc *EWMA) Last() float64 {
|
|
|
|
return inc.Values[len(inc.Values)-1]
|
|
|
|
}
|
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
func (inc *EWMA) calculateAndUpdate(kLines []types.KLine) {
|
|
|
|
if len(kLines) < inc.Window {
|
|
|
|
// we can't calculate
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var index = len(kLines) - 1
|
|
|
|
var lastK = kLines[index]
|
|
|
|
var multiplier = 2.0 / float64(inc.Window+1)
|
|
|
|
|
|
|
|
if inc.EndTime != zeroTime && lastK.EndTime.Before(inc.EndTime) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var recentK = kLines[index-(inc.Window-1) : index+1]
|
|
|
|
if len(inc.Values) > 0 {
|
|
|
|
var previousEWMA = inc.Values[len(inc.Values)-1]
|
2020-10-28 08:27:25 +00:00
|
|
|
var ewma = lastK.Close*multiplier + previousEWMA*(1-multiplier)
|
2020-10-28 01:13:57 +00:00
|
|
|
inc.Values.Push(ewma)
|
|
|
|
} else {
|
|
|
|
// The first EWMA is actually SMA
|
|
|
|
var sma = calculateSMA(recentK)
|
|
|
|
inc.Values.Push(sma)
|
|
|
|
}
|
|
|
|
|
|
|
|
inc.EndTime = kLines[index].EndTime
|
|
|
|
}
|
|
|
|
|
2020-10-28 08:27:25 +00:00
|
|
|
type KLineWindowUpdater interface {
|
|
|
|
OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *EWMA) BindMarketDataStore(updater KLineWindowUpdater) {
|
|
|
|
updater.OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if inc.Interval != interval {
|
2020-10-28 01:13:57 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if inc.EndTime != zeroTime && inc.EndTime.Before(inc.EndTime) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-10-28 08:27:25 +00:00
|
|
|
inc.calculateAndUpdate(window)
|
2020-10-28 01:13:57 +00:00
|
|
|
})
|
|
|
|
}
|