2023-07-10 08:54:22 +00:00
|
|
|
package indicatorv2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
2023-06-09 10:36:54 +00:00
|
|
|
|
2023-06-09 10:38:12 +00:00
|
|
|
type BOLLStream struct {
|
2023-06-09 10:36:54 +00:00
|
|
|
// the band series
|
2023-07-10 08:54:22 +00:00
|
|
|
*types.Float64Series
|
2023-06-09 10:36:54 +00:00
|
|
|
|
2023-07-10 08:54:22 +00:00
|
|
|
UpBand, DownBand *types.Float64Series
|
2023-06-09 10:36:54 +00:00
|
|
|
|
|
|
|
window int
|
|
|
|
k float64
|
|
|
|
|
|
|
|
SMA *SMAStream
|
|
|
|
StdDev *StdDevStream
|
|
|
|
}
|
|
|
|
|
|
|
|
// BOOL2 is bollinger indicator
|
|
|
|
// the data flow:
|
|
|
|
//
|
|
|
|
// priceSource ->
|
|
|
|
//
|
|
|
|
// -> calculate SMA
|
|
|
|
// -> calculate stdDev -> calculate bandWidth -> get latest SMA -> upBand, downBand
|
2023-07-10 08:54:22 +00:00
|
|
|
func BOLL(source types.Float64Source, window int, k float64) *BOLLStream {
|
2023-06-09 10:36:54 +00:00
|
|
|
// bind these indicators before our main calculator
|
2023-07-11 02:26:38 +00:00
|
|
|
sma := SMA(source, window)
|
2023-07-10 08:54:22 +00:00
|
|
|
stdDev := StdDev(source, window)
|
2023-06-09 10:36:54 +00:00
|
|
|
|
2023-06-09 10:38:12 +00:00
|
|
|
s := &BOLLStream{
|
2023-07-10 08:54:22 +00:00
|
|
|
Float64Series: types.NewFloat64Series(),
|
|
|
|
UpBand: types.NewFloat64Series(),
|
|
|
|
DownBand: types.NewFloat64Series(),
|
2023-06-09 10:36:54 +00:00
|
|
|
window: window,
|
|
|
|
k: k,
|
|
|
|
SMA: sma,
|
|
|
|
StdDev: stdDev,
|
|
|
|
}
|
|
|
|
|
|
|
|
// on band update
|
|
|
|
s.Float64Series.OnUpdate(func(band float64) {
|
|
|
|
mid := s.SMA.Last(0)
|
|
|
|
s.UpBand.PushAndEmit(mid + band)
|
|
|
|
s.DownBand.PushAndEmit(mid - band)
|
|
|
|
})
|
2024-01-24 08:25:28 +00:00
|
|
|
|
|
|
|
s.Bind(source, s)
|
2023-06-09 10:36:54 +00:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2023-06-09 10:38:12 +00:00
|
|
|
func (s *BOLLStream) Calculate(v float64) float64 {
|
2023-06-09 10:36:54 +00:00
|
|
|
stdDev := s.StdDev.Last(0)
|
|
|
|
band := stdDev * s.k
|
|
|
|
return band
|
|
|
|
}
|