// @version=6
// ═══════════════════════════════════════════════════════════════════════════════
// SMART MONEY CONCEPTS - ANTI-TRAP CONFIRMATION SYSTEM
// ═══════════════════════════════════════════════════════════════════════════════
// Enhanced with multi-layer confirmations to avoid liquidity traps
// Author: Enhanced Version | Version: 2.1
// ═══════════════════════════════════════════════════════════════════════════════

strategy(
     title="SMC Anti-Trap Strategy Pro",
     shorttitle="Yzkvng SMC Pro V2",
     overlay=true,
     initial_capital=10000,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=0,
     commission_type=strategy.commission.percent,
     commission_value=0.1,
     slippage=2,
     pyramiding=0
 )

// ═══════════════════════════════════════════════════════════════════════════════
// 📊 INPUT PARAMETERS
// ═══════════════════════════════════════════════════════════════════════════════

// --- Risk Management ---
grp1 = "═══ Risk Management ═══"
riskPercent      = input.float(1.0, "Risk Per Trade (%)", minval=0.1, maxval=5, step=0.1, group=grp1)
minRiskUSD       = input.float(10, "Minimum Risk Amount ($)", minval=0, step=1, group=grp1)
rrRatio          = input.float(2.0, "Risk/Reward Ratio", minval=0.5, maxval=10, step=0.1, group=grp1)
maxDailyTrades   = input.int(3, "Max Trades Per Day", minval=1, group=grp1)

// --- Structure Detection ---
grp2 = "═══ Structure Settings ═══"
swingLength      = input.int(5, "Swing Detection Length", minval=2, maxval=20, group=grp2, tooltip="Lookback for pivot high/low detection")
atrLength        = input.int(14, "ATR Period", minval=5, maxval=50, group=grp2)
atrMultiplier    = input.float(1.5, "ATR Stop Loss Multiplier", minval=0.5, maxval=5, step=0.1, group=grp2)
zoneBuffer       = input.float(1.0, "Retest Zone Buffer (ATR)", minval=0.5, maxval=3, step=0.1, group=grp2)

// --- Market Context ---
grp3 = "═══ Market Analysis ═══"
trendEmaLength   = input.int(50, "Trend EMA Length", minval=10, maxval=200, group=grp3)
emaSlopeLength   = input.int(5, "EMA Slope Lookback", minval=1, maxval=20, group=grp3)
adxLength        = input.int(14, "ADX Period", minval=5, maxval=50, group=grp3)
adxThreshold     = input.float(25, "ADX Trend Threshold", minval=10, maxval=50, step=1, group=grp3)
rangeLookback    = input.int(50, "Range Detection Period", minval=20, maxval=200, group=grp3)

// --- CONFIRMATION SETTINGS (NEW) ---
grp_confirm = "═══ ⚡ Anti-Trap Confirmations ═══"
requireCandleClose    = input.bool(true, "✓ Require Bullish/Bearish Close", group=grp_confirm, tooltip="Wait for confirmation candle")
requireVolume         = input.bool(true, "✓ Require Volume Spike", group=grp_confirm, tooltip="Volume must be above average")
volumeMultiplier      = input.float(1.2, "Volume Spike Multiplier", minval=1.0, maxval=3.0, step=0.1, group=grp_confirm)
requireMomentum       = input.bool(true, "✓ Require RSI Momentum", group=grp_confirm, tooltip="RSI must support direction")
rsiPeriod             = input.int(14, "RSI Period", minval=5, maxval=50, group=grp_confirm)
rsiBullThreshold      = input.float(40, "RSI Bull Min", minval=20, maxval=60, step=5, group=grp_confirm)
rsiBearThreshold      = input.float(60, "RSI Bear Max", minval=40, maxval=80, step=5, group=grp_confirm)
requirePriceAction    = input.bool(true, "✓ Check Wick Rejection", group=grp_confirm, tooltip="Candle must show rejection wicks")
wickRatio             = input.float(0.3, "Min Wick Ratio", minval=0.1, maxval=0.5, step=0.05, group=grp_confirm)
requireNoOpposingPA   = input.bool(true, "✓ Block Opposing Pressure", group=grp_confirm, tooltip="No strong candles against trade direction")
opposingBarCheck      = input.int(3, "Bars to Check", minval=1, maxval=10, group=grp_confirm)

// --- Trade Execution ---
grp4 = "═══ Trade Settings ═══"
autoTrade        = input.bool(false, "Enable Auto Trading", group=grp4)
tradeOnTrend     = input.bool(true, "Trade Trending Markets", group=grp4)
tradeOnRange     = input.bool(true, "Trade Ranging Markets", group=grp4)
minConfirmations = input.int(3, "Minimum Confirmations Required", minval=1, maxval=5, group=grp4, tooltip="How many confirmation checks must pass")

// --- Visual Display ---
grp5 = "═══ Visual Settings ═══"
showProjections  = input.bool(true, "Show ALL Predicted Levels", group=grp5)
projectionLength = input.int(30, "Projection Length (bars)", minval=10, maxval=100, group=grp5)
showZones        = input.bool(true, "Show Retest Zones", group=grp5)
showTable        = input.bool(true, "Show Info Table", group=grp5)
showConfirmTable = input.bool(true, "Show Confirmation Status", group=grp5)

// ═══════════════════════════════════════════════════════════════════════════════
// 🔧 CORE INDICATORS
// ═══════════════════════════════════════════════════════════════════════════════

atr = ta.atr(atrLength)
ema = ta.ema(close, trendEmaLength)
emaSlope = ema - ema[emaSlopeLength]

// RSI for momentum confirmation
rsi = ta.rsi(close, rsiPeriod)

// Volume analysis
avgVolume = ta.sma(volume, 20)
volumeSpike = volume > avgVolume * volumeMultiplier

// --- ADX Calculation (Wilder's Method) ---
calcADX(len) =>
    up = ta.change(high)
    down = -ta.change(low)
    plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
    minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
    trur = ta.rma(ta.tr, len)
    plus = fixnan(100 * ta.rma(plusDM, len) / trur)
    minus = fixnan(100 * ta.rma(minusDM, len) / trur)
    sum = plus + minus
    adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), len)
    [adx, plus, minus]

[adxValue, plusDI, minusDI] = calcADX(adxLength)

// ═══════════════════════════════════════════════════════════════════════════════
// 📍 PIVOT STRUCTURE TRACKING
// ═══════════════════════════════════════════════════════════════════════════════

pivotHigh = ta.pivothigh(high, swingLength, swingLength)
pivotLow = ta.pivotlow(low, swingLength, swingLength)

// Store last two pivot highs and lows
var float lastPH = na
var int lastPHBar = na
var float prevPH = na
var int prevPHBar = na

var float lastPL = na
var int lastPLBar = na
var float prevPL = na
var int prevPLBar = na

if not na(pivotHigh)
    prevPH := lastPH
    prevPHBar := lastPHBar
    lastPH := pivotHigh
    lastPHBar := bar_index - swingLength

if not na(pivotLow)
    prevPL := lastPL
    prevPLBar := lastPLBar
    lastPL := pivotLow
    lastPLBar := bar_index - swingLength

// ═══════════════════════════════════════════════════════════════════════════════
// 📈 MARKET STRUCTURE & TYPE DETECTION
// ═══════════════════════════════════════════════════════════════════════════════

// Structure determination
var string structure = "Neutral"
if not na(lastPH) and not na(prevPH) and not na(lastPL) and not na(prevPL)
    bool higherHighs = lastPH > prevPH
    bool higherLows = lastPL > prevPL
    bool lowerHighs = lastPH < prevPH
    bool lowerLows = lastPL < prevPL
    
    if higherHighs and higherLows
        structure := "Bullish"
    else if lowerHighs and lowerLows
        structure := "Bearish"
    else
        structure := "Neutral"

// Range detection
rangeHigh = ta.highest(high, rangeLookback)
rangeLow = ta.lowest(low, rangeLookback)
rangeSize = rangeHigh - rangeLow

// Market type classification
var string marketType = "Neutral"
bool isTrending = adxValue >= adxThreshold and math.abs(emaSlope) > atr * 0.5
bool inRange = close >= rangeLow and close <= rangeHigh and rangeSize > atr * 2

if isTrending
    marketType := emaSlope > 0 ? "Trending Up" : "Trending Down"
else if inRange
    marketType := "Ranging"
else
    marketType := "Neutral"

// ═══════════════════════════════════════════════════════════════════════════════
// ⚡ ANTI-TRAP CONFIRMATION SYSTEM
// ═══════════════════════════════════════════════════════════════════════════════

// 1. CANDLE CLOSE CONFIRMATION
bullishCandleClose = close > open and close > close[1]
bearishCandleClose = close < open and close < close[1]

// 2. VOLUME CONFIRMATION
volumeConfirmed = not requireVolume or volumeSpike

// 3. RSI MOMENTUM CONFIRMATION
rsiBullish = not requireMomentum or (rsi >= rsiBullThreshold and rsi < 70)
rsiBearish = not requireMomentum or (rsi <= rsiBearThreshold and rsi > 30)

// 4. PRICE ACTION / WICK REJECTION
candleBody = math.abs(close - open)
candleRange = high - low
lowerWick = low < math.min(open, close) ? math.min(open, close) - low : 0
upperWick = high > math.max(open, close) ? high - math.max(open, close) : 0

// For longs: lower wick should show rejection (buyers stepping in)
bullWickRejection = not requirePriceAction or (lowerWick >= candleRange * wickRatio)

// For shorts: upper wick should show rejection (sellers stepping in)
bearWickRejection = not requirePriceAction or (upperWick >= candleRange * wickRatio)

// 5. NO OPPOSING PRESSURE CHECK
// Check if recent bars show strong opposing direction
strongBearishBar(i) => (close[i] < open[i]) and (math.abs(close[i] - open[i]) > atr[i] * 0.5)
strongBullishBar(i) => (close[i] > open[i]) and (math.abs(close[i] - open[i]) > atr[i] * 0.5)

checkOpposingPressure(isLong) =>
    if not requireNoOpposingPA
        true
    else
        noOpposing = true
        for i = 1 to opposingBarCheck
            if isLong and strongBearishBar(i)
                noOpposing := false
                break
            if not isLong and strongBullishBar(i)
                noOpposing := false
                break
        noOpposing

// CONFIRMATION COUNTERS FOR DISPLAY
var int bullConfirmCount = 0
var int bearConfirmCount = 0

// Calculate confirmations
calcBullConfirmations() =>
    count = 0
    if not requireCandleClose or bullishCandleClose
        count += 1
    if volumeConfirmed
        count += 1
    if rsiBullish
        count += 1
    if bullWickRejection
        count += 1
    if checkOpposingPressure(true)
        count += 1
    count

calcBearConfirmations() =>
    count = 0
    if not requireCandleClose or bearishCandleClose
        count += 1
    if volumeConfirmed
        count += 1
    if rsiBearish
        count += 1
    if bearWickRejection
        count += 1
    if checkOpposingPressure(false)
        count += 1
    count

bullConfirmCount := calcBullConfirmations()
bearConfirmCount := calcBearConfirmations()

// ═══════════════════════════════════════════════════════════════════════════════
// 🎯 PREDICTED TRADE SETUPS
// ═══════════════════════════════════════════════════════════════════════════════

// Retest zones for trending setups
bullZoneTop = not na(prevPL) ? prevPL + atr * zoneBuffer : na
bullZoneBottom = not na(prevPL) ? prevPL - atr * 0.5 : na

bearZoneTop = not na(prevPH) ? prevPH + atr * 0.5 : na
bearZoneBottom = not na(prevPH) ? prevPH - atr * zoneBuffer : na

// PREDICTED BULL ENTRY (from previous pivot low)
predBullEntry = prevPL
predBullSL = not na(predBullEntry) ? predBullEntry - atr * atrMultiplier : na
predBullTP = not na(predBullEntry) and not na(predBullSL) ? predBullEntry + (predBullEntry - predBullSL) * rrRatio : na

// PREDICTED BEAR ENTRY (from previous pivot high)
predBearEntry = prevPH
predBearSL = not na(predBearEntry) ? predBearEntry + atr * atrMultiplier : na
predBearTP = not na(predBearEntry) and not na(predBearSL) ? predBearEntry - (predBearSL - predBearEntry) * rrRatio : na

// Range-based setups
rangeLongEntry = rangeLow
rangeLongSL = rangeLongEntry - atr * atrMultiplier
rangeLongTP = rangeLongEntry + (rangeLongEntry - rangeLongSL) * rrRatio

rangeShortEntry = rangeHigh
rangeShortSL = rangeShortEntry + atr * atrMultiplier
rangeShortTP = rangeShortEntry - (rangeShortSL - rangeShortEntry) * rrRatio

// ═══════════════════════════════════════════════════════════════════════════════
// ✅ ENHANCED CONFIRMATION CONDITIONS
// ═══════════════════════════════════════════════════════════════════════════════

bool longZoneTouch = not na(bullZoneTop) and low <= bullZoneTop and low >= bullZoneBottom

// LONG must pass ALL enabled confirmations
bool longConfirm = longZoneTouch and bullConfirmCount >= minConfirmations

bool shortZoneTouch = not na(bearZoneBottom) and high >= bearZoneBottom and high <= bearZoneTop

// SHORT must pass ALL enabled confirmations
bool shortConfirm = shortZoneTouch and bearConfirmCount >= minConfirmations

bool rangeLongTouch = close <= rangeLow + atr * 0.5
bool rangeLongConfirm = rangeLongTouch and bullConfirmCount >= minConfirmations

bool rangeShortTouch = close >= rangeHigh - atr * 0.5
bool rangeShortConfirm = rangeShortTouch and bearConfirmCount >= minConfirmations

// ═══════════════════════════════════════════════════════════════════════════════
// 🎲 NEXT TRADE DECISION LOGIC
// ═══════════════════════════════════════════════════════════════════════════════

var float nextEntry = na
var float nextSL = na
var float nextTP = na
var string nextTradeType = "None"
var string nextReason = ""

// Reset each bar
nextEntry := na
nextSL := na
nextTP := na
nextTradeType := "None"
nextReason := ""

// Priority 1: Trending markets
if marketType == "Trending Up" and tradeOnTrend
    if not na(predBullEntry) and not na(predBullSL) and not na(predBullTP)
        nextEntry := predBullEntry
        nextSL := predBullSL
        nextTP := predBullTP
        nextTradeType := "LONG"
        nextReason := "Trend Up + Retest (" + str.tostring(bullConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"

else if marketType == "Trending Down" and tradeOnTrend
    if not na(predBearEntry) and not na(predBearSL) and not na(predBearTP)
        nextEntry := predBearEntry
        nextSL := predBearSL
        nextTP := predBearTP
        nextTradeType := "SHORT"
        nextReason := "Trend Down + Retest (" + str.tostring(bearConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"

// Priority 2: Ranging markets
if marketType == "Ranging" and tradeOnRange and nextTradeType == "None"
    if math.abs(close - rangeHigh) <= atr * 1.5
        nextEntry := rangeShortEntry
        nextSL := rangeShortSL
        nextTP := rangeShortTP
        nextTradeType := "SHORT"
        nextReason := "Range Top (" + str.tostring(bearConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"
    else if math.abs(close - rangeLow) <= atr * 1.5
        nextEntry := rangeLongEntry
        nextSL := rangeLongSL
        nextTP := rangeLongTP
        nextTradeType := "LONG"
        nextReason := "Range Bottom (" + str.tostring(bullConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"

// Priority 3: Structure-based fallback
if nextTradeType == "None"
    if structure == "Bullish" and not na(predBullEntry)
        nextEntry := predBullEntry
        nextSL := predBullSL
        nextTP := predBullTP
        nextTradeType := "LONG"
        nextReason := "Bull Structure (" + str.tostring(bullConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"
    else if structure == "Bearish" and not na(predBearEntry)
        nextEntry := predBearEntry
        nextSL := predBearSL
        nextTP := predBearTP
        nextTradeType := "SHORT"
        nextReason := "Bear Structure (" + str.tostring(bearConfirmCount) + "/" + str.tostring(minConfirmations) + " ✓)"

// ═══════════════════════════════════════════════════════════════════════════════
// 💼 POSITION SIZING
// ═══════════════════════════════════════════════════════════════════════════════

calcPositionSize(entryPrice, stopPrice) =>
    riskAmount = math.max(strategy.equity * (riskPercent / 100), minRiskUSD)
    riskPerUnit = math.abs(entryPrice - stopPrice)
    qty = riskPerUnit > 0 ? riskAmount / riskPerUnit : 0.0
    qty

// ═══════════════════════════════════════════════════════════════════════════════
// 📊 TRADE EXECUTION WITH CONFIRMATIONS
// ═══════════════════════════════════════════════════════════════════════════════

var int dailyTrades = 0
if dayofmonth != dayofmonth[1]
    dailyTrades := 0

if autoTrade and strategy.position_size == 0 and dailyTrades < maxDailyTrades
    
    // Trending long (WITH CONFIRMATIONS)
    if tradeOnTrend and marketType == "Trending Up" and longConfirm
        qty = calcPositionSize(close, predBullSL)
        if qty > 0
            strategy.entry("Long", strategy.long, qty=qty)
            strategy.exit("Long Exit", "Long", stop=predBullSL, limit=predBullTP)
            dailyTrades += 1
    
    // Trending short (WITH CONFIRMATIONS)
    if tradeOnTrend and marketType == "Trending Down" and shortConfirm
        qty = calcPositionSize(close, predBearSL)
        if qty > 0
            strategy.entry("Short", strategy.short, qty=qty)
            strategy.exit("Short Exit", "Short", stop=predBearSL, limit=predBearTP)
            dailyTrades += 1
    
    // Range long (WITH CONFIRMATIONS)
    if tradeOnRange and marketType == "Ranging" and rangeLongConfirm
        qty = calcPositionSize(close, rangeLongSL)
        if qty > 0
            strategy.entry("Range Long", strategy.long, qty=qty)
            strategy.exit("Range Long Exit", "Range Long", stop=rangeLongSL, limit=rangeLongTP)
            dailyTrades += 1
    
    // Range short (WITH CONFIRMATIONS)
    if tradeOnRange and marketType == "Ranging" and rangeShortConfirm
        qty = calcPositionSize(close, rangeShortSL)
        if qty > 0
            strategy.entry("Range Short", strategy.short, qty=qty)
            strategy.exit("Range Short Exit", "Range Short", stop=rangeShortSL, limit=rangeShortTP)
            dailyTrades += 1

// ═══════════════════════════════════════════════════════════════════════════════
// 🎨 VISUAL ELEMENTS
// ═══════════════════════════════════════════════════════════════════════════════

// Plot EMA
plot(ema, "Trend EMA", color=color.new(color.yellow, 0), linewidth=2)

// Plot previous pivots
plot(prevPL, "Prev Pivot Low", color=color.new(color.green, 60), linewidth=1, style=plot.style_linebr)
plot(prevPH, "Prev Pivot High", color=color.new(color.red, 60), linewidth=1, style=plot.style_linebr)

// Structure bias indicators
plotshape(structure == "Bullish" ? low : na, "Bullish Bias", shape.triangleup, location.belowbar, color.new(color.green, 40), size=size.tiny)
plotshape(structure == "Bearish" ? high : na, "Bearish Bias", shape.triangledown, location.abovebar, color.new(color.red, 40), size=size.tiny)

// Confirmation signals
plotshape(longConfirm ? low : na, "✓ Long Confirmed", shape.circle, location.belowbar, color.new(color.lime, 0), size=size.small)
plotshape(shortConfirm ? high : na, "✓ Short Confirmed", shape.circle, location.abovebar, color.new(color.fuchsia, 0), size=size.small)

// ═══════════════════════════════════════════════════════════════════════════════
// 📦 RETEST ZONES
// ═══════════════════════════════════════════════════════════════════════════════

var box bullZoneBox = na
var box bearZoneBox = na

if showZones and not na(prevPL) and not na(bullZoneTop) and not na(bullZoneBottom)
    if not na(bullZoneBox)
        box.delete(bullZoneBox)
    bullZoneBox := box.new(prevPLBar, bullZoneTop, bar_index, bullZoneBottom, 
                           bgcolor=color.new(color.green, 90), 
                           border_color=color.new(color.green, 50), 
                           border_width=1)

if showZones and not na(prevPH) and not na(bearZoneTop) and not na(bearZoneBottom)
    if not na(bearZoneBox)
        box.delete(bearZoneBox)
    bearZoneBox := box.new(prevPHBar, bearZoneTop, bar_index, bearZoneBottom, 
                           bgcolor=color.new(color.red, 90), 
                           border_color=color.new(color.red, 50), 
                           border_width=1)

// Range levels
plot(marketType == "Ranging" ? rangeHigh : na, "Range High", color.new(color.orange, 0), linewidth=2, style=plot.style_linebr)
plot(marketType == "Ranging" ? rangeLow : na, "Range Low", color.new(color.orange, 0), linewidth=2, style=plot.style_linebr)

// ═══════════════════════════════════════════════════════════════════════════════
// 🔮 PREDICTED SETUPS
// ═══════════════════════════════════════════════════════════════════════════════

var line predBullEntryLine = na
var line predBullSLLine = na
var line predBullTPLine = na
var label predBullLabel = na

var line predBearEntryLine = na
var line predBearSLLine = na
var line predBearTPLine = na
var label predBearLabel = na

// Clean old drawings
if not na(predBullEntryLine)
    line.delete(predBullEntryLine)
if not na(predBullSLLine)
    line.delete(predBullSLLine)
if not na(predBullTPLine)
    line.delete(predBullTPLine)
if not na(predBullLabel)
    label.delete(predBullLabel)

if not na(predBearEntryLine)
    line.delete(predBearEntryLine)
if not na(predBearSLLine)
    line.delete(predBearSLLine)
if not na(predBearTPLine)
    line.delete(predBearTPLine)
if not na(predBearLabel)
    label.delete(predBearLabel)

// Draw PREDICTED BULL setup
if showProjections and not na(predBullEntry) and not na(predBullSL) and not na(predBullTP)
    predBullEntryLine := line.new(bar_index, predBullEntry, bar_index + projectionLength, predBullEntry, 
                                   color=color.new(color.green, 0), width=2, style=line.style_solid)
    predBullSLLine := line.new(bar_index, predBullSL, bar_index + projectionLength, predBullSL, 
                                color=color.new(color.red, 50), width=1, style=line.style_dashed)
    predBullTPLine := line.new(bar_index, predBullTP, bar_index + projectionLength, predBullTP, 
                                color=color.new(color.green, 30), width=1, style=line.style_dashed)
    predBullLabel := label.new(bar_index + projectionLength, predBullEntry, 
                                "🟢 BULL\nEntry: " + str.tostring(predBullEntry, format.mintick) + 
                                "\nSL: " + str.tostring(predBullSL, format.mintick) + 
                                "\nTP: " + str.tostring(predBullTP, format.mintick) +
                                "\n✓: " + str.tostring(bullConfirmCount) + "/5",
                                style=label.style_label_left, 
                                color=color.new(color.green, 80), 
                                textcolor=color.white, 
                                size=size.normal)

// Draw PREDICTED BEAR setup
if showProjections and not na(predBearEntry) and not na(predBearSL) and not na(predBearTP)
    predBearEntryLine := line.new(bar_index, predBearEntry, bar_index + projectionLength, predBearEntry, 
                                   color=color.new(color.red, 0), width=2, style=line.style_solid)
    predBearSLLine := line.new(bar_index, predBearSL, bar_index + projectionLength, predBearSL, 
                                color=color.new(color.green, 50), width=1, style=line.style_dashed)
    predBearTPLine := line.new(bar_index, predBearTP, bar_index + projectionLength, predBearTP, 
                                color=color.new(color.red, 30), width=1, style=line.style_dashed)
    predBearLabel := label.new(bar_index + projectionLength, predBearEntry, 
                                "🔴 BEAR\nEntry: " + str.tostring(predBearEntry, format.mintick) + 
                                "\nSL: " + str.tostring(predBearSL, format.mintick) + 
                                "\nTP: " + str.tostring(predBearTP, format.mintick) +
                                "\n✓: " + str.tostring(bearConfirmCount) + "/5",
                                style=label.style_label_left, 
                                color=color.new(color.green, 80), 
                                textcolor=color.white, 
                                size=size.normal)

// ═══════════════════════════════════════════════════════════════════════════════
// ⭐ NEXT PLANNED TRADE - BRIGHT & CLEAR
// ═══════════════════════════════════════════════════════════════════════════════

var line nextEntryLine = na
var line nextSLLine = na
var line nextTPLine = na
var label nextLabel = na

// Clean previous
if not na(nextEntryLine)
    line.delete(nextEntryLine)
if not na(nextSLLine)
    line.delete(nextSLLine)
if not na(nextTPLine)
    line.delete(nextTPLine)
if not na(nextLabel)
    label.delete(nextLabel)

// Draw NEXT TRADE with bright colors
if not na(nextEntry) and not na(nextSL) and not na(nextTP)
    isLong = nextTradeType == "LONG"
    
    nextEntryLine := line.new(bar_index, nextEntry, bar_index + projectionLength, nextEntry, 
                              color=isLong ? color.new(color.lime, 0) : color.new(color.fuchsia, 0), 
                              width=3, style=line.style_solid)
    
    nextSLLine := line.new(bar_index, nextSL, bar_index + projectionLength, nextSL, 
                           color=color.new(color.red, 40), width=2, style=line.style_dashed)
    
    nextTPLine := line.new(bar_index, nextTP, bar_index + projectionLength, nextTP, 
                           color=color.new(color.aqua, 20), width=2, style=line.style_dashed)
    
    labelText = "⭐ NEXT: " + nextTradeType + "\nEntry: " + str.tostring(nextEntry, format.mintick) +  "\nSL: " + str.tostring(nextSL, format.mintick) + "\nTP: " + str.tostring(nextTP, format.mintick) + "\nReason: " + nextReason
    
    nextLabel := label.new(bar_index + projectionLength, nextEntry, labelText,
                           style=label.style_label_left, 
                           color=isLong ? color.new(color.lime, 70) : color.new(color.fuchsia, 70), 
                           textcolor=color.white, 
                           size=size.large, 
                           textalign=text.align_left)

// ═══════════════════════════════════════════════════════════════════════════════
// 📊 INFO TABLE - CLEAN & PROFESSIONAL
// ═══════════════════════════════════════════════════════════════════════════════

if showTable
    var table infoTable = table.new(position.top_right, 2, 11, border_width=1)
    
    if barstate.islast
        // Header
        table.cell(infoTable, 0, 0, "📊 MARKET STATUS", text_color=color.white, bgcolor=color.new(color.blue, 60), text_size=size.normal)
        table.cell(infoTable, 1, 0, "", bgcolor=color.new(color.blue, 60))
        
        // Structure
        table.cell(infoTable, 0, 1, "Structure", text_color=color.white, bgcolor=color.new(color.gray, 70))
        structColor = structure == "Bullish" ? color.lime : structure == "Bearish" ? color.red : color.gray
        table.cell(infoTable, 1, 1, structure, text_color=structColor, bgcolor=color.new(color.gray, 85))
        
        // Market Type
        table.cell(infoTable, 0, 2, "Market Type", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 2, marketType, text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // Next Trade
        table.cell(infoTable, 0, 3, "Next Trade", text_color=color.white, bgcolor=color.new(color.gray, 70))
        nextColor = nextTradeType == "LONG" ? color.lime : nextTradeType == "SHORT" ? color.fuchsia : color.gray
        table.cell(infoTable, 1, 3, nextTradeType, text_color=nextColor, bgcolor=color.new(color.gray, 85), text_size=size.normal)
        
        // Reason
        table.cell(infoTable, 0, 4, "Reason", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 4, nextReason, text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // ADX
        table.cell(infoTable, 0, 5, "ADX", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 5, str.tostring(adxValue, "#.#"), text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // ATR
        table.cell(infoTable, 0, 6, "ATR", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 6, str.tostring(atr, format.mintick), text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // Risk
        table.cell(infoTable, 0, 7, "Risk/Trade", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 7, str.tostring(riskPercent, "#.#") + "%", text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // Daily Trades
        table.cell(infoTable, 0, 8, "Daily Trades", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 8, str.tostring(dailyTrades) + "/" + str.tostring(maxDailyTrades), text_color=color.white, bgcolor=color.new(color.gray, 85))
        
        // Auto Trade Status
        table.cell(infoTable, 0, 9, "Auto Trade", text_color=color.white, bgcolor=color.new(color.gray, 70))
        table.cell(infoTable, 1, 9, autoTrade ? "✓ ON" : "✗ OFF", text_color=autoTrade ? color.lime : color.red, bgcolor=color.new(color.gray, 85))
        
        //