indicator: move out subtract stream

This commit is contained in:
c9s 2023-05-29 21:37:31 +08:00
parent f067c92733
commit 8c7962f07f
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 49 additions and 40 deletions

View File

@ -72,43 +72,3 @@ func (s *EWMAStream) calculate(v float64) float64 {
m := s.multiplier
return (1.0-m)*last + m*v
}
type SubtractStream struct {
Float64Updater
types.SeriesBase
a, b, c floats.Slice
i int
}
func Subtract(a, b Float64Source) *SubtractStream {
s := &SubtractStream{}
s.SeriesBase.Series = s.c
a.OnUpdate(func(v float64) {
s.a.Push(v)
s.calculate()
})
b.OnUpdate(func(v float64) {
s.b.Push(v)
s.calculate()
})
return s
}
func (s *SubtractStream) calculate() {
if s.a.Length() != s.b.Length() {
return
}
if s.a.Length() > s.c.Length() {
var numNewElems = s.a.Length() - s.c.Length()
var tailA = s.a.Tail(numNewElems)
var tailB = s.b.Tail(numNewElems)
var tailC = tailA.Sub(tailB)
for _, f := range tailC {
s.c.Push(f)
s.EmitUpdate(f)
}
}
}

49
pkg/indicator/subtract.go Normal file
View File

@ -0,0 +1,49 @@
package indicator
import (
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
// SubtractStream subscribes 2 upstream data, and then subtract these 2 values
type SubtractStream struct {
Float64Updater
types.SeriesBase
a, b, c floats.Slice
i int
}
// Subtract creates the SubtractStream object
// subtract := Subtract(longEWMA, shortEWMA)
func Subtract(a, b Float64Source) *SubtractStream {
s := &SubtractStream{}
s.SeriesBase.Series = s.c
a.OnUpdate(func(v float64) {
s.a.Push(v)
s.calculate()
})
b.OnUpdate(func(v float64) {
s.b.Push(v)
s.calculate()
})
return s
}
func (s *SubtractStream) calculate() {
if s.a.Length() != s.b.Length() {
return
}
if s.a.Length() > s.c.Length() {
var numNewElems = s.a.Length() - s.c.Length()
var tailA = s.a.Tail(numNewElems)
var tailB = s.b.Tail(numNewElems)
var tailC = tailA.Sub(tailB)
for _, f := range tailC {
s.c.Push(f)
s.EmitUpdate(f)
}
}
}