Skip to content

Commit

Permalink
fix: simplify stoch indicator using float64slice. add ToReverseArray
Browse files Browse the repository at this point in the history
  • Loading branch information
zenixls2 committed Apr 11, 2022
1 parent 339d36d commit be0755d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 48 deletions.
52 changes: 4 additions & 48 deletions pkg/indicator/stoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
20 changes: 20 additions & 0 deletions pkg/types/indicator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit be0755d

Please sign in to comment.