Skip to content

Commit

Permalink
indicator/sma: clean CalculateAndUpdate and make cache field private
Browse files Browse the repository at this point in the history
  • Loading branch information
c9s committed Jul 14, 2022
1 parent 7696c9f commit bbf0127
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 23 deletions.
2 changes: 1 addition & 1 deletion pkg/indicator/emv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
42 changes: 20 additions & 22 deletions pkg/indicator/sma.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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())
}
}
Expand Down

0 comments on commit bbf0127

Please sign in to comment.