indicator/sma: clean CalculateAndUpdate and make cache field private

This commit is contained in:
c9s 2022-07-14 11:34:53 +08:00
parent 7696c9f21e
commit bbf01275cc
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 21 additions and 23 deletions

View File

@ -16,7 +16,7 @@ func Test_EMV(t *testing.T) {
}
emv.Update(63.74, 62.63, 32178836)
emv.Update(64.51, 63.85, 36461672)
assert.InDelta(t, 1.8, emv.Values.Cache.Last(), Delta)
assert.InDelta(t, 1.8, emv.Values.rawValues.Last(), Delta)
emv.Update(64.57, 63.81, 51372680)
emv.Update(64.31, 62.62, 42476356)
emv.Update(63.43, 62.73, 29504176)

View File

@ -14,9 +14,9 @@ const MaxNumOfSMATruncateSize = 100
type SMA struct {
types.SeriesBase
types.IntervalWindow
Values types.Float64Slice
Cache *types.Queue
EndTime time.Time
Values types.Float64Slice
rawValues *types.Queue
EndTime time.Time
UpdateCallbacks []func(value float64)
}
@ -43,40 +43,38 @@ func (inc *SMA) Length() int {
var _ types.SeriesExtend = &SMA{}
func (inc *SMA) Update(value float64) {
if inc.Cache == nil {
inc.Cache = types.NewQueue(inc.Window)
if inc.rawValues == nil {
inc.rawValues = types.NewQueue(inc.Window)
inc.SeriesBase.Series = inc
}
inc.Cache.Update(value)
if inc.Cache.Length() < inc.Window {
inc.rawValues.Update(value)
if inc.rawValues.Length() < inc.Window {
return
}
inc.Values.Push(types.Mean(inc.Cache))
if inc.Values.Length() > MaxNumOfSMA {
inc.Values = inc.Values[MaxNumOfSMATruncateSize-1:]
}
inc.Values.Push(types.Mean(inc.rawValues))
}
func (inc *SMA) PushK(k types.KLine) {
inc.Update(k.Close.Float64())
inc.EndTime = k.EndTime.Time()
}
func (inc *SMA) CalculateAndUpdate(kLines []types.KLine) {
var index = len(kLines) - 1
var kline = kLines[index]
if inc.EndTime != zeroTime && kline.EndTime.Before(inc.EndTime) {
return
}
func (inc *SMA) CalculateAndUpdate(allKLines []types.KLine) {
var last = allKLines[len(allKLines)-1]
if inc.rawValues == nil {
for _, k := range allKLines {
if inc.EndTime != zeroTime && k.EndTime.Before(inc.EndTime) {
continue
}
if inc.Cache == nil {
for _, k := range kLines {
inc.PushK(k)
inc.EndTime = k.EndTime.Time()
inc.EmitUpdate(inc.Values.Last())
}
} else {
inc.PushK(kline)
inc.EndTime = kline.EndTime.Time()
inc.PushK(last)
inc.EmitUpdate(inc.Values.Last())
}
}