-
-
Notifications
You must be signed in to change notification settings - Fork 277
/
pivotlow.go
105 lines (80 loc) · 1.81 KB
/
pivotlow.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
package indicator
import (
"time"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
//go:generate callbackgen -type PivotLow
type PivotLow struct {
types.SeriesBase
types.IntervalWindow
Lows floats.Slice
Values floats.Slice
EndTime time.Time
updateCallbacks []func(value float64)
}
func (inc *PivotLow) Length() int {
return inc.Values.Length()
}
func (inc *PivotLow) Last() float64 {
if len(inc.Values) == 0 {
return 0.0
}
return inc.Values.Last()
}
func (inc *PivotLow) Update(value float64) {
if len(inc.Lows) == 0 {
inc.SeriesBase.Series = inc
}
inc.Lows.Push(value)
if len(inc.Lows) < inc.Window {
return
}
low, ok := calculatePivotLow(inc.Lows, inc.Window, inc.RightWindow)
if !ok {
return
}
if low > 0.0 {
inc.Values.Push(low)
}
}
func (inc *PivotLow) PushK(k types.KLine) {
if k.EndTime.Before(inc.EndTime) {
return
}
inc.Update(k.Low.Float64())
inc.EndTime = k.EndTime.Time()
inc.EmitUpdate(inc.Last())
}
func calculatePivotF(values floats.Slice, left, right int, f func(a, pivot float64) bool) (float64, bool) {
length := len(values)
if right == 0 {
right = left
}
if length == 0 || length < left+right+1 {
return 0.0, false
}
end := length - 1
index := end - right
val := values[index]
for i := index - left; i <= index+right; i++ {
if i == index {
continue
}
// return if we found lower value
if !f(values[i], val) {
return 0.0, false
}
}
return val, true
}
func calculatePivotHigh(highs floats.Slice, left, right int) (float64, bool) {
return calculatePivotF(highs, left, right, func(a, pivot float64) bool {
return a < pivot
})
}
func calculatePivotLow(lows floats.Slice, left, right int) (float64, bool) {
return calculatePivotF(lows, left, right, func(a, pivot float64) bool {
return a > pivot
})
}