Adaptive Mean Reversion 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("Adaptive Mean Reversion Indicator", overlay=false)

// Market Regime Detection
volatilityThreshold = input.float(5.0, "Volatility Threshold")
isTrending = ta.atr(14) > volatilityThreshold

// Parameter Optimization
lookbackPeriod = isTrending ? input.int(40, "Lookback Period (Trending)") : input.int(20, "Lookback Period (Ranging)")
thresholdLevel = isTrending ? input.float(2.0, "Threshold Level (Trending)") : input.float(1.5, "Threshold Level (Ranging)")

// Calculate Mean Reversion
mean = ta.sma(close, lookbackPeriod)
deviation = ta.stdev(close, lookbackPeriod)
upperBand = mean + (deviation * thresholdLevel)
lowerBand = mean - (deviation * thresholdLevel)

// Real-Time Parameter Adjustment
adaptiveMean = isTrending ? mean : ta.sma(close, 3)
adaptiveUpperBand = isTrending ? upperBand : mean + (deviation * thresholdLevel * 0.75)
adaptiveLowerBand = isTrending ? lowerBand : mean - (deviation * thresholdLevel * 0.75)

// Plotting
plot(adaptiveMean, color=color.aqua, linewidth=2, title="Adaptive Mean")
plot(adaptiveUpperBand, color=color.lime, linewidth=2, title="Adaptive Upper Band")
plot(adaptiveLowerBand, color=color.fuchsia, linewidth=2, title="Adaptive Lower Band")

// Signal Generation
isAboveUpperBand = close > adaptiveUpperBand
isBelowLowerBand = close < adaptiveLowerBand
signal = isAboveUpperBand ? -1 : isBelowLowerBand ? 1 : 0

// RSI Calculation
rsiLength = input.int(14, "RSI Length")
rsi = ta.rsi(close, rsiLength)

// Confluence Condition
confluenceCondition = rsi > 70 or rsi < 30

// Background Color
bgcolor(signal == -1 and confluenceCondition ? color.new(color.lime, 80) : signal == 1 and confluenceCondition ? color.new(color.fuchsia, 80) : na)

// Bar Color
barcolor(signal == -1 and confluenceCondition ? color.lime : signal == 1 and confluenceCondition ? color.fuchsia : na)

// Alert Conditions
alertcondition(signal == 1 and confluenceCondition, title="Long Entry", message="Long Entry Signal")
alertcondition(signal == -1 and confluenceCondition, title="Short Entry", message="Short Entry Signal")
