Moving Average Reversals [QuantVue]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlgoBuddy

//@version=5
indicator("Moving Average Reversals", shorttitle = 'Moving Average Reversals', precision = 2)

//inputs
var g1 = 'Moving Average'
imatype =       input.string(defval = 'EMA', title = 'MA Type', options = ['EMA', 'SMA', 'HMA', 'WMA', 'VWMA'], inline = '1', group = g1)
imalength =     input.int(21, 'MA Length', minval = 1, maxval = 300, step = 1, inline = '1', group = g1)
isrc =          input.source(defval = close, title ='Source To Meassure Distance From ', inline = '2', group = g1, tooltip = 'Select the source to calculate it\'s distance from the moving average')
extColor =      input.color(color.rgb(255,0,0), 'Extended Color', inline = '3', group = g1)
inColor =       input.color(color.rgb(0,255,0), 'In Range Color', inline = '3', group = g1)

var g2 = 'Extensions'
showExt =       input.bool(true, 'Highlight Highest Extensions Up and Down', group = g2)
extDown =       input.color(color.new(color.aqua,70), 'Highest Extension Down', group = g2)
extUp =         input.color(color.new(color.maroon,70), 'Highest Extension Up', group = g2)

var g3 = 'Moving Average of Extensions'
showMa2 =       input.bool(true, 'Show Moving Average of Extensions', inline = '1', group = g3)
ma2Len =        input.int(10, 'Length', inline = '2', group = g3)
ma2Color =      input.color(color.orange, 'Color', inline = '2', group = g3)

// get the ma
ma = switch imatype
    'EMA' => ta.ema(close, imalength)  
    'SMA' => ta.sma(close, imalength)
    'HMA' => ta.hma(close, imalength) 
    'WMA' => ta.wma(close, imalength)
    'VWMA' => ta.vwma(close, imalength)

// calculate the distance from the source to the moving average 
distance =      ((isrc / ma) - 1) * 100
extensionMa =    ta.sma(distance, ma2Len)

//find the highest and lowest extensions from the selected MA over the past year
lowest =        ta.lowest(distance,252)
highest =       ta.highest(distance,252)

//create the gradient color
gradient =      distance > 0 ? color.from_gradient(distance, 0, highest, inColor, extColor) : color.from_gradient(distance, lowest, 0, extColor, inColor)

//plots
plot(distance, "Distance From Ma", style= plot.style_columns, linewidth = 4, color = gradient)
plot(showMa2 ? extensionMa : na, 'Extension MA', color = ma2Color)
bgcolor(showExt and distance == highest ? extUp : showExt and distance == lowest ? extDown : na)