From 432f9df1376561021c821bb24f35439782d1c33b Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 15 Sep 2022 11:49:19 +0800 Subject: [PATCH] indicator: refactor pivot function to floats --- pkg/datatype/floats/pivot.go | 34 ++++++++++++++++++++++++++++++++++ pkg/indicator/pivotlow.go | 33 ++------------------------------- 2 files changed, 36 insertions(+), 31 deletions(-) create mode 100644 pkg/datatype/floats/pivot.go diff --git a/pkg/datatype/floats/pivot.go b/pkg/datatype/floats/pivot.go new file mode 100644 index 000000000..f79403047 --- /dev/null +++ b/pkg/datatype/floats/pivot.go @@ -0,0 +1,34 @@ +package floats + +func (s Slice) Pivot(left, right int, f func(a, pivot float64) bool) (float64, bool) { + return CalculatePivot(s, left, right, f) +} + +func CalculatePivot(values Slice, left, right int, f func(a, pivot float64) bool) (float64, bool) { + length := len(values) + + if right == 0 { + right = left + } + + if length == 0 || length < left+right+1 { + return 0.0, false + } + + end := length - 1 + index := end - right + val := values[index] + + for i := index - left; i <= index+right; i++ { + if i == index { + continue + } + + // return if we found lower value + if !f(values[i], val) { + return 0.0, false + } + } + + return val, true +} diff --git a/pkg/indicator/pivotlow.go b/pkg/indicator/pivotlow.go index 526b27adf..135b61868 100644 --- a/pkg/indicator/pivotlow.go +++ b/pkg/indicator/pivotlow.go @@ -63,43 +63,14 @@ func (inc *PivotLow) PushK(k types.KLine) { inc.EmitUpdate(inc.Last()) } -func calculatePivotF(values floats.Slice, left, right int, f func(a, pivot float64) bool) (float64, bool) { - length := len(values) - - if right == 0 { - right = left - } - - if length == 0 || length < left+right+1 { - return 0.0, false - } - - end := length - 1 - index := end - right - val := values[index] - - for i := index - left; i <= index+right; i++ { - if i == index { - continue - } - - // return if we found lower value - if !f(values[i], val) { - return 0.0, false - } - } - - return val, true -} - func calculatePivotHigh(highs floats.Slice, left, right int) (float64, bool) { - return calculatePivotF(highs, left, right, func(a, pivot float64) bool { + return floats.CalculatePivot(highs, left, right, func(a, pivot float64) bool { return a < pivot }) } func calculatePivotLow(lows floats.Slice, left, right int) (float64, bool) { - return calculatePivotF(lows, left, right, func(a, pivot float64) bool { + return floats.CalculatePivot(lows, left, right, func(a, pivot float64) bool { return a > pivot }) }