Volatility-Based Mean Reversion Bands
// 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("Volatility-Based Mean Reversion Bands", overlay=true)

// Calculation Inputs
length = input.int(20, "Lookback Period", minval=1)
multiplier = input.float(2.5, "Multiplier", minval=0.1, maxval=10.0)

// Calculate Average True Range (ATR)
atr = ta.atr(length)

// Calculate Mean Reversion Bands
mean = ta.sma(close, length)
upperBand = mean + (atr * multiplier)
lowerBand = mean - (atr * multiplier)

// RSI Inputs
useRSI = input.bool(true, "Use RSI as Confluence")
rsiLength = input.int(20, "RSI Length", minval=1)

// Calculate RSI
rsi = useRSI ? ta.rsi(close, rsiLength) : na

// Confluence Conditions
confluenceRSI = useRSI ? (rsi > 70 or rsi < 30) : false
confluenceCondition = confluenceRSI

// Plotting
plot(mean, color=color.blue, linewidth=2, title="Mean")
plot(upperBand, color=color.lime, linewidth=2, title="Upper Band")
plot(lowerBand, color=color.fuchsia, linewidth=2, title="Lower Band")

// Bar Color
barC = close > upperBand ? color.lime : close < lowerBand ? color.fuchsia : na
barcolor(barC)

// Background Color
bgColor = barC == color.lime ? color.new(color.lime, 80) : barC == color.fuchsia ? color.new(color.fuchsia, 80) : na
bgcolor(bgColor)

// Entry Arrows
plotshape(close > upperBand and confluenceCondition, title="Short Entry", location=location.abovebar, color=color.fuchsia, style=shape.triangleup, size=size.small)
plotshape(close < lowerBand and confluenceCondition, title="Long Entry", location=location.belowbar, color=color.lime, style=shape.triangledown, size=size.small)

// Alert Conditions
alertcondition(close > upperBand and confluenceCondition, title="Short Entry", message="Short Entry Signal")
alertcondition(close < lowerBand and confluenceCondition, title="Long Entry", message="Long Entry Signal")