bbgo_origin/pkg/indicator/stoch.go

102 lines
1.9 KiB
Go
Raw Normal View History

2021-05-21 19:24:09 +00:00
package indicator
import (
"time"
"github.com/c9s/bbgo/pkg/types"
)
const DPeriod int = 3
/*
2021-05-21 21:52:10 +00:00
stoch implements stochastic oscillator indicator
2021-05-21 19:24:09 +00:00
Stochastic Oscillator
- https://www.investopedia.com/terms/s/stochasticoscillator.asp
*/
2021-05-21 21:52:10 +00:00
//go:generate callbackgen -type STOCH
type STOCH struct {
2021-05-21 19:24:09 +00:00
types.IntervalWindow
2021-05-22 12:20:48 +00:00
K types.Float64Slice
D types.Float64Slice
2021-05-21 19:24:09 +00:00
HighValues types.Float64Slice
LowValues types.Float64Slice
2021-05-21 19:24:09 +00:00
EndTime time.Time
UpdateCallbacks []func(k float64, d float64)
}
func (inc *STOCH) Update(high, low, cloze float64) {
inc.HighValues.Push(high)
inc.LowValues.Push(low)
2021-05-21 19:24:09 +00:00
lowest := inc.LowValues.Tail(inc.Window).Min()
highest := inc.HighValues.Tail(inc.Window).Max()
2021-05-21 19:24:09 +00:00
if highest == lowest {
inc.K.Push(50.0)
} else {
k := 100.0 * (cloze - lowest) / (highest - lowest)
inc.K.Push(k)
}
2021-05-21 19:24:09 +00:00
d := inc.K.Tail(DPeriod).Mean()
inc.D.Push(d)
}
2021-05-21 21:52:10 +00:00
func (inc *STOCH) LastK() float64 {
2021-05-21 19:24:09 +00:00
if len(inc.K) == 0 {
return 0.0
}
return inc.K[len(inc.K)-1]
}
2021-05-21 21:52:10 +00:00
func (inc *STOCH) LastD() float64 {
2021-05-21 19:24:09 +00:00
if len(inc.K) == 0 {
return 0.0
}
return inc.D[len(inc.D)-1]
}
func (inc *STOCH) PushK(k types.KLine) {
inc.Update(k.High.Float64(), k.Low.Float64(), k.Close.Float64())
}
func (inc *STOCH) CalculateAndUpdate(kLines []types.KLine) {
2021-05-21 19:24:09 +00:00
if len(kLines) < inc.Window || len(kLines) < DPeriod {
return
}
2022-03-28 19:19:29 +00:00
for _, k := range kLines {
2022-04-14 21:43:04 +00:00
if inc.EndTime != zeroTime && !k.EndTime.After(inc.EndTime) {
2021-05-21 19:24:09 +00:00
continue
}
inc.PushK(k)
2021-05-21 19:24:09 +00:00
}
2022-03-28 19:19:29 +00:00
inc.EmitUpdate(inc.LastK(), inc.LastD())
inc.EndTime = kLines[len(kLines)-1].EndTime.Time()
2021-05-21 19:24:09 +00:00
}
2021-05-21 21:52:10 +00:00
func (inc *STOCH) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
2021-05-21 19:24:09 +00:00
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
2021-05-21 19:24:09 +00:00
}
2021-05-21 21:52:10 +00:00
func (inc *STOCH) Bind(updater KLineWindowUpdater) {
2021-05-21 19:24:09 +00:00
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func (inc *STOCH) GetD() types.Series {
2022-04-08 09:48:33 +00:00
return &inc.D
}
func (inc *STOCH) GetK() types.Series {
2022-04-08 09:48:33 +00:00
return &inc.K
}