From be0755d755ba99e9c664d2df5e0496a8f5d01396 Mon Sep 17 00:00:00 2001 From: zenix Date: Thu, 7 Apr 2022 12:29:15 +0900 Subject: [PATCH] fix: simplify stoch indicator using float64slice. add ToReverseArray --- pkg/indicator/stoch.go | 52 ++++-------------------------------------- pkg/types/indicator.go | 20 ++++++++++++++++ 2 files changed, 24 insertions(+), 48 deletions(-) diff --git a/pkg/indicator/stoch.go b/pkg/indicator/stoch.go index 6df468156..0a909f977 100644 --- a/pkg/indicator/stoch.go +++ b/pkg/indicator/stoch.go @@ -83,54 +83,10 @@ func (inc *STOCH) Bind(updater KLineWindowUpdater) { updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate) } -func (inc *STOCH) GetD() *DSeries { - return &DSeries{inc} +func (inc *STOCH) GetD() types.Series { + return inc.D } -func (inc *STOCH) GetK() *KSeries { - return &KSeries{inc} +func (inc *STOCH) GetK() types.Series { + return inc.K } - -type DSeries struct { - *STOCH -} - -func (inc *DSeries) Last() float64 { - return inc.LastD() -} - -func (inc *DSeries) Length() int { - return len(inc.D) -} - -func (inc *DSeries) Index(i int) float64 { - length := len(inc.D) - if length == 0 || length-i-1 < 0 { - return 0 - } - return inc.D[length-i-1] -} - -var _ types.Series = &DSeries{} - -type KSeries struct { - *STOCH -} - -func (inc *KSeries) Last() float64 { - return inc.LastK() -} - -func (inc *KSeries) Index(i int) float64 { - length := len(inc.K) - if length == 0 || length-i-1 < 0 { - return 0 - } - return inc.K[length-i-1] -} - -func (inc *KSeries) Length() int { - return len(inc.K) -} - -var _ types.Series = &KSeries{} diff --git a/pkg/types/indicator.go b/pkg/types/indicator.go index c59294d3a..e25a02fc5 100644 --- a/pkg/types/indicator.go +++ b/pkg/types/indicator.go @@ -423,3 +423,23 @@ func ToArray(a Series, limit ...int) (result []float64) { } return } + +// Similar to ToArray but in reverse order. +// Useful when you want to cache series' calculated result as float64 array +// the then reuse the result in multiple places (so that no recalculation will be triggered) +// +// notice that the return type is a Float64Slice, which implements the Series interface +func ToReverseArray(a Series, limit ...int) (result Float64Slice) { + l := -1 + if len(limit) > 0 { + l = limit[0] + } + if l < a.Length() { + l = a.Length() + } + result = make([]float64, l, l) + for i := 0; i < l; i++ { + result[l-i-1] = a.Index(i) + } + return +}