Moving Average Contrarian Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo

//@version=5
indicator("Moving Average Contrarian Indicator", overlay=false)

length = input(40, "Moving Average Length")
src = close

// Calculate moving average
ma = ta.sma(src, length)

// Calculate distance from price to moving average
distance = src - ma

// Calculate normalized MACI
distance_min = ta.lowest(distance, length)
distance_max = ta.highest(distance, length)
maci = ((distance - distance_min) / (distance_max - distance_min)) * 100

// Determine barcolor and background color conditions
maci_sma = ta.sma(maci, length)
barC = maci > maci_sma and maci > 30 ? color.lime : maci < maci_sma and maci < 70 ? color.fuchsia : color.yellow
backC = maci > maci_sma and maci > 30 ? color.new(color.lime, 80) : maci < maci_sma and maci < 70 ? color.new(color.fuchsia, 80) : color.new(color.yellow, 80)

// Color
barcolor(barC)
bgcolor(backC, transp=70)

// Plotting
plot(maci, title="MACI", color=barC, style=plot.style_histogram, linewidth=4)
plot(maci_sma, title='MACI SMA', color=color.maroon, linewidth=2)

// Overbought and oversold levels
hline(70, "Overbought", color=color.fuchsia)
hline(30, "Oversold", color=color.lime)