bbgo_origin/pkg/indicator/v2/sma.go

34 lines
605 B
Go
Raw Permalink Normal View History

2023-07-10 08:54:22 +00:00
package indicatorv2
2023-06-01 00:11:30 +00:00
2023-07-10 08:54:22 +00:00
import (
"github.com/c9s/bbgo/pkg/types"
)
const MaxNumOfSMA = 5_000
2023-06-01 00:11:30 +00:00
type SMAStream struct {
2023-07-10 08:54:22 +00:00
*types.Float64Series
2023-06-01 00:11:30 +00:00
window int
rawValues *types.Queue
}
2023-07-11 02:26:38 +00:00
func SMA(source types.Float64Source, window int) *SMAStream {
2023-06-01 00:11:30 +00:00
s := &SMAStream{
2023-07-10 08:54:22 +00:00
Float64Series: types.NewFloat64Series(),
2023-06-01 00:11:30 +00:00
window: window,
rawValues: types.NewQueue(window),
}
s.Bind(source, s)
return s
}
func (s *SMAStream) Calculate(v float64) float64 {
s.rawValues.Update(v)
sma := s.rawValues.Mean(s.window)
return sma
}
func (s *SMAStream) Truncate() {
2023-07-10 08:54:22 +00:00
s.Slice = s.Slice.Truncate(MaxNumOfSMA)
2023-06-01 00:11:30 +00:00
}