forked from c9s/bbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sma.go
118 lines (90 loc) · 2.35 KB
/
sma.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package indicator
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/types"
)
const MaxNumOfSMA = 5_000
const MaxNumOfSMATruncateSize = 100
var zeroTime time.Time
//go:generate callbackgen -type SMA
type SMA struct {
types.IntervalWindow
Values types.Float64Slice
Cache types.Float64Slice
EndTime time.Time
UpdateCallbacks []func(value float64)
}
func (inc *SMA) Last() float64 {
if len(inc.Values) == 0 {
return 0.0
}
return inc.Values[len(inc.Values)-1]
}
func (inc *SMA) Index(i int) float64 {
length := len(inc.Values)
if length == 0 || length-i-1 < 0 {
return 0.0
}
return inc.Values[length-i-1]
}
func (inc *SMA) Length() int {
return len(inc.Values)
}
var _ types.Series = &SMA{}
func (inc *SMA) Update(value float64) {
if len(inc.Cache) < inc.Window {
inc.Cache = append(inc.Cache, value)
if len(inc.Cache) == inc.Window {
inc.Values = append(inc.Values, types.Mean(&inc.Cache))
}
return
}
length := len(inc.Values)
newVal := (inc.Values[length-1]*float64(inc.Window-1) + value) / float64(inc.Window)
inc.Values = append(inc.Values, newVal)
}
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]
sma, err := calculateSMA(recentK, inc.Window, KLineClosePriceMapper)
if err != nil {
log.WithError(err).Error("SMA error")
return
}
inc.Values.Push(sma)
if len(inc.Values) > MaxNumOfSMA {
inc.Values = inc.Values[MaxNumOfSMATruncateSize-1:]
}
inc.EndTime = kLines[index].EndTime.Time()
inc.EmitUpdate(sma)
}
func (inc *SMA) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.calculateAndUpdate(window)
}
func (inc *SMA) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func calculateSMA(kLines []types.KLine, window int, priceF KLinePriceMapper) (float64, error) {
length := len(kLines)
if length == 0 || length < window {
return 0.0, fmt.Errorf("insufficient elements for calculating SMA with window = %d", window)
}
sum := 0.0
for _, k := range kLines {
sum += priceF(k)
}
avg := sum / float64(window)
return avg, nil
}