forked from c9s/bbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hull.go
84 lines (71 loc) · 1.88 KB
/
hull.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
package indicator
import (
"math"
"github.com/c9s/bbgo/pkg/types"
)
// Refer: Hull Moving Average
// Refer URL: https://fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/hull-moving-average
//go:generate callbackgen -type HULL
type HULL struct {
types.SeriesBase
types.IntervalWindow
ma1 *EWMA
ma2 *EWMA
result *EWMA
updateCallbacks []func(value float64)
}
func (inc *HULL) Update(value float64) {
if inc.result == nil {
inc.SeriesBase.Series = inc
inc.ma1 = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window / 2}}
inc.ma2 = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window}}
inc.result = &EWMA{IntervalWindow: types.IntervalWindow{inc.Interval, int(math.Sqrt(float64(inc.Window)))}}
}
inc.ma1.Update(value)
inc.ma2.Update(value)
inc.result.Update(2*inc.ma1.Last() - inc.ma2.Last())
}
func (inc *HULL) Last() float64 {
if inc.result == nil {
return 0
}
return inc.result.Last()
}
func (inc *HULL) Index(i int) float64 {
if inc.result == nil {
return 0
}
return inc.result.Index(i)
}
func (inc *HULL) Length() int {
if inc.result == nil {
return 0
}
return inc.result.Length()
}
var _ types.SeriesExtend = &HULL{}
// TODO: should we just ignore the possible overlapping?
func (inc *HULL) CalculateAndUpdate(allKLines []types.KLine) {
doable := false
if inc.ma1 == nil || inc.ma1.Length() == 0 {
doable = true
}
for _, k := range allKLines {
if !doable && k.EndTime.After(inc.ma1.EndTime) {
doable = true
}
if doable {
inc.Update(k.Close.Float64())
inc.EmitUpdate(inc.Last())
}
}
}
func (inc *HULL) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
}
func (inc *HULL) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}