bbgo_origin/pkg/indicator/subtract.go

50 lines
977 B
Go
Raw Normal View History

2023-05-29 13:37:31 +00:00
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
2023-05-30 03:35:24 +00:00
a, b floats.Slice
i int
2023-05-29 13:37:31 +00:00
}
// Subtract creates the SubtractStream object
// subtract := Subtract(longEWMA, shortEWMA)
func Subtract(a, b Float64Source) *SubtractStream {
s := &SubtractStream{}
2023-05-30 03:35:24 +00:00
s.SeriesBase.Series = s.slice
2023-05-29 13:37:31 +00:00
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
}
2023-05-30 03:35:24 +00:00
if s.a.Length() > s.slice.Length() {
var numNewElems = s.a.Length() - s.slice.Length()
2023-05-29 13:37:31 +00:00
var tailA = s.a.Tail(numNewElems)
var tailB = s.b.Tail(numNewElems)
var tailC = tailA.Sub(tailB)
for _, f := range tailC {
2023-05-30 03:35:24 +00:00
s.slice.Push(f)
2023-05-29 13:37:31 +00:00
s.EmitUpdate(f)
}
}
}