Percentile Rank of Moving Average Convergence Divergence
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheSaltyAustin

//@version=5
indicator(title="Ranked Moving Average Convergence Divergence", shorttitle="MACD ranked", timeframe="", timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])

lookback = input.int(750, title='MACD Lookback', group='Ranking')

// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

var macdArray = array.new_float(lookback,0.0)
var signalArray = array.new_float(lookback,0.0)
var histArray = array.new_float(lookback,0.0)

array.push(macdArray, math.abs(macd) )
array.push(signalArray, math.abs(signal) )
array.push(histArray, math.abs(hist) )

array.remove(macdArray, 0)
array.remove(signalArray, 0)
array.remove(histArray, 0)

macdRank   = array.percentrank(macdArray  , lookback-1)
signalRank = array.percentrank(signalArray, lookback-1)
histRank   = array.percentrank(histArray  , lookback-1)

plot(histRank, color=color.new(color.olive,50), linewidth=2, title='Histogram Rank', style=plot.style_columns)
plot(macdRank, color=#4dd0e1, linewidth=2, title='MACD (fast) Rank')
plot(signalRank, color=#056656, linewidth=2, title='Signal (slow) Rank')
hline(75, title='3rd Quartile', color=color.new(color.white,50), linestyle=hline.style_dashed )
hline(50, title='Median' , color=color.new(color.white,50), linestyle=hline.style_dashed )
hline(25, title='1st Quartile' , color=color.new(color.white,50), linestyle=hline.style_dashed )

