ADAPTIVE ORB SESSIONS

VONKAR · strategy · 2116 行 · 点赞 945 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ╔══════════════════════════════════════════════════════════════════════╗
// ║  ALERT SETUP: Create ONE alert → Order fills only                  ║
// ║  Clear the Message box and paste ONLY this:                        ║
// ║  {{strategy.order.alert_message}}                                  ║
// ║  Add your TradersPost / Ghost webhook URL → Done                   ║
// ╚══════════════════════════════════════════════════════════════════════╝
strategy(
     "ORB SESSIONS",
     overlay                         = true,
     initial_capital                 = 50000,
     currency                        = currency.USD,
     default_qty_type                = strategy.fixed,
     default_qty_value               = 1,
     pyramiding                      = 1,
     commission_type                 = strategy.commission.cash_per_contract,
     commission_value                = 1.2,
     slippage                        = 2,
     margin_long                     = 1,
     margin_short                    = 1,
     calc_on_every_tick              = true,
     calc_on_order_fills             = false,
     use_bar_magnifier               = true,
     process_orders_on_close         = false,
     backtest_fill_limits_assumption = 0,
     fill_orders_on_standard_ohlc    = false,
     max_lines_count                 = 500,
     max_labels_count                = 500,
     max_boxes_count                 = 500
)
 
// ════════════════════════════════════════════════════════════════════════════════
// GLOBAL SETTINGS
// ════════════════════════════════════════════════════════════════════════════════
grpGlobal = "Global Settings"
i_timezone = input.string("America/New_York", "Timezone", options=["America/New_York", "America/Chicago", "America/Los_Angeles", "Europe/London", "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore", "Australia/Sydney", "UTC"], tooltip="All session times are interpreted in this timezone.", group=grpGlobal)
 
// ── Helpers ──
f_dayKey(_t, _tz) => year(_t, _tz) * 10000 + month(_t, _tz) * 100 + dayofmonth(_t, _tz)
 
 
// ── TP Quantity Split Helper (prevents 0-qty TPs when trading small size) ──
f_tpQty(_total, _p1, _p2, _p3) =>
    int total = math.max(0, int(math.round(_total)))
    float p1 = math.max(0.0, _p1)
    float p2 = math.max(0.0, _p2)
    float p3 = math.max(0.0, _p3)
    bool a1 = p1 > 0
    bool a2 = p2 > 0
    bool a3 = p3 > 0
    int active = (a1 ? 1 : 0) + (a2 ? 1 : 0) + (a3 ? 1 : 0)
    if total == 0
        [0, 0, 0]
    else if active == 0
        [total, 0, 0]
    else
        // Base allocation (floors)
        int q1 = a1 ? int(math.floor(total * (p1 / 100.0))) : 0
        int q2 = a2 ? int(math.floor(total * (p2 / 100.0))) : 0
        int q3 = a3 ? int(math.floor(total * (p3 / 100.0))) : 0
 
        // If we have enough contracts to give at least 1 to each active TP, do it.
        if total >= active
            if a1 and q1 == 0
                q1 := 1
            if a2 and q2 == 0
                q2 := 1
            if a3 and q3 == 0
                q3 := 1
        else
            // Not enough contracts to split: prioritize TP1 then TP2 then TP3
            q1 := a1 ? 1 : 0
            q2 := 0
            q3 := 0
            if q1 == 0 and a2
                q2 := 1
            if q1 == 0 and q2 == 0 and a3
                q3 := 1
 
        int sumQ = q1 + q2 + q3
 
        // If we over-allocated (can happen after min-1 forcing), trim from later TPs first.
        while sumQ > total
            if q3 > 0
                q3 -= 1
            else if q2 > 0
                q2 -= 1
            else if q1 > 0
                q1 -= 1
            sumQ := q1 + q2 + q3
 
        // Distribute remainder to earlier TPs by priority and pct weight.
        int rem = total - sumQ
        while rem > 0
            if a1
                q1 += 1
                rem -= 1
            if rem > 0 and a2
                q2 += 1
                rem -= 1
            if rem > 0 and a3
                q3 += 1
                rem -= 1
 
        [q1, q2, q3]
 
 
 
// ── Shared Trade Settings ──
grpTrade = "Trade Settings (All Sessions)"
i_orbEntryMode     = input.string("Breakout", "Entry Mode", options=["Breakout", "Retest Zone", "Retest Midpoint"], tooltip="Breakout: enter on candle close through level.\nRetest Zone: wait for wick back to broken level.\nRetest Midpoint: wait for wick back to ORB midpoint.", group=grpTrade)
i_orbRetestTimeout = input.int(20, "Retest Timeout (bars)", minval=3, maxval=100, group=grpTrade, display=display.none)
i_orbContracts     = input.int(6, "Contracts", minval=1, maxval=100, group=grpTrade)
i_orbShowSLTP      = input.bool(true, "Show SL/TP Lines", group=grpTrade)
i_orbShowEntry     = input.bool(true, "Show Entry Arrows", group=grpTrade)
 
 
// ── Day & Time Filters ──
grpFilter = "Day & Time Filters"
i_filterMon = input.bool(true, "Monday", group=grpFilter, inline="days")
i_filterTue = input.bool(false, "Tuesday", group=grpFilter, inline="days")
i_filterWed = input.bool(true, "Wednesday", group=grpFilter, inline="days2")
i_filterThu = input.bool(true, "Thursday", group=grpFilter, inline="days2")
i_filterFri = input.bool(true, "Friday", group=grpFilter, inline="days3")
i_flatWindowEnable = input.bool(true, "Prop Firm Flat Window", tooltip="Flatten all positions and block new entries during this time window. Common for prop firms that require flat positions during certain hours.", group=grpFilter)
i_flatWindowStart  = input.string("1300", "Flat Start (HHMM)", group=grpFilter, inline="flat")
i_flatWindowEnd    = input.string("1500", "Flat End (HHMM)", group=grpFilter, inline="flat")
 
// Day filter check
f_dayAllowed() =>
    int dow = dayofweek(time, i_timezone)
    dow == dayofweek.monday    ? i_filterMon :
     dow == dayofweek.tuesday   ? i_filterTue :
     dow == dayofweek.wednesday ? i_filterWed :
     dow == dayofweek.thursday  ? i_filterThu :
     dow == dayofweek.friday    ? i_filterFri : false
 
dayAllowed = f_dayAllowed()
 
// Prop firm flat window check
_flatStartH = math.floor(str.tonumber(i_flatWindowStart) / 100)
_flatStartM = str.tonumber(i_flatWindowStart) % 100
_flatEndH   = math.floor(str.tonumber(i_flatWindowEnd) / 100)
_flatEndM   = str.tonumber(i_flatWindowEnd) % 100
_curH = hour(time, i_timezone)
_curM = minute(time, i_timezone)
_curTime = _curH * 60 + _curM
_flatStart = _flatStartH * 60 + _flatStartM
_flatEnd   = _flatEndH * 60 + _flatEndM
inFlatWindow = i_flatWindowEnable and (_flatStart < _flatEnd ? (_curTime >= _flatStart and _curTime < _flatEnd) : (_curTime >= _flatStart or _curTime < _flatEnd))
flatWindowJustStarted = inFlatWindow and not inFlatWindow[1]
 
// ── Trailing Stop Settings ──
grpTrail = "Trailing Stop"
i_trailEnable   = input.bool(true, "Enable Trailing Stop", tooltip="After price moves N ticks past a TP, the stop moves to that TP level. If price retraces to the armed level, the position is closed.", group=grpTrail)
i_trailArmTicks = input.int(20, "Arm Distance (ticks past TP)", minval=1, maxval=200, tooltip="How many ticks beyond a TP level price must travel before the stop trails up to that TP.", group=grpTrail)
i_trailShowLine = input.bool(true, "Show Trail Stop Line", group=grpTrail)
 
// ── Re-Arm Settings ──
grpRearm = "Re-Arm After Trade"
i_rearmEnable     = input.bool(false, "Enable Re-Arm", tooltip="After a trade closes, the system can re-arm for a new breakout based on the settings below.", group=grpRearm)
i_rearmMaxTrades  = input.int(5, "Max Trades Per Session", minval=1, maxval=20, tooltip="Maximum number of entries allowed per session (including re-arms).", group=grpRearm)
i_rearmAfter      = input.string("Both", "Re-Arm After", options=["SL Only", "TP Only", "Both"], tooltip="Which exit types allow re-arming.\nSL Only: only re-arm after a stop loss.\nTP Only: only re-arm after take profit.\nBoth: re-arm after either.", group=grpRearm)
i_rearmDirection  = input.string("Both Directions", "Direction", options=["Same Direction", "Opposite Direction", "Both Directions"], tooltip="Same: re-arm only for the same direction as last trade.\nOpposite: only allow the opposite direction (flips each time).\nBoth: allow either direction.", group=grpRearm)
i_rearmCooldown   = input.int(0, "Cooldown Bars", minval=0, maxval=50, tooltip="Minimum bars to wait after a trade closes before re-arm process begins. 0 = no cooldown.", group=grpRearm)
i_rearmBars       = input.int(0, "Bars Inside ORB", minval=0, maxval=50, tooltip="After cooldown, how many bars with a close inside the ORB range (with buffer) before re-arming. 0 = re-arm immediately after cooldown.", group=grpRearm)
i_rearmBuffer     = input.int(0, "Buffer (ticks inside ORB)", minval=0, maxval=100, tooltip="Price must be this many ticks inside the ORB boundary to count as inside. 0 = touching the edge counts.", group=grpRearm)
 
 
// ════════════════════════════════════════════════════════════════════════════════
// SESSION 1: NEW YORK
// ════════════════════════════════════════════════════════════════════════════════
grpNY = "Session 1: New York ORB"
i_nyEnable     = input.bool(true, "Enable NY Session", group=grpNY)
i_nyDirection  = input.string("Both", "Direction", options=["Long Only", "Short Only", "Both"], group=grpNY)
i_nyContrarian = input.bool(false, "Contrarian Mode", tooltip="Flip entry direction: break above ORB = Short, break below = Long. SL/TP logic unchanged.", group=grpNY)
i_nyFlattenEOD = input.bool(true, "Flatten at Session End", group=grpNY)
i_nyORBStart   = input.string("0930", "ORB Start (HHMM)", group=grpNY)
i_nyORBDur     = input.string("15 Min", "ORB Duration", options=["5 Min", "15 Min", "30 Min", "1 Hour", "Custom"], group=grpNY)
i_nyORBEnd     = input.string("0945", "ORB Custom End (HHMM)", tooltip="Only used when Duration = Custom", group=grpNY, display=display.none)
i_nySessEnd    = input.string("1600", "Session End (HHMM)", tooltip="Go flat and reset at this time.", group=grpNY)
i_nyHistory    = input.int(30, "Days to Show", minval=1, maxval=50, group=grpNY, display=display.none)
i_nyLineWidth  = input.int(3, "Line Thickness", minval=1, maxval=5, group=grpNY, display=display.none)
i_nyHighColor  = input.color(color.new(#00d4ff, 0), "High Color", group=grpNY, display=display.none)
i_nyLowColor   = input.color(color.new(#00d4ff, 0), "Low Color", group=grpNY, display=display.none)
i_nyMidColor   = input.color(color.new(#00d4ff, 50), "Midline Color", group=grpNY, display=display.none)
i_nyShowMid    = input.bool(true, "Show Midline", group=grpNY, display=display.none)
i_nySLMethod   = input.string("Opposite Side", "Stop Loss", options=["Midpoint", "Opposite Side", "Fixed Points"], group=grpNY)
i_nySLPoints   = input.float(20.0, "SL Fixed Points", minval=0.25, step=0.25, group=grpNY, display=display.none)
i_nyTP1RR      = input.float(1.0, "TP1 R:R", minval=0.1, step=0.1, group=grpNY, inline="nytp1")
i_nyTP1Qty     = input.int(6, "Qty", minval=1, maxval=100, group=grpNY, inline="nytp1")
i_nyTP2RR      = input.float(2.0, "TP2 R:R", minval=0.1, step=0.1, group=grpNY, inline="nytp2")
i_nyTP2Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpNY, inline="nytp2")
i_nyTP3RR      = input.float(3.0, "TP3 R:R", minval=0.1, step=0.1, group=grpNY, inline="nytp3")
i_nyTP3Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpNY, inline="nytp3")
 
// ════════════════════════════════════════════════════════════════════════════════
// SESSION 2: ASIA
// ════════════════════════════════════════════════════════════════════════════════
grpAS = "Session 2: Asia ORB"
i_asEnable     = input.bool(true, "Enable Asia Session", group=grpAS)
i_asDirection  = input.string("Both", "Direction", options=["Long Only", "Short Only", "Both"], group=grpAS)
i_asContrarian = input.bool(false, "Contrarian Mode", tooltip="Flip entry direction: break above ORB = Short, break below = Long. SL/TP logic unchanged.", group=grpAS)
i_asFlattenEOD = input.bool(true, "Flatten at Session End", group=grpAS)
i_asORBStart   = input.string("1800", "ORB Start (HHMM)", group=grpAS)
i_asORBDur     = input.string("15 Min", "ORB Duration", options=["5 Min", "15 Min", "30 Min", "1 Hour", "Custom"], group=grpAS)
i_asORBEnd     = input.string("1815", "ORB Custom End (HHMM)", tooltip="Only used when Duration = Custom", group=grpAS, display=display.none)
i_asSessEnd    = input.string("0300", "Session End (HHMM)", tooltip="Go flat and reset at this time.", group=grpAS)
i_asHistory    = input.int(30, "Days to Show", minval=1, maxval=50, group=grpAS, display=display.none)
i_asLineWidth  = input.int(3, "Line Thickness", minval=1, maxval=5, group=grpAS, display=display.none)
i_asHighColor  = input.color(color.new(#e040fb, 0), "High Color", group=grpAS, display=display.none)
i_asLowColor   = input.color(color.new(#e040fb, 0), "Low Color", group=grpAS, display=display.none)
i_asMidColor   = input.color(color.new(#e040fb, 50), "Midline Color", group=grpAS, display=display.none)
i_asShowMid    = input.bool(true, "Show Midline", group=grpAS, display=display.none)
i_asSLMethod   = input.string("Opposite Side", "Stop Loss", options=["Midpoint", "Opposite Side", "Fixed Points"], group=grpAS)
i_asSLPoints   = input.float(20.0, "SL Fixed Points", minval=0.25, step=0.25, group=grpAS, display=display.none)
i_asTP1RR      = input.float(1.0, "TP1 R:R", minval=0.1, step=0.1, group=grpAS, inline="astp1")
i_asTP1Qty     = input.int(6, "Qty", minval=1, maxval=100, group=grpAS, inline="astp1")
i_asTP2RR      = input.float(2.0, "TP2 R:R", minval=0.1, step=0.1, group=grpAS, inline="astp2")
i_asTP2Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpAS, inline="astp2")
i_asTP3RR      = input.float(3.0, "TP3 R:R", minval=0.1, step=0.1, group=grpAS, inline="astp3")
i_asTP3Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpAS, inline="astp3")
 
// ════════════════════════════════════════════════════════════════════════════════
// SESSION 3: LONDON
// ════════════════════════════════════════════════════════════════════════════════
grpLN = "Session 3: London ORB"
i_lnEnable     = input.bool(true, "Enable London Session", group=grpLN)
i_lnDirection  = input.string("Both", "Direction", options=["Long Only", "Short Only", "Both"], group=grpLN)
i_lnContrarian = input.bool(false, "Contrarian Mode", tooltip="Flip entry direction: break above ORB = Short, break below = Long. SL/TP logic unchanged.", group=grpLN)
i_lnFlattenEOD = input.bool(true, "Flatten at Session End", group=grpLN)
i_lnORBStart   = input.string("0300", "ORB Start (HHMM)", group=grpLN)
i_lnORBDur     = input.string("15 Min", "ORB Duration", options=["5 Min", "15 Min", "30 Min", "1 Hour", "Custom"], group=grpLN)
i_lnORBEnd     = input.string("0315", "ORB Custom End (HHMM)", tooltip="Only used when Duration = Custom", group=grpLN, display=display.none)
i_lnSessEnd    = input.string("0930", "Session End (HHMM)", tooltip="Go flat and reset at this time.", group=grpLN)
i_lnHistory    = input.int(30, "Days to Show", minval=1, maxval=50, group=grpLN, display=display.none)
i_lnLineWidth  = input.int(3, "Line Thickness", minval=1, maxval=5, group=grpLN, display=display.none)
i_lnHighColor  = input.color(color.new(#ff9800, 0), "High Color", group=grpLN, display=display.none)
i_lnLowColor   = input.color(color.new(#ff9800, 0), "Low Color", group=grpLN, display=display.none)
i_lnMidColor   = input.color(color.new(#ff9800, 50), "Midline Color", group=grpLN, display=display.none)
i_lnShowMid    = input.bool(true, "Show Midline", group=grpLN, display=display.none)
i_lnSLMethod   = input.string("Opposite Side", "Stop Loss", options=["Midpoint", "Opposite Side", "Fixed Points"], group=grpLN)
i_lnSLPoints   = input.float(20.0, "SL Fixed Points", minval=0.25, step=0.25, group=grpLN, display=display.none)
i_lnTP1RR      = input.float(1.0, "TP1 R:R", minval=0.1, step=0.1, group=grpLN, inline="lntp1")
i_lnTP1Qty     = input.int(6, "Qty", minval=1, maxval=100, group=grpLN, inline="lntp1")
i_lnTP2RR      = input.float(2.0, "TP2 R:R", minval=0.1, step=0.1, group=grpLN, inline="lntp2")
i_lnTP2Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpLN, inline="lntp2")
i_lnTP3RR      = input.float(3.0, "TP3 R:R", minval=0.1, step=0.1, group=grpLN, inline="lntp3")
i_lnTP3Qty     = input.int(0, "Qty", minval=0, maxval=100, group=grpLN, inline="lntp3")
 
// ════════════════════════════════════════════════════════════════════════════════
// OVERLAY SETTINGS
// ════════════════════════════════════════════════════════════════════════════════
grpSessions = "Session Overlay Mode"
sessionMode = input.string("Full Sessions", "Mode", options=["Kill Zones", "Full Sessions"], group=grpSessions, display=display.none)
 
grpPD = "Previous Day"
showPDHL = input.bool(true, "Show PDH/PDL", group=grpPD)
pdSource = input.string("RTH Only", "PDH/PDL Source", options=["RTH Only", "Full Session (Futures)"], group=grpPD, display=display.none)
rthStart = input.string("0930", "RTH Start (HHMM)", group=grpPD, display=display.none)
rthEnd = input.string("1600", "RTH End (HHMM)", group=grpPD, display=display.none)
fullSessionStart = input.string("1800", "Full Session Start (HHMM)", group=grpPD, display=display.none)
fullSessionEnd = input.string("1700", "Full Session End (HHMM)", group=grpPD, display=display.none)
pdHistory = input.int(1, "Days to Show", minval=0, maxval=10, group=grpPD, display=display.none)
pdLineWidth = input.int(1, "Line Thickness", minval=1, maxval=5, group=grpPD, display=display.none)
pdhColor = input.color(color.new(color.yellow, 0), "Color", group=grpPD, display=display.none)
 
grpAsianOverlay = "Asian Session Overlay"
showAsian = input.bool(true, "Show Asian H/L", group=grpAsianOverlay, display=display.none)
showAsianBox = input.bool(false, "Show Session Box", group=grpAsianOverlay, display=display.none)
showAsianMid = input.bool(false, "Show Midline", group=grpAsianOverlay, display=display.none)
extendAsianLines = input.bool(true, "Extend Lines", group=grpAsianOverlay, display=display.none)
asianExtendUntil = input.string("1130", "Extend Until (HHMM)", group=grpAsianOverlay, display=display.none)
asianStartKZ = input.string("2000", "Kill Zone Start", group=grpAsianOverlay, display=display.none)
asianEndKZ = input.string("0000", "Kill Zone End", group=grpAsianOverlay, display=display.none)
asianStartFull = input.string("1800", "Full Session Start", group=grpAsianOverlay, display=display.none)
asianEndFull = input.string("0300", "Full Session End", group=grpAsianOverlay, display=display.none)
asianHistory = input.int(1, "Days to Show", minval=0, maxval=10, group=grpAsianOverlay, display=display.none)
asianLineWidth = input.int(1, "Line Thickness", minval=1, maxval=5, group=grpAsianOverlay, display=display.none)
asianColor = input.color(color.new(color.purple, 0), "Color", group=grpAsianOverlay, display=display.none)
asianBoxColor = input.color(color.new(color.purple, 90), "Box Fill", group=grpAsianOverlay, display=display.none)
 
grpLondonOverlay = "London Session Overlay"
showLondon = input.bool(true, "Show London H/L", group=grpLondonOverlay, display=display.none)
showLondonBox = input.bool(false, "Show Session Box", group=grpLondonOverlay, display=display.none)
showLondonMid = input.bool(false, "Show Midline", group=grpLondonOverlay, display=display.none)
extendLondonLines = input.bool(true, "Extend Lines", group=grpLondonOverlay, display=display.none)
londonExtendUntil = input.string("1130", "Extend Until (HHMM)", group=grpLondonOverlay, display=display.none)
londonStartKZ = input.string("0200", "Kill Zone Start", group=grpLondonOverlay, display=display.none)
londonEndKZ = input.string("0500", "Kill Zone End", group=grpLondonOverlay, display=display.none)
londonStartFull = input.string("0300", "Full Session Start", group=grpLondonOverlay, display=display.none)
londonEndFull = input.string("0930", "Full Session End", group=grpLondonOverlay, display=display.none)
londonHistory = input.int(1, "Days to Show", minval=0, maxval=10, group=grpLondonOverlay, display=display.none)
londonLineWidth = input.int(1, "Line Thickness", minval=1, maxval=5, group=grpLondonOverlay, display=display.none)
londonColor = input.color(color.new(color.orange, 0), "Color", group=grpLondonOverlay, display=display.none)
londonBoxColor = input.color(color.new(color.orange, 90), "Box Fill", group=grpLondonOverlay, display=display.none)
 
grpNYAMOverlay = "NY AM Session Overlay"
showNYAM = input.bool(false, "Show NY AM H/L", group=grpNYAMOverlay, display=display.none)
showNYAMBox = input.bool(false, "Show Session Box", group=grpNYAMOverlay, display=display.none)
showNYAMMid = input.bool(false, "Show Midline", group=grpNYAMOverlay, display=display.none)
nyamStartKZ = input.string("0830", "Kill Zone Start", group=grpNYAMOverlay, display=display.none)
nyamEndKZ = input.string("1100", "Kill Zone End", group=grpNYAMOverlay, display=display.none)
nyamStartFull = input.string("0930", "Full Session Start", group=grpNYAMOverlay, display=display.none)
nyamEndFull = input.string("1200", "Full Session End", group=grpNYAMOverlay, display=display.none)
nyamHistory = input.int(1, "Days to Show", minval=0, maxval=10, group=grpNYAMOverlay, display=display.none)
nyamLineWidth = input.int(1, "Line Thickness", minval=1, maxval=5, group=grpNYAMOverlay, display=display.none)
nyamColor = input.color(color.new(color.blue, 0), "Color", group=grpNYAMOverlay, display=display.none)
nyamBoxColor = input.color(color.new(color.blue, 90), "Box Fill", group=grpNYAMOverlay, display=display.none)
 
grpNYPMOverlay = "NY PM Session Overlay"
showNYPM = input.bool(false, "Show NY PM H/L", group=grpNYPMOverlay, display=display.none)
showNYPMBox = input.bool(false, "Show Session Box", group=grpNYPMOverlay, display=display.none)
showNYPMMid = input.bool(false, "Show Midline", group=grpNYPMOverlay, display=display.none)
nypmStartKZ = input.string("1330", "Kill Zone Start", group=grpNYPMOverlay, display=display.none)
nypmEndKZ = input.string("1600", "Kill Zone End", group=grpNYPMOverlay, display=display.none)
nypmStartFull = input.string("1200", "Full Session Start", group=grpNYPMOverlay, display=display.none)
nypmEndFull = input.string("1600", "Full Session End", group=grpNYPMOverlay, display=display.none)
nypmHistory = input.int(1, "Days to Show", minval=0, maxval=10, group=grpNYPMOverlay, display=display.none)
nypmLineWidth = input.int(1, "Line Thickness", minval=1, maxval=5, group=grpNYPMOverlay, display=display.none)
nypmColor = input.color(color.new(color.teal, 0), "Color", group=grpNYPMOverlay, display=display.none)
nypmBoxColor = input.color(color.new(color.teal, 90), "Box Fill", group=grpNYPMOverlay, display=display.none)
 
grpFVG = "Fair Value Gaps"
showFVG = input.bool(true, "Show FVGs", group=grpFVG, display=display.none)
fvgThreshold = input.float(0, "Threshold %", minval=0, maxval=5, step=0.1, group=grpFVG, display=display.none)
autoThreshold = input.bool(true, "Auto Threshold", group=grpFVG, display=display.none)
fvgExtend = input.int(50, "Extend Bars", minval=10, maxval=200, group=grpFVG, display=display.none)
fvgMitigation = input.bool(true, "Remove When Mitigated", group=grpFVG, display=display.none)
bullFVGColor = input.color(color.new(#089981, 70), "Bullish FVG", group=grpFVG, display=display.none)
bearFVGColor = input.color(color.new(#f23645, 70), "Bearish FVG", group=grpFVG, display=display.none)
 
grpHTF = "Higher Timeframe Bias"
showDashboard = input.bool(true, "Show Dashboard", group=grpHTF, display=display.none)
htf1 = input.timeframe("240", "Timeframe 1", group=grpHTF, display=display.none)
htf2 = input.timeframe("60", "Timeframe 2", group=grpHTF, display=display.none)
swingLookback = input.int(10, "Swing Lookback", minval=3, maxval=50, group=grpHTF, display=display.none)
dashPosition = input.string("Top Right", "Dashboard Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grpHTF, display=display.none)
dashSize = input.string("Tiny", "Dashboard Size", options=["Tiny", "Small", "Normal"], group=grpHTF, display=display.none)
 
grpDashColors = "Dashboard Colors"
dashBgColor = input.color(color.new(#0d1117, 10), "Background", group=grpDashColors, display=display.none)
dashBorderColor = input.color(color.new(color.gray, 70), "Border", group=grpDashColors, display=display.none)
dashHeaderBg = input.color(color.new(#2962ff, 70), "Header Background", group=grpDashColors, display=display.none)
dashHeaderText = input.color(color.white, "Header Text", group=grpDashColors, display=display.none)
dashLabelColor = input.color(color.gray, "Labels", group=grpDashColors, display=display.none)
dashBullColor = input.color(color.green, "Bullish", group=grpDashColors, display=display.none)
dashBearColor = input.color(color.red, "Bearish", group=grpDashColors, display=display.none)
dashNeutralColor = input.color(color.gray, "Neutral", group=grpDashColors, display=display.none)
 
grpStyle = "Style"
lineStyle = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=grpStyle, display=display.none)
showLabels = input.bool(true, "Show Labels", group=grpStyle, display=display.none)
labelSize = input.string("Tiny", "Label Size", options=["Tiny", "Small", "Normal"], group=grpStyle, display=display.none)
 
// ════════════════════════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════════════════════════
armDist = i_trailArmTicks * syminfo.mintick
rearmBuf = i_rearmBuffer * syminfo.mintick
 
// ── Helper: check if exit type qualifies for re-arm ──
f_exitQualifies(bool wasSL) =>
    (i_rearmAfter == "Both") or (i_rearmAfter == "SL Only" and wasSL) or (i_rearmAfter == "TP Only" and not wasSL)
 
// ── Helper: check if direction is allowed for re-arm ──
// Returns [allowLong, allowShort]
f_dirAllowed(int lastDir) =>
    bool aL = true
    bool aS = true
    if i_rearmDirection == "Same Direction"
        aL := lastDir == 1
        aS := lastDir == -1
    else if i_rearmDirection == "Opposite Direction"
        aL := lastDir == -1
        aS := lastDir == 1
    [aL, aS]
 
 
calcEndTime(simple string startTime, simple string duration) =>
    startHour = math.floor(str.tonumber(str.substring(startTime, 0, 2)))
    startMin = math.floor(str.tonumber(str.substring(startTime, 2, 4)))
    addMins = switch duration
        "5 Min" => 5
        "15 Min" => 15
        "30 Min" => 30
        "1 Hour" => 60
        => 0
    totalMins = startMin + addMins
    endHour = (startHour + math.floor(totalMins / 60)) % 24
    endMin = totalMins % 60
    endHourStr = endHour < 10 ? "0" + str.tostring(endHour) : str.tostring(endHour)
    endMinStr = endMin < 10 ? "0" + str.tostring(endMin) : str.tostring(endMin)
    endHourStr + endMinStr
 
getLineStyle() =>
    switch lineStyle
        "Solid" => line.style_solid
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
 
getLabelSize() =>
    switch labelSize
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
 
getDashSize() =>
    switch dashSize
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
 
formatTF(simple string tf) =>
    switch tf
        "1" => "1m"
        "3" => "3m"
        "5" => "5m"
        "15" => "15m"
        "30" => "30m"
        "45" => "45m"
        "60" => "1H"
        "120" => "2H"
        "180" => "3H"
        "240" => "4H"
        "D" => "1D"
        "W" => "1W"
        => tf
 
// ════════════════════════════════════════════════════════════════════════════════
// TYPES
// ════════════════════════════════════════════════════════════════════════════════
type orbData
    float hi
    float lo
    float mid
    int startBar
    int hiBar
    int loBar
    int endBar
    line hiLine
    line loLine
    line midLine
    label hiLabel
    label loLabel
    label midLabel
 
type levelData
    float hi
    float lo
    float mid
    int startBar
    int hiBar
    int loBar
    line hiLine
    line loLine
    line midLine
    label hiLabel
    label loLabel
    label midLabel
    box sessionBox
 
type fvgData
    float top
    float bottom
    bool isBull
    int barIdx
    box area
 
// ════════════════════════════════════════════════════════════════════════════════
// BUILD SESSION STRINGS
// ════════════════════════════════════════════════════════════════════════════════
nyORBEndTime = i_nyORBDur == "Custom" ? i_nyORBEnd : calcEndTime(i_nyORBStart, i_nyORBDur)
nyORBSession = i_nyORBStart + "-" + nyORBEndTime
nyTradeSession = i_nyORBStart + "-" + i_nySessEnd
 
asORBEndTime = i_asORBDur == "Custom" ? i_asORBEnd : calcEndTime(i_asORBStart, i_asORBDur)
asORBSession = i_asORBStart + "-" + asORBEndTime
asTradeSession = i_asORBStart + "-" + i_asSessEnd
 
lnORBEndTime = i_lnORBDur == "Custom" ? i_lnORBEnd : calcEndTime(i_lnORBStart, i_lnORBDur)
lnORBSession = i_lnORBStart + "-" + lnORBEndTime
lnTradeSession = i_lnORBStart + "-" + i_lnSessEnd
 
pdSession = pdSource == "RTH Only" ? rthStart + "-" + rthEnd : fullSessionStart + "-" + fullSessionEnd
asianSession = sessionMode == "Kill Zones" ? asianStartKZ + "-" + asianEndKZ : asianStartFull + "-" + asianEndFull
londonSession = sessionMode == "Kill Zones" ? londonStartKZ + "-" + londonEndKZ : londonStartFull + "-" + londonEndFull
nyamSession = sessionMode == "Kill Zones" ? nyamStartKZ + "-" + nyamEndKZ : nyamStartFull + "-" + nyamEndFull
nypmSession = sessionMode == "Kill Zones" ? nypmStartKZ + "-" + nypmEndKZ : nypmStartFull + "-" + nypmEndFull
asianEnd_ = sessionMode == "Kill Zones" ? asianEndKZ : asianEndFull
londonEnd_ = sessionMode == "Kill Zones" ? londonEndKZ : londonEndFull
asianExtendSession = asianEnd_ + "-" + asianExtendUntil
londonExtendSession = londonEnd_ + "-" + londonExtendUntil
 
// ════════════════════════════════════════════════════════════════════════════════
// TIME CHECKS
// ════════════════════════════════════════════════════════════════════════════════
inNYORB   = not na(time(timeframe.period, nyORBSession, i_timezone))
inNYTrade = not na(time(timeframe.period, nyTradeSession, i_timezone))
inAsORB   = not na(time(timeframe.period, asORBSession, i_timezone))
inAsTrade = not na(time(timeframe.period, asTradeSession, i_timezone))
inLnORB   = not na(time(timeframe.period, lnORBSession, i_timezone))
inLnTrade = not na(time(timeframe.period, lnTradeSession, i_timezone))
inPDSession = not na(time(timeframe.period, pdSession, i_timezone))
inAsianSession = not na(time(timeframe.period, asianSession, i_timezone))
inLondonSession = not na(time(timeframe.period, londonSession, i_timezone))
inNYAMSession = not na(time(timeframe.period, nyamSession, i_timezone))
inNYPMSession = not na(time(timeframe.period, nypmSession, i_timezone))
inAsianExtend = extendAsianLines and not na(time(timeframe.period, asianExtendSession, i_timezone))
inLondonExtend = extendLondonLines and not na(time(timeframe.period, londonExtendSession, i_timezone))
 
// Per-session TP qty calculations
_nyTp1Qty = math.min(i_nyTP1Qty, i_orbContracts)
_nyTp2Qty = i_nyTP2Qty > 0 ? math.min(i_nyTP2Qty, i_orbContracts - _nyTp1Qty) : 0
_nyTp3Qty = i_nyTP3Qty > 0 ? math.min(i_nyTP3Qty, i_orbContracts - _nyTp1Qty - _nyTp2Qty) : (i_orbContracts - _nyTp1Qty - _nyTp2Qty)
 
_asTp1Qty = math.min(i_asTP1Qty, i_orbContracts)
_asTp2Qty = i_asTP2Qty > 0 ? math.min(i_asTP2Qty, i_orbContracts - _asTp1Qty) : 0
_asTp3Qty = i_asTP3Qty > 0 ? math.min(i_asTP3Qty, i_orbContracts - _asTp1Qty - _asTp2Qty) : (i_orbContracts - _asTp1Qty - _asTp2Qty)
 
_lnTp1Qty = math.min(i_lnTP1Qty, i_orbContracts)
_lnTp2Qty = i_lnTP2Qty > 0 ? math.min(i_lnTP2Qty, i_orbContracts - _lnTp1Qty) : 0
_lnTp3Qty = i_lnTP3Qty > 0 ? math.min(i_lnTP3Qty, i_orbContracts - _lnTp1Qty - _lnTp2Qty) : (i_orbContracts - _lnTp1Qty - _lnTp2Qty)
 
// ════════════════════════════════════════════════════════════════════════════════
// HIGHER TIMEFRAME BIAS
// ════════════════════════════════════════════════════════════════════════════════
[htf1High, htf1Low] = request.security(syminfo.tickerid, htf1, [high, low])
htf1SwingHigh = ta.pivothigh(htf1High, swingLookback, swingLookback)
htf1SwingLow = ta.pivotlow(htf1Low, swingLookback, swingLookback)
var float htf1LastHigh = na, var float htf1PrevHigh = na
var float htf1LastLow = na, var float htf1PrevLow = na
if not na(htf1SwingHigh)
    htf1PrevHigh := htf1LastHigh, htf1LastHigh := htf1SwingHigh
if not na(htf1SwingLow)
    htf1PrevLow := htf1LastLow, htf1LastLow := htf1SwingLow
htf1Bullish = not na(htf1LastHigh) and not na(htf1PrevHigh) and htf1LastHigh > htf1PrevHigh and not na(htf1LastLow) and not na(htf1PrevLow) and htf1LastLow > htf1PrevLow
htf1Bearish = not na(htf1LastHigh) and not na(htf1PrevHigh) and htf1LastHigh < htf1PrevHigh and not na(htf1LastLow) and not na(htf1PrevLow) and htf1LastLow < htf1PrevLow
htf1BiasText = htf1Bullish ? "BULLISH" : htf1Bearish ? "BEARISH" : "NEUTRAL"
htf1BiasColor = htf1Bullish ? dashBullColor : htf1Bearish ? dashBearColor : dashNeutralColor
htf1HH = not na(htf1LastHigh) and not na(htf1PrevHigh) and htf1LastHigh > htf1PrevHigh
htf1LH = not na(htf1LastHigh) and not na(htf1PrevHigh) and htf1LastHigh < htf1PrevHigh
htf1HL = not na(htf1LastLow) and not na(htf1PrevLow) and htf1LastLow > htf1PrevLow
htf1LL = not na(htf1LastLow) and not na(htf1PrevLow) and htf1LastLow < htf1PrevLow
htf1StructureText = (htf1HH ? "HH" : htf1LH ? "LH" : "-") + " / " + (htf1HL ? "HL" : htf1LL ? "LL" : "-")
 
[htf2High, htf2Low] = request.security(syminfo.tickerid, htf2, [high, low])
htf2SwingHigh = ta.pivothigh(htf2High, swingLookback, swingLookback)
htf2SwingLow = ta.pivotlow(htf2Low, swingLookback, swingLookback)
var float htf2LastHigh = na, var float htf2PrevHigh = na
var float htf2LastLow = na, var float htf2PrevLow = na
if not na(htf2SwingHigh)
    htf2PrevHigh := htf2LastHigh, htf2LastHigh := htf2SwingHigh
if not na(htf2SwingLow)
    htf2PrevLow := htf2LastLow, htf2LastLow := htf2SwingLow
htf2Bullish = not na(htf2LastHigh) and not na(htf2PrevHigh) and htf2LastHigh > htf2PrevHigh and not na(htf2LastLow) and not na(htf2PrevLow) and htf2LastLow > htf2PrevLow
htf2Bearish = not na(htf2LastHigh) and not na(htf2PrevHigh) and htf2LastHigh < htf2PrevHigh and not na(htf2LastLow) and not na(htf2PrevLow) and htf2LastLow < htf2PrevLow
htf2BiasText = htf2Bullish ? "BULLISH" : htf2Bearish ? "BEARISH" : "NEUTRAL"
htf2BiasColor = htf2Bullish ? dashBullColor : htf2Bearish ? dashBearColor : dashNeutralColor
htf2HH = not na(htf2LastHigh) and not na(htf2PrevHigh) and htf2LastHigh > htf2PrevHigh
htf2LH = not na(htf2LastHigh) and not na(htf2PrevHigh) and htf2LastHigh < htf2PrevHigh
htf2HL = not na(htf2LastLow) and not na(htf2PrevLow) and htf2LastLow > htf2PrevLow
htf2LL = not na(htf2LastLow) and not na(htf2PrevLow) and htf2LastLow < htf2PrevLow
htf2StructureText = (htf2HH ? "HH" : htf2LH ? "LH" : "-") + " / " + (htf2HL ? "HL" : htf2LL ? "LL" : "-")
 
// ════════════════════════════════════════════════════════════════════════════════
//  TRAILING STOP HELPER
//  Calculates new trail stop given current state. Returns updated trailSL.
//  For longs:  if high >= TPn + armDist, trailSL moves UP to TPn
//  For shorts: if low  <= TPn - armDist, trailSL moves DOWN to TPn
// ════════════════════════════════════════════════════════════════════════════════
calcTrail(int dir, float curTrail, float tp1, float tp2, float tp3, float origSL) =>
    float newTrail = curTrail
    if i_trailEnable and dir != 0
        if dir == 1  // long
            if not na(tp3) and high >= tp3 + armDist
                newTrail := math.max(newTrail, tp3)
            else if not na(tp2) and high >= tp2 + armDist
                newTrail := math.max(newTrail, tp2)
            else if not na(tp1) and high >= tp1 + armDist
                newTrail := math.max(newTrail, tp1)
        else  // short
            if not na(tp3) and low <= tp3 - armDist
                newTrail := math.min(newTrail, tp3)
            else if not na(tp2) and low <= tp2 - armDist
                newTrail := math.min(newTrail, tp2)
            else if not na(tp1) and low <= tp1 - armDist
                newTrail := math.min(newTrail, tp1)
    newTrail
 
 
 
// ── SL/TP Line Style ──
grpLines = "SL/TP Lines"
i_slLineColor  = input.color(color.red, "SL Color", group=grpLines, inline="sl")
i_slLineStyle  = input.string("Dashed", "Style", options=["Solid", "Dashed", "Dotted"], group=grpLines, inline="sl")
i_slLineWidth  = input.int(1, "Width", minval=1, maxval=5, group=grpLines, inline="sl")
i_tpLineColor  = input.color(color.lime, "TP Color", group=grpLines, inline="tp")
i_tpLineStyle  = input.string("Dashed", "Style", options=["Solid", "Dashed", "Dotted"], group=grpLines, inline="tp")
i_tpLineWidth  = input.int(2, "Width", minval=1, maxval=5, group=grpLines, inline="tp")
 
f_lineStyle(string s) =>
    s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed
 
slStyle = f_lineStyle(i_slLineStyle)
tpStyle = f_lineStyle(i_tpLineStyle)
 
// ── Webhook Alert JSON (TradersPost / Ghost compatible) ──
// Set your TradingView alert message to: {{strategy.order.alert_message}}
// Alert on: Order fills only
_jsonBuy   = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "quantity": ' + str.tostring(i_orbContracts) + ', "signalPrice": ' + str.tostring(close) + '}'
_jsonSell  = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "quantity": ' + str.tostring(i_orbContracts) + ', "signalPrice": ' + str.tostring(close) + '}'
_jsonExit  = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "signalPrice": ' + str.tostring(close) + '}'
 
 
 
// ════════════════════════════════════════════════════════════════════════════════
// ═══  NEW YORK ORB MODULE  ══════════════════════════════════════════════════════
// ════════════════════════════════════════════════════════════════════════════════
var orbData[] nyOrbArray = array.new<orbData>(0)
var float nyORBHigh = na, var float nyORBLow = na, var float nyORBMid = na
var int nyOrbStartBar = na, var int nyOrbHighBar = na, var int nyOrbLowBar = na
var bool nyOrbBuilding = false, var bool nyOrbComplete = false
var bool  nySigFired = false, var bool  nyBrkPending = false
var int   nyBrkDir = 0, var int nyBrkBar = 0
var float nySigEntry = na, var float nySigSL = na
var float nySigTP1 = na, var float nySigTP2 = na, var float nySigTP3 = na
var int   nySigDir = 0
var bool  nyTP1Hit = false, var bool nyTP2Hit = false, var bool nyTP3Hit = false, var bool nySLHit = false
var line  nySLLine = na, var line nyTP1Line = na, var line nyTP2Line = na, var line nyTP3Line = na
var label nySLLabel = na, var label nyTP1Label = na, var label nyTP2Label = na, var label nyTP3Label = na
var float nyTrailSL = na
var line  nyTrailLine = na
var label nyTrailLabel = na
var bool nyFlattenDone = false
var int nyTradeCount = 0
var int nyInsideBars = 0
var bool nyLastWasSL = false
var int nyLastDir = 0
var int nyExitBar = 0
var bool nyCooldownDone = false
var bool nyInsideStarted = false
 
nyDay = f_dayKey(time, i_timezone)
nyNewDay = nyDay != nz(nyDay[1], nyDay)
nySessionStart = (inNYTrade and not inNYTrade[1]) or (inNYTrade and nyNewDay)
if nySessionStart
    nyFlattenDone := false
    nyTradeCount := 0
    nyInsideBars := 0
    nyLastWasSL := false
    nyLastDir := 0
    nyExitBar := 0
    nyCooldownDone := false
    nyInsideStarted := false
    nyORBHigh := na, nyORBLow := na, nyORBMid := na
    nyOrbBuilding := false, nyOrbComplete := false
    nyOrbStartBar := na, nyOrbHighBar := na, nyOrbLowBar := na
    nySigFired := false, nyBrkPending := false, nyBrkDir := 0, nyBrkBar := 0
    if strategy.position_size == 0
        nySigDir := 0
    nyTP1Hit := false, nyTP2Hit := false, nyTP3Hit := false, nySLHit := false
    nySigEntry := na, nySigSL := na, nySigTP1 := na, nySigTP2 := na, nySigTP3 := na
    nyTrailSL := na
    // Don't delete old SL/TP lines — they persist for history
    nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
    nySLLabel := na, nyTP1Label := na, nyTP2Label := na, nyTP3Label := na
    nyTrailLine := na, nyTrailLabel := na
 
nySessionEnd = not inNYTrade and inNYTrade[1]
if nySessionEnd and i_nyEnable
    // Freeze ORB lines at session end
    if nyOrbArray.size() > 0
        for j = 0 to nyOrbArray.size() - 1
            _o = nyOrbArray.get(j)
            if na(_o.endBar)
                _o.endBar := bar_index[1]
                nyOrbArray.set(j, _o)
    // Hard flatten: close all positions and cancel pending orders
    // Freeze lines before flatten
    if not na(nySLLine)
        nySLLine.set_x2(bar_index)
    if not na(nyTP1Line)
        nyTP1Line.set_x2(bar_index)
    if not na(nyTP2Line)
        nyTP2Line.set_x2(bar_index)
    if not na(nyTP3Line)
        nyTP3Line.set_x2(bar_index)
    nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
    strategy.close_all(comment="NY End", alert_message=_jsonExit)
    strategy.cancel_all()
    nySigDir := 0
// NY: ORB Build
if i_nyEnable and inNYORB and not nyOrbComplete
    if not nyOrbBuilding
        nyOrbStartBar := bar_index, nyOrbBuilding := true
    if na(nyORBHigh) or high > nyORBHigh
        nyORBHigh := high, nyOrbHighBar := bar_index
    if na(nyORBLow) or low < nyORBLow
        nyORBLow := low, nyOrbLowBar := bar_index
 
if i_nyEnable and not inNYORB and nyOrbBuilding and not nyOrbComplete and not na(nyORBHigh)
    nyOrbComplete := true
    nyORBMid := (nyORBHigh + nyORBLow) / 2
    hiLine = line.new(nyOrbHighBar, nyORBHigh, bar_index, nyORBHigh, color=i_nyHighColor, style=getLineStyle(), width=i_nyLineWidth)
    loLine = line.new(nyOrbLowBar, nyORBLow, bar_index, nyORBLow, color=i_nyLowColor, style=getLineStyle(), width=i_nyLineWidth)
    midLine = i_nyShowMid ? line.new(nyOrbStartBar, nyORBMid, bar_index, nyORBMid, color=i_nyMidColor, style=line.style_dotted, width=math.max(1, i_nyLineWidth - 1)) : na
    hiLabel = showLabels ? label.new(bar_index + 2, nyORBHigh, "NY ORB H", style=label.style_none, textcolor=i_nyHighColor, size=getLabelSize()) : na
    loLabel = showLabels ? label.new(bar_index + 2, nyORBLow, "NY ORB L", style=label.style_none, textcolor=i_nyLowColor, size=getLabelSize()) : na
    midLabel = showLabels and i_nyShowMid ? label.new(bar_index + 2, nyORBMid, "NY ORB M", style=label.style_none, textcolor=i_nyMidColor, size=getLabelSize()) : na
    newOrb = orbData.new(nyORBHigh, nyORBLow, nyORBMid, nyOrbStartBar, nyOrbHighBar, nyOrbLowBar, na, hiLine, loLine, midLine, hiLabel, loLabel, midLabel)
    nyOrbArray.unshift(newOrb)
    if nyOrbArray.size() > i_nyHistory
        old = nyOrbArray.pop()
        old.hiLine.delete(), old.loLine.delete(), old.midLine.delete()
        old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete()
 
// NY: Extend all historic ORB lines
if nyOrbArray.size() > 0
    for i = 0 to nyOrbArray.size() - 1
        cur = nyOrbArray.get(i)
        int _x2 = na(cur.endBar) ? bar_index : cur.endBar
        int _lx = na(cur.endBar) ? (bar_index + 2) : (cur.endBar + 2)
 
        cur.hiLine.set_x2(_x2)
        cur.loLine.set_x2(_x2)
        if i_nyShowMid and not na(cur.midLine)
            cur.midLine.set_x2(_x2)
 
        if i == 0 and showLabels
            cur.hiLabel.set_x(_lx)
            cur.loLabel.set_x(_lx)
            if i_nyShowMid and not na(cur.midLabel)
                cur.midLabel.set_x(_lx)
        else
            cur.hiLabel.delete()
            cur.loLabel.delete()
            if not na(cur.midLabel)
                cur.midLabel.delete()
            cur.hiLabel := na
            cur.loLabel := na
            cur.midLabel := na
 
// NY: Signals
 
 
nyCrossUp = ta.crossover(close, nyORBHigh)
nyHighBreak = nyOrbComplete and inNYTrade and nyCrossUp
nyCrossDn = ta.crossunder(close, nyORBLow)
nyLowBreak  = nyOrbComplete and inNYTrade and nyCrossDn
bool nyLongSig = false, bool nyShortSig = false
 
if i_nyEnable and nyBrkPending and bar_index > nyBrkBar and not nySigFired
    _retestLvl = i_orbEntryMode == "Retest Midpoint" ? nyORBMid : (nyBrkDir == 1 ? nyORBHigh : nyORBLow)
    if nyBrkDir == 1
        if low <= _retestLvl and close > nyORBHigh
            nyLongSig := true, nyBrkPending := false
        else if close <= nyORBHigh
            nyBrkPending := false
    else if nyBrkDir == -1
        if high >= _retestLvl and close < nyORBLow
            nyShortSig := true, nyBrkPending := false
        else if close >= nyORBLow
            nyBrkPending := false
    if nyBrkPending and bar_index - nyBrkBar >= i_orbRetestTimeout
        nyBrkPending := false
 
if i_nyEnable and nyOrbComplete and inNYTrade and not nySigFired and (nyTradeCount < i_rearmMaxTrades or not i_rearmEnable)
    if nyHighBreak and not nyBrkPending
        if i_orbEntryMode == "Breakout"
            nyLongSig := true
        else
            nyBrkPending := true, nyBrkDir := 1, nyBrkBar := bar_index
    else if nyLowBreak and not nyBrkPending
        if i_orbEntryMode == "Breakout"
            nyShortSig := true
        else
            nyBrkPending := true, nyBrkDir := -1, nyBrkBar := bar_index
// NY: Contrarian mode — flip signals
if i_nyContrarian
    bool _tmpL = nyLongSig
    bool _tmpS = nyShortSig
    nyLongSig := _tmpS
    nyShortSig := _tmpL
// NY: Direction filter on re-armed signals
if i_rearmEnable and nyTradeCount > 0 and nyLastDir != 0
    [nyAllowL, nyAllowS] = f_dirAllowed(nyLastDir)
    if nyLongSig and not nyAllowL
        nyLongSig := false
    if nyShortSig and not nyAllowS
        nyShortSig := false
 
 
// NY: Entry Long
if barstate.isconfirmed and nyLongSig and dayAllowed and not inFlatWindow and i_nyDirection != "Short Only"
    nySigFired := true, nySigEntry := close, nySigDir := 1
    nyTradeCount += 1
    nySigSL := i_nySLMethod == "Midpoint" ? nyORBMid : i_nySLMethod == "Opposite Side" ? nyORBLow : close - i_nySLPoints
    _risk = math.abs(nySigEntry - nySigSL)
    if _risk > 0
        nySigTP1 := nySigEntry + _risk * i_nyTP1RR, nySigTP2 := nySigEntry + _risk * i_nyTP2RR, nySigTP3 := nySigEntry + _risk * i_nyTP3RR
    nyTrailSL := nySigSL
    strategy.entry("NY Long", strategy.long, qty=i_orbContracts, alert_message=_jsonBuy)
    if _risk > 0
        strategy.exit("NY TP1", from_entry="NY Long", qty=_nyTp1Qty, limit=nySigTP1, stop=nySigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _nyTp2Qty > 0
            strategy.exit("NY TP2", from_entry="NY Long", qty=_nyTp2Qty, limit=nySigTP2, stop=nySigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _nyTp3Qty > 0
            strategy.exit("NY TP3", from_entry="NY Long", qty=_nyTp3Qty, limit=nySigTP3, stop=nySigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("NY SL", from_entry="NY Long", stop=nySigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        nySLLine  := line.new(bar_index, nySigSL, bar_index + 1, nySigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        nySLLabel := showLabels ? label.new(bar_index + 2, nySigSL, "SL", style=label.style_none, textcolor=i_slLineColor, size=getLabelSize()) : na
        if not na(nySigTP1)
            nyTP1Line := line.new(bar_index, nySigTP1, bar_index + 1, nySigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
            nyTP1Label := showLabels ? label.new(bar_index + 2, nySigTP1, "TP1", style=label.style_none, textcolor=i_tpLineColor, size=getLabelSize()) : na
        if not na(nySigTP2) and _nyTp2Qty > 0
            nyTP2Line := line.new(bar_index, nySigTP2, bar_index + 1, nySigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
            nyTP2Label := showLabels ? label.new(bar_index + 2, nySigTP2, "TP2", style=label.style_none, textcolor=i_tpLineColor, size=getLabelSize()) : na
        if not na(nySigTP3) and _nyTp3Qty > 0
            nyTP3Line := line.new(bar_index, nySigTP3, bar_index + 1, nySigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
            nyTP3Label := showLabels ? label.new(bar_index + 2, nySigTP3, "TP3", style=label.style_none, textcolor=i_tpLineColor, size=getLabelSize()) : na
 
// NY: Entry Short
if barstate.isconfirmed and nyShortSig and dayAllowed and not inFlatWindow and i_nyDirection != "Long Only"
    nySigFired := true, nySigEntry := close, nySigDir := -1
    nyTradeCount += 1
    nySigSL := i_nySLMethod == "Midpoint" ? nyORBMid : i_nySLMethod == "Opposite Side" ? nyORBHigh : close + i_nySLPoints
    _risk = math.abs(nySigSL - nySigEntry)
    if _risk > 0
        nySigTP1 := nySigEntry - _risk * i_nyTP1RR, nySigTP2 := nySigEntry - _risk * i_nyTP2RR, nySigTP3 := nySigEntry - _risk * i_nyTP3RR
    nyTrailSL := nySigSL
    strategy.entry("NY Short", strategy.short, qty=i_orbContracts, alert_message=_jsonSell)
    if _risk > 0
        strategy.exit("NY TP1", from_entry="NY Short", qty=_nyTp1Qty, limit=nySigTP1, stop=nySigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _nyTp2Qty > 0
            strategy.exit("NY TP2", from_entry="NY Short", qty=_nyTp2Qty, limit=nySigTP2, stop=nySigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _nyTp3Qty > 0
            strategy.exit("NY TP3", from_entry="NY Short", qty=_nyTp3Qty, limit=nySigTP3, stop=nySigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("NY SL", from_entry="NY Short", stop=nySigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        nySLLine  := line.new(bar_index, nySigSL, bar_index + 1, nySigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        if not na(nySigTP1)
            nyTP1Line := line.new(bar_index, nySigTP1, bar_index + 1, nySigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
        if not na(nySigTP2) and _nyTp2Qty > 0
            nyTP2Line := line.new(bar_index, nySigTP2, bar_index + 1, nySigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
        if not na(nySigTP3) and _nyTp3Qty > 0
            nyTP3Line := line.new(bar_index, nySigTP3, bar_index + 1, nySigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
 
// NY: Trailing Stop Update
if i_trailEnable and nySigDir != 0 and not nySLHit and strategy.position_size != 0
    _prevTrail = nyTrailSL
    nyTrailSL := calcTrail(nySigDir, nyTrailSL, nySigTP1, nySigTP2, nySigTP3, nySigSL)
    if nyTrailSL != _prevTrail
        // Re-issue exits with new trail stop for remaining qty
        if nySigDir == 1
            strategy.exit("NY TP1", from_entry="NY Long", qty=_nyTp1Qty, limit=nySigTP1, stop=nyTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _nyTp2Qty > 0
                strategy.exit("NY TP2", from_entry="NY Long", qty=_nyTp2Qty, limit=nySigTP2, stop=nyTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _nyTp3Qty > 0
                strategy.exit("NY TP3", from_entry="NY Long", qty=_nyTp3Qty, limit=nySigTP3, stop=nyTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
        else
            strategy.exit("NY TP1", from_entry="NY Short", qty=_nyTp1Qty, limit=nySigTP1, stop=nyTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _nyTp2Qty > 0
                strategy.exit("NY TP2", from_entry="NY Short", qty=_nyTp2Qty, limit=nySigTP2, stop=nyTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _nyTp3Qty > 0
                strategy.exit("NY TP3", from_entry="NY Short", qty=_nyTp3Qty, limit=nySigTP3, stop=nyTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    // Draw trail line
    if i_trailShowLine and nyTrailSL != nySigSL
        nyTrailLine := line.new(bar_index - 1, nyTrailSL, bar_index, nyTrailSL, color=color.new(color.yellow, 0), style=line.style_dotted, width=2)
        nyTrailLabel := showLabels ? label.new(bar_index + 2, nyTrailSL, "TRAIL", style=label.style_none, textcolor=color.yellow, size=getLabelSize()) : na
 
 
 
// NY: SL/TP line extend to current bar while trade active
if nySigDir != 0 and i_orbShowSLTP
    if not na(nySLLine)
        nySLLine.set_x2(bar_index)
    if not na(nyTP1Line)
        nyTP1Line.set_x2(bar_index)
    if not na(nyTP2Line)
        nyTP2Line.set_x2(bar_index)
    if not na(nyTP3Line)
        nyTP3Line.set_x2(bar_index)
 
if i_nyEnable and nySigDir != 0 and not nySLHit
    if nySigDir == 1
        if low <= nyTrailSL
            nySLHit := true
            nyLastWasSL := true
            nyLastDir := nySigDir
            nyExitBar := bar_index
            nyCooldownDone := false
            nyInsideStarted := false
            nyInsideBars := 0
            nySigDir := 0
            // Freeze SL/TP lines at exit bar
            if not na(nySLLine)
                nySLLine.set_x2(bar_index)
            if not na(nyTP1Line)
                nyTP1Line.set_x2(bar_index)
            if not na(nyTP2Line)
                nyTP2Line.set_x2(bar_index)
            if not na(nyTP3Line)
                nyTP3Line.set_x2(bar_index)
            nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
        else
            if not nyTP1Hit and high >= nySigTP1
                nyTP1Hit := true
            if not nyTP2Hit and high >= nySigTP2
                nyTP2Hit := true
            if not nyTP3Hit and high >= nySigTP3
                nyTP3Hit := true
    else if nySigDir == -1
        if high >= nyTrailSL
            nySLHit := true
            nyLastWasSL := true
            nyLastDir := nySigDir
            nyExitBar := bar_index
            nyCooldownDone := false
            nyInsideStarted := false
            nyInsideBars := 0
            nySigDir := 0
            if not na(nySLLine)
                nySLLine.set_x2(bar_index)
            if not na(nyTP1Line)
                nyTP1Line.set_x2(bar_index)
            if not na(nyTP2Line)
                nyTP2Line.set_x2(bar_index)
            if not na(nyTP3Line)
                nyTP3Line.set_x2(bar_index)
            nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
        else
            if not nyTP1Hit and low <= nySigTP1
                nyTP1Hit := true
            if not nyTP2Hit and low <= nySigTP2
                nyTP2Hit := true
            if not nyTP3Hit and low <= nySigTP3
                nyTP3Hit := true
 
// NY: Detect TP exit (position closed without SL — requires prior bar had position)
if i_nyEnable and nySigFired and nySigDir != 0 and strategy.position_size == 0 and strategy.position_size[1] != 0 and not nySLHit
    nyLastWasSL := false
    nyLastDir := nySigDir
    nyExitBar := bar_index
    nyCooldownDone := false
    nyInsideStarted := false
    nyInsideBars := 0
    nySigDir := 0
    // Freeze SL/TP lines at exit bar
    if not na(nySLLine)
        nySLLine.set_x2(bar_index)
    if not na(nyTP1Line)
        nyTP1Line.set_x2(bar_index)
    if not na(nyTP2Line)
        nyTP2Line.set_x2(bar_index)
    if not na(nyTP3Line)
        nyTP3Line.set_x2(bar_index)
    nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
plotshape(i_orbShowEntry and nyLongSig,  title="NY Long",  style=shape.triangleup,   location=location.belowbar, color=color.green, size=size.small, text="NY LONG")
plotshape(i_orbShowEntry and nyShortSig, title="NY Short", style=shape.triangledown, location=location.abovebar, color=color.red,   size=size.small, text="NY SHORT")
 
 
// ════════════════════════════════════════════════════════════════════════════════
// ═══  ASIA ORB MODULE  ══════════════════════════════════════════════════════════
// ════════════════════════════════════════════════════════════════════════════════
var orbData[] asOrbArray = array.new<orbData>(0)
var float asORBHigh = na, var float asORBLow = na, var float asORBMid = na
var int asOrbStartBar = na, var int asOrbHighBar = na, var int asOrbLowBar = na
var bool asOrbBuilding = false, var bool asOrbComplete = false
var bool  asSigFired = false, var bool  asBrkPending = false
var int   asBrkDir = 0, var int asBrkBar = 0
var float asSigEntry = na, var float asSigSL = na
var float asSigTP1 = na, var float asSigTP2 = na, var float asSigTP3 = na
var int   asSigDir = 0
var bool  asTP1Hit = false, var bool asTP2Hit = false, var bool asTP3Hit = false, var bool asSLHit = false
var line  asSLLine = na, var line asTP1Line = na, var line asTP2Line = na, var line asTP3Line = na
var label asSLLabel = na, var label asTP1Label = na, var label asTP2Label = na, var label asTP3Label = na
var float asTrailSL = na
var line  asTrailLine = na
var label asTrailLabel = na
var bool asFlattenDone = false
var int asTradeCount = 0
var int asInsideBars = 0
var bool asLastWasSL = false
var int asLastDir = 0
var int asExitBar = 0
var bool asCooldownDone = false
var bool asInsideStarted = false
 
asDay = f_dayKey(time, i_timezone)
asNewDay = asDay != nz(asDay[1], asDay)
asSessionStart = (inAsTrade and not inAsTrade[1]) or (inAsTrade and asNewDay)
if asSessionStart
    asFlattenDone := false
    asTradeCount := 0
    asInsideBars := 0
    asLastWasSL := false
    asLastDir := 0
    asExitBar := 0
    asCooldownDone := false
    asInsideStarted := false
    asORBHigh := na, asORBLow := na, asORBMid := na
    asOrbBuilding := false, asOrbComplete := false
    asOrbStartBar := na, asOrbHighBar := na, asOrbLowBar := na
    asSigFired := false, asBrkPending := false, asBrkDir := 0, asBrkBar := 0
    if strategy.position_size == 0
        asSigDir := 0
    asTP1Hit := false, asTP2Hit := false, asTP3Hit := false, asSLHit := false
    asSigEntry := na, asSigSL := na, asSigTP1 := na, asSigTP2 := na, asSigTP3 := na
    asTrailSL := na
    // Don't delete old SL/TP lines — they persist for history
    asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
    asSLLabel := na, asTP1Label := na, asTP2Label := na, asTP3Label := na
    asTrailLine := na, asTrailLabel := na
 
asSessionEnd = not inAsTrade and inAsTrade[1]
if asSessionEnd and i_asEnable
    // Freeze ORB lines at session end
    if asOrbArray.size() > 0
        for j = 0 to asOrbArray.size() - 1
            _o = asOrbArray.get(j)
            if na(_o.endBar)
                _o.endBar := bar_index[1]
                asOrbArray.set(j, _o)
    // Hard flatten: close all positions and cancel pending orders
    // Freeze lines before flatten
    if not na(asSLLine)
        asSLLine.set_x2(bar_index)
    if not na(asTP1Line)
        asTP1Line.set_x2(bar_index)
    if not na(asTP2Line)
        asTP2Line.set_x2(bar_index)
    if not na(asTP3Line)
        asTP3Line.set_x2(bar_index)
    asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
    strategy.close_all(comment="AS End", alert_message=_jsonExit)
    strategy.cancel_all()
    asSigDir := 0
if i_asEnable and inAsORB and not asOrbComplete
    if not asOrbBuilding
        asOrbStartBar := bar_index, asOrbBuilding := true
    if na(asORBHigh) or high > asORBHigh
        asORBHigh := high, asOrbHighBar := bar_index
    if na(asORBLow) or low < asORBLow
        asORBLow := low, asOrbLowBar := bar_index
 
if i_asEnable and not inAsORB and asOrbBuilding and not asOrbComplete and not na(asORBHigh)
    asOrbComplete := true
    asORBMid := (asORBHigh + asORBLow) / 2
    hiLine = line.new(asOrbHighBar, asORBHigh, bar_index, asORBHigh, color=i_asHighColor, style=getLineStyle(), width=i_asLineWidth)
    loLine = line.new(asOrbLowBar, asORBLow, bar_index, asORBLow, color=i_asLowColor, style=getLineStyle(), width=i_asLineWidth)
    midLine = i_asShowMid ? line.new(asOrbStartBar, asORBMid, bar_index, asORBMid, color=i_asMidColor, style=line.style_dotted, width=math.max(1, i_asLineWidth - 1)) : na
    hiLabel = showLabels ? label.new(bar_index + 2, asORBHigh, "ASIA ORB H", style=label.style_none, textcolor=i_asHighColor, size=getLabelSize()) : na
    loLabel = showLabels ? label.new(bar_index + 2, asORBLow, "ASIA ORB L", style=label.style_none, textcolor=i_asLowColor, size=getLabelSize()) : na
    midLabel = showLabels and i_asShowMid ? label.new(bar_index + 2, asORBMid, "ASIA ORB M", style=label.style_none, textcolor=i_asMidColor, size=getLabelSize()) : na
    newOrb = orbData.new(asORBHigh, asORBLow, asORBMid, asOrbStartBar, asOrbHighBar, asOrbLowBar, na, hiLine, loLine, midLine, hiLabel, loLabel, midLabel)
    asOrbArray.unshift(newOrb)
    if asOrbArray.size() > i_asHistory
        old = asOrbArray.pop()
        old.hiLine.delete(), old.loLine.delete(), old.midLine.delete()
        old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete()
 
if asOrbArray.size() > 0
    for i = 0 to asOrbArray.size() - 1
        cur = asOrbArray.get(i)
        int _x2 = na(cur.endBar) ? bar_index : cur.endBar
        int _lx = na(cur.endBar) ? (bar_index + 2) : (cur.endBar + 2)
 
        cur.hiLine.set_x2(_x2)
        cur.loLine.set_x2(_x2)
        if i_asShowMid and not na(cur.midLine)
            cur.midLine.set_x2(_x2)
 
        if i == 0 and showLabels
            cur.hiLabel.set_x(_lx)
            cur.loLabel.set_x(_lx)
            if i_asShowMid and not na(cur.midLabel)
                cur.midLabel.set_x(_lx)
        else
            cur.hiLabel.delete()
            cur.loLabel.delete()
            if not na(cur.midLabel)
                cur.midLabel.delete()
            cur.hiLabel := na
            cur.loLabel := na
            cur.midLabel := na
 
 
 
asCrossUp = ta.crossover(close, asORBHigh)
asHighBreak = asOrbComplete and inAsTrade and asCrossUp
asCrossDn = ta.crossunder(close, asORBLow)
asLowBreak  = asOrbComplete and inAsTrade and asCrossDn
bool asLongSig = false, bool asShortSig = false
 
if i_asEnable and asBrkPending and bar_index > asBrkBar and not asSigFired
    _retestLvl = i_orbEntryMode == "Retest Midpoint" ? asORBMid : (asBrkDir == 1 ? asORBHigh : asORBLow)
    if asBrkDir == 1
        if low <= _retestLvl and close > asORBHigh
            asLongSig := true, asBrkPending := false
        else if close <= asORBHigh
            asBrkPending := false
    else if asBrkDir == -1
        if high >= _retestLvl and close < asORBLow
            asShortSig := true, asBrkPending := false
        else if close >= asORBLow
            asBrkPending := false
    if asBrkPending and bar_index - asBrkBar >= i_orbRetestTimeout
        asBrkPending := false
 
if i_asEnable and asOrbComplete and inAsTrade and not asSigFired and (asTradeCount < i_rearmMaxTrades or not i_rearmEnable)
    if asHighBreak and not asBrkPending
        if i_orbEntryMode == "Breakout"
            asLongSig := true
        else
            asBrkPending := true, asBrkDir := 1, asBrkBar := bar_index
    else if asLowBreak and not asBrkPending
        if i_orbEntryMode == "Breakout"
            asShortSig := true
        else
            asBrkPending := true, asBrkDir := -1, asBrkBar := bar_index
// AS: Contrarian mode — flip signals
if i_asContrarian
    bool _tmpL = asLongSig
    bool _tmpS = asShortSig
    asLongSig := _tmpS
    asShortSig := _tmpL
// AS: Direction filter on re-armed signals
if i_rearmEnable and asTradeCount > 0 and asLastDir != 0
    [asAllowL, asAllowS] = f_dirAllowed(asLastDir)
    if asLongSig and not asAllowL
        asLongSig := false
    if asShortSig and not asAllowS
        asShortSig := false
 
 
if barstate.isconfirmed and asLongSig and dayAllowed and not inFlatWindow and i_asDirection != "Short Only"
    asSigFired := true, asSigEntry := close, asSigDir := 1
    asTradeCount += 1
    asSigSL := i_asSLMethod == "Midpoint" ? asORBMid : i_asSLMethod == "Opposite Side" ? asORBLow : close - i_asSLPoints
    _risk = math.abs(asSigEntry - asSigSL)
    if _risk > 0
        asSigTP1 := asSigEntry + _risk * i_asTP1RR, asSigTP2 := asSigEntry + _risk * i_asTP2RR, asSigTP3 := asSigEntry + _risk * i_asTP3RR
    asTrailSL := asSigSL
    strategy.entry("AS Long", strategy.long, qty=i_orbContracts, alert_message=_jsonBuy)
    if _risk > 0
        strategy.exit("AS TP1", from_entry="AS Long", qty=_asTp1Qty, limit=asSigTP1, stop=asSigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _asTp2Qty > 0
            strategy.exit("AS TP2", from_entry="AS Long", qty=_asTp2Qty, limit=asSigTP2, stop=asSigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _asTp3Qty > 0
            strategy.exit("AS TP3", from_entry="AS Long", qty=_asTp3Qty, limit=asSigTP3, stop=asSigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("AS SL", from_entry="AS Long", stop=asSigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        asSLLine  := line.new(bar_index, asSigSL, bar_index + 1, asSigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        if not na(asSigTP1)
            asTP1Line := line.new(bar_index, asSigTP1, bar_index + 1, asSigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
        if not na(asSigTP2) and _asTp2Qty > 0
            asTP2Line := line.new(bar_index, asSigTP2, bar_index + 1, asSigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
        if not na(asSigTP3) and _asTp3Qty > 0
            asTP3Line := line.new(bar_index, asSigTP3, bar_index + 1, asSigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
 
if barstate.isconfirmed and asShortSig and dayAllowed and not inFlatWindow and i_asDirection != "Long Only"
    asSigFired := true, asSigEntry := close, asSigDir := -1
    asTradeCount += 1
    asSigSL := i_asSLMethod == "Midpoint" ? asORBMid : i_asSLMethod == "Opposite Side" ? asORBHigh : close + i_asSLPoints
    _risk = math.abs(asSigSL - asSigEntry)
    if _risk > 0
        asSigTP1 := asSigEntry - _risk * i_asTP1RR, asSigTP2 := asSigEntry - _risk * i_asTP2RR, asSigTP3 := asSigEntry - _risk * i_asTP3RR
    asTrailSL := asSigSL
    strategy.entry("AS Short", strategy.short, qty=i_orbContracts, alert_message=_jsonSell)
    if _risk > 0
        strategy.exit("AS TP1", from_entry="AS Short", qty=_asTp1Qty, limit=asSigTP1, stop=asSigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _asTp2Qty > 0
            strategy.exit("AS TP2", from_entry="AS Short", qty=_asTp2Qty, limit=asSigTP2, stop=asSigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _asTp3Qty > 0
            strategy.exit("AS TP3", from_entry="AS Short", qty=_asTp3Qty, limit=asSigTP3, stop=asSigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("AS SL", from_entry="AS Short", stop=asSigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        asSLLine  := line.new(bar_index, asSigSL, bar_index + 1, asSigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        if not na(asSigTP1)
            asTP1Line := line.new(bar_index, asSigTP1, bar_index + 1, asSigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
        if not na(asSigTP2) and _asTp2Qty > 0
            asTP2Line := line.new(bar_index, asSigTP2, bar_index + 1, asSigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
        if not na(asSigTP3) and _asTp3Qty > 0
            asTP3Line := line.new(bar_index, asSigTP3, bar_index + 1, asSigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
 
// Asia: Trailing Stop
if i_trailEnable and asSigDir != 0 and not asSLHit and strategy.position_size != 0
    _prevTrail = asTrailSL
    asTrailSL := calcTrail(asSigDir, asTrailSL, asSigTP1, asSigTP2, asSigTP3, asSigSL)
    if asTrailSL != _prevTrail
        if asSigDir == 1
            strategy.exit("AS TP1", from_entry="AS Long", qty=_asTp1Qty, limit=asSigTP1, stop=asTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _asTp2Qty > 0
                strategy.exit("AS TP2", from_entry="AS Long", qty=_asTp2Qty, limit=asSigTP2, stop=asTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _asTp3Qty > 0
                strategy.exit("AS TP3", from_entry="AS Long", qty=_asTp3Qty, limit=asSigTP3, stop=asTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
        else
            strategy.exit("AS TP1", from_entry="AS Short", qty=_asTp1Qty, limit=asSigTP1, stop=asTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _asTp2Qty > 0
                strategy.exit("AS TP2", from_entry="AS Short", qty=_asTp2Qty, limit=asSigTP2, stop=asTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _asTp3Qty > 0
                strategy.exit("AS TP3", from_entry="AS Short", qty=_asTp3Qty, limit=asSigTP3, stop=asTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    if i_trailShowLine and asTrailSL != asSigSL
        asTrailLine := line.new(bar_index - 1, asTrailSL, bar_index, asTrailSL, color=color.new(color.yellow, 0), style=line.style_dotted, width=2)
        asTrailLabel := showLabels ? label.new(bar_index + 2, asTrailSL, "TRAIL", style=label.style_none, textcolor=color.yellow, size=getLabelSize()) : na
 
 
 
// AS: SL/TP line extend to current bar while trade active
if asSigDir != 0 and i_orbShowSLTP
    if not na(asSLLine)
        asSLLine.set_x2(bar_index)
    if not na(asTP1Line)
        asTP1Line.set_x2(bar_index)
    if not na(asTP2Line)
        asTP2Line.set_x2(bar_index)
    if not na(asTP3Line)
        asTP3Line.set_x2(bar_index)
 
if i_asEnable and asSigDir != 0 and not asSLHit
    if asSigDir == 1
        if low <= asTrailSL
            asSLHit := true
            asLastWasSL := true
            asLastDir := asSigDir
            asExitBar := bar_index
            asCooldownDone := false
            asInsideStarted := false
            asInsideBars := 0
            asSigDir := 0
            if not na(asSLLine)
                asSLLine.set_x2(bar_index)
            if not na(asTP1Line)
                asTP1Line.set_x2(bar_index)
            if not na(asTP2Line)
                asTP2Line.set_x2(bar_index)
            if not na(asTP3Line)
                asTP3Line.set_x2(bar_index)
            asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
        else
            if not asTP1Hit and high >= asSigTP1
                asTP1Hit := true
            if not asTP2Hit and high >= asSigTP2
                asTP2Hit := true
            if not asTP3Hit and high >= asSigTP3
                asTP3Hit := true
    else if asSigDir == -1
        if high >= asTrailSL
            asSLHit := true
            asLastWasSL := true
            asLastDir := asSigDir
            asExitBar := bar_index
            asCooldownDone := false
            asInsideStarted := false
            asInsideBars := 0
            asSigDir := 0
            if not na(asSLLine)
                asSLLine.set_x2(bar_index)
            if not na(asTP1Line)
                asTP1Line.set_x2(bar_index)
            if not na(asTP2Line)
                asTP2Line.set_x2(bar_index)
            if not na(asTP3Line)
                asTP3Line.set_x2(bar_index)
            asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
        else
            if not asTP1Hit and low <= asSigTP1
                asTP1Hit := true
            if not asTP2Hit and low <= asSigTP2
                asTP2Hit := true
            if not asTP3Hit and low <= asSigTP3
                asTP3Hit := true
 
// AS: Detect TP exit (position closed without SL — requires prior bar had position)
if i_asEnable and asSigFired and asSigDir != 0 and strategy.position_size == 0 and strategy.position_size[1] != 0 and not asSLHit
    asLastWasSL := false
    asLastDir := asSigDir
    asExitBar := bar_index
    asCooldownDone := false
    asInsideStarted := false
    asInsideBars := 0
    asSigDir := 0
    if not na(asSLLine)
        asSLLine.set_x2(bar_index)
    if not na(asTP1Line)
        asTP1Line.set_x2(bar_index)
    if not na(asTP2Line)
        asTP2Line.set_x2(bar_index)
    if not na(asTP3Line)
        asTP3Line.set_x2(bar_index)
    asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
plotshape(i_orbShowEntry and asLongSig,  title="AS Long",  style=shape.triangleup,   location=location.belowbar, color=#e040fb, size=size.small, text="AS LONG")
plotshape(i_orbShowEntry and asShortSig, title="AS Short", style=shape.triangledown, location=location.abovebar, color=#e040fb, size=size.small, text="AS SHORT")
 
 
// ════════════════════════════════════════════════════════════════════════════════
// ═══  LONDON ORB MODULE  ════════════════════════════════════════════════════════
// ════════════════════════════════════════════════════════════════════════════════
var orbData[] lnOrbArray = array.new<orbData>(0)
var float lnORBHigh = na, var float lnORBLow = na, var float lnORBMid = na
var int lnOrbStartBar = na, var int lnOrbHighBar = na, var int lnOrbLowBar = na
var bool lnOrbBuilding = false, var bool lnOrbComplete = false
var bool  lnSigFired = false, var bool  lnBrkPending = false
var int   lnBrkDir = 0, var int lnBrkBar = 0
var float lnSigEntry = na, var float lnSigSL = na
var float lnSigTP1 = na, var float lnSigTP2 = na, var float lnSigTP3 = na
var int   lnSigDir = 0
var bool  lnTP1Hit = false, var bool lnTP2Hit = false, var bool lnTP3Hit = false, var bool lnSLHit = false
var line  lnSLLine = na, var line lnTP1Line = na, var line lnTP2Line = na, var line lnTP3Line = na
var label lnSLLabel = na, var label lnTP1Label = na, var label lnTP2Label = na, var label lnTP3Label = na
var float lnTrailSL = na
var line  lnTrailLine = na
var label lnTrailLabel = na
var bool lnFlattenDone = false
var int lnTradeCount = 0
var int lnInsideBars = 0
var bool lnLastWasSL = false
var int lnLastDir = 0
var int lnExitBar = 0
var bool lnCooldownDone = false
var bool lnInsideStarted = false
 
lnDay = f_dayKey(time, i_timezone)
lnNewDay = lnDay != nz(lnDay[1], lnDay)
lnSessionStart = (inLnTrade and not inLnTrade[1]) or (inLnTrade and lnNewDay)
if lnSessionStart
    lnFlattenDone := false
    lnTradeCount := 0
    lnInsideBars := 0
    lnLastWasSL := false
    lnLastDir := 0
    lnExitBar := 0
    lnCooldownDone := false
    lnInsideStarted := false
    lnORBHigh := na, lnORBLow := na, lnORBMid := na
    lnOrbBuilding := false, lnOrbComplete := false
    lnOrbStartBar := na, lnOrbHighBar := na, lnOrbLowBar := na
    lnSigFired := false, lnBrkPending := false, lnBrkDir := 0, lnBrkBar := 0
    if strategy.position_size == 0
        lnSigDir := 0
    lnTP1Hit := false, lnTP2Hit := false, lnTP3Hit := false, lnSLHit := false
    lnSigEntry := na, lnSigSL := na, lnSigTP1 := na, lnSigTP2 := na, lnSigTP3 := na
    lnTrailSL := na
    // Don't delete old SL/TP lines — they persist for history
    lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
    lnSLLabel := na, lnTP1Label := na, lnTP2Label := na, lnTP3Label := na
    lnTrailLine := na, lnTrailLabel := na
 
lnSessionEnd = not inLnTrade and inLnTrade[1]
if lnSessionEnd and i_lnEnable
    // Freeze ORB lines at session end
    if lnOrbArray.size() > 0
        for j = 0 to lnOrbArray.size() - 1
            _o = lnOrbArray.get(j)
            if na(_o.endBar)
                _o.endBar := bar_index[1]
                lnOrbArray.set(j, _o)
    // Hard flatten: close all positions and cancel pending orders
    // Freeze lines before flatten
    if not na(lnSLLine)
        lnSLLine.set_x2(bar_index)
    if not na(lnTP1Line)
        lnTP1Line.set_x2(bar_index)
    if not na(lnTP2Line)
        lnTP2Line.set_x2(bar_index)
    if not na(lnTP3Line)
        lnTP3Line.set_x2(bar_index)
    lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
    strategy.close_all(comment="LDN End", alert_message=_jsonExit)
    strategy.cancel_all()
    lnSigDir := 0
if i_lnEnable and inLnORB and not lnOrbComplete
    if not lnOrbBuilding
        lnOrbStartBar := bar_index, lnOrbBuilding := true
    if na(lnORBHigh) or high > lnORBHigh
        lnORBHigh := high, lnOrbHighBar := bar_index
    if na(lnORBLow) or low < lnORBLow
        lnORBLow := low, lnOrbLowBar := bar_index
 
if i_lnEnable and not inLnORB and lnOrbBuilding and not lnOrbComplete and not na(lnORBHigh)
    lnOrbComplete := true
    lnORBMid := (lnORBHigh + lnORBLow) / 2
    hiLine = line.new(lnOrbHighBar, lnORBHigh, bar_index, lnORBHigh, color=i_lnHighColor, style=getLineStyle(), width=i_lnLineWidth)
    loLine = line.new(lnOrbLowBar, lnORBLow, bar_index, lnORBLow, color=i_lnLowColor, style=getLineStyle(), width=i_lnLineWidth)
    midLine = i_lnShowMid ? line.new(lnOrbStartBar, lnORBMid, bar_index, lnORBMid, color=i_lnMidColor, style=line.style_dotted, width=math.max(1, i_lnLineWidth - 1)) : na
    hiLabel = showLabels ? label.new(bar_index + 102, lnORBHigh, "LDN ORB H", style=label.style_none, textcolor=i_lnHighColor, size=getLabelSize()) : na
    loLabel = showLabels ? label.new(bar_index + 102, lnORBLow, "LDN ORB L", style=label.style_none, textcolor=i_lnLowColor, size=getLabelSize()) : na
    midLabel = showLabels and i_lnShowMid ? label.new(bar_index + 102, lnORBMid, "LDN ORB M", style=label.style_none, textcolor=i_lnMidColor, size=getLabelSize()) : na
    newOrb = orbData.new(lnORBHigh, lnORBLow, lnORBMid, lnOrbStartBar, lnOrbHighBar, lnOrbLowBar, na, hiLine, loLine, midLine, hiLabel, loLabel, midLabel)
    lnOrbArray.unshift(newOrb)
    if lnOrbArray.size() > i_lnHistory
        old = lnOrbArray.pop()
        old.hiLine.delete(), old.loLine.delete(), old.midLine.delete()
        old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete()
 
if lnOrbArray.size() > 0
    for i = 0 to lnOrbArray.size() - 1
        cur = lnOrbArray.get(i)
        int _x2 = na(cur.endBar) ? bar_index : cur.endBar
        int _lx = na(cur.endBar) ? (bar_index + 2) : (cur.endBar + 2)
 
        cur.hiLine.set_x2(_x2)
        cur.loLine.set_x2(_x2)
        if i_lnShowMid and not na(cur.midLine)
            cur.midLine.set_x2(_x2)
 
        if i == 0 and showLabels
            cur.hiLabel.set_x(_lx)
            cur.loLabel.set_x(_lx)
            if i_lnShowMid and not na(cur.midLabel)
                cur.midLabel.set_x(_lx)
        else
            cur.hiLabel.delete()
            cur.loLabel.delete()
            if not na(cur.midLabel)
                cur.midLabel.delete()
            cur.hiLabel := na
            cur.loLabel := na
            cur.midLabel := na
 
 
 
lnCrossUp = ta.crossover(close, lnORBHigh)
lnHighBreak = lnOrbComplete and inLnTrade and lnCrossUp
lnCrossDn = ta.crossunder(close, lnORBLow)
lnLowBreak  = lnOrbComplete and inLnTrade and lnCrossDn
bool lnLongSig = false, bool lnShortSig = false
 
if i_lnEnable and lnBrkPending and bar_index > lnBrkBar and not lnSigFired
    _retestLvl = i_orbEntryMode == "Retest Midpoint" ? lnORBMid : (lnBrkDir == 1 ? lnORBHigh : lnORBLow)
    if lnBrkDir == 1
        if low <= _retestLvl and close > lnORBHigh
            lnLongSig := true, lnBrkPending := false
        else if close <= lnORBHigh
            lnBrkPending := false
    else if lnBrkDir == -1
        if high >= _retestLvl and close < lnORBLow
            lnShortSig := true, lnBrkPending := false
        else if close >= lnORBLow
            lnBrkPending := false
    if lnBrkPending and bar_index - lnBrkBar >= i_orbRetestTimeout
        lnBrkPending := false
 
if i_lnEnable and lnOrbComplete and inLnTrade and not lnSigFired and (lnTradeCount < i_rearmMaxTrades or not i_rearmEnable)
    if lnHighBreak and not lnBrkPending
        if i_orbEntryMode == "Breakout"
            lnLongSig := true
        else
            lnBrkPending := true, lnBrkDir := 1, lnBrkBar := bar_index
    else if lnLowBreak and not lnBrkPending
        if i_orbEntryMode == "Breakout"
            lnShortSig := true
        else
            lnBrkPending := true, lnBrkDir := -1, lnBrkBar := bar_index
// LN: Contrarian mode — flip signals
if i_lnContrarian
    bool _tmpL = lnLongSig
    bool _tmpS = lnShortSig
    lnLongSig := _tmpS
    lnShortSig := _tmpL
// LN: Direction filter on re-armed signals
if i_rearmEnable and lnTradeCount > 0 and lnLastDir != 0
    [lnAllowL, lnAllowS] = f_dirAllowed(lnLastDir)
    if lnLongSig and not lnAllowL
        lnLongSig := false
    if lnShortSig and not lnAllowS
        lnShortSig := false
 
 
if barstate.isconfirmed and lnLongSig and dayAllowed and not inFlatWindow and i_lnDirection != "Short Only"
    lnSigFired := true, lnSigEntry := close, lnSigDir := 1
    lnTradeCount += 1
    lnSigSL := i_lnSLMethod == "Midpoint" ? lnORBMid : i_lnSLMethod == "Opposite Side" ? lnORBLow : close - i_lnSLPoints
    _risk = math.abs(lnSigEntry - lnSigSL)
    if _risk > 0
        lnSigTP1 := lnSigEntry + _risk * i_lnTP1RR, lnSigTP2 := lnSigEntry + _risk * i_lnTP2RR, lnSigTP3 := lnSigEntry + _risk * i_lnTP3RR
    lnTrailSL := lnSigSL
    strategy.entry("LDN Long", strategy.long, qty=i_orbContracts, alert_message=_jsonBuy)
    if _risk > 0
        strategy.exit("LDN TP1", from_entry="LDN Long", qty=_lnTp1Qty, limit=lnSigTP1, stop=lnSigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _lnTp2Qty > 0
            strategy.exit("LDN TP2", from_entry="LDN Long", qty=_lnTp2Qty, limit=lnSigTP2, stop=lnSigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _lnTp3Qty > 0
            strategy.exit("LDN TP3", from_entry="LDN Long", qty=_lnTp3Qty, limit=lnSigTP3, stop=lnSigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("LDN SL", from_entry="LDN Long", stop=lnSigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        lnSLLine  := line.new(bar_index, lnSigSL, bar_index + 1, lnSigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        if not na(lnSigTP1)
            lnTP1Line := line.new(bar_index, lnSigTP1, bar_index + 1, lnSigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
        if not na(lnSigTP2) and _lnTp2Qty > 0
            lnTP2Line := line.new(bar_index, lnSigTP2, bar_index + 1, lnSigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
        if not na(lnSigTP3) and _lnTp3Qty > 0
            lnTP3Line := line.new(bar_index, lnSigTP3, bar_index + 1, lnSigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
 
if barstate.isconfirmed and lnShortSig and dayAllowed and not inFlatWindow and i_lnDirection != "Long Only"
    lnSigFired := true, lnSigEntry := close, lnSigDir := -1
    lnTradeCount += 1
    lnSigSL := i_lnSLMethod == "Midpoint" ? lnORBMid : i_lnSLMethod == "Opposite Side" ? lnORBHigh : close + i_lnSLPoints
    _risk = math.abs(lnSigSL - lnSigEntry)
    if _risk > 0
        lnSigTP1 := lnSigEntry - _risk * i_lnTP1RR, lnSigTP2 := lnSigEntry - _risk * i_lnTP2RR, lnSigTP3 := lnSigEntry - _risk * i_lnTP3RR
    lnTrailSL := lnSigSL
    strategy.entry("LDN Short", strategy.short, qty=i_orbContracts, alert_message=_jsonSell)
    if _risk > 0
        strategy.exit("LDN TP1", from_entry="LDN Short", qty=_lnTp1Qty, limit=lnSigTP1, stop=lnSigSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
        if _lnTp2Qty > 0
            strategy.exit("LDN TP2", from_entry="LDN Short", qty=_lnTp2Qty, limit=lnSigTP2, stop=lnSigSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
        if _lnTp3Qty > 0
            strategy.exit("LDN TP3", from_entry="LDN Short", qty=_lnTp3Qty, limit=lnSigTP3, stop=lnSigSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    else
        strategy.exit("LDN SL", from_entry="LDN Short", stop=lnSigSL, alert_message=_jsonExit)
    if i_orbShowSLTP
        lnSLLine  := line.new(bar_index, lnSigSL, bar_index + 1, lnSigSL, color=i_slLineColor, style=slStyle, width=i_slLineWidth)
        if not na(lnSigTP1)
            lnTP1Line := line.new(bar_index, lnSigTP1, bar_index + 1, lnSigTP1, color=i_tpLineColor, style=tpStyle, width=i_tpLineWidth)
        if not na(lnSigTP2) and _lnTp2Qty > 0
            lnTP2Line := line.new(bar_index, lnSigTP2, bar_index + 1, lnSigTP2, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
        if not na(lnSigTP3) and _lnTp3Qty > 0
            lnTP3Line := line.new(bar_index, lnSigTP3, bar_index + 1, lnSigTP3, color=i_tpLineColor, style=tpStyle, width=math.max(1, i_tpLineWidth - 1))
 
 
// London: Trailing Stop
if i_trailEnable and lnSigDir != 0 and not lnSLHit and strategy.position_size != 0
    _prevTrail = lnTrailSL
    lnTrailSL := calcTrail(lnSigDir, lnTrailSL, lnSigTP1, lnSigTP2, lnSigTP3, lnSigSL)
    if lnTrailSL != _prevTrail
        if lnSigDir == 1
            strategy.exit("LDN TP1", from_entry="LDN Long", qty=_lnTp1Qty, limit=lnSigTP1, stop=lnTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _lnTp2Qty > 0
                strategy.exit("LDN TP2", from_entry="LDN Long", qty=_lnTp2Qty, limit=lnSigTP2, stop=lnTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _lnTp3Qty > 0
                strategy.exit("LDN TP3", from_entry="LDN Long", qty=_lnTp3Qty, limit=lnSigTP3, stop=lnTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
        else
            strategy.exit("LDN TP1", from_entry="LDN Short", qty=_lnTp1Qty, limit=lnSigTP1, stop=lnTrailSL, comment_profit="TP1", comment_loss="SL", alert_message=_jsonExit)
            if _lnTp2Qty > 0
                strategy.exit("LDN TP2", from_entry="LDN Short", qty=_lnTp2Qty, limit=lnSigTP2, stop=lnTrailSL, comment_profit="TP2", comment_loss="SL", alert_message=_jsonExit)
            if _lnTp3Qty > 0
                strategy.exit("LDN TP3", from_entry="LDN Short", qty=_lnTp3Qty, limit=lnSigTP3, stop=lnTrailSL, comment_profit="TP3", comment_loss="SL", alert_message=_jsonExit)
    if i_trailShowLine and lnTrailSL != lnSigSL
        lnTrailLine := line.new(bar_index - 1, lnTrailSL, bar_index, lnTrailSL, color=color.new(color.yellow, 0), style=line.style_dotted, width=2)
        lnTrailLabel := showLabels ? label.new(bar_index + 2, lnTrailSL, "TRAIL", style=label.style_none, textcolor=color.yellow, size=getLabelSize()) : na
 
 
 
// LN: SL/TP line extend to current bar while trade active
if lnSigDir != 0 and i_orbShowSLTP
    if not na(lnSLLine)
        lnSLLine.set_x2(bar_index)
    if not na(lnTP1Line)
        lnTP1Line.set_x2(bar_index)
    if not na(lnTP2Line)
        lnTP2Line.set_x2(bar_index)
    if not na(lnTP3Line)
        lnTP3Line.set_x2(bar_index)
 
if i_lnEnable and lnSigDir != 0 and not lnSLHit
    if lnSigDir == 1
        if low <= lnTrailSL
            lnSLHit := true
            lnLastWasSL := true
            lnLastDir := lnSigDir
            lnExitBar := bar_index
            lnCooldownDone := false
            lnInsideStarted := false
            lnInsideBars := 0
            lnSigDir := 0
            if not na(lnSLLine)
                lnSLLine.set_x2(bar_index)
            if not na(lnTP1Line)
                lnTP1Line.set_x2(bar_index)
            if not na(lnTP2Line)
                lnTP2Line.set_x2(bar_index)
            if not na(lnTP3Line)
                lnTP3Line.set_x2(bar_index)
            lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
        else
            if not lnTP1Hit and high >= lnSigTP1
                lnTP1Hit := true
            if not lnTP2Hit and high >= lnSigTP2
                lnTP2Hit := true
            if not lnTP3Hit and high >= lnSigTP3
                lnTP3Hit := true
    else if lnSigDir == -1
        if high >= lnTrailSL
            lnSLHit := true
            lnLastWasSL := true
            lnLastDir := lnSigDir
            lnExitBar := bar_index
            lnCooldownDone := false
            lnInsideStarted := false
            lnInsideBars := 0
            lnSigDir := 0
            if not na(lnSLLine)
                lnSLLine.set_x2(bar_index)
            if not na(lnTP1Line)
                lnTP1Line.set_x2(bar_index)
            if not na(lnTP2Line)
                lnTP2Line.set_x2(bar_index)
            if not na(lnTP3Line)
                lnTP3Line.set_x2(bar_index)
            lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
        else
            if not lnTP1Hit and low <= lnSigTP1
                lnTP1Hit := true
            if not lnTP2Hit and low <= lnSigTP2
                lnTP2Hit := true
            if not lnTP3Hit and low <= lnSigTP3
                lnTP3Hit := true
 
// LN: Detect TP exit (position closed without SL — requires prior bar had position)
if i_lnEnable and lnSigFired and lnSigDir != 0 and strategy.position_size == 0 and strategy.position_size[1] != 0 and not lnSLHit
    lnLastWasSL := false
    lnLastDir := lnSigDir
    lnExitBar := bar_index
    lnCooldownDone := false
    lnInsideStarted := false
    lnInsideBars := 0
    lnSigDir := 0
    if not na(lnSLLine)
        lnSLLine.set_x2(bar_index)
    if not na(lnTP1Line)
        lnTP1Line.set_x2(bar_index)
    if not na(lnTP2Line)
        lnTP2Line.set_x2(bar_index)
    if not na(lnTP3Line)
        lnTP3Line.set_x2(bar_index)
    lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
plotshape(i_orbShowEntry and lnLongSig,  title="LN Long",  style=shape.triangleup,   location=location.belowbar, color=#ff9800, size=size.small, text="LDN LONG")
plotshape(i_orbShowEntry and lnShortSig, title="LN Short", style=shape.triangledown, location=location.abovebar, color=#ff9800, size=size.small, text="LDN SHORT")
 
// ── Prop Firm Flat Window: close everything when window starts ──
if flatWindowJustStarted and strategy.position_size != 0
    strategy.close_all(comment="FLAT WINDOW", alert_message=_jsonExit)
    strategy.cancel_all()
    if not na(nySLLine)
        nySLLine.set_x2(bar_index)
    if not na(nyTP1Line)
        nyTP1Line.set_x2(bar_index)
    if not na(nyTP2Line)
        nyTP2Line.set_x2(bar_index)
    if not na(nyTP3Line)
        nyTP3Line.set_x2(bar_index)
    nySLLine := na, nyTP1Line := na, nyTP2Line := na, nyTP3Line := na
    nySigDir := 0
    if not na(asSLLine)
        asSLLine.set_x2(bar_index)
    if not na(asTP1Line)
        asTP1Line.set_x2(bar_index)
    if not na(asTP2Line)
        asTP2Line.set_x2(bar_index)
    if not na(asTP3Line)
        asTP3Line.set_x2(bar_index)
    asSLLine := na, asTP1Line := na, asTP2Line := na, asTP3Line := na
    asSigDir := 0
    if not na(lnSLLine)
        lnSLLine.set_x2(bar_index)
    if not na(lnTP1Line)
        lnTP1Line.set_x2(bar_index)
    if not na(lnTP2Line)
        lnTP2Line.set_x2(bar_index)
    if not na(lnTP3Line)
        lnTP3Line.set_x2(bar_index)
    lnSLLine := na, lnTP1Line := na, lnTP2Line := na, lnTP3Line := na
    lnSigDir := 0
 
// ═══ SL/TP Level Plots (guaranteed visibility) ═══
_nyTPplot = i_nyEnable and nySigDir != 0 and i_orbShowSLTP ? nySigTP1 : na
_nySLplot = i_nyEnable and nySigDir != 0 and i_orbShowSLTP ? nySigSL : na
_asTPplot = i_asEnable and asSigDir != 0 and i_orbShowSLTP ? asSigTP1 : na
_asSLplot = i_asEnable and asSigDir != 0 and i_orbShowSLTP ? asSigSL : na
_lnTPplot = i_lnEnable and lnSigDir != 0 and i_orbShowSLTP ? lnSigTP1 : na
_lnSLplot = i_lnEnable and lnSigDir != 0 and i_orbShowSLTP ? lnSigSL : na
 
plot(_nyTPplot, "NY TP", color=i_tpLineColor, style=plot.style_linebr, linewidth=2)
plot(_nySLplot, "NY SL", color=i_slLineColor, style=plot.style_linebr, linewidth=1)
plot(_asTPplot, "AS TP", color=i_tpLineColor, style=plot.style_linebr, linewidth=2)
plot(_asSLplot, "AS SL", color=i_slLineColor, style=plot.style_linebr, linewidth=1)
plot(_lnTPplot, "LN TP", color=i_tpLineColor, style=plot.style_linebr, linewidth=2)
plot(_lnSLplot, "LN SL", color=i_slLineColor, style=plot.style_linebr, linewidth=1)
 
 
// ════════════════════════════════════════════════════════════════════════════════
// Overlay level tracking vars
var float currentPDH = na, var float currentPDL = na
var float curAsianHigh = na, var float curAsianLow = na
var float curLondonHigh = na, var float curLondonLow = na
var float curNYAMHigh = na, var float curNYAMLow = na
var float curNYPMHigh = na, var float curNYPMLow = na
 
// PREVIOUS DAY HIGH/LOW
// ════════════════════════════════════════════════════════════════════════════════
var levelData[] pdArray = array.new<levelData>(0)
var float pdTrackHigh = na, var float pdTrackLow = na
newDay = dayofweek != dayofweek[1]
 
if newDay
    if showPDHL and pdHistory > 0 and not na(pdTrackHigh)
        currentPDH := pdTrackHigh, currentPDL := pdTrackLow
        hiLine = line.new(bar_index, pdTrackHigh, bar_index, pdTrackHigh, color=pdhColor, style=getLineStyle(), width=pdLineWidth)
        loLine = line.new(bar_index, pdTrackLow, bar_index, pdTrackLow, color=pdhColor, style=getLineStyle(), width=pdLineWidth)
        hiLabel = showLabels ? label.new(bar_index, pdTrackHigh, "PDH", style=label.style_none, textcolor=pdhColor, size=getLabelSize()) : na
        loLabel = showLabels ? label.new(bar_index, pdTrackLow, "PDL", style=label.style_none, textcolor=pdhColor, size=getLabelSize()) : na
        newLevel = levelData.new(pdTrackHigh, pdTrackLow, na, na, bar_index, bar_index, hiLine, loLine, na, hiLabel, loLabel, na, na)
        pdArray.unshift(newLevel)
        if pdArray.size() > pdHistory
            old = pdArray.pop()
            old.hiLine.delete(), old.loLine.delete(), old.hiLabel.delete(), old.loLabel.delete()
    pdTrackHigh := na, pdTrackLow := na
if inPDSession
    if na(pdTrackHigh) or high > pdTrackHigh
        pdTrackHigh := high
    if na(pdTrackLow) or low < pdTrackLow
        pdTrackLow := low
if pdArray.size() > 0
    for i = 0 to pdArray.size() - 1
        lvl = pdArray.get(i)
        lvl.hiLine.set_x2(bar_index), lvl.loLine.set_x2(bar_index)
        if i == 0 and showLabels
            lvl.hiLabel.set_x(bar_index), lvl.loLabel.set_x(bar_index)
        else
            lvl.hiLabel.delete(), lvl.loLabel.delete()
            lvl.hiLabel := na, lvl.loLabel := na
 
// ════════════════════════════════════════════════════════════════════════════════
// ASIAN SESSION OVERLAY
// ════════════════════════════════════════════════════════════════════════════════
var levelData[] asianArray = array.new<levelData>(0)
var float ovAsianHigh = na, var float ovAsianLow = na
var int ovAsianHighBar = na, var int ovAsianLowBar = na, var int ovAsianStartBar = na
var bool ovAsianBuilding = false
var float curAsianMid = na
var box curAsianBox = na
 
if inAsianSession
    if not inAsianSession[1]
        ovAsianHigh := high, ovAsianLow := low
        ovAsianHighBar := bar_index, ovAsianLowBar := bar_index, ovAsianStartBar := bar_index
        ovAsianBuilding := true
        if showAsianBox and showAsian
            curAsianBox.delete()
            curAsianBox := box.new(bar_index, high, bar_index, low, border_color=asianColor, bgcolor=asianBoxColor, border_width=1)
    else
        if high > ovAsianHigh
            ovAsianHigh := high, ovAsianHighBar := bar_index
        if low < ovAsianLow
            ovAsianLow := low, ovAsianLowBar := bar_index
        if showAsianBox and showAsian and not na(curAsianBox)
            curAsianBox.set_top(ovAsianHigh), curAsianBox.set_bottom(ovAsianLow), curAsianBox.set_right(bar_index)
 
if not inAsianSession and inAsianSession[1] and ovAsianBuilding
    ovAsianBuilding := false
    curAsianHigh := ovAsianHigh, curAsianLow := ovAsianLow, curAsianMid := (ovAsianHigh + ovAsianLow) / 2
    if showAsian and asianHistory > 0 and not na(ovAsianHigh)
        hiLine = line.new(ovAsianHighBar, ovAsianHigh, bar_index + 100, ovAsianHigh, color=asianColor, style=getLineStyle(), width=asianLineWidth)
        loLine = line.new(ovAsianLowBar, ovAsianLow, bar_index + 100, ovAsianLow, color=asianColor, style=getLineStyle(), width=asianLineWidth)
        midLine = showAsianMid ? line.new(ovAsianStartBar, curAsianMid, bar_index + 100, curAsianMid, color=color.new(asianColor, 50), style=line.style_dotted, width=math.max(1, asianLineWidth - 1)) : na
        hiLabel = showLabels ? label.new(bar_index + 102, ovAsianHigh, "ASIA H", style=label.style_none, textcolor=asianColor, size=getLabelSize()) : na
        loLabel = showLabels ? label.new(bar_index + 102, ovAsianLow, "ASIA L", style=label.style_none, textcolor=asianColor, size=getLabelSize()) : na
        midLabel = showLabels and showAsianMid ? label.new(bar_index + 102, curAsianMid, "ASIA M", style=label.style_none, textcolor=color.new(asianColor, 50), size=getLabelSize()) : na
        newLevel = levelData.new(ovAsianHigh, ovAsianLow, curAsianMid, ovAsianStartBar, ovAsianHighBar, ovAsianLowBar, hiLine, loLine, midLine, hiLabel, loLabel, midLabel, curAsianBox)
        asianArray.unshift(newLevel)
        if asianArray.size() > asianHistory
            old = asianArray.pop()
            old.hiLine.delete(), old.loLine.delete(), old.midLine.delete()
            old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete(), old.sessionBox.delete()
 
if asianArray.size() > 0
    for i = 0 to asianArray.size() - 1
        lvl = asianArray.get(i)
        lvl.hiLine.set_x2(bar_index), lvl.loLine.set_x2(bar_index)
        if showAsianMid and not na(lvl.midLine)
            lvl.midLine.set_x2(bar_index)
        if i == 0 and showLabels
            lvl.hiLabel.set_x(bar_index), lvl.loLabel.set_x(bar_index)
            if showAsianMid and not na(lvl.midLabel)
                lvl.midLabel.set_x(bar_index + 2)
        else
            lvl.hiLabel.delete(), lvl.loLabel.delete(), lvl.midLabel.delete()
            lvl.hiLabel := na, lvl.loLabel := na, lvl.midLabel := na
 
// ════════════════════════════════════════════════════════════════════════════════
// LONDON SESSION OVERLAY
// ════════════════════════════════════════════════════════════════════════════════
var levelData[] londonArray = array.new<levelData>(0)
var float ovLondonHigh = na, var float ovLondonLow = na
var int ovLondonHighBar = na, var int ovLondonLowBar = na, var int ovLondonStartBar = na
var bool ovLondonBuilding = false
var float curLondonMid = na
var box curLondonBox = na
 
if inLondonSession
    if not inLondonSession[1]
        ovLondonHigh := high, ovLondonLow := low
        ovLondonHighBar := bar_index, ovLondonLowBar := bar_index, ovLondonStartBar := bar_index
        ovLondonBuilding := true
        if showLondonBox and showLondon
            curLondonBox.delete()
            curLondonBox := box.new(bar_index, high, bar_index, low, border_color=londonColor, bgcolor=londonBoxColor, border_width=1)
    else
        if high > ovLondonHigh
            ovLondonHigh := high, ovLondonHighBar := bar_index
        if low < ovLondonLow
            ovLondonLow := low, ovLondonLowBar := bar_index
        if showLondonBox and showLondon and not na(curLondonBox)
            curLondonBox.set_top(ovLondonHigh), curLondonBox.set_bottom(ovLondonLow), curLondonBox.set_right(bar_index)
 
if not inLondonSession and inLondonSession[1] and ovLondonBuilding
    ovLondonBuilding := false
    curLondonHigh := ovLondonHigh, curLondonLow := ovLondonLow, curLondonMid := (ovLondonHigh + ovLondonLow) / 2
    if showLondon and londonHistory > 0 and not na(ovLondonHigh)
        hiLine = line.new(ovLondonHighBar, ovLondonHigh, bar_index + 100, ovLondonHigh, color=londonColor, style=getLineStyle(), width=londonLineWidth)
        loLine = line.new(ovLondonLowBar, ovLondonLow, bar_index + 100, ovLondonLow, color=londonColor, style=getLineStyle(), width=londonLineWidth)
        midLine = showLondonMid ? line.new(ovLondonStartBar, curLondonMid, bar_index + 100, curLondonMid, color=color.new(londonColor, 50), style=line.style_dotted, width=math.max(1, londonLineWidth - 1)) : na
        hiLabel = showLabels ? label.new(bar_index + 102, ovLondonHigh, "LDN H", style=label.style_none, textcolor=londonColor, size=getLabelSize()) : na
        loLabel = showLabels ? label.new(bar_index + 102, ovLondonLow, "LDN L", style=label.style_none, textcolor=londonColor, size=getLabelSize()) : na
        midLabel = showLabels and showLondonMid ? label.new(bar_index + 102, curLondonMid, "LDN M", style=label.style_none, textcolor=color.new(londonColor, 50), size=getLabelSize()) : na
        newLevel = levelData.new(ovLondonHigh, ovLondonLow, curLondonMid, ovLondonStartBar, ovLondonHighBar, ovLondonLowBar, hiLine, loLine, midLine, hiLabel, loLabel, midLabel, curLondonBox)
        londonArray.unshift(newLevel)
        if londonArray.size() > londonHistory
            old = londonArray.pop()
            old.hiLine.delete(), old.loLine.delete(), old.midLine.delete()
            old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete(), old.sessionBox.delete()
 
if londonArray.size() > 0
    for i = 0 to londonArray.size() - 1
        lvl = londonArray.get(i)
        lvl.hiLine.set_x2(bar_index), lvl.loLine.set_x2(bar_index)
        if showLondonMid and not na(lvl.midLine)
            lvl.midLine.set_x2(bar_index)
        if i == 0 and showLabels
            lvl.hiLabel.set_x(bar_index), lvl.loLabel.set_x(bar_index)
            if showLondonMid and not na(lvl.midLabel)
                lvl.midLabel.set_x(bar_index + 2)
        else
            lvl.hiLabel.delete(), lvl.loLabel.delete(), lvl.midLabel.delete()
            lvl.hiLabel := na, lvl.loLabel := na, lvl.midLabel := na
 
// ════════════════════════════════════════════════════════════════════════════════
// NY AM / NY PM SESSION OVERLAYS
// ════════════════════════════════════════════════════════════════════════════════
var levelData[] nyamArray = array.new<levelData>(0)
var float ovNYAMHigh = na, var float ovNYAMLow = na
var int ovNYAMHighBar = na, var int ovNYAMLowBar = na, var int ovNYAMStartBar = na
var bool ovNYAMBuilding = false
var float curNYAMMid = na
var box curNYAMBox = na
 
if inNYAMSession
    if not inNYAMSession[1]
        ovNYAMHigh := high, ovNYAMLow := low, ovNYAMHighBar := bar_index, ovNYAMLowBar := bar_index, ovNYAMStartBar := bar_index, ovNYAMBuilding := true
        if showNYAMBox and showNYAM
            curNYAMBox.delete()
            curNYAMBox := box.new(bar_index, high, bar_index, low, border_color=nyamColor, bgcolor=nyamBoxColor, border_width=1)
    else
        if high > ovNYAMHigh
            ovNYAMHigh := high, ovNYAMHighBar := bar_index
        if low < ovNYAMLow
            ovNYAMLow := low, ovNYAMLowBar := bar_index
        if showNYAMBox and showNYAM and not na(curNYAMBox)
            curNYAMBox.set_top(ovNYAMHigh), curNYAMBox.set_bottom(ovNYAMLow), curNYAMBox.set_right(bar_index)
 
if not inNYAMSession and inNYAMSession[1] and ovNYAMBuilding
    ovNYAMBuilding := false
    curNYAMHigh := ovNYAMHigh, curNYAMLow := ovNYAMLow, curNYAMMid := (ovNYAMHigh + ovNYAMLow) / 2
    if showNYAM and nyamHistory > 0 and not na(ovNYAMHigh)
        hiLine = line.new(ovNYAMHighBar, ovNYAMHigh, bar_index + 100, ovNYAMHigh, color=nyamColor, style=getLineStyle(), width=nyamLineWidth)
        loLine = line.new(ovNYAMLowBar, ovNYAMLow, bar_index + 100, ovNYAMLow, color=nyamColor, style=getLineStyle(), width=nyamLineWidth)
        midLine = showNYAMMid ? line.new(ovNYAMStartBar, curNYAMMid, bar_index + 100, curNYAMMid, color=color.new(nyamColor, 50), style=line.style_dotted, width=math.max(1, nyamLineWidth - 1)) : na
        hiLabel = showLabels ? label.new(bar_index + 102, ovNYAMHigh, "NY AM H", style=label.style_none, textcolor=nyamColor, size=getLabelSize()) : na
        loLabel = showLabels ? label.new(bar_index + 102, ovNYAMLow, "NY AM L", style=label.style_none, textcolor=nyamColor, size=getLabelSize()) : na
        midLabel = showLabels and showNYAMMid ? label.new(bar_index + 102, curNYAMMid, "NY AM M", style=label.style_none, textcolor=color.new(nyamColor, 50), size=getLabelSize()) : na
        newLevel = levelData.new(ovNYAMHigh, ovNYAMLow, curNYAMMid, ovNYAMStartBar, ovNYAMHighBar, ovNYAMLowBar, hiLine, loLine, midLine, hiLabel, loLabel, midLabel, curNYAMBox)
        nyamArray.unshift(newLevel)
        if nyamArray.size() > nyamHistory
            old = nyamArray.pop()
            old.hiLine.delete(), old.loLine.delete(), old.midLine.delete(), old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete(), old.sessionBox.delete()
 
if nyamArray.size() > 0
    for i = 0 to nyamArray.size() - 1
        lvl = nyamArray.get(i)
        lvl.hiLine.set_x2(bar_index), lvl.loLine.set_x2(bar_index)
        if showNYAMMid and not na(lvl.midLine)
            lvl.midLine.set_x2(bar_index)
        if i == 0 and showLabels
            lvl.hiLabel.set_x(bar_index), lvl.loLabel.set_x(bar_index)
            if showNYAMMid and not na(lvl.midLabel)
                lvl.midLabel.set_x(bar_index + 2)
        else
            lvl.hiLabel.delete(), lvl.loLabel.delete(), lvl.midLabel.delete()
            lvl.hiLabel := na, lvl.loLabel := na, lvl.midLabel := na
 
var levelData[] nypmArray = array.new<levelData>(0)
var float ovNYPMHigh = na, var float ovNYPMLow = na
var int ovNYPMHighBar = na, var int ovNYPMLowBar = na, var int ovNYPMStartBar = na
var bool ovNYPMBuilding = false
var float curNYPMMid = na
var box curNYPMBox = na
 
if inNYPMSession
    if not inNYPMSession[1]
        ovNYPMHigh := high, ovNYPMLow := low, ovNYPMHighBar := bar_index, ovNYPMLowBar := bar_index, ovNYPMStartBar := bar_index, ovNYPMBuilding := true
        if showNYPMBox and showNYPM
            curNYPMBox.delete()
            curNYPMBox := box.new(bar_index, high, bar_index, low, border_color=nypmColor, bgcolor=nypmBoxColor, border_width=1)
    else
        if high > ovNYPMHigh
            ovNYPMHigh := high, ovNYPMHighBar := bar_index
        if low < ovNYPMLow
            ovNYPMLow := low, ovNYPMLowBar := bar_index
        if showNYPMBox and showNYPM and not na(curNYPMBox)
            curNYPMBox.set_top(ovNYPMHigh), curNYPMBox.set_bottom(ovNYPMLow), curNYPMBox.set_right(bar_index)
 
if not inNYPMSession and inNYPMSession[1] and ovNYPMBuilding
    ovNYPMBuilding := false
    curNYPMHigh := ovNYPMHigh, curNYPMLow := ovNYPMLow, curNYPMMid := (ovNYPMHigh + ovNYPMLow) / 2
    if showNYPM and nypmHistory > 0 and not na(ovNYPMHigh)
        hiLine = line.new(ovNYPMHighBar, ovNYPMHigh, bar_index + 100, ovNYPMHigh, color=nypmColor, style=getLineStyle(), width=nypmLineWidth)
        loLine = line.new(ovNYPMLowBar, ovNYPMLow, bar_index + 100, ovNYPMLow, color=nypmColor, style=getLineStyle(), width=nypmLineWidth)
        midLine = showNYPMMid ? line.new(ovNYPMStartBar, curNYPMMid, bar_index + 100, curNYPMMid, color=color.new(nypmColor, 50), style=line.style_dotted, width=math.max(1, nypmLineWidth - 1)) : na
        hiLabel = showLabels ? label.new(bar_index + 102, ovNYPMHigh, "NY PM H", style=label.style_none, textcolor=nypmColor, size=getLabelSize()) : na
        loLabel = showLabels ? label.new(bar_index + 102, ovNYPMLow, "NY PM L", style=label.style_none, textcolor=nypmColor, size=getLabelSize()) : na
        midLabel = showLabels and showNYPMMid ? label.new(bar_index + 102, curNYPMMid, "NY PM M", style=label.style_none, textcolor=color.new(nypmColor, 50), size=getLabelSize()) : na
        newLevel = levelData.new(ovNYPMHigh, ovNYPMLow, curNYPMMid, ovNYPMStartBar, ovNYPMHighBar, ovNYPMLowBar, hiLine, loLine, midLine, hiLabel, loLabel, midLabel, curNYPMBox)
        nypmArray.unshift(newLevel)
        if nypmArray.size() > nypmHistory
            old = nypmArray.pop()
            old.hiLine.delete(), old.loLine.delete(), old.midLine.delete(), old.hiLabel.delete(), old.loLabel.delete(), old.midLabel.delete(), old.sessionBox.delete()
 
if nypmArray.size() > 0
    for i = 0 to nypmArray.size() - 1
        lvl = nypmArray.get(i)
        lvl.hiLine.set_x2(bar_index), lvl.loLine.set_x2(bar_index)
        if showNYPMMid and not na(lvl.midLine)
            lvl.midLine.set_x2(bar_index)
        if i == 0 and showLabels
            lvl.hiLabel.set_x(bar_index), lvl.loLabel.set_x(bar_index)
            if showNYPMMid and not na(lvl.midLabel)
                lvl.midLabel.set_x(bar_index + 2)
        else
            lvl.hiLabel.delete(), lvl.loLabel.delete(), lvl.midLabel.delete()
            lvl.hiLabel := na, lvl.loLabel := na, lvl.midLabel := na
 
// ════════════════════════════════════════════════════════════════════════════════
// FAIR VALUE GAPS
// ════════════════════════════════════════════════════════════════════════════════
var fvgData[] fvgArray = array.new<fvgData>(0)
var bool newBullFVG = false, var bool newBearFVG = false, var bool fvgMitigatedAlert = false
newBullFVG := false, newBearFVG := false, fvgMitigatedAlert := false
 
if showFVG
    threshold = autoThreshold ? ta.cum((high - low) / low) / bar_index : fvgThreshold / 100
    bullFVG = low > high[2] and close[1] > high[2] and (low - high[2]) / high[2] > threshold
    bearFVG = high < low[2] and close[1] < low[2] and (low[2] - high) / high > threshold
    if bullFVG
        newBox = box.new(bar_index - 2, low, bar_index + fvgExtend, high[2], na, bgcolor=bullFVGColor)
        fvgArray.unshift(fvgData.new(low, high[2], true, bar_index, newBox))
        newBullFVG := true
    if bearFVG
        newBox = box.new(bar_index - 2, low[2], bar_index + fvgExtend, high, na, bgcolor=bearFVGColor)
        fvgArray.unshift(fvgData.new(low[2], high, false, bar_index, newBox))
        newBearFVG := true
    if fvgMitigation and fvgArray.size() > 0
        for i = fvgArray.size() - 1 to 0
            f = fvgArray.get(i)
            if (f.isBull ? close < f.bottom : close > f.top)
                f.area.delete(), fvgArray.remove(i), fvgMitigatedAlert := true
    while fvgArray.size() > 100
        old = fvgArray.pop()
        old.area.delete()
 
 
 
// ════════════════════════════════════════════════════════════════════════════════
// RE-ARM LOGIC
// 1. Check exit type matches i_rearmAfter (SL Only / TP Only / Both)
// 2. Wait for cooldown bars after trade close
// 3. If i_rearmBars > 0, wait for first bar inside ORB (with buffer), 
//    then count bars from there (no reset on outside bars)
// 4. If i_rearmBars == 0, re-arm immediately after cooldown
// 5. Check direction filter and max trades
// ════════════════════════════════════════════════════════════════════════════════
// ── NY Re-Arm ──
if i_rearmEnable and i_nyEnable and nyOrbComplete and inNYTrade and nySigFired and nySigDir == 0 and strategy.position_size == 0 and nyTradeCount < i_rearmMaxTrades
    if f_exitQualifies(nyLastWasSL)
        // Step 1: Cooldown
        if not nyCooldownDone
            if bar_index - nyExitBar >= i_rearmCooldown
                nyCooldownDone := true
        // Step 2: Inside bars (or immediate if i_rearmBars == 0)
        if nyCooldownDone
            if i_rearmBars == 0
                nySigFired := false
                nyBrkPending := false
                nyTP1Hit := false, nyTP2Hit := false, nyTP3Hit := false, nySLHit := false
            else
                // Check if bar is inside ORB range with buffer
                if not nyInsideStarted
                    if close >= nyORBLow + rearmBuf and close <= nyORBHigh - rearmBuf
                        nyInsideStarted := true
                        nyInsideBars := 1
                else
                    nyInsideBars += 1
                if nyInsideStarted and nyInsideBars >= i_rearmBars
                    nySigFired := false
                    nyBrkPending := false
                    nyInsideBars := 0
                    nyInsideStarted := false
                    nyTP1Hit := false, nyTP2Hit := false, nyTP3Hit := false, nySLHit := false
 
// ── AS Re-Arm ──
if i_rearmEnable and i_asEnable and asOrbComplete and inAsTrade and asSigFired and asSigDir == 0 and strategy.position_size == 0 and asTradeCount < i_rearmMaxTrades
    if f_exitQualifies(asLastWasSL)
        if not asCooldownDone
            if bar_index - asExitBar >= i_rearmCooldown
                asCooldownDone := true
        if asCooldownDone
            if i_rearmBars == 0
                asSigFired := false
                asBrkPending := false
                asTP1Hit := false, asTP2Hit := false, asTP3Hit := false, asSLHit := false
            else
                if not asInsideStarted
                    if close >= asORBLow + rearmBuf and close <= asORBHigh - rearmBuf
                        asInsideStarted := true
                        asInsideBars := 1
                else
                    asInsideBars += 1
                if asInsideStarted and asInsideBars >= i_rearmBars
                    asSigFired := false
                    asBrkPending := false
                    asInsideBars := 0
                    asInsideStarted := false
                    asTP1Hit := false, asTP2Hit := false, asTP3Hit := false, asSLHit := false
 
// ── LN Re-Arm ──
if i_rearmEnable and i_lnEnable and lnOrbComplete and inLnTrade and lnSigFired and lnSigDir == 0 and strategy.position_size == 0 and lnTradeCount < i_rearmMaxTrades
    if f_exitQualifies(lnLastWasSL)
        if not lnCooldownDone
            if bar_index - lnExitBar >= i_rearmCooldown
                lnCooldownDone := true
        if lnCooldownDone
            if i_rearmBars == 0
                lnSigFired := false
                lnBrkPending := false
                lnTP1Hit := false, lnTP2Hit := false, lnTP3Hit := false, lnSLHit := false
            else
                if not lnInsideStarted
                    if close >= lnORBLow + rearmBuf and close <= lnORBHigh - rearmBuf
                        lnInsideStarted := true
                        lnInsideBars := 1
                else
                    lnInsideBars += 1
                if lnInsideStarted and lnInsideBars >= i_rearmBars
                    lnSigFired := false
                    lnBrkPending := false
                    lnInsideBars := 0
                    lnInsideStarted := false
                    lnTP1Hit := false, lnTP2Hit := false, lnTP3Hit := false, lnSLHit := false
 
 
 
// ════════════════════════════════════════════════════════════════════════════════
// DASHBOARD
// ════════════════════════════════════════════════════════════════════════════════
if showDashboard
    tablePos = switch dashPosition
        "Top Right" => position.top_right
        "Top Left" => position.top_left
        "Bottom Right" => position.bottom_right
        => position.bottom_left
    var table dash = table.new(tablePos, 3, 9, bgcolor=dashBgColor, border_width=1, border_color=dashBorderColor)
    if barstate.islast
        dash.cell(0, 0, "HTF BIAS", text_color=dashHeaderText, text_size=getDashSize(), bgcolor=dashHeaderBg)
        dash.cell(1, 0, "Structure", text_color=dashHeaderText, text_size=getDashSize(), bgcolor=dashHeaderBg)
        dash.cell(2, 0, "Bias", text_color=dashHeaderText, text_size=getDashSize(), bgcolor=dashHeaderBg)
        dash.cell(0, 1, formatTF(htf1), text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 1, htf1StructureText, text_color=htf1BiasColor, text_size=getDashSize())
        dash.cell(2, 1, htf1BiasText, text_color=htf1BiasColor, text_size=getDashSize())
        dash.cell(0, 2, formatTF(htf2), text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 2, htf2StructureText, text_color=htf2BiasColor, text_size=getDashSize())
        dash.cell(2, 2, htf2BiasText, text_color=htf2BiasColor, text_size=getDashSize())
        // ORB status
        nyOrbText = i_nyEnable ? (nyOrbComplete ? str.tostring(nyORBHigh, format.mintick) + " / " + str.tostring(nyORBLow, format.mintick) : nyOrbBuilding ? "Building..." : "—") : "OFF"
        dash.cell(0, 3, "NY ORB", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 3, nyOrbText, text_color=i_nyHighColor, text_size=getDashSize())
        dash.merge_cells(1, 3, 2, 3)
        asOrbText = i_asEnable ? (asOrbComplete ? str.tostring(asORBHigh, format.mintick) + " / " + str.tostring(asORBLow, format.mintick) : asOrbBuilding ? "Building..." : "—") : "OFF"
        dash.cell(0, 4, "ASIA ORB", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 4, asOrbText, text_color=i_asHighColor, text_size=getDashSize())
        dash.merge_cells(1, 4, 2, 4)
        lnOrbText = i_lnEnable ? (lnOrbComplete ? str.tostring(lnORBHigh, format.mintick) + " / " + str.tostring(lnORBLow, format.mintick) : lnOrbBuilding ? "Building..." : "—") : "OFF"
        dash.cell(0, 5, "LDN ORB", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 5, lnOrbText, text_color=i_lnHighColor, text_size=getDashSize())
        dash.merge_cells(1, 5, 2, 5)
        // Trail status
        _trailText = i_trailEnable ? str.tostring(i_trailArmTicks) + " tick arm" : "OFF"
        dash.cell(0, 6, "Trail Stop", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 6, _trailText, text_color=i_trailEnable ? color.yellow : dashNeutralColor, text_size=getDashSize())
        dash.merge_cells(1, 6, 2, 6)
        // Mode
        dash.cell(0, 7, "Mode", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 7, sessionMode, text_color=dashLabelColor, text_size=getDashSize())
        dash.merge_cells(1, 7, 2, 7)
        // P&L
        _pnl = strategy.netprofit
        _pnlColor = _pnl >= 0 ? dashBullColor : dashBearColor
        dash.cell(0, 8, "Net P&L", text_color=dashLabelColor, text_size=getDashSize())
        dash.cell(1, 8, str.tostring(_pnl, format.mintick), text_color=_pnlColor, text_size=getDashSize())
        dash.merge_cells(1, 8, 2, 8)

← 返回列表