-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
sma.go
109 lines (88 loc) · 2.2 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
package indicator
import (
"fmt"
"time"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
const MaxNumOfSMA = 5_000
const MaxNumOfSMATruncateSize = 100
//go:generate callbackgen -type SMA
type SMA struct {
types.SeriesBase
types.IntervalWindow
Values floats.Slice
rawValues *types.Queue
EndTime time.Time
UpdateCallbacks []func(value float64)
}
func (inc *SMA) Last() float64 {
if inc.Values.Length() == 0 {
return 0.0
}
return inc.Values.Last()
}
func (inc *SMA) Index(i int) float64 {
if i >= inc.Values.Length() {
return 0.0
}
return inc.Values.Index(i)
}
func (inc *SMA) Length() int {
return inc.Values.Length()
}
func (inc *SMA) Clone() types.UpdatableSeriesExtend {
out := &SMA{
Values: inc.Values[:],
rawValues: inc.rawValues.Clone(),
EndTime: inc.EndTime,
}
out.SeriesBase.Series = out
return out
}
var _ types.SeriesExtend = &SMA{}
func (inc *SMA) Update(value float64) {
if inc.rawValues == nil {
inc.rawValues = types.NewQueue(inc.Window)
inc.SeriesBase.Series = inc
}
inc.rawValues.Update(value)
if inc.rawValues.Length() < inc.Window {
return
}
inc.Values.Push(types.Mean(inc.rawValues))
if len(inc.Values) > MaxNumOfSMA {
inc.Values = inc.Values[MaxNumOfSMATruncateSize-1:]
}
}
func (inc *SMA) BindK(target KLineClosedEmitter, symbol string, interval types.Interval) {
target.OnKLineClosed(types.KLineWith(symbol, interval, inc.PushK))
}
func (inc *SMA) PushK(k types.KLine) {
if inc.EndTime != zeroTime && k.EndTime.Before(inc.EndTime) {
return
}
inc.Update(k.Close.Float64())
inc.EndTime = k.EndTime.Time()
inc.EmitUpdate(inc.Values.Last())
}
func (inc *SMA) LoadK(allKLines []types.KLine) {
for _, k := range allKLines {
inc.PushK(k)
}
}
func calculateSMA(kLines []types.KLine, window int, priceF KLineValueMapper) (float64, error) {
length := len(kLines)
if length == 0 || length < window {
return 0.0, fmt.Errorf("insufficient elements for calculating SMA with window = %d", window)
}
if length != window {
return 0.0, fmt.Errorf("too much klines passed in, requires only %d klines", window)
}
sum := 0.0
for _, k := range kLines {
sum += priceF(k)
}
avg := sum / float64(window)
return avg, nil
}