MA Correlation Coefficient
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © nonamealgo

//@version=5
indicator(title = 'MA Correlation Coefficient', shorttitle = 'MA Correlation', overlay = false)
import PineCoders/VisibleChart/4

// Inputs //
src = input(defval = close, title = 'Source')
corr_len = input.int(14, title = 'Correlation Window', minval = 1)
modeSwitch = input.string(defval = 'SMA', title = 'Average Type', options = ['SMA','EMA','HMA','VWMA'])

ma1_len = input.int(7, title = 'MA1', minval = 1, group = 'Lookback')
ma2_len = input.int(14, title = 'MA2', minval = 1, group = 'Lookback')
ma3_len = input.int(30, title = 'MA3', minval = 1, group = 'Lookback')
ma4_len = input.int(91, title = 'MA4', minval = 1, group = 'Lookback')

grad_bottom_color = input.color(defval = color.rgb(5, 48, 97), title = 'Bottom Color', group = 'Gradient ')
grad_centre_color = input.color(defval = color.rgb(247, 247, 247), title = 'Centre Color', group = 'Gradient ')
grad_top_color = input.color(defval = color.rgb(103, 0, 31), title = 'Top Color', group = 'Gradient ')

// Functions //
// Switch
Mode(modeSwitch, src, len) => modeSwitch == 'SMA' ?
 ta.sma(source = src, length = len) : modeSwitch == 'EMA' ?
  ta.ema(source = src, length = len) : modeSwitch == 'VWMA' ?
   ta.vwma(source = src, length = len) : modeSwitch == 'HMA' ? ta.hma(source = src, length = len) : na
// Color picker
ColorPicker(src, bColor, cColor, tColor) => color.from_gradient(value = src, bottom_value = src <= 0 ? -1 : 0, top_value = src <= 0 ? 0 : 1, bottom_color = src <= 0 ? bColor : cColor, top_color = src <= 0 ? cColor : tColor)

// Moving Averages //
ma1 = Mode(modeSwitch, src, ma1_len)
ma2 = Mode(modeSwitch, src, ma2_len)
ma3 = Mode(modeSwitch, src, ma3_len)
ma4 = Mode(modeSwitch, src, ma4_len)

// Calculate Correlation Coefficients //
cma1 = ta.correlation(source1 = src, source2 = ma1, length = corr_len)
cma2 = ta.correlation(source1 = src, source2 = ma2, length = corr_len)
cma3 = ta.correlation(source1 = src, source2 = ma3, length = corr_len)
cma4 = ta.correlation(source1 = src, source2 = ma4, length = corr_len)

// Correlation Colors //
color1 = ColorPicker(cma1, grad_bottom_color, grad_centre_color, grad_top_color)
color2 = ColorPicker(cma2, grad_bottom_color, grad_centre_color, grad_top_color)
color3 = ColorPicker(cma3, grad_bottom_color, grad_centre_color, grad_top_color)
color4 = ColorPicker(cma4, grad_bottom_color, grad_centre_color, grad_top_color)

// Plot Columns //
plot(series = 4, style = plot.style_area, color = color4, title = 'MA4 Correlation')
plot(series = 3, style = plot.style_area, color = color3, title = 'MA3 Correlation')
plot(series = 2, style = plot.style_area, color = color2, title = 'MA2 Correlation')
plot(series = 1, style = plot.style_area, color = color1, title = 'MA1 Correlation')