bbgo_origin/pkg/indicator/pivot_low.go

75 lines
1.3 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 {
types.IntervalWindow
2022-07-26 09:00:17 +00:00
types.SeriesBase
2022-07-26 08:50:45 +00:00
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 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())
}
2022-07-26 09:56:31 +00:00
2022-07-26 09:00:17 +00:00
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 09:00:17 +00:00
var pv types.Float64Slice
for _, low := range lows {
pv.Push(low)
2022-07-26 08:50:45 +00:00
}
pl := 0.
if lows.Min() == lows.Index(int(window/2.)-1) {
pl = lows.Min()
}
return pl, nil
}