ICT FX PRO IFVG SYSTEM V6.0

ICTFX_PRO · study · 3765 行 · 点赞 23 · TradingView 原页

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

Pine Script

//@version=6
indicator("ICT FX PRO IFVG SYSTEM V 6.0", shorttitle = "ICT FX PRO IFVG SYSTEM V 6.0", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 600)
max_bars_back(time, 5000)
int MAX_BACK = 4900
 
const string NY       = "America/New_York"
const string ST_SOLID = "Solid"
const string ST_DASH  = "Dashed"
const string ST_DOT   = "Dotted"
 
// ═══════════════════════════ SETTINGS (checkboxes only) ═══════════════════════════
bool BO_TF_OK = timeframe.in_seconds() <= 3600   // breakout ranges only on 1H and lower charts
bool PD_TF_OK = timeframe.in_seconds() >= 300    // dealing ranges drawn on 5m and higher only (bias timeframes)
i_boHist  = input.bool(true, "BREAKOUT HISTORY", group = "MAIN", inline = "bh", tooltip = "ON = keep the past breakout ranges of the last N days on the chart. OFF = only the current one.")
i_boDays  = input.int(5, "Days", minval = 1, maxval = 60, group = "MAIN", inline = "bh")
i_bo      = input.bool(true, "8 AM BREAKOUT", group = "MAIN", tooltip = "ON/OFF for the whole breakout part: Breakout 1 and 2 ranges and their alerts. Everything else (levels, PD, IFVG, HTF FVG) keeps working.")
const string G_SS = "IFVG"
const string G_HF = "HTF FVG"
const string G_KL = "KEY LEVELS"
const string G_AL = "ALERT"
 
bool i_smt = false   // SMT system not used in this script
bool i_cisd = false   // CISD is not drawn here; its engine still runs because the IFVG is built on it
bool i_ciLq = false
bool i_showBrk = false
i_ifvg    = input.bool(true,  "IFVG", group = G_SS, tooltip = "IFVG after a change in the delivery at a fresh 20-candle low / high: the FVG of the leg into that low (high) closest to it, closed through after it. Ends when price closes back through it or takes that low (high).")
bool i_ifvgCln  = true    // gap must be clean until the extreme (fixed)
i_ifvgNear = input.bool(true, "IFVG PREMIUM ONLY", group = G_SS, tooltip = "Only clear IFVGs:\n• the gap sits in the PREMIUM half of the leg (before a high) / DISCOUNT half (before a low)\n• gap size >= 15% of ATR (no tiny gaps)\n• the gap was made by a DISPLACEMENT candle (body >= 0.85x ATR, or the gap itself >= 0.4x ATR), not chop\n• price closes through it within 20 candles of the high / low")
i_ivLq    = input.bool(true, "LIQUIDITY SWEEP ($$$)", group = G_SS, tooltip = "ON = the high (low) must have SWEPT a swing high (low) in the final push (drawn as $$$, from the swing to the sweep candle). No $$$ → no IFVG.\nOFF = no liquidity condition.")
bool i_ivCi = false   // CISD fallback (IFVG C) removed
bool i_ivCb = false   // CLOSE BACK SWEEP removed
bool i_ivKl = false   // KEY LIQUIDITY ONLY removed
bool i_ivAge = false  // MIN SWING AGE removed
i_ivTgt   = input.bool(true, "TARGET LIQUIDITY", group = G_SS, tooltip = "There must be untaken liquidity to aim for in the trade direction (nearest swing high / low not yet taken, or a key level), at least 2R away.\nR = from the IFVG edge (entry) to the swept high / low (stop).\nDrawn as a dotted orange line with 🎯 (from the target swing to the IFVG).\nTarget reached → 🎯 is written INSIDE the IFVG box, the line and its 🎯 go 4 candles later.\nStop (the swept high / low) taken first → the line goes, no 🎯.")
bool i_ivOpp = false  // NO OPPOSING FVG removed
i_ivDr    = input.bool(true, "WITH DEALING RANGE", group = G_SS, tooltip = "Bullish IFVG only in the DISCOUNT half, bearish IFVG only in the PREMIUM half of the dealing range:\n• charts below 1H → the 1H range\n• 1H and above → the 4H range\nNo range = no filter.")
bool i_ivMin = false  // MIN GAP SIZE removed
float i_ivMinP = 9.0
i_ivCisd  = input.bool(true, "CISD (ON IFVG)", group = G_SS, tooltip = "Draw the CISD only on IFVGs that had one: thin line from the run open to a few candles past the CISD candle, \"CISD\" at its end (blue bull · red bear). No CISD on that IFVG = nothing drawn.")
i_ivSmt   = input.bool(true, "SMT (ON IFVG)", group = G_SS, tooltip = "SMT at the IFVG's high / low vs the correlated index (NQ / MNQ → ES · ES / MES → NQ · others → ES):\nbull = the chart took the swept swing low ($$$) but ES did NOT make a lower low there (bear = the mirror at highs).\nDrawn as a line swing → extreme with \"SMT\", and added to the IFVG alert (… + SMT). No SMT = nothing drawn.")
i_ivDbg   = input.bool(false, "IFVG DEBUG", group = G_SS, tooltip = "Yellow label at every low / high that could give an IFVG, with what happened:\nARM = run made the 20-candle low (high), waiting for the CISD close · NO CISD = no close back over the run open within 30 candles · REPLACED = a newer run took over\nCISD ✓ then the IFVG search: IFVG ✓, or why not: NO GAP (no FVG in the leg) · NOT INVERTED · CLOSED BACK · NOT CLEAN · NOT DISC/PREM · SMALL · WEAK CANDLE · SLOW (>20) · NO $$$ · NO TARGET · TARGET < 2R · NOT IN DR DISC/PREM")
bool i_en1 = false
bool i_en2 = false
bool i_en3 = false
 
i_f1h     = input.bool(true, "FVG", inline = "f1", group = G_HF)
i_t1      = input.string("15m", "", options = ["15m", "30m", "1H", "4H", "1D", "W"], inline = "f1", group = G_HF)
i_if1h    = input.bool(true, "IFVG",   inline = "f1", group = G_HF)
i_f4h     = input.bool(true, "FVG", inline = "f4", group = G_HF)
i_t2      = input.string("30m", "", options = ["15m", "30m", "1H", "4H", "1D", "W"], inline = "f4", group = G_HF)
i_if4h    = input.bool(true, "IFVG",   inline = "f4", group = G_HF)
i_f1d     = input.bool(true, "FVG", inline = "fd", group = G_HF)
i_t3      = input.string("1H", "", options = ["15m", "30m", "1H", "4H", "1D", "W"], inline = "fd", group = G_HF)
i_if1d    = input.bool(true, "IFVG",   inline = "fd", group = G_HF)
i_f4      = input.bool(true, "FVG", inline = "f5", group = G_HF)
i_t4      = input.string("4H", "", options = ["15m", "30m", "1H", "4H", "1D", "W"], inline = "f5", group = G_HF)
i_if4     = input.bool(true, "IFVG",   inline = "f5", group = G_HF)
i_f5      = input.bool(true, "FVG", inline = "f6", group = G_HF)
i_t5      = input.string("1D", "", options = ["15m", "30m", "1H", "4H", "1D", "W"], inline = "f6", group = G_HF, tooltip = "5 HTF gap slots, each with its own timeframe (15m · 30m · 1H · 4H · 1D · W). A timeframe lower than or equal to the chart, or already used by another slot, is skipped.")
i_if5     = input.bool(true, "IFVG",   inline = "f6", group = G_HF, tooltip = "5 HTF gap slots, each with its own timeframe (15m · 30m · 1H · 4H · 1D · W). A timeframe lower than or equal to the chart, or already used by another slot, is skipped.\nIFVG ON = when a candle CLOSES through that timeframe's FVG, it turns into an IFVG (dashed, blue = support / red = resistance) and stays.\nIFVG OFF = a broken FVG of that timeframe is simply removed.")
i_hfForm  = input.bool(false, "FORMING FVG", group = G_HF, tooltip = "Show the HTF gap that is FORMING right now (live, last 25% of that timeframe's candle, size-filtered) as a dashed box \"BULL 1H · forming\". It becomes a real FVG only when that candle closes; otherwise it disappears.")
i_hfPd    = input.bool(false, "FVG IN PREMIUM / DISCOUNT ONLY", group = G_HF, tooltip = "Each HTF gap is checked against the CURRENT dealing range of its own timeframe (1D gap → daily range, 4H → 4H range, 1H → 1H range):\n• bullish FVG / IFVG (support) shown only in the DISCOUNT half (below the 50%)\n• bearish FVG / IFVG (resistance) shown only in the PREMIUM half (above the 50%)\nOther gaps are hidden (not deleted) and give no FVG ALERT. No range on that timeframe = gap shown.")
i_hfShort = input.bool(true, "FVG SHORT (±8 CANDLES)", group = G_HF, tooltip = "ON = each HTF FVG / IFVG is drawn only around the last candle: from 8 candles back to 8 candles ahead, moving with price — you only see that there is a gap at that level.\nOFF = drawn from where the gap started.")
i_hfLine  = input.bool(false, "FVG AS LINE", group = G_HF, tooltip = "On = each HTF FVG / IFVG is drawn as ONE line at the edge price reaches first (bullish gap below price: its top · bearish gap above price: its bottom) with its name, instead of the full box. A small \"T\" from the line to the other edge of the gap shows its size. Detection, IFVG flips and alerts are unchanged.")
 
i_showAll = input.bool(false, "SHOW ALL", group = G_KL, tooltip = "OFF = clean chart:\n• sessions and BSL / SSL always drawn\n• key levels (opens · PDH/PDL/PDC · PWH/PWL/PWC · PMH/PML/PMC) and NDOG/NWOG only when price is near them (0.5 x daily ATR)\n• HTF FVG / IFVG NOT drawn — only the HTF gap an IFVG reversed from, until its target, its stop or the IFVG fails\nON = everything drawn all the time (HTF gaps included).")
i_klShort = input.bool(true, "SHORT LINES (11 BACK · 6 AHEAD)", group = G_KL, tooltip = "ON = session, opens (midnight · 8:30 · 9:30) and PDH/PDL · PWH/PWL · PMH/PML lines are drawn only around the last candle: from 11 candles back to 6 candles ahead, moving with price — you see the level, not a long line.\nOFF = drawn from where the level started.")
i_sesLq   = input.bool(true, "SESSIONS + BUY / SELL SIDE", group = G_KL, tooltip = "Asia / London / NY session high-low and the nearest BSL / SSL pools.")
bool i_bsl = i_sesLq
bool i_ses = i_sesLq
i_opens   = input.bool(true, "OPENS (MIDNIGHT · 8:30 · 9:30)", group = G_KL)
bool i_mid = i_opens
bool i_830 = i_opens
bool i_930 = i_opens
i_prev    = input.bool(true, "PREVIOUS HIGH / LOW / CLOSE (D · W · M)", group = G_KL, tooltip = "PDH / PDL / PDC · PWH / PWL / PWC · PMH / PML / PMC")
bool i_pd = i_prev
bool i_pw = i_prev
bool i_pm = i_prev
i_ndog    = input.bool(true, "NDOG",                 group = G_KL, tooltip = "New Day Opening Gap: the gap between the daily close (17:00 ET) and the next open (18:00 ET). Box + dashed CE (50%). Today's only.")
i_nwog    = input.bool(true, "NWOG",                 group = G_KL, tooltip = "New Week Opening Gap: the gap between Friday's close and Sunday's open (18:00 ET). Box + dashed CE (50%). This week's only.")
 
const string G_PD = "PREMIUM & DISCOUNT"
i_pd_on  = input.bool(true, "PREMIUM & DISCOUNT", group = G_PD, tooltip = "Auto dealing range of each strong impulse: PREMIUM (upper half) / DISCOUNT (lower half) / EQ 50%.")
i_pdKeep = input.bool(true,  "KEEP SHOWN RANGE", group = G_PD, tooltip = "ON = once a range is on the chart it is removed ONLY by a close beyond its origin (bearish: above its high · bullish: below its low). A quick return through the 50% no longer deletes it — that return is the PREMIUM / DISCOUNT you trade.\nOFF = old behaviour: a close back through the 50% within 3 candles of the extreme deletes it (failed impulse).\nCandidates that are not shown yet always keep the failed-impulse filter.")
bool i_pdW = false   // HTF dealing ranges are not drawn (table only)
bool i_pdD = false
bool i_pd4 = false
bool i_pd1 = false
i_pdTbl  = input.bool(true,  "PD TABLE",  group = G_PD, tooltip = "Compact dark table of W / D / 4H / 1H, independent of the checkboxes above (they only draw):\n▲ / ▼ range direction · Zone: PREM / EQ (within 5% of the 50%) / DISC / ABOVE / BELOW the range · 50%: ✓ price already reached the 50% after the range extreme, ✗ not yet · BIAS: how many timeframes agree.")
bool i_pdBull = true   // engine always runs (table); the checkbox only controls the drawing
bool i_pdBear = true
bool i_pdBoth = false
bool i_pdOte  = false
bool i_pdLbl  = true
 
bool i_alert = false
i_boAl    = input.bool(true, "BREAKOUT ALERT", group = G_AL, tooltip = "Breakout 1 / 2 range break — a candle of the chart you set the alert on CLOSES beyond the range:\n🟢 BO1 BREAKOUT | MNQ | 5M  ·  🔴 BO2 BREAKOUT | MNQ | 5M")
i_alLq    = input.bool(true, "LIQUIDITY SWEEP ALERT", group = G_AL, tooltip = "BSL / SSL pool: alert ONLY when the candle wicks through it and CLOSES BACK (sweep):\n🔴 BSL SWEEP | MNQ | 3M  ·  🟢 SSL SWEEP | MNQ | 3M\nA candle that closes through and continues = no alert (the pool is spent).")
i_alPx    = input.bool(true, "PREVIOUS H/L/C ALERT", group = G_AL, tooltip = "PDH / PDL / PDC · PWH / PWL / PWC · PMH / PML / PMC — same SWEEP rule:\nwick through + close back = alert, close through = ignored (one chance per level).\n🔴 PDH SWEEP | MNQ | 3M  ·  🟢 PWL SWEEP | MNQ | 3M  ·  🟢 PDC SWEEP | MNQ | 3M\n(H = sweep up 🔴 · L = sweep down 🟢 · C = from the side price comes from)")
i_alOp    = input.bool(true, "OPENS ALERT", group = G_AL, tooltip = "Today's MIDNIGHT / 8:30 / 9:30 open — same SWEEP rule (one chance per level):\n🟢 MIDNIGHT SWEEP | MNQ | 3M = came from above, wicked below, closed back above\n🔴 9:30 SWEEP | MNQ | 3M = came from below, wicked above, closed back below")
i_alSes   = input.bool(true, "SESSION SWEPT ALERT", group = G_AL, tooltip = "Price takes today's Asia / London / NY session high or low (first trade through):\n🔴 ASIA H SWEPT | MNQ | 3M  ·  🟢 LDN L SWEPT | MNQ | 3M")
i_alPD    = input.bool(true, "PREMIUM / DISCOUNT ALERT", group = G_AL, tooltip = "The chart range (make one alert per timeframe: W, D, 4H, 1H charts), live:\n🟢 NEAR DISCOUNT | MNQ | 4H = within min(5% of the range, 1x ATR) of the 50%\n🟢 IN DISCOUNT | MNQ | 4H = crossed the 50% into discount\n🔴 NEAR PREMIUM / 🔴 IN PREMIUM = the same above the 50%\nOnly the trading side: bullish range → discount alerts · bearish range → premium alerts.\nAgain only after a close deep on the other side (40% of the range from the 50%) and 20+ candles later.")
float PD_NEAR = 0.10   // alert when price is within 10% of the range from the 50%
i_alNear  = input.bool(true, "NEAR LEVEL ALERT", group = G_AL, tooltip = "Price comes NEAR (0.5 x daily ATR) a key level or an HTF FVG / IFVG — the moment it appears on the chart:\n🔔 NEAR PWH | MNQ | 3M  ·  🔔 NEAR 4H FVG | MNQ | 3M\nOnce per level; again only after price has moved away (2x the near distance).")
i_alFvg   = input.bool(true, "FVG ALERT", group = G_AL, tooltip = "Price trades into an HTF FVG or IFVG box (first touch):\n🔴 FVG 1H | MNQ | 3M  ·  🟢 IFVG 4H | MNQ | 3M")
i_alIfvg  = input.bool(true, "IFVG ALERT", group = G_AL, tooltip = "New IFVG (candle close), and price coming back NEAR it (within 1 x ATR of its edge, after it had moved away) — once per IFVG, with the zone price reversed from (HTF gap · session / previous high-low) and the extras when there: CISD · SMT:\n🟢 NEW IFVG ← 15m FVG + ASIA L + SMT | MNQ | 1M\n🔴 NEAR IFVG ← 1H IFVG + CISD | MNQ | 1M")
bool i_alCiF = i_alIfvg
 
// ─────────── fixed defaults (hidden) ───────────
 
i_auto = true
string i_s1 = "CME_MINI:NQ1!"
string i_s2 = "CME_MINI:ES1!"
string i_s3 = "CBOT_MINI:YM1!"
bool i_iv1 = false
bool i_iv2 = false
bool i_iv3 = false
 
bool   i_dbl  = false
int    i_w    = 2
string i_st   = ST_SOLID
color  i_cBu  = #4CAF50
color  i_cBe  = #F23645
color  i_lBu  = #4CAF50
color  i_lBe  = #F23645
int    i_maxN = 0
 
string i_brkSt = ST_DASH
int    i_brkT  = 65
 
bool   i_ciAll = false
color  i_ciBu  = #2962FF
color  i_ciBe  = #F23645
string i_ciSt  = ST_DOT
int    i_ciMax = 40
 
bool   i_showDiv = false
int    i_maxDiv  = 50
color  i_dC      = color.new(color.gray, 60)
int    i_dW      = 1
string i_dS      = ST_DOT
 
color  i_lbBg  = color.new(color.black, 100)
color  i_lbTx  = color.new(color.white, 100)
string i_lbSz  = "Small"
string i_lbPos = "Middle"
string i_lbSty = "Auto"
bool   i_tag   = false
 
bool   i_alClose = true
 
string i_stPos = "Bottom Right"
color  i_stTx  = #787B86
color  i_stBg  = color.new(#787B86, 90)
 
// Nearby liquidity
bool   lqBMajOn   = i_bsl
color  lqBMajCol  = color.new(#000000, 0)
string lqBMajSty  = "····"
bool   lqSMajOn   = i_bsl
color  lqSMajCol  = color.new(#000000, 0)
string lqSMajSty  = "····"
int    lqMajLen   = 40
bool   lqKeyTagOn = true
string lqLblSz    = "Small"
bool   lqThick    = true
bool   lqShort    = true
 
// Session levels
bool   sesAsOn  = i_ses
color  sesAsCol = #f5a800
int    sesAsW   = 1
bool   sesLoOn  = i_ses
color  sesLoCol = #2962ff
int    sesLoW   = 1
bool   sesNyOn  = i_ses
color  sesNyCol = #f23645
int    sesNyW   = 1
string sesSty   = "----"
string sesLblSz = "Small"
 
// HTF FVGs: 5 slots, each with its own timeframe (inputs)
bool   useHf1  = i_f1h
string hf1Sel  = i_t1
color  hf1Bull = color.new(#26a69a, 75)
color  hf1Bear = color.new(#000000, 72)
bool   useHf2  = i_f4h
string hf2Sel  = i_t2
color  hf2Bull = color.new(#26a69a, 75)
color  hf2Bear = color.new(#000000, 72)
bool   useHf3  = i_f1d
string hf3Sel  = i_t3
color  hf3Bull = color.new(#26a69a, 75)
color  hf3Bear = color.new(#000000, 72)
bool   useHf4  = i_f4
string hf4Sel  = i_t4
color  hf4Bull = color.new(#26a69a, 75)
color  hf4Bear = color.new(#000000, 72)
bool   useHf5  = i_f5
string hf5Sel  = i_t5
color  hf5Bull = color.new(#26a69a, 75)
color  hf5Bear = color.new(#000000, 72)
color  hfTxtCol  = color.black
bool   hfIfvg    = true
color  hfIfBu    = color.new(#2962ff, 80)
color  hfIfBe    = color.new(#f23645, 80)
bool   hfForm    = i_hfForm
int    hfFormPct = 25
float  hfFormMin = 0.15
 
// ═══════════════════════════ HELPERS ═══════════════════════════
f_style(string s) => s == ST_DASH ? line.style_dashed : s == ST_DOT ? line.style_dotted : line.style_solid
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
f_pos(string s) =>
    switch s
        "Bottom Right" => position.bottom_right
        "Top Left"     => position.top_left
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_short(string s) => s == "" ? "" : array.last(str.split(s, ":"))
 
f_mx(float a, float b) => na(b) ? a : na(a) ? b : math.max(a, b)
f_mn(float a, float b) => na(b) ? a : na(a) ? b : math.min(a, b)
 
f_tf() =>
    int m = timeframe.multiplier
    timeframe.isseconds ? str.tostring(m) + "S" : timeframe.isminutes ? (m % 60 == 0 ? str.tostring(m / 60) + "H" : str.tostring(m) + "M") : timeframe.isdaily ? str.tostring(m) + "D" : timeframe.isweekly ? str.tostring(m) + "W" : str.tostring(m) + "MO"
 
string SYM = syminfo.root != "" ? syminfo.root : syminfo.ticker
string TF  = f_tf()
// cycle auto-scales with the chart: 90m quarters up to 45m charts, 6H (daily session) quarters
// up to 3H charts, whole-day quarters (weekly cycle) up to 12H charts
int    CYC_TF = timeframe.in_seconds()
string TAG    = CYC_TF <= 2700 ? "90m" : CYC_TF <= 10800 ? "6H" : "D"
 
// SMT symbols not used in this script (kept as empty constants for the shared code)
string chartId = syminfo.prefix + ":" + syminfo.ticker
bool   has1 = false
bool   has2 = false
string n1   = ""
string n2   = ""
float  oh1  = na
float  ol1  = na
float  oh2  = na
float  ol2  = na
 
// ═══════════════════════════ TIME ENGINE ═══════════════════════════
int tfSec    = timeframe.in_seconds(timeframe.period)
int LEN      = CYC_TF <= 2700 ? 5400000 : CYC_TF <= 10800 ? 21600000 : 86400000
int secDay   = hour(time, NY) * 3600 + minute(time, NY) * 60 + second(time, NY)
int offMs    = ((secDay - 64800 + 86400) % 86400) * 1000   // ms since 18:00 NY
int qIdx     = int(math.floor(offMs / LEN))
int qStart   = time - offMs + qIdx * LEN
int qNum     = qIdx % 4 + 1
 
var int lastQ = na
bool qNew = na(lastQ) or qStart != lastQ
lastQ := qStart
 
bool active = i_smt and LEN >= 2 * tfSec * 1000
 
// ═══════════════════════════ CISD ENGINE ═══════════════════════════
bool isBu = close > open
bool isBe = close < open
 
var float dnO = na   // open of 1st candle of latest bearish series
var int   dnT = na
var float upO = na   // open of 1st candle of latest bullish series
var int   upT = na
 
bool  cisdBu = isBu and not na(dnO) and close > dnO
bool  cisdBe = isBe and not na(upO) and close < upO
float ciBuY  = dnO
int   ciBuX  = dnT
float ciBeY  = upO
int   ciBeX  = upT
 
// fresh-extreme tracking of the current series (for CISD / IFVG WITHOUT SMT)
float ll20 = ta.lowest(low, 20)[1]
float hh20 = ta.highest(high, 20)[1]
var float dnLo  = na
var int   dnLoT = na
var bool  dnSw  = false
var float upHi  = na
var int   upHiT = na
var bool  upSw  = false
if not na(dnO) and (na(dnLo) or low < dnLo)
    dnLo  := low
    dnLoT := time
    dnSw  := dnSw or low < ll20
if not na(upO) and (na(upHi) or high > upHi)
    upHi  := high
    upHiT := time
    upSw  := upSw or high > hh20
// standalone CISD events (snapshot before the series reset)
bool  stdBu   = cisdBu and dnSw
bool  stdBe   = cisdBe and upSw
float stdBuLo = dnLo
int   stdBuT  = dnLoT
float stdBeHi = upHi
int   stdBeT  = upHiT
 
if cisdBu
    dnO := na
if cisdBe
    upO := na
if isBe and not isBe[1]
    dnO := open
    dnT := time
    dnLo  := low
    dnLoT := time
    dnSw  := low < ll20
if isBu and not isBu[1]
    upO := open
    upT := time
    upHi  := high
    upHiT := time
    upSw  := high > hh20
 
// start of the series that delivered price into each new extreme (never reset)
var float lUpO = na
var int   lUpT = na
var float lDnO = na
var int   lDnT = na
if isBu and not isBu[1]
    lUpO := open
    lUpT := time
if isBe and not isBe[1]
    lDnO := open
    lDnT := time
 
// CISD drawings
var array<line>  ciL = array.new<line>()
var array<label> ciB = array.new<label>()
 
// thin solid line from the open of the series to a few candles past the CISD candle, "CISD" at its end
f_cisdDraw(int x0, float y, color col) =>
    int   xR = time + 4 * timeframe.in_seconds() * 1000
    line  l = line.new(x0, y, xR, y, xloc = xloc.bar_time, color = col, style = line.style_solid, width = 1)
    label b = label.new(xR, y, "CISD", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = col, size = size.small)
    [l, b]
 
f_cisd(int x0, float y, color col) =>
    [l, b] = f_cisdDraw(x0, y, col)
    ciL.push(l)
    ciB.push(b)
    while ciL.size() > i_ciMax
        line.delete(ciL.shift())
        label.delete(ciB.shift())
 
// SMT win measure (chart only: hides SMTs that delivered before breaking)
float SMT_WIN_ATR = 2.0
float smtAtr = ta.atr(14)
 
string ALF = i_alClose ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
 
// bar buffers for the SMT IFVG search (index 0 = current bar), filled every bar
var array<float> sbH = array.new<float>()
var array<float> sbL = array.new<float>()
var array<float> sbC = array.new<float>()
var array<float> sbT = array.new<float>()
sbH.unshift(high)
sbL.unshift(low)
sbC.unshift(close)
sbT.unshift(time)
var array<float> sbO = array.new<float>()
sbO.unshift(open)
var array<float> sbA = array.new<float>()
sbA.unshift(nz(ta.atr(14)))
// correlated index for the IFVG SMT (same timeframe, same bars)
string SMT_SYM = str.contains(syminfo.root, "NQ") ? i_s2 : str.contains(syminfo.root, "ES") ? i_s1 : i_s2
[cmpH, cmpL] = request.security(SMT_SYM, timeframe.period, [high, low], lookahead = barmerge.lookahead_off)
var array<float> sbH2 = array.new<float>()
var array<float> sbL2 = array.new<float>()
sbH2.unshift(cmpH)
sbL2.unshift(cmpL)
if sbH2.size() > 300
    sbH2.pop()
    sbL2.pop()
if sbH.size() > 300
    sbH.pop()
    sbL.pop()
    sbC.pop()
    sbT.pop()
    sbO.pop()
    sbA.pop()
f_sb(array<float> a, int i) => i >= 0 and i < a.size() ? a.get(i) : na
 
// ═══════════════════════════ TYPES ═══════════════════════════
// HTF FVG / IFVG boxes (filled by the HTF FVG engine further down)
var array<box> hfBoxes = array.new<box>()
var array<int> hfDirs  = array.new<int>()
var array<int> hfSlot  = array.new<int>()
var array<int> hfSec   = array.new<int>()
var array<bool> hfInv  = array.new<bool>()   // true = this box has inverted into an IFVG
var array<bool> hfHit  = array.new<bool>()   // price already traded into this box (alert sent)
var array<int>  hfBorn = array.new<int>()
var array<bool> hfNr   = array.new<bool>()   // NEAR alert latch per HTF box
var array<bool> hfPdOk = array.new<bool>()   // gap sits on the right side of its timeframe's dealing range (set by CLEAN CHART)    // bar the box was drawn / inverted on
 
type Sig
    line   ln
    label  lb
    float  lvl
    bool   bear
    bool   swept = false
    color  col
    color  tcol
    int    ct            // confirm time
    float  cl            // CISD level = open of the series that made the SMT extreme
    int    clT
    int    xT            // time of the SMT extreme
    bool   cDone = false // CISD already drawn for this extreme
    line   cdl           // this SMT's CISD drawing (lives and dies with the SMT)
    label  cdb
    color  ccol
    float  atrAt         // ATR(14) when the SMT formed (win yardstick)
    bool   won = false   // price moved >= SMT_WIN_ATR x ATR in favour before breaking the SMT
    bool   gone = false  // deleted (live SMT vanished / trimmed)
    box    ivBox         // SMT IFVG zone
    float  ivKey         // identity of the drawn zone (left-candle time)
    int    ivBar         // bar the current zone was first drawn
    bool   ivHit = false // IFVG alert sent for this zone
    float  ivTop         // locked zone
    int    ivR           // time of the inversion candle (right edge of the trace)
    float  ivBot
    bool   ivEnd = false // the locked IFVG failed: no new IFVG for this SMT
    bool   al = false    // SMT alert / SMT-only trade already done
    bool   std = false   // standalone IFVG owner (IFVG WITHOUT SMT), not a real SMT
    int    ivLockBar     // bar the IFVG was locked
    label  dbl           // IFVG DEBUG label
    bool   cisd = false  // a CISD has confirmed this extreme
    string ivTag = "IFVG" // "IFVG" = liquidity swept ($$$) · "IFVG C" = no $$$, confirmed by a CISD
    float  swL           // swept liquidity level ($$$) found at lock
    int    swT
    string swN = "$$$"
    float  tgL           // target liquidity (🎯)
    int    tgT
    float  tgStop        // the swept high / low (stop): taken first = target cancelled
    bool   tgHit = false // target reached → 🎯 inside the box
    box    trB           // the box after it was frozen to the history
    string src = ""      // what price reversed from: "15m FVG + ASIA L + $$$"
    float  srStop        // the high / low of the reversal (stop)
    float  srTop         // the HTF gap it reversed from (drawn until target / stop / fail)
    float  srBot
    string srNm = ""
    int    srL           // first candle that traded into that gap
    bool   ivRej = false // the filters said NO at the inversion → final (no late IFVG)
    string ivWhy = ""
    bool   ivArm = false // price moved away from the IFVG (NEAR alert armed)
    int    ciX           // CISD: run open time / level / CISD candle time
    float  ciY
    int    ciT
    bool   ciDone = false
    bool   smt = false
 
type Cyc
    int         cnt = 0
    float       pH
    float       pL
    int         pHt
    int         pLt
    float       pH1
    float       pL1
    float       pH2
    float       pL2
    float       cH
    float       cL
    int         cHt
    int         cLt
    float       cH1
    float       cL1
    float       cH2
    float       cL2
    float       cHo
    int         cHoT
    float       cLo
    int         cLoT
    Sig         bear
    Sig         bull
    array<Sig>  hist
    array<line> divs
    int         nBu = 0
    int         nBe = 0
    int         sBu = 0
    int         sBe = 0
    int         wBu = 0     // SMTs that delivered (moved >= SMT_WIN_ATR x ATR in favour) before breaking
    int         wBe = 0
 
// finished IFVGs stay as a faded trace on their 3 formation candles (no extension)
// trace = gap origin → inversion candle, with a dashed CE (50%) line, no extension
var array<box>  ivTrace  = array.new<box>()
var array<line> ivTraceL = array.new<line>()
var array<float>  ivKP = array.new<float>()    // key highs / lows for the IFVG liquidity filters
var array<string> ivKN = array.new<string>()
var array<bool>   ivKH = array.new<bool>()     // true = a high
var array<float>  ivPP = array.new<float>()    // open BSL / SSL pools (TARGET LIQUIDITY)
var array<bool>   ivPH = array.new<bool>()
var float ivDrH = na   // dealing range used by WITH DEALING RANGE
var float ivDrL = na
// joins two level names; two session highs (lows) become one short name: "LDN/AS H"
f_sesOk(string t) =>
    array<string> p = str.split(t, " ")
    bool ok = p.size() == 2 or (p.size() == 3 and p.get(2) == "✓")
    if ok
        ok := p.get(1) == "H" or p.get(1) == "L"
    if ok
        for q in str.split(p.get(0), "/")
            ok := ok and (q == "ASIA" or q == "AS" or q == "LDN" or q == "NY")
    ok
f_join(string a, string b) =>
    string r = a + " + " + b
    if f_sesOk(a) and f_sesOk(b)
        array<string> pa = str.split(a, " ")
        array<string> pb = str.split(b, " ")
        if pa.get(1) == pb.get(1) and pa.size() == pb.size()
            string pre = str.replace_all(pa.get(0), "ASIA", "AS")
            for q in str.split(str.replace_all(pb.get(0), "ASIA", "AS"), "/")
                if not str.contains("/" + pre + "/", "/" + q + "/")
                    pre += "/" + q
            r := pre + " " + pa.get(1) + (pa.size() == 3 ? " ✓" : "")
    r
f_secNm(int s) =>
    s >= 604800 ? "W" : s >= 86400 ? "1D" : s >= 14400 ? "4H" : s >= 3600 ? "1H" : s >= 1800 ? "30m" : "15m"
var array<Sig> srS = array.new<Sig>()   // IFVGs whose source HTF gap is drawn
var array<box> srB = array.new<box>()
// alert text: the zone it reversed from, then the extras (CISD, SMT) when they are there
f_ivSrc(Sig s) =>
    string r = s.src
    if s.cisd
        r := r == "" ? "CISD" : r + " + CISD"
    if s.smt
        r := r == "" ? "SMT" : r + " + SMT"
    r == "" ? "" : " ← " + r
f_ivTxt(Sig s) => s.ivTag + (s.tgHit ? " 🎯" : "")
var array<Sig>   tgS  = array.new<Sig>()     // IFVGs whose target is still open
var array<line>  tgLn = array.new<line>()
var array<label> tgLb = array.new<label>()
var array<int>   tgHB = array.new<int>()       // bar the target was reached (na = still open)
var array<line>  ivLqL = array.new<line>()    // swept liquidity "$$$" of each IFVG (kept in the history)
var array<label> ivLqB = array.new<label>()
 
// The liquidity the run into the extreme SWEPT: the closest swing high (low) below (above) the
// extreme — a 3-candle pivot within 60 candles before it — that was still untaken when the final
// push started (first taken within the last 15 candles before the extreme).
// Filters (checkboxes): CLOSE BACK SWEEP · KEY LIQUIDITY ONLY · MIN SWING AGE.
// Returns [level, time of the swing, name] (na = none).
f_brk(bool bear, float v, int kFrom, int a) =>
    // first candle (oldest → newest, from kFrom - 1 to a) that traded beyond v (-1 = none)
    int fb = -1
    if kFrom - 1 >= a
        for q = kFrom - 1 to a
            float hq = bear ? f_sb(sbH, q) : f_sb(sbL, q)
            if fb < 0 and (bear ? hq > v : hq < v)
                fb := q
    fb
f_cbOk(bool bear, float v, int fb, int a) =>
    // CLOSE BACK SWEEP: max 1 close beyond v from the sweep to the extreme, back inside within 3 candles
    int nB = 0
    for q = fb to a
        float cq = f_sb(sbC, q)
        nB += (bear ? cq > v : cq < v) ? 1 : 0
    bool back = false
    for q = a to math.max(a - 3, 0)
        float cq = f_sb(sbC, q)
        back := back or (bear ? cq < v : cq > v)
    nB <= 1 and back
f_sweptLiq(bool bear, int xT) =>
    float  lvl = na
    int    lt  = na
    string nm  = "$$$"
    int    n   = sbT.size()
    int    a   = 0
    while a + 1 < n and f_sb(sbT, a) > xT
        a += 1
    float ext = bear ? f_sb(sbH, a) : f_sb(sbL, a)
    float atr = nz(f_sb(sbA, a), smtAtr)
    int kMax = math.min(a + 60, n - 6)
    if not na(ext) and kMax >= a + 2
        for k = a + 2 to kMax
            float v = bear ? f_sb(sbH, k) : f_sb(sbL, k)
            bool piv = true
            bool big = true
            for q = 1 to 5
                float l1 = bear ? f_sb(sbH, k - q) : f_sb(sbL, k - q)
                float l2 = bear ? f_sb(sbH, k + q) : f_sb(sbL, k + q)
                bool beat = bear ? (l1 > v or l2 > v) : (l1 < v or l2 < v)
                if beat
                    big := false
                    if q <= 2
                        piv := false
            if piv and (bear ? v < ext : v > ext) and (na(lvl) or (bear ? v > lvl : v < lvl))
                int fb = f_brk(bear, v, k, a)
                bool ok = fb >= a and fb - a <= 15
                ok := ok and (not i_ivAge or k - fb >= 10)
                ok := ok and (not i_ivCb or f_cbOk(bear, v, fb, a))
                string tag = "$$$"
                if ok and i_ivKl
                    // equal highs / lows: another swing within 0.1 x ATR
                    bool eq = false
                    for k2 = a + 2 to kMax
                        if not eq and k2 != k and math.abs(k2 - k) > 2
                            float v2 = bear ? f_sb(sbH, k2) : f_sb(sbL, k2)
                            bool p2 = true
                            for q = 1 to 2
                                float m1 = bear ? f_sb(sbH, k2 - q) : f_sb(sbL, k2 - q)
                                float m2 = bear ? f_sb(sbH, k2 + q) : f_sb(sbL, k2 + q)
                                if bear ? (m1 > v2 or m2 > v2) : (m1 < v2 or m2 < v2)
                                    p2 := false
                            eq := p2 and math.abs(v2 - v) <= 0.1 * atr
                    ok := eq or big
                    tag := eq ? (bear ? "$$$ EQH" : "$$$ EQL") : (bear ? "$$$ SWING H" : "$$$ SWING L")
                if ok
                    lvl := v
                    lt  := int(f_sb(sbT, k))
                    nm  := tag
        // key levels (session / previous day-week-month highs and lows) swept by the same push
        if i_ivKl and ivKP.size() > 0
            int kTop = math.min(a + 60, n - 1)
            for i = 0 to ivKP.size() - 1
                float v = ivKP.get(i)
                if ivKH.get(i) == bear and not na(v) and (bear ? v < ext : v > ext) and (na(lvl) or (bear ? v > lvl : v < lvl))
                    int fb = f_brk(bear, v, kTop + 1, a)
                    bool ok = fb >= a and fb - a <= 15
                    ok := ok and (not i_ivCb or f_cbOk(bear, v, fb, a))
                    if ok
                        lvl := v
                        lt  := int(f_sb(sbT, math.min(fb + 20, n - 1)))
                        nm  := "$$$ " + ivKN.get(i)
    [lvl, lt, nm]
 
// TARGET: nearest untaken liquidity beyond the entry in the trade direction (swing high / low in the
// buffer that no candle has taken since, or a key level price has not reached). [level, time]
f_ivTarget(bool bear, int a, float entry) =>
    float tg  = na
    int   tgt = na
    int   n   = sbT.size()
    float run = bear ? f_sb(sbL, 0) : f_sb(sbH, 0)   // extreme of the candles newer than k
    if n > 6
        for k = 1 to n - 3
            float v = bear ? f_sb(sbL, k) : f_sb(sbH, k)
            if k >= 2
                bool piv = true
                for q = 1 to 2
                    float l1 = bear ? f_sb(sbL, k - q) : f_sb(sbH, k - q)
                    float l2 = bear ? f_sb(sbL, k + q) : f_sb(sbH, k + q)
                    if bear ? (l1 < v or l2 < v) : (l1 > v or l2 > v)
                        piv := false
                bool untaken = bear ? v < run : v > run
                if piv and untaken and (bear ? v < entry : v > entry) and (na(tg) or (bear ? v > tg : v < tg))
                    tg  := v
                    tgt := int(f_sb(sbT, k))
            run := bear ? math.min(run, v) : math.max(run, v)
    // key levels price has not traded to since the extreme
    float since = bear ? f_sb(sbL, 0) : f_sb(sbH, 0)
    for q = 0 to math.min(a, n - 1)
        since := bear ? math.min(since, f_sb(sbL, q)) : math.max(since, f_sb(sbH, q))
    if ivKP.size() > 0
        for i = 0 to ivKP.size() - 1
            float v = ivKP.get(i)
            if ivKH.get(i) != bear and not na(v) and (bear ? v < since and v < entry : v > since and v > entry) and (na(tg) or (bear ? v > tg : v < tg))
                tg  := v
                tgt := int(f_sb(sbT, math.min(a + 20, n - 1)))
    [tg, tgt]
 
// OPPOSING FVG between the entry and 2R: chart FVG of the other direction not closed through yet,
// or an HTF FVG / IFVG box of the other direction. Returns its name ("" = none).
f_ivOpp(bool bear, float p1, float p2) =>
    float lo = math.min(p1, p2)
    float hi = math.max(p1, p2)
    string res = ""
    int   n    = sbT.size()
    float mC   = na   // extreme close of the candles newer than the gap
    if n > 4
        for m = 1 to math.min(n - 2, 250)
            if m - 2 >= 0
                float cq = f_sb(sbC, m - 2)
                mC := na(mC) ? cq : bear ? math.min(mC, cq) : math.max(mC, cq)
            // bull IFVG: opposing = bearish FVG (low c1 > high c3) · bear IFVG: bullish FVG (high c1 < low c3)
            float top = bear ? f_sb(sbL, m - 1) : f_sb(sbL, m + 1)
            float bot = bear ? f_sb(sbH, m + 1) : f_sb(sbH, m - 1)
            if res == "" and not na(top) and not na(bot) and top - bot >= 0.15 * smtAtr
                bool alive = na(mC) or (bear ? mC >= bot : mC <= top)
                if alive and bot < hi and top > lo
                    res := " OPPOSING FVG"
    if res == "" and hfBoxes.size() > 0
        for i = 0 to hfBoxes.size() - 1
            box hb = hfBoxes.get(i)
            if (bear ? hfDirs.get(i) == 1 : hfDirs.get(i) == -1) and hb.get_bottom() < hi and hb.get_top() > lo
                res := " OPPOSING HTF FVG"
    res
 
f_ifvgFreeze(Sig s) =>
    if not na(s) and not na(s.ivBox)
        if i_ifvg and not na(s.ivR)
            // finished IFVG stays in the history as a SHORT trace: gap → inversion candle (+3),
            // same colour lighter, "IFVG" text, dashed 50% line — no extension
            color cz  = s.bear ? #F23645 : #26C6DA
            int   lft = s.ivBox.get_left()
            int   rgt = s.ivR + 3 * timeframe.in_seconds() * 1000
            float tp  = s.ivBox.get_top()
            float bt  = s.ivBox.get_bottom()
            float ce  = (tp + bt) / 2
            s.ivBox.set_right(rgt)
            s.ivBox.set_bgcolor(color.new(cz, 80))
            s.ivBox.set_border_color(color.new(cz, 100))
            s.ivBox.set_text(f_ivTxt(s))
            s.ivBox.set_text_color(color.new(color.gray, 20))
            s.trB := s.ivBox
            ivTrace.push(s.ivBox)
            ivTraceL.push(line.new(lft, ce, rgt, ce, xloc = xloc.bar_time, color = color.new(cz, 50), style = line.style_dashed, width = 1))
            while ivTrace.size() > 40
                box.delete(ivTrace.shift())
                line.delete(ivTraceL.shift())
        else
            box.delete(s.ivBox)
        s.ivBox := na
 
f_kill(Sig s) =>
    if not na(s)
        s.gone := true
        f_ifvgFreeze(s)
        line.delete(s.ln)
        label.delete(s.lb)
        line.delete(s.cdl)
        label.delete(s.cdb)
 
// ─────────── SMT IFVG ───────────
color IV_BU = color.new(#26C6DA, 65)   // light cyan (bullish IFVG)
color IV_BE = color.new(#F23645, 78)   // light red (bearish IFVG)
 
// IFVG for a CISD: the FVG of the leg into the extreme (formed at or before it) that sits CLOSEST
// TO THE EXTREME (highest gap before a high / lowest gap before a low), closed through after it.
// displacement: the middle candle's body >= 0.7 x ATR (ATR before it), or the gap itself >= 0.35 x ATR
f_disp(int m, float top, float bot) =>
    float at = nz(f_sb(sbA, m + 1), smtAtr)
    math.abs(f_sb(sbC, m) - f_sb(sbO, m)) >= 0.85 * at or (top - bot) >= 0.4 * at
f_dbSet(label l, string t) =>
    if not na(l)
        l.set_text(t)
f_ifvgUpdate(Sig s) =>
    if not na(s)
        // the zone is also tracked (not drawn) when the stats enter on the IFVG retest
        bool ok = s.std and not s.gone and s.cDone and not s.swept and not s.ivEnd
        float bestB = na
        float bestT = na
        float bestL = na
        float bestD = na
        float bestR = na
        int   bestIa = na   // candles since the chosen gap inverted
        string why  = ""
        // LOCKED: once an IFVG is chosen it stays put; it only ends on a close back through it
        if ok and not na(s.ivKey)
            bool failNow = barstate.isconfirmed and (s.bear ? close > s.ivTop : close < s.ivBot)
            if failNow
                s.ivEnd := true
            else
                bestT := s.ivTop
                bestB := s.ivBot
                bestL := s.ivKey
        if ok and na(s.ivKey)
            bool bear = s.bear
            int  n    = sbT.size()
            int  a    = 0
            while a + 1 < n and f_sb(sbT, a) > s.xT
                a += 1
            int mx = math.min(a + 60, n - 2)
            // the leg into the SMT extreme starts at the opposite extreme before it
            // (bull SMT: highest high before the low · bear SMT: lowest low before the high)
            int   ls = a
            float lv = bear ? f_sb(sbL, a) : f_sb(sbH, a)
            for k = a to mx
                float v = bear ? f_sb(sbL, k) : f_sb(sbH, k)
                if bear ? v < lv : v > lv
                    lv := v
                    ls := k
            mx := math.min(mx, ls - 1)   // c1 (= m + 1) must be inside the leg
            float ext  = bear ? f_sb(sbH, a) : f_sb(sbL, a)   // SMT extreme
            float legM = (lv + ext) / 2                       // middle of the leg
            why := "NO GAP"
            float  whyD = na
            if mx >= a + 1
                for m = a + 1 to mx
                    // c3 = m - 1 (newer, at/before the extreme), c1 = m + 1 (older)
                    float top = bear ? f_sb(sbL, m - 1) : f_sb(sbL, m + 1)
                    float bot = bear ? f_sb(sbH, m + 1) : f_sb(sbH, m - 1)
                    // CLEAN: no close beyond the far side between the gap (c3) and the SMT extreme
                    bool used = false
                    if i_ifvgCln and m - 2 >= a + 1
                        for q = a + 1 to m - 2
                            float cq = f_sb(sbC, q)
                            used := used or (bear ? cq < bot : cq > top)
                    if i_ivDbg and not na(top) and not na(bot) and top > bot
                        // reasons for this gap (debug): keep the gap closest to the extreme
                        int  dInv = -1
                        bool dFail = false
                        for j = a to 0
                            float c = f_sb(sbC, j)
                            if dInv < 0
                                if bear ? c < bot : c > top
                                    dInv := j
                            else if bear ? c > top : c < bot
                                dFail := true
                        string w = ""
                        w += used ? " NOT CLEAN" : ""
                        w += dInv < 0 ? " NOT INVERTED" : ""
                        w += dFail ? " CLOSED BACK" : ""
                        if i_ifvgNear
                            w += (bear ? (top + bot) / 2 < legM : (top + bot) / 2 > legM) ? " NOT DISC/PREM" : ""
                            w += top - bot < 0.15 * smtAtr ? " SMALL" : ""
                            w += not f_disp(m, top, bot) ? " WEAK CANDLE" : ""
                            w += dInv >= 0 and a - dInv > 20 ? " SLOW" : ""
                        w += i_ivMin and top - bot < i_ivMinP ? " < " + str.tostring(i_ivMinP) + " PTS" : ""
                        float dd = bear ? -(top + bot) / 2 : (top + bot) / 2
                        if na(whyD) or dd < whyD
                            whyD := dd
                            why := w == "" ? " OK" : w
                    if not na(top) and not na(bot) and top > bot and not used and (not i_ivMin or top - bot >= i_ivMinP)
                        int  inv  = -1
                        bool fail = false
                        for j = a to 0
                            float c = f_sb(sbC, j)
                            if inv < 0
                                if bear ? c < bot : c > top
                                    inv := j
                            else if bear ? c > top : c < bot
                                fail := true
                        bool near = not i_ifvgNear or (inv >= 0 and
                             (bear ? (top + bot) / 2 >= legM : (top + bot) / 2 <= legM) and
                             top - bot >= 0.15 * smtAtr and
                             f_disp(m, top, bot) and
                             a - inv <= 20)
                        if inv >= 0 and not fail and near
                            // pick the gap CLOSEST TO THE EXTREME (deepest premium / discount of the leg),
                            // not the one nearest to the current close
                            float d = bear ? -(top + bot) / 2 : (top + bot) / 2
                            if na(bestD) or d < bestD
                                bestD := d
                                bestT := top
                                bestB := bot
                                bestL := f_sb(sbT, m + 1)
                                bestR := f_sb(sbT, inv)
                                bestIa := inv
        // a NO from the filters is final: the IFVG is judged once, on the candle it inverts —
        // never later (a target / range that only fits many candles later = no IFVG)
        if ok and na(s.ivKey) and s.ivRej
            bestL := na
            bestT := na
            bestB := na
            why := s.ivWhy
        // LIQUIDITY: the high (low) must have swept a swing ($$$) — otherwise IFVG C (CISD) or nothing
        // + the extra filters (checkboxes): WITH DEALING RANGE · TARGET LIQUIDITY · NO OPPOSING FVG
        if ok and na(s.ivKey) and not na(bestL)
            string rej = ""
            [sw_, swt_, swn_] = f_sweptLiq(s.bear, s.xT)
            if i_ivLq
                if not na(sw_)
                    s.ivTag := "IFVG"
                else if i_ivCi and s.cisd
                    s.ivTag := "IFVG C"   // no liquidity sweep, but a CISD confirmed the turn
                else
                    rej := i_ivCi ? " NO $$$ (waiting CISD)" : " NO $$$"
            if rej == "" and i_ivDr and not na(ivDrH) and not na(ivDrL) and ivDrH > ivDrL
                float eqD = (ivDrH + ivDrL) / 2
                float mdG = (bestT + bestB) / 2
                if s.bear ? mdG < eqD : mdG > eqD
                    rej := s.bear ? " NOT IN DR PREM" : " NOT IN DR DISC"
            float tg_  = na
            int   tgt_ = na
            if rej == "" and (i_ivTgt or i_ivOpp)
                int a_ = 0
                while a_ + 1 < sbT.size() and f_sb(sbT, a_) > s.xT
                    a_ += 1
                float ext_  = s.bear ? f_sb(sbH, a_) : f_sb(sbL, a_)
                float stop_ = ext_   // stop beyond the high / low
                float ent_  = s.bear ? bestB : bestT
                float r_    = math.abs(ent_ - stop_)
                float r2_   = s.bear ? ent_ - 2 * r_ : ent_ + 2 * r_
                if i_ivTgt
                    [tq, tqt] = f_ivTarget(s.bear, a_, ent_)
                    if na(tq)
                        rej := " NO TARGET"
                    else if math.abs(tq - ent_) < 2 * r_
                        rej := " TARGET < 2R"
                    else
                        tg_  := tq
                        tgt_ := tqt
                        s.tgStop := ext_
                if rej == "" and i_ivOpp
                    rej := f_ivOpp(s.bear, ent_, r2_)
            if rej != ""
                bestL := na
                bestT := na
                bestB := na
                why := rej
            else
                s.swL := sw_
                s.swT := swt_
                s.swN := swn_
                s.tgL := tg_
                s.tgT := tgt_
        if i_ivDbg and ok and na(s.ivKey)
            string hd_ = s.cisd ? "CISD ✓" : "ARM"
            f_dbSet(s.dbl, na(bestL) ? hd_ + "\nIFVG ✗" + why : hd_ + "\nIFVG ✓")
        if na(bestL)
            f_ifvgFreeze(s)
        else
            int tR = time + 10 * timeframe.in_seconds() * 1000
            if not i_ifvg
                box.delete(s.ivBox)
                s.ivBox := na
            else if na(s.ivBox)
                s.ivBox := box.new(int(bestL), bestT, tR, bestB, xloc = xloc.bar_time, bgcolor = s.bear ? IV_BE : IV_BU, border_color = color.new(color.black, 100), text = s.ivTag, text_size = size.tiny, text_color = color.black, text_halign = text.align_right, text_valign = text.align_center)
            else
                s.ivBox.set_lefttop(int(bestL), bestT)
                s.ivBox.set_rightbottom(tR, bestB)
            if na(s.ivKey)
                // ── SOURCE: what price reversed from at the high / low ──
                int ai_ = 0
                while ai_ + 1 < sbT.size() and f_sb(sbT, ai_) > s.xT
                    ai_ += 1
                float ex_  = s.bear ? f_sb(sbH, ai_) : f_sb(sbL, ai_)
                float at_  = nz(smtAtr)
                s.srStop := ex_
                string sr_ = ""
                // 1. HTF gap (support for a bull IFVG / resistance for a bear one) the extreme traded into
                int bestSec = 0
                if hfBoxes.size() > 0
                    for i = 0 to hfBoxes.size() - 1
                        box hb = hfBoxes.get(i)
                        int d  = hfDirs.get(i)
                        bool inG = s.bear ? (d == -1 and ex_ >= hb.get_bottom() and ex_ <= hb.get_top() + 0.5 * at_) : (d == 1 and ex_ <= hb.get_top() and ex_ >= hb.get_bottom() - 0.5 * at_)
                        if inG and hfBorn.get(i) <= bar_index - ai_ and hfSec.get(i) > bestSec
                            bestSec := hfSec.get(i)
                            // only WHERE price turned: the wick of the reversal candle (from its body
                            // to the high / low), not the whole gap
                            float bO = f_sb(sbO, ai_)
                            float bC = f_sb(sbC, ai_)
                            float bE = s.bear ? math.max(bO, bC) : math.min(bO, bC)   // body edge
                            float hP = 0.08 * at_   // minimum thickness so it stays visible
                            s.srTop := s.bear ? ex_ : math.max(bE, ex_ + hP)
                            s.srBot := s.bear ? math.min(bE, ex_ - hP) : ex_
                            s.srNm  := f_secNm(hfSec.get(i)) + (hfInv.get(i) ? " IFVG" : " FVG")
                if bestSec > 0
                    sr_ := s.srNm
                    int fq = math.min(ai_ + 2, sbT.size() - 1)   // starts 2 candles before the high / low
                    s.srL := int(f_sb(sbT, fq))
                // 2. session / previous high-low swept (or tapped) by the extreme
                float  lvHit = na
                string lvNm  = ""
                if ivKP.size() > 0
                    int kTop = math.min(ai_ + 60, sbT.size() - 1)
                    for i = 0 to ivKP.size() - 1
                        float v = ivKP.get(i)
                        if not na(v) and ivKH.get(i) == s.bear
                            int  fb  = f_brk(s.bear, v, kTop + 1, ai_)
                            bool swp = (s.bear ? v < ex_ : v > ex_) and fb >= ai_ and fb - ai_ <= 15
                            bool tap = math.abs(ex_ - v) <= 0.1 * at_
                            if swp or tap
                                lvNm  := lvNm == "" ? ivKN.get(i) : f_join(lvNm, ivKN.get(i))
                                lvHit := v
                if lvNm != ""
                    sr_ := sr_ == "" ? lvNm : sr_ + " + " + lvNm
                // 4. SMT vs the correlated index at the swept swing → the extreme
                if i_ivSmt and not na(s.swL) and not na(s.swT)
                    int kS = -1
                    for q = ai_ + 1 to math.min(ai_ + 70, sbT.size() - 1)
                        if kS < 0 and f_sb(sbT, q) == s.swT
                            kS := q
                    if kS > ai_ and sbH2.size() > kS + 1
                        float c2Ex = na   // correlated extreme around our high / low (±1 candle)
                        float c2Sw = na   // correlated extreme around the swing (±1 candle)
                        for q = math.max(ai_ - 1, 0) to ai_ + 1
                            float v2 = s.bear ? f_sb(sbH2, q) : f_sb(sbL2, q)
                            c2Ex := na(c2Ex) ? v2 : s.bear ? math.max(c2Ex, v2) : math.min(c2Ex, v2)
                        for q = kS - 1 to kS + 1
                            float v2 = s.bear ? f_sb(sbH2, q) : f_sb(sbL2, q)
                            c2Sw := na(c2Sw) ? v2 : s.bear ? math.max(c2Sw, v2) : math.min(c2Sw, v2)
                        // chart took the swing, the correlated index did not
                        if not na(c2Ex) and not na(c2Sw) and (s.bear ? c2Ex < c2Sw : c2Ex > c2Sw)
                            s.smt := true
                            if i_ifvg
                                color cM = s.bear ? i_lBe : i_lBu
                                ivLqL.push(line.new(s.swT, s.swL, s.xT, ex_, xloc = xloc.bar_time, color = cM, style = line.style_solid, width = 2))
                                ivLqB.push(label.new(int((s.swT + s.xT) / 2), (s.swL + ex_) / 2, "SMT", xloc = xloc.bar_time, style = s.bear ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = cM, size = size.small))
                s.src := sr_
                if bestSec > 0 and i_ifvg
                    color cS = s.bear ? color.new(#F23645, 85) : color.new(#26A69A, 85)
                    srS.push(s)
                    srB.push(box.new(s.srL, s.srTop, time + 8 * timeframe.in_seconds() * 1000, s.srBot, xloc = xloc.bar_time, bgcolor = cS, border_color = color.new(cS, 40), text = s.srNm, text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_top, text_color = color.new(color.gray, 0)))
                    while srS.size() > 3
                        srS.shift()
                        box.delete(srB.shift())
                if s.std and i_alCiF
                    alert((s.bear ? "🔴" : "🟢") + " NEW " + s.ivTag + f_ivSrc(s) + " | " + SYM + " | " + TF, ALF)
                s.ivLockBar := bar_index
                // draw the liquidity this IFVG's high (low) swept: "$$$" from the swing to the extreme
                if i_ifvg
                    float swL = s.swL
                    int   swT = s.swT
                    if not na(swL) and not na(swT)
                        int tE = s.xT   // ends AT the candle that swept it
                        color cL = color.new(#2962FF, 0)
                        ivLqL.push(line.new(swT, swL, tE, swL, xloc = xloc.bar_time, color = cL, style = line.style_solid, width = 1))
                        ivLqB.push(label.new(int((swT + tE) / 2), swL, s.swN, xloc = xloc.bar_time, style = s.bear ? label.style_label_down : label.style_label_up, color = color.new(color.black, 100), textcolor = cL, size = size.small))
                    // TARGET LIQUIDITY 🎯: dotted line from the target swing to 10 candles past the IFVG
                    if not na(s.tgL) and not na(s.tgT)
                        int tE2 = time + 10 * timeframe.in_seconds() * 1000
                        color cT = color.new(#FF9800, 0)
                        tgS.push(s)
                        tgHB.push(na)
                        tgLn.push(line.new(s.tgT, s.tgL, tE2, s.tgL, xloc = xloc.bar_time, color = cT, style = line.style_dotted, width = 1))
                        tgLb.push(label.new(tE2, s.tgL, "🎯", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = cT, size = size.small))
                        while tgS.size() > 4
                            tgS.shift()
                            tgHB.shift()
                            line.delete(tgLn.shift())
                            label.delete(tgLb.shift())
                    while ivLqL.size() > 40
                        line.delete(ivLqL.shift())
                        label.delete(ivLqB.shift())
                s.ivR   := int(bestR)
                s.ivKey := bestL
                s.ivTop := bestT
                s.ivBot := bestB
                s.ivBar := bar_index
                s.ivHit := false
            // IFVG ALERT — NEAR: price moved away (more than 1 x ATR from the IFVG edge) and comes back
            // within 1 x ATR of it → once per IFVG, before it touches
            float nD = nz(smtAtr)
            if bar_index > s.ivBar and (s.bear ? low < bestB - nD : high > bestT + nD)
                s.ivArm := true
            if i_ifvg and i_alIfvg and s.ivArm and not s.ivHit and bar_index > s.ivBar and (s.bear ? high >= bestB - nD : low <= bestT + nD)
                s.ivHit := true
                alert((s.bear ? "🔴" : "🟢") + " NEAR " + s.ivTag + f_ivSrc(s) + " | " + SYM + " | " + TF, ALF)
    0
 
f_vis(Sig s, bool on) =>
    color clr = color.new(color.black, 100)
    color lc  = s.swept ? color.new(s.col, i_brkT)  : s.col
    color tc  = s.swept ? color.new(s.tcol, i_brkT) : s.tcol
    s.ln.set_style(s.swept ? f_style(i_brkSt) : f_style(i_st))
    s.ln.set_color(on ? lc : clr)
    s.lb.set_textcolor(on ? tc : clr)
    s.lb.set_color(on ? i_lbBg : clr)
    if not na(s.cdl)
        color cc = s.swept ? color.new(s.ccol, i_brkT) : s.ccol
        s.cdl.set_color(on ? cc : clr)
        s.cdb.set_textcolor(on ? cc : clr)
 
// ═══════════════════════════ CYCLE METHODS ═══════════════════════════
method draw(Cyc c, Sig s, bool bear, string txt) =>
    int    x1  = bear ? c.pHt : c.pLt
    float  y1  = bear ? c.pH  : c.pL
    int    x2  = bear ? c.cHt : c.cLt
    float  y2  = bear ? c.cH  : c.cL
    float  lvl = bear ? math.max(y1, y2) : math.min(y1, y2)
    color  lc  = bear ? i_cBe : i_cBu
    color  tc  = color.t(i_lbTx) >= 100 ? (bear ? i_lBe : i_lBu) : i_lbTx
    string t   = i_tag ? txt + " | " + TAG : txt
    int    lx  = i_lbPos == "Start" ? x1 : i_lbPos == "End" ? x2 : int((x1 + x2) / 2)
    float  ly  = i_lbPos == "Start" ? y1 : i_lbPos == "End" ? y2 : (y1 + y2) / 2
    string ls  = i_lbSty == "Up" ? label.style_label_up : i_lbSty == "Down" ? label.style_label_down : bear ? label.style_label_down : label.style_label_up
    float  cl  = bear ? c.cHo  : c.cLo
    int    clT = bear ? c.cHoT : c.cLoT
    Sig r = s
    if na(r)
        line  ln = line.new(x1 = x1, y1 = y1, x2 = x2, y2 = y2, xloc = xloc.bar_time, extend = extend.none, color = lc, style = f_style(i_st), width = i_w)
        label lb = label.new(x = lx, y = ly, text = t, xloc = xloc.bar_time, yloc = yloc.price, color = i_lbBg, style = ls, textcolor = tc, size = f_size(i_lbSz))
        r := Sig.new(ln = ln, lb = lb, lvl = lvl, bear = bear, col = lc, tcol = tc, cl = cl, clT = clT, xT = x2, atrAt = smtAtr)
    else
        r.ln.set_xy1(x1, y1)
        r.ln.set_xy2(x2, y2)
        r.lb.set_xy(lx, ly)
        r.lb.set_text(t)
        r.lvl := lvl
        if r.xT != x2   // new extreme → new CISD setup and a fresh IFVG search
            r.cDone := false
            r.ivKey := na
            r.ivEnd := false
            f_ifvgFreeze(r)
        r.cl  := cl
        r.clT := clT
        r.xT  := x2
    r
 
// newest valid SSMTs first; broken ones only when "Show Broken SSMTs" is on
method refresh(Cyc c) =>
    int n  = 0
    int sz = c.hist.size()
    if sz > 0
        for i = sz - 1 to 0
            Sig s = c.hist.get(i)
            f_vis(s, s.swept ? (i_showBrk and not s.won) : (i_maxN == 0 or n < i_maxN))
            n += s.swept ? 0 : 1
 
method confirm(Cyc c, Sig s) =>
    s.ct := time
    c.hist.push(s)
    c.nBe += s.bear ? 1 : 0
    c.nBu += s.bear ? 0 : 1
    c.wBe += s.bear and s.won ? 1 : 0
    c.wBu += not s.bear and s.won ? 1 : 0
    while c.hist.size() > 300
        f_kill(c.hist.shift())
    c.refresh()
 
method live(Cyc c, Sig s, string txt, bool bear) =>
    Sig r = s
    if txt != ""
        r := c.draw(r, bear, txt)
        if not r.al
            r.al := true
            if i_alert
                alert((bear ? "🔴" : "🟢") + " SMT | " + SYM + " | " + TF, ALF)
    else if not na(r)
        f_kill(r)
        r := na
    r
 
method divTxt(Cyc c, bool bear) =>
    string t = ""
    if bear
        bool mHH = c.cH > c.pH
        if has1 and not na(c.pH1) and not na(c.cH1) and (c.cH1 > c.pH1) != mHH
            t := n1
        if has2 and not na(c.pH2) and not na(c.cH2) and (c.cH2 > c.pH2) != mHH
            t := t == "" ? n2 : t + ", " + n2
    else
        bool mLL = c.cL < c.pL
        if has1 and not na(c.pL1) and not na(c.cL1) and (c.cL1 < c.pL1) != mLL
            t := n1
        if has2 and not na(c.pL2) and not na(c.cL2) and (c.cL2 < c.pL2) != mLL
            t := t == "" ? n2 : t + ", " + n2
    t
 
// a live (forming) SMT can already deliver before its quarter closes
f_trackLive(Sig s) =>
    if not na(s) and not s.won and (s.bear ? s.lvl - low : high - s.lvl) >= SMT_WIN_ATR * s.atrAt
        s.won := true
 
method sweep(Cyc c) =>
    bool changed = false
    for s in c.hist
        if not s.swept and (s.bear ? high > s.lvl : low < s.lvl)
            // broken: counts as a real break only if the SMT never delivered first
            s.swept := true
            f_ifvgFreeze(s)
            c.sBe   += s.bear and not s.won ? 1 : 0
            c.sBu   += not s.bear and not s.won ? 1 : 0
            changed := true
        else if not s.swept and not s.won and (s.bear ? s.lvl - low : high - s.lvl) >= SMT_WIN_ATR * s.atrAt
            c.wBe += s.bear ? 1 : 0
            c.wBu += s.bear ? 0 : 1
            s.won := true
    if changed
        c.refresh()
 
method step(Cyc c) =>
    if qNew
        if not na(c.bear)
            c.confirm(c.bear)
            c.bear := na
        if not na(c.bull)
            c.confirm(c.bull)
            c.bull := na
        c.pH  := c.cH
        c.pL  := c.cL
        c.pHt := c.cHt
        c.pLt := c.cLt
        c.pH1 := c.cH1
        c.pL1 := c.cL1
        c.pH2 := c.cH2
        c.pL2 := c.cL2
        c.cnt += 1
        c.cH  := high
        c.cL  := low
        c.cHt := time
        c.cLt := time
        c.cHo  := lUpO
        c.cHoT := lUpT
        c.cLo  := lDnO
        c.cLoT := lDnT
        c.cH1 := oh1
        c.cL1 := ol1
        c.cH2 := oh2
        c.cL2 := ol2
        if i_showDiv
            c.divs.push(line.new(x1 = time, y1 = low, x2 = time, y2 = high, xloc = xloc.bar_time, extend = extend.both, color = i_dC, style = f_style(i_dS), width = i_dW))
            while c.divs.size() > i_maxDiv
                line.delete(c.divs.shift())
    else if c.cnt > 0
        if high > c.cH
            c.cH   := high
            c.cHt  := time
            c.cHo  := lUpO
            c.cHoT := lUpT
        if low < c.cL
            c.cL   := low
            c.cLt  := time
            c.cLo  := lDnO
            c.cLoT := lDnT
        c.cH1 := f_mx(c.cH1, oh1)
        c.cL1 := f_mn(c.cL1, ol1)
        c.cH2 := f_mx(c.cH2, oh2)
        c.cL2 := f_mn(c.cL2, ol2)
    if c.cnt >= 3 and not na(c.pH)
        c.bear := c.live(c.bear, c.divTxt(true), true)
        c.bull := c.live(c.bull, c.divTxt(false), false)
    f_trackLive(c.bear)
    f_trackLive(c.bull)
    c.sweep()
 
// ═══════════════════════════ MAIN ═══════════════════════════
var Cyc cyc = Cyc.new(hist = array.new<Sig>(), divs = array.new<line>())
 
if active
    cyc.step()
 
// ═══════════════════════════ DASHBOARD STYLE (ICT FX PRO) ═══════════════════════════
color DB_FRAME = #2A2E39
color DB_BG    = #1E2433
color DB_LBL   = #B2B5BE
color DB_VAL   = #FFFFFF
color DB_TTL   = #FF9800
color DB_UPB   = #D1F5E0
color DB_UPT   = #22AB94
color DB_DNB   = #FFD6D9
color DB_DNT   = #F23645
color DB_NEB   = #E0E3EB
color DB_NET   = #9598A1
color DB_ORB   = #FFE9D0
color DB_ORT   = #FF7A00
string DB_NAME = "8 AM BREAKOUT"
 
int DB_FS = 8   // font size in points (compact for tablet)
f_db(table t, int c, int r, string txt, color tc, color bg) =>
    t.cell(c, r, txt, text_color = tc, bgcolor = bg, text_size = DB_FS, text_halign = text.align_center)
 
// ═══════════════════════════════════════════════════════════════════════
//  PORTED FROM MM IFVG v6.54 — display only, independent of the SMT logic
//  (Nearby Liquidity · Session Levels · Higher Timeframe FVGs). No alerts.
// ═══════════════════════════════════════════════════════════════════════
 
f_lstyle(string s) =>
    s == "----" ? line.style_dashed : s == "····" ? line.style_dotted : line.style_solid
 
f_szName(string s) =>
    s == "Large" ? size.large : s == "Medium" ? size.normal : s == "Small" ? size.small : size.tiny
 
f_tfName(simple string tf) =>
    tf == "1"   ? "1m"  : tf == "2"   ? "2m"  : tf == "3"   ? "3m"  :
     tf == "5"   ? "5m"  : tf == "10"  ? "10m" : tf == "15"  ? "15m" :
     tf == "30"  ? "30m" : tf == "45"  ? "45m" : tf == "60"  ? "1H"  :
     tf == "120" ? "2H"  : tf == "180" ? "3H"  : tf == "240" ? "4H"  :
     (tf == "D" or tf == "1D") ? "D" :
     (tf == "W" or tf == "1W") ? "W" :
     (tf == "M" or tf == "1M") ? "M" : tf
 
// Minutes-of-day window check, America/New_York (handles DST)
f_inWin(int s, int e) =>
    m = hour(time, "America/New_York") * 60 + minute(time, "America/New_York")
    m >= s and m < e
 
// Session H/L tracker: commits the completed session's extremes (+ the candle time of each)
f_sessLvls(bool inSess) =>
    var float runHi = na
    var float runLo = na
    var float comHi = na
    var float comLo = na
    var int   runHiT = na
    var int   runLoT = na
    var int   comHiT = na
    var int   comLoT = na
    if inSess and not inSess[1]
        runHi  := high
        runLo  := low
        runHiT := time
        runLoT := time
    else if inSess
        if na(runHi) or high > runHi
            runHi  := high
            runHiT := time
        if na(runLo) or low < runLo
            runLo  := low
            runLoT := time
    if not inSess and inSess[1]
        comHi  := runHi
        comLo  := runLo
        comHiT := runHiT
        comLoT := runLoT
    [comHi, comLo, comHiT, comLoT]
 
// Level state: sweep event + taken latch, one latch per call site (keep calls top-level)
f_lvlState(float lvl, bool isHigh) =>
    var bool taken = false
    if lvl != lvl[1]
        taken := false
    sw = false
    if not taken and not na(lvl)
        if isHigh ? high > lvl : low < lvl
            taken := true
            sw := true
    [sw, taken]
 
// ── Previous Day / Week / Month highs & lows (for the liquidity key-level tags) ──
[pdhR, pdlR, pdT, pdcR] = request.security(syminfo.tickerid, "D", [high[1], low[1], time[1], close[1]], lookahead=barmerge.lookahead_on)
[pwhR, pwlR, pwT, pwcR] = request.security(syminfo.tickerid, "W", [high[1], low[1], time[1], close[1]], lookahead=barmerge.lookahead_on)
float dAtr  = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
// "near" distance for hidden levels, scaled to the chart timeframe (1m sees a smaller window than 1H)
int   _cs   = timeframe.in_seconds()
float NEARK = _cs <= 60 ? 0.12 : _cs <= 180 ? 0.18 : _cs <= 300 ? 0.25 : _cs <= 900 ? 0.35 : 0.5
float NEARD = nz(dAtr, ta.atr(14) * 20) * NEARK
int   HF_MAXN = _cs <= 300 ? 2 : 3   // HTF gaps shown per side (above / below price) when SHOW ALL is off
f_isNear(float top, float bot) => i_showAll or (not na(top) and not na(bot) and (close >= bot - NEARD and close <= top + NEARD))
// NEAR LEVEL ALERT for a single level (one latch per call site)
f_nearAl(float lvl, bool on, string tag) =>
    var bool armed = true
    if not na(lvl)
        float d = math.abs(close - lvl)
        if d > 2 * NEARD
            armed := true
        else if armed and d <= NEARD
            armed := false
            if on and i_alNear
                alert("🔔 NEAR " + tag + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
    0
[pmhR, pmlR, pmT, pmcR] = request.security(syminfo.tickerid, "M", [high[1], low[1], time[1], close[1]], lookahead=barmerge.lookahead_on)
 
int _chartSec = timeframe.in_seconds(timeframe.period)
float pdh = _chartSec < 86400   ? pdhR : na
float pdl = _chartSec < 86400   ? pdlR : na
float pwh = _chartSec < 604800  ? pwhR : na
float pwl = _chartSec < 604800  ? pwlR : na
float pmh = _chartSec < 2592000 ? pmhR : na
float pml = _chartSec < 2592000 ? pmlR : na
float pdc = _chartSec < 86400   ? pdcR : na
float pwc = _chartSec < 604800  ? pwcR : na
float pmc = _chartSec < 2592000 ? pmcR : na
 
bool klNewD = nz(ta.change(time("D")), 0) != 0
 
// ═══ SESSION HIGH / LOW LINES ═══
bool inAsia = f_inWin(1200, 1440)   // 20:00 – 00:00 ET
bool inLon  = f_inWin(120, 300)     //  2:00 – 05:00 ET
bool inNY   = f_inWin(570, 960)     //  9:30 – 16:00 ET
 
[asiaH, asiaL, asiaHT, asiaLT] = f_sessLvls(inAsia)
[lonH,  lonL,  lonHT,  lonLT]  = f_sessLvls(inLon)
[nyH,   nyL,   nyHT,   nyLT]   = f_sessLvls(inNY)
 
[swAsH, tkAsH] = f_lvlState(asiaH, true)
[swAsL, tkAsL] = f_lvlState(asiaL, false)
[swLoH, tkLoH] = f_lvlState(lonH,  true)
[swLoL, tkLoL] = f_lvlState(lonL,  false)
[swNyH, tkNyH] = f_lvlState(nyH,   true)
[swNyL, tkNyL] = f_lvlState(nyL,   false)
 
int LVL_BARS = 70   // session & open lines: reach at least 70 candles ahead from where they start, then follow price
 
var int sesDayT = na
if klNewD or na(sesDayT)
    sesDayT := time
// SESSION SWEPT ALERT: one per level, only for today's session levels (since the 18:00 ET roll)
f_sesAlert(bool sw, int t0, string tag, bool isHigh) =>
    if i_alSes and sw and not na(t0) and t0 >= sesDayT
        alert((isHigh ? "🔴 " : "🟢 ") + tag + " SWEPT | " + SYM + " | " + TF, ALF)
    0
f_sesAlert(swAsH, asiaHT, "ASIA H", true)
f_sesAlert(swAsL, asiaLT, "ASIA L", false)
f_sesAlert(swLoH, lonHT,  "LDN H",  true)
f_sesAlert(swLoL, lonLT,  "LDN L",  false)
f_sesAlert(swNyH, nyHT,   "NY H",   true)
f_sesAlert(swNyL, nyLT,   "NY L",   false)
 
var array<line>  sesLines = array.new<line>()
var array<label> sesLbls  = array.new<label>()
var array<float> sesLv    = array.new<float>()   // drawn session levels (same index as sesLbls) — liquidity merges into these
var array<bool>  sesHi    = array.new<bool>()
f_sesDraw(float lvl, int t0, bool taken, bool on, string tag, color col, int w) =>
    if on and not na(lvl) and not na(t0) and t0 >= sesDayT
        int tR = math.max(t0 + LVL_BARS * timeframe.in_seconds() * 1000, time + timeframe.in_seconds() * 1000)   // at least 70 candles, then follows price
        sesLines.push(line.new(t0, lvl, tR, lvl, xloc=xloc.bar_time, color=col, width=w, style=f_lstyle(sesSty)))
        sesLbls.push(label.new(tR, lvl, tag + (taken ? " ✓" : ""), xloc=xloc.bar_time, style=label.style_label_left, color=#ffffff00, textcolor=col, size=f_szName(sesLblSz)))
        sesLv.push(lvl)
        sesHi.push(str.endswith(tag, "H"))
    0
if barstate.islast
    while sesLines.size() > 0
        line.delete(sesLines.pop())
    while sesLbls.size() > 0
        label.delete(sesLbls.pop())
    sesLv.clear()
    sesHi.clear()
    f_sesDraw(asiaH, asiaHT, tkAsH, sesAsOn, "ASIA H", sesAsCol, sesAsW)
    f_sesDraw(asiaL, asiaLT, tkAsL, sesAsOn, "ASIA L", sesAsCol, sesAsW)
    f_sesDraw(lonH,  lonHT,  tkLoH, sesLoOn, "LDN H",  sesLoCol, sesLoW)
    f_sesDraw(lonL,  lonLT,  tkLoL, sesLoOn, "LDN L",  sesLoCol, sesLoW)
    f_sesDraw(nyH,   nyHT,   tkNyH, sesNyOn, "NY H",   sesNyCol, sesNyW)
    f_sesDraw(nyL,   nyLT,   tkNyL, sesNyOn, "NY L",   sesNyCol, sesNyW)
 
// ═══ HIGHER TIMEFRAME FVGs ═══
color HF_NONE = #ffffff00
 
f_hfTf(simple string sel) =>
    sel == '15m' ? '15' : sel == '30m' ? '30' : sel == '1H' ? '60' : sel == '4H' ? '240' : sel == 'W' ? 'W' : '1D'
 
simple string hf1Tf = f_hfTf(hf1Sel)
simple string hf2Tf = f_hfTf(hf2Sel)
simple string hf3Tf = f_hfTf(hf3Sel)
simple string hf4Tf = f_hfTf(hf4Sel)
simple string hf5Tf = f_hfTf(hf5Sel)
 
// Confirmed: last CLOSED HTF bar via [1] + lookahead_on, fired when the HTF bar's time changes.
[hf1_bull, hf1_bT, hf1_bB, hf1_bear, hf1_sT, hf1_sB, hf1_t, hf1_c] = request.security(syminfo.tickerid, hf1Tf, [low[1] > high[3] and close[2] > open[2], low[1], high[3], high[1] < low[3] and close[2] < open[2], low[3], high[1], time[1], close[1]], lookahead = barmerge.lookahead_on)
[hf2_bull, hf2_bT, hf2_bB, hf2_bear, hf2_sT, hf2_sB, hf2_t, hf2_c] = request.security(syminfo.tickerid, hf2Tf, [low[1] > high[3] and close[2] > open[2], low[1], high[3], high[1] < low[3] and close[2] < open[2], low[3], high[1], time[1], close[1]], lookahead = barmerge.lookahead_on)
 
bool hf1New = not na(hf1_t) and hf1_t != nz(hf1_t[1], -1)
bool hf2New = not na(hf2_t) and hf2_t != nz(hf2_t[1], -1)
[hf3_bull, hf3_bT, hf3_bB, hf3_bear, hf3_sT, hf3_sB, hf3_t, hf3_c] = request.security(syminfo.tickerid, hf3Tf, [low[1] > high[3] and close[2] > open[2], low[1], high[3], high[1] < low[3] and close[2] < open[2], low[3], high[1], time[1], close[1]], lookahead = barmerge.lookahead_on)
bool hf3New = not na(hf3_t) and hf3_t != nz(hf3_t[1], -1)
 
// Forming: the DEVELOPING HTF candle as c3, plus its open/close time and HTF ATR.
[hf1f_bull, hf1f_bT, hf1f_bB, hf1f_bear, hf1f_sT, hf1f_sB, hf1f_t2, hf1f_tO, hf1f_tC, hf1f_atr] = request.security(syminfo.tickerid, hf1Tf, [low > high[2] and close[1] > open[1], low, high[2], high < low[2] and close[1] < open[1], low[2], high, time[2], time, time_close, ta.atr(14)], lookahead = barmerge.lookahead_off)
[hf2f_bull, hf2f_bT, hf2f_bB, hf2f_bear, hf2f_sT, hf2f_sB, hf2f_t2, hf2f_tO, hf2f_tC, hf2f_atr] = request.security(syminfo.tickerid, hf2Tf, [low > high[2] and close[1] > open[1], low, high[2], high < low[2] and close[1] < open[1], low[2], high, time[2], time, time_close, ta.atr(14)], lookahead = barmerge.lookahead_off)
bool newHf1Bull = hf1New and hf1_bull
bool newHf1Bear = hf1New and hf1_bear
bool newHf2Bull = hf2New and hf2_bull
bool newHf2Bear = hf2New and hf2_bear
[hf3f_bull, hf3f_bT, hf3f_bB, hf3f_bear, hf3f_sT, hf3f_sB, hf3f_t2, hf3f_tO, hf3f_tC, hf3f_atr] = request.security(syminfo.tickerid, hf3Tf, [low > high[2] and close[1] > open[1], low, high[2], high < low[2] and close[1] < open[1], low[2], high, time[2], time, time_close, ta.atr(14)], lookahead = barmerge.lookahead_off)
bool newHf3Bull = hf3New and hf3_bull
bool newHf3Bear = hf3New and hf3_bear
[hf4_bull, hf4_bT, hf4_bB, hf4_bear, hf4_sT, hf4_sB, hf4_t, hf4_c] = request.security(syminfo.tickerid, hf4Tf, [low[1] > high[3] and close[2] > open[2], low[1], high[3], high[1] < low[3] and close[2] < open[2], low[3], high[1], time[1], close[1]], lookahead = barmerge.lookahead_on)
bool hf4New = not na(hf4_t) and hf4_t != nz(hf4_t[1], -1)
[hf4f_bull, hf4f_bT, hf4f_bB, hf4f_bear, hf4f_sT, hf4f_sB, hf4f_t2, hf4f_tO, hf4f_tC, hf4f_atr] = request.security(syminfo.tickerid, hf4Tf, [low > high[2] and close[1] > open[1], low, high[2], high < low[2] and close[1] < open[1], low[2], high, time[2], time, time_close, ta.atr(14)], lookahead = barmerge.lookahead_off)
bool newHf4Bull = hf4New and hf4_bull
bool newHf4Bear = hf4New and hf4_bear
[hf5_bull, hf5_bT, hf5_bB, hf5_bear, hf5_sT, hf5_sB, hf5_t, hf5_c] = request.security(syminfo.tickerid, hf5Tf, [low[1] > high[3] and close[2] > open[2], low[1], high[3], high[1] < low[3] and close[2] < open[2], low[3], high[1], time[1], close[1]], lookahead = barmerge.lookahead_on)
bool hf5New = not na(hf5_t) and hf5_t != nz(hf5_t[1], -1)
[hf5f_bull, hf5f_bT, hf5f_bB, hf5f_bear, hf5f_sT, hf5f_sB, hf5f_t2, hf5f_tO, hf5f_tC, hf5f_atr] = request.security(syminfo.tickerid, hf5Tf, [low > high[2] and close[1] > open[1], low, high[2], high < low[2] and close[1] < open[1], low[2], high, time[2], time, time_close, ta.atr(14)], lookahead = barmerge.lookahead_off)
bool newHf5Bull = hf5New and hf5_bull
bool newHf5Bear = hf5New and hf5_bear
 
 
int HF_CAP = 40   // per-slot budget
 
f_hfLeft(simple string tf) =>
    int bpH = math.max(1, int(timeframe.in_seconds(tf) / timeframe.in_seconds(timeframe.period)))
    math.max(math.max(0, bar_index - MAX_BACK), bar_index - 3 * bpH)
 
// Overlapping HTF gaps: the higher timeframe owns the level, the lower one comes off.
f_hfOverlap(float t1, float b1, float t2, float b2) =>
    t1 > b2 and t2 > b1
 
f_hfRemove(int i) =>
    box.delete(hfBoxes.get(i))
    box _b = hfBoxes.remove(i)
    int _d = hfDirs.remove(i)
    int _s = hfSlot.remove(i)
    int _c = hfSec.remove(i)
    bool _v = hfInv.remove(i)
    bool _h = hfHit.remove(i)
    int  _n = hfBorn.remove(i)
    bool _p = hfPdOk.remove(i)
    bool _q = hfNr.remove(i)
    0
 
f_secName(int s) =>
    s >= 604800 ? "W" : s >= 86400 ? "1D" : s >= 14400 ? "4H" : s >= 3600 ? "1H" : s >= 1800 ? "30m" : "15m"
 
f_hfAdd(float top, float bot, int dir, int slot, int sec, simple string tf, color col) =>
    if not na(top) and not na(bot) and top > bot
        // overlapping gaps of different timeframes are ALL kept (each lives until it is filled);
        // CLEAN CHART draws them as one box with the higher timeframe first
        hfBoxes.push(box.new(f_hfLeft(tf), top, bar_index, bot, xloc = xloc.bar_index, bgcolor = col, border_color = HF_NONE, text = (dir == 1 ? "BULL " : "BEAR ") + (tf == "1D" ? "1D" : f_tfName(tf)), text_size = size.tiny, text_halign = text.align_right, text_color = hfTxtCol))
        hfDirs.push(dir)
        hfSlot.push(slot)
        hfSec.push(sec)
        hfInv.push(false)
        hfHit.push(false)
        hfBorn.push(bar_index)
        hfPdOk.push(true)
        hfNr.push(false)
        int cnt = 0
        for i = 0 to hfSlot.size() - 1
            if hfSlot.get(i) == slot
                cnt += 1
        if cnt > HF_CAP
            for i = 0 to hfSlot.size() - 1
                if hfSlot.get(i) == slot
                    f_hfRemove(i)
                    break
 
int hf1Sec = timeframe.in_seconds(hf1Tf)
int hf2Sec = timeframe.in_seconds(hf2Tf)
bool hf1On = useHf1 and hf1Sec > timeframe.in_seconds()
int hf3Sec = timeframe.in_seconds(hf3Tf)
bool hf2On = useHf2 and hf2Sec > timeframe.in_seconds() and not (hf1On and hf2Tf == hf1Tf)
bool hf3On = useHf3 and hf3Sec > timeframe.in_seconds() and not (hf1On and hf3Tf == hf1Tf) and not (hf2On and hf3Tf == hf2Tf)
int hf4Sec = timeframe.in_seconds(hf4Tf)
bool hf4On = useHf4 and hf4Sec > timeframe.in_seconds() and not (hf1On and hf4Tf == hf1Tf) and not (hf2On and hf4Tf == hf2Tf) and not (hf3On and hf4Tf == hf3Tf)
int hf5Sec = timeframe.in_seconds(hf5Tf)
bool hf5On = useHf5 and hf5Sec > timeframe.in_seconds() and not (hf1On and hf5Tf == hf1Tf) and not (hf2On and hf5Tf == hf2Tf) and not (hf3On and hf5Tf == hf3Tf) and not (hf4On and hf5Tf == hf4Tf)
 
f_doSlot(int k) =>
    if k == 1 and hf1On
        if newHf1Bull
            f_hfAdd(hf1_bT, hf1_bB, 1, 1, hf1Sec, hf1Tf, hf1Bull)
        if newHf1Bear
            f_hfAdd(hf1_sT, hf1_sB, -1, 1, hf1Sec, hf1Tf, hf1Bear)
    if k == 2 and hf2On
        if newHf2Bull
            f_hfAdd(hf2_bT, hf2_bB, 1, 2, hf2Sec, hf2Tf, hf2Bull)
        if newHf2Bear
            f_hfAdd(hf2_sT, hf2_sB, -1, 2, hf2Sec, hf2Tf, hf2Bear)
    if k == 3 and hf3On
        if newHf3Bull
            f_hfAdd(hf3_bT, hf3_bB, 1, 3, hf3Sec, hf3Tf, hf3Bull)
        if newHf3Bear
            f_hfAdd(hf3_sT, hf3_sB, -1, 3, hf3Sec, hf3Tf, hf3Bear)
    if k == 4 and hf4On
        if newHf4Bull
            f_hfAdd(hf4_bT, hf4_bB, 1, 4, hf4Sec, hf4Tf, hf4Bull)
        if newHf4Bear
            f_hfAdd(hf4_sT, hf4_sB, -1, 4, hf4Sec, hf4Tf, hf4Bear)
    if k == 5 and hf5On
        if newHf5Bull
            f_hfAdd(hf5_bT, hf5_bB, 1, 5, hf5Sec, hf5Tf, hf5Bull)
        if newHf5Bear
            f_hfAdd(hf5_sT, hf5_sB, -1, 5, hf5Sec, hf5Tf, hf5Bear)
    0
 
// Higher TF first within the bar, so it takes the level before a lower TF can claim it.
array<int>  hfOrdSec  = array.from(hf1Sec, hf2Sec, hf3Sec, hf4Sec, hf5Sec)
array<bool> hfOrdDone = array.new<bool>(5, false)
for _r = 0 to 4
    int pick = -1
    for _k = 0 to 4
        if not hfOrdDone.get(_k) and (pick < 0 or hfOrdSec.get(_k) > hfOrdSec.get(pick))
            pick := _k
    hfOrdDone.set(pick, true)
    f_doSlot(pick + 1)
 
// Extend to the current bar.
// FVG : confirmed CLOSE through the far side → inverts into an IFVG (if enabled);
//       otherwise removed once fully filled (wick through), as before.
// IFVG: removed on a confirmed close back through its other side.
var int hfTapBuT = na   // last candle that traded into a BULL FVG / IFVG (CISD liquidity condition)
var int hfTapBeT = na   // last candle that traded into a BEAR FVG / IFVG
if hfBoxes.size() > 0
    for i = hfBoxes.size() - 1 to 0
        box hb = hfBoxes.get(i)
        box.set_right(hb, i_hfShort ? bar_index + 8 : bar_index)
        if i_hfShort
            box.set_left(hb, bar_index - 8)
        int   hd  = hfDirs.get(i)
        float hTp = box.get_top(hb)
        float hBt = box.get_bottom(hb)
        // FVG / IFVG of a timeframe are judged on THAT timeframe's candle close (not the chart's),
        // checked when its candle has just closed
        int   slc       = hfSlot.get(i)
        bool  tfNew     = slc == 1 ? hf1New : slc == 2 ? hf2New : slc == 3 ? hf3New : slc == 4 ? hf4New : hf5New
        float tfC       = slc == 1 ? hf1_c : slc == 2 ? hf2_c : slc == 3 ? hf3_c : slc == 4 ? hf4_c : hf5_c
        bool  closeThru = tfNew and bar_index > hfBorn.get(i) and not na(tfC) and (hd == 1 ? tfC < hBt : tfC > hTp)
        bool  wasInv    = hfInv.get(i)
        int   sl        = hfSlot.get(i)   // 1 = 1H, 2 = 4H, 3 = 1D
        bool  slIfvg    = sl == 1 ? i_if1h : sl == 2 ? i_if4h : sl == 3 ? i_if1d : sl == 4 ? i_if4 : i_if5
        bool  doInv     = not wasInv and hfIfvg and slIfvg and closeThru
        // a plain FVG with IFVG on waits for its timeframe's close (wick through + close back = still valid);
        // with IFVG off it is removed once fully filled (wick through), as before
        bool  kill      = wasInv ? closeThru : (not doInv and not (hfIfvg and slIfvg) and ((hd == 1 and low <= hBt) or (hd == -1 and high >= hTp)))
        // NEAR LEVEL ALERT for HTF gaps (once; re-armed when price is 2x the near distance away)
        float hDist = close > hTp ? close - hTp : close < hBt ? hBt - close : 0.0
        if hDist > 2 * NEARD
            hfNr.set(i, false)
        else if not hfNr.get(i) and hDist <= NEARD and bar_index > hfBorn.get(i)
            hfNr.set(i, true)
            if i_alNear and (not i_hfPd or hfPdOk.get(i))
                alert("🔔 NEAR " + f_secName(hfSec.get(i)) + (hfInv.get(i) ? " IFVG" : " FVG") + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
        // FVG ALERT: first time price trades into the box (not on the bar it was drawn / inverted)
        bool  touch     = not doInv and not hfHit.get(i) and bar_index > hfBorn.get(i) and (hd == 1 ? low <= hTp : high >= hBt)
        if touch   // first entry into this box = liquidity for the CISD (counted once per box)
            hfTapBuT := hd == 1 ? time : hfTapBuT
            hfTapBeT := hd == -1 ? time : hfTapBeT
            hfHit.set(i, true)
            if i_alFvg and (not i_hfPd or hfPdOk.get(i))
                alert((hd == 1 ? "🟢 " : "🔴 ") + (wasInv ? "IFVG " : "FVG ") + f_secName(hfSec.get(i)) + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
        if doInv
            int nd = -hd
            hfInv.set(i, true)
            hfDirs.set(i, nd)
            hfHit.set(i, false)
            hfBorn.set(i, bar_index)
            box.set_bgcolor(hb, nd == 1 ? hfIfBu : hfIfBe)
            box.set_border_color(hb, color.new(nd == 1 ? hfIfBu : hfIfBe, 30))
            box.set_border_style(hb, line.style_dashed)
            box.set_text(hb, (nd == 1 ? "BULL IFVG " : "BEAR IFVG ") + f_secName(hfSec.get(i)))
        if kill
            f_hfRemove(i)
 
// Forming HTF FVG boxes (live only, last part of the HTF candle, size-filtered)
var box hfP1b = na
var box hfP1s = na
var box hfP2b = na
var box hfP2s = na
var box hfP3b = na
var box hfP3s = na
var box hfP4b = na
var box hfP4s = na
var box hfP5b = na
var box hfP5s = na
f_hfLate(int tO, int tC) =>
    bool ok = false
    if not na(tO) and not na(tC) and tC > tO
        ok := (timenow - tO) >= (tC - tO) * (1.0 - hfFormPct / 100.0)
    ok
f_hfPend(box old, bool on, float top, float bot, int tL, float hAtr, int dir, simple string tf, color col) =>
    box.delete(old)
    box nb = na
    if on and not na(top) and not na(bot) and top > bot and not na(tL) and (hfFormMin <= 0 or na(hAtr) or top - bot >= hfFormMin * hAtr)
        nb := box.new(tL, top, time + timeframe.in_seconds() * 1000, bot, xloc = xloc.bar_time,
             bgcolor = color.new(col, math.min(100, color.t(col) + 12)),
             border_color = color.new(hfTxtCol, 40), border_style = line.style_dashed, border_width = 1,
             text = (dir == 1 ? "BULL " : "BEAR ") + (tf == "1D" ? "1D" : f_tfName(tf)) + " · forming",
             text_size = size.tiny, text_halign = text.align_right, text_color = hfTxtCol)
    nb
if barstate.islast
    bool late1 = hfForm and hf1On and barstate.isrealtime and f_hfLate(hf1f_tO, hf1f_tC)
    bool late2 = hfForm and hf2On and barstate.isrealtime and f_hfLate(hf2f_tO, hf2f_tC)
    hfP1b := f_hfPend(hfP1b, late1 and hf1f_bull, hf1f_bT, hf1f_bB, hf1f_t2, hf1f_atr,  1, hf1Tf, hf1Bull)
    hfP1s := f_hfPend(hfP1s, late1 and hf1f_bear, hf1f_sT, hf1f_sB, hf1f_t2, hf1f_atr, -1, hf1Tf, hf1Bear)
    hfP2b := f_hfPend(hfP2b, late2 and hf2f_bull, hf2f_bT, hf2f_bB, hf2f_t2, hf2f_atr,  1, hf2Tf, hf2Bull)
    hfP2s := f_hfPend(hfP2s, late2 and hf2f_bear, hf2f_sT, hf2f_sB, hf2f_t2, hf2f_atr, -1, hf2Tf, hf2Bear)
    bool late3 = hfForm and hf3On and barstate.isrealtime and f_hfLate(hf3f_tO, hf3f_tC)
    hfP3b := f_hfPend(hfP3b, late3 and hf3f_bull, hf3f_bT, hf3f_bB, hf3f_t2, hf3f_atr,  1, hf3Tf, hf3Bull)
    hfP3s := f_hfPend(hfP3s, late3 and hf3f_bear, hf3f_sT, hf3f_sB, hf3f_t2, hf3f_atr, -1, hf3Tf, hf3Bear)
    bool late4 = hfForm and hf4On and barstate.isrealtime and f_hfLate(hf4f_tO, hf4f_tC)
    hfP4b := f_hfPend(hfP4b, late4 and hf4f_bull, hf4f_bT, hf4f_bB, hf4f_t2, hf4f_atr,  1, hf4Tf, hf4Bull)
    hfP4s := f_hfPend(hfP4s, late4 and hf4f_bear, hf4f_sT, hf4f_sB, hf4f_t2, hf4f_atr, -1, hf4Tf, hf4Bear)
    bool late5 = hfForm and hf5On and barstate.isrealtime and f_hfLate(hf5f_tO, hf5f_tC)
    hfP5b := f_hfPend(hfP5b, late5 and hf5f_bull, hf5f_bT, hf5f_bB, hf5f_t2, hf5f_atr,  1, hf5Tf, hf5Bull)
    hfP5s := f_hfPend(hfP5s, late5 and hf5f_bear, hf5f_sT, hf5f_sB, hf5f_t2, hf5f_atr, -1, hf5Tf, hf5Bear)
 
// ═══ NEARBY LIQUIDITY: nearest untaken MAJOR pool above (BSL) and below (SSL) ═══
int LIQ_MAJOR = lqMajLen
 
var array<float> lqHiLvl = array.new<float>()
var array<int>   lqHiT   = array.new<int>()
var array<int>   lqHiN   = array.new<int>()
var array<bool>  lqHiMaj = array.new<bool>()
var array<float> lqLoLvl = array.new<float>()
var array<int>   lqLoT   = array.new<int>()
var array<int>   lqLoN   = array.new<int>()
var array<bool>  lqLoMaj = array.new<bool>()
var array<line>  lqLines = array.new<line>()
var array<label> lqLbls  = array.new<label>()
 
color LQ_NONE = #ffffff00
 
float lqAtr    = ta.atr(200)
float lqTol    = nz(lqAtr, syminfo.mintick * 40) / 4
float lqKeyTol = nz(lqAtr, syminfo.mintick * 40) / 12
 
float lqPhMaj = ta.pivothigh(high, LIQ_MAJOR, LIQ_MAJOR)
float lqPlMaj = ta.pivotlow(low,  LIQ_MAJOR, LIQ_MAJOR)
 
// Merge a confirmed swing into the pool (equal highs/lows become one pool at the extreme wick)
f_lqAdd(bool isHigh, float lvl, int t0, bool isMaj) =>
    array<float> lvls = isHigh ? lqHiLvl : lqLoLvl
    array<int>   ts   = isHigh ? lqHiT   : lqLoT
    array<int>   ns   = isHigh ? lqHiN   : lqLoN
    array<bool>  mjs  = isHigh ? lqHiMaj : lqLoMaj
    int hit = -1
    if lvls.size() > 0
        for i = 0 to lvls.size() - 1
            if math.abs(lvls.get(i) - lvl) <= lqTol
                hit := i
                break
    if hit >= 0
        lvls.set(hit, isHigh ? math.max(lvls.get(hit), lvl) : math.min(lvls.get(hit), lvl))
        ns.set(hit, ns.get(hit) + 1)
        mjs.set(hit, mjs.get(hit) or isMaj)
    else
        lvls.push(lvl)
        ts.push(t0)
        ns.push(1)
        mjs.push(isMaj)
        if lvls.size() > 30
            float _c1 = lvls.shift()
            int   _c2 = ts.shift()
            int   _c3 = ns.shift()
            bool  _c4 = mjs.shift()
    hit
 
// taken pools: kept as a faded "✓" trace (pool start → take candle) until the market day rolls (18:00 ET)
var array<float> lqTkLvl = array.new<float>()
var array<int>   lqTkT0  = array.new<int>()
var array<int>   lqTkT1  = array.new<int>()
var array<bool>  lqTkHi  = array.new<bool>()
// Only the LAST taken pool of each side stays: if price reversed from it, it stays where it is;
// if price broke on to the next pool, the older one is removed (one at a time, not all at once).
f_lqTaken(bool isHigh, float lvl, int t0) =>
    bool add = true
    if lqTkLvl.size() > 0
        for i = lqTkLvl.size() - 1 to 0
            if lqTkHi.get(i) == isHigh
                // older trace of this side, or a less extreme one taken on this same candle → out
                if lqTkT1.get(i) < time or (isHigh ? lvl > lqTkLvl.get(i) : lvl < lqTkLvl.get(i))
                    float _r1 = lqTkLvl.remove(i)
                    int   _r2 = lqTkT0.remove(i)
                    int   _r3 = lqTkT1.remove(i)
                    bool  _r4 = lqTkHi.remove(i)
                else
                    add := false
    if add
        lqTkLvl.push(lvl)
        lqTkT0.push(t0)
        lqTkT1.push(time)
        lqTkHi.push(isHigh)
    // LIQUIDITY SWEEP ALERT: only a SWEEP (wick through, candle CLOSES back) — a close through is ignored
    if i_alLq and barstate.isconfirmed and (isHigh ? close < lvl : close > lvl)
        alert((isHigh ? "🔴 BSL" : "🟢 SSL") + " SWEEP | " + SYM + " | " + TF, alert.freq_once_per_bar_close)
    0
 
bool lqAnyOn = lqBMajOn or lqSMajOn
var int lqSwHiT = na   // last time a BSL pool was taken
var int lqSwLoT = na   // last time a SSL pool was taken
if lqAnyOn
    if not na(lqPhMaj)
        f_lqAdd(true, lqPhMaj, time[LIQ_MAJOR], true)
    if not na(lqPlMaj)
        f_lqAdd(false, lqPlMaj, time[LIQ_MAJOR], true)
    // a trade through the level spends it (remembered for the CISD liquidity condition)
    if lqHiLvl.size() > 0
        for i = lqHiLvl.size() - 1 to 0
            if high > lqHiLvl.get(i)
                lqSwHiT := time
                f_lqTaken(true, lqHiLvl.get(i), lqHiT.get(i))
                float _s1 = lqHiLvl.remove(i)
                int   _s2 = lqHiT.remove(i)
                int   _s3 = lqHiN.remove(i)
                bool  _s4 = lqHiMaj.remove(i)
    if lqLoLvl.size() > 0
        for i = lqLoLvl.size() - 1 to 0
            if low < lqLoLvl.get(i)
                lqSwLoT := time
                f_lqTaken(false, lqLoLvl.get(i), lqLoT.get(i))
                float _s5 = lqLoLvl.remove(i)
                int   _s6 = lqLoT.remove(i)
                int   _s7 = lqLoN.remove(i)
                bool  _s8 = lqLoMaj.remove(i)
 
f_lqKeyTag(float lvl, bool isHigh) =>
    string k = ""
    if not na(lvl)
        float d = isHigh ? pdh : pdl
        float w = isHigh ? pwh : pwl
        float m = isHigh ? pmh : pml
        if not na(d) and math.abs(lvl - d) <= lqKeyTol
            k := isHigh ? "PDH" : "PDL"
        if not na(w) and math.abs(lvl - w) <= lqKeyTol
            k := isHigh ? "PWH" : "PWL"
        if not na(m) and math.abs(lvl - m) <= lqKeyTol
            k := isHigh ? "PMH" : "PML"
    k
 
// When the pool sits on a drawn session high / low (same side, within ATR(200)/12), no second line:
// the session line carries both names, e.g. "LDN L + SSL".
f_lqDraw(float lvl, int t0, int n, bool isHigh, bool isMaj, color lc, string sty) =>
    if not na(lvl)
        string tag = lqShort ? (isHigh ? "BSL" : "SSL") : (isMaj ? "Major " : "Minor ") + (isHigh ? "BSL" : "SSL")
        string kt  = lqKeyTagOn ? f_lqKeyTag(lvl, isHigh) : ""
        tag := kt == "" ? tag : tag + " · " + kt
        int m = -1
        if sesLv.size() > 0
            for i = 0 to sesLv.size() - 1
                if sesHi.get(i) == isHigh and math.abs(sesLv.get(i) - lvl) <= lqKeyTol
                    m := i
                    break
        if m >= 0
            label sl = sesLbls.get(m)
            sl.set_text(sl.get_text() + " + " + tag)
        else
            lqLines.push(line.new(t0, lvl, time, lvl, xloc=xloc.bar_time, color=lc, width=lqThick and n >= 2 ? 2 : 1, style=f_lstyle(sty)))
            lqLbls.push(label.new(time + timeframe.in_seconds() * 1000, lvl, tag, xloc=xloc.bar_time, style=label.style_label_left, size=f_szName(lqLblSz), color=LQ_NONE, textcolor=lc))
 
// drop traces from before today's market day
while lqTkT1.size() > 0 and lqTkT1.first() < sesDayT
    float _t1 = lqTkLvl.shift()
    int   _t2 = lqTkT0.shift()
    int   _t3 = lqTkT1.shift()
    bool  _t4 = lqTkHi.shift()
var array<line>  lqTkLn = array.new<line>()
var array<label> lqTkLb = array.new<label>()
if barstate.islast
    while lqLines.size() > 0
        line.delete(lqLines.pop())
    while lqLbls.size() > 0
        label.delete(lqLbls.pop())
    while lqTkLn.size() > 0
        line.delete(lqTkLn.pop())
    while lqTkLb.size() > 0
        label.delete(lqTkLb.pop())
    if lqTkLvl.size() > 0
        for i = 0 to lqTkLvl.size() - 1
            bool hi_ = lqTkHi.get(i)
            if hi_ ? lqBMajOn : lqSMajOn
                color tc = color.new(hi_ ? lqBMajCol : lqSMajCol, 55)
                lqTkLn.push(line.new(lqTkT0.get(i), lqTkLvl.get(i), lqTkT1.get(i), lqTkLvl.get(i), xloc = xloc.bar_time, color = tc, width = 1, style = line.style_dotted))
                lqTkLb.push(label.new(lqTkT1.get(i), lqTkLvl.get(i), (hi_ ? "BSL" : "SSL") + " ✓", xloc = xloc.bar_time, style = label.style_label_left, size = f_szName(lqLblSz), color = LQ_NONE, textcolor = tc))
    if lqBMajOn and lqHiLvl.size() > 0
        int bMaj = -1
        for i = 0 to lqHiLvl.size() - 1
            float lv = lqHiLvl.get(i)
            if lv > close and lqHiMaj.get(i) and (bMaj < 0 or lv < lqHiLvl.get(bMaj))
                bMaj := i
        if bMaj >= 0
            f_lqDraw(lqHiLvl.get(bMaj), lqHiT.get(bMaj), lqHiN.get(bMaj), true, true, lqBMajCol, lqBMajSty)
    if lqSMajOn and lqLoLvl.size() > 0
        int sMaj = -1
        for i = 0 to lqLoLvl.size() - 1
            float lv = lqLoLvl.get(i)
            if lv < close and lqLoMaj.get(i) and (sMaj < 0 or lv > lqLoLvl.get(sMaj))
                sMaj := i
        if sMaj >= 0
            f_lqDraw(lqLoLvl.get(sMaj), lqLoT.get(sMaj), lqLoN.get(sMaj), false, true, lqSMajCol, lqSMajSty)
 
 
// ═══ KEY LEVELS: Midnight / 8:30 / 9:30 opens + PD / PW / PM high-low-close ═══
int nyMin = hour(time, NY) * 60 + minute(time, NY)
 
// open price of the first bar at/after a NY clock time (0 = midnight)
f_openAt(int tgt) =>
    var float o = na
    var int   t = na
    bool hit = tgt == 0 ? nyMin < nz(nyMin[1], 9999) : (nyMin >= tgt and nz(nyMin[1], 9999) < tgt)
    if hit
        o := open
        t := time
    [o, t]
 
[midO, midT] = f_openAt(0)
[o830, t830] = f_openAt(510)
[o930, t930] = f_openAt(570)
 
int tDay = time("D")
int tWk  = time("W")
int tMo  = time("M")
 
color KL_MID = #2962ff
color KL_830 = #f5b800
color KL_930 = #f23645
color KL_PX  = #000000
 
var array<line>  klLines = array.new<line>()
var array<label> klLbls  = array.new<label>()
f_klDraw(float lvl, int t0, bool on, string tag, color col, string sty, bool fixedLen) =>
    if on and not na(lvl) and not na(t0) and f_isNear(lvl, lvl)
        int tNow = time + timeframe.in_seconds() * 1000
        int tR   = fixedLen ? math.max(t0 + LVL_BARS * timeframe.in_seconds() * 1000, tNow) : tNow   // at least 70 candles, then follows price
        klLines.push(line.new(t0, lvl, tR, lvl, xloc = xloc.bar_time, color = col, width = 1, style = sty))
        klLbls.push(label.new(tR, lvl, tag, xloc = xloc.bar_time, style = label.style_label_left, color = #ffffff00, textcolor = col, size = size.small))
    0
 
if barstate.islast
    while klLines.size() > 0
        line.delete(klLines.pop())
    while klLbls.size() > 0
        label.delete(klLbls.pop())
    // opens: only today's (since the 18:00 ET roll)
    f_klDraw(midO, midT, i_mid and midT >= sesDayT, "MIDNIGHT", KL_MID, line.style_solid, true)
    f_klDraw(o830, t830, i_830 and t830 >= sesDayT, "8:30",     KL_830, line.style_solid, true)
    f_klDraw(o930, t930, i_930 and t930 >= sesDayT, "9:30",     KL_930, line.style_solid, true)
    f_klDraw(pdh, tDay, i_pd, "PDH", KL_PX, line.style_dashed, false)
    f_klDraw(pdl, tDay, i_pd, "PDL", KL_PX, line.style_dashed, false)
    f_klDraw(pdc, tDay, i_pd, "PDC", KL_PX, line.style_dotted, false)
    f_klDraw(pwh, tWk,  i_pw, "PWH", KL_PX, line.style_dashed, false)
    f_klDraw(pwl, tWk,  i_pw, "PWL", KL_PX, line.style_dashed, false)
    f_klDraw(pwc, tWk,  i_pw, "PWC", KL_PX, line.style_dotted, false)
    f_klDraw(pmh, tMo,  i_pm, "PMH", KL_PX, line.style_dashed, false)
    f_klDraw(pml, tMo,  i_pm, "PML", KL_PX, line.style_dashed, false)
    f_klDraw(pmc, tMo,  i_pm, "PMC", KL_PX, line.style_dotted, false)
 
// ═══ KEY LEVEL SWEEP ALERTS — wick through + close back = alert · close through = ignored ═══
// kind 1 = high (sweep up) · -1 = low (sweep down) · 0 = middle level (close / open): from the side price comes from
// One chance per level: the first candle that reaches it decides. Evaluated on the candle close.
f_kSweep(float lvl, int t0, bool on, string tag, int kind) =>
    var bool done = false
    if lvl != lvl[1] or t0 != t0[1]
        done := false
    if on and barstate.isconfirmed and not done and not na(lvl) and (na(t0) or time > t0)
        bool upT = high >= lvl and nz(close[1], open) < lvl   // reached from below
        bool dnT = low <= lvl and nz(close[1], open) > lvl    // reached from above
        if kind == 1 ? high > lvl : kind == -1 ? low < lvl : (upT or dnT)
            done := true
            bool bear = kind == 1 or (kind == 0 and upT)
            if bear ? close < lvl : close > lvl
                alert((bear ? "🔴 " : "🟢 ") + tag + " SWEEP | " + SYM + " | " + TF, alert.freq_once_per_bar_close)
    0
f_kSweep(pdh, na, i_alPx, "PDH", 1)
f_kSweep(pdl, na, i_alPx, "PDL", -1)
f_kSweep(pdc, na, i_alPx, "PDC", 0)
f_kSweep(pwh, na, i_alPx, "PWH", 1)
f_kSweep(pwl, na, i_alPx, "PWL", -1)
f_kSweep(pwc, na, i_alPx, "PWC", 0)
f_kSweep(pmh, na, i_alPx, "PMH", 1)
f_kSweep(pml, na, i_alPx, "PML", -1)
f_kSweep(pmc, na, i_alPx, "PMC", 0)
f_kSweep(midO, midT, i_alOp and midT >= sesDayT, "MIDNIGHT", 0)
f_kSweep(o830, t830, i_alOp and t830 >= sesDayT, "8:30", 0)
f_kSweep(o930, t930, i_alOp and t930 >= sesDayT, "9:30", 0)
// NEAR LEVEL ALERT (key levels)
f_nearAl(pdh, i_pd, "PDH")
f_nearAl(pdl, i_pd, "PDL")
f_nearAl(pdc, i_pd, "PDC")
f_nearAl(pwh, i_pw, "PWH")
f_nearAl(pwl, i_pw, "PWL")
f_nearAl(pwc, i_pw, "PWC")
f_nearAl(pmh, i_pm, "PMH")
f_nearAl(pml, i_pm, "PML")
f_nearAl(pmc, i_pm, "PMC")
 
// ═══ OPENING GAPS: NDOG (new day) / NWOG (new week) ═══
// gap = previous candle close → first candle open of the new day / week (futures: 17:00 close → 18:00 ET open)
color OG_DAY = #607D8B
color OG_WK  = #9C27B0
bool  ogDay  = timeframe.isintraday and nz(ta.change(time("D")), 0) != 0
bool  ogWk   = timeframe.in_seconds() < 604800 and nz(ta.change(time("W")), 0) != 0
 
var float ndTop = na
var float ndBot = na
var int   ndT   = na
var float nwTop = na
var float nwBot = na
var int   nwT   = na
if ogDay and bar_index > 0
    ndTop := math.max(close[1], open)
    ndBot := math.min(close[1], open)
    ndT   := time[1]
if ogWk and bar_index > 0
    nwTop := math.max(close[1], open)
    nwBot := math.min(close[1], open)
    nwT   := time[1]
 
var box   ndBox = na
var line  ndCe  = na
var box   nwBox = na
var line  nwCe  = na
f_ogDraw(box ob, line ol, bool on, float top, float bot, int t0, string tag, color col) =>
    box.delete(ob)
    line.delete(ol)
    box  nb = na
    line nl = na
    if on and not na(top) and not na(bot) and not na(t0) and top > bot and f_isNear(top, bot)
        int tR = time + 10 * timeframe.in_seconds() * 1000
        nb := box.new(t0, top, tR, bot, xloc = xloc.bar_time, bgcolor = color.new(col, 82), border_color = color.new(col, 40), text = tag, text_size = size.tiny, text_color = color.black, text_halign = text.align_right, text_valign = text.align_top)
        nl := line.new(t0, (top + bot) / 2, tR, (top + bot) / 2, xloc = xloc.bar_time, color = col, style = line.style_dashed, width = 1)
    [nb, nl]
if barstate.islast
    [b1, l1] = f_ogDraw(ndBox, ndCe, i_ndog, ndTop, ndBot, ndT, "NDOG", OG_DAY)
    ndBox := b1
    ndCe  := l1
    [b2, l2] = f_ogDraw(nwBox, nwCe, i_nwog, nwTop, nwBot, nwT, "NWOG", OG_WK)
    nwBox := b2
    nwCe  := l2
 
 
// ═══════════════════════════════════════════════════════════════════════
//  PREMIUM & DISCOUNT — auto dealing range of each impulse (merged from PD Range)
//  BOS → origin at the STRONG impulse candle (body >= 2x ATR) or, without one, the nearest
//  local swing that launched the move. Shown only when: size >= 3x ATR(100), 2 closes beyond
//  the broken level, displacement (strong candle / FVG / 4-candle run), efficiency >= 50%,
//  no strong counter candle, bodies >= 50% (40% when efficiency >= 65%).
//  Shallow pullbacks (never reached 50%) continue the same range; a failed impulse
//  (close back through 50% within 3 candles of the extreme) is dropped.
// ═══════════════════════════════════════════════════════════════════════
// Higher timeframes (1H and above) get their own thresholds: HTF candles carry natural wicks,
// ATR(100) spans months/years there, and a 5-bar swing is weeks of confirmation.
bool PD_HTF = timeframe.in_seconds() >= 3600
int  PD_LEN = PD_HTF ? 2 : 5
bool PD_DBG = false
max_bars_back(open, 600)
max_bars_back(high, 600)
max_bars_back(low, 600)
max_bars_back(close, 600)
int PD_TFMS = timeframe.in_seconds() * 1000
// ─────────── fixed colours ───────────
color PD_PREM = color.new(#f23645, 85)
color PD_DISC = color.new(#089981, 85)
color PD_OTE  = color.new(#2962ff, 80)
color PD_EQ   = color.new(#787B86, 0)
color PD_TXT  = color.new(#787B86, 0)
 
// ─────────── impulse ingredients ───────────
float pdAtr     = ta.atr(14)
float pdAtrL    = ta.atr(100)
float pdAtrS    = PD_HTF ? pdAtr : math.max(pdAtr, nz(pdAtrL, pdAtr))   // LTF: a quiet stretch can't make an ordinary candle look "strong"
float pdAtrZ    = PD_HTF ? pdAtr : pdAtrL   // size yardstick: ATR(14) on HTF, ATR(100) on LTF
// STRONG candle = body >= 2x ATR(14). If the leg has one, the range starts at that impulse
// candle; if it has none, the range falls back to ANY (the whole leg from its swing extreme).
// Exactly one range per break of structure, never both.
float pdDMult   = 2.0
bool  pdBullDsp = close > open and (close - open) >= pdDMult * pdAtrS
bool  pdBearDsp = close < open and (open - close) >= pdDMult * pdAtrS
// history buffers for the dynamic look-backs in the range engine (RE10143)
// BAR BUFFERS: the range engine reads past candles from these arrays (index 0 = current bar),
// filled on EVERY bar at global scope. History operators inside conditionally-called methods are
// unreliable in Pine, so the engine never uses [] directly.
var array<float> pdBO = array.new<float>()
var array<float> pdBH = array.new<float>()
var array<float> pdBL = array.new<float>()
var array<float> pdBC = array.new<float>()
var array<float> pdBT = array.new<float>()
var array<float> pdBA = array.new<float>()
var array<float> pdBS = array.new<float>()
var array<float> pdBU = array.new<float>()
var array<float> pdBD = array.new<float>()
pdBO.unshift(open)
pdBH.unshift(high)
pdBL.unshift(low)
pdBC.unshift(close)
pdBT.unshift(time)
pdBA.unshift(pdAtr)
pdBS.unshift(pdAtrS)
pdBU.unshift(pdBullDsp ? 1 : 0)
pdBD.unshift(pdBearDsp ? 1 : 0)
if pdBO.size() > 600
    pdBO.pop()
    pdBH.pop()
    pdBL.pop()
    pdBC.pop()
    pdBT.pop()
    pdBA.pop()
    pdBS.pop()
    pdBU.pop()
    pdBD.pop()
f_pdG(array<float> a, int i) => i >= 0 and i < a.size() ? a.get(i) : na
 
// ─────────── swings ───────────
float pdPh = ta.pivothigh(high, PD_LEN, PD_LEN)
float pdPl = ta.pivotlow(low, PD_LEN, PD_LEN)
 
var float pdShP = na
var int   pdShB = na
var bool  pdShUsed = true
var float pdSlP = na
var int   pdSlB = na
var bool  pdSlUsed = true
 
if not na(pdPh)
    pdShP    := pdPh
    pdShB    := bar_index - PD_LEN
    pdShUsed := false
if not na(pdPl)
    pdSlP    := pdPl
    pdSlB    := bar_index - PD_LEN
    pdSlUsed := false
 
// ─────────── strength filters (hidden) ───────────
// A range is only SHOWN once it is a real move:
//   1. height (high – low) >= 3 x ATR(100)  (long ATR: quiet hours can't shrink the bar)
//   2. at least 2 confirmed candle CLOSES beyond the broken swing level
// Until then it is tracked invisibly (pending). A pending range that dies first is never drawn,
// and it never replaces / removes a range that is already on the chart.
// CONTINUATION: a new break whose pullback never reached the 50% of the current range in the
// same direction is part of the same impulse → no new range, the current one keeps extending.
// FAILED IMPULSE: a confirmed close back through the 50% within 3 candles of the range
// extreme = no follow-through, the range is dropped (pending or visible).
float PD_MIN_ATR  = PD_HTF ? 2.0 : 3.0
int   PD_MIN_CLS  = PD_HTF ? 1 : 2
int   PD_FAIL_WIN = 3
// DISPLACEMENT: a range without a STRONG candle needs an FVG in its leg OR a pdRunV of 4+ consecutive
// candles with the move (body >= 0.5 x ATR each). A slow grind has neither.
// STRONG candle = body >= 2x the larger of ATR(14) / ATR(100).
// QUALITY (origin → extreme): a clean one-sided delivery, not a choppy staircase
//   efficiency = (bodies with the move − bodies against it) / all bodies   >= 50%
//   no counter candle with a body >= 1.5 x ATR(14) inside the leg
//   bodies make up >= 50% of the candles' full ranges (a wick-heavy leg is indecision, not delivery)
//   (>= 40% is enough when efficiency >= 65%: a clearly one-sided leg may end with reversal wicks)
float PD_MIN_EFF  = 0.5
int   PD_RUN_LEN  = 4     // consecutive candles with the move (displacement without an FVG)
float PD_RUN_BODY = 0.5   // each with a body >= 0.5 x ATR
float PD_MIN_BODY = PD_HTF ? 0.35 : 0.5   // bodies / full candle ranges in the leg: below this the leg is mostly wicks (indecision)
float PD_MIN_BODY_TREND = PD_HTF ? 0.25 : 0.4   // relaxed body floor when the leg is clearly one-sided
float PD_EFF_TREND      = 0.65  // efficiency that counts as "clearly one-sided"
float PD_OPP_ATR  = 1.5
 
// ─────────── range object ───────────
type PdRng
    int   dir        // 1 = bullish impulse, -1 = bearish
    float hi
    float lo
    int   t0         // origin candle time
    int   born       // bar the range became visible
    float brk        // the swing level the impulse broke
    int   nCl = 0    // confirmed closes beyond brk
    int   xBar       // bar index of the latest range extreme (high for bull, low for bear)
    int   oBar       // bar index of the origin candle
    bool  shown = false
    bool  alerted = false
    bool  any = false   // created without a STRONG candle: upgrades if one prints later in the leg
    box   bP
    box   bD
    box   bO
    line  eq
    label lE
 
color PD_NONE = color.new(color.black, 100)
 
f_pdKill(PdRng r) =>
    if not na(r)
        box.delete(r.bP)
        box.delete(r.bD)
        box.delete(r.bO)
        line.delete(r.eq)
        label.delete(r.lE)
 
method pdRender(PdRng r) =>
    int   tR  = time + 10 * PD_TFMS
    float eqv = (r.hi + r.lo) / 2
    bool  on  = r.shown and i_pd_on and PD_TF_OK
    r.bP.set_lefttop(r.t0, r.hi)
    r.bP.set_rightbottom(tR, eqv)
    r.bP.set_bgcolor(on ? PD_PREM : PD_NONE)
    r.bP.set_text_color(on ? PD_TXT : PD_NONE)
    r.bD.set_lefttop(r.t0, eqv)
    r.bD.set_rightbottom(tR, r.lo)
    r.bD.set_bgcolor(on ? PD_DISC : PD_NONE)
    r.bD.set_text_color(on ? PD_TXT : PD_NONE)
    r.eq.set_xy1(r.t0, eqv)
    r.eq.set_xy2(tR, eqv)
    r.eq.set_color(on ? PD_EQ : PD_NONE)
    if not na(r.lE)
        r.lE.set_xy(tR, eqv)
        r.lE.set_textcolor(on ? PD_TXT : PD_NONE)
    if not na(r.bO)
        float rg = r.hi - r.lo
        float a  = r.dir == 1 ? r.hi - 0.62 * rg : r.lo + 0.62 * rg
        float b  = r.dir == 1 ? r.hi - 0.79 * rg : r.lo + 0.79 * rg
        r.bO.set_lefttop(r.t0, math.max(a, b))
        r.bO.set_rightbottom(tR, math.min(a, b))
        r.bO.set_bgcolor(on ? PD_OTE : PD_NONE)
        r.bO.set_border_color(on ? color.new(PD_OTE, 40) : PD_NONE)
        r.bO.set_text_color(on ? PD_TXT : PD_NONE)
 
f_pdNew(int dir, float hi, float lo, int t0, int oBar, float brk, bool anyMode) =>
    string tp = ""
    string td = ""
    box   bP = box.new(t0, hi, time, lo, xloc = xloc.bar_time, bgcolor = PD_NONE, border_color = PD_NONE, text = tp, text_size = size.small, text_color = PD_NONE, text_halign = text.align_right, text_valign = text.align_top)
    box   bD = box.new(t0, hi, time, lo, xloc = xloc.bar_time, bgcolor = PD_NONE, border_color = PD_NONE, text = td, text_size = size.small, text_color = PD_NONE, text_halign = text.align_right, text_valign = text.align_bottom)
    box   bO = i_pdOte ? box.new(t0, hi, time, lo, xloc = xloc.bar_time, bgcolor = PD_NONE, border_color = PD_NONE, border_style = line.style_dotted, text = i_pdLbl ? "OTE" : "", text_size = size.tiny, text_color = PD_NONE, text_halign = text.align_right) : na
    line  eq = line.new(t0, (hi + lo) / 2, time, (hi + lo) / 2, xloc = xloc.bar_time, color = PD_NONE, style = line.style_dashed, width = 1)
    label lE = i_pdLbl ? label.new(time, (hi + lo) / 2, "EQ 50%", xloc = xloc.bar_time, style = label.style_label_left, color = PD_NONE, textcolor = PD_NONE, size = size.small) : na
    PdRng r = PdRng.new(dir = dir, hi = hi, lo = lo, t0 = t0, born = bar_index, brk = brk, any = anyMode, xBar = bar_index, oBar = oBar, bP = bP, bD = bD, bO = bO, eq = eq, lE = lE)
    r.pdRender()
    r
 
// upgrade ANY → STRONG when a pdStrong candle prints later in the same leg,
// extend with the leg, and report whether the range is still alive (no close beyond its origin)
method pdStep(PdRng r) =>
    if r.dir == 1
        if r.any and pdBullDsp and high >= r.hi
            int k = 0
            while k + 1 <= 300 and int(f_pdG(pdBT, k + 1)) > r.t0 and f_pdG(pdBC, k + 1) > f_pdG(pdBO, k + 1)
                k += 1
            if int(f_pdG(pdBT, k + 1)) >= r.t0 and f_pdG(pdBL, k + 1) < f_pdG(pdBL, k)
                k += 1
            float lo2 = low
            for i = 0 to k
                lo2 := math.min(lo2, f_pdG(pdBL, i))
            r.lo   := lo2
            r.t0   := int(f_pdG(pdBT, k))
            r.oBar := bar_index - k
            r.any  := false
        if high > r.hi
            r.hi   := high
            r.xBar := bar_index
        r.nCl += barstate.isconfirmed and close > r.brk ? 1 : 0
    else
        if r.any and pdBearDsp and low <= r.lo
            int k = 0
            while k + 1 <= 300 and int(f_pdG(pdBT, k + 1)) > r.t0 and f_pdG(pdBC, k + 1) < f_pdG(pdBO, k + 1)
                k += 1
            if int(f_pdG(pdBT, k + 1)) >= r.t0 and f_pdG(pdBH, k + 1) > f_pdG(pdBH, k)
                k += 1
            float hi2 = high
            for i = 0 to k
                hi2 := math.max(hi2, f_pdG(pdBH, i))
            r.hi   := hi2
            r.t0   := int(f_pdG(pdBT, k))
            r.oBar := bar_index - k
            r.any  := false
        if low < r.lo
            r.lo   := low
            r.xBar := bar_index
        r.nCl += barstate.isconfirmed and close < r.brk ? 1 : 0
    float eqv  = (r.hi + r.lo) / 2
    bool  fail = not (i_pdKeep and r.shown) and bar_index - r.xBar <= PD_FAIL_WIN and (r.dir == 1 ? close < eqv : close > eqv)
    bool  dead = barstate.isconfirmed and ((r.dir == 1 ? close < r.lo : close > r.hi) or fail)
    not dead
 
method pdQuality(PdRng r) =>
    int   a    = math.max(0, bar_index - r.xBar)
    int   b    = math.max(a, math.min(bar_index - r.oBar, 400))
    float wSum = 0.0
    float vSum = 0.0
    float rSum = 0.0
    bool  bigC = false
    for i = a to b
        float body = f_pdG(pdBC, i) - f_pdG(pdBO, i)
        float mv   = r.dir == 1 ? body : -body
        bigC := bigC or -mv >= PD_OPP_ATR * f_pdG(pdBA, i)
        wSum += math.max(mv, 0)
        vSum += math.max(-mv, 0)
        rSum += f_pdG(pdBH, i) - f_pdG(pdBL, i)
    float tot = wSum + vSum
    float eff = tot > 0 ? (wSum - vSum) / tot : 0
    float bdy = rSum > 0 ? tot / rSum : 0
    not bigC and eff >= PD_MIN_EFF and bdy >= (eff >= PD_EFF_TREND ? PD_MIN_BODY_TREND : PD_MIN_BODY)
 
// displacement evidence for ranges WITHOUT a pdStrong candle (origin → extreme):
//   an FVG in the leg, OR a pdRunV of >= 4 consecutive candles with the move, each body >= 0.5 x ATR
method pdHasDisp(PdRng r) =>
    int  a   = math.max(0, bar_index - r.xBar)
    int  b   = math.min(bar_index - r.oBar, 400)
    bool ok  = false
    int  pdRunV = 0
    for i = a to b
        if i + 2 <= b and (r.dir == 1 ? f_pdG(pdBL, i) > f_pdG(pdBH, i + 2) : f_pdG(pdBH, i) < f_pdG(pdBL, i + 2))
            ok := true
        float mv = r.dir == 1 ? f_pdG(pdBC, i) - f_pdG(pdBO, i) : f_pdG(pdBO, i) - f_pdG(pdBC, i)
        pdRunV := mv >= PD_RUN_BODY * f_pdG(pdBS, i) ? pdRunV + 1 : 0
        ok  := ok or pdRunV >= PD_RUN_LEN
    ok
 
method pdDiag(PdRng r) =>
    int   a    = math.max(0, bar_index - r.xBar)
    int   b    = math.max(a, math.min(bar_index - r.oBar, 400))
    float wSum = 0.0
    float vSum = 0.0
    float rSum = 0.0
    bool  bigC = false
    for i = a to b
        float mv = r.dir == 1 ? f_pdG(pdBC, i) - f_pdG(pdBO, i) : f_pdG(pdBO, i) - f_pdG(pdBC, i)
        bigC := bigC or -mv >= PD_OPP_ATR * f_pdG(pdBA, i)
        wSum += math.max(mv, 0)
        vSum += math.max(-mv, 0)
        rSum += f_pdG(pdBH, i) - f_pdG(pdBL, i)
    float tot = wSum + vSum
    float eff = tot > 0 ? (wSum - vSum) / tot : 0
    float bdy = rSum > 0 ? tot / rSum : 0
    string ok = "✓"
    string no = "✗"
    "SIZE " + (r.hi - r.lo >= PD_MIN_ATR * pdAtrZ ? ok : no) + str.format(" {0,number,#.#}xATR", (r.hi - r.lo) / pdAtrZ) +
     "\n2CL " + (r.nCl >= PD_MIN_CLS ? ok : no) + " (" + str.tostring(r.nCl) + ")" +
     "\n" + (r.any ? "FVG/RUN " + (r.pdHasDisp() ? ok : no) : "STRONG ✓") +
     "\nEFF " + (eff >= PD_MIN_EFF ? ok : no) + str.format(" {0,number,#}%", eff * 100) +
     "\nCTR " + (bigC ? no : ok) +
     "\nBODY " + (bdy >= (eff >= PD_EFF_TREND ? PD_MIN_BODY_TREND : PD_MIN_BODY) ? ok : no) + str.format(" {0,number,#}%", bdy * 100) + (eff >= PD_EFF_TREND ? " (min 40)" : " (min 50)")
 
method pdStrong(PdRng r) =>
    r.hi - r.lo >= PD_MIN_ATR * pdAtrZ and r.nCl >= PD_MIN_CLS and r.pdQuality() and (not r.any or r.pdHasDisp())
 
var PdRng pdRBu = na   // visible bullish range
var PdRng pdRBe = na   // visible bearish range
var PdRng pdPBu = na   // pending bullish candidate
var PdRng pdPBe = na   // pending bearish candidate
 
// ─────────── BULL impulse: close breaks the last swing high ───────────
if i_pdBull and not pdShUsed and not na(pdShP) and close > pdShP
    int   n   = math.min(bar_index - pdShB, 500)
    float mn  = low
    int   off = 0
    for i = 0 to n
        if f_pdG(pdBL, i) < mn
            mn  := f_pdG(pdBL, i)
            off := i
    // earliest STRONG candle in the leg (closest to the origin)
    int j = -1
    for i = 0 to off
        if f_pdG(pdBU, i) == 1
            j := i
    if j >= 0   // STRONG: start at the impulse candle
        int k = j
        while k + 1 <= off and f_pdG(pdBC, k + 1) > f_pdG(pdBO, k + 1)
            k += 1
        if k + 1 <= n and f_pdG(pdBL, k + 1) < f_pdG(pdBL, k)
            k += 1
        float lo2 = low
        for i = 0 to k
            lo2 := math.min(lo2, f_pdG(pdBL, i))
        mn  := lo2
        off := k
    else        // ANY: nearest local swing low (lower than 2 candles each side) that launched the move
        float pdRunV = low
        int   fo  = -1
        for i = 0 to off
            pdRunV := math.min(pdRunV, f_pdG(pdBL, i))
            if i >= 2 and i + 2 <= n and f_pdG(pdBL, i) == pdRunV and f_pdG(pdBL, i) < f_pdG(pdBL, i + 1) and f_pdG(pdBL, i) < f_pdG(pdBL, i + 2) and f_pdG(pdBL, i) <= f_pdG(pdBL, i - 1) and f_pdG(pdBL, i) <= f_pdG(pdBL, i - 2)
                fo := i
                break
        if fo >= 0
            mn  := f_pdG(pdBL, fo)
            off := fo
    float mx = high
    int   xo = 0
    for i = 0 to off
        if f_pdG(pdBH, i) > mx
            mx := f_pdG(pdBH, i)
            xo := i
    // CONTINUATION: the pullback before this break stayed in the PREMIUM of the current bullish
    // range (never reached its 50%) → same impulse, keep that range and just let it extend.
    PdRng pdCur = pdRBu   // only a VISIBLE range can absorb a continuation; a weak hidden one never blocks a new move
    bool pdCont = not na(pdCur) and mn > (pdCur.hi + pdCur.lo) / 2
    if not pdCont
        f_pdKill(pdPBu)
        pdPBu := f_pdNew(1, mx, mn, int(f_pdG(pdBT, off)), bar_index - off, pdShP, j < 0)
        pdPBu.xBar := bar_index - xo
    pdShUsed := true
 
// ─────────── BEAR impulse: close breaks the last swing low ───────────
if i_pdBear and not pdSlUsed and not na(pdSlP) and close < pdSlP
    int   n   = math.min(bar_index - pdSlB, 500)
    float mx  = high
    int   off = 0
    for i = 0 to n
        if f_pdG(pdBH, i) > mx
            mx  := f_pdG(pdBH, i)
            off := i
    int j = -1
    for i = 0 to off
        if f_pdG(pdBD, i) == 1
            j := i
    if j >= 0
        int k = j
        while k + 1 <= off and f_pdG(pdBC, k + 1) < f_pdG(pdBO, k + 1)
            k += 1
        if k + 1 <= n and f_pdG(pdBH, k + 1) > f_pdG(pdBH, k)
            k += 1
        float hi2 = high
        for i = 0 to k
            hi2 := math.max(hi2, f_pdG(pdBH, i))
        mx  := hi2
        off := k
    else        // ANY: nearest local swing high (higher than 2 candles each side) that launched the move
        float pdRunV = high
        int   fo  = -1
        for i = 0 to off
            pdRunV := math.max(pdRunV, f_pdG(pdBH, i))
            if i >= 2 and i + 2 <= n and f_pdG(pdBH, i) == pdRunV and f_pdG(pdBH, i) > f_pdG(pdBH, i + 1) and f_pdG(pdBH, i) > f_pdG(pdBH, i + 2) and f_pdG(pdBH, i) >= f_pdG(pdBH, i - 1) and f_pdG(pdBH, i) >= f_pdG(pdBH, i - 2)
                fo := i
                break
        if fo >= 0
            mx  := f_pdG(pdBH, fo)
            off := fo
    float mn = low
    int   xo = 0
    for i = 0 to off
        if f_pdG(pdBL, i) < mn
            mn := f_pdG(pdBL, i)
            xo := i
    // CONTINUATION: the pullback stayed in the DISCOUNT of the current bearish range
    PdRng pdCur = pdRBe
    bool pdCont = not na(pdCur) and mx < (pdCur.hi + pdCur.lo) / 2
    if not pdCont
        f_pdKill(pdPBe)
        pdPBe := f_pdNew(-1, mx, mn, int(f_pdG(pdBT, off)), bar_index - off, pdSlP, j < 0)
        pdPBe.xBar := bar_index - xo
    pdSlUsed := true
 
// ─────────── pending candidates: promote when pdStrong, drop when they die ───────────
if not na(pdPBu)
    if not pdPBu.pdStep()
        f_pdKill(pdPBu)
        pdPBu := na
    else if pdPBu.pdStrong()
        f_pdKill(pdRBu)
        pdRBu := pdPBu
        pdPBu := na
        pdRBu.shown := true
        pdRBu.born  := bar_index
        if not i_pdBoth
            f_pdKill(pdRBe)
            pdRBe := na
if not na(pdPBe)
    if not pdPBe.pdStep()
        f_pdKill(pdPBe)
        pdPBe := na
    else if pdPBe.pdStrong()
        f_pdKill(pdRBe)
        pdRBe := pdPBe
        pdPBe := na
        pdRBe.shown := true
        pdRBe.born  := bar_index
        if not i_pdBoth
            f_pdKill(pdRBu)
            pdRBu := na
 
// ─────────── visible ranges: maintain, alert, pdRender ───────────
if not na(pdRBu) and pdRBu.born < bar_index
    if not pdRBu.pdStep() or (not i_pdKeep and pdRBu.xBar == bar_index and not pdRBu.pdQuality())
        f_pdKill(pdRBu)
        pdRBu := na
if not na(pdRBe) and pdRBe.born < bar_index
    if not pdRBe.pdStep() or (not i_pdKeep and pdRBe.xBar == bar_index and not pdRBe.pdQuality())
        f_pdKill(pdRBe)
        pdRBe := na
 
if not na(pdRBu)
    pdRBu.pdRender()
if not na(pdRBe)
    pdRBe.pdRender()
if not na(pdPBu)
    pdPBu.pdRender()
if not na(pdPBe)
    pdPBe.pdRender()
 
// ─────────── DEBUG: hidden candidates with their checks ───────────
var box   pdDbB1 = na
var box   pdDbB2 = na
var label pdDbL1 = na
var label pdDbL2 = na
f_pdDbg(PdRng r, box oldB, label oldL) =>
    box.delete(oldB)
    label.delete(oldL)
    box   nb = na
    label nl = na
    if PD_DBG and not na(r)
        nb := box.new(r.t0, r.hi, time + 10 * PD_TFMS, r.lo, xloc = xloc.bar_time, bgcolor = color.new(color.gray, 94), border_color = color.gray, border_style = line.style_dashed)
        nl := label.new(time + 10 * PD_TFMS, r.dir == 1 ? r.hi : r.lo, (r.dir == 1 ? "BULL candidate\n" : "BEAR candidate\n") + r.pdDiag(), xloc = xloc.bar_time, style = r.dir == 1 ? label.style_label_lower_left : label.style_label_upper_left, color = color.new(color.white, 10), textcolor = color.black, size = size.small, textalign = text.align_left)
    [nb, nl]
if barstate.islast
    [pdb1, pdl1] = f_pdDbg(pdPBu, pdDbB1, pdDbL1)
    [pdb2, pdl2] = f_pdDbg(pdPBe, pdDbB2, pdDbL2)
    pdDbB1 := pdb1
    pdDbL1 := pdl1
    pdDbB2 := pdb2
    pdDbL2 := pdl2
 
// ═══════════════════════════════════════════════════════════════════════
//  HTF PREMIUM & DISCOUNT — W / D / 4H / 1H current dealing range + table
//  Same engine as the chart range (HTF thresholds), run inside request.security
//  on the requested timeframe. Values are read from the last CLOSED candle of
//  that timeframe ([1] + lookahead_on) → no repaint.
// ═══════════════════════════════════════════════════════════════════════
type PdC
    int   dir
    float hi
    float lo
    int   t0
    float brk
    int   nCl = 0
    int   xBar
    int   oBar
    bool  any = false
 
// extend / upgrade / alive check (bars buffers: O H L C T)
f_hcStep(PdC r, array<float> bO, array<float> bH, array<float> bL, array<float> bC, array<float> bT, bool bDsp, bool sDsp, bool vis) =>
    if r.dir == 1
        if r.any and bDsp and high >= r.hi
            int k = 0
            while k + 1 <= 300 and int(f_pdG(bT, k + 1)) > r.t0 and f_pdG(bC, k + 1) > f_pdG(bO, k + 1)
                k += 1
            if int(f_pdG(bT, k + 1)) >= r.t0 and f_pdG(bL, k + 1) < f_pdG(bL, k)
                k += 1
            float lo2 = low
            for i = 0 to k
                lo2 := math.min(lo2, f_pdG(bL, i))
            r.lo   := lo2
            r.t0   := int(f_pdG(bT, k))
            r.oBar := bar_index - k
            r.any  := false
        if high > r.hi
            r.hi   := high
            r.xBar := bar_index
        r.nCl += barstate.isconfirmed and close > r.brk ? 1 : 0
    else
        if r.any and sDsp and low <= r.lo
            int k = 0
            while k + 1 <= 300 and int(f_pdG(bT, k + 1)) > r.t0 and f_pdG(bC, k + 1) < f_pdG(bO, k + 1)
                k += 1
            if int(f_pdG(bT, k + 1)) >= r.t0 and f_pdG(bH, k + 1) > f_pdG(bH, k)
                k += 1
            float hi2 = high
            for i = 0 to k
                hi2 := math.max(hi2, f_pdG(bH, i))
            r.hi   := hi2
            r.t0   := int(f_pdG(bT, k))
            r.oBar := bar_index - k
            r.any  := false
        if low < r.lo
            r.lo   := low
            r.xBar := bar_index
        r.nCl += barstate.isconfirmed and close < r.brk ? 1 : 0
    float eqv  = (r.hi + r.lo) / 2
    bool  fail = not (i_pdKeep and vis) and bar_index - r.xBar <= PD_FAIL_WIN and (r.dir == 1 ? close < eqv : close > eqv)
    bool  dead = barstate.isconfirmed and ((r.dir == 1 ? close < r.lo : close > r.hi) or fail)
    not dead
 
f_hcQuality(PdC r, array<float> bO, array<float> bH, array<float> bL, array<float> bC, array<float> bA) =>
    int   a    = math.max(0, bar_index - r.xBar)
    int   b    = math.max(a, math.min(bar_index - r.oBar, 400))
    float wSum = 0.0
    float vSum = 0.0
    float rSum = 0.0
    bool  bigC = false
    for i = a to b
        float body = f_pdG(bC, i) - f_pdG(bO, i)
        float mv   = r.dir == 1 ? body : -body
        bigC := bigC or -mv >= PD_OPP_ATR * f_pdG(bA, i)
        wSum += math.max(mv, 0)
        vSum += math.max(-mv, 0)
        rSum += f_pdG(bH, i) - f_pdG(bL, i)
    float tot = wSum + vSum
    float eff = tot > 0 ? (wSum - vSum) / tot : 0
    float bdy = rSum > 0 ? tot / rSum : 0
    not bigC and eff >= PD_MIN_EFF and bdy >= (eff >= PD_EFF_TREND ? 0.25 : 0.35)
 
f_hcDisp(PdC r, array<float> bO, array<float> bH, array<float> bL, array<float> bC, array<float> bA) =>
    int  a  = math.max(0, bar_index - r.xBar)
    int  b  = math.min(bar_index - r.oBar, 400)
    bool ok = false
    int  rn = 0
    for i = a to b
        if i + 2 <= b and (r.dir == 1 ? f_pdG(bL, i) > f_pdG(bH, i + 2) : f_pdG(bH, i) < f_pdG(bL, i + 2))
            ok := true
        float mv = r.dir == 1 ? f_pdG(bC, i) - f_pdG(bO, i) : f_pdG(bO, i) - f_pdG(bC, i)
        rn := mv >= PD_RUN_BODY * f_pdG(bA, i) ? rn + 1 : 0
        ok := ok or rn >= PD_RUN_LEN
    ok
 
f_hcStrong(PdC r, float atr, array<float> bO, array<float> bH, array<float> bL, array<float> bC, array<float> bA) =>
    r.hi - r.lo >= 2.0 * atr and r.nCl >= 1 and f_hcQuality(r, bO, bH, bL, bC, bA) and (not r.any or f_hcDisp(r, bO, bH, bL, bC, bA))
 
// the whole engine for ONE timeframe → [dir, hi, lo, t0] of its visible range (last closed candle)
f_pdHtfCore() =>
    float atr  = ta.atr(14)
    bool  bDsp = close > open and (close - open) >= 2.0 * atr
    bool  sDsp = close < open and (open - close) >= 2.0 * atr
    var array<float> bO = array.new<float>()
    var array<float> bH = array.new<float>()
    var array<float> bL = array.new<float>()
    var array<float> bC = array.new<float>()
    var array<float> bT = array.new<float>()
    var array<float> bA = array.new<float>()
    var array<float> bU = array.new<float>()
    var array<float> bD = array.new<float>()
    bO.unshift(open)
    bH.unshift(high)
    bL.unshift(low)
    bC.unshift(close)
    bT.unshift(time)
    bA.unshift(atr)
    bU.unshift(bDsp ? 1 : 0)
    bD.unshift(sDsp ? 1 : 0)
    if bO.size() > 600
        bO.pop()
        bH.pop()
        bL.pop()
        bC.pop()
        bT.pop()
        bA.pop()
        bU.pop()
        bD.pop()
    float ph = ta.pivothigh(high, 2, 2)
    float pl = ta.pivotlow(low, 2, 2)
    var float shP = na
    var int   shB = na
    var bool  shU = true
    var float slP = na
    var int   slB = na
    var bool  slU = true
    if not na(ph)
        shP := ph
        shB := bar_index - 2
        shU := false
    if not na(pl)
        slP := pl
        slB := bar_index - 2
        slU := false
    var PdC rBu = na
    var PdC rBe = na
    var PdC pBu = na
    var PdC pBe = na
    // BULL break
    if not shU and not na(shP) and close > shP
        int   n   = math.min(bar_index - shB, 500)
        float mn  = low
        int   off = 0
        for i = 0 to n
            if f_pdG(bL, i) < mn
                mn  := f_pdG(bL, i)
                off := i
        int j = -1
        for i = 0 to off
            if f_pdG(bU, i) == 1
                j := i
        if j >= 0
            int k = j
            while k + 1 <= off and f_pdG(bC, k + 1) > f_pdG(bO, k + 1)
                k += 1
            if k + 1 <= n and f_pdG(bL, k + 1) < f_pdG(bL, k)
                k += 1
            float lo2 = low
            for i = 0 to k
                lo2 := math.min(lo2, f_pdG(bL, i))
            mn  := lo2
            off := k
        else
            float rv = low
            int   fo = -1
            for i = 0 to off
                rv := math.min(rv, f_pdG(bL, i))
                if i >= 2 and i + 2 <= n and f_pdG(bL, i) == rv and f_pdG(bL, i) < f_pdG(bL, i + 1) and f_pdG(bL, i) < f_pdG(bL, i + 2) and f_pdG(bL, i) <= f_pdG(bL, i - 1) and f_pdG(bL, i) <= f_pdG(bL, i - 2)
                    fo := i
                    break
            if fo >= 0
                mn  := f_pdG(bL, fo)
                off := fo
        float mx = high
        int   xo = 0
        for i = 0 to off
            if f_pdG(bH, i) > mx
                mx := f_pdG(bH, i)
                xo := i
        bool cont = not na(rBu) and mn > (rBu.hi + rBu.lo) / 2
        if not cont
            pBu := PdC.new(dir = 1, hi = mx, lo = mn, t0 = int(f_pdG(bT, off)), brk = shP, any = j < 0, xBar = bar_index - xo, oBar = bar_index - off)
        shU := true
    // BEAR break
    if not slU and not na(slP) and close < slP
        int   n   = math.min(bar_index - slB, 500)
        float mx  = high
        int   off = 0
        for i = 0 to n
            if f_pdG(bH, i) > mx
                mx  := f_pdG(bH, i)
                off := i
        int j = -1
        for i = 0 to off
            if f_pdG(bD, i) == 1
                j := i
        if j >= 0
            int k = j
            while k + 1 <= off and f_pdG(bC, k + 1) < f_pdG(bO, k + 1)
                k += 1
            if k + 1 <= n and f_pdG(bH, k + 1) > f_pdG(bH, k)
                k += 1
            float hi2 = high
            for i = 0 to k
                hi2 := math.max(hi2, f_pdG(bH, i))
            mx  := hi2
            off := k
        else
            float rv = high
            int   fo = -1
            for i = 0 to off
                rv := math.max(rv, f_pdG(bH, i))
                if i >= 2 and i + 2 <= n and f_pdG(bH, i) == rv and f_pdG(bH, i) > f_pdG(bH, i + 1) and f_pdG(bH, i) > f_pdG(bH, i + 2) and f_pdG(bH, i) >= f_pdG(bH, i - 1) and f_pdG(bH, i) >= f_pdG(bH, i - 2)
                    fo := i
                    break
            if fo >= 0
                mx  := f_pdG(bH, fo)
                off := fo
        float mn = low
        int   xo = 0
        for i = 0 to off
            if f_pdG(bL, i) < mn
                mn := f_pdG(bL, i)
                xo := i
        bool cont = not na(rBe) and mx < (rBe.hi + rBe.lo) / 2
        if not cont
            pBe := PdC.new(dir = -1, hi = mx, lo = mn, t0 = int(f_pdG(bT, off)), brk = slP, any = j < 0, xBar = bar_index - xo, oBar = bar_index - off)
        slU := true
    // pending → visible
    bool newBu = false
    bool newBe = false
    if not na(pBu)
        if not f_hcStep(pBu, bO, bH, bL, bC, bT, bDsp, sDsp, false)
            pBu := na
        else if f_hcStrong(pBu, atr, bO, bH, bL, bC, bA)
            rBu   := pBu
            pBu   := na
            rBe   := na
            newBu := true
    if not na(pBe)
        if not f_hcStep(pBe, bO, bH, bL, bC, bT, bDsp, sDsp, false)
            pBe := na
        else if f_hcStrong(pBe, atr, bO, bH, bL, bC, bA)
            rBe   := pBe
            pBe   := na
            rBu   := na
            newBe := true
    // visible: maintain
    if not na(rBu) and not newBu
        if not f_hcStep(rBu, bO, bH, bL, bC, bT, bDsp, sDsp, true) or (not i_pdKeep and rBu.xBar == bar_index and not f_hcQuality(rBu, bO, bH, bL, bC, bA))
            rBu := na
    if not na(rBe) and not newBe
        if not f_hcStep(rBe, bO, bH, bL, bC, bT, bDsp, sDsp, true) or (not i_pdKeep and rBe.xBar == bar_index and not f_hcQuality(rBe, bO, bH, bL, bC, bA))
            rBe := na
    int   d  = 0
    float h  = na
    float l  = na
    int   t  = na
    float rx = na   // deepest pullback AFTER the range extreme (bull: lowest low, bear: highest high)
    if not na(rBu)
        d := 1
        h := rBu.hi
        l := rBu.lo
        t := rBu.t0
        int m = math.min(bar_index - rBu.xBar, 400)
        if m > 0
            for i = 0 to m - 1
                rx := na(rx) ? f_pdG(bL, i) : math.min(rx, f_pdG(bL, i))
    else if not na(rBe)
        d := -1
        h := rBe.hi
        l := rBe.lo
        t := rBe.t0
        int m = math.min(bar_index - rBe.xBar, 400)
        if m > 0
            for i = 0 to m - 1
                rx := na(rx) ? f_pdG(bH, i) : math.max(rx, f_pdG(bH, i))
    // CURRENT state incl. the developing candle = exactly what that timeframe's own chart shows.
    // Read only on the last chart bar (table + drawing), so lookahead_on never leaks into history.
    [d, h, l, t, rx, d[1]]
 
int  PDC_SEC = timeframe.in_seconds()
bool pdOkW = i_pdW and 604800 > PDC_SEC and PD_TF_OK
bool pdOkD = i_pdD and 86400  > PDC_SEC and PD_TF_OK
bool pdOk4 = i_pd4 and 14400  > PDC_SEC and PD_TF_OK
bool pdOk1 = i_pd1 and 3600   > PDC_SEC and PD_TF_OK
[pdWd, pdWH, pdWL, pdWt, pdWR, pdWp] = request.security(syminfo.tickerid, "W",   f_pdHtfCore(), lookahead = barmerge.lookahead_on)
[pdDd, pdDH, pdDL, pdDt, pdDR, pdDp] = request.security(syminfo.tickerid, "D",   f_pdHtfCore(), lookahead = barmerge.lookahead_on)
[pd4d, pd4H, pd4L, pd4t, pd4R, pd4p] = request.security(syminfo.tickerid, "240", f_pdHtfCore(), lookahead = barmerge.lookahead_on)
[pd1d, pd1H, pd1L, pd1t, pd1R, pd1p] = request.security(syminfo.tickerid, "60",  f_pdHtfCore(), lookahead = barmerge.lookahead_on)
 
// ═══ PREMIUM / DISCOUNT ALERTS (the chart range — one alert per chart timeframe) ═══
// For each half of the range (DISCOUNT below the 50% · PREMIUM above):
//   NEAR = price comes within min(10% of the range, 2 x ATR) of the 50%  (no more "near" that is far away on big ranges)
//   IN   = price actually crosses the 50% into that half
// Re-armed when price has left that half and gone 25% of the range into the other half (e.g. back up to
// the middle of PREMIUM) → the NEXT return gives NEW alerts. A half price is already in when the range
// appears is not alerted until price has left it that way.
const float PD_NEAR_ATR = 1.0    // NEAR = within min(5% of the range, 1 x ATR) of the 50%
const float PD_NEAR_PCT = 0.05
const float PD_REARM    = 0.40   // re-armed only after a close deep on the other side (90% / 10% of the range)
const int   PD_COOL     = 20     // and not again within 20 candles
f_pdAl(float h, float l, int id, bool on, bool live, string tag) =>
    var int  lastId = na
    var bool aNd = false   // NEAR DISCOUNT armed
    var bool aId = false   // IN DISCOUNT armed
    var bool aNp = false   // NEAR PREMIUM armed
    var bool aIp = false   // IN PREMIUM armed
    var int  lastAl = na
    if on and live and not na(h) and not na(l) and h > l
        float rng = h - l
        float eq  = (h + l) / 2
        float nd  = math.min(PD_NEAR_PCT * rng, PD_NEAR_ATR * nz(smtAtr, rng))
        // the trading side only: bullish range → DISCOUNT (buy) · bearish range → PREMIUM (sell)
        bool  bull = id > 0
        bool  cool = na(lastAl) or bar_index - lastAl >= PD_COOL
        string tg = tag == "" ? "" : " " + tag
        if na(lastId) or id != lastId
            // new range (or first live bar): arm only the halves price is not already in / near
            lastId := id
            aNd := low > eq + nd
            aId := low > eq
            aNp := high < eq - nd
            aIp := high < eq
        else
            if aNd and low <= eq + nd and bull and cool
                aNd := false
                lastAl := bar_index
                alert("🟢 NEAR DISCOUNT" + tg + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
            if aId and low <= eq and bull
                aId := false
                lastAl := bar_index
                alert("🟢 IN DISCOUNT" + tg + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
            if aNp and high >= eq - nd and not bull and cool
                aNp := false
                lastAl := bar_index
                alert("🔴 NEAR PREMIUM" + tg + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
            if aIp and high >= eq and not bull
                aIp := false
                lastAl := bar_index
                alert("🔴 IN PREMIUM" + tg + " | " + SYM + " | " + TF, alert.freq_once_per_bar)
            // re-arm after price has really left that half
            if barstate.isconfirmed
                if close >= eq + PD_REARM * rng
                    aNd := true
                    aId := true
                if close <= eq - PD_REARM * rng
                    aNp := true
                    aIp := true
    0
 
PdRng pdAct = not na(pdRBu) ? pdRBu : pdRBe
f_pdAl(na(pdAct) ? na : pdAct.hi, na(pdAct) ? na : pdAct.lo, na(pdAct) ? na : pdAct.t0 * pdAct.dir, i_alPD and i_pd_on and not na(pdAct) and bar_index > pdAct.born, true, "")
 
 
// ─────────── drawing: one reusable set per timeframe, same colours as the chart range ───────────
type PdV
    box   bP
    box   bD
    line  eq
    label lE
 
f_pdvNew() =>
    PdV.new(box.new(time, close, time, close, xloc = xloc.bar_time, bgcolor = PD_NONE, border_color = PD_NONE, text_size = size.small, text_color = PD_NONE, text_halign = text.align_right, text_valign = text.align_top),
     box.new(time, close, time, close, xloc = xloc.bar_time, bgcolor = PD_NONE, border_color = PD_NONE, text_size = size.small, text_color = PD_NONE, text_halign = text.align_right, text_valign = text.align_bottom),
     line.new(time, close, time, close, xloc = xloc.bar_time, color = PD_NONE, style = line.style_dashed, width = 1),
     label.new(time, close, "", xloc = xloc.bar_time, style = label.style_label_left, color = PD_NONE, textcolor = PD_NONE, size = size.small))
 
f_pdvSet(PdV v, bool on, int d, float h, float l, int t0, string tag) =>
    bool show = on and d != 0 and not na(h) and not na(l) and not na(t0)
    if show
        int   tR  = time + 10 * PD_TFMS
        float eqv = (h + l) / 2
        v.bP.set_lefttop(t0, h)
        v.bP.set_rightbottom(tR, eqv)
        v.bD.set_lefttop(t0, eqv)
        v.bD.set_rightbottom(tR, l)
        v.eq.set_xy1(t0, eqv)
        v.eq.set_xy2(tR, eqv)
        v.lE.set_xy(tR, eqv)
        v.lE.set_text(tag + " EQ 50%")
    v.bP.set_bgcolor(show ? PD_PREM : PD_NONE)
    v.bP.set_text_color(show ? PD_TXT : PD_NONE)
    v.bD.set_bgcolor(show ? PD_DISC : PD_NONE)
    v.bD.set_text_color(show ? PD_TXT : PD_NONE)
    v.eq.set_color(show ? PD_EQ : PD_NONE)
    v.lE.set_textcolor(show ? PD_TXT : PD_NONE)
 
var PdV pdvW = f_pdvNew()
var PdV pdvD = f_pdvNew()
var PdV pdv4 = f_pdvNew()
var PdV pdv1 = f_pdvNew()
if barstate.islast
    f_pdvSet(pdvW, pdOkW, pdWd, pdWH, pdWL, pdWt, "W")
    f_pdvSet(pdvD, pdOkD, pdDd, pdDH, pdDL, pdDt, "D")
    f_pdvSet(pdv4, pdOk4, pd4d, pd4H, pd4L, pd4t, "4H")
    f_pdvSet(pdv1, pdOk1, pd1d, pd1H, pd1L, pd1t, "1H")
 
// ─────────── PD DASHBOARD: W / D / 4H / 1H (checkboxes only draw) ───────────
// ZONE : PREM / EQ (within 5% of the range around 50%) / DISC / ABOVE / BELOW the range
// 50%  : ✓ price already traded to the 50% after the range extreme · ✗ not yet
f_pdRow(table t, int row, string tag, int d, float h, float l, float rx) =>
    bool   has = d != 0 and not na(h) and not na(l)
    float  eqv = has ? (h + l) / 2 : na
    float  rg  = has ? h - l : na
    string zn  = not has ? "—" : close > h ? "ABOVE" : close < l ? "BELOW" : math.abs(close - eqv) <= 0.05 * rg ? "EQ" : close > eqv ? "PREM" : "DISC"
    bool   hit = has and not na(rx) and (d == 1 ? rx <= eqv : rx >= eqv)
    bool   up  = zn == "DISC" or zn == "BELOW"
    bool   dn  = zn == "PREM" or zn == "ABOVE"
    f_db(t, 0, row, tag, DB_LBL, DB_BG)
    if has
        f_db(t, 1, row, d == 1 ? "▲" : "▼", d == 1 ? DB_UPT : DB_DNT, d == 1 ? DB_UPB : DB_DNB)
        f_db(t, 2, row, zn, dn ? DB_DNT : up ? DB_UPT : DB_ORT, dn ? DB_DNB : up ? DB_UPB : DB_ORB)
        f_db(t, 3, row, hit ? "✓" : "✗", hit ? DB_UPT : DB_NET, DB_BG)
    else
        f_db(t, 1, row, "—", DB_NET, DB_BG)
        f_db(t, 2, row, "—", DB_NET, DB_BG)
        f_db(t, 3, row, "—", DB_NET, DB_BG)
    has ? d : 0
 
// deepest pullback so far = closed candles of that TF + the developing candle
f_rxNow(int d, float rx, float cl, float ch) =>
    d == 1 ? (na(rx) ? cl : math.min(rx, cl)) : d == -1 ? (na(rx) ? ch : math.max(rx, ch)) : na
 
// chart-engine range (used only when the chart itself is on W / D / 4H / 1H)
f_pdChart() =>
    int   cd = 0
    float ch = na
    float cl = na
    float cx = na
    if not na(pdRBu)
        cd := 1
        ch := pdRBu.hi
        cl := pdRBu.lo
        int m = math.min(bar_index - pdRBu.xBar, 599)
        if m > 0
            for i = 0 to m - 1
                cx := na(cx) ? f_pdG(pdBL, i) : math.min(cx, f_pdG(pdBL, i))
    else if not na(pdRBe)
        cd := -1
        ch := pdRBe.hi
        cl := pdRBe.lo
        int m = math.min(bar_index - pdRBe.xBar, 599)
        if m > 0
            for i = 0 to m - 1
                cx := na(cx) ? f_pdG(pdBH, i) : math.max(cx, f_pdG(pdBH, i))
    [cd, ch, cl, cx]
 
var table pdTb = table.new(position.top_right, 4, 7, frame_color = DB_FRAME, frame_width = 2, border_color = DB_FRAME, border_width = 1)
if barstate.islast
    pdTb.clear(0, 0, 3, 6)
    if i_pdTbl and PDC_SEC <= 604800
        f_db(pdTb, 0, 0, DB_NAME, DB_TTL, DB_BG)
        pdTb.merge_cells(0, 0, 3, 0)
        f_db(pdTb, 0, 1, "TF",    DB_LBL, DB_BG)
        f_db(pdTb, 1, 1, "BIAS", DB_LBL, DB_BG)
        f_db(pdTb, 2, 1, "ZONE",  DB_LBL, DB_BG)
        f_db(pdTb, 3, 1, "50%",   DB_LBL, DB_BG)
        [cd, ch, cl, cx] = f_pdChart()
        int nBu = 0
        int nBe = 0
        int r   = 2
        int v   = 0
        if PDC_SEC == 604800
            v := f_pdRow(pdTb, r, "W", cd, ch, cl, cx)
        else
            v := f_pdRow(pdTb, r, "W", pdWd, pdWH, pdWL, pdWR)
        nBu += v == 1 ? 1 : 0
        nBe += v == -1 ? 1 : 0
        r += 1
        if PDC_SEC <= 86400
            if PDC_SEC == 86400
                v := f_pdRow(pdTb, r, "D", cd, ch, cl, cx)
            else
                v := f_pdRow(pdTb, r, "D", pdDd, pdDH, pdDL, pdDR)
            nBu += v == 1 ? 1 : 0
            nBe += v == -1 ? 1 : 0
            r += 1
        if PDC_SEC <= 14400
            if PDC_SEC == 14400
                v := f_pdRow(pdTb, r, "4H", cd, ch, cl, cx)
            else
                v := f_pdRow(pdTb, r, "4H", pd4d, pd4H, pd4L, pd4R)
            nBu += v == 1 ? 1 : 0
            nBe += v == -1 ? 1 : 0
            r += 1
        if PDC_SEC <= 3600
            if PDC_SEC == 3600
                v := f_pdRow(pdTb, r, "1H", cd, ch, cl, cx)
            else
                v := f_pdRow(pdTb, r, "1H", pd1d, pd1H, pd1L, pd1R)
            nBu += v == 1 ? 1 : 0
            nBe += v == -1 ? 1 : 0
            r += 1
        // BIAS: how many timeframes agree
        int    nT  = nBu + nBe
        bool   mix = nT == 0 or nBu == nBe
        string bs  = mix ? "MIXED" : nBu > nBe ? "▲ BULLISH " + str.tostring(nBu) + "/" + str.tostring(nT) : "▼ BEARISH " + str.tostring(nBe) + "/" + str.tostring(nT)
        f_db(pdTb, 0, r, "HTF", DB_LBL, DB_BG)
        f_db(pdTb, 1, r, bs, mix ? DB_NET : nBu > nBe ? DB_UPT : DB_DNT, mix ? DB_NEB : nBu > nBe ? DB_UPB : DB_DNB)
        pdTb.merge_cells(1, r, 3, r)
 
// ═══════════════════════════════════════════════════════════════════════
//  MERGE LEVELS — session H/L, liquidity (BSL/SSL) and key levels (opens, PD/PW/PM)
//  that sit on the same price (within ATR(200)/12) become ONE line with all names:
//  e.g. "LDN L + SSL + PDL". The first line keeps its colour and spans the whole group.
// ═══════════════════════════════════════════════════════════════════════
if barstate.islast
    color mNone = #ffffff00
    array<line>  mL = array.new<line>()
    array<label> mB = array.new<label>()
    if sesLines.size() > 0
        for i = 0 to sesLines.size() - 1
            mL.push(sesLines.get(i))
            mB.push(sesLbls.get(i))
    if lqLines.size() > 0
        for i = 0 to lqLines.size() - 1
            mL.push(lqLines.get(i))
            mB.push(lqLbls.get(i))
    if klLines.size() > 0
        for i = 0 to klLines.size() - 1
            mL.push(klLines.get(i))
            mB.push(klLbls.get(i))
    int n = mL.size()
    if n > 1
        array<bool> used = array.new<bool>(n, false)
        for i = 0 to n - 2
            if not used.get(i)
                line   li  = mL.get(i)
                float  yi  = li.get_y1()
                string txt = mB.get(i).get_text()
                int    x1  = li.get_x1()
                int    x2  = li.get_x2()
                bool   mg  = false
                for j = i + 1 to n - 1
                    if not used.get(j)
                        line lj = mL.get(j)
                        if math.abs(lj.get_y1() - yi) <= lqKeyTol
                            used.set(j, true)
                            mg  := true
                            txt := txt + " + " + mB.get(j).get_text()
                            x1  := math.min(x1, lj.get_x1())
                            x2  := math.max(x2, lj.get_x2())
                            lj.set_color(mNone)
                            mB.get(j).set_textcolor(mNone)
                            mB.get(j).set_text("")   // empty text = merged away (used by CLEAN CHART)
                if mg
                    li.set_x1(x1)
                    li.set_x2(x2)
                    mB.get(i).set_text(txt)
                    mB.get(i).set_x(x2)
 
// ═══ HTF FVG AS LINE: one line at the near edge (bull = top, bear = bottom) instead of the box ═══
var array<line>  hfLn = array.new<line>()
var array<label> hfLb = array.new<label>()
var array<line>  hfTs = array.new<line>()   // "T" size marker: stem from the near edge to the far edge
var array<line>  hfTc = array.new<line>()   //                  cap on the far edge
if barstate.islast
    while hfLn.size() > 0
        line.delete(hfLn.pop())
    while hfTs.size() > 0
        line.delete(hfTs.pop())
    while hfTc.size() > 0
        line.delete(hfTc.pop())
    while hfLb.size() > 0
        label.delete(hfLb.pop())
    if i_hfLine and hfBoxes.size() > 0
        for i = 0 to hfBoxes.size() - 1
            box   hb  = hfBoxes.get(i)
            int   d   = hfDirs.get(i)
            bool  inv = hfInv.get(i)
            color c   = inv ? (d == 1 ? #2962ff : #f23645) : (d == 1 ? #26a69a : #000000)
            float y   = d == 1 ? hb.get_top() : hb.get_bottom()
            hb.set_bgcolor(HF_NONE)
            hb.set_border_color(HF_NONE)
            hb.set_text_color(HF_NONE)
            int   x1  = math.max(hb.get_left(), bar_index - 4900)
            int   x2  = hb.get_right()
            hfLn.push(line.new(x1, y, x2, y, xloc = xloc.bar_index, color = c, width = 1, style = inv ? line.style_dashed : line.style_solid))
            // GAP SIZE "T": from the line to the other edge of the gap, with a short cap there
            float yF  = d == 1 ? hb.get_bottom() : hb.get_top()
            int   xm  = int((x1 + x2) / 2)
            int   cw  = math.max(2, int((x2 - x1) / 6))
            // only for a gap that is small for this chart (<= 3x ATR), or a big one price is inside now
            bool  tOk = hb.get_top() - hb.get_bottom() <= 3 * nz(smtAtr) or (close < hb.get_top() and close > hb.get_bottom())
            hfTs.push(tOk ? line.new(xm, y, xm, yF, xloc = xloc.bar_index, color = c, width = 1) : na)
            hfTc.push(tOk ? line.new(xm - cw, yF, xm + cw, yF, xloc = xloc.bar_index, color = c, width = 1) : na)
            hfLb.push(label.new(hb.get_right(), y, (d == 1 ? "BULL " : "BEAR ") + (inv ? "IFVG " : "FVG ") + f_secName(hfSec.get(i)), xloc = xloc.bar_index, style = label.style_label_left, color = HF_NONE, textcolor = c, size = size.small))
 
// ═══════════════════════════════════════════════════════════════════════
//  CISD + IFVG (no SMT needed) — only after LIQUIDITY is taken
//  The series that delivered price into the low (high) must have traded through a key level
//  (sessions, PD/PW/PM, opens, NDOG/NWOG), a BSL/SSL pool or a right-side HTF FVG / IFVG.
//  Runs at the end of the bar, when every level of this bar is known.
// ═══════════════════════════════════════════════════════════════════════
f_in(float l, float a, float b) => not na(l) and not na(a) and not na(b) and l >= math.min(a, b) and l <= math.max(a, b)
 
// each key level can trigger ONE CISD per direction (no repeats while price chops around it)
var array<float> ciUsedBu = array.new<float>()
var array<float> ciUsedBe = array.new<float>()
array<float> keyLv = array.from(asiaH, asiaL, lonH, lonL, nyH, nyL, pdh, pdl, pdc, pwh, pwl, pwc, pmh, pml, pmc, midO, o830, o930, ndTop, ndBot, nwTop, nwBot)
 
// first key level inside the span the series travelled [a, b] that has not produced a CISD yet (na = none)
f_keyNew(float a, float b, array<float> used) =>
    float hit = na
    for lv in keyLv
        if na(hit) and f_in(lv, a, b)
            bool seen = false
            if used.size() > 0
                for u in used
                    seen := seen or math.abs(u - lv) <= lqKeyTol
            if not seen
                hit := lv
    hit
 
// ─────────── CISD ENGINE (run based) ───────────
// Concept credit: "CISD Projections" © LuxAlgo (CC BY-NC-SA 4.0) — rewritten here, personal use.
// RUN  = consecutive candles closing above (bull run) / below (bear run) the previous close.
// CISD = during the NEXT run, a close that crosses the OPEN of the previous run:
//        bear run → close crosses ABOVE its open = bullish CISD · bull run → close crosses BELOW = bearish CISD
// The run must have >= 2 candles and must have made the 20-candle low (bear run) / high (bull run).
// One CISD per run; the chance ends when the following run ends.
bool rUp    = close >= close[1]
bool rDn    = close < close[1]
bool newRun = (rUp and rDn[1]) or (rDn and rUp[1])
 
var int   cDir = 0
var float cOpn = na
var float cTop = na
var float cBot = na
var int   cTopT = na
var int   cBotT = na
var int   cBars = 0
var int   cStT = na
 
var int   pDir = 0
var float pOpn = na
var float pTop = na
var float pBot = na
var int   pTopT = na
var int   pBotT = na
var int   pBars = 0
var int   pStT = na
var float pHH = na
var float pLL = na
var bool  pTrig = true
 
bool  cBu   = false
bool  cBe   = false
float atrRun = ta.atr(14)[2]   // ATR before a single-candle run (for the displacement check)
const int CI_WIN = 30
var bool  aBeOn = false
var float aBeOpn = na
var float aBeTop = na
var int   aBeTopT = na
var int   aBeStT = na
var int   aBeBar = na
var bool  aBuOn = false
var float aBuOpn = na
var float aBuBot = na
var int   aBuBotT = na
var int   aBuStT = na
var int   aBuBar = na
var label dbArmBu = na   // IFVG DEBUG
var label dbArmBe = na
f_dbArm(label old, int t, float y, bool low_) =>
    if not na(old) and old.get_text() == "ARM"
        old.set_text("ARM → REPLACED")
    label.new(t, y, "ARM", xloc = xloc.bar_time, style = low_ ? label.style_label_up : label.style_label_down, color = #FFF59D, textcolor = color.black, size = size.tiny, textalign = text.align_left)
float exHi  = na
int   exHiT = na
float exLo  = na
int   exLoT = na
 
if barstate.isconfirmed
    if newRun or cDir == 0
        // the run that just ended becomes the one waiting for its CISD
        pDir  := cDir
        pOpn  := cOpn
        pTop  := cTop
        pBot  := cBot
        pTopT := cTopT
        pBotT := cBotT
        pBars := cBars
        pStT  := cStT
        pHH   := hh20
        pLL   := ll20
        pTrig := false
        cDir  := rUp ? 1 : -1
        cOpn  := open
        cTop  := high
        cBot  := low
        cTopT := time
        cBotT := time
        cBars := 1
        cStT  := time
        // a finished run that made the 20-candle extreme ARMS a CISD: >= 2 candles, or ONE
        // displacement candle (body >= 1x ATR before it) — a single big candle into the low / high
        bool runOk = pBars >= 2 or (pBars == 1 and math.abs(close[1] - pOpn) >= nz(atrRun, 0))
        if runOk and not na(pOpn)
            if pDir == 1 and pTop == pHH
                aBeOn  := true
                aBeOpn := pOpn
                aBeTop := pTop
                aBeTopT := pTopT
                aBeStT := pStT
                aBeBar := bar_index
                if i_ivDbg
                    dbArmBe := f_dbArm(dbArmBe, pTopT, pTop, false)
            if pDir == -1 and pBot == pLL
                aBuOn  := true
                aBuOpn := pOpn
                aBuBot := pBot
                aBuBotT := pBotT
                aBuStT := pStT
                aBuBar := bar_index
                if i_ivDbg
                    dbArmBu := f_dbArm(dbArmBu, pBotT, pBot, true)
    else
        cBars += 1
        if high > cTop
            cTop  := high
            cTopT := time
        if low < cBot
            cBot  := low
            cBotT := time
    // armed until the extreme is taken or CI_WIN candles pass (distribution tops / accumulation lows count too)
    // a wick beyond the extreme (candle that closes back the other way) only MOVES the extreme;
    // the CISD level (open of the run that delivered price there) stays. Ends after CI_WIN candles.
    if aBeOn and high > aBeTop
        aBeTop  := high
        aBeTopT := time
    if aBuOn and low < aBuBot
        aBuBot  := low
        aBuBotT := time
    if aBeOn and bar_index - aBeBar > CI_WIN
        aBeOn := false
        f_dbSet(dbArmBe, "NO CISD (30)")
    if aBuOn and bar_index - aBuBar > CI_WIN
        aBuOn := false
        f_dbSet(dbArmBu, "NO CISD (30)")
    cBe := aBeOn and close < aBeOpn and close[1] >= aBeOpn
    cBu := aBuOn and close > aBuOpn and close[1] <= aBuOpn
    if cBe
        aBeOn := false
        exHi  := aBeTop
        exHiT := aBeTopT
    if cBu
        aBuOn := false
        exLo  := aBuBot
        exLoT := aBuBotT
 
int   ciBuX_ = aBuStT
float ciBuY_ = aBuOpn
int   ciBeX_ = aBeStT
float ciBeY_ = aBeOpn
 
// optional liquidity condition: the run into the extreme traded through a level / pool / HTF gap
float kBu = cBu ? f_keyNew(exLo, aBuOpn, ciUsedBu) : na
float kBe = cBe ? f_keyNew(aBeOpn, exHi, ciUsedBe) : na
bool  lqBu = not na(kBu) or (not na(lqSwLoT) and lqSwLoT >= aBuStT) or (not na(hfTapBuT) and hfTapBuT >= aBuStT)
bool  lqBe = not na(kBe) or (not na(lqSwHiT) and lqSwHiT >= aBeStT) or (not na(hfTapBeT) and hfTapBeT >= aBeStT)
bool  liqBu = cBu and (not i_ciLq or lqBu)
bool  liqBe = cBe and (not i_ciLq or lqBe)
 
if liqBu and not na(kBu)
    ciUsedBu.push(kBu)
    if ciUsedBu.size() > 60
        ciUsedBu.shift()
if liqBe and not na(kBe)
    ciUsedBe.push(kBe)
    if ciUsedBe.size() > 60
        ciUsedBe.shift()
if liqBu
    lqSwLoT := na
    hfTapBuT := na
if liqBe
    lqSwHiT := na
    hfTapBeT := na
 
if i_cisd and liqBu
    f_cisd(ciBuX_, ciBuY_, i_ciBu)
if i_cisd and liqBe
    f_cisd(ciBeX_, ciBeY_, i_ciBe)
// key highs / lows + dealing range for the IFVG liquidity filters
ivKP.clear()
ivKN.clear()
ivKH.clear()
for [i_, v_] in array.from(asiaH, asiaL, lonH, lonL, nyH, nyL, pdh, pdl, pwh, pwl, pmh, pml)
    ivKP.push(v_)
    ivKH.push(i_ % 2 == 0)
for nm_ in array.from("ASIA H", "ASIA L", "LDN H", "LDN L", "NY H", "NY L", "PDH", "PDL", "PWH", "PWL", "PMH", "PML")
    ivKN.push(nm_)
ivPP.clear()
ivPH.clear()
for v_ in lqHiLvl
    ivPP.push(v_)
    ivPH.push(true)
for v_ in lqLoLvl
    ivPP.push(v_)
    ivPH.push(false)
ivDrH := timeframe.in_seconds() < 3600 ? pd1H : pd4H
ivDrL := timeframe.in_seconds() < 3600 ? pd1L : pd4L
var array<Sig> ivOwnS = array.new<Sig>(2)   // 0 = bullish (after a low), 1 = bearish (after a high)
if i_ifvg or i_alCiF
    // NO CISD WAIT: the IFVG search starts as soon as a 20-candle high / low is ARMED (and follows
    // the extreme when a wick moves it), so the IFVG appears on the candle that closes through the gap.
    // A CISD later only marks it. A NEW extreme always takes over (like before): the previous IFVG
    // of that side stays in the history as a trace.
    Sig o0 = ivOwnS.get(0)
    Sig o1 = ivOwnS.get(1)
    if aBuOn and (na(o0) or o0.xT != aBuBotT)
        f_ifvgFreeze(o0)
        ivOwnS.set(0, Sig.new(bear = false, lvl = aBuBot, xT = aBuBotT, cDone = true, std = true, dbl = dbArmBu))
    if aBeOn and (na(o1) or o1.xT != aBeTopT)
        f_ifvgFreeze(o1)
        ivOwnS.set(1, Sig.new(bear = true, lvl = aBeTop, xT = aBeTopT, cDone = true, std = true, dbl = dbArmBe))
    // CISD on an extreme that has no search yet (e.g. armed window over) → start one now
    if liqBu
        Sig c0 = ivOwnS.get(0)
        if na(c0) or c0.xT != exLoT
            f_ifvgFreeze(c0)
            ivOwnS.set(0, Sig.new(bear = false, lvl = exLo, xT = exLoT, cDone = true, std = true, dbl = dbArmBu))
        Sig cc0 = ivOwnS.get(0)
        cc0.cisd := true
        if na(cc0.ciT)
            cc0.ciX := ciBuX_
            cc0.ciY := ciBuY_
            cc0.ciT := time
        if na(cc0.ivKey)
            f_dbSet(dbArmBu, "CISD ✓")
    if liqBe
        Sig c1 = ivOwnS.get(1)
        if na(c1) or c1.xT != exHiT
            f_ifvgFreeze(c1)
            ivOwnS.set(1, Sig.new(bear = true, lvl = exHi, xT = exHiT, cDone = true, std = true, dbl = dbArmBe))
        Sig cc1 = ivOwnS.get(1)
        cc1.cisd := true
        if na(cc1.ciT)
            cc1.ciX := ciBeX_
            cc1.ciY := ciBeY_
            cc1.ciT := time
        if na(cc1.ivKey)
            f_dbSet(dbArmBe, "CISD ✓")
    for k = 0 to 1
        Sig so = ivOwnS.get(k)
        if not na(so) and not so.swept and bar_index > 0 and (so.bear ? high > so.lvl : low < so.lvl)
            so.swept := true
        f_ifvgUpdate(so)
        // CISD drawn only on an IFVG that had one (once)
        if i_ivCisd and i_ifvg and not na(so) and so.cisd and not so.ciDone and not na(so.ivKey) and not na(so.ciT) and not na(so.ciX)
            so.ciDone := true
            int   xR_ = so.ciT + 4 * timeframe.in_seconds() * 1000
            color cc_ = so.bear ? i_ciBe : i_ciBu
            ciL.push(line.new(so.ciX, so.ciY, xR_, so.ciY, xloc = xloc.bar_time, color = cc_, style = line.style_solid, width = 1))
            ciB.push(label.new(xR_, so.ciY, "CISD", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = cc_, size = size.small))
            while ciL.size() > i_ciMax
                line.delete(ciL.shift())
                label.delete(ciB.shift())
 
// SOURCE GAP: drawn while the IFVG is open — removed on target, stop taken, or the IFVG failing
if srS.size() > 0
    for i = srS.size() - 1 to 0
        Sig  t   = srS.get(i)
        bool stp = not na(t.srStop) and (t.bear ? high > t.srStop : low < t.srStop)
        if t.tgHit or t.ivEnd or stp
            srS.remove(i)
            box.delete(srB.remove(i))
        else
            srB.get(i).set_right(time + 8 * timeframe.in_seconds() * 1000)
 
// TARGET tracking: reached → 🎯 into the IFVG box, line + 🎯 removed 4 candles later
//                  stop (swept high / low) taken first → line removed
if tgS.size() > 0
    for i = tgS.size() - 1 to 0
        Sig  t   = tgS.get(i)
        int  hb_ = tgHB.get(i)
        bool del = false
        if na(hb_)
            bool hit = t.bear ? low <= t.tgL : high >= t.tgL
            bool stp = not na(t.tgStop) and (t.bear ? high > t.tgStop : low < t.tgStop)
            if hit
                t.tgHit := true
                box b = na(t.ivBox) ? t.trB : t.ivBox
                if not na(b)
                    b.set_text(f_ivTxt(t))
                tgHB.set(i, bar_index)
            else if stp
                del := true
        else if bar_index - hb_ >= 4
            del := true
        if del
            tgS.remove(i)
            tgHB.remove(i)
            line.delete(tgLn.remove(i))
            label.delete(tgLb.remove(i))
 
 
// ═══════════════════════════════════════════════════════════════════════
//  8 AM BREAKOUT — 2 session ranges (Bahrain time)
//  The high / low lines follow the running high / low of the session window, then lock and
//  extend to the freeze hour. Red middle line = SL. Alert: a chart candle CLOSES beyond the range
//  (close + half of the body beyond it) — make the alert on the timeframe you want.
// ═══════════════════════════════════════════════════════════════════════
BHR = "Asia/Bahrain"
 
f_boAlert(string msg) =>
    if i_boAl
        alert(msg, alert.freq_once_per_bar_close)
 
pad2(int h) =>
    h < 10 ? "0" + str.tostring(h) : str.tostring(h)
 
color dayLblColor = color.black
 
bo1En      = input.bool(true, "Enable", group="Breakout 1", inline="bo1")
bo1Session = input.session("0800-0831", "Session", group="Breakout 1", inline="bo1")
bo1Freeze  = input.int(15, "Freeze Hour", minval=0, maxval=23, group="Breakout 1", tooltip = "The lines stop at this hour (Bahrain). If it is earlier than the session, it is the next day.")
 
bo2En      = input.bool(true, "Enable", group="Breakout 2", inline="bo2")
bo2Session = input.session("1600-1631", "Session", group="Breakout 2", inline="bo2")
bo2Freeze  = input.int(20, "Freeze Hour", minval=0, maxval=23, group="Breakout 2", tooltip = "The lines stop at this hour (Bahrain). If it is earlier than the session, it is the next day.")
 
type boState
    line  hLine
    line  lLine
    line  midLineL
    line  midLineR
    label midLabel
    int   startBar
    int   startTime
    int   freezeTime             // exact time the levels expire (freeze hour)
    float sessHigh
    float sessLow
    bool  linesFrozen = true
    bool  sessionEnded = false
    bool  upAlerted = false
    bool  downAlerted = false
    label dayLabel
 
var boState[] boArr = array.new<boState>()
// past breakout drawings (history): lines + labels with the start time of their session
var array<line>  boHL = array.new<line>()
var array<int>   boHLT = array.new<int>()
var array<label> boHB = array.new<label>()
var array<int>   boHBT = array.new<int>()
f_boArchive(boState bo) =>
    if not na(bo.hLine)
        for ln in array.from(bo.hLine, bo.lLine, bo.midLineL, bo.midLineR)
            boHL.push(ln)
            boHLT.push(bo.startTime)
        for lb in array.from(bo.midLabel, bo.dayLabel)
            boHB.push(lb)
            boHBT.push(bo.startTime)
// remove history older than N days (or all of it when HISTORY is off)
f_boPrune() =>
    int cut = i_boHist ? time - i_boDays * 86400000 : time + 1
    while boHL.size() > 0 and boHLT.first() < cut
        line.delete(boHL.shift())
        int _a = boHLT.shift()
    while boHB.size() > 0 and boHBT.first() < cut
        label.delete(boHB.shift())
        int _b = boHBT.shift()
if barstate.isfirst
    for i = 0 to 1
        boArr.push(boState.new())
 
gapHalf = 3
 
// All drawings use xloc.bar_time, so lines can reach the freeze hour on any timeframe.
updateMidSplit(boState bo, float midY, int endT) =>
    int barMs = timeframe.in_seconds() * 1000
    int gapMs = gapHalf * barMs
    int midT  = int(math.avg(bo.startTime, endT))
    if endT - bo.startTime >= gapMs * 2
        line.set_xy1(bo.midLineL, bo.startTime, midY)
        line.set_xy2(bo.midLineL, midT - gapMs, midY)
        line.set_xy1(bo.midLineR, midT + gapMs, midY)
        line.set_xy2(bo.midLineR, endT, midY)
    else
        line.set_xy1(bo.midLineL, bo.startTime, midY)
        line.set_xy2(bo.midLineL, endT, midY)
        line.set_xy1(bo.midLineR, endT, midY)
        line.set_xy2(bo.midLineR, endT, midY)
    label.set_xy(bo.midLabel, midT, midY)
 
processBreakout(bool en, string sessionRange, int freezeHour, int idx, string tag) =>
    bo = array.get(boArr, idx)
    if en
        t = time(timeframe.period, sessionRange, BHR)
        inSess = not na(t)
        inSessPrev = not na(time(timeframe.period, sessionRange, BHR)[1])
 
        freezeStr = pad2(freezeHour) + "00-" + pad2(freezeHour) + "01"
        t7 = time(timeframe.period, freezeStr, BHR)
        in7 = not na(t7)
        in7Prev = not na(time(timeframe.period, freezeStr, BHR)[1])
 
        if inSess and not inSessPrev
            f_boArchive(bo)
            bo.startBar := bar_index
            bo.startTime := time
            bo.sessHigh := high
            bo.sessLow  := low
            float midY0 = (bo.sessHigh + bo.sessLow) / 2
            bo.hLine    := line.new(time, bo.sessHigh, time, bo.sessHigh, xloc=xloc.bar_time, color=color.black, width=2, force_overlay=true)
            bo.lLine    := line.new(time, bo.sessLow, time, bo.sessLow, xloc=xloc.bar_time, color=color.black, width=2, force_overlay=true)
            bo.midLineL := line.new(time, midY0, time, midY0, xloc=xloc.bar_time, color=color.red, width=2, force_overlay=true)
            bo.midLineR := line.new(time, midY0, time, midY0, xloc=xloc.bar_time, color=color.red, width=2, force_overlay=true)
            bo.midLabel := label.new(time, midY0, "SL", xloc=xloc.bar_time, style=label.style_label_center, color=color(na), textcolor=color.red, size=size.normal, force_overlay=true)
            // Day name (e.g. "Fri") on the right end of the top line
            bo.dayLabel := label.new(time, bo.sessHigh, str.format_time(time, "EEE", BHR), xloc=xloc.bar_time, style=label.style_label_lower_right, color=color(na), textcolor=dayLblColor, size=size.normal, force_overlay=true)
            bo.linesFrozen := false
            bo.upAlerted   := false
            bo.downAlerted := false
            bo.sessionEnded := false
            bo.freezeTime := na
        else if inSess
            bo.sessHigh := math.max(bo.sessHigh, high)
            bo.sessLow  := math.min(bo.sessLow, low)
            line.set_y1(bo.hLine, bo.sessHigh)
            line.set_y2(bo.hLine, bo.sessHigh)
            label.set_y(bo.dayLabel, bo.sessHigh)
            line.set_y1(bo.lLine, bo.sessLow)
            line.set_y2(bo.lLine, bo.sessLow)
            updateMidSplit(bo, (bo.sessHigh + bo.sessLow) / 2, time)
 
        // Freeze at the freeze hour (also by time, so a weekend / holiday can't keep an old range alive)
        if (in7 and not in7Prev) or (not na(bo.freezeTime) and time >= bo.freezeTime)
            bo.linesFrozen := true
 
        // back at the SL line → a new break can alert again
        if not na(bo.sessHigh) and not na(bo.sessLow)
            float midLevel = (bo.sessHigh + bo.sessLow) / 2
            if low <= midLevel and high >= midLevel
                bo.upAlerted := false
                bo.downAlerted := false
 
        if not bo.linesFrozen and not na(bo.hLine)
            if inSess
                line.set_x2(bo.hLine, time)
                line.set_x2(bo.lLine, time)
                label.set_x(bo.dayLabel, time)
                updateMidSplit(bo, (bo.sessHigh + bo.sessLow) / 2, time)
            else if not bo.sessionEnded
                bo.sessionEnded := true
                int todayFreezeTime = timestamp(BHR, year(time, BHR), month(time, BHR), dayofmonth(time, BHR), freezeHour, 0)
                int targetTime = todayFreezeTime <= time ? todayFreezeTime + 86400000 : todayFreezeTime
                bo.freezeTime := targetTime
                line.set_x2(bo.hLine, targetTime)
                line.set_x2(bo.lLine, targetTime)
                label.set_xy(bo.dayLabel, targetTime, bo.sessHigh)
                updateMidSplit(bo, (bo.sessHigh + bo.sessLow) / 2, targetTime)
 
        // BREAKOUT ALERT: the chart candle CLOSES beyond the range (close + half of the body beyond it)
        if barstate.isconfirmed and bo.sessionEnded and not bo.linesFrozen and not na(bo.sessHigh) and not na(bo.sessLow)
            float bodyMidN = (open + close) / 2
            if close > bo.sessHigh and bodyMidN > bo.sessHigh and not bo.upAlerted
                bo.upAlerted := true
                f_boAlert("🟢 " + tag + " BREAKOUT | " + SYM + " | " + TF)
            if close < bo.sessLow and bodyMidN < bo.sessLow and not bo.downAlerted
                bo.downAlerted := true
                f_boAlert("🔴 " + tag + " BREAKOUT | " + SYM + " | " + TF)
 
processBreakout(bo1En and i_bo and BO_TF_OK, bo1Session, bo1Freeze, 0, "BO1")
processBreakout(bo2En and i_bo and BO_TF_OK, bo2Session, bo2Freeze, 1, "BO2")
f_boPrune()
 
 
// ═══════════════════════════════════════════════════════════════════════
//  CLEAN CHART — no overlapping drawings
//  1. Zones (IFVG · HTF FVG / IFVG · NWOG · NDOG) that overlap (>= 50% of the smaller one)
//     become ONE box with all names: "IFVG + NWOG". Priority: IFVG > HTF FVG (higher TF first)
//     > NWOG > NDOG — the first keeps its box, the others are hidden.
//  2. A line (session · liquidity · key level) inside a zone or on its edge is hidden and its
//     name goes into the zone label: "BULL 1D + PDL".
//  3. FVG AS LINE: an HTF FVG line on the same price as a key line merges into that line:
//     "PDL + BULL FVG 1D".
// ═══════════════════════════════════════════════════════════════════════
if barstate.islast
    color cNone = #ffffff00
    // ── 0. HTF gap vs its own timeframe's dealing range ──
    if hfBoxes.size() > 0
        for i = 0 to hfBoxes.size() - 1
            int   sc = hfSec.get(i)
            float rH = sc >= 604800 ? pdWH : sc >= 86400 ? pdDH : sc >= 14400 ? pd4H : sc >= 3600 ? pd1H : na
            float rL = sc >= 604800 ? pdWL : sc >= 86400 ? pdDL : sc >= 14400 ? pd4L : sc >= 3600 ? pd1L : na
            int   rD = sc >= 604800 ? pdWd : sc >= 86400 ? pdDd : sc >= 14400 ? pd4d : sc >= 3600 ? pd1d : 0
            bool  ok = true
            if i_hfPd and rD != 0 and not na(rH) and not na(rL) and rH > rL
                box   hb = hfBoxes.get(i)
                float md = (hb.get_top() + hb.get_bottom()) / 2
                float eq = (rH + rL) / 2
                ok := hfDirs.get(i) == 1 ? md <= eq : md >= eq
            hfPdOk.set(i, ok)
    // visibility: right side of its range + near price + only the nearest HF_MAXN above and below
    array<bool> hVis = array.new<bool>(hfBoxes.size(), false)
    if hfBoxes.size() > 0
        array<float> dUp = array.new<float>()
        array<float> dDn = array.new<float>()
        for i = 0 to hfBoxes.size() - 1
            box hb = hfBoxes.get(i)
            if hfPdOk.get(i) and f_isNear(hb.get_top(), hb.get_bottom())
                if hb.get_bottom() > close
                    dUp.push(hb.get_bottom() - close)
                else if hb.get_top() < close
                    dDn.push(close - hb.get_top())
        dUp.sort()
        dDn.sort()
        float cutUp = i_showAll or dUp.size() <= HF_MAXN ? na : dUp.get(HF_MAXN - 1)
        float cutDn = i_showAll or dDn.size() <= HF_MAXN ? na : dDn.get(HF_MAXN - 1)
        for i = 0 to hfBoxes.size() - 1
            box hb = hfBoxes.get(i)
            // HTF gaps are NOT drawn (only the one an IFVG reversed from) — SHOW ALL draws them
            bool v = i_showAll and hfPdOk.get(i) and f_isNear(hb.get_top(), hb.get_bottom())
            if v and hb.get_bottom() > close and not na(cutUp)
                v := hb.get_bottom() - close <= cutUp
            if v and hb.get_top() < close and not na(cutDn)
                v := close - hb.get_top() <= cutDn
            hVis.set(i, v)
            // FVG AS LINE: same index as the box
            if not v and i_hfLine and i < hfLn.size()
                hfLn.get(i).set_color(cNone)
                hfLb.get(i).set_textcolor(cNone)
                hfLb.get(i).set_text("")
        // ── same level → only the BEST gap stays: in the right half of its own timeframe's dealing
        //    range (bull = discount, bear = premium) first, then the higher timeframe ──
        array<float> hRk = array.new<float>(hfBoxes.size(), 0.0)
        for i = 0 to hfBoxes.size() - 1
            box   hb = hfBoxes.get(i)
            int   sc = hfSec.get(i)
            float rH = sc >= 604800 ? pdWH : sc >= 86400 ? pdDH : sc >= 14400 ? pd4H : sc >= 3600 ? pd1H : na
            float rL = sc >= 604800 ? pdWL : sc >= 86400 ? pdDL : sc >= 14400 ? pd4L : sc >= 3600 ? pd1L : na
            bool  fit = false
            if not na(rH) and not na(rL) and rH > rL
                float md = (hb.get_top() + hb.get_bottom()) / 2
                fit := hfDirs.get(i) == 1 ? md <= (rH + rL) / 2 : md >= (rH + rL) / 2
            hRk.set(i, (fit ? 10000000.0 : 0.0) + sc)
        for i = 0 to hfBoxes.size() - 1
            for j = 0 to hfBoxes.size() - 1
                if j != i and hVis.get(i) and hVis.get(j)
                    box  bi = hfBoxes.get(i)
                    box  bj = hfBoxes.get(j)
                    // same level = the boxes overlap, OR their lines (near edge: bull top · bear bottom)
                    // are so close their names would sit on each other (bull + bear included)
                    float yi = hfDirs.get(i) == 1 ? bi.get_top() : bi.get_bottom()
                    float yj = hfDirs.get(j) == 1 ? bj.get_top() : bj.get_bottom()
                    float tl = math.max(lqKeyTol, 0.5 * nz(smtAtr, lqKeyTol))
                    bool same = (bi.get_top() > bj.get_bottom() and bj.get_top() > bi.get_bottom()) or math.abs(yi - yj) <= tl
                    if same
                        int lose = hRk.get(j) < hRk.get(i) or (hRk.get(j) == hRk.get(i) and j > i) ? j : i
                        hVis.set(lose, false)
                        if i_hfLine and lose < hfLn.size()
                            hfLn.get(lose).set_color(cNone)
                            hfLb.get(lose).set_textcolor(cNone)
                            hfLb.get(lose).set_text("")
    array<box>    zB  = array.new<box>()
    array<string> zN  = array.new<string>()
    array<line>   zCe = array.new<line>()
    array<int>    zK  = array.new<int>()   // 0 = chart IFVG · 1 = HTF FVG/IFVG · 2 = NDOG/NWOG
    // ── restore + collect zones (in priority order) ──
    for k = 0 to 1
        Sig so = ivOwnS.get(k)
        if not na(so) and not na(so.ivBox) and i_ifvg
            so.ivBox.set_bgcolor(so.bear ? IV_BE : IV_BU)
            so.ivBox.set_text(f_ivTxt(so))
            zB.push(so.ivBox)
            zN.push(f_ivTxt(so))
            zCe.push(na)
            zK.push(0)
    if not i_hfLine and hfBoxes.size() > 0
        // higher timeframe first
        for bk in array.from("W", "1D", "4H", "1H", "30m", "15m")
            for i = 0 to hfBoxes.size() - 1
                if f_secName(hfSec.get(i)) == bk
                    box  hb  = hfBoxes.get(i)
                    int  d   = hfDirs.get(i)
                    bool inv = hfInv.get(i)
                    int  sl  = hfSlot.get(i)
                    color cB = inv ? (d == 1 ? hfIfBu : hfIfBe) : (d == 1 ? (sl == 1 ? hf1Bull : sl == 2 ? hf2Bull : sl == 3 ? hf3Bull : sl == 4 ? hf4Bull : hf5Bull) : (sl == 1 ? hf1Bear : sl == 2 ? hf2Bear : sl == 3 ? hf3Bear : sl == 4 ? hf4Bear : hf5Bear))
                    string nm = (d == 1 ? "BULL " : "BEAR ") + (inv ? "IFVG " : "") + f_secName(hfSec.get(i))
                    if hVis.get(i)
                        hb.set_bgcolor(cB)
                        hb.set_border_color(inv ? color.new(cB, 30) : HF_NONE)
                        hb.set_text_color(hfTxtCol)
                        hb.set_text(nm)
                        zB.push(hb)
                        zN.push(nm)
                        zCe.push(na)
                        zK.push(1)
                    else
                        hb.set_bgcolor(cNone)
                        hb.set_border_color(cNone)
                        hb.set_text_color(cNone)
    if not na(nwBox)
        zB.push(nwBox)
        zN.push("NWOG")
        zCe.push(nwCe)
        zK.push(2)
    if not na(ndBox)
        zB.push(ndBox)
        zN.push("NDOG")
        zCe.push(ndCe)
        zK.push(2)
    int nz_ = zB.size()
    array<bool> zHid = array.new<bool>(nz_, false)
    // ── 1. overlapping zones → one box ──
    if nz_ > 1
        for i = 0 to nz_ - 2
            if not zHid.get(i)
                box bi = zB.get(i)
                for j = i + 1 to nz_ - 1
                    if not zHid.get(j)
                        box   bj = zB.get(j)
                        float ov = math.min(bi.get_top(), bj.get_top()) - math.max(bi.get_bottom(), bj.get_bottom())
                        float hS = math.min(bi.get_top() - bi.get_bottom(), bj.get_top() - bj.get_bottom())
                        int  ki = zK.get(i)
                        int  kj = zK.get(j)
                        bool canMerge = ki == kj or (ki >= 1 and ki <= 2 and kj >= 1 and kj <= 2)
                        if canMerge and hS > 0 and ov >= 0.5 * hS
                            zHid.set(j, true)
                            zN.set(i, f_join(zN.get(i), zN.get(j)))
                            bj.set_bgcolor(cNone)
                            bj.set_border_color(cNone)
                            bj.set_text_color(cNone)
                            line ce = zCe.get(j)
                            if not na(ce)
                                ce.set_color(cNone)
    // ── 2. lines inside / on the edge of a zone → into the zone label ──
    array<line>  aL = array.new<line>()
    array<label> aB = array.new<label>()
    if sesLines.size() > 0
        for i = 0 to sesLines.size() - 1
            aL.push(sesLines.get(i))
            aB.push(sesLbls.get(i))
    if lqLines.size() > 0
        for i = 0 to lqLines.size() - 1
            aL.push(lqLines.get(i))
            aB.push(lqLbls.get(i))
    if klLines.size() > 0
        for i = 0 to klLines.size() - 1
            aL.push(klLines.get(i))
            aB.push(klLbls.get(i))
    int nKey = aL.size()   // key lines (time based) end here; HTF FVG lines follow
    // SHORT LINES: sessions · opens · PDH/PDL · PWH/PWL · PMH/PML only around the last candle
    // (11 candles back → 6 ahead, name at the end). BSL / SSL are not changed.
    int tfMs = timeframe.in_seconds() * 1000
    if i_klShort
        int tEnd = time + 6 * tfMs
        for ln in array.concat(array.copy(sesLines), klLines)
            ln.set_x1(time - 11 * tfMs)
            ln.set_x2(tEnd)
        for lb in array.concat(array.copy(sesLbls), klLbls)
            lb.set_x(tEnd)
    float mTol = math.max(lqKeyTol, 0.5 * nz(smtAtr, lqKeyTol))   // labels closer than this would overlap
    if hfLn.size() > 0
        for i = 0 to hfLn.size() - 1
            aL.push(hfLn.get(i))
            aB.push(hfLb.get(i))
    if aL.size() > 0
        for i = 0 to aL.size() - 1
            label lb = aB.get(i)
            string t = lb.get_text()
            if t != ""
                float y = aL.get(i).get_y1()
                bool  done = false
                if nz_ > 0
                    for z = 0 to nz_ - 1
                        if not done and not zHid.get(z)
                            box bz = zB.get(z)
                            if y <= bz.get_top() + lqKeyTol and y >= bz.get_bottom() - lqKeyTol
                                zN.set(z, f_join(zN.get(z), t))
                                aL.get(i).set_color(cNone)
                                lb.set_textcolor(cNone)
                                lb.set_text("")
                                done := true
                // 3. HTF FVG line on the same price as a key line → merge into the key line
                if not done and i >= nKey and nKey > 0
                    for k = 0 to nKey - 1
                        label kb = aB.get(k)
                        if not done and kb.get_text() != "" and math.abs(aL.get(k).get_y1() - y) <= mTol
                            kb.set_text(f_join(kb.get_text(), t))
                            aL.get(i).set_color(cNone)
                            lb.set_textcolor(cNone)
                            lb.set_text("")
                            done := true
    // ── 4. any two remaining labels that would overlap → one label with both names ──
    if aL.size() > 1
        for i = 0 to aL.size() - 2
            label li = aB.get(i)
            if li.get_text() != ""
                for j = i + 1 to aL.size() - 1
                    label lj = aB.get(j)
                    if lj.get_text() != "" and math.abs(aL.get(j).get_y1() - aL.get(i).get_y1()) <= mTol
                        li.set_text(f_join(li.get_text(), lj.get_text()))
                        aL.get(j).set_color(cNone)
                        lj.set_textcolor(cNone)
                        lj.set_text("")
    // ── write the joined names ──
    if nz_ > 0
        for z = 0 to nz_ - 1
            if not zHid.get(z)
                zB.get(z).set_text(zN.get(z))
 
// ── FVG AS LINE: the gap-size "T" follows its line (hidden when the line was hidden / merged) ──
if barstate.islast and hfTs.size() > 0
    for i = 0 to math.min(hfTs.size(), hfLb.size()) - 1
        // a hidden / merged HTF line always has its label text cleared
        if hfLb.get(i).get_text() == "" and not na(hfTs.get(i))
            hfTs.get(i).set_color(#ffffff00)
            hfTc.get(i).set_color(#ffffff00)

← 返回列表