bbgo_origin/pkg/indicator/pivot_low.go

83 lines
1.4 KiB
Go
Raw Normal View History

2022-07-26 08:50:45 +00:00
package indicator
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"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
2022-07-26 09:00:17 +00:00
Lows types.Float64Slice
2022-07-26 08:50:45 +00:00
Values types.Float64Slice
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
}
2022-07-26 09:00:17 +00:00
low, err := calculatePivotLow(inc.Lows, inc.Window)
2022-07-26 08:50:45 +00:00
if err != nil {
2022-07-26 09:00:17 +00:00
log.WithError(err).Errorf("can not calculate pivot low")
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 calculatePivotLow(lows types.Float64Slice, window int) (float64, error) {
length := len(lows)
2022-07-26 08:50:45 +00:00
if length == 0 || length < window {
return 0., fmt.Errorf("insufficient elements for calculating with window = %d", window)
}
2022-07-26 17:58:05 +00:00
end := length - 1
2022-07-26 17:43:36 +00:00
min := lows[end-(window-1):].Min()
2022-07-26 17:30:43 +00:00
if min == lows.Index(int(window/2.)-1) {
return min, nil
2022-07-26 08:50:45 +00:00
}
2022-07-26 17:30:43 +00:00
return 0., nil
2022-07-26 08:50:45 +00:00
}