Skip to content

Commit

Permalink
indicator: add v2 sma
Browse files Browse the repository at this point in the history
  • Loading branch information
c9s committed Jun 1, 2023
1 parent 47e869a commit ee8bbe3
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 33 deletions.
19 changes: 0 additions & 19 deletions pkg/indicator/sma.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package indicator

import (
"fmt"
"time"

"github.com/c9s/bbgo/pkg/datatype/floats"
Expand Down Expand Up @@ -82,21 +81,3 @@ func (inc *SMA) LoadK(allKLines []types.KLine) {
inc.PushK(k)
}
}

func calculateSMA(kLines []types.KLine, window int, priceF KLineValueMapper) (float64, error) {
length := len(kLines)
if length == 0 || length < window {
return 0.0, fmt.Errorf("insufficient elements for calculating SMA with window = %d", window)
}
if length != window {
return 0.0, fmt.Errorf("too much klines passed in, requires only %d klines", window)
}

sum := 0.0
for _, k := range kLines {
sum += priceF(k)
}

avg := sum / float64(window)
return avg, nil
}
16 changes: 2 additions & 14 deletions pkg/indicator/v2_rsi.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,11 @@ func RSI2(source Float64Source, window int) *RSIStream {
Float64Series: NewFloat64Series(),
window: window,
}

if sub, ok := source.(Float64Subscription); ok {
sub.AddSubscriber(s.calculateAndPush)
} else {
source.OnUpdate(s.calculateAndPush)
}

s.Bind(source, s)
return s
}

func (s *RSIStream) calculate(_ float64) float64 {
func (s *RSIStream) Calculate(_ float64) float64 {
var gainSum, lossSum float64
var sourceLen = s.source.Length()
var limit = min(s.window, sourceLen)
Expand All @@ -48,9 +42,3 @@ func (s *RSIStream) calculate(_ float64) float64 {
rsi := 100.0 - (100.0 / (1.0 + rs))
return rsi
}

func (s *RSIStream) calculateAndPush(x float64) {
rsi := s.calculate(x)
s.slice.Push(rsi)
s.EmitUpdate(rsi)
}
29 changes: 29 additions & 0 deletions pkg/indicator/v2_sma.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package indicator

import "github.com/c9s/bbgo/pkg/types"

type SMAStream struct {
Float64Series
window int
rawValues *types.Queue
}

func SMA2(source Float64Source, window int) *SMAStream {
s := &SMAStream{
Float64Series: NewFloat64Series(),
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() {
s.slice.Truncate(MaxNumOfSMA)
}

0 comments on commit ee8bbe3

Please sign in to comment.