-
Notifications
You must be signed in to change notification settings - Fork 0
/
ewma.go
72 lines (56 loc) · 1.6 KB
/
ewma.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
package indicator
import (
"time"
"github.com/c9s/bbgo/pkg/types"
)
//go:generate callbackgen -type EWMA
type EWMA struct {
types.IntervalWindow
Values Float64Slice
EndTime time.Time
UpdateCallbacks []func(value float64)
}
func (inc *EWMA) Last() float64 {
return inc.Values[len(inc.Values)-1]
}
func (inc *EWMA) calculateAndUpdate(kLines []types.KLine) {
if len(kLines) < inc.Window {
// we can't calculate
return
}
var index = len(kLines) - 1
var lastK = kLines[index]
// see https://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp
var multiplier = 2.0 / float64(inc.Window+1)
if inc.EndTime != zeroTime && lastK.EndTime.Before(inc.EndTime) {
return
}
inc.EndTime = kLines[index].EndTime
var recentK = kLines[index-(inc.Window-1) : index+1]
if len(inc.Values) > 0 {
var previousEWMA = inc.Values[len(inc.Values)-1]
var ewma = lastK.Close*multiplier + previousEWMA*(1-multiplier)
inc.Values.Push(ewma)
inc.EmitUpdate(ewma)
} else {
// The first EWMA is actually SMA
var sma = calculateSMA(recentK)
inc.Values.Push(sma)
inc.EmitUpdate(sma)
}
}
type KLineWindowUpdater interface {
OnKLineWindowUpdate(func(interval types.Interval, window types.KLineWindow))
}
func (inc *EWMA) 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 *EWMA) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}