Indicator · Pine Script v6 · On the chart

Luxy BIG beautiful Dynamic ORB

by theonetrade

This indicator calculates and plots multi-stage Opening Range Breakout high, low, and mid-range levels for 5, 15, 30, and 60 minute intervals on the price chart.

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code3,217
Settings40inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

3,217 lines of Pine Script v6 from assets/indicator/bit-exact/luxy_big_beautiful_dynamic_orb_AZUUpYlW.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

luxy_big_beautiful_dynamic_orb_AZUUpYlW.pine
//@version=6 
indicator("Luxy BIG beautiful Dynamic ORB - v5", shorttitle = "Luxy Big Beautiful ORB", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=300)


// ====================================== DISCLAIMER & INFO =========================================
//
// DISCLAIMER: This indicator is for educational and informational purposes only.
// It does not constitute financial advice. Trading involves substantial risk of loss.
// Past performance does not guarantee future results. Always do your own research.
//
// DESCRIPTION:
// Dynamic Opening Range Breakout (ORB) indicator with multi-stage ranges (5/15/30/60 min).
// Identifies breakouts, retests, and failed breaks with advanced filtering options.
// Includes position sizing, risk management, and higher timeframe bias analysis.
//
// FEATURES:
// • Multi-stage ORB levels (5, 15, 30, 60 minutes)
// • Breakout and retest detection with cycle counting
// • Volume, trend, and HTF bias filters
// • Position sizing with risk management
// • Target/stop-loss visualization
// • Real-time dashboard with trade parameters
//
// BEST PRACTICES: 
// • Recommended for liquid stocks with >1M daily volume
// • Best on 5-minute charts during regular trading hours
// • Paper trade first to understand the signals
// • Use with proper risk management (1-2% risk per trade)
// • Combine with overall market analysis
//
// LIMITATIONS:
// • May produce dangerous signals in choppy/ranging markets
// • Requires clean data feed for accurate ORB calculation
// • Not suitable for all market conditions
// • Performance varies by instrument and timeframe
//
// CREDITS:
// • Based on Opening Range Breakout concepts by Mark Fisher
// • Enhanced with modern technical analysis techniques
// • Original implementation by OrenLuxy 
//

// =========================================== TYPE DEFINITIONS ======================================

type ORBData
    string name          
    int    minutes       
    float  high         
    float  low          
    float  mid          
    float  orbRange     
    bool   isEnabled     
    bool   isBuilding    
    bool   isComplete    
    int    completionBar 
    bool   breakoutUp    
    bool   breakoutDown  
    int    breakoutBar   
    float  breakoutLevel 
    int    cyclesUp      
    int    cyclesDown    
    box    orbBox        
    line   highLine      
    line   lowLine       
    line   midLine       
    label  edgeLabel     
    color  orbColor      
    int    lineWidth     
    string lineStyle     

// ================================================ GROUPS ===========================================

grp_colors   = "🎨 ORB COLORS ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_session  = "⏰ SESSION SETTINGS ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_breakout = "⚡ BREAKOUT DETECTION ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_targets  = "🎯 TARGETS & RISK ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_FVG      = "↩️ FVG FILTER ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_lines    = "📍 TP/SL LINES ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_pullback = "↩️ PULLBACK FILTER ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_volume   = "📊 VOLUME FILTER ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_trend    = "📈 TREND FILTER ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_dash     = "📊 DASHBOARD ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_htf      = "📈 HIGHER TIMEFRAME ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"
grp_god      = "⚡ GOD MODE ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬"

// ============================================ CONSTANTS ============================================

LABEL_OFFSET_ATR_MULTIPLIER = 0.8  // 0.8× ATR distance from high/low
LABEL_OFFSET_BARS = 2              // Bars ahead for edge labels (keeps them visible)

MAX_BARS_FAILED_BREAK = 5  // Maximum bars to consider a retest as "failed break" instead of committed breakout
showEdgeLabels = input.bool(true, "Show Edge Labels", inline = "core", group=grp_colors)
labelFormat = input.string("Detailed", "Label Format", options=["Simple", "Detailed"], group=grp_colors, inline="core1")
labelSize = input.string("Small", "All Label Size", inline = "core1", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grp_colors, tooltip="Display ORB stage labels at the edge of price levels\n\nShows which ORB period is active (5min/15min/30min/60min)\nLabels follow price as chart scrolls\n\nON = Labels visible\nOFF = Clean chart\n\nVisual size for ALL labels (breakout, retest, failed)\n\nTINY: Minimal space, cluttered on small screens\nSMALL: Clean and readable (recommended)\nNORMAL: Good for presentations\nLARGE: High visibility\nHUGE: Maximum visibility\n\nLabel text format for ALL labels (TP/SL and Breakouts)\n\nSIMPLE:\n• Minimal text\n• TP/SL: 'ENTRY', 'TP1', 'SL'\n• Breakout: '🔼 BREAKOUT UP #1'\n• Clean and compact\n• Good for: Small screens, many lines\n\nDETAILED:\n• Full info with context\n• TP/SL: 'ENTRY: $150.50', 'TP1: $152.20 +1.1%'\n• Breakout: 'ORB15 | #1 | Vol: 2.3x'\n• Shows prices, percentages, ORB stage, volume\n• Good for: Analysis, larger screens (recommended) ⭐\n\nAFTER HIT:\n• TP: '✅ TP1: $152.20'\n• SL: '❌ SL: $148.50'")
showBG = input.bool(true, "Show Background", inline="BG", group=grp_colors)
fillTransparency = input.int(95, "  | Transparency", inline="BG", minval=0, maxval=100, step=5, group=grp_colors, tooltip="Background fill transparency for ORB range\n\n0 = Fully opaque (solid color)\n50 = Semi-transparent\n95 = Nearly invisible (recommended)\n100 = Completely invisible")
enableORB5Signals = input.bool(true, "Enable ORB 5", group=grp_colors, inline="5-15", tooltip="Enable/Disable ORB stages\n\nORB 5: First 5 minutes - fastest signals, most noise\nORB 15: First 15 minutes - balanced signals\nORB 30: First 30 minutes - slower, more reliable\nORB 60: First 60 minutes - slowest, most confirmed\n\nDisable stages you don't want to trade")
orb5LineColor = input.color(color.yellow, "", inline = "5-15",  group=grp_colors)
enableORB15Signals = input.bool(true, "Enable ORB15", group=grp_colors, inline="5-15")
orb15LineColor = input.color(color.green, "", inline = "5-15",group=grp_colors) 
enableORB30Signals = input.bool(true, "Enable ORB30", group=grp_colors, inline="30-60")
orb30LineColor = input.color(color.blue, "", inline = "30-60", group=grp_colors)
enableORB60Signals = input.bool(true, "Enable ORB60", group=grp_colors, inline="30-60")
orb60LineColor = input.color(color.purple, "", inline = "30-60", group=grp_colors)
showMidLine = input.bool(true, "Mid-Range Line", group=grp_colors, tooltip="Display a thin line at the midpoint between ORB High and Low\n\nUSEFUL FOR:\n• Visual center reference\n• Mean reversion trading\n• Support/resistance level\n• Range symmetry analysis\n\nThe line uses the same color as the ORB boundaries but thinner\n\nON = Midpoint line visible\nOFF = Only High/Low lines")

sessionMode = input.string("Auto-Detect", "Session Mode", options=["Auto-Detect", "Custom"], group=grp_session, tooltip="Define trading session for ORB calculation\n\n🎯 AUTO-DETECT (Recommended):\n• TradingView automatically detects symbol's native hours\n• Stocks: Exchange hours (NYSE 9:30-16:00, LSE 8:00-16:30, etc.)\n• E-mini Futures: See 'Futures Trading Hours' setting below\n• Crypto: 24/7\n• Forex: Native forex session\n• Works perfectly for 99% of cases!\n\n⚙️ CUSTOM:\n• Define your own session hours manually\n• Use format: HHMM-HHMM (e.g., '0930-1600')\n• Set in 'Custom Session Hours' below\n• Timezone: Chart timezone\n\n💡 TIP: Auto-Detect handles timezone/DST automatically!\nIf ORB appears 1 hour off, check chart timezone:\nRight-click chart → Settings → Symbol → Timezone")
customSession = input.session("0930-1600", "Custom Session Hours", group=grp_session, tooltip="Custom trading session definition\n\nONLY ACTIVE when Session Mode = Custom\n\nFORMAT: HHMM-HHMM (24-hour)\n\nEXAMPLES:\n• 0930-1600 = NYSE regular hours\n• 0400-2000 = Extended trading\n• 0000-2359 = Full 24 hours\n\nTIMEZONE: Chart timezone")

enableExtendedHours = input.bool(false, "Include Extended Hours", group=grp_session, inline="ext1", tooltip="Include pre-market and after-hours trading\n\n🌅 PRE-MARKET: 04:00-09:30 EST\n🌆 REGULAR: 09:30-16:00 EST\n🌃 AFTER-HOURS: 16:00-20:00 EST\n\nWhen ENABLED:\n• ORB tracking works 04:00-20:00\n• Dashboard shows 'OPEN' during extended hours\n• Breakouts detected in extended hours\n\nWhen DISABLED:\n• ORB tracking only 09:30-16:00 (regular)\n• Dashboard shows 'CLOSED' outside regular hours\n\nRECOMMENDED: Enable if you trade extended hours")
extendedPreMarket = input.session("0400-0930", "Pre-Market", group=grp_session, inline="ext2", tooltip="Pre-market trading hours\n\nDEFAULT: 04:00-09:30 (NYSE)\n\nDefine the pre-market session window.\nOnly the START time (04:00) is used for extended hours calculation.")
extendedAfterHours = input.session("1600-2000", "After-Hours", group=grp_session, inline="ext3", tooltip="After-hours trading session\n\nDEFAULT: 16:00-20:00 (NYSE)\n\nDefine the after-hours session window.\nOnly the END time (20:00) is used for extended hours calculation.")

futuresTradingHours = input.string("Auto-Detect", "Futures Trading Hours", options=["Auto-Detect", "RTH Only (9:30-16:00)", "Electronic Full Day (24hr)"],  group=grp_session, tooltip="Control how ORB tracks E-mini futures (ES, NQ, RTY, YM)\n\n🔹 RTH ONLY (9:30-16:00):\n• ORB resets at 9:30 AM ET\n• Tracking ends at 4:00 PM ET\n• Total: 6.5 hours\n• Best for: Day traders focusing on regular session\n\n🔹 ELECTRONIC FULL DAY (24hr):\n• ORB resets at 9:30 AM ET daily\n• Tracking continues 24 hours until next 9:30 AM\n• Covers full Globex session (18:00-17:00)\n• Best for: Swing traders, overnight positions\n\n🔹 AUTO-DETECT (recommended):\n• Checks for volume outside RTH hours\n• If volume detected → Electronic mode\n• If no volume → RTH mode\n• Adapts automatically to your trading style\n\nNOTE: This setting only affects E-mini futures.\nStocks use 'Extended Hours' setting above.")

string tradingSession = "0930-1600:23456"  // Default: NYSE hours, Mon-Fri
string sessionTimezone = syminfo.timezone  // Default: use symbol's native timezone
var int sessionStartHour = na
var int sessionStartMinute = na
var int sessionEndHour = na
var int sessionEndMinute = na
bool useElectronicFullDay = false  // Track if E-mini futures using Electronic Full Day mode (24hr from 9:30-9:30)

if sessionMode == "Auto-Detect"
    // Use native session detection for all asset types
    // TradingView automatically handles timezone and session hours
    if syminfo.type == "futures"
        // Futures: use native session (E-mini override below)
        tradingSession := ""
    else if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf"
        if enableExtendedHours
            string preMarketStart = str.split(extendedPreMarket, "-").get(0)
            string afterHoursEnd = str.split(extendedAfterHours, "-").get(1)
            tradingSession := preMarketStart + "-" + afterHoursEnd + ":23456"
        else
            // Use NATIVE session - TradingView knows the correct hours and timezone!
            tradingSession := ""
    else if syminfo.type == "crypto"
        // Use native 24/7 session
        tradingSession := ""
    else if syminfo.type == "forex"
        // Use native forex session
        tradingSession := ""
    else
        // Use native session for other assets
        tradingSession := ""
    // Parse session string to extract hours and minutes

else if sessionMode == "Custom"
    if str.contains(customSession, ":")
        tradingSession := customSession
    else
        tradingSession := customSession + ":23456"

// Only parse session string if it's not empty (native session uses empty string)
if tradingSession != ""
    string sessionTimeOnly = str.contains(tradingSession, ":") ? str.split(tradingSession, ":").get(0) : tradingSession
    array<string> sessionParts = str.split(sessionTimeOnly, "-")

    if array.size(sessionParts) == 2
        string startTime = array.get(sessionParts, 0)
        string endTime = array.get(sessionParts, 1)

        if str.length(startTime) == 4
            sessionStartHour := int(str.tonumber(str.substring(startTime, 0, 2)))
            sessionStartMinute := int(str.tonumber(str.substring(startTime, 2, 4)))

        if str.length(endTime) == 4
            sessionEndHour := int(str.tonumber(str.substring(endTime, 0, 2)))
            sessionEndMinute := int(str.tonumber(str.substring(endTime, 2, 4)))

// ========================================================================================
// E-MINI FUTURES GLOBAL OVERRIDE
// ========================================================================================
// This section ensures 'Futures Trading Hours' setting works REGARDLESS of Session Mode
// ONLY affects: ES, NQ, RTY, YM (E-mini futures)
// All other assets (stocks, crypto, forex, commodities): NOT affected
// ========================================================================================
if syminfo.type == "futures"
    if str.contains(syminfo.ticker, "ES") or str.contains(syminfo.ticker, "NQ") or str.contains(syminfo.ticker, "RTY") or str.contains(syminfo.ticker, "YM")
        // CME E-mini futures: Electronic hours 18:00-17:00 CT (23 hours with 1-hour break)
        // RTH (Regular Trading Hours): 09:30-16:00 ET
        sessionTimezone := "America/New_York"  // Always use ET timezone for E-minis

        // Determine which mode to use based on futuresTradingHours setting
        if futuresTradingHours == "Electronic Full Day (24hr)"
            // Electronic Full Day: ORB resets at 9:30 AM ET, tracks 24 hours until next 9:30 AM
            tradingSession := ""  // Use native 24/7 session
            useElectronicFullDay := true
        else if futuresTradingHours == "RTH Only (9:30-16:00)"
            // RTH Only: Standard trading hours 9:30 AM - 4:00 PM ET, Monday-Friday
            tradingSession := "0930-1600:23456"  // Mon-Fri (fixed from 12345)
            useElectronicFullDay := false
        else  // Auto-Detect
            // Auto-detect: Check if there's volume outside RTH hours
            // If trading detected before 9:30 AM or after 4:00 PM → Electronic mode
            int currentHour = hour(time, sessionTimezone)
            int currentMinute = minute(time, sessionTimezone)
            bool outsideRTH = (currentHour < 9 or (currentHour == 9 and currentMinute < 30) or currentHour >= 16)
            bool hasVolumeOutsideRTH = outsideRTH and volume > 0

            if hasVolumeOutsideRTH
                // Electronic mode detected
                tradingSession := ""
                useElectronicFullDay := true
            else
                // RTH mode (default)
                tradingSession := "0930-1600:23456"  // Mon-Fri (fixed from 12345)
                useElectronicFullDay := false

// ========================================================================================

enableBreakout = input.bool(true, "Enable Breakout Detection", inline = "Show", group=grp_breakout)
showBreakLabels = input.bool(true, "Show Breakout Labels", group=grp_breakout, inline = "Show", tooltip="Detect and label breakouts above ORB High or below ORB Low\n\nON: Shows breakout labels when price exits ORB range\nOFF: Only displays ORB levels without signals\n\nBreakouts detected on CLOSE (no repaint)")
enableRetest = input.bool(true, "Show Retest Labels", group=grp_breakout, inline="retest", tooltip="Show labels when price returns to ORB after breakout\n\nRETEST = Price broke out, then came back to test ORB level\n\nUSEFUL FOR:\n• Re-entry opportunities\n• Confirming support/resistance\n• Failed breakout detection\n\nON: Shows retest labels\nOFF: Only shows initial breakout")
signalMode = input.string("Track Cycles", "Signal Mode", options=["First Only", "Track Cycles"], group=grp_breakout, inline="mode", tooltip="How many breakout signals to show per day\n\nFIRST ONLY:\n• Shows only the FIRST breakout in each direction\n• One UP signal, one DOWN signal max per day\n• Clean chart, less noise\n• Good for: Swing traders, position traders\n\nTRACK CYCLES:\n• Tracks Breakout → Retest → Re-breakout cycles\n• Multiple signals as price oscillates\n• Detects momentum returns\n• Good for: Active traders, scalpers\n\nRECOMMENDED: Track Cycles")
maxCycles = input.int(6, "Max Cycles", minval=1, maxval=10, group=grp_breakout, inline="mode", tooltip="Maximum cycles to track when Signal Mode = Track Cycles\n\nCYCLE = Breakout → Retest → Re-breakout sequence\n\n1-2 cycles: Clean chart, fewer signals\n4-6 cycles: Balanced (recommended)\n8-10 cycles: Very active, may clutter chart\n\nIGNORED when Signal Mode = First Only")
breakoutBuffer = input.float(0.2, "Breakout Buffer (%)", minval=0, maxval=5, step=0.1, group=grp_breakout, inline="buffer", tooltip="Extra distance required beyond ORB level for breakout\n\nPREVENTS: False breakouts from tiny penetrations\n\nHOW IT WORKS:\n• UP: Price must close ABOVE (ORB High + buffer%)\n• DOWN: Price must close BELOW (ORB Low - buffer%)\n\nRECOMMENDATIONS:\n• 0.0% = Exact level (sensitive, more signals)\n• 0.1% = Tiny buffer (recommended)\n• 0.3% = Moderate filter\n• 0.5%+ = Conservative (fewer signals)\n\nHigher = fewer but stronger breakouts")
retestBuffer = input.float(0.0, "Retest Buffer (%)", minval=0, maxval=5, step=0.1, group=grp_breakout, inline="buffer", tooltip="Tolerance for retest detection\n\nALLOWS: Price to slightly penetrate ORB during retest\n\nHOW IT WORKS:\n• After UP breakout: Retest if price returns to ORB High ± buffer\n• After DOWN breakout: Retest if price returns to ORB Low ± buffer\n\nRECOMMENDATIONS:\n• 0.0% = Must touch exact level (strict)\n• 0.1-0.2% = Slight tolerance (recommended)\n• 0.3-0.5% = Generous tolerance\n\nHigher = more retests detected")
minRetestDistancePct = input.float(0.5, "Min Distance for Retest (%)", minval=0.5, maxval=10, step=0.5, group=grp_breakout, tooltip="How far price must travel away from ORB before retest is valid\n\nPREVENTS: Labeling tiny bounces as 'retests'\n\nEXAMPLE: ORB High = $10.00, Distance = 2%\n• Price breaks to $10.20 (2% away) ✓ Valid\n• Price returns to $10.00 → RETEST LABEL\n• If only went to $10.05 (0.5% away) ✗ Not valid\n\nRECOMMENDATIONS:\n• 0.5% = Very sensitive (many retests)\n• 2.0% = Balanced (filters noise) ⭐\n• 3.0%+ = Only strong moves\n\nHigher = fewer but more meaningful retests")
minBarsOutside = input.int(2, "Min Bars Outside ORB", minval=1, maxval=10, group=grp_breakout, tooltip="How many bars price must stay outside ORB for 'committed' breakout\n\nPREVENTS: Labeling quick failures as breakouts\n\nEXAMPLE: Min Bars = 2\n• Bar 1: Price breaks above ORB High\n• Bar 2: Still above ORB High ✓\n• Bar 3: Returns inside → Now can show retest\n\nIf returned on Bar 2 → Shows 'FAILED BREAK' instead\n\nRECOMMENDATIONS:\n• 1 bar = Aggressive (more signals, more failures)\n• 2 bars = Balanced (recommended) ⭐\n• 3-4 bars = Conservative (only strong moves)\n\nHigher = fewer but stronger breakouts")
minPullbackPct = input.float(0.3, "Min Pullback for Re-break (%)", minval=0.1, maxval=2, step=0.1, group=grp_breakout, tooltip="How far price must pull back before detecting new breakout\n\nPREVENTS: Too many signals from small wiggles\n\nEXAMPLE: Last breakout at $10.00\n• Price reaches $10.50\n• Must pull back to $10.35 (0.3% = $0.15) before new breakout counted\n\nRECOMMENDED:\n• 0.3% = Balanced (recommended) ⭐\n• 0.5% = Less sensitive\n• 1.0% = Very selective")

enableFVGFilter = input.bool(false, "Enable FVG Filter  | ", group=grp_FVG, inline="fvg1")
showFVG = input.bool(true, "Show FVG Boxes", group=grp_FVG, inline="fvg1", tooltip="Fair Value Gap Filter\n\nRequires breakout through FVG for confirmation\n\nFVG = Price gap from strong momentum\nON: Only signals with FVG\nOFF: All signals")
maxFVGtoKeep = input.int(5, "Max FVG", minval=1, maxval=20, inline="fvg2", group=grp_FVG)
fvgProximity = input.float(2.0, "FVG Proximity", minval=0.5, maxval=5.0, inline="fvg2", step=0.5, group=grp_FVG, tooltip="How close to FVG?\n\n1.0 = Must be IN the FVG\n2.0 = Within 2x FVG size (recommended)\n3.0 = Within 3x FVG size (very permissive)")
fvgTransparency = input.int(90, "Transparency", minval=0, maxval=100, step=5, inline="fvgcolor", group=grp_FVG)
fvgBullColor = input.color(color.green, "Bullish FVG", inline="fvgcolor", group=grp_FVG)
fvgBearColor = input.color(color.orange, "Bearish FVG", inline="fvgcolor", group=grp_FVG)

enablePullbackFilter = input.bool(false, "Enable Pullback Filter", group=grp_pullback, tooltip="Require pullback confirmation before showing breakout signal\n\nWHY: Filters weak breakouts that reverse immediately\nHOW: Waits for price to pull back slightly, then continue breakout direction\n\nWORKFLOW:\n1. Price breaks above/below ORB\n2. Wait for pullback (small dip/rise)\n3. Price continues in breakout direction\n4. NOW show signal ✅\n\nBENEFITS:\n• Better entry prices\n• Fewer false breakouts\n• Improved risk/reward\n• Confirmation of strength\n\nDRAWBACKS:\n• Misses fast runners\n• Slower signals\n• More conservative\n\nON: Wait for pullback confirmation\nOFF: Immediate signals (current behavior)\n\nRECOMMENDED: Try OFF first, enable if too many false signals")
pullbackPercent = input.float(0.3, "Pullback Required (%)", minval=0.1, maxval=2.0, step=0.1, group=grp_pullback, inline="pb", tooltip="How much pullback required for confirmation\n\nEXAMPLE: ORB High = $100, Pullback = 0.5%\n• Breaks to $100.60 (above ORB)\n• Pulls back to $100.10 (0.5% dip) ✓\n• Continues to $100.70 → SIGNAL!\n\nSMALLER % = More signals, faster\nLARGER % = Fewer signals, stronger\n\nRECOMMENDED:\n• 0.3% = Sensitive (active trading) ⭐\n• 0.5% = Balanced\n• 1.0% = Conservative (swing trading)")
pullbackTimeout = input.int(10, "Timeout (bars)", minval=3, maxval=30, group=grp_pullback, inline="pb", tooltip="Max bars to wait for pullback\n\nIf pullback doesn't happen within this time:\n→ Shows signal anyway (prevents missing strong moves)\n\nEXAMPLE: Timeout = 10 bars\n• Breakout occurs\n• Wait 10 bars for pullback\n• No pullback? → Show signal at bar 10\n• Pullback at bar 5? → Show signal when continues\n\nSHORTER = Less waiting, more immediate signals\nLONGER = More patient, better confirmation\n\nRECOMMENDED:\n• 5 bars = Quick (5min chart = 25 min)\n• 10 bars = Balanced (5min chart = 50 min) ⭐\n• 15 bars = Patient (5min chart = 75 min)")

enableVolumeFilter = input.bool(false, "Enable Volume Filter", group=grp_volume, inline="enable", tooltip="Require volume confirmation for breakout signals\n\nWHY: High volume breakouts are more reliable\nWHAT: Compares current volume to moving average\n\nON: Only shows breakouts with sufficient volume\nOFF: Shows all breakouts regardless of volume\n\nRECOMMENDED: ON for stocks, OFF for crypto")
volumeMaLength = input.int(20, "| MA Length", minval=1, group=grp_volume, inline="enable", tooltip="Volume moving average period for comparison\n\nSHORTER = More sensitive to recent volume spikes\nLONGER = Smoother average, less reactive\n\nRECOMMENDATIONS:\n• 10 periods: Very responsive\n• 20 periods: Balanced (recommended) ⭐\n• 50 periods: Long-term average\n\nCHART TIMEFRAME affects calculation:\n• 5min chart, MA=20 → Last 100 minutes\n• 1hour chart, MA=20 → Last 20 hours")
volumeMultiplier = input.float(1.5, "Min Volume ×", minval=0.5, step=0.1, group=grp_volume, inline="mult", tooltip="Minimum volume multiplier required for breakout\n\nCURRENT VOLUME must be ≥ (Volume MA × Multiplier)\n\nEXAMPLE: Volume MA = 1M shares, Multiplier = 1.5\n• Breakout with 1.6M volume ✓ Valid\n• Breakout with 1.2M volume ✗ Rejected\n\nRECOMMENDATIONS:\n• 1.0× = Any above-average volume\n• 1.5× = Moderate requirement (recommended) ⭐\n• 2.0× = Strong requirement (fewer signals)\n• 2.5×+ = Very selective\n\nHigher = fewer but higher-quality signals")
strongVolumeMultiplier = input.float(2.0, "Strong ×", minval=1.0, step=0.1, group=grp_volume, inline="mult", tooltip="Strong volume override threshold\n\nSPECIAL RULE: If volume exceeds this multiplier:\n→ BYPASSES all other filters (trend, etc.)\n→ Shows breakout immediately\n\nRATIONALE: Massive volume = institutional activity\n\nEXAMPLE: Volume MA = 1M, Strong = 2.0×\n• Breakout with 2.5M volume → Shows even if trend filter says NO\n\nRECOMMENDATIONS:\n• 2.0× = Balanced (recommended) ⭐\n• 2.5× = More selective\n• 3.0× = Only exceptional volume\n\nMUST BE ≥ Min Volume Multiplier")

// Trend Filter
enableTrendFilter = input.bool(false, "Enable Trend Filter", group=grp_trend, inline = "FILTER", tooltip="Only show breakouts that align with broader trend\n\nWHY: Trend-aligned breakouts have higher success rate\nWHAT: Checks if price is above/below trend indicator\n\nRULES:\n• UP breakout: Only if price ABOVE trend\n• DOWN breakout: Only if price BELOW trend\n\nON: Filters against-trend breakouts\nOFF: Shows all breakouts\n\nRECOMMENDED: ON for conservative trading")
trendMode = input.string("VWAP", "| Trend Mode",inline = "FILTER", options=["VWAP", "EMA", "Custom EMA", "SuperTrend", "VWAP+EMA", "VWAP+SuperTrend"], group=grp_trend, tooltip="Method to determine trend direction\n\nVWAP (Volume-Weighted Average Price):\n• Accounts for volume in price calculation\n• Good for: Intraday trading\n• Above VWAP = Bullish, Below = Bearish\n\nEMA (12-period):\n• Fast exponential moving average\n• Responsive to recent price action\n• Good for: Quick trends\n\nCUSTOM EMA:\n• Your own EMA period\n• Longer = Smoother trend\n• Good for: Swing trading (50-200 period)\n\nSUPERTREND:\n• ATR-based trailing stop\n• Clear trend direction\n• Good for: Strong trends\n\nVWAP+EMA:\n• BOTH must agree\n• More conservative\n• Fewer but higher quality signals\n\nVWAP+SUPERTREND:\n• BOTH must agree\n• Most conservative\n• Best signal quality")

customEmaLength = input.int(50, "Custom EMA Length", minval=1, group=grp_trend, inline="ema", tooltip="EMA period when Trend Mode = Custom EMA\n\nSHORTER = More reactive, more signals\nLONGER = Smoother, fewer signals\n\nRECOMMENDATIONS:\n• 20-30: Intraday trading\n• 50: Swing trading (recommended) ⭐\n• 100-200: Position trading\n\nIGNORED for other trend modes")
supertrendPeriod = input.int(10, "SuperTrend Period", minval=1, group=grp_trend, inline="st", tooltip="ATR period for SuperTrend calculation\n\nSHORTER = More sensitive, tighter stops\nLONGER = Smoother, wider stops\n\nRECOMMENDATIONS:\n• 7: Aggressive\n• 10: Balanced (recommended) ⭐\n• 14: Conservative\n\nONLY USED when Trend Mode includes SuperTrend")
supertrendMult = input.float(3.0, "Mult", minval=0.1, step=0.1, group=grp_trend, inline="st", tooltip="ATR multiplier for SuperTrend bands\n\nLOWER = Tighter bands, more trend changes\nHIGHER = Wider bands, fewer changes\n\nRECOMMENDATIONS:\n• 2.0: Sensitive (more signals)\n• 3.0: Balanced (recommended) ⭐\n• 4.0+: Conservative (fewer signals)\n\nONLY USED when Trend Mode includes SuperTrend")

// ========================================= TARGETS & RISK MANAGEMENT ================================
enableTargets = input.bool(true, "Enable Targets & Stop-Loss", group=grp_targets, tooltip="Calculate and display profit targets (TP) and stop-loss (SL)\n\nWHEN ENABLED:\n• Shows TP/SL lines on chart during breakout\n• Displays values in dashboard\n• Calculates Risk/Reward ratio\n\nWHEN DISABLED:\n• Only shows ORB levels\n• No trade management\n\nRECOMMENDED: ON for active trading")

showTP1 = input.bool(true, "TP1 (1R)", group=grp_targets, inline="show")
showTP1_5 = input.bool(false, "TP1.5 (1.5R)", group=grp_targets, inline="show")
showTP2 = input.bool(true, "TP2 (2R)", group=grp_targets, inline="show")
showTP3 = input.bool(false, "TP3 (3R)", group=grp_targets, inline="show", tooltip="Select which Take Profit levels to display\n\nR = RISK UNITS (1R = distance from entry to stop-loss)\n\nTP1 (1R): Conservative target, 1:1 risk/reward\nTP1.5 (1.5R): Intermediate target\nTP2 (2R): Balanced target, 2:1 risk/reward\nTP3 (3R): Aggressive target, 3:1 risk/reward\n\nRECOMMENDED COMBINATIONS:\n• Scalping: TP1 + TP1.5\n• Day Trading: TP1 + TP2 ⭐\n• Swing Trading: TP1 + TP2 + TP3\n\nLines and labels stop updating when last enabled TP is hit")

stopMode = input.string("ATR", "Stop Method", options=["ATR", "ORB %", "Swing", "Safer", "Scaled ATR", "% Based", "Smart Adaptive"], group=grp_targets, inline="tgt", tooltip="How to calculate Stop Loss placement\n\n🆕 ATR-BASED VOLATILITY SYSTEM:\n\nSMART ADAPTIVE (Recommended) ⭐:\n• Adjusts to ACTUAL volatility (not price)\n• ATR < 1.5% = Tight stop (0.7× ATR)\n• ATR 1.5-3% = Normal stop (1.0× ATR)\n• ATR > 3% = Wide stop (1.5× ATR)\n• Perfect for: ALL assets automatically\n\nSCALED ATR:\n• Dynamic multiplier based on volatility %\n• Very volatile (>5% ATR): 2.5× ATR\n• High volatility (3-5%): 2.0× ATR\n• Normal (1.5-3%): 1.5× ATR\n• Low (<1.5%): 1.2× ATR\n• Good for: Mixed portfolios\n\nATR:\n• Standard ATR with volatility adjustment\n• Multiplier adjusts to market conditions\n• Formula: SL = Entry ± (ATR × Multiplier × VolAdjust)\n• Good for: Traditional traders\n\n% BASED:\n• Fixed percentage from entry\n• You set the % (e.g., 1.0%)\n• Simple and consistent\n• Good for: Beginners\n\n────────────────────────\n\n🔥 NEW VOLATILITY PROTECTION:\n\nALL METHODS NOW USE ATR-BASED MINIMUMS:\n• Crypto: Min 1.0× ATR (wider for volatility)\n• Forex: Min 0.3× ATR (tighter for stability)\n• Stocks: Min 0.5-1.5× ATR (based on volatility)\n\nABSOLUTE MINIMUMS:\n• Crypto: 1.0% of price\n• Forex: 0.2% of price\n• Stocks: 0.3% of price\n\n────────────────────────\n\nORB %:\n• Fixed percentage beyond ORB level\n• Simple and predictable\n• Formula: SL = ORB_Level ± (ORB_Range × %)\n• Good for: ORB-focused trading\n\nSWING:\n• Placed at recent swing high/low\n• Technical support/resistance\n• Respects chart structure\n• May be far from entry\n• Good for: Technical traders\n\nSAFER:\n• Widest stop of all methods\n• Lowest chance of stop-out\n• Largest potential loss\n• Good for: Risk-averse traders")
atrLength = input.int(14, "ATR", minval=5, maxval=50, group=grp_targets, inline="atr2", tooltip="ATR calculation period\n\nATR = Average True Range = How much price moves\n\nSHORTER = More reactive to recent volatility\nLONGER = Smoother, stable average\n\nRECOMMENDATIONS:\n• 7-10: Day trading, responsive\n• 14: Standard, balanced (recommended) ⭐\n• 20-30: Swing trading, smooth\n\nUSED FOR: ATR-based targets and stops")
atrMultiplier = input.float(1.5, "×", minval=0.5, maxval=3, step=0.1, group=grp_targets, inline="atr2", tooltip="ATR multiplier for stop-loss distance\n\nSL = Entry ± (ATR × Multiplier)\n\nLOWER = Tighter stop, less risk, more stop-outs\nHIGHER = Wider stop, more risk, fewer stop-outs\n\nRECOMMENDATIONS:\n• 1.0×: Tight stop (aggressive)\n• 1.5×: Balanced (recommended) ⭐\n• 2.0×: Loose stop (conservative)\n• 2.5×+: Very loose (volatile stocks)\n\nONLY AFFECTS: ATR stop method")
percentBasedStop = input.float(1.0, "% Based Stop", minval=0.1, maxval=5.0, step=0.1, group=grp_targets, inline="pct", tooltip="Stop Loss percentage from entry\n\nONLY USED when Stop Method = % Based\n\nFORMULA:\n• LONG: SL = Entry × (1 - Stop%)\n• SHORT: SL = Entry × (1 + Stop%)\n\nEXAMPLE: Entry = $100, Stop = 1.0%\n• LONG SL: $99.00 (1% below)\n• SHORT SL: $101.00 (1% above)\n\nRECOMMENDATIONS:\n• 0.5%: Tight (day trading, scalping)\n• 1.0%: Balanced (recommended) ⭐\n• 1.5%: Medium (swing trading)\n• 2.0%+: Wide (position trading)\n\nPERFECT FOR:\n• High-price assets (BTC, TSLA)\n• Consistent risk management\n• Easy to understand")
stopOrbFraction = input.float(20, "ORB Stop %", minval=10, maxval=50, step=5, group=grp_targets, inline="stop", tooltip="Stop distance as percentage of ORB range\n\nONLY USED when Stop Method = ORB %\n\nFORMULA:\n• LONG: SL = ORB_Low - (ORB_Range × 20%)\n• SHORT: SL = ORB_High + (ORB_Range × 20%)\n\nEXAMPLE: ORB Range = $1.00, Fraction = 20%\n• SL placed $0.20 beyond ORB boundary\n\nRECOMMENDATIONS:\n• 10-15%: Tight (more stop-outs)\n• 20%: Balanced (recommended) ⭐\n• 30-40%: Loose (fewer stop-outs)\n• 50%: Very loose")
swingBars = input.int(3, "Swing Bars", minval=1, maxval=10, group=grp_targets, inline="stop", tooltip="Lookback period to find swing high/low\n\nONLY USED when Stop Method = Swing\n\nSWING = Local high/low point (reversal point)\n\nSHORTER = Recent swing (closer SL)\nLONGER = Deeper swing (farther SL)\n\nEXAMPLE: Swing Bars = 3\n• Looks back 3 bars\n• Finds lowest low (for LONG) or highest high (for SHORT)\n• Places SL there\n\nRECOMMENDATIONS:\n• 2: Very recent swing (aggressive)\n• 3: Recent swing (recommended) ⭐\n• 5: Moderate swing\n• 7-10: Deep swing (conservative)")
showTPSLLines = input.bool(true, "Show TP/SL Lines on Chart", group=grp_lines, tooltip="Display Entry, TP, and SL as horizontal lines on chart\n\nWHEN BREAKOUT OCCURS:\n• Lines appear instantly\n• Extend forward as chart progresses\n• Update with each new bar\n\nLINES FREEZE (stop updating) when:\n• Last TP is hit ✓\n• Stop Loss is hit ✗\n• End of Day (if enabled)\n\nCOLORS:\n• Entry: Cyan (LONG) / Orange (SHORT)\n• TP: Green when hit, cyan/orange before\n• SL: Red always\n\nON: Shows lines (recommended)\nOFF: Only dashboard display")
freezeOnEOD = input.bool(true, "Freeze Lines at End of Day", group=grp_lines, inline="freeze", tooltip="Stop updating lines when trading session ends\n\nON (Recommended):\n• Lines freeze at session close\n• Keeps intraday setup visible\n• Clean daily reset\n• Good for: ORB strategy (intraday)\n\nOFF:\n• Lines continue extending until hit\n• May cross multiple sessions\n• Good for: Swing trading, 24/7 markets\n\nNOTE: Lines also freeze when SL hit or last TP hit")

// ============================================ DASHBOARD ============================================
showDashboard = input.bool(true, "Show Info Panel", group=grp_dash, inline="theme")
dashTheme = input.string("Dark", "| Theme", options=["Dark", "Light"], group=grp_dash, inline="theme", tooltip="Dashboard color scheme\n\nDARK (Recommended):\n• Light text on dark background\n• Matches dark chart themes\n• Less eye strain\n• Professional look\n\nLIGHT:\n• Dark text on light background\n• Matches light chart themes\n• Good for presentations\n• High contrast")
dashPos = input.string("Bottom Left", "Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Right"], group=grp_dash, inline="pos", tooltip="Dashboard placement on chart\n\nTOP LEFT: Good for price action top-right\nTOP RIGHT: Good for price action top-left\nBOTTOM LEFT: Classic placement (recommended) ⭐\nBOTTOM RIGHT: Avoid volume bars\nMIDDLE RIGHT: Floating position\n\nChoose based on where price usually is")
dashSize = input.string("Auto", "Text Size", options=["Auto", "Small", "Normal", "Large"], group=grp_dash, inline="pos", tooltip="Text size inside dashboard\n\nAUTO: Adapts to chart zoom (recommended) ⭐\nSMALL: Compact, more screen space\nNORMAL: Readable\nLARGE: Presentations, poor eyesight")
showStage = input.bool(true, "Show Stage", group=grp_dash, inline="rows1", tooltip="Display current ORB stage\n\nSHOWS: Which timeframe is active\n• ORB 5 (5 minutes)\n• ORB 15 (15 minutes)\n• ORB 30 (30 minutes)\n• ORB 60 (60 minutes)\n\nUseful for knowing which ORB you're trading")
showRange = input.bool(true, "Show Range", group=grp_dash, inline="rows1", tooltip="Display ORB range size\n\nSHOWS:\n• High-Low difference (dollars)\n• Range as percentage\n\nEXAMPLE: '$0.50 (2.5%)'\n\nUseful for assessing if range is significant")
showStatus = input.bool(true, "Show Status", group=grp_dash, inline="rows1", tooltip="Display breakout status\n\nSTATES:\nINSIDE RANGE: Price within ORB\n• 🟢 BREAK UP: Above ORB High\n´ BREAK DOWN: Below ORB Low\n• 🟠 RETEST: Returned to ORB after breakout\n\nQuick visual confirmation of position")
showVol = input.bool(true, "Show Volume", group=grp_dash, inline="rows2", tooltip="Display volume status\n\nONLY SHOWN when Volume Filter enabled\n\nSHOWS:\n• Current volume vs average\n• Multiplier (e.g., '1.8x')\n• ✅ if above threshold\n• ⌠if below threshold\n\nUseful for confirming breakout strength")
showTrend = input.bool(true, "Show Trend", group=grp_dash, inline="rows2", tooltip="Display trend direction\n\nONLY SHOWN when Trend Filter enabled\n\nSHOWS:\n• Trend direction (UP/DOWN/NEUTRAL)\n• Method used (VWAP/EMA/etc.)\n• ✅ Aligned / ⌠Against trend\n\nUseful for context")
showRisk = input.bool(true, "Show Risk/Reward", group=grp_dash, inline="rows2", tooltip="Display Risk/Reward ratio\n\nSHOWS: Ratio of potential profit to risk\n\nFORMAT: '1:2.5' means:\n• Risk: $100\n• Reward: $250\n\nINDICATORS:\n• ✅ Ratio ≥ 2.0 (good)\n• ⚠️ Ratio 1.5-2.0 (acceptable)\n• ❌ Ratio < 1.5 (poor)\n\nBased on highest enabled TP")
showVolatilityMeter = input.bool(true, "Show Volatility Meter", group=grp_dash, inline="rows3", tooltip="Display current market volatility level\n\nMEASURES: ATR as percentage of price\n\nLEVELS:\n🔥🔥🔥 EXTREME (>3%): Very volatile, wider stops needed\n🔥🔥 HIGH (2-3%): Active movement, standard stops\n🔥 MEDIUM (1-2%): Normal trading range\n⚪ LOW (<1%): Quiet market, tight stops possible\n\nUSE FOR:\n• Adjusting position size\n• Setting appropriate stops\n• Understanding market conditions\n\nHigh volatility = Bigger potential moves but more risk")
 
enablePosSizing = input.bool(true, "Calculate Position Size", group=grp_dash, tooltip="Calculate shares to buy based on risk management\n\nCALCULATES:\n• Max shares to buy\n• Position dollar value\n• Risk amount\n• TP profit projections\n• TP allocation splits\n\nWHY:\n• Consistent risk per trade\n• Proper position sizing\n• Prevents over-leveraging\n\nSHOWS: Extra section in dashboard\n\nON: Shows position sizing\nOFF: Only price levels")
riskMode = input.string("$ Amount", "Risk", options=["$ Amount", "% of Account"], group=grp_dash, inline="risk", tooltip="How to define your risk per trade\n\n$ AMOUNT:\n• Risk fixed dollar amount\n• Simple and direct\n• Example: '$150 per trade'\n• Good for: Consistent trading\n\n% OF ACCOUNT:\n• Risk percentage of total account\n• Scales with account size\n• Example: '1% of $25,000 = $250'\n• Good for: Account growth\n\nRECOMMENDED: % of Account")
fixedRisk = input.float(150, "$", minval=10, maxval=10000, group=grp_dash, inline="risk", tooltip="Fixed dollar amount to risk per trade\n\nONLY USED when Risk Mode = $ Amount\n\nEXAMPLE: Fixed Risk = $150\n• Entry: $10.00\n• Stop: $9.50 (50¢ risk per share)\n• Position: 300 shares ($150 ÷ $0.50)\n• Total position value: $3,000\n\nRECOMMENDATIONS:\n• $50-100: Small accounts\n• $150-300: Medium accounts ⭐\n• $500+: Large accounts")
accountSize = input.float(25000, "Account $", minval=1000, group=grp_dash, inline="acct", tooltip="Total trading account size\n\nUSED FOR: Calculating risk percentage\n\nEXAMPLE: Account = $25,000, Risk = 1%\n• Risk per trade = $250\n\nUPDATE THIS:\n• When account grows/shrinks significantly\n• For accurate position sizing\n• Monthly review recommended")
riskPct = input.float(0.5, "Risk %", minval=0.1, maxval=5, step=0.1, group=grp_dash, inline="acct", tooltip="Percentage of account to risk per trade\n\nONLY USED when Risk Mode = % of Account\n\nRISK LEVELS:\n• 0.25-0.5%: Very conservative, slow growth\n• 0.5-1%: Balanced (recommended) ⭐\n• 1-2%: Aggressive, faster growth\n• 2-3%: Very aggressive, high risk\n• 3%+: Extreme risk, not recommended\n\nEXAMPLE: Account = $25,000, Risk = 1%\n• Risk per trade = $250\n• Entry: $10, Stop: $9.50 (50¢ risk)\n• Position: 500 shares\n\nRECOMMENDED: 0.5-1% for most traders")
maxPositionPct = input.float(25.0, "Max Position %", minval=5, maxval=100, step=5, group=grp_dash, inline="poslimit", tooltip="Maximum position size as % of account\n\nPREVENTS OVER-LEVERAGE when stop is very tight\n\nEXAMPLE: Account = $10,000, Max = 25%\n• Maximum position value = $2,500\n• If stock = $100, max 25 shares\n• Even if risk calculation allows more\n\nRECOMMENDED LEVELS:\n• 10-15%: Very conservative\n• 20-25%: Balanced ⭐\n• 30-50%: Aggressive\n• 50%+: Very aggressive\n\nThis protects against:\n• Tight stops causing huge positions\n• Slippage on large positions\n• Liquidity issues")

accountCurrency = input.string("USD", "Account Currency", options=["USD", "EUR", "GBP", "JPY", "INR", "CAD", "AUD", "CHF"], group=grp_dash, inline="currency", tooltip="Currency of your trading account\n\nUSD: U.S. Dollar\nEUR: Euro\nGBP: British Pound\nJPY: Japanese Yen\nINR: Indian Rupee\nCAD: Canadian Dollar\nAUD: Australian Dollar\nCHF: Swiss Franc\n\nIMPORTANT: Affects position sizing calculations\nAll risk and position values are shown in this currency")
useDynamicRates = input.bool(true, "Live Exchange Rates", group=grp_dash, inline="exchange", tooltip="Fetch live exchange rates from market data\n\nON: Uses real-time rates from TradingView (recommended)\nOFF: Use manual rate input\n\nNOTE: Live rates may not be available for all pairs")
manualRate = input.float(1.0, "/ Or set manual Rate: $1=", minval=0.001, maxval=10000, step=0.1, group=grp_dash, inline="exchange", tooltip="Fallback exchange rate when live rates unavailable\n\nFrom USD to your account currency\n\nEXAMPLES:\n• USD to INR = 83.0\n• USD to EUR = 0.92\n• USD to JPY = 150.0")

symbolCurrency = syminfo.currency

float liveRate = na
string currencyPair = ""

if useDynamicRates and accountCurrency != "USD"
    currencyPair := accountCurrency == "EUR" ? "EURUSD" :
                   accountCurrency == "GBP" ? "GBPUSD" :
                   accountCurrency == "JPY" ? "USDJPY" :
                   accountCurrency == "INR" ? "USDINR" :
                   accountCurrency == "CAD" ? "USDCAD" :
                   accountCurrency == "AUD" ? "AUDUSD" :
                   accountCurrency == "CHF" ? "USDCHF" : ""
    
    if currencyPair != ""
        liveRate := request.security(currencyPair, "D", close, lookahead=barmerge.lookahead_off)

float defaultRate = accountCurrency == "EUR" ? 0.92 :
                   accountCurrency == "GBP" ? 0.79 :
                   accountCurrency == "JPY" ? 150.0 :
                   accountCurrency == "INR" ? 83.0 :
                   accountCurrency == "CAD" ? 1.38 :
                   accountCurrency == "AUD" ? 1.55 :
                   accountCurrency == "CHF" ? 0.90 : 1.0
exchangeRate = accountCurrency == "USD" ? 1.0 :
               not useDynamicRates ? manualRate :
               na(liveRate) ? defaultRate :
               // Invert rates for pairs where USD is quote currency (EUR, GBP, AUD)
               (accountCurrency == "EUR" or accountCurrency == "GBP" or accountCurrency == "AUD") ? 1/liveRate : 
               liveRate  // Direct rate for pairs where USD is base currency (JPY, INR, CAD, CHF)

// ======================================= HIGHER TIMEFRAME FILTER ===================================
enableHTF = input.bool(true, "Check Daily Trend", group=grp_htf, tooltip="Check higher timeframe trend before taking breakouts\n\nWHY: Breakouts WITH higher timeframe trend have higher success rate\n\nWHAT IT DOES:\n• Checks daily/4H/weekly trend\n• Shows warning if breakout against trend\n• Displays HTF bias in dashboard\n\nDOES NOT BLOCK signals - only warns you\n\nON: Shows HTF context (recommended for swing traders)\nOFF: Focuses only on intraday ORB")
htfTF = input.string("D", "Timeframe", options=["15", "30", "60", "120", "240", "D", "W", "M"], group=grp_htf, inline="htf", tooltip="Higher timeframe to analyze for trend\n\nRECOMMENDED OPTIONS:\n• 15/30/60 min: For 1-5 min charts\n• 240 (4H): For 15-60 min charts\n• D (Daily): For intraday trading ⭐\n• W (Weekly): For swing trading\n• M (Monthly): For position trading\n\nRULE: HTF should be 4-10× your chart timeframe\n\nEXAMPLES:\n• 5min chart → Use 30/60/D\n• 15min chart → Use 60/240/D\n• 1H chart → Use 240/D/W")
htfMethod = input.string("Price vs MA", "Method", options=["Price vs MA", "Candle Direction"], group=grp_htf, inline="htf", tooltip="How to determine HTF trend\n\nPRICE VS MA (Recommended):\n• Compares HTF close to moving average\n• Above MA = Bullish\n• Below MA = Bearish\n• Smooth and reliable\n• Less prone to whipsaws\n\nCANDLE DIRECTION:\n• Based on HTF candle color\n• Green candle = Bullish\n• Red candle = Bearish\n• More reactive\n• Can change quickly\n\nRECOMMENDED: Price vs MA for stability")
htfEMA = input.int(20, "MA", minval=5, maxval=200, group=grp_htf, inline="htf2", tooltip="")
htfMinStrength = input.float(2.0, "Min Distance %", minval=0.0, maxval=10.0, step=0.5, group=grp_htf, inline="htf2", tooltip="Moving average period for HTF trend\n\nONLY USED when Method = Price vs MA\n\nSHORTER = More reactive, frequent changes\nLONGER = Smoother, stable trend\n\nRECOMMENDATIONS:\n• 10-20: Responsive (short-term trend)\n• 20-50: Balanced (recommended) ⭐\n• 50-100: Smooth (intermediate trend)\n• 100-200: Very smooth (long-term trend)\n\nCOMMON CHOICES:\n• Daily TF + 20 EMA: Classic\n• Daily TF + 50 EMA: Swing trading\n• Weekly TF + 20 EMA: Position trading\n\nMinimum distance from MA to consider trend valid\n\nPrice must be at least X% away from MA\n\nLOWER = Accept weak trends\nHIGHER = Only strong trends\n\nRECOMMENDATIONS:\n• 0-1%: Very permissive\n• 1-2%: Balanced ⭐\n• 2-3%: Conservative\n• 3%+: Very selective\n\nHELPS AVOID:\n• Choppy/sideways markets\n• Weak trend signals\n• False breakouts")

// ============================================ GOD MODE =============================================
godModeEnabled = input.bool(true, "Enable GOD MODE", group=grp_god, tooltip="Master switch for the GOD MODE intelligence layer\n\nADDS:\n• Breakout Quality Score (0-100, graded A+ to D) on labels, alerts and dashboard\n• Day Context row: gap vs yesterday + ORB width vs daily ATR\n• Level Confluence: flags ORB levels sitting on PDH/PDL or premarket high/low (🏆)\n• Chop-Day Guard: warns after repeated failed breaks\n• Adaptive breakout buffer scaled by ATR\n\nOFF = classic behavior, exactly as before")
godAdaptiveBuffer = input.bool(true, "Adaptive Buffer", group=grp_god, inline="god1", tooltip="Scales the breakout buffer with volatility\n\nEffective buffer = max(Breakout Buffer %, 10% of ATR)\n\nVolatile tickers automatically get a wider buffer (fewer false breakouts); quiet tickers keep the fixed %.\n\nReplaces one-size-fits-all % with per-ticker calibration.")
godChopGuard = input.bool(true, "Chop-Day Guard", group=grp_god, inline="god1", tooltip="Detects choppy range days\n\n2+ FAILED BREAKS in one session = CHOP DAY:\n• ⚠️ Warning in dashboard\n• Quality Score capped at 40 (C/D)\n\nProtects against the most common ORB failure mode: range-day whipsaws.")
godShowScore = input.bool(true, "Score on Labels", group=grp_god, inline="god1", tooltip="Appends the Quality Score to breakout labels\n\nExample: ⚡ 87 (A+) 🏆\n\n🏆 = ORB level confluent with PDH/PDL or premarket high/low")

// ============================================= ALERTS ==============================================
// All alerts enabled by default - no user controls (internal use only)
bool enableAlerts = true
bool alertBreakouts = true
bool alertRetests = true
bool alertFailedBreaks = true
bool alertStageComplete = true
bool alertTradeManagement = true

// ========================================= INPUT VALIDATION ========================================
if breakoutBuffer < 0 or breakoutBuffer > 5
    runtime.error("❌ Breakout Buffer must be between 0-5%. Current value: " + str.tostring(breakoutBuffer))
if minRetestDistancePct < 0.5
    runtime.error("❌ Min Retest Distance too low. Must be >= 0.5% to prevent false signals. Current: " + str.tostring(minRetestDistancePct))
if minBarsOutside < 1
    runtime.error("❌ Min Bars Outside must be >= 1. Current: " + str.tostring(minBarsOutside))
if maxCycles < 1 or maxCycles > 10
    runtime.error("❌ Max Cycles must be between 1-10. Current: " + str.tostring(maxCycles))
if enableVolumeFilter
    if volumeMultiplier < 0.5
        runtime.error("❌ Volume Multiplier too low. Must be >= 0.5x. Current: " + str.tostring(volumeMultiplier))
    if strongVolumeMultiplier < volumeMultiplier
        runtime.error("❌ Strong Volume Multiplier must be >= Min Volume Multiplier. Strong: " + str.tostring(strongVolumeMultiplier) + ", Min: " + str.tostring(volumeMultiplier))
    if volumeMaLength < 1
        runtime.error("❌ Volume MA Length must be >= 1. Current: " + str.tostring(volumeMaLength))
if enableTargets
    if atrLength < 5 or atrLength > 50
        runtime.error("❌ ATR Length must be between 5-50. Current: " + str.tostring(atrLength))    
    if atrMultiplier < 0.5 or atrMultiplier > 5
        runtime.error("❌ ATR Multiplier must be between 0.5-5. Current: " + str.tostring(atrMultiplier))    
    if stopOrbFraction < 10 or stopOrbFraction > 100
        runtime.error("❌ ORB Stop % must be between 10-100%. Current: " + str.tostring(stopOrbFraction))    
    if swingBars < 1 or swingBars > 20
        runtime.error("❌ Swing Bars must be between 1-20. Current: " + str.tostring(swingBars))
if enablePosSizing
    if riskMode == "$ Amount" and fixedRisk < 10
        runtime.error("❌ Fixed Risk too low. Must be >= $10. Current: $" + str.tostring(fixedRisk))   
    if riskMode == "% of Account"
        if riskPct < 0.1 or riskPct > 10
            runtime.error("❌ Risk % must be between 0.1-10%. Current: " + str.tostring(riskPct) + "%")      
        if accountSize < 100
            runtime.error("❌ Account Size too low. Must be >= $100. Current: $" + str.tostring(accountSize))
if fillTransparency < 0 or fillTransparency > 100
    runtime.error("❌ Fill Transparency must be between 0-100%. Current: " + str.tostring(fillTransparency))
if enableHTF
    if htfEMA < 5 or htfEMA > 200
        runtime.error("❌ HTF EMA period must be between 5-200. Current: " + str.tostring(htfEMA))
if enableTrendFilter
    if customEmaLength < 1 or customEmaLength > 500
        runtime.error("❌ Custom EMA Length must be between 1-500. Current: " + str.tostring(customEmaLength))
    
    if supertrendPeriod < 1 or supertrendPeriod > 50
        runtime.error("❌ SuperTrend Period must be between 1-50. Current: " + str.tostring(supertrendPeriod))
    
    if supertrendMult < 0.1 or supertrendMult > 10
        runtime.error("❌ SuperTrend Multiplier must be between 0.1-10. Current: " + str.tostring(supertrendMult))
// TP validation removed - allowing all TPs to be disabled while keeping ORB functionality

// ========================================= SESSION DETECTION =======================================
// Fix for crypto session handling - credit to Crucialblockchain (Reddit credit: u/Crucialblockchain)
// Issue: Crypto was always inSession=true, ignoring custom session times (e.g., London 08:00-16:30)
// Solution: Check if 24/7 mode first, otherwise respect session hours

// Detect if using native session (empty tradingSession string)
bool useNativeSession = tradingSession == ""

// 24/7 market detection: crypto with native session OR explicit 24/7 string
bool is24_7Market = syminfo.type == "crypto" and (useNativeSession or tradingSession == "0000-2359:1234567")

inSession = false
if useNativeSession
    // Use TradingView's native session detection (no session parameter)
    // This automatically handles timezone conversions!
    inSession := not na(time(timeframe.period))
else
    // Use custom session string (Extended Hours, timezone modes, Custom mode) with timezone support
    if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
        inSession := not na(time(timeframe.period, tradingSession, sessionTimezone))
    else if syminfo.type == "crypto"
        if is24_7Market
            inSession := true  // 24/7 trading - always in session
        else
            inSession := not na(time(timeframe.period, tradingSession, sessionTimezone))  // Respect custom session hours
    else if syminfo.type == "forex"
        inSession := not na(time(timeframe.period, tradingSession, sessionTimezone))
    else
        inSession := not na(time(timeframe.period, tradingSession, sessionTimezone))

// ============================================== VARIABLES ==========================================
var label labH = na
var label labL = na
var color cachedLineColor = na
var float lastLabelH = na
var float lastLabelL = na
var string cachedStageName = na
var bool hadSessionToday = false
var bool hadBreakUp = false
var bool hadBreakDown = false
var int breakUpBar = na
var int breakDownBar = na
var bool shownBreakUpLabel = false
var bool shownBreakDownLabel = false
var bool everHadBreakUp = false
var bool everHadBreakDown = false
var float breakoutEntryPrice = na

var int cyclesUp = 0
var int cyclesDown = 0

var int retestCyclesUp = 0 
var int retestCyclesDown = 0

var int sessionBreakoutsUp = 0
var int sessionBreakoutsDown = 0
var int sessionRetestsUp = 0
var int sessionRetestsDown = 0 

 

var string alertMsgRetestUp = ""
var string alertMsgRetestDown = ""
var string alertMsgFailedUp = ""
var string alertMsgFailedDown = ""
var string alertMsgStageComplete = ""

bool alertBreakUpTriggered = false
bool alertBreakDownTriggered = false
bool alertRetestUpTriggered = false
bool alertRetestDownTriggered = false
bool alertFailedUpTriggered = false
bool alertFailedDownTriggered = false
bool alertStageCompleteTriggered = false

// Trade management alert triggers
bool alertEntryTriggered = false
bool alertSLTriggered = false
bool alertTP1Triggered = false
bool alertTP1_5Triggered = false
bool alertTP2Triggered = false
bool alertTP3Triggered = false

var int barsOutsideAfterBreakUp = 0
var int barsOutsideAfterBreakDown = 0

var label lastBreakUpLabel = na
var label lastBreakDownLabel = na
var int lastLabelStage = na

var int breakUpBarIndex = 0
var int breakDownBarIndex = 0

var bool pendingLongEntry = false
var bool pendingShortEntry = false
var int pendingLongBar = na
var int pendingShortBar = na

var array<label> breakoutLabels = array.new<label>()
MAX_LABELS_TO_KEEP = 10
var array<line> tpslLines = array.new<line>()
var array<box> orbBoxes = array.new<box>()
MAX_LINES_TO_KEEP = 20
MAX_BOXES_TO_KEEP = 10

var int lastDashUpdateBar = -1

var float cachedATR = na
var int cachedATRBar = -1
var float cachedVolumeMA = na
var int cachedVolumeMABar = -1

var float cachedEntry = na
var float cachedSL = na
var float cachedTP1 = na
var float cachedTP1_5 = na
var float cachedTP2 = na
var float cachedTP3 = na
var float cachedShares = na
var float cachedPosValue = na
var float cachedMaxLoss = na
var float cachedRiskAmount = na

var array<box> fvgBoxes = array.new<box>()
var array<float> fvgTops = array.new<float>()
var array<float> fvgBottoms = array.new<float>()
var array<bool> fvgIsBullish = array.new<bool>()
var array<bool> fvgIsActive = array.new<bool>()
var array<int> fvgStartBar = array.new<int>()

var bool hadRetestUp = false
var bool hadRetestDown = false
var int retestUpBar = na
var int retestDownBar = na
var bool wentFarEnoughUp = false
var bool wentFarEnoughDown = false
var int sessionStartBar = na
var float sessionStartTime = na

var float trendVWAP = na
var float trendEMA12 = na
var float trendEMACustom = na
var float trendSTUp = na
var float trendSTDown = na
var int trendSTDirection = 0
var float volumeMA = na

var bool htfBullish = false
var bool htfBearish = false
var string htfBiasText = ""

var float actH = na
var float actL = na
var float actM = na

var float tradeOrbHigh = na
var float tradeOrbLow = na

var bool haveRange = false
var bool haveDisplayRange = false

var int stage = 0
var float displayH = na
var float displayL = na

var line orbEntryLine = na
var label orbEntryLabel = na
var float orbEntryPrice = na
var int orbEntryBar = na
var color orbLineColor = na
var line orbSLLine = na
var label orbSLLabel = na
var float orbSLPrice = na
var line orbTP1Line = na
var label orbTP1Label = na
var float orbTP1Price = na
var line orbTP1_5Line = na
var label orbTP1_5Label = na
var float orbTP1_5Price = na
var line orbTP2Line = na
var label orbTP2Label = na
var float orbTP2Price = na
var line orbTP3Line = na
var label orbTP3Label = na
var float orbTP3Price = na
var bool orbLinesFrozen = false
var int orbTradeDirection = 0

var bool orbTP1Hit = false
var bool orbTP1_5Hit = false
var bool orbTP2Hit = false
var bool orbTP3Hit = false
var bool orbSLHit = false

var int session_wins = 0
var int session_losses = 0
var float session_total_rr = 0.0
var int session_trades = 0
var float session_best_r = 0.0
var float session_worst_r = 0.0
var bool trade_closed = false
var string last_trade_result = ""

var float current_trade_r = 0.0
var bool tp1_counted = false
var bool tp1_5_counted = false
var bool tp2_counted = false
var bool tp3_counted = false

var float maxShares = na
var float positionValue = na
var float maxLoss = na

var int prevOrbEntryBar = na

var table dashTable = na

var int prevCyclesUp = 0
var int prevCyclesDown = 0

// ========================================= ORB OBJECTS INITIALIZATION ==============================
var ORBData orb5Obj = ORBData.new(name = "ORB5",minutes = 5,high = na, low = na, mid = na, orbRange = na,isEnabled = false, isBuilding = false, isComplete = false,completionBar = 0,breakoutUp = false, breakoutDown = false,breakoutBar = 0, breakoutLevel = na,cyclesUp = 0, cyclesDown = 0,orbBox = na, highLine = na, lowLine = na, midLine = na, edgeLabel = na,orbColor = color.blue,lineWidth = 1,lineStyle = line.style_solid)
var ORBData orb15Obj = ORBData.new(name = "ORB15",minutes = 15,high = na, low = na, mid = na, orbRange = na,isEnabled = false, isBuilding = false, isComplete = false,completionBar = 0,breakoutUp = false, breakoutDown = false,breakoutBar = 0, breakoutLevel = na,cyclesUp = 0, cyclesDown = 0,orbBox = na, highLine = na, lowLine = na, midLine = na, edgeLabel = na,orbColor = color.green, lineWidth = 1,lineStyle = line.style_solid)
var ORBData orb30Obj = ORBData.new(name = "ORB30",minutes = 30,high = na, low = na, mid = na, orbRange = na,isEnabled = false,  isBuilding = false, isComplete = false,completionBar = 0,breakoutUp = false, breakoutDown = false,breakoutBar = 0, breakoutLevel = na,cyclesUp = 0, cyclesDown = 0,orbBox = na, highLine = na, lowLine = na, midLine = na, edgeLabel = na,orbColor = color.orange,  lineWidth = 1,lineStyle = line.style_solid)
var ORBData orb60Obj = ORBData.new(name = "ORB60",minutes = 60,high = na, low = na, mid = na, orbRange = na,isEnabled = false, isBuilding = false, isComplete = false,completionBar = 0,breakoutUp = false, breakoutDown = false,breakoutBar = 0, breakoutLevel = na,cyclesUp = 0, cyclesDown = 0,orbBox = na, highLine = na, lowLine = na, midLine = na, edgeLabel = na,orbColor = color.red, lineWidth = 1,lineStyle = line.style_solid)

var ORBData activeORB = na
var array<ORBData> allORBs = array.from(orb5Obj, orb15Obj, orb30Obj, orb60Obj)
var array<ORBData> cachedPrevORBs = array.new<ORBData>(4, na)
var array<ORBData> cachedNextORBs = array.new<ORBData>(4, na)
var bool orbNavigationCached = false

if barstate.isfirst
    orb5Obj.isEnabled := enableORB5Signals
    orb15Obj.isEnabled := enableORB15Signals
    orb30Obj.isEnabled := enableORB30Signals
    orb60Obj.isEnabled := enableORB60Signals
    
    orb5Obj.orbColor := orb5LineColor
    orb15Obj.orbColor := orb15LineColor
    orb30Obj.orbColor := orb30LineColor
    orb60Obj.orbColor := orb60LineColor

// ============================================ ALERT FUNCTIONS ======================================
sendAlert(string message) =>
    if enableAlerts
        alert(message, alert.freq_once_per_bar_close)

// ========================================== VALIDATION FUNCTIONS ===================================
hasVolumeConfirmation(volMA, mult, strongMult) =>
    if na(volMA) or volMA == 0
        true
    else
        currentVol = volume
        isStrongVolume = strongMult > 0 and currentVol >= volMA * strongMult
        isNormalVolume = currentVol >= volMA * mult
        isStrongVolume or isNormalVolume

// =========================================== TARGET & STOP FUNCTIONS ================================
calculateTargets(entry, sl, isBullish) =>
    float risk = math.abs(entry - sl)
    float orbWidth = actH - actL  // Current ORB width

    float riskAdjustment = entry < 1000 ? 1.0 : entry < 5000 ? 0.8 :  0.6
    
    float tp1_orb = isBullish ? entry + (orbWidth * 1.0) : entry - (orbWidth * 1.0)
    float tp1_5_orb = isBullish ? entry + (orbWidth * 1.5) : entry - (orbWidth * 1.5)
    float tp2_orb = isBullish ? entry + (orbWidth * 2.0) : entry - (orbWidth * 2.0)
    float tp3_orb = isBullish ? entry + (orbWidth * 3.0) : entry - (orbWidth * 3.0)
    
    float tp1_risk = isBullish ? entry + (risk * 1.0 * riskAdjustment) : entry - (risk * 1.0 * riskAdjustment)
    float tp1_5_risk = isBullish ? entry + (risk * 1.5 * riskAdjustment) : entry - (risk * 1.5 * riskAdjustment)
    float tp2_risk = isBullish ? entry + (risk * 2.0 * riskAdjustment) : entry - (risk * 2.0 * riskAdjustment)
    float tp3_risk = isBullish ? entry + (risk * 3.0 * riskAdjustment) : entry - (risk * 3.0 * riskAdjustment)
    
    float tp1 = isBullish ? math.min(tp1_orb, tp1_risk) : math.max(tp1_orb, tp1_risk)
    float tp1_5 = isBullish ? math.min(tp1_5_orb, tp1_5_risk) : math.max(tp1_5_orb, tp1_5_risk)
    float tp2 = isBullish ? math.min(tp2_orb, tp2_risk) : math.max(tp2_orb, tp2_risk)
    float tp3 = isBullish ? math.min(tp3_orb, tp3_risk) : math.max(tp3_orb, tp3_risk)
    
    [tp1, tp1_5, tp2, tp3]

calculateStopLoss(entry, orbHigh, orbLow, orbRange, atr, mode, isBullish) =>
    float sl = na
    float orbFraction = stopOrbFraction / 100
    
    float validATR = na(atr) or atr == 0 ? orbRange * 0.5 : atr
    
    float atrPercent = (validATR / entry) * 100
    
    float minStopMultiplier = syminfo.type == "crypto" ? 1.0 :      // Crypto needs wider stops
                              syminfo.type == "forex" ? 0.3 :       // Forex needs tighter stops
                              atrPercent > 5 ? 1.5 :                // Very volatile (>5% ATR)
                              atrPercent > 3 ? 1.0 :                // High volatility (3-5% ATR)  
                              atrPercent > 1.5 ? 0.7 :              // Normal volatility (1.5-3% ATR)
                              0.5                                   // Low volatility (<1.5% ATR)
    
    float minStopDistance = validATR * minStopMultiplier
    
    float absoluteMin = syminfo.type == "crypto" ? entry * 0.01 :   // 1% min for crypto
                       syminfo.type == "forex" ? entry * 0.002 :    // 0.2% min for forex
                       entry * 0.003                                // 0.3% min for stocks
    
    minStopDistance := math.max(minStopDistance, absoluteMin)
    
    if isBullish
        if mode == "ATR"
            float priceAdjust = entry < 1000 ? 1.0 :   // Standard for normal prices
                               entry < 5000 ? 0.7 :    // Reduce for high price
                               0.5                     // Further reduce for very high price
            sl := entry - (validATR * atrMultiplier * priceAdjust)
        else if mode == "ORB %"
            sl := orbLow - (orbRange * orbFraction)
        else if mode == "Swing"
            sl := ta.lowest(low, swingBars)
        else if mode == "Safer"
            float atrSL = entry - (validATR * atrMultiplier * 2)  // Wider for safer
            float swingSL = ta.lowest(low, swingBars)
            float orbSL = orbLow - (orbRange * orbFraction * 1.5)  // 150% of normal ORB fraction
            sl := math.min(swingSL, math.min(atrSL, orbSL))  // Most conservative
        else if mode == "% Based"
            sl := entry * (1 - percentBasedStop / 100)  // Simple % from entry
        else if mode == "Smart Adaptive"
            float smartMultiplier = atrPercent > 3 ? 1.5 : atrPercent > 1.5 ? 1.0 : 0.7
            float atrStop = entry - (validATR * smartMultiplier)
            float orbStop = orbLow - (orbRange * 0.3)  // 30% of ORB range
            // Use ATR-based stop primarily, ORB as fallback
            sl := math.min(atrStop, orbStop)  // More conservative (farther from entry)
        else if mode == "Scaled ATR"
            float scaledMult = atrPercent > 5 ? 2.5 :     // Very volatile - wider stop
                              atrPercent > 3 ? 2.0 :      // High volatility
                              atrPercent > 1.5 ? 1.5 :    // Normal volatility
                              1.2                         // Low volatility - tighter stop
            sl := entry - (validATR * scaledMult)
    else
        if mode == "ATR"
            float volAdjust = atrPercent > 3 ? 1.2 : atrPercent > 1.5 ? 1.0 : 0.8
            sl := entry + (validATR * atrMultiplier * volAdjust)
        else if mode == "ORB %"
            sl := orbHigh + (orbRange * orbFraction)
        else if mode == "Swing"
            sl := ta.highest(high, swingBars)
        else if mode == "Safer"
            float atrSL = entry + (validATR * atrMultiplier * 2)
            float swingSL = ta.highest(high, swingBars)
            float orbSL = orbHigh + (orbRange * orbFraction * 1.5)
            sl := math.max(swingSL, math.max(atrSL, orbSL))
        else if mode == "% Based"
            sl := entry * (1 + percentBasedStop / 100)
        else if mode == "Smart Adaptive"
            // Same volatility-based logic for bearish
            float smartMultiplier = atrPercent > 3 ? 1.5 : atrPercent > 1.5 ? 1.0 : 0.7
            float atrStop = entry + (validATR * smartMultiplier)
            float orbStop = orbHigh + (orbRange * 0.3)
            sl := math.max(atrStop, orbStop)  // More conservative
        else if mode == "Scaled ATR"
            // Same volatility scaling for bearish
            float scaledMult = atrPercent > 5 ? 2.5 :
                              atrPercent > 3 ? 2.0 :
                              atrPercent > 1.5 ? 1.5 :
                              1.2
            sl := entry + (validATR * scaledMult)
    
    sl := isBullish ? math.min(sl, entry - minStopDistance) : math.max(sl, entry + minStopDistance)
    
    sl

calculatePositionSize(entry, sl) =>
    float riskAmount = 0.0
    
    if riskMode == "% of Account"
        riskAmount := accountSize * (riskPct / 100)
    else
        riskAmount := fixedRisk
        
    if symbolCurrency != accountCurrency
        riskAmount := riskAmount * exchangeRate
    
    float riskPerShare = math.abs(entry - sl) 
    float sharesFromRisk = riskPerShare > 0 ? math.floor(riskAmount / riskPerShare) : 0
    float maxPositionValue = accountSize * (maxPositionPct / 100)

    if symbolCurrency != accountCurrency
        maxPositionValue := maxPositionValue * exchangeRate
    
    float maxSharesFromLimit = entry > 0 ? math.floor(maxPositionValue / entry) : 0
    float shares = math.min(sharesFromRisk, maxSharesFromLimit)
    float posValue = shares * entry
    shares := math.floor(shares)
    float maxLossCalc = shares * riskPerShare
    
    [shares, posValue, maxLossCalc, riskAmount]

calculateTPSplits(show1, show1_5, show2, show3) =>
    int activeCount = 0
    if show1
        activeCount += 1
    if show1_5
        activeCount += 1
    if show2
        activeCount += 1
    if show3
        activeCount += 1
    
    float split1 = 0.0
    float split1_5 = 0.0
    float split2 = 0.0
    float split3 = 0.0
    
    if activeCount == 1
        if show1
            split1 := 1.0
        else if show1_5
            split1_5 := 1.0
        else if show2
            split2 := 1.0
        else if show3
            split3 := 1.0
    else if activeCount == 2
        float half = 0.5
        if show1
            split1 := half
            if show1_5
                split1_5 := half
            else if show2
                split2 := half
            else if show3
                split3 := half
        else if show1_5
            split1_5 := half
            if show2
                split2 := half
            else if show3
                split3 := half
        else if show2
            split2 := half
            if show3
                split3 := half
        else if show3
            split3 := half
    else if activeCount >= 3
        float remaining = 0.5
        float remainder = remaining / (activeCount - 1)
        
        bool firstAssigned = false
        if show1
            split1 := firstAssigned ? remainder : 0.5
            firstAssigned := true
        if show1_5
            split1_5 := firstAssigned ? remainder : 0.5
            firstAssigned := true
        if show2
            split2 := firstAssigned ? remainder : 0.5
            firstAssigned := true
        if show3
            split3 := firstAssigned ? remainder : 0.5
            firstAssigned := true
    
    [split1, split1_5, split2, split3]

checkHTFBias() =>
    bool bullish = false
    bool bearish = false
    string biasText = ""
    float strength = 0.0
    
    if enableHTF
        [htfClose, htfOpen, htfMA] = request.security(syminfo.tickerid, htfTF, [close, open, ta.ema(close, htfEMA)], barmerge.gaps_off, barmerge.lookahead_off)
        
        if htfMethod == "Price vs MA"
            float distancePct = htfMA > 0 ? ((htfClose - htfMA) / htfMA) * 100 : 0
            strength := math.abs(distancePct)
            
            bool strongEnough = enableHTF ? strength >= htfMinStrength : false
            
            bullish := htfClose > htfMA and strongEnough
            bearish := htfClose < htfMA and strongEnough
            
        else if htfMethod == "Candle Direction"
            float bodySize = math.abs(htfClose - htfOpen)
            float candleRange = htfClose > 0 ? (bodySize / htfClose) * 100 : 0
            strength := candleRange
            
            bullish := htfClose > htfOpen
            bearish := htfClose < htfOpen
        
        if bullish
            biasText := strength > htfMinStrength * 2 ? "✅✅ Strong Aligned" : "✅ Aligned"
        else if bearish
            biasText := strength > htfMinStrength * 2 ? "⚠️ Strong Counter ⚠️" : "⚠️ Counter-Trend"
        else
            biasText := "➖ Neutral/Weak"
    
    [bullish, bearish, biasText, strength]

// ============================================== FUNCTIONS ==========================================
getBodyHigh() => math.max(open, close)
getBodyLow() => math.min(open, close)
bodyClosedAbove(level) => getBodyLow() > level
bodyClosedBelow(level) => getBodyHigh() < level

float currentTF_minutes = timeframe.in_seconds() / 60
needsConfirmation = currentTF_minutes <= 5

getBuffer(level, pct) =>
    level * (pct / 100)
priceRetestFromAbove(level, buffer) =>
    getBodyLow() < level + buffer
priceRetestFromBelow(level, buffer) =>
    getBodyHigh() > level - buffer
getLabelSize(sizeStr) =>
    sizeStr == "Tiny" ? size.tiny : sizeStr == "Small" ? size.small : sizeStr == "Normal" ? size.normal : sizeStr == "Large" ? size.large : size.huge
calcSuperTrend(atrPeriod, multiplier) =>
    atr = ta.atr(atrPeriod)
    hl2Val = hl2
    
    basicUpperBand = hl2Val + multiplier * atr
    basicLowerBand = hl2Val - multiplier * atr
    
    var float finalUpperBand = na
    var float finalLowerBand = na
    var int trendDir = 1
    
    finalUpperBand := na(finalUpperBand[1]) or basicUpperBand < finalUpperBand[1] or close[1] > finalUpperBand[1] ? basicUpperBand : finalUpperBand[1]
    finalLowerBand := na(finalLowerBand[1]) or basicLowerBand > finalLowerBand[1] or close[1] < finalLowerBand[1] ? basicLowerBand : finalLowerBand[1]
    
    trendDir := na(trendDir[1]) ? 1 : close > finalUpperBand[1] ? 1 : close < finalLowerBand[1] ? -1 : trendDir[1]
    
    [finalLowerBand, finalUpperBand, trendDir]

isTrendUp(mode, closePrice, vwapVal, ema12Val, emaCustomVal, stDir) =>
    switch mode
        "VWAP" => closePrice > vwapVal
        "EMA" => closePrice > ema12Val
        "Custom EMA" => closePrice > emaCustomVal
        "SuperTrend" => stDir == 1
        "VWAP+EMA" => closePrice > vwapVal and closePrice > ema12Val
        "VWAP+SuperTrend" => closePrice > vwapVal and stDir == 1
        => true

isTrendDown(mode, closePrice, vwapVal, ema12Val, emaCustomVal, stDir) =>
    switch mode
        "VWAP" => closePrice < vwapVal
        "EMA" => closePrice < ema12Val
        "Custom EMA" => closePrice < emaCustomVal
        "SuperTrend" => stDir == -1
        "VWAP+EMA" => closePrice < vwapVal and closePrice < ema12Val
        "VWAP+SuperTrend" => closePrice < vwapVal and stDir == -1
        => true

isTradingDay() =>
    bool isTrading = true
    
    if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
        int currentDayOfWeek = dayofweek(timenow)
        // 1=Sunday, 2=Monday, ..., 7=Saturday
        // Trading days: Monday(2) to Friday(6)
        isTrading := currentDayOfWeek >= 2 and currentDayOfWeek <= 6
    else if syminfo.type == "crypto"
        isTrading := true  // 24/7
    else if syminfo.type == "forex"
        int currentDayOfWeek = dayofweek(timenow)
        // Forex: Sunday evening to Friday evening
        isTrading := currentDayOfWeek >= 1 and currentDayOfWeek <= 6
    else
        isTrading := true
    
    isTrading

isReplayMode() =>
    bool isReplay = false
    
    if barstate.islast
        int timeDiffMinutes = int((timenow - time_close) / 60000)

        int currentDayOfWeek = dayofweek(timenow)
        int barDayOfWeek = dayofweek(time_close)
    
        bool isWeekendNow = currentDayOfWeek == 7 or currentDayOfWeek == 1  // Saturday or Sunday
        bool barWasFriday = barDayOfWeek == 6  // Last bar was Friday

        if isWeekendNow and barWasFriday
            isReplay := false  // LIVE on weekend - don't show dashboard

        else if currentDayOfWeek == 2 and barDayOfWeek == 6
            isReplay := false  // LIVE on Monday pre-market

        else
            isReplay := timeDiffMinutes > 1440
    
    isReplay

isWithinSessionHours() =>
    bool withinHours = false

    // If using native session, use TradingView's inSession variable
    if useNativeSession
        withinHours := inSession
    else
        bool useReplayTime = isReplayMode()
        int timeToCheck = useReplayTime ? time : timenow

        int currentDayOfWeek = dayofweek(timeToCheck)
        bool isTradingDay = syminfo.type == "stock" ? (currentDayOfWeek >= 2 and currentDayOfWeek <= 6) : true

        if not isTradingDay and syminfo.type == "stock"
            withinHours := false
        else if not na(sessionStartHour) and not na(sessionEndHour)
            // Get time components from appropriate source
            int currentHour = hour(timeToCheck)
            int currentMinute = minute(timeToCheck)

            int currentMinutesFromMidnight = currentHour * 60 + currentMinute
            int sessionStartMinutes = sessionStartHour * 60 + sessionStartMinute
            int sessionEndMinutes = sessionEndHour * 60 + sessionEndMinute

            withinHours := currentMinutesFromMidnight >= sessionStartMinutes and currentMinutesFromMidnight <= sessionEndMinutes

    withinHours

// ====================================== ORB HELPER FUNCTIONS =======================================
getPreviousEnabledORB(ORBData currentOrb) =>
    ORBData prevOrb = na
    for orb in allORBs
        if orb.isEnabled and orb.minutes < currentOrb.minutes
            if na(prevOrb) or orb.minutes > prevOrb.minutes
                prevOrb := orb
    prevOrb

getNextEnabledORB(ORBData currentOrb) =>
    ORBData nextOrb = na
    for orb in allORBs
        if orb.isEnabled and orb.minutes > currentOrb.minutes
            if na(nextOrb) or orb.minutes < nextOrb.minutes
                nextOrb := orb
    nextOrb

// ====================================== CLEANUP FUNCTIONS ==========================================
cleanupLine(lineObject) =>
    if not na(lineObject)
        array.push(tpslLines, lineObject)
        if array.size(tpslLines) > MAX_LINES_TO_KEEP
            oldLine = array.shift(tpslLines)
            if not na(oldLine)
                line.delete(oldLine)

cleanupLabel(labelObject) =>
    if not na(labelObject)
        array.push(breakoutLabels, labelObject)
        if array.size(breakoutLabels) > MAX_LABELS_TO_KEEP
            oldLabel = array.shift(breakoutLabels)
            if not na(oldLabel)
                label.delete(oldLabel)

// Clean up old boxes to prevent memory issues
cleanupBox(boxObject) =>
    if not na(boxObject)
        array.push(orbBoxes, boxObject)
        if array.size(orbBoxes) > MAX_BOXES_TO_KEEP
            oldBox = array.shift(orbBoxes)
            if not na(oldBox)
                box.delete(oldBox)

// ===================================== FVG DETECTION FUNCTIONS =====================================
detectBullishFVG() =>
    bool hasFVG = false
    float fvgTop = na
    float fvgBottom = na
    
    if bar_index >= 2
        if high[2] < low[0]
            hasFVG := true
            fvgTop := low[0]
            fvgBottom := high[2]
    
    [hasFVG, fvgTop, fvgBottom]

detectBearishFVG() =>
    bool hasFVG = false
    float fvgTop = na
    float fvgBottom = na
    
    if bar_index >= 2
        if low[2] > high[0]
            hasFVG := true
            fvgTop := low[2]
            fvgBottom := high[0]
    
    [hasFVG, fvgTop, fvgBottom]

hasValidFVGNearLevel(level, isBullish) =>
    bool foundFVG = false
    
    if array.size(fvgTops) > 0
        for i = 0 to array.size(fvgTops) - 1
            if array.get(fvgIsBullish, i) == isBullish
                fvgTop = array.get(fvgTops, i)
                fvgBottom = array.get(fvgBottoms, i)
                fvgSize = fvgTop - fvgBottom
                
                // Use user-defined proximity
                expandedTop = fvgTop + (fvgSize * fvgProximity)
                expandedBottom = fvgBottom - (fvgSize * fvgProximity)
                
                if level >= expandedBottom and level <= expandedTop
                    foundFVG := true
                    break
    
    foundFVG
 
cleanupOldFVG() =>
    while array.size(fvgBoxes) > maxFVGtoKeep
        oldBox = array.shift(fvgBoxes)
        array.shift(fvgTops)
        array.shift(fvgBottoms)
        array.shift(fvgIsBullish)
        array.shift(fvgIsActive)
        array.shift(fvgStartBar)
        if not na(oldBox)
            box.delete(oldBox)

// ================================ SESSION STATUS DETECTION FUNCTIONS ===============================
isWithinDisplayHours() =>
    bool withinDisplay = false
 
    bool useReplayTime = isReplayMode()
    int timeToCheck = useReplayTime ? time : timenow
    
    if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
        int currentDayOfWeek = dayofweek(timeToCheck)
        bool isTradingDay = currentDayOfWeek >= 2 and currentDayOfWeek <= 6
        
        if not isTradingDay
            withinDisplay := false
        else
            int currentHour = hour(timeToCheck)
            int currentMinute = minute(timeToCheck)
            int currentMinutesFromMidnight = currentHour * 60 + currentMinute

            int displayStartMinutes = 4 * 60  // 240 minutes = 04:00
            int displayEndMinutes = 20 * 60   // 1200 minutes = 20:00
            
            withinDisplay := currentMinutesFromMidnight >= displayStartMinutes and currentMinutesFromMidnight < displayEndMinutes
    else if syminfo.type == "crypto"
        withinDisplay := true  // 24/7 display
    else if syminfo.type == "forex"
        withinDisplay := true  // Display when forex session active
    else
        withinDisplay := true  // Default: always display
    
    withinDisplay

isInRegularHours() =>
    bool inRegular = false
    
    bool useReplayTime = isReplayMode()
    int timeToCheck = useReplayTime ? time : timenow
    
    if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
        int currentDayOfWeek = dayofweek(timeToCheck)
        bool isTradingDay = currentDayOfWeek >= 2 and currentDayOfWeek <= 6
        
        if not isTradingDay
            inRegular := false
        else
            int currentHour = hour(timeToCheck)
            int currentMinute = minute(timeToCheck)
            int currentMinutesFromMidnight = currentHour * 60 + currentMinute
            
            int regularStartMinutes = 9 * 60 + 30  // Default: 09:30
            int regularEndMinutes = 16 * 60        // Default: 16:00

            // Only use custom session hours when NOT in native session mode
            if not useNativeSession and not na(sessionStartHour) and not na(sessionEndHour)
                if enableExtendedHours
                    regularStartMinutes := 9 * 60 + 30
                    regularEndMinutes := 16 * 60
                else
                    regularStartMinutes := sessionStartHour * 60 + sessionStartMinute
                    regularEndMinutes := sessionEndHour * 60 + sessionEndMinute

            inRegular := currentMinutesFromMidnight >= regularStartMinutes and currentMinutesFromMidnight <= regularEndMinutes
    else if syminfo.type == "crypto"
        inRegular := true  // Crypto is always "regular" (24/7)
    else
        inRegular := true
    
    inRegular

// ========================================= NEW DAY/SESSION RESET ===================================
isNewSession = false
isNewDay = false

// Special reset logic for E-mini Electronic Full Day mode
// ORB resets daily at 9:30 AM ET, even though trading is 24/7
if useElectronicFullDay
    // Get current and previous bar times in sessionTimezone (America/New_York for E-minis)
    int currentHour = hour(time, sessionTimezone)
    int currentMinute = minute(time, sessionTimezone)
    int prevHour = hour(time[1], sessionTimezone)
    int prevMinute = minute(time[1], sessionTimezone)

    // Calculate minutes from midnight for easier comparison
    int currentMinutesFromMidnight = currentHour * 60 + currentMinute
    int prevMinutesFromMidnight = prevHour * 60 + prevMinute
    int resetTimeMinutes = 9 * 60 + 30  // 9:30 AM = 570 minutes

    // Check if we crossed the 9:30 AM threshold
    // Current bar is at or after 9:30, previous bar was before 9:30
    bool nowAfter930 = currentMinutesFromMidnight >= resetTimeMinutes
    bool prevBefore930 = prevMinutesFromMidnight < resetTimeMinutes

    isNewSession := nowAfter930 and prevBefore930
    isNewDay := false  // Don't use day change logic for Electronic Full Day
else if is24_7Market
    currentDay = dayofmonth(time)
    prevDay = dayofmonth(time[1])
    isNewDay := currentDay != prevDay
    isNewSession := false
else
    isNewSession := inSession and not inSession[1]
    isNewDay := ta.change(dayofweek) != 0

shouldReset = isNewSession or isNewDay

if shouldReset

    hadSessionToday := false

    orbNavigationCached := false
    if shouldReset
        hadSessionToday := false
        orbNavigationCached := false
        wentFarEnoughUp := false
        wentFarEnoughDown := false

    for i = 0 to array.size(allORBs) - 1
        orbObj = array.get(allORBs, i)
        if orbObj.minutes == 5
            orbObj.high := high
            orbObj.low := low
            orbObj.mid := hl2
            orbObj.orbRange := 0
        else
            orbObj.high := na
            orbObj.low := na
            orbObj.mid := na
            orbObj.orbRange := 0
        orbObj.isBuilding := true
        orbObj.isComplete := false
        orbObj.completionBar := 0
        orbObj.breakoutUp := false
        orbObj.breakoutDown := false
        orbObj.breakoutBar := 0
        orbObj.breakoutLevel := na
        orbObj.cyclesUp := 0
        orbObj.cyclesDown := 0

        if not na(orbObj.orbBox)
            box.delete(orbObj.orbBox)
        if not na(orbObj.highLine)
            line.delete(orbObj.highLine)
        if not na(orbObj.lowLine)
            line.delete(orbObj.lowLine)
        if not na(orbObj.midLine)
            line.delete(orbObj.midLine)
        if not na(orbObj.edgeLabel)
            label.delete(orbObj.edgeLabel)

        orbObj.orbBox := na
        orbObj.highLine := na
        orbObj.lowLine := na
        orbObj.midLine := na
        orbObj.edgeLabel := na

    activeORB := na
    actH := na
    actL := na
    actM := na

    tradeOrbHigh := na
    tradeOrbLow := na

    tradeOrbHigh := na
    tradeOrbLow := na
    haveRange := false
    haveDisplayRange := false
    stage := 0
    displayH := na
    displayL := na
    breakUpBarIndex := 0
    breakDownBarIndex := 0

    cyclesUp := 0
    cyclesDown := 0
    retestCyclesUp := 0
    retestCyclesDown := 0
    barsOutsideAfterBreakUp := 0
    barsOutsideAfterBreakDown := 0
    wentFarEnoughUp := false
    wentFarEnoughDown := false

    sessionBreakoutsUp := 0
    sessionBreakoutsDown := 0
    sessionRetestsUp := 0
    sessionRetestsDown := 0

    // daily counters reset removed

    session_wins := 0
    session_losses := 0
    session_total_rr := 0.0
    session_trades := 0
    session_best_r := 0.0
    session_worst_r := 0.0
    trade_closed := false
    last_trade_result := ""

    current_trade_r := 0.0
    tp1_counted := false
    tp1_5_counted := false
    tp2_counted := false
    tp3_counted := false

    prevOrbEntryBar := na

    sessionStartBar := na
    sessionStartTime := na
    
    cachedLineColor := na
    cachedStageName := na
    
    lastLabelH := na
    lastLabelL := na
    lastLabelStage := na
    
    if not na(labH)
        label.delete(labH)
        labH := na
    if not na(labL)
        label.delete(labL)
        labL := na

    hadBreakUp := false
    hadBreakDown := false
    breakUpBar := na
    breakDownBar := na
    shownBreakUpLabel := false
    shownBreakDownLabel := false        
    everHadBreakUp := false
    everHadBreakDown := false
    breakoutEntryPrice := na
    hadRetestUp := false
    hadRetestDown := false
    retestUpBar := na
    retestDownBar := na
    lastLabelStage := na

    pendingLongEntry := false
    pendingShortEntry := false
    pendingLongBar := na
    pendingShortBar := na

    if not na(orbEntryLine)
        line.delete(orbEntryLine)
        orbEntryLine := na
    if not na(orbEntryLabel)
        label.delete(orbEntryLabel)
        orbEntryLabel := na
    if not na(orbSLLine)
        line.delete(orbSLLine)
        orbSLLine := na
    if not na(orbSLLabel)
        label.delete(orbSLLabel)
        orbSLLabel := na
    if not na(orbTP1Line)
        line.delete(orbTP1Line)
        orbTP1Line := na
    if not na(orbTP1Label)
        label.delete(orbTP1Label)
        orbTP1Label := na
    if not na(orbTP1_5Line)
        line.delete(orbTP1_5Line)
        orbTP1_5Line := na
    if not na(orbTP1_5Label)
        label.delete(orbTP1_5Label)
        orbTP1_5Label := na
    if not na(orbTP2Line)
        line.delete(orbTP2Line)
        orbTP2Line := na
    if not na(orbTP2Label)
        label.delete(orbTP2Label)
        orbTP2Label := na
    if not na(orbTP3Line)
        line.delete(orbTP3Line)
        orbTP3Line := na
    if not na(orbTP3Label)
        label.delete(orbTP3Label)
        orbTP3Label := na
    
    orbEntryPrice := na
    orbEntryBar := na
    orbLineColor := na
    orbSLPrice := na
    orbTP1Price := na
    orbTP1_5Price := na
    orbTP2Price := na
    orbTP3Price := na
    orbLinesFrozen := false
    orbTP1Hit := false
    orbTP1_5Hit := false
    orbTP2Hit := false
    orbTP3Hit := false
    orbSLHit := false
    orbTradeDirection := 0

    current_trade_r := 0.0
    tp1_counted := false
    tp1_5_counted := false
    tp2_counted := false
    tp3_counted := false

    maxShares := na
    positionValue := na
    maxLoss := na

    lastDashUpdateBar := bar_index - 100

// ========================================= TIME CALCULATION ========================================
var float sessionFirstBarTime = na

if inSession and na(sessionStartTime)
    sessionStartBar := bar_index
    sessionStartTime := time
    sessionFirstBarTime := time
    hadSessionToday := true// Track session start time and bar when new session is detected
if isNewSession
    sessionStartBar := bar_index
    sessionStartTime := time
    sessionFirstBarTime := time  // Reset first bar time for new session
    hadSessionToday := true  // Mark that session started today

float minsFromOpen = -1.0

if not na(sessionFirstBarTime) and inSession
    minsFromOpen := (time - sessionFirstBarTime) / 60000   
    if minsFromOpen > 480
        minsFromOpen := 480  
    if minsFromOpen < 0
        minsFromOpen := 0

// ===================================== GLOBAL CACHE (PERFORMANCE) ==================================
if barstate.isconfirmed or barstate.islast
    bool needATR = everHadBreakUp or everHadBreakDown or showDashboard or not na(activeORB)
    if needATR and bar_index != cachedATRBar
        cachedATR := ta.atr(atrLength)
        cachedATRBar := bar_index
    
    if bar_index != cachedVolumeMABar
        cachedVolumeMA := ta.sma(volume, volumeMaLength)
        cachedVolumeMABar := bar_index
 
// ======================================= ORB LEVEL BUILDING ========================================
currentTF_seconds = timeframe.in_seconds()
isHTF = currentTF_seconds >= 86400

// ========================================== GOD MODE CONTEXT =======================================
// Daily levels from the previous COMPLETED day (offset [1] = no repaint) + daily ATR for OR-quality scoring
[godPrevDayHigh, godPrevDayLow, godPrevDayClose, godDailyATR] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1], ta.atr(14)[1]], barmerge.gaps_off, barmerge.lookahead_off)

var float godPmHigh = na
var float godPmLow = na
var float godSessionOpen = na
var int godFailedBreaks = 0
var float godLastScore = na
var string godLastScoreDir = ""

if shouldReset
    godSessionOpen := open
    godFailedBreaks := 0
    godLastScore := na
    godLastScoreDir := ""

if godModeEnabled and not isHTF
    if ta.change(time("D")) != 0
        godPmHigh := na
        godPmLow := na
    if not inSession
        godPmHigh := math.max(nz(godPmHigh, high), high)
        godPmLow := math.min(nz(godPmLow, low), low)

float godGapPct = godModeEnabled and not na(godSessionOpen) and not na(godPrevDayClose) and godPrevDayClose > 0 ? (godSessionOpen - godPrevDayClose) / godPrevDayClose * 100 : na
bool godChopDay = godModeEnabled and godChopGuard and godFailedBreaks >= 2


// ============================== NEW ARCHITECTURE: INDEPENDENT ORB BUILDING =========================
if not isHTF and minsFromOpen >= 0 and (barstate.isconfirmed or barstate.islast) and inSession
    for i = 0 to array.size(allORBs) - 1
        orbObj = array.get(allORBs, i)

        if orbObj.isEnabled and orbObj.isBuilding
            if minsFromOpen > orbObj.minutes
                orbObj.isBuilding := false
                orbObj.isComplete := true
                orbObj.completionBar := bar_index

                if na(activeORB) or orbObj.minutes > activeORB.minutes
                    activeORB := orbObj
                    actH := orbObj.high
                    actL := orbObj.low
                    actM := orbObj.mid
                    haveRange := true
                    haveDisplayRange := true
                    stage := orbObj.minutes
                    displayH := orbObj.high
                    displayL := orbObj.low
                    cachedStageName := orbObj.name
                    cachedLineColor := orbObj.orbColor

            else

                if na(orbObj.high)
                    prevOrb = getPreviousEnabledORB(orbObj)
                    if not na(prevOrb) and prevOrb.isComplete
                        orbObj.high := prevOrb.high
                        orbObj.low := prevOrb.low
                        orbObj.mid := prevOrb.mid
                        orbObj.orbRange := prevOrb.orbRange

                if minsFromOpen < orbObj.minutes
                    orbObj.high := math.max(nz(orbObj.high, high), high)
                    orbObj.low := math.min(nz(orbObj.low, low), low)
                    orbObj.mid := (orbObj.high + orbObj.low) / 2
                    orbObj.orbRange := orbObj.high - orbObj.low

                    if minsFromOpen >= orbObj.minutes - 1 and not orbObj.isComplete
                        orbObj.isBuilding := false
                        orbObj.isComplete := true
                        orbObj.completionBar := bar_index

                        activeORB := orbObj

                        actH := orbObj.high
                        actL := orbObj.low
                        actM := orbObj.mid
                        haveRange := true
                        haveDisplayRange := true

                        stage := orbObj.minutes
                        displayH := orbObj.high
                        displayL := orbObj.low
                        cachedStageName := orbObj.name
                        cachedLineColor := orbObj.orbColor

// ================================== CACHE ORB NAVIGATION (PERFORMANCE) =============================
if not orbNavigationCached and not isHTF
    for i = 0 to array.size(allORBs) - 1
        orbObj = array.get(allORBs, i)

        ORBData prevOrb = na
        for j = 0 to array.size(allORBs) - 1
            checkOrb = array.get(allORBs, j)
            if checkOrb.isEnabled and checkOrb.minutes < orbObj.minutes
                if na(prevOrb) or checkOrb.minutes > prevOrb.minutes
                    prevOrb := checkOrb
        array.set(cachedPrevORBs, i, prevOrb)
 
        ORBData nextOrb = na
        for j = 0 to array.size(allORBs) - 1
            checkOrb = array.get(allORBs, j)
            if checkOrb.isEnabled and checkOrb.minutes > orbObj.minutes
                if na(nextOrb) or checkOrb.minutes < nextOrb.minutes
                    nextOrb := checkOrb
        array.set(cachedNextORBs, i, nextOrb)
    
    orbNavigationCached := true

// ===================================== STAGE & COLOR MANAGEMENT ====================================
for i = 0 to array.size(allORBs) - 1
    orbObj = array.get(allORBs, i)
    if orbObj.isEnabled and orbObj.isComplete and orbObj.completionBar == bar_index
        rangeSize = orbObj.high - orbObj.low
        rangePct = (rangeSize / orbObj.low) * 100
        alertMsgStageComplete := "✅ " + orbObj.name + " COMPLETE - " + syminfo.ticker + " | Range: $" + str.tostring(orbObj.high, "#.##") + " - $" + str.tostring(orbObj.low, "#.##") + " (" + str.tostring(rangePct, "#.#") + "%)"
        sendAlert(alertMsgStageComplete)
        alertStageCompleteTriggered := true


// ======================================= TREND CALCULATION ========================================
if enableTrendFilter
    if str.contains(trendMode, "VWAP")
        trendVWAP := ta.vwap(close)
    
    if trendMode == "EMA" or trendMode == "VWAP+EMA"
        trendEMA12 := ta.ema(close, 12)
    
    if trendMode == "Custom EMA"
        trendEMACustom := ta.ema(close, customEmaLength)
    
    if str.contains(trendMode, "SuperTrend")
        if barstate.isnew or na(trendSTUp)
            [stLower, stUpper, stDir] = calcSuperTrend(supertrendPeriod, supertrendMult)
            trendSTUp := stLower
            trendSTDown := stUpper
            trendSTDirection := stDir

// ========================================== GOD MODE SCORING =======================================
f_nearLvl(lvl, ref, tol) => not na(lvl) and not na(ref) and math.abs(lvl - ref) <= tol
f_godGrade(s) => s >= 85 ? "A+" : s >= 70 ? "A" : s >= 55 ? "B" : s >= 40 ? "C" : "D"

float godLvlTol = nz(cachedATR) * 0.25
bool godHighConfluence = godModeEnabled and haveRange and (f_nearLvl(actH, godPrevDayHigh, godLvlTol) or f_nearLvl(actH, godPmHigh, godLvlTol))
bool godLowConfluence = godModeEnabled and haveRange and (f_nearLvl(actL, godPrevDayLow, godLvlTol) or f_nearLvl(actL, godPmLow, godLvlTol))

f_godScore(bool isUp) =>
    float score = 50.0
    float volRatio = nz(cachedVolumeMA) > 0 ? volume / cachedVolumeMA : 1.0
    score += volRatio >= strongVolumeMultiplier ? 20 : volRatio >= volumeMultiplier ? 12 : volRatio >= 1.0 ? 4 : -10
    score += isUp ? (htfBullish ? 15 : htfBearish ? -15 : 0) : (htfBearish ? 15 : htfBullish ? -15 : 0)
    float orVsAtr = not na(godDailyATR) and godDailyATR > 0 and not na(activeORB) ? activeORB.orbRange / godDailyATR : na
    score += na(orVsAtr) ? 0 : orVsAtr <= 0.25 ? 10 : orVsAtr <= 0.5 ? 5 : orVsAtr <= 0.75 ? 0 : -10
    float gapAligned = na(godGapPct) ? na : isUp ? godGapPct : -godGapPct
    score += na(gapAligned) ? 0 : gapAligned >= 0.5 ? 8 : gapAligned <= -0.5 ? -8 : 0
    score += (isUp ? godHighConfluence : godLowConfluence) ? 12 : 0
    int priorBreaks = (isUp ? sessionBreakoutsUp : sessionBreakoutsDown) - 1
    score -= math.min(math.max(priorBreaks, 0) * 5, 15)
    if godChopDay
        score := math.min(score, 40)
    math.max(0.0, math.min(100.0, score))

// ====================================== BREAKOUT DETECTION =========================================
canDetectBreakout = not isHTF and enableBreakout and not na(activeORB) and barstate.isconfirmed
volumeMA := cachedVolumeMA

// ============================= PENDING ENTRY PROCESSING (NEXT BAR AFTER BREAKOUT) ================
bool pendingLongDue = pendingLongEntry and bar_index > pendingLongBar
bool pendingShortDue = pendingShortEntry and bar_index > pendingShortBar
bool entryIsLong = pendingLongDue and not pendingShortDue  // both due -> short wins (matches old sequential overwrite)

if pendingLongDue or pendingShortDue
    if enableTargets
        // Get active ORB levels
        float activeHigh = not na(activeORB) ? activeORB.high : na
        float activeLow = not na(activeORB) ? activeORB.low : na

        if not na(activeHigh) and not na(activeLow)
            // Delete old lines first
            if not na(orbEntryLine)
                line.delete(orbEntryLine)
                orbEntryLine := na
            if not na(orbEntryLabel)
                label.delete(orbEntryLabel)
                orbEntryLabel := na
            if not na(orbSLLine)
                line.delete(orbSLLine)
                orbSLLine := na
            if not na(orbSLLabel)
                label.delete(orbSLLabel)
                orbSLLabel := na
            if not na(orbTP1Line)
                line.delete(orbTP1Line)
                orbTP1Line := na
            if not na(orbTP1Label)
                label.delete(orbTP1Label)
                orbTP1Label := na
            if not na(orbTP1_5Line)
                line.delete(orbTP1_5Line)
                orbTP1_5Line := na
            if not na(orbTP1_5Label)
                label.delete(orbTP1_5Label)
                orbTP1_5Label := na
            if not na(orbTP2Line)
                line.delete(orbTP2Line)
                orbTP2Line := na
            if not na(orbTP2Label)
                label.delete(orbTP2Label)
                orbTP2Label := na
            if not na(orbTP3Line)
                line.delete(orbTP3Line)
                orbTP3Line := na
            if not na(orbTP3Label)
                label.delete(orbTP3Label)
                orbTP3Label := na

            float entry = open
            float atr = cachedATR
            float sl = calculateStopLoss(entry, activeHigh, activeLow, activeHigh - activeLow, atr, stopMode, entryIsLong)
            [tp1, tp1_5, tp2, tp3] = calculateTargets(entry, sl, entryIsLong)

            [shares, posValue, maxLossCalc, riskAmount] = calculatePositionSize(entry, sl)

            orbEntryPrice := entry
            breakoutEntryPrice := entry  // Sync with global entry price
            orbEntryBar := bar_index
            orbLineColor := entryIsLong ? color.new(color.aqua, 0) : color.new(color.orange, 0)
            orbSLPrice := sl
            orbTP1Price := tp1
            orbTP1_5Price := tp1_5
            orbTP2Price := tp2
            orbTP3Price := tp3
            orbLinesFrozen := false
            orbTP1Hit := false
            orbTP1_5Hit := false
            orbTP2Hit := false
            orbTP3Hit := false
            orbSLHit := false
            orbTradeDirection := entryIsLong ? 1 : -1

            maxShares := shares
            positionValue := posValue
            maxLoss := maxLossCalc

            // Entry line - ALWAYS shown
            orbEntryLine := line.new(orbEntryBar, orbEntryPrice, bar_index, orbEntryPrice, xloc=xloc.bar_index, extend=extend.none, color=orbLineColor, width=1, style=line.style_solid)
            cleanupLine(orbEntryLine)
            string entryText = labelFormat == "Simple" ? "ENTRY" : str.format("ENTRY: ${0}", str.tostring(orbEntryPrice, "#.##"))
            orbEntryLabel := label.new(orbEntryBar, orbEntryPrice, entryText, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=orbLineColor, size=getLabelSize(labelSize))

            // SL and TP lines - only if showTPSLLines is enabled
            if showTPSLLines
                orbSLLine := line.new(orbEntryBar, orbSLPrice, bar_index, orbSLPrice, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.red, 0), width=1, style=line.style_solid)
                cleanupLine(orbSLLine)
                string slText = labelFormat == "Simple" ? "SL" : str.format("SL: ${0}", str.tostring(orbSLPrice, "#.##"))
                orbSLLabel := label.new(orbEntryBar, orbSLPrice, slText, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(color.red, 0), size=getLabelSize(labelSize))

                if showTP1
                    orbTP1Line := line.new(orbEntryBar, orbTP1Price, bar_index, orbTP1Price, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.green, 0), width=1, style=line.style_solid)
                    cleanupLine(orbTP1Line)
                    float tp1Pct = ((entryIsLong ? orbTP1Price - entry : entry - orbTP1Price) / entry) * 100
                    string tp1Text = labelFormat == "Simple" ? "TP1" : str.format("TP1: ${0} +{1}%", str.tostring(orbTP1Price, "#.##"), str.tostring(tp1Pct, "#.#"))
                    orbTP1Label := label.new(orbEntryBar, orbTP1Price, tp1Text, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(color.green, 0), size=getLabelSize(labelSize))

                if showTP1_5
                    orbTP1_5Line := line.new(orbEntryBar, orbTP1_5Price, bar_index, orbTP1_5Price, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.green, 0), width=1, style=line.style_solid)
                    cleanupLine(orbTP1_5Line)
                    float tp1_5Pct = ((entryIsLong ? orbTP1_5Price - entry : entry - orbTP1_5Price) / entry) * 100
                    string tp1_5Text = labelFormat == "Simple" ? "TP1.5" : str.format("TP1.5: ${0} +{1}%", str.tostring(orbTP1_5Price, "#.##"), str.tostring(tp1_5Pct, "#.#"))
                    orbTP1_5Label := label.new(orbEntryBar, orbTP1_5Price, tp1_5Text, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(color.green, 0), size=getLabelSize(labelSize))

                if showTP2
                    orbTP2Line := line.new(orbEntryBar, orbTP2Price, bar_index, orbTP2Price, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.green, 0), width=1, style=line.style_solid)
                    cleanupLine(orbTP2Line)
                    float tp2Pct = ((entryIsLong ? orbTP2Price - entry : entry - orbTP2Price) / entry) * 100
                    string tp2Text = labelFormat == "Simple" ? "TP2" : str.format("TP2: ${0} +{1}%", str.tostring(orbTP2Price, "#.##"), str.tostring(tp2Pct, "#.#"))
                    orbTP2Label := label.new(orbEntryBar, orbTP2Price, tp2Text, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(color.green, 0), size=getLabelSize(labelSize))

                if showTP3
                    orbTP3Line := line.new(orbEntryBar, orbTP3Price, bar_index, orbTP3Price, xloc=xloc.bar_index, extend=extend.none, color=color.new(color.green, 0), width=1, style=line.style_solid)
                    cleanupLine(orbTP3Line)
                    float tp3Pct = ((entryIsLong ? orbTP3Price - entry : entry - orbTP3Price) / entry) * 100
                    string tp3Text = labelFormat == "Simple" ? "TP3" : str.format("TP3: ${0} +{1}%", str.tostring(orbTP3Price, "#.##"), str.tostring(tp3Pct, "#.#"))
                    orbTP3Label := label.new(orbEntryBar, orbTP3Price, tp3Text, xloc=xloc.bar_index, style=label.style_label_left, textcolor=color.white, color=color.new(color.green, 0), size=getLabelSize(labelSize))

    // Trigger entry alert
    alertEntryTriggered := true

    if pendingLongDue
        pendingLongEntry := false
        pendingLongBar := na
    if pendingShortDue
        pendingShortEntry := false
        pendingShortBar := na

[bullFVG, bullTop, bullBottom] = detectBullishFVG()
[bearFVG, bearTop, bearBottom] = detectBearishFVG()

if bullFVG and showFVG and not na(activeORB)
    fvgBox = box.new(left=bar_index-2, top=bullTop, right=bar_index, bottom=bullBottom,
                     border_color=color.new(fvgBullColor, 0),
                     bgcolor=color.new(fvgBullColor, fvgTransparency),
                     border_width=1,
                     extend=extend.none)  // Changed from extend.right to extend.none
    array.push(fvgBoxes, fvgBox)
    array.push(fvgTops, bullTop)
    array.push(fvgBottoms, bullBottom)
    array.push(fvgIsBullish, true)
    array.push(fvgIsActive, true)
    array.push(fvgStartBar, bar_index-2)
    cleanupOldFVG()

if bearFVG and showFVG and not na(activeORB)
    fvgBox = box.new(left=bar_index-2, top=bearTop, right=bar_index, bottom=bearBottom,
                     border_color=color.new(fvgBearColor, 0),
                     bgcolor=color.new(fvgBearColor, fvgTransparency),
                     border_width=1,
                     extend=extend.none)  // Changed from extend.right to extend.none 
    array.push(fvgBoxes, fvgBox)
    array.push(fvgTops, bearTop)
    array.push(fvgBottoms, bearBottom)
    array.push(fvgIsBullish, false)
    array.push(fvgIsActive, true)
    array.push(fvgStartBar, bar_index-2)
    cleanupOldFVG()

if showFVG and array.size(fvgBoxes) > 0 and (barstate.isnew or barstate.islast)
    for i = 0 to array.size(fvgBoxes) - 1
        if array.get(fvgIsActive, i)
            fvgTop = array.get(fvgTops, i)
            fvgBottom = array.get(fvgBottoms, i)
            isBull = array.get(fvgIsBullish, i)
            startBar = array.get(fvgStartBar, i)
            currentBox = array.get(fvgBoxes, i)
            boxColor = isBull ? fvgBullColor : fvgBearColor

            fvgFilled = false
            if isBull
                fvgFilled := close < fvgBottom
            else
                fvgFilled := close > fvgTop
            
            if not na(currentBox)
                if fvgFilled
                    box.set_right(currentBox, bar_index)
                    box.set_border_style(currentBox, line.style_dashed)
                    array.set(fvgIsActive, i, false)
                    
                    if bar_index - array.get(fvgStartBar, i) > 10
                        box.delete(currentBox)
                        array.set(fvgBoxes, i, na)
                else
                    box.set_right(currentBox, bar_index)

// ======================= NEW ARCHITECTURE: BREAKOUT DETECTION WITH activeORB =======================
if not na(activeORB) and activeORB.isComplete and inSession and enableBreakout and barstate.isconfirmed

    activeHigh = activeORB.high
    activeLow = activeORB.low
    activeMid = activeORB.mid

    float effBreakoutBuffer = godModeEnabled and godAdaptiveBuffer and nz(cachedATR) > 0 and close > 0 ? math.max(breakoutBuffer, cachedATR * 0.10 / close * 100) : breakoutBuffer
    activeBufferUp = getBuffer(activeHigh, effBreakoutBuffer)
    activeBufferDown = getBuffer(activeLow, effBreakoutBuffer)
 
    volumeOK = not enableVolumeFilter or hasVolumeConfirmation(volumeMA, volumeMultiplier, strongVolumeMultiplier)

    trendOK_Up = not enableTrendFilter or isTrendUp(trendMode, close, trendVWAP, trendEMA12, trendEMACustom, trendSTDirection)
    trendOK_Down = not enableTrendFilter or isTrendDown(trendMode, close, trendVWAP, trendEMA12, trendEMACustom, trendSTDirection)

    crossedAbove = close > activeHigh + activeBufferUp and close[1] <= activeHigh + activeBufferUp
    if crossedAbove and volumeOK and trendOK_Up and not activeORB.breakoutUp
        activeORB.breakoutUp := true
        activeORB.breakoutBar := bar_index
        activeORB.breakoutLevel := activeHigh
        activeORB.cyclesUp := activeORB.cyclesUp + 1
        cyclesUp := cyclesUp + 1
        hadRetestUp := false
        wentFarEnoughUp := false

        sessionBreakoutsUp := sessionBreakoutsUp + 1
        if godModeEnabled
            godLastScore := f_godScore(true)
            godLastScoreDir := "UP"
        

        everHadBreakUp := true
        hadBreakUp := true
        breakUpBar := bar_index
        breakUpBarIndex := bar_index
        
        tradeOrbHigh := activeORB.high
        tradeOrbLow := activeORB.low
        
        if showBreakLabels
            string breakText = ""
            if labelFormat == "Simple"
                breakText := "🔼 BREAKOUT UP #" + str.tostring(sessionBreakoutsUp)
            else  // Detailed
                float volRatio = volumeMA > 0 ? volume / volumeMA : 0
                string volText = volRatio >= strongVolumeMultiplier ? str.tostring(volRatio, "#.#") + "x ⚡" : volRatio >= volumeMultiplier ? str.tostring(volRatio, "#.#") + "x" : str.tostring(volRatio, "#.#") + "x ⚠️"
                breakText := "🔼 BREAKOUT UP\n" + activeORB.name + " #" + str.tostring(sessionBreakoutsUp) + "\nVol: " + volText
            if godModeEnabled and godShowScore and not na(godLastScore)
                breakText += "\n⚡ " + str.tostring(godLastScore, "#") + " (" + f_godGrade(godLastScore) + ")" + (godHighConfluence ? " 🏆" : "")

            float labelOffset = cachedATR * LABEL_OFFSET_ATR_MULTIPLIER
            float labelY = high + labelOffset

            breakLabel = label.new(bar_index, labelY, breakText, color = color.new(color.green, 0), textalign = text.align_center, style = label.style_label_down, textcolor = color.white, size = getLabelSize(labelSize))
            cleanupLabel(breakLabel)

        if enableAlerts and alertBreakouts
            alertMsg = "🔼 BREAKOUT UP" + str.tostring(sessionBreakoutsUp) + " - " + syminfo.ticker + " @ " + str.tostring(close, "#.##") + " | " + activeORB.name + (godModeEnabled and not na(godLastScore) ? " | ⚡" + str.tostring(godLastScore, "#") + " " + f_godGrade(godLastScore) : "")
            sendAlert(alertMsg)
            alertBreakUpTriggered := true  // FIX: Set trigger for TradingView alerts

    // ========== MARK PENDING LONG ENTRY (TP/SL created on NEXT bar) ==========
        pendingLongEntry := true
        pendingLongBar := bar_index

    // === BREAKOUT DOWN (NEW) ===
    crossedBelow = close < activeLow - activeBufferDown and close[1] >= activeLow - activeBufferDown
    
    if crossedBelow and volumeOK and trendOK_Down and not activeORB.breakoutDown
        activeORB.breakoutDown := true
        activeORB.breakoutBar := bar_index
        activeORB.breakoutLevel := activeLow
        activeORB.cyclesDown := activeORB.cyclesDown + 1
        cyclesDown := cyclesDown + 1
        hadRetestDown := false
        wentFarEnoughDown := false

        sessionBreakoutsDown := sessionBreakoutsDown + 1
        if godModeEnabled
            godLastScore := f_godScore(false)
            godLastScoreDir := "DOWN"
        

        everHadBreakDown := true
        hadBreakDown := true
        breakDownBar := bar_index
        breakDownBarIndex := bar_index

        tradeOrbHigh := activeORB.high
        tradeOrbLow := activeORB.low

        if showBreakLabels
            string breakText = ""
            if labelFormat == "Simple"
                breakText := "🔽 BREAKOUT DOWN #" + str.tostring(sessionBreakoutsDown)
            else  // Detailed
                float volRatio = volumeMA > 0 ? volume / volumeMA : 0
                string volText = volRatio >= strongVolumeMultiplier ? str.tostring(volRatio, "#.#") + "x ⚡" : volRatio >= volumeMultiplier ? str.tostring(volRatio, "#.#") + "x" : str.tostring(volRatio, "#.#") + "x ⚠️"
                breakText := "🔽 BREAKOUT DOWN\n" + activeORB.name + " | #" + str.tostring(sessionBreakoutsDown) + "\nVol: " + volText
            if godModeEnabled and godShowScore and not na(godLastScore)
                breakText += "\n⚡ " + str.tostring(godLastScore, "#") + " (" + f_godGrade(godLastScore) + ")" + (godLowConfluence ? " 🏆" : "")
            
            float labelOffset = cachedATR * LABEL_OFFSET_ATR_MULTIPLIER
            float labelY = low - labelOffset

            breakLabel = label.new(bar_index, labelY, breakText, color = color.new(color.red, 0), style = label.style_label_up, textalign = text.align_center, textcolor = color.white, size = getLabelSize(labelSize)) 
            cleanupLabel(breakLabel)

        if enableAlerts and alertBreakouts
            alertMsg = "🔽 BREAKOUT DOWN #" + str.tostring(sessionBreakoutsDown) + " - " + syminfo.ticker + " @ " + str.tostring(close, "#.##") + " | " + activeORB.name + (godModeEnabled and not na(godLastScore) ? " | ⚡" + str.tostring(godLastScore, "#") + " " + f_godGrade(godLastScore) : "")
            sendAlert(alertMsg)
            alertBreakDownTriggered := true  // FIX: Set trigger for TradingView alerts

        pendingShortEntry := true
        pendingShortBar := bar_index 


// ====================================== BARS OUTSIDE TRACKING ======================================
if not isHTF and barstate.isconfirmed
    
    if hadBreakUp and bar_index > breakUpBarIndex
        if close > tradeOrbHigh
            barsOutsideAfterBreakUp += 1
            
            minRetestDistance = tradeOrbHigh * (minRetestDistancePct / 100)
            if close > tradeOrbHigh + minRetestDistance
                wentFarEnoughUp := true
        else
            barsOutsideAfterBreakUp := 0

    if hadBreakDown and bar_index > breakDownBarIndex
        if close < tradeOrbLow
            barsOutsideAfterBreakDown += 1
            
            minRetestDistance = tradeOrbLow * (minRetestDistancePct / 100)
            if close < tradeOrbLow - minRetestDistance
                wentFarEnoughDown := true
        else
            barsOutsideAfterBreakDown := 0

// ======================================= RETEST DETECTION ==========================================
if not isHTF and enableRetest and haveRange and barstate.isconfirmed
        
    retestBufferCalc = getBuffer(actH, retestBuffer)
        
    if hadBreakUp and not hadRetestUp
        wentFarEnough = wentFarEnoughUp
        
        isCommittedBreakout = barsOutsideAfterBreakUp >= minBarsOutside
        
        priceBackInside = close < tradeOrbHigh + retestBufferCalc and close > tradeOrbLow - retestBufferCalc
        
        barsSinceBreak = bar_index - breakUpBarIndex
        isFailedBreak = everHadBreakUp and barsSinceBreak > 0 and barsSinceBreak <= MAX_BARS_FAILED_BREAK and priceBackInside and not isCommittedBreakout
        if isFailedBreak
            if not na(lastBreakUpLabel)
                label.set_text(lastBreakUpLabel, "⚠️ FAILED BREAK")
                label.set_color(lastBreakUpLabel, color.new(color.orange, 0))

            if alertFailedBreaks
                orbStageName = not na(activeORB) ? activeORB.name : "None"
                alertMsgFailedUp := "⚠️ FAILED BREAK UP - " + syminfo.ticker + " @ $" + str.tostring(close, "#.##") + " | " + orbStageName + " - Price back inside range after " + str.tostring(barsSinceBreak) + " bars"
                sendAlert(alertMsgFailedUp)
                alertFailedUpTriggered := true
            
            

            if cyclesUp > 0
                cyclesUp -= 1
            
            godFailedBreaks += 1
            hadBreakUp := false
            barsOutsideAfterBreakUp := 0
            if not na(activeORB)
                activeORB.breakoutUp := false
        
        else if wentFarEnough and priceBackInside and isCommittedBreakout
            hadRetestUp := true
            retestUpBar := bar_index
            barsOutsideAfterBreakUp := 0
            
            if signalMode == "Track Cycles"
                hadBreakUp := false
                if not na(activeORB)
                    activeORB.breakoutUp := false

            showRetestLabel = true
            if signalMode == "Track Cycles"
                showRetestLabel := retestCyclesUp < maxCycles
            
            if showRetestLabel
                retestCyclesUp += 1
                sessionRetestsUp += 1
                
                retestText = str.format("🔁 RETEST UP #{0}", str.tostring(sessionRetestsUp))
                float labelOffset = cachedATR * LABEL_OFFSET_ATR_MULTIPLIER
                float labelY = high + labelOffset
                retestLabel = label.new(bar_index, labelY, retestText,
                          style=label.style_label_down,
                          color=color.new(color.orange, 20),
                          textcolor=color.white,
                          size=getLabelSize(labelSize))
                cleanupLabel(retestLabel)

                if alertRetests
                    orbStageName = not na(activeORB) ? activeORB.name : "None"
                    alertMsgRetestUp := "🔁 RETEST UP #" + str.tostring(retestCyclesUp) + " - " + syminfo.ticker + " @ $" + str.tostring(close, "#.##") + " | Back to " + orbStageName + " range"
                    sendAlert(alertMsgRetestUp)
                    alertRetestUpTriggered := true
                    
    if hadBreakDown and not hadRetestDown
        wentLowEnough = wentFarEnoughDown       
        isCommittedBreakout = barsOutsideAfterBreakDown >= minBarsOutside       
        priceBackInside = close > tradeOrbLow - retestBufferCalc and close < tradeOrbHigh + retestBufferCalc
        
        barsSinceBreak = bar_index - breakDownBarIndex
        isFailedBreak = everHadBreakDown and barsSinceBreak > 0 and barsSinceBreak <= MAX_BARS_FAILED_BREAK and priceBackInside and not isCommittedBreakout
        if isFailedBreak
            if not na(lastBreakDownLabel)
                label.set_text(lastBreakDownLabel, "⚠️ FAILED BREAK")
                label.set_color(lastBreakDownLabel, color.new(color.orange, 0))
            
            if alertFailedBreaks
                orbStageName = not na(activeORB) ? activeORB.name : "None"
                alertMsgFailedDown := "⚠️ FAILED BREAK DOWN - " + syminfo.ticker + " @ $" + str.tostring(close, "#.##") + " | " + orbStageName + " - Price back inside range after " + str.tostring(barsSinceBreak) + " bars"
                sendAlert(alertMsgFailedDown)
                alertFailedDownTriggered := true
            
            

            if cyclesDown > 0
                cyclesDown -= 1
            
            godFailedBreaks += 1
            hadBreakDown := false
            barsOutsideAfterBreakDown := 0
            if not na(activeORB)
                activeORB.breakoutDown := false
        
        else if wentLowEnough and priceBackInside and isCommittedBreakout
            hadRetestDown := true
            retestDownBar := bar_index
            barsOutsideAfterBreakDown := 0
            
            if signalMode == "Track Cycles"
                hadBreakDown := false
                if not na(activeORB)
                    activeORB.breakoutDown := false
            
            showRetestLabel = true
            if signalMode == "Track Cycles"
                showRetestLabel := retestCyclesDown < maxCycles
            
            if showRetestLabel
                retestCyclesDown += 1
                sessionRetestsDown += 1
                
                retestText = str.format("🔁 RETEST DOWN #{0}", str.tostring(sessionRetestsDown))
                
                float labelOffset = cachedATR * LABEL_OFFSET_ATR_MULTIPLIER
                float labelY = low - labelOffset
                retestLabel = label.new(bar_index, labelY, retestText,
                          style=label.style_label_up,
                          color=color.new(color.orange, 20),
                          textcolor=color.white,
                          size=getLabelSize(labelSize))
                cleanupLabel(retestLabel)

                if alertRetests
                    orbStageName = not na(activeORB) ? activeORB.name : "None"
                    alertMsgRetestDown := "🔁 RETEST DOWN #" + str.tostring(retestCyclesDown) + " - " + syminfo.ticker + " @ $" + str.tostring(close, "#.##") + " | Back to " + orbStageName + " range"
                    sendAlert(alertMsgRetestDown)
                    alertRetestDownTriggered := true

isBullish = everHadBreakUp
entry = orbEntryPrice
sl = orbSLPrice
tp1 = orbTP1Price
tp1_5 = orbTP1_5Price
tp2 = orbTP2Price
tp3 = orbTP3Price
atr = cachedATR

// ========================================== EDGE LABELS ============================================
if not isHTF and showEdgeLabels and haveDisplayRange

    stageChanged = stage != lastLabelStage
    priceChangedH = displayH != lastLabelH
    priceChangedL = displayL != lastLabelL
    labelsExist = not na(labH) and not na(labL)
    needsUpdate = stageChanged or priceChangedH or priceChangedL or not labelsExist
    
    if needsUpdate
        labelColor = color.new(cachedLineColor, 0)
        
        if na(labH)
            labH := label.new(bar_index + LABEL_OFFSET_BARS, displayH, cachedStageName, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_left, color=labelColor, textcolor=color.white, size=getLabelSize(labelSize))
        else
            label.set_y(labH, displayH)
            if stageChanged
                label.set_text(labH, cachedStageName)
                label.set_color(labH, labelColor)
        
        if na(labL)
            labL := label.new(bar_index + LABEL_OFFSET_BARS, displayL, cachedStageName, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_left, color=labelColor, textcolor=color.white, size=getLabelSize(labelSize))
        else
            label.set_y(labL, displayL)
            if stageChanged
                label.set_text(labL, cachedStageName)
                label.set_color(labL, labelColor)
        
        lastLabelH := displayH
        lastLabelL := displayL
        lastLabelStage := stage
    
    if barstate.islast and not isHTF and haveDisplayRange
        if not na(labH)
            label.set_x(labH, bar_index + LABEL_OFFSET_BARS)
        if not na(labL)
            label.set_x(labL, bar_index + LABEL_OFFSET_BARS)


// ================================ TP/SL LINES UPDATE LOOP ==========================================
if not orbLinesFrozen and not na(orbEntryBar) and bar_index >= orbEntryBar
    if not na(orbEntryLine)
        line.set_x2(orbEntryLine, bar_index)
    if not na(orbEntryLabel)
        label.set_x(orbEntryLabel, bar_index)

    if not na(orbSLLine)
        line.set_x2(orbSLLine, bar_index)
    if not na(orbSLLabel)
        label.set_x(orbSLLabel, bar_index)

    if not na(orbTP1Line)
        line.set_x2(orbTP1Line, bar_index)
    if not na(orbTP1Label)
        label.set_x(orbTP1Label, bar_index)

    if not na(orbTP1_5Line)
        line.set_x2(orbTP1_5Line, bar_index)
    if not na(orbTP1_5Label)
        label.set_x(orbTP1_5Label, bar_index)

    if not na(orbTP2Line)
        line.set_x2(orbTP2Line, bar_index)
    if not na(orbTP2Label)
        label.set_x(orbTP2Label, bar_index)

    if not na(orbTP3Line)
        line.set_x2(orbTP3Line, bar_index)
    if not na(orbTP3Label)
        label.set_x(orbTP3Label, bar_index)

if not orbLinesFrozen and not na(orbEntryPrice) and (barstate.isconfirmed or barstate.islast)

    bool isLongTrade = orbTradeDirection == 1

    if not orbTP1Hit and not na(orbTP1Price) and showTP1 and bar_index >= orbEntryBar and (isLongTrade ? high >= orbTP1Price : low <= orbTP1Price)
        orbTP1Hit := true
        alertTP1Triggered := true  // Trigger TP1 alert
        if not na(orbTP1Label)
            string tp1Text = labelFormat == "Simple" ? "✅ TP1" : str.format("✅ TP1: ${0}", str.tostring(orbTP1Price, "#.##"))
            label.set_text(orbTP1Label, tp1Text)
            label.set_color(orbTP1Label, color.new(color.green, 0))
        if not na(orbTP1Line)
            line.set_color(orbTP1Line, color.new(color.green, 0))

    if not orbTP1_5Hit and not na(orbTP1_5Price) and showTP1_5 and bar_index >= orbEntryBar and (isLongTrade ? high >= orbTP1_5Price : low <= orbTP1_5Price)
        orbTP1_5Hit := true
        alertTP1_5Triggered := true  // Trigger TP1.5 alert
        if not na(orbTP1_5Label)
            string tp1_5Text = labelFormat == "Simple" ? "✅ TP1.5" : str.format("✅ TP1.5: ${0}", str.tostring(orbTP1_5Price, "#.##"))
            label.set_text(orbTP1_5Label, tp1_5Text)
            label.set_color(orbTP1_5Label, color.new(color.green, 0))
        if not na(orbTP1_5Line)
            line.set_color(orbTP1_5Line, color.new(color.green, 0))

    if not orbTP2Hit and not na(orbTP2Price) and showTP2 and bar_index >= orbEntryBar and (isLongTrade ? high >= orbTP2Price : low <= orbTP2Price)
        orbTP2Hit := true
        alertTP2Triggered := true  // Trigger TP2 alert
        if not na(orbTP2Label)
            string tp2Text = labelFormat == "Simple" ? "✅ TP2" : str.format("✅ TP2: ${0}", str.tostring(orbTP2Price, "#.##"))
            label.set_text(orbTP2Label, tp2Text)
            label.set_color(orbTP2Label, color.new(color.green, 0))
        if not na(orbTP2Line)
            line.set_color(orbTP2Line, color.new(color.green, 0))

    if not orbTP3Hit and not na(orbTP3Price) and showTP3 and bar_index >= orbEntryBar and (isLongTrade ? high >= orbTP3Price : low <= orbTP3Price)
        orbTP3Hit := true
        alertTP3Triggered := true  // Trigger TP3 alert
        if not na(orbTP3Label)
            string tp3Text = labelFormat == "Simple" ? "✅ TP3" : str.format("✅ TP3: ${0}", str.tostring(orbTP3Price, "#.##"))
            label.set_text(orbTP3Label, tp3Text)
            label.set_color(orbTP3Label, color.new(color.green, 0))
        if not na(orbTP3Line)
            line.set_color(orbTP3Line, color.new(color.green, 0))

    lastTPHit = false
    if showTP3 and orbTP3Hit
        lastTPHit := true
    else if not showTP3 and showTP2 and orbTP2Hit
        lastTPHit := true
    else if not showTP3 and not showTP2 and showTP1_5 and orbTP1_5Hit
        lastTPHit := true
    else if not showTP3 and not showTP2 and not showTP1_5 and showTP1 and orbTP1Hit
        lastTPHit := true

    if lastTPHit
        orbLinesFrozen := true

    if not orbSLHit and not na(orbSLPrice) and bar_index >= orbEntryBar and (isLongTrade ? low <= orbSLPrice : high >= orbSLPrice)
        orbSLHit := true
        alertSLTriggered := true  // Trigger SL alert
        orbLinesFrozen := true
        // Reset breakout flag to allow new breakouts after SL hit
        if not na(activeORB)
            if isLongTrade
                activeORB.breakoutUp := false
            else
                activeORB.breakoutDown := false
        if not na(orbSLLabel)
            string slText = labelFormat == "Simple" ? "❌ SL" : str.format("❌ SL: ${0}", str.tostring(orbSLPrice, "#.##"))
            label.set_text(orbSLLabel, slText)

    if freezeOnEOD and not inSession and inSession[1]
        orbLinesFrozen := true

// ===================== REAL-TIME TP TRACKING & TRADE CLOSE DETECTION ==============================
bool cyclesChanged = (cyclesUp != prevCyclesUp) or (cyclesDown != prevCyclesDown)
bool newBreakoutDetected = not na(orbEntryBar) and (na(prevOrbEntryBar) or orbEntryBar != prevOrbEntryBar or cyclesChanged)

if newBreakoutDetected
    trade_closed := false
    prevOrbEntryBar := orbEntryBar
    prevCyclesUp := cyclesUp
    prevCyclesDown := cyclesDown
    current_trade_r := 0.0
    tp1_counted := false
    tp1_5_counted := false
    tp2_counted := false
    tp3_counted := false

bool hasActiveBreakout = (everHadBreakUp or everHadBreakDown) and not na(orbEntryBar)

if hasActiveBreakout and not trade_closed

    // STEP 1: CALCULATE CURRENT TRADE R (Real-time)
    current_trade_r := 0.0
    
    if orbTP3Hit and showTP3
        current_trade_r := 3.0
    else if orbTP2Hit and showTP2
        current_trade_r := 2.0
    else if orbTP1_5Hit and showTP1_5
        current_trade_r := 1.5
    else if orbTP1Hit and showTP1
        current_trade_r := 1.0

    // STEP 2: CHECK TRADE CLOSE CONDITIONS
    bool lastTPisTP3 = showTP3
    bool lastTPisTP2 = showTP2 and not showTP3
    bool lastTPisTP1_5 = showTP1_5 and not showTP2 and not showTP3
    bool lastTPisTP1 = showTP1 and not showTP1_5 and not showTP2 and not showTP3
    
    bool shouldClose = false
    string resultText = ""
    bool isWin = false

    if orbSLHit
        shouldClose := true
        isWin := false
        current_trade_r := -1.0
        resultText := "❌ SL Hit (-1R)"

    else if (orbTP3Hit and lastTPisTP3) or (orbTP2Hit and lastTPisTP2) or (orbTP1_5Hit and lastTPisTP1_5) or (orbTP1Hit and lastTPisTP1)
        shouldClose := true
        isWin := true

        if orbTP3Hit and lastTPisTP3
            resultText := "✅ TP3 Hit (+3R)"
        else if orbTP2Hit and lastTPisTP2
            resultText := "✅ TP2 Hit (+2R)"
        else if orbTP1_5Hit and lastTPisTP1_5
            resultText := "✅ TP1.5 Hit (+1.5R)"
        else if orbTP1Hit and lastTPisTP1
            resultText := "✅ TP1 Hit (+1R)"

    else if freezeOnEOD and not inSession and inSession[1]
        shouldClose := true

        if orbTradeDirection == 1  // LONG
            float riskDist = entry - sl
            float profitDist = close - entry
            current_trade_r := riskDist > 0 ? profitDist / riskDist : 0.0
        else if orbTradeDirection == -1  // SHORT
            float riskDist = sl - entry
            float profitDist = entry - close
            current_trade_r := riskDist > 0 ? profitDist / riskDist : 0.0

        isWin := current_trade_r > 0

        string eodIcon = current_trade_r > 0 ? "✅" : current_trade_r < 0 ? "❌" : "⚖️"
        resultText := str.format("{0} EOD Close: {1}R", eodIcon, str.tostring(current_trade_r, "#.#"))
    
    // STEP 3: CLOSE TRADE & UPDATE SESSION STATS
    if shouldClose and not trade_closed
        trade_closed := true
        session_trades += 1

        session_total_rr += current_trade_r

        if isWin
            session_wins += 1
            session_best_r := math.max(session_best_r, current_trade_r)
        else
            session_losses += 1
            session_worst_r := math.min(session_worst_r, current_trade_r)

        last_trade_result := resultText

// ====================== DYNAMIC ORB VISUALIZATION (BUILDING PHASE) ================================
float plotORB5High = na
float plotORB5Low = na
float plotORB5Mid = na
float plotORB15High = na
float plotORB15Low = na
float plotORB15Mid = na
float plotORB30High = na
float plotORB30Low = na
float plotORB30Mid = na
float plotORB60High = na
float plotORB60Low = na
float plotORB60Mid = na

ORBData lastEnabledORB = na
for orbObj in allORBs
    if orbObj.isEnabled
        if na(lastEnabledORB) or orbObj.minutes > lastEnabledORB.minutes
            lastEnabledORB := orbObj

if not isHTF and inSession

    float barEndTime = time + (currentTF_seconds * 1000)
    float minsFromOpenToEndOfBar = not na(sessionFirstBarTime) ? (barEndTime - sessionFirstBarTime) / 60000 : -1
 
    if orb5Obj.isEnabled and orb5Obj.minutes >= currentTF_minutes
        prevOrb = array.get(cachedPrevORBs, 0)
        nextOrb = array.get(cachedNextORBs, 0)
        
        bool prevOrbVisible = na(prevOrb) ? false : prevOrb.minutes >= currentTF_minutes
        float startMin = -1.0  // Special case for first ORB            
        float endMin = na(nextOrb) ? 9999.0 : orb5Obj.minutes -1
        bool inWindow = minsFromOpen > startMin and minsFromOpen <= endMin
        bool hasData = not na(orb5Obj.high) and not na(orb5Obj.low)
        
        if inWindow and hasData
            plotORB5High := orb5Obj.high
            plotORB5Low := orb5Obj.low
            plotORB5Mid := orb5Obj.mid
        else
            plotORB5High := na
            plotORB5Low := na
            plotORB5Mid := na
    else
        plotORB5High := na
        plotORB5Low := na
        plotORB5Mid := na

    if orb15Obj.isEnabled and orb15Obj.minutes >= currentTF_minutes
        prevOrb = getPreviousEnabledORB(orb15Obj)
        nextOrb = getNextEnabledORB(orb15Obj)

        bool prevOrbVisible = na(prevOrb) ? false : prevOrb.minutes >= currentTF_minutes
        float startMin = na(prevOrb) or not prevOrbVisible ? 0.0 : prevOrb.minutes - 1 
        float endMin = na(nextOrb) ? 9999.0 : orb15Obj.minutes
        bool startsBeforeEnd = minsFromOpen < endMin
        bool endsAfterStart = minsFromOpenToEndOfBar > startMin
        bool inWindow = startsBeforeEnd and endsAfterStart
        bool hasData = not na(orb15Obj.high) and not na(orb15Obj.low)
        
        if inWindow and hasData
            plotORB15High := orb15Obj.high
            plotORB15Low := orb15Obj.low
            plotORB15Mid := orb15Obj.mid
        else
            plotORB15High := na
            plotORB15Low := na
            plotORB15Mid := na
    else
        plotORB15High := na
        plotORB15Low := na
        plotORB15Mid := na

    if orb30Obj.isEnabled and orb30Obj.minutes >= currentTF_minutes
        prevOrb = getPreviousEnabledORB(orb30Obj)
        nextOrb = getNextEnabledORB(orb30Obj)

        bool prevOrbVisible = na(prevOrb) ? false : prevOrb.minutes >= currentTF_minutes
        float startMin = na(prevOrb) or not prevOrbVisible ? 0.0 : prevOrb.minutes - 1
        float endMin = na(nextOrb) ? 9999.0 : orb30Obj.minutes
        bool startsBeforeEnd = minsFromOpen < endMin
        bool endsAfterStart = minsFromOpenToEndOfBar > startMin
        bool inWindow = startsBeforeEnd and endsAfterStart
        bool hasData = not na(orb30Obj.high) and not na(orb30Obj.low)
        
        if inWindow and hasData
            plotORB30High := orb30Obj.high
            plotORB30Low := orb30Obj.low
            plotORB30Mid := orb30Obj.mid
        else
            plotORB30High := na
            plotORB30Low := na
            plotORB30Mid := na
    else
        plotORB30High := na
        plotORB30Low := na
        plotORB30Mid := na

    if orb60Obj.isEnabled and orb60Obj.minutes >= currentTF_minutes
        prevOrb = getPreviousEnabledORB(orb60Obj)
        nextOrb = getNextEnabledORB(orb60Obj)

        bool prevOrbVisible = na(prevOrb) ? false : prevOrb.minutes >= currentTF_minutes
        float startMin = na(prevOrb) or not prevOrbVisible ? 0.0 : prevOrb.minutes - 1
        float endMin = 9999.0 
        bool startsBeforeEnd = minsFromOpen < endMin
        bool endsAfterStart = minsFromOpenToEndOfBar > startMin
        bool inWindow = startsBeforeEnd and endsAfterStart
        bool hasData = not na(orb60Obj.high) and not na(orb60Obj.low)
        
        if inWindow and hasData
            plotORB60High := orb60Obj.high
            plotORB60Low := orb60Obj.low
            plotORB60Mid := orb60Obj.mid
        else
            plotORB60High := na
            plotORB60Low := na
            plotORB60Mid := na
    else
        plotORB60High := na
        plotORB60Low := na
        plotORB60Mid := na

// ORB5 Plots (during building only)
p_orb5_high = plot(plotORB5High, title="ORB5 High", color=color.new(orb5LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
p_orb5_low = plot(plotORB5Low, title="ORB5 Low", color=color.new(orb5LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
fill(p_orb5_high, p_orb5_low, color=color.new(orb5LineColor, showBG ? fillTransparency : 100), title="ORB5 Fill")
plot(showMidLine ? plotORB5Mid : na, title="ORB5 Mid", color=color.new(orb5LineColor, 30), linewidth=1, style=plot.style_linebr, display=display.all)

// ORB15 Plots (during building only)
p_orb15_high = plot(plotORB15High, title="ORB15 High", color=color.new(orb15LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
p_orb15_low = plot(plotORB15Low, title="ORB15 Low", color=color.new(orb15LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
fill(p_orb15_high, p_orb15_low, color=color.new(orb15LineColor, showBG ? fillTransparency : 100), title="ORB15 Fill")
plot(showMidLine ? plotORB15Mid : na, title="ORB15 Mid", color=color.new(orb15LineColor, 30), linewidth=1, style=plot.style_linebr, display=display.all)

// ORB30 Plots (during building only)
p_orb30_high = plot(plotORB30High, title="ORB30 High", color=color.new(orb30LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
p_orb30_low = plot(plotORB30Low, title="ORB30 Low", color=color.new(orb30LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
fill(p_orb30_high, p_orb30_low, color=color.new(orb30LineColor, showBG ? fillTransparency : 100), title="ORB30 Fill")
plot(showMidLine ? plotORB30Mid : na, title="ORB30 Mid", color=color.new(orb30LineColor, 30), linewidth=1, style=plot.style_linebr, display=display.all)

// ORB60 Plots (during building only)
p_orb60_high = plot(plotORB60High, title="ORB60 High", color=color.new(orb60LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
p_orb60_low = plot(plotORB60Low, title="ORB60 Low", color=color.new(orb60LineColor, 0), linewidth=1, style=plot.style_linebr, display=display.all)
fill(p_orb60_high, p_orb60_low, color=color.new(orb60LineColor, showBG ? fillTransparency : 100), title="ORB60 Fill")
plot(showMidLine ? plotORB60Mid : na, title="ORB60 Mid", color=color.new(orb60LineColor, 30), linewidth=1, style=plot.style_linebr, display=display.all)

// ============================================ DASHBOARD ============================================
var string cachedHTFBiasText = ""
var int lastHTFCheckBar = -1
var bool cachedHTFBullish = false
var bool cachedHTFBearish = false
var float cachedHTFStrength = 0.0
var bool shouldCheckHTF = false

var int lastDashStage = -1
var bool lastDashBreakUp = false
var bool lastDashBreakDown = false
var float lastDashOrbHigh = na
var float lastDashOrbLow = na
var bool lastDashTP1Hit = false
var bool lastDashTP1_5Hit = false
var bool lastDashTP2Hit = false
var bool lastDashTP3Hit = false
var bool lastDashSLHit = false

if showDashboard and enableHTF
    [htfTimeChanged] = request.security(syminfo.tickerid, htfTF, [ta.change(time) != 0], barmerge.gaps_off, barmerge.lookahead_off)

    if barstate.islast and (htfTimeChanged or na(cachedHTFBiasText))
        [htfBullishCalc, htfBearishCalc, htfBiasTextTemp, htfStrengthTemp] = checkHTFBias()
        cachedHTFBiasText := htfBiasTextTemp
        cachedHTFBullish := htfBullishCalc
        cachedHTFBearish := htfBearishCalc
        cachedHTFStrength := htfStrengthTemp
        lastHTFCheckBar := bar_index
    
    htfBullish := cachedHTFBullish  
    htfBearish := cachedHTFBearish
    htfBiasText := cachedHTFBiasText

    bool stageChanged = stage != lastDashStage
    bool breakStateChanged = hadBreakUp != lastDashBreakUp or hadBreakDown != lastDashBreakDown
    bool orbLevelsChanged = not na(activeORB) and (activeORB.high != lastDashOrbHigh or activeORB.low != lastDashOrbLow)
    bool targetHitStateChanged = orbTP1Hit != lastDashTP1Hit or orbTP1_5Hit != lastDashTP1_5Hit or orbTP2Hit != lastDashTP2Hit or orbTP3Hit != lastDashTP3Hit or orbSLHit != lastDashSLHit
    bool forceUpdate = (bar_index - lastDashUpdateBar) >= 20
    bool dashDataChanged = barstate.islast and (stageChanged or breakStateChanged or orbLevelsChanged or targetHitStateChanged or forceUpdate)

    bool isDarkTheme = dashTheme == "Dark"
    color bgColor = isDarkTheme ? color.new(color.black, 0) : color.new(color.white, 10)
    color txtColor = isDarkTheme ? color.white : color.black
    color headerColor = isDarkTheme ? color.new(color.aqua, 30) : color.new(color.silver, 30)
    tablePos = dashPos == "Top Left" ? position.top_left : dashPos == "Top Right" ? position.top_right : dashPos == "Bottom Left" ? position.bottom_left : dashPos == "Bottom Right" ? position.bottom_right : position.middle_right
    txtSize = dashSize == "Small" ? size.small : dashSize == "Normal" ? size.normal : dashSize == "Large" ? size.large : size.auto
    
    if showDashboard and na(dashTable)
        dashTable := table.new(tablePos, 2, 28, bgcolor=bgColor, border_width=0, frame_width=1)
        table.clear(dashTable, 0, 0, 1, 27)
        table.set_position(dashTable, tablePos)
        lastDashUpdateBar := bar_index

    if showDashboard and not na(dashTable)
        lastDashUpdateBar := bar_index
        lastDashStage := stage
        lastDashBreakUp := hadBreakUp
        lastDashBreakDown := hadBreakDown
        if not na(activeORB)
            lastDashOrbHigh := activeORB.high
            lastDashOrbLow := activeORB.low
        lastDashTP1Hit := orbTP1Hit
        lastDashTP1_5Hit := orbTP1_5Hit
        lastDashTP2Hit := orbTP2Hit
        lastDashTP3Hit := orbTP3Hit
        lastDashSLHit := orbSLHit
        
        table.clear(dashTable, 0, 0, 1, 27)
        table.set_position(dashTable, tablePos)

    int row = 0

    bool showFullDashboard = false
    string sessionIcon = ""
    string sessionStatusText = ""

    bool isMarketOpen = isTradingDay() and isWithinSessionHours()
    bool isDisplayWindow = isWithinDisplayHours()

    bool hasValidOrbData = not na(activeORB) or everHadBreakUp or everHadBreakDown or not na(orbEntryPrice)

    if isHTF
        sessionIcon := "⚠️"
        sessionStatusText := "HTF MODE - Use 5-60min timeframe"
        showFullDashboard := false
    else if isMarketOpen
        bool isRegularHours = isInRegularHours()
        sessionIcon := isRegularHours ? "☀️" : "💤"
        sessionStatusText := isRegularHours ? "MARKET OPEN" : "EXTENDED HOURS"
        showFullDashboard := true
    else if hadSessionToday and hasValidOrbData and isDisplayWindow and not isMarketOpen
        sessionIcon := "🌙"

        bool useReplayTime = isReplayMode()
        int timeToCheck = useReplayTime ? time : timenow
        
        string sessionDate = not na(sessionStartTime) ? str.format_time(int(sessionStartTime), "MM/dd", syminfo.timezone) : "N/A"
        string currentDate = str.format_time(timeToCheck, "MM/dd", syminfo.timezone)

        if sessionDate == currentDate
            sessionStatusText := "AFTER HOURS - Today's Data (" + sessionDate + ")"
        else
            sessionStatusText := "AFTER HOURS - Yesterday's Data (" + sessionDate + ")"

        showFullDashboard := true
    else if not hadSessionToday and isDisplayWindow and isTradingDay() and enableExtendedHours
        sessionIcon := "⏰"
        sessionStatusText := "PRE-MARKET - Waiting for ORB"
        showFullDashboard := false
    else
        sessionIcon := "🌙"
        sessionStatusText := "MARKET CLOSED"
        showFullDashboard := false

    // BUILD DASHBOARD
    if not showFullDashboard and not na(dashTable) and (dashDataChanged or forceUpdate)
        // Clear the full table range (table has 26 rows: 0..25)
        table.clear(dashTable, 0, 0, 1, 27)
        table.set_position(dashTable, tablePos)

        string statusTitle = sessionIcon + " " + sessionStatusText
        color statusBgColor = isDarkTheme ? color.new(color.gray, 20) : color.new(color.gray, 80)

        string statusTooltip = ""
        if isHTF
            statusTooltip := "ORB works only on timeframes 1-60 minutes.\n\nPlease switch to a lower timeframe to use ORB."
        else if not hadSessionToday and isDisplayWindow and isTradingDay() and enableExtendedHours
            statusTooltip := "Waiting for market open to build ORB.\n\nExtended hours trading is enabled.\nORB will start building at session start."
        else
            statusTooltip := "Market is closed.\n\nORB will activate during market hours."

        table.cell(dashTable, 0, 0, statusTitle, text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=statusBgColor, tooltip=statusTooltip)
        table.cell(dashTable, 1, 0, "", bgcolor=statusBgColor)
        table.merge_cells(dashTable, 0, 0, 1, 0)
        
        lastDashUpdateBar := bar_index
        
    else if showFullDashboard and not na(dashTable)

        float entry = na
        float sl = na
        float tp1 = na
        float tp1_5 = na
        float tp2 = na
        float tp3 = na
        float atr = na
        bool isBullish = false
        int shares = na
        float posValue = na
        float maxLossCalc = na
        float riskAmount = na
        float riskPctOfAcct = na
         
        // HEADER - With Session Status Icon
        string headerTitle = sessionIcon + " ORB DASHBOARD"
        color headerBgColor = headerColor
        string headerTooltip = "ORB Dashboard - " + sessionStatusText + "\n\n"

        if isWithinDisplayHours() and isInRegularHours()
            headerTooltip += "☀️ REGULAR HOURS (09:30-16:00)\n"
            headerTooltip += "Market is open for trading.\n\n"
        else if isWithinDisplayHours() and not isInRegularHours()
            headerTooltip += "🌙 EXTENDED HOURS\n"
            headerTooltip += "Pre-market (04:00-09:30) or After-hours (16:00-20:00)\n"
            headerTooltip += "Showing data from extended session.\n\n"

        if everHadBreakUp
            headerTitle += " ⬆️"
            headerBgColor := color.new(color.green, 10)
            headerTooltip += "⬆️ BREAKOUT UP active\n"
        else if everHadBreakDown
            headerTitle += " ⬇️"
            headerBgColor := color.new(color.red, 10)
            headerTooltip += "⬇️ BREAKOUT DOWN active\n"

        headerTooltip += "\n━━━━━━━━━━━━━━━━━━━━━\n"
        headerTooltip += "Shows Opening Range Breakout status and trade setup.\n"
        headerTooltip += "The dashboard displays active breakout trade parameters including entry, targets, and stop loss."

        if not na(dashTable)
            table.cell(dashTable, 0, row, headerTitle, text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=headerBgColor, tooltip=headerTooltip)
            table.cell(dashTable, 1, row, "", text_halign=text.align_center, bgcolor=headerBgColor)
            table.merge_cells(dashTable, 0, row, 1, row)
        row += 1

        if showStage and not na(activeORB)
            bool isMarketNow = isTradingDay() and isWithinSessionHours()
            bool showingPastData = hadSessionToday and not isMarketNow

            activeOrbText = showingPastData ? "📊 Last: " + activeORB.name : "🎯 Active: " + activeORB.name
            
            // ENHANCED TOOLTIP: Time, Session, Market & ORB Details
            bool useReplayTime = isReplayMode()
            int timeToCheck = useReplayTime ? time : timenow
            string modeIndicator = useReplayTime ? " [REPLAY]" : " [LIVE]"

            string currentTime = str.format_time(timeToCheck, "HH:mm:ss", syminfo.timezone) + modeIndicator
            string currentDate = str.format_time(timeToCheck, "yyyy-MM-dd", syminfo.timezone)
            string barTime = str.format_time(time, "HH:mm:ss", syminfo.timezone)

            string chartTimezoneDisplay = "Unknown - Check: Right-click → Settings → Timezone"

            string timezoneHint = "\n\nℹ️ If time seems wrong:\n" + 
                                  "Your chart may be set to UTC, EST, or another timezone.\n" + 
                                  "To change: Right-click chart → Settings → Timezone\n\n" + 
                                  "Common settings:\n" + 
                                  "• Asia/Jerusalem (Israel time)\n" + 
                                  "• America/New_York (NYSE time)\n" + 
                                  "• UTC (Universal time - neutral)\n"

            string sessionDescription = ""
            if sessionMode == "New-York"
                sessionDescription := "NYSE Hours (09:30-16:00 EST/EDT)"
            else if sessionMode == "London"
                sessionDescription := "LSE Hours (08:00-16:30 GMT/BST)"
            else if sessionMode == "Tokyo"
                sessionDescription := "TSE Hours (09:00-15:00 JST)"
            else if sessionMode == "Sydney"
                sessionDescription := "ASX Hours (10:00-16:00 AEST)"
            else if sessionMode == "Frankfurt"
                sessionDescription := "XETRA Hours (09:00-17:30 CET/CEST)"
            else if sessionMode == "Auto-Detect"
                if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
                    sessionDescription := "Exchange Hours (Auto-detected for " + syminfo.ticker + ")"
                else if syminfo.type == "crypto"
                    sessionDescription := "24/7 Trading"
                else
                    sessionDescription := "Auto-detected Session"
            else if sessionMode == "Custom"
                sessionDescription := "Custom Session (" + str.replace(tradingSession, ":23456", "") + ")"
            
            // === SESSION STATUS ===
            bool withinSessionHours = isWithinSessionHours()
            string sessionStatus = withinSessionHours ? "✅ OPEN" : "❌ CLOSED"

            string timeFromOpen = "N/A"
            
            if withinSessionHours and not na(sessionStartTime)
                int minutesElapsed = int((time - sessionStartTime) / 60000)
                int hours = int(minutesElapsed / 60)
                int mins = minutesElapsed % 60
                timeFromOpen := str.format("{0}h {1}m (OPEN)", hours, mins)
            else if not na(sessionStartTime)
                timeFromOpen := "Session Closed"
            
            // === ACTIVE ORB DETAILS ===
            string orbHighStr = str.tostring(activeORB.high, "#.####")
            string orbLowStr = str.tostring(activeORB.low, "#.####")
            string orbRangeStr = str.tostring(activeORB.orbRange, "#.####")
            string orbRangePct = str.tostring((activeORB.orbRange / activeORB.low) * 100, "#.##")
            
            // === BREAKOUT STATISTICS ===
            string breakoutStats = str.format("{0}↑ / {1}↓", activeORB.cyclesUp, activeORB.cyclesDown)
            int totalBreakouts = activeORB.cyclesUp + activeORB.cyclesDown
            
            // === MARKET DETECTION ===
            marketType = syminfo.type == "stock" ? "Stock" : syminfo.type == "crypto" ? "Crypto" : syminfo.type == "forex" ? "Forex" : syminfo.type
            resetTiming = is24_7Market ? "Midnight UTC (24/7 mode)" : "Session start: " + str.replace(tradingSession, ":23456", "") + " (" + sessionMode + ")"
            
            // === BUILD TOOLTIP ===
            if sessionMode == "New-York"
                sessionDescription := "NYSE Hours (09:30-16:00 EST/EDT)"
            else if sessionMode == "London"
                sessionDescription := "LSE Hours (08:00-16:30 GMT/BST)"
            else if sessionMode == "Tokyo"
                sessionDescription := "TSE Hours (09:00-15:00 JST)"
            else if sessionMode == "Sydney"
                sessionDescription := "ASX Hours (10:00-16:00 AEST)"
            else if sessionMode == "Frankfurt"
                sessionDescription := "XETRA Hours (09:00-17:30 CET/CEST)"
            else if sessionMode == "Auto-Detect"
                if syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "index" or syminfo.type == "dr" or syminfo.type == "etf" or syminfo.type == "futures"
                    sessionDescription := "Exchange Hours (Auto-detected for " + syminfo.ticker + ")"
                else if syminfo.type == "crypto"
                    sessionDescription := "24/7 Trading"
                else
                    sessionDescription := "Auto-detected Session"
            else if sessionMode == "Custom"
                sessionDescription := "Custom Session (" + str.replace(tradingSession, ":23456", "") + ")"
            
            // === BUILD TOOLTIP ===
            bool is24_7 = syminfo.type == "crypto" or str.contains(tradingSession, "0000-2359")

            string sessionInfoSection = ""
            if not is24_7
                sessionInfoSection := "Time from session open: " + timeFromOpen + "\n\n" + "Session Definition: " + sessionDescription + "\n" + "Raw Session String: " + tradingSession + "\n\n"
            
            activeOrbTooltip = "Currently Active ORB\n\n" + 
                              "This is the ORB period being used for breakout detection.\n\n" + 
                              "• Breakouts are checked against THIS ORB only\n" + 
                              "• When a new ORB completes, it becomes active\n" + 
                              "• Priority: ORB60 > ORB30 > ORB15 > ORB5\n\n" + 
                              
                              "─────────────────\n" + 
                              "⏰ CHART TIME DISPLAY\n" + 
                              "─────────────────\n" + 
                              "Date: " + currentDate + "\n" + 
                              "Current Bar: " + currentTime + "\n" + 
                              "Bar Open: " + barTime + "\n\n" + 
                              
                              "ℹ️ If time seems wrong:\n" + 
                              "Your chart may be set to UTC, EST, or another timezone.\n" + 
                              "To change: Right-click chart → Settings → Timezone\n\n" +

                              "─────────────────\n" + 
                              "📊 SESSION STATUS\n" + 
                              "─────────────────\n" + 
                              "Status: " + sessionStatus + "\n" + 
                              (is24_7 ? "" : "Time from session open: " + timeFromOpen + "\n\n" + 
                                             "Session Definition: " + sessionDescription + "\n" + 
                                             "Raw Session String: " + tradingSession + "\n\n")
            
            table.cell(dashTable, 0, row, activeOrbText, text_color=color.new(color.yellow, 0), text_size=txtSize, text_halign=text.align_center, bgcolor=color.new(color.blue, 20), tooltip=activeOrbTooltip)
            table.cell(dashTable, 1, row, "", bgcolor=color.new(color.blue, 20))
            table.merge_cells(dashTable, 0, row, 1, row)
            row += 1

        // Range info
        if showRange and not isHTF and not na(activeORB)
            orbRange = activeORB.high - activeORB.low
            rangePct = activeORB.low > 0 ? (orbRange / activeORB.low) * 100 : 0
            rangeTooltip = "ORB Range Size\n\nShows the width of the Opening Range in both dollars and percentage.\n\n• Large range (>1.5%) = High volatility\n• Medium range (0.5-1.5%) = Normal volatility\n• Small range (<0.5%) = Low volatility\n\nLarger ranges may require wider stops and smaller position sizes."
            
            table.cell(dashTable, 0, row, "Range:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=rangeTooltip)
            table.cell(dashTable, 1, row, str.format("${0} ({1}% width)", str.tostring(orbRange, "#.##"), str.tostring(rangePct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
        
        // Volatility Meter
        if showVolatilityMeter and not isHTF
            float atrPct = cachedATR > 0 and close > 0 ? (cachedATR / close) * 100 : 0
            string volIcon = atrPct > 3.0 ? "🔥🔥🔥" : atrPct > 2.0 ? "🔥🔥" : atrPct > 1.0 ? "🔥" : "⚪"
            string volText = atrPct > 3.0 ? "Extreme" : atrPct > 2.0 ? "High" : atrPct > 1.0 ? "Medium" : "Low"
            string volFull = volIcon + " " + volText
            
            volTooltip = "Market Volatility Level\n\nMeasures current volatility using ATR percentage of price.\n\nCurrent ATR: " + str.tostring(atrPct, "#.##") + "%\n\nLEVELS:\n🔥🔥🔥 EXTREME (>3%)\n• Very volatile conditions\n• Wider stops recommended\n• Smaller position sizes\n• Larger potential moves\n\n🔥🔥 HIGH (2-3%)\n• Active price movement\n• Standard stops work well\n• Normal position sizing\n• Good trading conditions\n\n🔥 MEDIUM (1-2%)\n• Normal trading range\n• Standard risk management\n• Typical daily movement\n\n⚪ LOW (<1%)\n• Quiet market\n• Tighter stops possible\n• Limited movement expected\n• May have smaller ORB ranges\n\nIMPLICATIONS:\nHigher volatility = Bigger potential profit BUT more risk of stop-out"
            
            table.cell(dashTable, 0, row, "📊 Volatility:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=volTooltip)
            table.cell(dashTable, 1, row, volFull, text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1

        // GOD MODE: Quality Score + Day Context
        if godModeEnabled and not isHTF
            string godScoreText = na(godLastScore) ? "—" : "⚡ " + str.tostring(godLastScore, "#") + " (" + f_godGrade(godLastScore) + ") " + godLastScoreDir + ((godLastScoreDir == "UP" and godHighConfluence) or (godLastScoreDir == "DOWN" and godLowConfluence) ? " 🏆" : "")
            color godScoreColor = na(godLastScore) ? txtColor : godLastScore >= 70 ? color.new(color.lime, 0) : godLastScore >= 55 ? color.new(color.yellow, 0) : color.new(color.orange, 0)
            godScoreTooltip = "GOD MODE Breakout Quality Score\n\nGrades the most recent breakout 0-100:\n• Volume strength vs average\n• HTF bias alignment\n• ORB width vs daily ATR (narrow = better)\n• Gap direction alignment\n• PDH/PDL/premarket level confluence (🏆)\n• Breakout cycle number (first = best)\n\nGRADES:\nA+ (85+) = Exceptional setup\nA (70-84) = Strong setup\nB (55-69) = Decent setup\nC (40-54) = Weak setup\nD (<40) = Avoid\n\nCHOP DAY caps the score at 40."
            table.cell(dashTable, 0, row, "⚡ GOD Score:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=godScoreTooltip)
            table.cell(dashTable, 1, row, godScoreText, text_color=godScoreColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
            string godGapText = na(godGapPct) ? "" : "Gap " + (godGapPct >= 0 ? "+" : "") + str.tostring(godGapPct, "#.#") + "%"
            string godOrText = not na(godDailyATR) and godDailyATR > 0 and not na(activeORB) ? "OR " + str.tostring(activeORB.orbRange / godDailyATR, "#.##") + "×dATR" : ""
            string godCtxText = godChopDay ? "⚠️ CHOP DAY (" + str.tostring(godFailedBreaks) + " fails)" : godGapText + (godGapText != "" and godOrText != "" ? " | " : "") + godOrText
            godCtxTooltip = "GOD MODE Day Context\n\nGAP: Today's open vs yesterday's close\n• Breakouts aligned with the gap direction score higher\n\nOR vs dATR: ORB width as a fraction of daily ATR\n• ≤0.25× = Compressed range, high expansion odds (best)\n• 0.25-0.5× = Normal\n• >0.75× = Range already used up, poor R/R\n\n⚠️ CHOP DAY: 2+ failed breaks this session\n• Quality Score capped at 40\n• Whipsaw conditions - trade with caution"
            table.cell(dashTable, 0, row, "🌅 Day Context:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=godCtxTooltip)
            table.cell(dashTable, 1, row, godCtxText, text_color=godChopDay ? color.new(color.orange, 0) : txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1

        

        // Volume
        if showVol and enableVolumeFilter and not isHTF
            volRatio = volumeMA > 0 ? volume / volumeMA : 0
            volStatus = volRatio >= strongVolumeMultiplier ? "✅ Strong" : volRatio >= volumeMultiplier ? "✅ Good" : "⚠️ Weak"
            table.cell(dashTable, 0, row, "Volume:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left)
            table.cell(dashTable, 1, row, str.format("{0}× {1}", str.tostring(volRatio, "#.#"), volStatus), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
        
        // Trend
        if showTrend and not isHTF
            trendStatus = "➖ Neutral"
            if isTrendUp(trendMode, close, trendVWAP, trendEMA12, trendEMACustom, trendSTDirection)
                trendStatus := "✅ Bullish"
            else if isTrendDown(trendMode, close, trendVWAP, trendEMA12, trendEMACustom, trendSTDirection)
                trendStatus := "⚠️ Bearish"
            
            table.cell(dashTable, 0, row, "Trend:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left)
            table.cell(dashTable, 1, row, trendStatus + (enableTrendFilter ? " (Filtered)" : ""), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
        
        // HTF Bias
        if enableHTF
            htfTooltip = "Higher Timeframe Bias\n\nShows if the broader market trend supports your breakout direction.\n\n✅ Aligned: HTF trend matches breakout direction (good)\n⚠️ Counter-Trend: HTF trend opposes breakout (risky)\n➖ Neutral: No clear HTF trend\n\nBreakouts WITH HTF trend have higher success rates."
            table.cell(dashTable, 0, row, "HTF Bias:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=htfTooltip)
            table.cell(dashTable, 1, row, cachedHTFBiasText, text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
        
        // ORB Status Section - minimal spacer
        table.cell(dashTable, 0, row, "", text_color=txtColor, text_size=size.tiny)
        table.cell(dashTable, 1, row, "", text_color=txtColor, text_size=size.tiny)
        table.cell_set_height(dashTable, 0, row, 0.1)
        table.cell_set_height(dashTable, 1, row, 0.1)
        row += 1
    
        // ORB STATUS section - only show if enabled AND not on HTF
        if showStatus and not isHTF
            table.cell(dashTable, 0, row, "📈 ORB STATUS", text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=headerColor)
            table.cell(dashTable, 1, row, "", bgcolor=headerColor)
            table.merge_cells(dashTable, 0, row, 1, row)
            row += 1
            
            // Calculate end time of current bar for smart display (HTF compatibility)
            float barEndTime = time + (currentTF_seconds * 1000)
            float minsFromOpenToEndOfBar = not na(sessionFirstBarTime) ? (barEndTime - sessionFirstBarTime) / 60000 : -1
            
            // Show status of each ORB
            for i = 0 to array.size(allORBs) - 1
                orbObj = array.get(allORBs, i)
                if not na(orbObj) and orbObj.isEnabled
                    orbStatus = ""
                    orbIcon = ""
                    orbTooltip = ""
                    
                    // Smart display: Check if current bar COVERS the completion point
                    bool barCoversCompletion = minsFromOpen >= 0 and minsFromOpen < orbObj.minutes and minsFromOpenToEndOfBar >= orbObj.minutes
                    
                    if orbObj.isBuilding
                        if barCoversCompletion
                            // Display as complete even though internally still building
                            orbStatus := "✅ Complete (This Bar)"
                            orbIcon := ""
                            orbTooltip := orbObj.name + " Status\n\nShowing COMPLETE because current bar covers the " + str.tostring(orbObj.minutes) + "-minute period.\n\nBar timeframe: " + timeframe.period + "\nBar covers: " + str.tostring(minsFromOpen, "#") + "-" + str.tostring(minsFromOpenToEndOfBar, "#") + " minutes from open\n\nInternal state: Still building (will finalize next bar)\nDisplay: Complete (user-friendly)"
                        else
                            orbStatus := "🔨 Building..."
                            orbIcon := ""
                            orbTooltip := orbObj.name + " Status\n\nCurrently building the " + str.tostring(orbObj.minutes) + "-minute range.\n\nTime elapsed: " + str.tostring(minsFromOpen, "#") + " minutes\nCompletion at: " + str.tostring(orbObj.minutes) + " minutes\n\nThe range is updating with each bar until completion."
                    else if orbObj.isComplete
                        cycleText = ""
                        if orbObj.cyclesUp > 0 or orbObj.cyclesDown > 0
                            cycleText := str.format(" | {0}↑/{1}↓", orbObj.cyclesUp, orbObj.cyclesDown)
                        
                        if not na(activeORB) and orbObj.name == activeORB.name
                            orbStatus := "✅ Complete" + cycleText
                            orbIcon := " ⭐"
                            orbTooltip := orbObj.name + " Status\n\n✅ COMPLETE and ACTIVE\n\nThis is the current ORB being used for breakout detection.\n\nRange: $" + str.tostring(orbObj.low, "#.##") + " - $" + str.tostring(orbObj.high, "#.##") + "\nBreakouts: " + str.tostring(orbObj.cyclesUp) + " UP | " + str.tostring(orbObj.cyclesDown) + " DOWN"
                        else
                            orbStatus := "📌 Complete" + cycleText
                            orbIcon := ""
                            orbTooltip := orbObj.name + " Status\n\n📌 COMPLETE (not active)\n\nThis ORB completed but a larger ORB is now active.\n\nRange: $" + str.tostring(orbObj.low, "#.##") + " - $" + str.tostring(orbObj.high, "#.##") + "\nBreakouts: " + str.tostring(orbObj.cyclesUp) + " UP | " + str.tostring(orbObj.cyclesDown) + " DOWN"
                    
                    table.cell(dashTable, 0, row, orbObj.name + orbIcon + ":", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=orbTooltip)
                    table.cell(dashTable, 1, row, orbStatus, text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                    row += 1

        /// Trade info section (only if ENTRY occurred AND targets enabled AND trade still active)
        if enableTargets and not na(orbEntryBar) and not trade_closed

            table.cell(dashTable, 0, row, "", text_color=txtColor, text_size=size.tiny)
            table.cell(dashTable, 1, row, "", text_color=txtColor, text_size=size.tiny)
            table.cell_set_height(dashTable, 0, row, 0.1)
            table.cell_set_height(dashTable, 1, row, 0.1)
            row += 1
            
            isBullish := everHadBreakUp
            entry := orbEntryPrice
            sl := orbSLPrice
            tp1 := orbTP1Price
            tp1_5 := orbTP1_5Price
            tp2 := orbTP2Price
            tp3 := orbTP3Price
            atr := cachedATR
            
            if enablePosSizing
                float displayShares = maxShares
                float displayPosValue = positionValue
                float displayRiskAmount = maxLoss
                
                if na(maxShares) or na(positionValue) or na(maxLoss)
                    // Show error state
                    table.cell(dashTable, 0, row, "⚠️ Position Error:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip="Position size calculation failed. Check Entry/SL values.")
                    table.cell(dashTable, 1, row, "Invalid Data", text_color=color.new(color.red, 0), text_size=txtSize, text_halign=text.align_right)
                    row += 1
                else

                    table.cell(dashTable, 0, row, "Position Size:", text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=headerColor)
                    table.cell(dashTable, 1, row, "", bgcolor=headerColor)
                    table.merge_cells(dashTable, 0, row, 1, row)
                    row += 1

                    string currencySymbol = accountCurrency == "EUR" ? "€" :
                                          accountCurrency == "GBP" ? "£" :
                                          accountCurrency == "JPY" ? "¥" :
                                          accountCurrency == "INR" ? "₹" :
                                          accountCurrency == "CAD" ? "C$" :
                                          accountCurrency == "AUD" ? "A$" :
                                          accountCurrency == "CHF" ? "Fr." :
                                          "$"
  
                    sharesTooltip = "Maximum Position Size in " + accountCurrency + "\n\nNumber of shares you can buy while staying within your risk limits.\n\nCALCULATED BY:\nRisk Amount ÷ Distance to Stop Loss\n\nEXAMPLE:\n• Risk: " + currencySymbol + "150\n• Entry: " + currencySymbol + "10.00\n• Stop: " + currencySymbol + "9.50 (50¢ distance)\n• Max Shares: 300 shares (" + currencySymbol + "150 ÷ " + currencySymbol + "0.50)\n• Position Value: " + currencySymbol + "3,000\n\nThis ensures consistent risk management across all trades.\n\n⚠️ FIXED at breakout - does not change with price!"
                    table.cell(dashTable, 0, row, "Max Shares:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=sharesTooltip)
                    string sharesText = na(displayShares) ? "N/A" : str.tostring(displayShares, "#")
                    float displayPosValueInAcctCurr = na(displayPosValue) ? na : displayPosValue / (accountCurrency == "INR" ? exchangeRate : 1)
                    string posValueText = na(displayPosValueInAcctCurr) ? "N/A" : str.tostring(displayPosValueInAcctCurr, "#,###")
                    table.cell(dashTable, 1, row, sharesText + " (" + currencySymbol + posValueText + ")", text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                    row += 1
                    
                    // Risk amount
                    riskPctOfAcct := (displayRiskAmount / accountSize) * 100
                    riskTooltip = "Risk Amount in " + accountCurrency + "\n\nTotal amount you'll lose if stop loss is hit.\n\nSHOWS:\n• " + accountCurrency + " amount at risk\n• Percentage of total account\n\nRECOMMENDED RISK LEVELS:\n• 0.5-1% of account (conservative)\n• 1-2% of account (balanced)\n• 2-3% of account (aggressive)\n\nNEVER risk more than 3% on a single trade.\n\nThis is your MAXIMUM LOSS - stick to it!\n\n⚠️ FIXED at breakout - does not change!"
                    table.cell(dashTable, 0, row, "Risk:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=riskTooltip)
                    table.cell(dashTable, 1, row, str.format("{0}{1} ({2}%)", currencySymbol, str.tostring(displayRiskAmount / (accountCurrency == "INR" ? exchangeRate : 1), "#"), str.tostring(riskPctOfAcct, "#.#")), text_color=color.new(color.orange, 0), text_size=txtSize, text_halign=text.align_right)
                    row += 1
                    
                    // Blank row after position size
                    table.cell(dashTable, 0, row, "", text_color=txtColor, text_size=size.tiny, height=0.5)
                    table.cell(dashTable, 1, row, "", text_color=txtColor, text_size=size.tiny, height=0.5)
                    row += 1

            // Entry - with validation
            bool validTrade = not na(entry) and not na(sl) and entry > 0 and sl > 0
            
            if validTrade
                entryTooltip = "Entry Price\n\nYour suggested entry point for the trade.\n\nFOR LONG: ORB High level (where breakout occurred)\nFOR SHORT: ORB Low level (where breakdown occurred)\n\nThis is where you would buy/sell to enter the position.\n\nNOTE: Market entry may differ slightly due to slippage."
                table.cell(dashTable, 0, row, "Entry:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=entryTooltip)
                table.cell(dashTable, 1, row, str.format("${0}", str.tostring(entry, "#.##")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1
            else
                table.cell(dashTable, 0, row, "⚠️ Trade Data:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left)
                table.cell(dashTable, 1, row, "Calculating...", text_color=color.new(color.orange, 0), text_size=txtSize, text_halign=text.align_right)
                row += 1
            
            // Stop Loss
            slDist = math.abs(entry - sl)
            slPct = (slDist / entry) * 100
            stopTooltip = "Stop Loss\n\nYour exit price if trade goes against you. Limits maximum loss per trade.\n\nCALCULATED BY: " + stopMode + " method\n\nDISTANCE: Shows $ distance and % from entry\n\nIMPORTANT: Always use a stop loss to protect your capital. Never hold a losing position hoping it will recover."
            table.cell(dashTable, 0, row, "Stop:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=stopTooltip)
            table.cell(dashTable, 1, row, str.format("${0} ({1}%)", str.tostring(sl, "#.##"), str.tostring(slPct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
            
            // Targets (only enabled ones)
            if showTP1
                tp1Dist = math.abs(tp1 - entry)
                tp1Pct = (tp1Dist / entry) * 100
                tp1Label = orbTP1Hit ? "✅ TP1:" : "TP1:"
                tp1Tooltip = "Take Profit 1 (1R)\n\nFirst profit target at 1× Risk distance.\n\n1R = Risk/Reward ratio of 1:1\n\nIf you risk $100, TP1 gives you $100 profit.\n\nSTRATEGY:\n• Conservative: Exit full position at TP1\n• Balanced: Take 50% profit, hold rest for TP2\n• Aggressive: Hold through for higher targets\n\n✅ = Target hit"
                table.cell(dashTable, 0, row, tp1Label, text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=tp1Tooltip)
                table.cell(dashTable, 1, row, str.format("${0} (+{1}%)", str.tostring(tp1, "#.##"), str.tostring(tp1Pct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1
            
            if showTP1_5
                tp1_5Dist = math.abs(tp1_5 - entry)
                tp1_5Pct = (tp1_5Dist / entry) * 100
                tp1_5Label = orbTP1_5Hit ? "✅ TP1.5:" : "TP1.5:"
                tp1_5Tooltip = "Take Profit 1.5 (1.5R)\n\nIntermediate target at 1.5× Risk distance.\n\n1.5R = Risk/Reward ratio of 1:1.5\n\nIf you risk $100, TP1.5 gives you $150 profit.\n\nUSEFUL FOR:\n• Scaling out of positions gradually\n• Capturing middle-ground profits\n• Adjusting to market volatility\n\n✅ = Target hit"
                table.cell(dashTable, 0, row, tp1_5Label, text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=tp1_5Tooltip)
                table.cell(dashTable, 1, row, str.format("${0} (+{1}%)", str.tostring(tp1_5, "#.##"), str.tostring(tp1_5Pct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1
            
            if showTP2
                tp2Dist = math.abs(tp2 - entry)
                tp2Pct = (tp2Dist / entry) * 100
                tp2Label = orbTP2Hit ? "✅ TP2:" : "TP2:"
                tp2Tooltip = "Take Profit 2 (2R)\n\nMain profit target at 2× Risk distance.\n\n2R = Risk/Reward ratio of 1:2\n\nIf you risk $100, TP2 gives you $200 profit.\n\nThis is the STANDARD target for most ORB traders.\n\nSTRATEGY:\n• Exit remaining position at TP2\n• Move stop to breakeven after TP1 hit\n• Let runners go to TP3 if strong momentum\n\n✅ = Target hit"
                table.cell(dashTable, 0, row, tp2Label, text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=tp2Tooltip)
                table.cell(dashTable, 1, row, str.format("${0} (+{1}%)", str.tostring(tp2, "#.##"), str.tostring(tp2Pct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1
            
            if showTP3
                tp3Dist = math.abs(tp3 - entry)
                tp3Pct = (tp3Dist / entry) * 100
                tp3Label = orbTP3Hit ? "✅ TP3:" : "TP3:"
                tp3Tooltip = "Take Profit 3 (3R)\n\nExtended profit target at 3× Risk distance.\n\n3R = Risk/Reward ratio of 1:3\n\nIf you risk $100, TP3 gives you $300 profit.\n\nONLY FOR:\n• Strong trending days\n• High momentum breakouts\n• Extended runners\n\nMOST TRADES won't reach TP3.\n\nSTRATEGY: Trail stop or use for 'lottery tickets'\n\n✅ = Target hit"
                table.cell(dashTable, 0, row, tp3Label, text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=tp3Tooltip)
                table.cell(dashTable, 1, row, str.format("${0} (+{1}%)", str.tostring(tp3, "#.##"), str.tostring(tp3Pct, "#.#")), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1

            // Risk/Reward - Smart logic with caching
            if showRisk
                riskDist = math.abs(entry - sl)
                
                // Determine target: Hit TPs priority, then highest enabled
                float rrTarget = orbTP3Hit and showTP3 ? tp3 : orbTP2Hit and showTP2 ? tp2 : orbTP1_5Hit and showTP1_5 ? tp1_5 : orbTP1Hit and showTP1 ? tp1 : showTP3 ? tp3 : showTP2 ? tp2 : showTP1_5 ? tp1_5 : showTP1 ? tp1 : tp2
                bool anyHit = orbTP3Hit or orbTP2Hit or orbTP1_5Hit or orbTP1Hit
                
                rewardDist = math.abs(rrTarget - entry)
                rrRatio = riskDist > 0 ? rewardDist / riskDist : 0
                rrStatus = anyHit ? "✅" : rrRatio >= 2.0 ? "⭐" : rrRatio >= 1.5 ? "⚠️" : "❌"
                
                table.cell(dashTable, 0, row, "R/R Ratio:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left)
                table.cell(dashTable, 1, row, str.format("1:{0} {1}", str.tostring(rrRatio, "#.#"), rrStatus), text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
                row += 1
        
        // Show last trade result when trade closed
        if enableTargets and (everHadBreakUp or everHadBreakDown) and trade_closed and last_trade_result != ""
            table.cell(dashTable, 0, row, "", text_color=txtColor, text_size=size.tiny)
            table.cell(dashTable, 1, row, "", text_color=txtColor, text_size=size.tiny)
            table.cell_set_height(dashTable, 0, row, 0.1)
            table.cell_set_height(dashTable, 1, row, 0.1)
            row += 1
            
            // Last trade result
            string lastTradeTooltip = "Last Trade Result\n\nShows the outcome of the most recent trade.\n\n✅ = Target hit (profit)\n❌ = Stop loss hit (loss)\n\nR = Risk/Reward ratio\n+2R means you made 2x your risk\n-1R means you lost your risk amount"
            if not na(dashTable)
                table.clear(dashTable, 0, row, 1, row)

            table.cell(dashTable, 0, row, "Last Trade:", text_color=txtColor, text_size=txtSize, text_halign=text.align_left, tooltip=lastTradeTooltip)
            table.cell(dashTable, 1, row, last_trade_result, text_color=txtColor, text_size=txtSize, text_halign=text.align_right)
            row += 1
    
    else if not na(dashTable)

        bool isDarkTheme = dashTheme == "Dark"
        color bgColor = isDarkTheme ? color.new(color.black, 0) : color.new(color.white, 10)
        color txtColor = isDarkTheme ? color.white : color.black
        color headerColor = isDarkTheme ? color.new(color.aqua, 30) : color.new(color.silver, 30)
  
        string headerTitle = sessionIcon + " ORB DASHBOARD"
        string headerTooltip = "ORB Dashboard\n\n" + sessionStatusText + "\n\nMarket is currently closed.\n\nDisplay hours: 04:00-20:00\nCurrent time is outside this window.\n\nThe indicator will resume when the next session begins."
        
        table.cell(dashTable, 0, row, headerTitle, text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=headerColor, tooltip=headerTooltip)
        table.cell(dashTable, 1, row, "", bgcolor=headerColor)
        table.merge_cells(dashTable, 0, row, 1, row)
        row += 1
        
        // NOT IN SESSION message
        string notInSessionMsg = sessionStatusText
        string notInSessionTooltip = sessionStatusText == "PRE-MARKET - Waiting for ORB" ? "Pre-Market Session\n\n📍 Trading day has started\n⏰ ORB will begin building at 09:30\n\nCurrent status:\n• Pre-market trading active (04:00-09:30)\n• Regular session starts at 09:30\n• ORB periods will track first 5, 15, 30, 60 minutes\n\nThe dashboard will show full data once ORB begins." : "Market Closed\n\nCurrent time is outside display hours (04:00-20:00).\n\nORB tracking will resume at next session open.\n\nTo see data from the last session, scroll back to regular or extended trading hours on the chart."
        table.cell(dashTable, 0, row, notInSessionMsg, text_color=txtColor, text_size=txtSize, text_halign=text.align_center, bgcolor=color.new(color.gray, 90), tooltip=notInSessionTooltip)
        table.cell(dashTable, 1, row, "", bgcolor=color.new(color.gray, 90))
        table.merge_cells(dashTable, 0, row, 1, row)
        row += 1
    
    // SESSION STATISTICS ROW (Always visible when there are trades)
    if session_trades > 0 and showFullDashboard and not na(dashTable)
        float winRate = (session_wins / session_trades) * 100

        string statsText = str.format("Stats: {0}✅ | {1}❌ | {2}R | WR: {3}%", 
                                      str.tostring(session_wins),
                                      str.tostring(session_losses),
                                      str.tostring(session_total_rr, "#.#"),
                                      str.tostring(winRate, "#"))
        
        // Build detailed tooltip
        string statsTooltip = "══════════════════════════════\n"
        statsTooltip += "📊 SESSION STATISTICS - Detailed View\n"
        statsTooltip += "══════════════════════════════\n\n"
        statsTooltip += "TRADES TODAY: " + str.tostring(session_trades) + "\n"
        statsTooltip += "├─ ✅ Wins: " + str.tostring(session_wins) + " (" + str.tostring(winRate, "#.#") + "%)\n"
        statsTooltip += "├─ ❌ Losses: " + str.tostring(session_losses) + " (" + str.tostring(100 - winRate, "#.#") + "%)\n"
        statsTooltip += "└─ ⚖️ Win Rate: " + str.tostring(winRate, "#.#") + "%\n\n"
        statsTooltip += "══════════════════════════════\n"
        statsTooltip += "R PERFORMANCE:\n"
        statsTooltip += "├─ 💰 Total R: " + str.tostring(session_total_rr, "#.##") + "R\n"
        
        if session_wins > 0
            float avgWin = session_total_rr > 0 ? (session_total_rr + session_losses) / session_wins : 0.0
            if avgWin > 0
                statsTooltip += "├─ 📈 Avg Win: " + str.tostring(avgWin, "#.##") + "R\n"
        
        if session_losses > 0
            float avgLoss = -1.0
            statsTooltip += "├─ 📉 Avg Loss: " + str.tostring(avgLoss, "#.##") + "R\n"
        
        statsTooltip += "├─ 🏆 Best Trade: " + str.tostring(session_best_r, "#.##") + "R\n"
        
        if session_worst_r < 0
            statsTooltip += "└─ 💀 Worst Trade: " + str.tostring(session_worst_r, "#.##") + "R\n"
        
        statsTooltip += "\══════════════════════════════\n"
        statsTooltip += "💡 TIP: Target 2:1 R/R minimum\n"
        
        if session_total_rr > 0
            statsTooltip += "    Current session: PROFITABLE ⭐\n"
        else if session_total_rr == 0
            statsTooltip += "    Current session: BREAKEVEN ⚖️\n"
        else
            statsTooltip += "    Current session: NEGATIVE ⚠️\n"
        
        // Display the stats row (merged across both columns)
        color statsRowColor = session_total_rr > 0 ? color.new(color.green, 92) : session_total_rr < 0 ? color.new(color.red, 92) : color.new(color.gray, 92)
        
        table.cell(dashTable, 0, row, statsText, 
                   text_color=color.new(color.white, 0), 
                   text_size=txtSize, 
                   text_halign=text.align_center,
                   bgcolor=statsRowColor,
                   tooltip=statsTooltip)
        table.cell(dashTable, 1, row, "", bgcolor=statsRowColor)
        table.merge_cells(dashTable, 0, row, 1, row)
        row += 1

// ====================================== INDIVIDUAL ALERTS ==========================================
alertcondition(alertBreakUpTriggered and enableAlerts and alertBreakouts, 
               title="🔼 ORB Breakout UP", 
               message="{{ticker}} - Breakout ABOVE ORB High @ ${{close}}")

alertcondition(alertBreakDownTriggered and enableAlerts and alertBreakouts, 
               title="🔽 ORB Breakout DOWN", 
               message="{{ticker}} - Breakout BELOW ORB Low @ ${{close}}")

alertcondition(alertRetestUpTriggered and enableAlerts and alertRetests, 
               title="🔁 ORB Retest UP", 
               message="{{ticker}} - Retesting ORB after breakout UP @ ${{close}}")

alertcondition(alertRetestDownTriggered and enableAlerts and alertRetests, 
               title="🔁 ORB Retest DOWN", 
               message="{{ticker}} - Retesting ORB after breakout DOWN @ ${{close}}")

alertcondition(alertFailedUpTriggered and enableAlerts and alertFailedBreaks, 
               title="⚠️ ORB Failed Break UP", 
               message="{{ticker}} - Failed breakout UP, back inside ORB @ ${{close}}")

alertcondition(alertFailedDownTriggered and enableAlerts and alertFailedBreaks, 
               title="⚠️ ORB Failed Break DOWN", 
               message="{{ticker}} - Failed breakout DOWN, back inside ORB @ ${{close}}")

alertcondition(alertStageCompleteTriggered and enableAlerts and alertStageComplete,
               title="✅ ORB Stage Complete",
               message="{{ticker}} - ORB Stage completed")

// ================================ TRADE MANAGEMENT ALERTS =================================
alertcondition(alertEntryTriggered and enableAlerts and alertTradeManagement and enableTargets,
               title="🎯 ENTRY Triggered",
               message="{{ticker}} - ENTRY @ ${{close}} | Trade setup activated")

alertcondition(alertSLTriggered and enableAlerts and alertTradeManagement and enableTargets,
               title="❌ STOP LOSS Hit",
               message="{{ticker}} - STOP LOSS HIT @ ${{close}} | Trade closed with loss")

alertcondition(alertTP1Triggered and enableAlerts and alertTradeManagement and enableTargets and showTP1,
               title="✅ TP1 Hit (1R)",
               message="{{ticker}} - TP1 HIT @ ${{close}} | 1R profit target reached")

alertcondition(alertTP1_5Triggered and enableAlerts and alertTradeManagement and enableTargets and showTP1_5,
               title="✅ TP1.5 Hit (1.5R)",
               message="{{ticker}} - TP1.5 HIT @ ${{close}} | 1.5R profit target reached")

alertcondition(alertTP2Triggered and enableAlerts and alertTradeManagement and enableTargets and showTP2,
               title="✅ TP2 Hit (2R)",
               message="{{ticker}} - TP2 HIT @ ${{close}} | 2R profit target reached")

alertcondition(alertTP3Triggered and enableAlerts and alertTradeManagement and enableTargets and showTP3,
               title="✅ TP3 Hit (3R)",
               message="{{ticker}} - TP3 HIT @ ${{close}} | 3R profit target reached")

//END 13:50 09/07/2026 - Merged duplicated long/short pending-entry and TP/SL tracking blocks

Overview

Luxy BIG beautiful Dynamic ORB draws shaded range boxes and labels breakouts, retests, and failed breaks with cycle counting, plus optional target, stop-loss, and dashboard elements. Main settings adjust active ORB durations, custom or extended session hours, breakout and retest percentage buffers, minimum bars outside, and maximum tracked cycles. It requires clean data feeds and can generate misleading signals during choppy or ranging markets.

Details

Published by

theonetrade on GitHub

Draws

On the price chart

Markets

Stocks

Timeframes

M1-M5, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Show Edge LabelsbooltrueshowEdgeLabels
Label FormatstringDetailedlabelFormat
All Label SizestringSmalllabelSize
Show BackgroundbooltrueshowBG
| Transparencyint95fillTransparency
Enable ORB 5booltrueenableORB5Signals
orb5LineColorcolorcolor.yelloworb5LineColor
Enable ORB15booltrueenableORB15Signals
orb15LineColorcolorcolor.greenorb15LineColor
Enable ORB30booltrueenableORB30Signals
orb30LineColorcolorcolor.blueorb30LineColor
Enable ORB60booltrueenableORB60Signals
Show all 40 settings
SettingTypeDefaultVariable
orb60LineColorcolorcolor.purpleorb60LineColor
Mid-Range LinebooltrueshowMidLine
Session ModestringAuto-DetectsessionMode
Custom Session Hourssession0930-1600customSession
Include Extended HoursboolfalseenableExtendedHours
Pre-Marketsession0400-0930extendedPreMarket
After-Hourssession1600-2000extendedAfterHours
Futures Trading HoursstringAuto-DetectfuturesTradingHours
Enable Breakout DetectionbooltrueenableBreakout
Show Breakout LabelsbooltrueshowBreakLabels
Show Retest LabelsbooltrueenableRetest
Signal ModestringTrack CyclessignalMode
Max Cyclesint6maxCycles
Breakout Buffer (%)float0.2breakoutBuffer
Retest Buffer (%)float0.0retestBuffer
Min Distance for Retest (%)float0.5minRetestDistancePct
Min Bars Outside ORBint2minBarsOutside
Min Pullback for Re-break (%)float0.3minPullbackPct
Enable FVG Filter | boolfalseenableFVGFilter
Show FVG BoxesbooltrueshowFVG
Max FVGint5maxFVGtoKeep
FVG Proximityfloat2.0fvgProximity
Transparencyint90fvgTransparency
Bullish FVGcolorcolor.greenfvgBullColor
Bearish FVGcolorcolor.orangefvgBearColor
Enable Pullback FilterboolfalseenablePullbackFilter
Pullback Required (%)float0.3pullbackPercent
Timeout (bars)int10pullbackTimeout
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

IB / ORB Live Stats

by TamaraKGreen
47 stars

This overlay indicator marks the New York initial balance and a configurable opening range on the price chart and reports live range statistics in two tables. It builds an IB box for a default 09:30–10:30 ET window, an ORB box from 09:30 for a set number of mi

Indicator v6 Sessions & timeBreakout
Updated 2 months ago · None stated GitHub repository of IB / ORB Live Stats

ORB Pro - Research-Based ORB

by Mrshahidali420
16 stars

The ORB Pro indicator calculates and plots Opening Range Breakout levels, stop-loss and take-profit zones, signal labels, and an status dashboard on the price chart. Built on academic research, it evaluates trades using an opening-candle direction filter, open

Indicator v6 BreakoutSessions & time Repaints
Updated 4 months ago · None stated GitHub repository of ORB Pro - Research-Based ORB

Daily Bias Indicator

by Timonkru
1 stars

Daily Bias Indicator evaluates price relative to the previous day's high, low, and midpoint, along with the opening range breakout to compute a directional score. It plots step lines for previous day levels and opening range boundaries directly on the price ch

Indicator v6 Support & resistanceSessions & time
Updated 9 months ago · MIT GitHub repository of Daily Bias Indicator
575 stars

This indicator builds Market Profile Time Price Opportunity (TPO) structures across defined session timeframes directly on the main price chart. It visualizes the Point of Control (POC) and Value Area boundaries using dynamic box drawings. An integrated multi-

Indicator v5 Support & resistanceScreeners & dashboards
Updated 1 year ago · MPL-2.0 GitHub repository of Market Profile with Screener
257 stars

This indicator overlays an intraday SPX and ES chart with a midnight session range, regular-trading-hours opening levels, and a VWAP projection box. It draws the midnight high, mid, and low, flags edge rejections within an absolute tolerance, and plots optiona

Indicator v6 TrendSupport & resistance
Updated 2 months ago · None stated GitHub repository of SPX Midnight Box + Snag Logic

More Breakout scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers