update this code to high version : //@version=5
strategy("Combined Indicator, Quantum Cloud & Multi RSI Divergence Quantum AI", overlay=true, max_lines_count=500, 
     initial_capital=10000, currency=currency.USD, 
     default_qty_type=strategy.percent_of_equity, default_qty_value=10, 
     calc_on_order_fills=true, calc_on_every_tick=false)

//─────────────────────────────
// INPUT PARAMETERS - PART 1 (Classic/Quantum Cloud)
//─────────────────────────────
rsiLength    = input(14, "RSI Length")
macdFast     = input(12, "Classic MACD Fast Length")
macdSlow     = input(26, "Classic MACD Slow Length")
macdSignal   = input(9,  "Classic MACD Signal Length")
stochLength  = input(14, "Stochastic Length")
momLength    = input(10, "Momentum Length")

adxLength    = input(14, "ADX Length")
adxThreshold = input.float(25.0, "ADX Threshold", step=0.1)

atrPeriod    = input(14, "ATR Length (Quantum Cloud)")
factor       = input.float(2.0, "Supertrend Factor", step=0.01)
x1           = input(14, "Trend Pressure Period")
alpha        = input.float(0.5, "Alpha", step=0.1)
bpt          = input.float(0.6, "Buy Pressure Threshold %", step=0.1)
spt          = input.float(0.6, "Sell Pressure Threshold %", step=0.1)
fastLength   = input(8,  "Quantum MACD Fast Length")
slowLength   = input(17, "Quantum MACD Slow Length")
signalLength = input(9,  "Quantum MACD Signal Length")
ema200       = input(true, "Show EMA 200")
ema50        = input(true, "Show EMA 50")
ema20        = input(true, "Show EMA 20")

//─────────────────────────────
// INPUT PARAMETERS - PART 2 (RSI Divergence & Risk/Trend)
//─────────────────────────────
src          = input(close, title="RSI Source")
rsiPeriod1   = input.int(14, title="RSI Period 1")
rsiPeriod2   = input.int(21, title="RSI Period 2")
rsiPeriod3   = input.int(28, title="RSI Period 3")
// Renamed these inputs for clarity – adjust if needed:
rsiPeriod4   = input.int(35, title="RSI Period 4")
rsiPeriod5   = input.int(42, title="RSI Period 5")
lbR          = input.int(5, title="Pivot Lookback Right")
lbL          = input.int(5, title="Pivot Lookback Left")
rangeUpper   = input.int(60, title="Max Lookback Range")
rangeLower   = input.int(5, title="Min Lookback Range")

// Divergence Plot Options
plotBull         = input.bool(true, title="Plot Regular Bullish")
plotHiddenBull   = input.bool(false, title="Plot Hidden Bullish")
plotBear         = input.bool(true, title="Plot Regular Bearish")
plotHiddenBear   = input.bool(false, title="Plot Hidden Bearish")
plotStrongBull        = input.bool(true, title="Plot Strong Bullish")
plotStrongHiddenBull  = input.bool(false, title="Plot Strong Hidden Bullish")
plotStrongBear        = input.bool(true, title="Plot Strong Bearish")
plotStrongHiddenBear  = input.bool(false, title="Plot Strong Hidden Bearish")

// EMA & MACD Settings for Divergence (renamed to avoid conflicts)
emaPeriod1_div   = input.int(20, title="EMA Period 1 (Divergence)")
emaPeriod2_div   = input.int(50, title="EMA Period 2 (Divergence)")
macdFast2   = input.int(12, title="MACD Fast Length (Divergence)")
macdSlow2   = input.int(26, title="MACD Slow Length (Divergence)")
macdSignal2 = input.int(9, title="MACD Signal Smoothing (Divergence)")

// Risk Management Inputs
useATRStop      = input.bool(false, title="Use ATR-based Stop Loss/TP")
atrPeriod2      = input.int(14, title="ATR Period for SL/TP")
atrMultiplierSL = input.float(1.5, title="ATR Multiplier for Stop Loss", step=0.1)
atrMultiplierTP = input.float(3.0, title="ATR Multiplier for Take Profit", step=0.1)
stopLossPerc    = input.float(2.0, title="Stop Loss % (if not using ATR)", step=0.1)
takeProfitPerc  = input.float(4.0, title="Take Profit % (if not using ATR)", step=0.1)
enableTrailing  = input.bool(true, title="Enable Trailing Stop")
trailPerc       = input.float(1.0, title="Trailing Stop %", step=0.1)

// Higher Timeframe Trend Filter
htfTF       = input.timeframe("D", title="Higher Timeframe for Trend Filter")
useHTFTrend = input.bool(true, title="Use Higher Timeframe Trend Filter")
htfEMA      = request.security(syminfo.tickerid, htfTF, ta.ema(src, emaPeriod2_div))

// Volume Confirmation Filter
volFilterEnabled = input.bool(false, title="Enable Volume Confirmation")
volMultiplier    = input.float(1.0, title="Volume Multiplier (Volume > SMA(Volume,20)*Multiplier)", step=0.1)
volSMA           = ta.sma(volume, 20)
volCondition     = volume > (volSMA * volMultiplier)

// Backtest Date Filter
startYear    = input.int(2020, "Backtest Start Year", minval=2000)
startMonth   = input.int(1, "Backtest Start Month", minval=1, maxval=12)
startDay     = input.int(1, "Backtest Start Day", minval=1, maxval=31)
backtestStart = timestamp(startYear, startMonth, startDay, 00, 00)
allowTrade    = (time >= backtestStart)

//─────────────────────────────
// ATR LINE STRATEGY INPUTS
//─────────────────────────────
atrLineStrategyEnabled    = input.bool(true, "Enable ATR Line Strategy")
atrLineStrategyLength     = input.int(14, "ATR Line Strategy Length", minval=1)
atrLineStrategyMultiplier = input.float(1.0, "ATR Line Strategy Multiplier", step=0.1)

//─────────────────────────────
// CALCULATIONS - PART 1 (Classic & Quantum Cloud)
//─────────────────────────────
// Classic Indicators
rsiValue    = ta.rsi(close, rsiLength)
rsiBullish  = rsiValue > 50
rsiBearish  = rsiValue < 50

[classicMacdLine, classicSignalLine, _] = ta.macd(close, macdFast, macdSlow, macdSignal)
macdBullish = classicMacdLine > classicSignalLine
macdBearish = classicMacdLine < classicSignalLine

k           = ta.sma(ta.stoch(close, high, low, stochLength), 3)
d           = ta.sma(k, 3)
stochBullish= k > d
stochBearish= k < d

momentumValue = ta.mom(close, momLength)
momBullish    = momentumValue > 0
momBearish    = momentumValue < 0

// ADX Calculations (custom)
up        = high - high[1]
down      = low[1] - low
plusDM    = (up > down and up > 0) ? up : 0.0
minusDM   = (down > up and down > 0) ? down : 0.0
tr        = ta.tr(true)
atrVal    = ta.rma(tr, adxLength)
plusDI    = 100 * ta.rma(plusDM, adxLength) / atrVal
minusDI   = 100 * ta.rma(minusDM, adxLength) / atrVal
dx        = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
adxValue  = ta.rma(dx, adxLength)

adxNeutral   = adxValue < adxThreshold
adxBullish   = plusDI > minusDI and not adxNeutral
adxBearish   = minusDI > plusDI and not adxNeutral
adxSignalText = adxNeutral ? "Neutral ➤" : adxBullish ? "Bullish" : "Bearish"
adxColor      = adxNeutral ? color.new(#FFC107, 70) : adxBullish ? color.new(#4CAF50, 70) : color.new(#F44336, 70)

// Quantum Cloud Components
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
x2 = ta.atr(x1) * alpha
xl = close - x2
xh = close + x2

// Volume-weighted calculations
vwmaPeriod1 = math.ceil(x1 / 4)
vwmaPeriod2 = math.ceil(x1 / 2)
a1 = ta.vwma(hl2 * volume, vwmaPeriod1) / ta.vwma(volume, vwmaPeriod1)
a2 = ta.vwma(hl2 * volume, vwmaPeriod2) / ta.vwma(volume, vwmaPeriod2)
a3 = 2 * a1 - a2
a4 = ta.vwma(a3, x1)

// Adaptive Price Filter
b1 = ta.sma(close, x1)
a5 = 2 * a4 * b1 / (a4 + b1)

// Trading Signals (Quantum Cloud)
buy  = a5 <= xl and close > b1 * (1 + bpt * 0.01)
sell = a5 >= xh and close < b1 * (1 - spt * 0.01)
var int xs = 0
xs := buy ? 1 : sell ? -1 : xs

// Quantum MACD
qMacdLine    = ta.ema(close, fastLength) - ta.ema(close, slowLength)
qSignalLine  = ta.ema(qMacdLine, signalLength)
qMacdBullish = ta.crossover(qMacdLine, qSignalLine) and qMacdLine > 0
qMacdBearish = ta.crossunder(qMacdLine, qSignalLine) and qMacdLine < 0

//─────────────────────────────
// VISUALS & TABLES - PART 1
//─────────────────────────────
// Create an indicator table
var table indicatorTable = table.new(position.top_right, 6, 6, frame_width=2, frame_color=color.gray)
if barstate.isfirst
    table.cell(indicatorTable, 0, 0, "Indicator", bgcolor=color.new(#2A2A2A, 0), text_color=color.white)
    table.cell(indicatorTable, 1, 0, "RSI",       bgcolor=color.new(#2A2A2A, 0), text_color=color.white)
    table.cell(indicatorTable, 2, 0, "MACD",      bgcolor=color.new(#2A2A2A, 0), text_color=color.white)
    table.cell(indicatorTable, 3, 0, "Stoch",     bgcolor=color.new(#2A2A2A, 0), text_color=color.white)
    table.cell(indicatorTable, 4, 0, "Momentum",  bgcolor=color.new(#2A2A2A, 0), text_color=color.white)
    table.cell(indicatorTable, 5, 0, "ADX",       bgcolor=color.new(#2A2A2A, 0), text_color=color.white)

table.cell(indicatorTable, 0, 1, "Status", bgcolor=color.new(#404040, 0), text_color=color.white)
table.cell(indicatorTable, 1, 1, rsiBullish  ? "Bullish" : "Bearish", bgcolor=rsiBullish  ? color.new(color.green, 70) : color.new(color.red, 70))
table.cell(indicatorTable, 2, 1, macdBullish ? "Bullish" : "Bearish", bgcolor=macdBullish ? color.new(color.green, 70) : color.new(color.red, 70))
table.cell(indicatorTable, 3, 1, stochBullish? "Bullish" : "Bearish", bgcolor=stochBullish? color.new(color.green, 70) : color.new(color.red, 70))
table.cell(indicatorTable, 4, 1, momBullish  ? "Bullish" : "Bearish", bgcolor=momBullish  ? color.new(color.green, 70) : color.new(color.red, 70))
table.cell(indicatorTable, 5, 1, adxSignalText,                      bgcolor=adxColor, text_color=color.white)

bullishCount  = (rsiBullish ? 1 : 0) + (macdBullish ? 1 : 0) + (stochBullish ? 1 : 0) + (momBullish ? 1 : 0)
bearishCount  = (rsiBearish ? 1 : 0) + (macdBearish ? 1 : 0) + (stochBearish ? 1 : 0) + (momBearish ? 1 : 0)
strongBullish = bullishCount >= 3
strongBearish = bearishCount >= 3

table.cell(indicatorTable, 0, 2, "Strength", bgcolor=color.new(#404040, 0), text_color=color.white)
strengthText  = strongBullish ? "Strong Bull ▲" : strongBearish ? "Strong Bear ▼" : "Neutral ➤"
strengthColor = strongBullish ? color.new(#4CAF50, 70) : strongBearish ? color.new(#F44336, 70) : color.new(#FFC107, 70)
table.cell(indicatorTable, 1, 2, strengthText,  bgcolor=strengthColor, text_color=color.white)
table.cell(indicatorTable, 2, 2, strengthText,  bgcolor=strengthColor, text_color=color.white)
table.cell(indicatorTable, 3, 2, strengthText,  bgcolor=strengthColor, text_color=color.white)
table.cell(indicatorTable, 4, 2, strengthText,  bgcolor=strengthColor, text_color=color.white)
table.cell(indicatorTable, 5, 2, adxSignalText, bgcolor=adxColor, text_color=color.white)

// Signal markers and EMA plots
plotshape(qMacdBullish, title="MACD Bullish", text="↑MACD", style=shape.triangleup, location=location.belowbar, 
     color=color.new(#00FF00, 0), textcolor=color.white, size=size.small)
plotshape(qMacdBearish, title="MACD Bearish", text="↓MACD", style=shape.triangledown, location=location.abovebar, 
     color=color.new(#FF0000, 0), textcolor=color.white, size=size.small)
barcolor(color = xs == 1 ? color.new(#00FF00, 70) : xs == -1 ? color.new(#FF0000, 70) : na)
plotshape(buy and xs != xs[1], title="BUY", text='B', style=shape.labelup, location=location.belowbar, 
     color=color.green, textcolor=color.white, size=size.small)
plotshape(sell and xs != xs[1], title="SELL", text='S', style=shape.labeldown, location=location.abovebar, 
     color=color.red, textcolor=color.white, size=size.small)
plotshape(buy and xs != xs[1] and direction > 0 and qMacdBullish, title="Quantum BUY", text='🚀', 
     style=shape.labelup, location=location.belowbar, color=color.new(#00FF00, 50), textcolor=color.white, size=size.normal)
plotshape(sell and xs != xs[1] and direction < 0 and qMacdBearish, title="Quantum SELL", text='☄️', 
     style=shape.labeldown, location=location.abovebar, color=color.new(#FF0000, 50), textcolor=color.white, size=size.normal)
plot(ta.ema(close, 200), color=ema200 ? color.new(#000000, 0) : na, title="EMA 200", linewidth=3)
plot(ta.ema(close, 50),  color=ema50  ? color.new(#2196F3, 0) : na, title="EMA 50", linewidth=2)
plot(ta.ema(close, 20),  color=ema20  ? color.new(#FF9800, 0) : na, title="EMA 20", linewidth=2)

//─────────────────────────────
// ATR LINE STRATEGY CALCULATIONS & PLOTTING
//─────────────────────────────
atrValueLine = ta.atr(atrLineStrategyLength)
smaATR       = ta.sma(close, atrLineStrategyLength)
upperATRLine = smaATR + atrValueLine * atrLineStrategyMultiplier
lowerATRLine = smaATR - atrValueLine * atrLineStrategyMultiplier

plot(upperATRLine, title="Upper ATR Line Strategy", color=atrLineStrategyEnabled ? color.red : na, linewidth=1)
plot(lowerATRLine, title="Lower ATR Line Strategy", color=atrLineStrategyEnabled ? color.green : na, linewidth=1)

//─────────────────────────────
// CALCULATIONS - PART 2 (RSI Divergence & Quantum AI)
//─────────────────────────────
rsi1  = ta.rsi(src, rsiPeriod1)
rsi2  = ta.rsi(src, rsiPeriod2)
rsi3  = ta.rsi(src, rsiPeriod3)
rsi4  = ta.rsi(src, rsiPeriod4)
rsi5  = ta.rsi(src, rsiPeriod5)

// Helper function for pivot range
_inRange(cond) =>
    bars = ta.barssince(cond)
    (bars >= rangeLower) and (bars <= rangeUpper)

// Function to calculate divergence signals
divergenceSignals(rsiVal, rsiP) =>
    rocVal = ta.roc(rsiVal, rsiP)
    pivotLow  = ta.pivotlow(rsiVal, lbL, lbR)
    pivotHigh = ta.pivothigh(rsiVal, lbL, lbR)
    inRangePL = _inRange(pivotLow[1])
    inRangePH = _inRange(pivotHigh[1])
    bullCond       = (low[lbR] < ta.valuewhen(pivotLow, low[lbR], 1)) and (rsiVal[lbR] > ta.valuewhen(pivotLow, rsiVal[lbR], 1)) and (not na(pivotLow)) and (rocVal > 0) and inRangePL
    hiddenBullCond = (low[lbR] > ta.valuewhen(pivotLow, low[lbR], 1)) and (rsiVal[lbR] < ta.valuewhen(pivotLow, rsiVal[lbR], 1)) and (not na(pivotLow)) and (rocVal > 0) and inRangePL
    bearCond       = (high[lbR] > ta.valuewhen(pivotHigh, high[lbR], 1)) and (rsiVal[lbR] < ta.valuewhen(pivotHigh, rsiVal[lbR], 1)) and (not na(pivotHigh)) and (rocVal < 0) and inRangePH
    hiddenBearCond = (high[lbR] < ta.valuewhen(pivotHigh, high[lbR], 1)) and (rsiVal[lbR] > ta.valuewhen(pivotHigh, rsiVal[lbR], 1)) and (not na(pivotHigh)) and (rocVal < 0) and inRangePH
    [bullCond, hiddenBullCond, bearCond, hiddenBearCond]

[bullCond1, hiddenBullCond1, bearCond1, hiddenBearCond1] = divergenceSignals(rsi1, rsiPeriod1)
[bullCond2, hiddenBullCond2, bearCond2, hiddenBearCond2] = divergenceSignals(rsi2, rsiPeriod2)
[bullCond3, hiddenBullCond3, bearCond3, hiddenBearCond3] = divergenceSignals(rsi3, rsiPeriod3)
[bullCond4, hiddenBullCond4, bearCond4, hiddenBearCond4] = divergenceSignals(rsi4, rsiPeriod4)
[bullCond5, hiddenBullCond5, bearCond5, hiddenBearCond5] = divergenceSignals(rsi5, rsiPeriod5)

strongBull_div       = bullCond1 and bullCond2 and bullCond3 and bullCond4 and bullCond5
strongHiddenBull_div = hiddenBullCond1 and hiddenBullCond2 and hiddenBullCond3 and hiddenBullCond4 and hiddenBullCond5
strongBear_div       = bearCond1 and bearCond2 and bearCond3 and bearCond4 and bearCond5
strongHiddenBear_div = hiddenBearCond1 and hiddenBearCond2 and hiddenBearCond3 and hiddenBearCond4 and hiddenBearCond5

//─────────────────────────────
// PLOTTING DIVERGENCE SIGNALS
//─────────────────────────────
plotshape(bullCond1 and plotBull, offset=-lbR, title="Bullish RSI1", text="Bull 14", style=shape.labelup, location=location.belowbar, color=color.blue, textcolor=color.white)
plotshape(hiddenBullCond1 and plotHiddenBull, offset=-lbR, title="Hidden Bullish RSI1", text="H Bull 14", style=shape.labelup, location=location.belowbar, color=color.new(color.blue, 80), textcolor=color.white)
plotshape(bearCond1 and plotBear, offset=-lbR, title="Bearish RSI1", text="Bear 14", style=shape.labeldown, location=location.abovebar, color=color.purple, textcolor=color.white)
plotshape(hiddenBearCond1 and plotHiddenBear, offset=-lbR, title="Hidden Bearish RSI1", text="H Bear 14", style=shape.labeldown, location=location.abovebar, color=color.new(color.purple, 80), textcolor=color.white)

plotshape(bullCond2 and plotBull, offset=-lbR, title="Bullish RSI2", text="Bull 21", style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white)
plotshape(hiddenBullCond2 and plotHiddenBull, offset=-lbR, title="Hidden Bullish RSI2", text="H Bull 21", style=shape.labelup, location=location.belowbar, color=color.new(color.green, 80), textcolor=color.white)
plotshape(bearCond2 and plotBear, offset=-lbR, title="Bearish RSI2", text="Bear 21", style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white)
plotshape(hiddenBearCond2 and plotHiddenBear, offset=-lbR, title="Hidden Bearish RSI2", text="H Bear 21", style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 80), textcolor=color.white)

plotshape(bullCond3 and plotBull, offset=-lbR, title="Bullish RSI3", text="Bull 28", style=shape.labelup, location=location.belowbar, color=color.orange, textcolor=color.white)
plotshape(hiddenBullCond3 and plotHiddenBull, offset=-lbR, title="Hidden Bullish RSI3", text="H Bull 28", style=shape.labelup, location=location.belowbar, color=color.new(color.orange, 80), textcolor=color.white)
plotshape(bearCond3 and plotBear, offset=-lbR, title="Bearish RSI3", text="Bear 28", style=shape.labeldown, location=location.abovebar, color=color.maroon, textcolor=color.white)
plotshape(hiddenBearCond3 and plotHiddenBear, offset=-lbR, title="Hidden Bearish RSI3", text="H Bear 28", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 80), textcolor=color.white)

plotshape(bullCond4 and plotBull, offset=-lbR, title="Bullish RSI4", text="Bull 35", style=shape.labelup, location=location.belowbar, color=color.aqua, textcolor=color.white)
plotshape(hiddenBullCond4 and plotHiddenBull, offset=-lbR, title="Hidden Bullish RSI4", text="H Bull 35", style=shape.labelup, location=location.belowbar, color=color.new(color.aqua, 80), textcolor=color.white)
plotshape(bearCond4 and plotBear, offset=-lbR, title="Bearish RSI4", text="Bear 35", style=shape.labeldown, location=location.abovebar, color=color.fuchsia, textcolor=color.white)
plotshape(hiddenBearCond4 and plotHiddenBear, offset=-lbR, title="Hidden Bearish RSI4", text="H Bear 35", style=shape.labeldown, location=location.abovebar, color=color.new(color.fuchsia, 80), textcolor=color.white)

plotshape(bullCond5 and plotBull, offset=-lbR, title="Bullish RSI5", text="Bull 42", style=shape.labelup, location=location.belowbar, color=color.yellow, textcolor=color.white)
plotshape(hiddenBullCond5 and plotHiddenBull, offset=-lbR, title="Hidden Bullish RSI5", text="H Bull 42", style=shape.labelup, location=location.belowbar, color=color.new(color.yellow, 80), textcolor=color.white)
plotshape(bearCond5 and plotBear, offset=-lbR, title="Bearish RSI5", text="Bear 42", style=shape.labeldown, location=location.abovebar, color=color.rgb(165,42,42), textcolor=color.white)
plotshape(hiddenBearCond5 and plotHiddenBear, offset=-lbR, title="Hidden Bearish RSI5", text="H Bear 42", style=shape.labeldown, location=location.abovebar, color=color.new(color.rgb(165,42,42), 80), textcolor=color.white)

plotshape(strongBull_div and plotStrongBull, offset=-lbR, title="Strong Bullish", text="STRONG\nBULL", style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.white, size=size.normal)
plotshape(strongHiddenBull_div and plotStrongHiddenBull, offset=-lbR, title="Strong Hidden Bullish", text="STRONG\nH BULL", style=shape.labelup, location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.black, size=size.normal)
plotshape(strongBear_div and plotStrongBear, offset=-lbR, title="Strong Bearish", text="STRONG\nBEAR", style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.white, size=size.normal)
plotshape(strongHiddenBear_div and plotStrongHiddenBear, offset=-lbR, title="Strong Hidden Bearish", text="STRONG\nH BEAR", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), textcolor=color.white, size=size.normal)

// Additional Divergence MACD & EMA
[macdLine_div, signalLine_div, _] = ta.macd(src, macdFast2, macdSlow2, macdSignal2)
plotshape(ta.crossover(macdLine_div, signalLine_div), title="MACD Bullish (Div)", text="MACD BULL", style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.tiny)
plotshape(ta.crossunder(macdLine_div, signalLine_div), title="MACD Bearish (Div)", text="MACD BEAR", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)
ema1_div = ta.ema(src, emaPeriod1_div)
ema2_div = ta.ema(src, emaPeriod2_div)
plot(ema1_div, title="EMA 1 (Div)", color=color.new(color.red, 0))
plot(ema2_div, title="EMA 2 (Div)", color=color.new(color.blue, 0))

// Quantum AI System Integration (based on divergence signals)
var float quantumScore = 0.0
quantumScore := ((bullCond1 ? 1 : 0) + (bullCond2 ? 1 : 0) + (bullCond3 ? 1 : 0) + (bullCond4 ? 1 : 0) + (bullCond5 ? 1 : 0))
quantumScore := quantumScore - ((bearCond1 ? 1 : 0) + (bearCond2 ? 1 : 0) + (bearCond3 ? 1 : 0) + (bearCond4 ? 1 : 0) + (bearCond5 ? 1 : 0))
quantumScore := quantumScore + (ta.crossover(macdLine_div, signalLine_div) ? 1 : 0)
quantumScore := quantumScore - (ta.crossunder(macdLine_div, signalLine_div) ? 1 : 0)
quantumScore := quantumScore + (ta.crossover(ema1_div, ema2_div) ? 1 : 0)
quantumScore := quantumScore - (ta.crossunder(ema1_div, ema2_div) ? 1 : 0)
correctedQuantumScore = -quantumScore
quantumSignal = correctedQuantumScore > 1 ? 1 : correctedQuantumScore < -1 ? -1 : 0

// ─── NEW: Combined Quantum Strong Signals ───
combinedQuantumStrongBull = (quantumSignal == 1 and strongBull_div)
combinedQuantumStrongBear = (quantumSignal == -1 and strongBear_div)

plotshape(combinedQuantumStrongBull, title="Combined Quantum Strong Bullish", text="Q STRONG BULL", style=shape.labelup, location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.black, size=size.large)
plotshape(combinedQuantumStrongBear, title="Combined Quantum Strong Bearish", text="Q STRONG BEAR", style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.white, size=size.large)

// Higher Timeframe Trend Filter for Divergence signals
trendLong  = not useHTFTrend or (src > htfEMA)
trendShort = not useHTFTrend or (src < htfEMA)

//─────────────────────────────
// COMBINED STRATEGY TRADING LOGIC
//─────────────────────────────
// First, generate ATR-based signals
atrLongSignal  = atrLineStrategyEnabled and ta.crossover(close, lowerATRLine)
atrShortSignal = atrLineStrategyEnabled and ta.crossunder(close, upperATRLine)

// Then combine with your existing Quantum AI signal conditions and the new strong signals
combinedLongSignal  = (((quantumSignal == 1 or combinedQuantumStrongBull) and trendLong and (not volFilterEnabled or volCondition)) or atrLongSignal)
combinedShortSignal = (((quantumSignal == -1 or combinedQuantumStrongBear) and trendShort and (not volFilterEnabled or volCondition)) or atrShortSignal)

if allowTrade
    // Long Entry
    if combinedLongSignal
        if strategy.position_size < 0
            strategy.close("Short", comment="Close Short on Long Signal")
        if strategy.position_size <= 0
            strategy.entry("Long", strategy.long, comment="Combined Long Signal")
    // Short Entry
    if combinedShortSignal
        if strategy.position_size > 0
            strategy.close("Long", comment="Close Long on Short Signal")
        if strategy.position_size >= 0
            strategy.entry("Short", strategy.short, comment="Combined Short Signal")

//─────────────────────────────
// DYNAMIC STOP LOSS / TAKE PROFIT FUNCTION
//─────────────────────────────
f_calcStopTP(entryPrice, isLong) =>
    atr_val = ta.atr(atrPeriod2)
    stopPrice = isLong ? entryPrice - atr_val * atrMultiplierSL : entryPrice + atr_val * atrMultiplierSL
    tpPrice   = isLong ? entryPrice + atr_val * atrMultiplierTP : entryPrice - atr_val * atrMultiplierTP
    if not useATRStop
        stopPrice := isLong ? entryPrice * (1 - stopLossPerc / 100) : entryPrice * (1 + stopLossPerc / 100)
        tpPrice   := isLong ? entryPrice * (1 + takeProfitPerc / 100) : entryPrice * (1 - takeProfitPerc / 100)
    [stopPrice, tpPrice]

//─────────────────────────────
// EXIT ORDERS
//─────────────────────────────
if (strategy.position_size > 0)
    [longStopPrice, longTP] = f_calcStopTP(strategy.position_avg_price, true)
    if enableTrailing
        strategy.exit("Long Exit", from_entry="Long", stop=longStopPrice, limit=longTP, trail_offset=(trailPerc/100)*strategy.position_avg_price)
    else
        strategy.exit("Long Exit", from_entry="Long", stop=longStopPrice, limit=longTP)
if (strategy.position_size < 0)
    [shortStopPrice, shortTP] = f_calcStopTP(strategy.position_avg_price, false)
    if enableTrailing
        strategy.exit("Short Exit", from_entry="Short", stop=shortStopPrice, limit=shortTP, trail_offset=(trailPerc/100)*strategy.position_avg_price)
    else
        strategy.exit("Short Exit", from_entry="Short", stop=shortStopPrice, limit=shortTP)

//─────────────────────────────
// STANDARD & ADDITIONAL RSI CROSSOVER SIGNALS
//─────────────────────────────
rsiCrossUp   = ta.crossover(rsi1, rsi3)
rsiCrossDown = ta.crossunder(rsi1, rsi3)
plotshape(rsiCrossUp, title="RSI 14/28 Cross Up", text="RSI14/28 XUp", style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.white)
plotshape(rsiCrossDown, title="RSI 14/28 Cross Down", text="RSI14/28 XDown", style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.white)

rsi7 = ta.rsi(src, 7)
cross7_14      = ta.crossover(rsi7, rsi1)
cross14_21     = ta.crossover(rsi1, rsi2)
cross21_28     = ta.crossover(rsi2, rsi3)
cross28_35     = ta.crossover(rsi3, rsi4)
cross35_42     = ta.crossover(rsi4, rsi5)
strongRSICrossUp = cross7_14 and cross14_21 and cross21_28 and cross28_35 and cross35_42

cross7_14_down      = ta.crossunder(rsi7, rsi1)
cross14_21_down     = ta.crossunder(rsi1, rsi2)
cross21_28_down     = ta.crossunder(rsi2, rsi3)
cross28_35_down     = ta.crossunder(rsi3, rsi4)
cross35_42_down     = ta.crossunder(rsi4, rsi5)
strongRSICrossDown = cross7_14_down and cross14_21_down and cross21_28_down and cross28_35_down and cross35_42_down

plotshape(strongRSICrossUp, title="Strong All RSI Cross Up", text="ALL XUp", style=shape.labelup, location=location.belowbar, color=color.new(color.teal, 0), textcolor=color.white)
plotshape(strongRSICrossDown, title="Strong All RSI Cross Down", text="ALL XDown", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), textcolor=color.white)

rsi21CrossUp42   = ta.crossover(rsi2, rsi5)
rsi21CrossDown42 = ta.crossunder(rsi2, rsi5)
plotshape(rsi21CrossUp42, title="RSI21/42 Cross Up", text="RSI21>RSI42", style=shape.labelup, location=location.belowbar, color=color.new(color.purple, 0), textcolor=color.white)
plotshape(rsi21CrossDown42, title="RSI21/42 Cross Down", text="RSI21<RSI42", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), textcolor=color.white)

strongRsi21MacdBull = rsi21CrossUp42 and ta.crossover(macdLine_div, signalLine_div)
strongRsi21MacdBear = rsi21CrossDown42 and ta.crossunder(macdLine_div, signalLine_div)
plotshape(strongRsi21MacdBull, title="Strong RSI21/42 + MACD Bullish", text="STRONG\nRSI21>RSI42+MACD", style=shape.labelup, location=location.belowbar, color=color.new(color.teal, 0), textcolor=color.white, size=size.normal)
plotshape(strongRsi21MacdBear, title="Strong RSI21/42 + MACD Bearish", text="STRONG\nRSI21<RSI42+MACD", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), textcolor=color.white, size=size.normal)

combinedStrongBull = strongRSICrossUp and ta.crossover(macdLine_div, signalLine_div)
combinedStrongBear = strongRSICrossDown and ta.crossunder(macdLine_div, signalLine_div)
plotshape(combinedStrongBull, title="Combined Strong RSI+MACD Bullish", text="ALL RSI+MACD\nBULL", style=shape.labelup, location=location.belowbar, color=color.new(color.teal, 0), textcolor=color.white, size=size.normal)
plotshape(combinedStrongBear, title="Combined Strong RSI+MACD Bearish", text="ALL RSI+MACD\nBEAR", style=shape.labeldown, location=location.abovebar, color=color.new(color.maroon, 0), textcolor=color.white, size=size.normal)

//─────────────────────────────
// TABLE DISPLAY: RSI & Quantum Score
//─────────────────────────────
var tbl = table.new(position.top_right, 6, 3, border_width=1)
table.cell(tbl, 0, 0, "RSI 14", bgcolor=color.gray, text_color=color.white)
table.cell(tbl, 1, 0, "RSI 21", bgcolor=color.gray, text_color=color.white)
table.cell(tbl, 2, 0, "RSI 28", bgcolor=color.gray, text_color=color.white)
table.cell(tbl, 3, 0, "RSI 35", bgcolor=color.gray, text_color=color.white)
table.cell(tbl, 4, 0, "RSI 42", bgcolor=color.gray, text_color=color.white)
table.cell(tbl, 5, 0, "Q Score", bgcolor=color.gray, text_color=color.white)

table.cell(tbl, 0, 1, str.tostring(rsi1, "#.00"), bgcolor=color.new(color.gray, 80), text_color=rsi1 > 50 ? color.green : color.red)
table.cell(tbl, 1, 1, str.tostring(rsi2, "#.00"), bgcolor=color.new(color.gray, 80), text_color=rsi2 > 50 ? color.green : color.red)
table.cell(tbl, 2, 1, str.tostring(rsi3, "#.00"), bgcolor=color.new(color.gray, 80), text_color=rsi3 > 50 ? color.green : color.red)
table.cell(tbl, 3, 1, str.tostring(rsi4, "#.00"), bgcolor=color.new(color.gray, 80), text_color=rsi4 > 50 ? color.green : color.red)
table.cell(tbl, 4, 1, str.tostring(rsi5, "#.00"), bgcolor=color.new(color.gray, 80), text_color=rsi5 > 50 ? color.green : color.red)
table.cell(tbl, 5, 1, str.tostring(correctedQuantumScore, "#.00"), bgcolor=color.new(color.black, 80), text_color=correctedQuantumScore >= 0 ? color.green : color.red)

signalText = quantumSignal == 1 ? "Bullish" : quantumSignal == -1 ? "Bearish" : "Neutral"
table.cell(tbl, 0, 2, "Signal", bgcolor=color.gray, text_color=color.white)
for i = 1 to 5
    table.cell(tbl, i, 2, signalText, bgcolor=quantumSignal == 1 ? color.green : quantumSignal == -1 ? color.red : color.blue, text_color=color.white)

// Composite Strong Signal Calculation
var float compositeScore = 0.0
compositeScore := (strongRSICrossUp ? 1 : 0) + (strongRsi21MacdBull ? 1 : 0) + (atrLongSignal ? 1 : 0)
compositeScore := compositeScore - ((strongRSICrossDown ? 1 : 0) + (strongRsi21MacdBear ? 1 : 0) + (atrShortSignal ? 1 : 0))
strongCompositeSignal = compositeScore >= 2 ? 1 : compositeScore <= -2 ? -1 : 0

// Plot composite signals
plotshape(strongCompositeSignal == 1, title="Strong Composite Bull", text="SCB", style=shape.labelup, 
     location=location.belowbar, color=color.lime, size=size.normal)
plotshape(strongCompositeSignal == -1, title="Strong Composite Bear", text="SCBear", style=shape.labeldown, 
     location=location.abovebar, color=color.red, size=size.normal)

// Helper function defined at the top level
inRange(cond, _rangeLower, _rangeUpper) =>
    bars = ta.barssince(cond)
    (bars >= _rangeLower) and (bars <= _rangeUpper)

// Function to calculate divergence signals for a given RSI period
divergenceSignalsCustom(_src, _rsiPeriod, _lbL, _lbR, _rangeUpper, _rangeLower) =>
    _rsi = ta.rsi(_src, _rsiPeriod)
    rocVal = ta.roc(_rsi, _rsiPeriod)
    pivotLow  = ta.pivotlow(_rsi, _lbL, _lbR)
    pivotHigh = ta.pivothigh(_rsi, _lbL, _lbR)
    inRangePL = inRange(pivotLow[1], _rangeLower, _rangeUpper)
    inRangePH = inRange(pivotHigh[1], _rangeLower, _rangeUpper)
    bullCond       = (low[_lbR] < ta.valuewhen(pivotLow, low[_lbR], 1)) and (_rsi[_lbR] > ta.valuewhen(pivotLow, _rsi[_lbR], 1)) and (not na(pivotLow)) and (rocVal > 0) and inRangePL
    hiddenBullCond = (low[_lbR] > ta.valuewhen(pivotLow, low[_lbR], 1)) and (_rsi[_lbR] < ta.valuewhen(pivotLow, _rsi[_lbR], 1)) and (not na(pivotLow)) and (rocVal > 0) and inRangePL
    bearCond       = (high[_lbR] > ta.valuewhen(pivotHigh, high[_lbR], 1)) and (_rsi[_lbR] < ta.valuewhen(pivotHigh, _rsi[_lbR], 1)) and (not na(pivotHigh)) and (rocVal < 0) and inRangePH
    hiddenBearCond = (high[_lbR] < ta.valuewhen(pivotHigh, high[_lbR], 1)) and (_rsi[_lbR] > ta.valuewhen(pivotHigh, _rsi[_lbR], 1)) and (not na(pivotHigh)) and (rocVal < 0) and inRangePH
    [bullCond, hiddenBullCond, bearCond, hiddenBearCond]


// Usage for RSI period 14:
[divBullCond1, divHiddenBullCond1, divBearCond1, divHiddenBearCond1] = divergenceSignalsCustom(close, rsiPeriod1, lbL, lbR, rangeUpper, rangeLower)

//─────────────────────────────
// ALL RSI ABOVE/BELOW 50 WITH STRONG CROSSOVER SIGNALS
//─────────────────────────────
// Define conditions where all RSI periods are above or below 50
allRsiAbove50 = (rsi1 >= 50) and (rsi2 >= 50) and (rsi3 >= 50) and (rsi4 >= 50) and (rsi5 >= 50)
allRsiBelow50 = (rsi1 <= 50) and (rsi2 <= 50) and (rsi3 <= 50) and (rsi4 <= 50) and (rsi5 <= 50)

// Combine with strong RSI crossover conditions
strongBuyAllRsi = allRsiAbove50 and strongRSICrossUp
strongSellAllRsi = allRsiBelow50 and strongRSICrossDown

// Plotting the new signals
plotshape(strongBuyAllRsi, title="Strong Buy - All RSI≥50 & Cross Up", text="ALL RSI↑\nSTRONG BUY", 
     style=shape.labelup, location=location.belowbar, color=color.new(color.lime, 0), 
     textcolor=color.black, size=size.large)
plotshape(strongSellAllRsi, title="Strong Sell - All RSI≤50 & Cross Down", text="ALL RSI↓\nSTRONG SELL", 
     style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), 
     textcolor=color.white, size=size.large)