indicator: rewrite Multiply to make it consistent with Subtract

This commit is contained in:
c9s 2023-06-04 14:08:20 +08:00
parent aae7fd310e
commit 97e7b93997
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
3 changed files with 39 additions and 12 deletions

View File

@ -35,6 +35,10 @@ func (f *Float64Series) Length() int {
return len(f.slice)
}
func (f *Float64Series) Slice() floats.Slice {
return f.slice
}
func (f *Float64Series) PushAndEmit(x float64) {
f.slice.Push(x)
f.EmitUpdate(x)

View File

@ -5,8 +5,8 @@ type MACDStream struct {
shortWindow, longWindow, signalWindow int
fastEWMA, slowEWMA, signal *EWMAStream
histogram *SubtractStream
FastEWMA, SlowEWMA, Signal *EWMAStream
Histogram *SubtractStream
}
func MACD2(source Float64Source, shortWindow, longWindow, signalWindow int) *MACDStream {
@ -21,9 +21,9 @@ func MACD2(source Float64Source, shortWindow, longWindow, signalWindow int) *MAC
shortWindow: shortWindow,
longWindow: longWindow,
signalWindow: signalWindow,
fastEWMA: fastEWMA,
slowEWMA: slowEWMA,
signal: signal,
histogram: histogram,
FastEWMA: fastEWMA,
SlowEWMA: slowEWMA,
Signal: signal,
Histogram: histogram,
}
}

View File

@ -1,19 +1,42 @@
package indicator
import "github.com/c9s/bbgo/pkg/datatype/floats"
type MultiplyStream struct {
Float64Series
multiplier float64
a, b floats.Slice
}
func Multiply(source Float64Source, multiplier float64) *MultiplyStream {
func Multiply(a, b Float64Source) *MultiplyStream {
s := &MultiplyStream{
Float64Series: NewFloat64Series(),
multiplier: multiplier,
}
s.Bind(source, s)
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 *MultiplyStream) Calculate(v float64) float64 {
return v * s.multiplier
func (s *MultiplyStream) calculate() {
if s.a.Length() != s.b.Length() {
return
}
if s.a.Length() > s.slice.Length() {
var numNewElems = s.a.Length() - s.slice.Length()
var tailA = s.a.Tail(numNewElems)
var tailB = s.b.Tail(numNewElems)
var tailC = tailA.Mul(tailB)
for _, f := range tailC {
s.slice.Push(f)
s.EmitUpdate(f)
}
}
}