bbgo_origin/pkg/indicator/pivotlow.go

106 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-07-26 08:50:45 +00:00
package indicator
import (
"time"
"github.com/c9s/bbgo/pkg/datatype/floats"
2022-07-26 08:50:45 +00:00
"github.com/c9s/bbgo/pkg/types"
)
//go:generate callbackgen -type PivotLow
type PivotLow struct {
2022-07-26 09:00:17 +00:00
types.SeriesBase
2022-07-26 08:50:45 +00:00
2022-07-26 17:30:43 +00:00
types.IntervalWindow
Lows floats.Slice
Values floats.Slice
2022-07-26 08:50:45 +00:00
EndTime time.Time
updateCallbacks []func(value float64)
}
2022-07-26 16:58:05 +00:00
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()
}
2022-07-26 09:00:17 +00:00
func (inc *PivotLow) Update(value float64) {
if len(inc.Lows) == 0 {
inc.SeriesBase.Series = inc
2022-07-26 08:50:45 +00:00
}
2022-07-26 09:00:17 +00:00
inc.Lows.Push(value)
2022-07-26 08:50:45 +00:00
2022-07-26 09:00:17 +00:00
if len(inc.Lows) < inc.Window {
2022-07-26 08:50:45 +00:00
return
}
low, ok := calculatePivotLow(inc.Lows, inc.Window, inc.RightWindow)
if !ok {
2022-07-26 08:50:45 +00:00
return
}
2022-07-26 09:00:17 +00:00
if low > 0.0 {
inc.Values.Push(low)
2022-07-26 08:50:45 +00:00
}
2022-07-26 09:00:17 +00:00
}
2022-07-26 08:50:45 +00:00
2022-07-26 09:00:17 +00:00
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
2022-07-26 08:50:45 +00:00
}
2022-07-26 17:58:05 +00:00
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
}
2022-07-26 08:50:45 +00:00
}
return val, true
2022-07-26 08:50:45 +00:00
}
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
})
}