2020-10-28 01:13:57 +00:00
|
|
|
package indicator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Float64Slice []float64
|
|
|
|
|
|
|
|
func (s *Float64Slice) Push(v float64) {
|
|
|
|
*s = append(*s, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
var zeroTime time.Time
|
|
|
|
|
|
|
|
type SMA 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 *SMA) Last() float64 {
|
|
|
|
return inc.Values[len(inc.Values)-1]
|
|
|
|
}
|
|
|
|
|
2020-10-28 01:13:57 +00:00
|
|
|
func (inc *SMA) calculateAndUpdate(kLines []types.KLine) {
|
|
|
|
if len(kLines) < inc.Window {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var index = len(kLines) - 1
|
|
|
|
var kline = kLines[index]
|
|
|
|
|
|
|
|
if inc.EndTime != zeroTime && kline.EndTime.Before(inc.EndTime) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var recentK = kLines[index-(inc.Window-1) : index+1]
|
2020-10-28 01:43:19 +00:00
|
|
|
var sma = calculateSMA(recentK)
|
|
|
|
inc.Values.Push(sma)
|
2020-10-28 01:13:57 +00:00
|
|
|
inc.EndTime = kLines[index].EndTime
|
|
|
|
}
|
|
|
|
|
2020-10-28 23:40:02 +00:00
|
|
|
func (inc *SMA) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if inc.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if inc.EndTime != zeroTime && inc.EndTime.Before(inc.EndTime) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
inc.calculateAndUpdate(window)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *SMA) Bind(updater KLineWindowUpdater) {
|
|
|
|
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
|
2020-10-28 01:13:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func calculateSMA(kLines []types.KLine) float64 {
|
|
|
|
length := len(kLines)
|
2020-10-28 09:47:43 +00:00
|
|
|
|
|
|
|
if length == 0 {
|
|
|
|
return 0.0
|
|
|
|
}
|
|
|
|
|
|
|
|
sum := 0.0
|
2020-10-28 01:13:57 +00:00
|
|
|
for _, k := range kLines {
|
|
|
|
sum += k.Close
|
|
|
|
}
|
|
|
|
|
|
|
|
avg := sum / float64(length)
|
|
|
|
return avg
|
|
|
|
}
|