|
| 1 | +package techan |
| 2 | + |
| 3 | +import ( |
| 4 | + "math" |
| 5 | + |
| 6 | + "github.com/sdcoffey/big" |
| 7 | +) |
| 8 | + |
| 9 | +type stochasticRSIIndicator struct { |
| 10 | + curRSI Indicator |
| 11 | + minRSI Indicator |
| 12 | + maxRSI Indicator |
| 13 | +} |
| 14 | + |
| 15 | +// NewStochasticRSIIndicator returns a derivative Indicator which returns the stochastic RSI indicator for the given |
| 16 | +// RSI window. |
| 17 | +// https://www.investopedia.com/terms/s/stochrsi.asp |
| 18 | +func NewStochasticRSIIndicator(indicator Indicator, timeframe int) Indicator { |
| 19 | + rsiIndicator := NewRelativeStrengthIndexIndicator(indicator, timeframe) |
| 20 | + return stochasticRSIIndicator{ |
| 21 | + curRSI: rsiIndicator, |
| 22 | + minRSI: NewMinimumValueIndicator(rsiIndicator, timeframe), |
| 23 | + maxRSI: NewMaximumValueIndicator(rsiIndicator, timeframe), |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func (sri stochasticRSIIndicator) Calculate(index int) big.Decimal { |
| 28 | + curRSI := sri.curRSI.Calculate(index) |
| 29 | + minRSI := sri.minRSI.Calculate(index) |
| 30 | + maxRSI := sri.maxRSI.Calculate(index) |
| 31 | + |
| 32 | + if minRSI.EQ(maxRSI) { |
| 33 | + return big.NewDecimal(math.Inf(1)) |
| 34 | + } |
| 35 | + |
| 36 | + return curRSI.Sub(minRSI).Div(maxRSI.Sub(minRSI)).Mul(big.NewDecimal(100)) |
| 37 | +} |
| 38 | + |
| 39 | +type rsiKIndicator struct { |
| 40 | + stochasticRSI Indicator |
| 41 | + window int |
| 42 | +} |
| 43 | + |
| 44 | +// NewFastStochasticRSIIndicator returns a derivative Indicator which returns the fast stochastic RSI indicator (%K) |
| 45 | +// for the given stochastic window. |
| 46 | +func NewFastStochasticRSIIndicator(stochasticRSI Indicator, timeframe int) Indicator { |
| 47 | + return rsiKIndicator{stochasticRSI, timeframe} |
| 48 | +} |
| 49 | + |
| 50 | +func (k rsiKIndicator) Calculate(index int) big.Decimal { |
| 51 | + return NewSimpleMovingAverage(k.stochasticRSI, k.window).Calculate(index) |
| 52 | +} |
| 53 | + |
| 54 | +type rsiDIndicator struct { |
| 55 | + k Indicator |
| 56 | + window int |
| 57 | +} |
| 58 | + |
| 59 | +// NewSlowStochasticRSIIndicator returns a derivative Indicator which returns the slow stochastic RSI indicator (%D) |
| 60 | +// for the given stochastic window. |
| 61 | +func NewSlowStochasticRSIIndicator(k Indicator, timeframe int) Indicator { |
| 62 | + return rsiDIndicator{k, timeframe} |
| 63 | +} |
| 64 | + |
| 65 | +func (d rsiDIndicator) Calculate(index int) big.Decimal { |
| 66 | + return NewSimpleMovingAverage(d.k, d.window).Calculate(index) |
| 67 | +} |
0 commit comments