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) return len(f.slice)
} }
func (f *Float64Series) Slice() floats.Slice {
return f.slice
}
func (f *Float64Series) PushAndEmit(x float64) { func (f *Float64Series) PushAndEmit(x float64) {
f.slice.Push(x) f.slice.Push(x)
f.EmitUpdate(x) f.EmitUpdate(x)

View File

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

View File

@ -1,19 +1,42 @@
package indicator package indicator
import "github.com/c9s/bbgo/pkg/datatype/floats"
type MultiplyStream struct { type MultiplyStream struct {
Float64Series Float64Series
multiplier float64 a, b floats.Slice
} }
func Multiply(source Float64Source, multiplier float64) *MultiplyStream { func Multiply(a, b Float64Source) *MultiplyStream {
s := &MultiplyStream{ s := &MultiplyStream{
Float64Series: NewFloat64Series(), 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 return s
} }
func (s *MultiplyStream) Calculate(v float64) float64 { func (s *MultiplyStream) calculate() {
return v * s.multiplier 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)
}
}
} }