forked from c9s/bbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vidya.go
101 lines (86 loc) · 2.19 KB
/
vidya.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
package indicator
import (
"math"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
// Refer: Variable Index Dynamic Average
// Refer URL: https://metatrader5.com/en/terminal/help/indicators/trend_indicators/vida
//go:generate callbackgen -type VIDYA
type VIDYA struct {
types.SeriesBase
types.IntervalWindow
Values floats.Slice
input floats.Slice
updateCallbacks []func(value float64)
}
func (inc *VIDYA) Update(value float64) {
if inc.Values.Length() == 0 {
inc.SeriesBase.Series = inc
inc.Values.Push(value)
inc.input.Push(value)
return
}
inc.input.Push(value)
if len(inc.input) > MaxNumOfEWMA {
inc.input = inc.input[MaxNumOfEWMATruncateSize-1:]
}
/*upsum := 0.
downsum := 0.
for i := 0; i < inc.Window; i++ {
if len(inc.input) <= i+1 {
break
}
diff := inc.input.Index(i) - inc.input.Index(i+1)
if diff > 0 {
upsum += diff
} else {
downsum += -diff
}
}
if upsum == 0 && downsum == 0 {
return
}
CMO := math.Abs((upsum - downsum) / (upsum + downsum))*/
change := types.Change(&inc.input)
CMO := math.Abs(types.Sum(change, inc.Window) / types.Sum(types.Abs(change), inc.Window))
alpha := 2. / float64(inc.Window+1)
inc.Values.Push(value*alpha*CMO + inc.Values.Last()*(1.-alpha*CMO))
if inc.Values.Length() > MaxNumOfEWMA {
inc.Values = inc.Values[MaxNumOfEWMATruncateSize-1:]
}
}
func (inc *VIDYA) Last() float64 {
return inc.Values.Last()
}
func (inc *VIDYA) Index(i int) float64 {
return inc.Values.Index(i)
}
func (inc *VIDYA) Length() int {
return inc.Values.Length()
}
var _ types.SeriesExtend = &VIDYA{}
func (inc *VIDYA) PushK(k types.KLine) {
inc.Update(k.Close.Float64())
}
func (inc *VIDYA) CalculateAndUpdate(allKLines []types.KLine) {
if inc.input.Length() == 0 {
for _, k := range allKLines {
inc.PushK(k)
inc.EmitUpdate(inc.Last())
}
} else {
k := allKLines[len(allKLines)-1]
inc.PushK(k)
inc.EmitUpdate(inc.Last())
}
}
func (inc *VIDYA) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
}
func (inc *VIDYA) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}