forked from c9s/bbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pivot.go
117 lines (90 loc) · 2.31 KB
/
pivot.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
package indicator
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
//go:generate callbackgen -type Pivot
type Pivot struct {
types.IntervalWindow
// Values
Lows floats.Slice // higher low
Highs floats.Slice // lower high
EndTime time.Time
updateCallbacks []func(valueLow, valueHigh float64)
}
func (inc *Pivot) LastLow() float64 {
if len(inc.Lows) == 0 {
return 0.0
}
return inc.Lows[len(inc.Lows)-1]
}
func (inc *Pivot) LastHigh() float64 {
if len(inc.Highs) == 0 {
return 0.0
}
return inc.Highs[len(inc.Highs)-1]
}
func (inc *Pivot) CalculateAndUpdate(klines []types.KLine) {
if len(klines) < inc.Window {
return
}
var end = len(klines) - 1
var lastKLine = klines[end]
// skip old data
if inc.EndTime != zeroTime && lastKLine.GetEndTime().Before(inc.EndTime) {
return
}
recentT := klines[end-(inc.Window-1) : end+1]
l, h, err := calculatePivot(recentT, inc.Window, types.KLineLowPriceMapper, types.KLineHighPriceMapper)
if err != nil {
log.WithError(err).Error("can not calculate pivots")
return
}
if l > 0.0 {
inc.Lows.Push(l)
}
if h > 0.0 {
inc.Highs.Push(h)
}
if len(inc.Lows) > MaxNumOfVOL {
inc.Lows = inc.Lows[MaxNumOfVOLTruncateSize-1:]
}
if len(inc.Highs) > MaxNumOfVOL {
inc.Highs = inc.Highs[MaxNumOfVOLTruncateSize-1:]
}
inc.EndTime = klines[end].GetEndTime().Time()
inc.EmitUpdate(l, h)
}
func (inc *Pivot) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
}
func (inc *Pivot) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func calculatePivot(klines []types.KLine, window int, valLow types.KLineValueMapper, valHigh types.KLineValueMapper) (float64, float64, error) {
length := len(klines)
if length == 0 || length < window {
return 0., 0., fmt.Errorf("insufficient elements for calculating with window = %d", window)
}
var lows floats.Slice
var highs floats.Slice
for _, k := range klines {
lows.Push(valLow(k))
highs.Push(valHigh(k))
}
pl := 0.
if lows.Min() == lows.Last(int(window/2.)-1) {
pl = lows.Min()
}
ph := 0.
if highs.Max() == highs.Last(int(window/2.)-1) {
ph = highs.Max()
}
return pl, ph, nil
}