MarketMaulers IFVG (Open Source)

AlphaTraderRyan · study · 3198 行 · 点赞 68 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════
//  MarketMaulers IFVG  ·  v6.44
//  ──────────────────────────────────────────────────────
//  Inversion Fair Value Gaps, graded.
//
//  A fair value gap is tracked silently. It inverts when a confirmed candle CLOSE
//  punches through its far side: a wick through never counts. A failed SIBI becomes
//  a bullish IFVG (support), a failed BISI a bearish IFVG (resistance). A zone dies
//  on a confirmed close back through the other side.
//
//  WHAT IS IN THIS FILE
//    · The inversion engine: gap tracking, the close-through trigger, the inversion
//      window, and the rule that duplicate detections are ignored.
//    · The checklist and the grade each setup prints with, including the liquidity
//      sweep in its Required and Graded modes.
//    · The trade plan: entry, stop, the standard deviation ladder, position size,
//      and the setup panel, which holds the last printed setup until a new one prints.
//    · Nearby liquidity, equal highs and lows, key levels, higher timeframe FVG
//      overlays and the low resistance liquidity run. These engines are shared with
//      other tools in this suite.
//    · One alert() transport with its own dedupe.
//
//  The Delivery check can grade history differently from live. That limit is stated
//  in the description as well.
//
//  Display only. It marks zones and a plan. It places no orders.
//  Built by Market Maulers
// ═══════════════════════════════════════════════════════════════════════
indicator("MarketMaulers IFVG", shorttitle="MM IFVG", overlay=true,
     max_boxes_count=500, max_labels_count=500, max_lines_count=500)
 
// v6.44: RE10143 FIX (live error 27/9/2026 in the sibling raid tool on bar 20493, same LRLR engine: "requested historical offset (1600)
// is beyond the historical buffer's limit (1599)" at the LRLR label.set_xy).
// WHY a line with no [n] throws a history error: a drawing given xloc.bar_index coords has
// them converted to TIME internally, so an x far back is a hidden time[bar_index - x] read.
// Pine sizes the buffer by scanning the source for offsets it can see; a runtime anchor is
// invisible to that scan, so the guess ran out mid-chart. Two parts, both needed:
//   1. max_bars_back(time, 5000) sizes the buffer for `time` only (the one series involved).
//      NOT the indicator() parameter, which would size every series and slow the load.
//   2. Every far-back clamp now uses MAX_BACK = 4900, under the 5,000 buffer ceiling. The
//      old 9,500 clamp guarded the ~10,000-bar drawing limit but was still past the buffer.
// Same ported LRLR engine as the sibling raid tool, so the same crash was waiting here.
max_bars_back(time, 5000)
int MAX_BACK = 4900
 
 
// ═══════════════════════════════════════════════════════════════════════
//  INPUTS
// ═══════════════════════════════════════════════════════════════════════
 
// ═══ IFVG Detection ═══
grpD      = "IFVG Detection"
showBull  = input.bool(true,  "Bullish IFVGs", group=grpD, inline="dir")
showBear  = input.bool(true,  "Bearish IFVGs", group=grpD, inline="dir",
     tooltip="Bullish = a bearish FVG (SIBI) price CLOSES back above; the failed gap flips into support. Bearish = a bullish FVG (BISI) price CLOSES back below; flips into resistance.")
detMode   = input.string("Singular", "Detection", options=["Singular","Series","Both"], group=grpD,
     tooltip="WHICH KIND OF SETUP YOU WANT TO SEE. Every gap is tracked individually AND grouped into series clusters at the same time; this picks which of the two gets printed.\n\nSINGULAR: only standalone IFVGs. A gap that formed part of a series is not shown.\n\nSERIES: only clusters: two or more same-direction gaps in the SAME LEG, fused into one zone spanning the whole run. The cluster inverts only when price closes through the far side of that entire range (a different bar and a different price from any single member), so Series will surface setups that do not exist in Singular at all.\n\nBOTH: standalone and clusters together. Expect overlapping setups; that is the point.\n\nSame leg means consecutive same-direction gaps with no opposing move between them, NOT gaps that merely sit near each other in price. Two gaps at the same level hours apart are not a series.\n\nThe leg ends at a swing: 3 candles where the MIDDLE candle's wick is the highest of the three (swing high) or the lowest (swing low). A run of bullish gaps is closed by a swing high; a run of bearish gaps by a swing low. Once that prints, the series is sealed at whatever size it reached and the next gap starts a fresh one, which is why a series can never contain a move in both directions.")
maxShow   = input.int(250, "Max IFVGs on Chart", minval=1, maxval=300, group=grpD,
     tooltip="Cap on zones held for the WHOLE lookback. Dead ghosts are culled first. ~5 zones print per typical session, so 250 holds over a month of history.")
minGrade  = input.string("C", "Min Setup Grade", options=["C","B-","B","B+","A","A+"], group=grpD,
     tooltip="Lowest grade that draws. Grade = checkmark count: C=1 B-=2 B=3 B+=4 A=5 A+=6.")
 
// ═══ Confluence Engine ═══
grpS      = "Confluence Engine"
sweepReq  = input.string("Graded", "Sweep Requirement", options=["Required","Graded"], group=grpS,
     tooltip="Required = the MM law: no raid, no setup. Every zone needs a direction-matched sweep behind it (printed floor B-). Graded = the sweep counts toward the grade but is not required (printed floor B-: the inversion plus at least one other check). Both philosophies, one click apart.")
corrSym   = input.symbol("CME_MINI:ES1!", "SMT Correlate", group=grpS,
     tooltip="Used when the chart isn't NQ/MNQ/ES/MES (those auto-map to each other). SMT checks whether this symbol held its level while the chart swept.")
 
// ═══ Setup Economy ═══
// House rule (v6.11): a second entry into a trade that's already working
// is a second POSITION, not a second signal. One lane per direction.
grpE      = "Setup Economy"
ecoMode   = input.string("One Trade At A Time", "Entry Economy", options=["One Trade At A Time","All Entries"], group=grpE,
     tooltip="One Trade At A Time = while a setup is still delivering (still working down its SD ladder in the right direction), no second entry prints in that direction. The opposite direction only prints if it clears the Reversal Proof below, so a pullback that retests the live zone can't fire a counter-signal.\n\nAll Entries = every qualified inversion prints, including the 2nd and 3rd continuation entries off the same leg. Pick this if you want a later entry when you missed the first one.\n\nEither way, a setup that gets STOPPED OUT frees its direction immediately. that's the whole point of a stop.")
laneEnd   = input.string("SD -4", "Trade Is Done At", options=["SD -1","SD -2","SD -2.5","SD -4","TP or Stop"], group=grpE,
     tooltip="How far a setup has to deliver before it releases its direction and lets the next entry print.\n\nExample on a short: entry 28,200 with SD -4 down at 28,020. On 'SD -4' the engine treats that short as LIVE the whole way down: no second short prints between 28,200 and 28,020. Move it to 'SD -2' if you only trade the first two targets and want the lane back early.\n\n'TP or Stop' = the lane frees the moment price tags the setup's TP level. That releases early (TP is usually nearer than SD -2), so expect more back-to-back entries in one move.")
laneStall = input.int(25, "Stall Release (bars)", minval=0, maxval=300, group=grpE,
     tooltip="Safety valve so a dead setup can't lock the chart out. If a live setup goes this many bars without tagging a NEW SD level, it stops holding the direction and the next entry is allowed.\n\nA trade that's genuinely working keeps ticking rungs; one that went flat 30 bars ago isn't in play anymore. 0 = never release on time: the setup holds until it delivers or gets stopped.")
revMode   = input.string("Zone Invalidation", "Reversal Proof", options=["Zone Invalidation","Structure Shift","Never"], group=grpE,
     tooltip="What counts as a REAL reversal against a live setup: the difference between price actually turning and price just pulling back to retest the zone it came from.\n\nZone Invalidation = the reversal candle has to CLOSE through the far side of the live zone: the same close that stops that trade out. A wick into the zone, or a close that stops short of it, is a retest and prints nothing.\n\nStructure Shift = stricter. On top of the above, the close must take out the recent swing extreme: a full break of the leg that built the live setup.\n\nNever = no counter-direction print at all while a setup is live.")
revGrade  = input.string("B+", "Reversal Min Grade", options=["C","B-","B","B+","A","A+"], group=grpE,
     tooltip="A reversal fired against a live trade has to be a better setup than the one it's fighting. B+ = 4 of the 6 checks. Lower it if good turns are getting filtered out; raise it if chop is still sneaking counter-signals through.")
revDisp   = input.bool(true, "Reversal Needs Displacement", group=grpE,
     tooltip="ON = the turn has to be impulsive (a body ≥ 1.2× ATR within the last 5 bars). Price grinding back through a live zone on small candles is mean reversion, not a reversal. OFF = invalidation + grade decide on their own.")
 
// ═══ Killzone Filter ═══
string GRP_KZ = "Killzone Filter"
kzOn      = input.bool(false, "Filter Setups to Killzones", group=GRP_KZ,
     tooltip="ON = a setup only prints when its inversion lands inside an enabled window (all times ET, DST-aware). A close-through outside every window is consumed silently: that trade never existed, and no alert fires for it. OFF = the engine prints around the clock.")
kz1On     = input.bool(true, "", inline="kz1", group=GRP_KZ)
kz1S      = input.session("0200-0500", "London  ", inline="kz1", group=GRP_KZ)
kz2On     = input.bool(true, "", inline="kz2", group=GRP_KZ)
kz2S      = input.session("0830-1100", "NY AM   ", inline="kz2", group=GRP_KZ)
kz3On     = input.bool(true, "", inline="kz3", group=GRP_KZ)
kz3S      = input.session("1330-1600", "NY PM   ", inline="kz3", group=GRP_KZ,
     tooltip="The three windows, each with its own toggle. Defaults are the classic ICT killzones; edit freely.")
 
// ═══ Display ═══
grpV      = "Display"
zoneCol   = input.color(#ff9800, "Zone Color", group=grpV,
     tooltip="One color for every zone. Fresh, retested, and failed fills all derive from it.")
keepKill  = input.bool(true,  "Keep Failed IFVGs", group=grpV,
     tooltip="ON = a zone price closes back through stays on the chart as a hard-faded ghost: the full session story. OFF = failed zones are deleted.")
dayOnly   = input.bool(false, "Current Day Only", group=grpV,
     tooltip="ON = zones clear at the 18:00 ET day roll for a session-only view. OFF = zones persist for multi-day back-study.")
showPnl   = input.bool(true,  "Setup Panel", group=grpV, inline="pnl",
     tooltip="The last setup that PRINTED: direction, grade, checklist and status (LIVE, RETESTED, STOPPED, or COMPLETE once it reaches the level set in 'Trade Is Done At', SD -4 by default). It holds that setup until a new one prints, so it never switches to a zone that has not confirmed and never drops the trade you are in while it plays out.")
pnlPos    = input.string("Bottom Right", "", options=["Top Right","Bottom Right","Bottom Left","Top Left"], group=grpV, inline="pnl")
showSdRow = input.bool(true,  "Target Progress Row", group=grpV,
     tooltip="Adds one row to the Setup Panel showing how far the panel's setup has delivered: its TP (the liquidity it was drawn toward) and each SD level, ✓ once tagged. Updates the moment a level is touched. A setup stopped after tagging a level says so in the top chip, e.g. STOPPED · after SD -1.")
// v6.43: the panel gets the same controls as every other visual (house law).
pnlSz     = input.string("Small", "Panel Text", options=["Tiny","Small","Medium","Large"], group=grpV, inline="pnlS")
pnlBg     = input.color(color.new(#0c0e15, 6), "", group=grpV, inline="pnlS")
pnlTxt    = input.color(#d1d4dc, "", group=grpV, inline="pnlS",
     tooltip="Text size, background and text colour of the Setup Panel. The grade banner is drawn one size larger than the rows so the grade stays the first thing you read.")
pnlOk     = input.color(#00e676, "Panel ✓ / ✗ / Accent", group=grpV, inline="pnlC")
pnlNo     = input.color(color.new(#ff5252, 35), "", group=grpV, inline="pnlC")
pnlAcc    = input.color(#f5a800, "", group=grpV, inline="pnlC",
     tooltip="Check mark colour (also the Target Progress row once anything is hit), cross colour, and the accent used for the frame when no setup has printed and for the footer. With a setup on the panel, the frame takes the grade's colour.")
showCE    = input.bool(true,  "CE Line (50%)", group=grpV, inline="ce")
ceCol     = input.color(#000000, "", group=grpV, inline="ce")
ceStyle   = input.string("Dotted", "", options=["Solid","Dashed","Dotted"], group=grpV, inline="ce")
ceTransp  = input.int(50, "", minval=0, maxval=100, group=grpV, inline="ce",
     tooltip="Consequent Encroachment: the zone's midline, spanning exactly the zone box. Toggle, color, style, opacity % (0 = solid).")
 
// ═══ Trade Plan ═══
grpP      = "Trade Plan"
showPlan  = input.bool(true,  "Show Trade Plan", group=grpP,
     tooltip="Entry line at the inversion close, SL, SD projection ladder, auto contracts + $ risk on the MM± label. Hover the label for the full setup card.")
microRat  = input.int(10, "Micros per Mini", minval=1, maxval=100, group=grpP,
     tooltip="How many micro contracts equal one mini. 10 is correct for NQ/MNQ, ES/MES, YM/MYM, GC/MGC and CL/MCL.\n\nWhen ONE mini contract would risk more than your Risk Budget, the trade plan sizes in micros instead and the label says so. Set this to 1 to switch that off and always size in minis.\n\nNot every contract has a clean tenth-sized micro, so check yours before trusting the number on an instrument outside that list.")
riskBud   = input.float(500, "Risk Budget ($)", minval=1, step=100, group=grpP,
     tooltip="Contracts auto-size to the largest count whose total risk fits this budget (minimum 1). Risk = (entry − SL) × point value × contracts.")
peBullCol = input.color(#2962ff, "Entry", inline="pe", group=grpP)
peBearCol = input.color(#f23645, "", inline="pe", group=grpP)
peWidth   = input.int(2, "", minval=1, maxval=4, inline="pe", group=grpP,
     tooltip="Entry line: long color, short color, width. The MM± label follows these colors.")
showSLln  = input.bool(true, "SL   ", inline="sl", group=grpP)
slCol     = input.color(#f23645, "", inline="sl", group=grpP)
slStyle   = input.string("Solid", "", options=["Solid","Dashed","Dotted"], inline="sl", group=grpP)
slWidth   = input.int(1, "", minval=1, maxval=4, inline="sl", group=grpP,
     tooltip="Stop-loss line: toggle, color, style, width.")
slMode    = input.string("IFVG", "SL Placement", options=["Swing","IFVG"], group=grpP,
     tooltip="Swing = stop beyond the extreme of the leg that built the setup (full structural invalidation). IFVG = stop just past the far side of the zone itself: tighter risk, more contracts per budget, but a deep retest through the zone tags it out.")
slBufT    = input.int(2, "SL Buffer (ticks)", minval=0, maxval=100, group=grpP,
     tooltip="Stop sits this many ticks beyond the chosen invalidation level (applies to both placements).")
showSD    = input.bool(true, "SD  ", inline="sd", group=grpP)
sdCol     = input.color(#000000, "", inline="sd", group=grpP)
sdStyle   = input.string("Dotted", "", options=["Solid","Dashed","Dotted"], inline="sd", group=grpP)
sdWidth   = input.int(1, "", minval=1, maxval=4, inline="sd", group=grpP,
     tooltip="SD projections: the ladder measures one leg, then projects it past the entry in the trade direction as standard deviations: bearish steps down, bullish steps up. Which leg it measures is set by 'SD Measured From' below. Short segments so stacked setups stay clean. Toggle, color, style, width.")
// v6.12: the SD unit is now selectable. Same ladder (-1 / -2 / -2.5 / -4),
// same anchor (the entry), only the LENGTH of one deviation changes: so a
// scalper and a swing trader can run the identical setup at their own scale.
sdLeg     = input.string("Swing → Entry", "SD Measured From",
     options=["Swing → Entry","IFVG Box","Full Displacement Leg","Entry → Stop (R)"], group=grpP,
     tooltip="How long ONE standard deviation is. The ladder and the entry never move, only the spacing between the rungs.\n\nSwing → Entry (default): the manipulation leg: swing extreme to the inversion close. Day-trade scale.\n\nIFVG Box: the height of the inverted gap itself. The tightest unit on the chart, so -1 and -2 sit close to the entry. Scalping: you are taking the first push off the zone, not the day's range.\n\nFull Displacement Leg: swing high to swing low of the whole impulse that built the gap, not just the half above the entry. The widest unit. Swing trading: -4 can sit a session or more away.\n\nEntry → Stop (R): one deviation = your actual risk, so the rungs read as 1R / 2R / 2.5R / 4R. This one follows 'SL Placement' above: on IFVG it is a tight R, on Swing it is a structural R. Use it when you scale out by R rather than by structure.\n\nExample on a short entered at 28,400 with the swing high at 28,460 and a 15-point-tall gap: Swing → Entry puts -1 at 28,340; IFVG Box puts it at 28,385; Entry → Stop with an IFVG stop puts it near 28,383.\n\nWorth knowing: Entry Economy reads this ladder. A trade holds its direction until it reaches the rung set in 'Trade Is Done At', so a tighter unit here means that rung gets tagged sooner and the next setup is allowed to print sooner. If you move to IFVG Box and start seeing setups stack up again, that is why. Raise 'Trade Is Done At' to compensate.")
pLblSz    = input.string("Small", "Label Size", options=["Tiny","Small","Medium","Large"], group=grpP,
     tooltip="Size of the MM± entry label (the one carrying the setup pop-up).")
keepPlans = input.bool(false, "Keep Stopped Plans", group=grpP,
     tooltip="OFF = a stopped-out setup takes its entry line and label with it. ON = every plan stays as a journal record.")
 
// ═══ Nearby Liquidity ═══
string GRP_LIQ = "Nearby Liquidity"
lqBMajOn  = input.bool(true,  "Buyside Major ", inline="lq1", group=GRP_LIQ)
lqBMajCol = input.color(color.new(#000000, 0), "", inline="lq1", group=GRP_LIQ)
lqBMajSty = input.string("····", "", options=["⎯⎯⎯", "----", "····"], inline="lq1", group=GRP_LIQ)
lqBMinOn  = input.bool(true,  "Buyside Minor ", inline="lq2", group=GRP_LIQ)
lqBMinCol = input.color(color.new(#000000, 0), "", inline="lq2", group=GRP_LIQ)
lqBMinSty = input.string("····", "", options=["⎯⎯⎯", "----", "····"], inline="lq2", group=GRP_LIQ)
lqSMajOn  = input.bool(true,  "Sellside Major", inline="lq3", group=GRP_LIQ)
lqSMajCol = input.color(color.new(#000000, 0), "", inline="lq3", group=GRP_LIQ)
lqSMajSty = input.string("····", "", options=["⎯⎯⎯", "----", "····"], inline="lq3", group=GRP_LIQ)
lqSMinOn  = input.bool(true,  "Sellside Minor", inline="lq4", group=GRP_LIQ)
lqSMinCol = input.color(color.new(#000000, 0), "", inline="lq4", group=GRP_LIQ)
lqSMinSty = input.string("····", "", options=["⎯⎯⎯", "----", "····"], inline="lq4", group=GRP_LIQ,
     tooltip="The nearest untaken MAJOR and MINOR liquidity pool on each side of price: toggle, color, line type per row. Levels delete the moment price trades through them. Major is always the outer level, and up to 'Minors per side' minors draw between price and it. Same engine as Maulers Raid to Delivery.")
lqMinLen  = input.int(5,  "Minor Swing (bars)", minval=2, maxval=50, group=GRP_LIQ,
     tooltip="Bars each side a swing must be the extreme to count as MINOR liquidity. 5 catches the stair-step swings an intraday leg is built from.")
lqMajLen  = input.int(40, "Major Swing (bars)", minval=10, maxval=200, group=GRP_LIQ,
     tooltip="Bars each side for MAJOR liquidity: the session-defining extremes (~3.5 hours of clearance each side on 5m).")
// v6.43: ported from the sibling raid tool with its defaults (same engine).
lqMinN    = input.int(5, "Minors per side", minval=1, maxval=5, group=GRP_LIQ,
     tooltip="How many MINOR pools draw on each side, nearest to price first. They only draw between price and that side's Major level: a minor never draws past the major.\n\nWhy you may see a clear swing with no Major tag: a swing only grades Major once the Major Swing count of bars has printed on each side of it. A fresh swing shows as a minor until then, and upgrades on its own if it survives.")
lqKeyTagOn = input.bool(true, "Tag key levels", group=GRP_LIQ,
     tooltip="When a drawn pool sits on the previous day, week or month high or low, its label says so: SSL · PDL, BSL · PWH, and so on. If it lines up with more than one, the higher timeframe wins (PML over PWL over PDL).\n\nThis only names the pool. It does not change which pools show, and the Key Levels group still decides whether those levels are drawn.\n\nPrevious day = the exchange daily candle. On CME futures that runs 6pm to 5pm New York time, so a 4am low belongs to that day's candle.")
lqLblSz   = input.string("Tiny", "Label Size", options=["Tiny","Small","Medium","Large"], group=GRP_LIQ)
lqThick   = input.bool(true, "Thicken Stacked Pools", group=GRP_LIQ,
     tooltip="ON = a level holding 2+ pooled equal swings draws one width thicker.")
lqShort   = input.bool(true, "Shorthand Labels", group=GRP_LIQ,
     tooltip="ON = flat tags: BSL / SSL. OFF = Major BSL / Minor BSL / Major SSL / Minor SSL.")
 
// ═══ Equal Highs / Lows: EXACT settings + engine from the sibling raid tool (levels tool port) ═══
string GRP_EQL = 'Equal Highs / Lows'
showEql = input.bool(false, 'Show Equal Highs/Lows', group = GRP_EQL)
eqlMinBars = input.int(0, 'Minimum Bar Distance', minval = 0, maxval = 500, group = GRP_EQL, tooltip = 'Minimum bars between the candles forming an equal high/low')
eqlTolTicks = input.int(0, 'Tolerance (ticks)', minval = 0, maxval = 50, group = GRP_EQL, tooltip = '0 = exact wick match. Increase to allow near-equal wicks to count as an EQH/EQL.')
eqhColor = input.color(#000000, 'EQH Color', inline = 'eqlC', group = GRP_EQL)
eqlColor = input.color(#000000, 'EQL Color', inline = 'eqlC', group = GRP_EQL)
eqlLineStyleStr = input.string('Solid', 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], inline = 'eqlL', group = GRP_EQL)
eqlLineWidth = input.int(1, 'Width', minval = 1, maxval = 5, inline = 'eqlL', group = GRP_EQL)
eqlExtendRight = input.bool(false, 'Extend Right', group = GRP_EQL, tooltip = 'Extend EQH/EQL lines to the right edge of the chart')
 
// ═══ Higher Timeframe FVGs: EXACT feature/engine from the sibling raid tool (v4.14) ═══
string GRP_HFVG = 'Higher Timeframe FVGs'
useHf1 = input.bool(false, 'HTF FVG 1', inline = 'hf1', group = GRP_HFVG, tooltip = 'Higher-timeframe FVGs need enough chart history to see the HTF candles, so how deep they reach depends on your chart TF and TradingView plan. Rough guide on a 23h futures symbol with Premium (20,000 bars): every option works on a 1m chart or above. 1D thins out on 30s charts and will NOT draw below that; 4H holds down to about 5s. Plans below Premium have half the history or less, so limits hit sooner. If a slot looks empty: raise your chart timeframe or pick a lower HTF - nothing is broken, the history just does not contain the candles.')
hf1Sel = input.string('1H', '', options = ['15m', '1H', '4H', '1D'], inline = 'hf1', group = GRP_HFVG)
hf1Bull = input.color(color.new(#26a69a, 75), '', inline = 'hf1', group = GRP_HFVG)
hf1Bear = input.color(color.new(#000000, 72), '', inline = 'hf1', group = GRP_HFVG)
useHf2 = input.bool(false, 'HTF FVG 2', inline = 'hf2', group = GRP_HFVG, tooltip = 'Higher-timeframe FVGs need enough chart history to see the HTF candles, so how deep they reach depends on your chart TF and TradingView plan. Rough guide on a 23h futures symbol with Premium (20,000 bars): every option works on a 1m chart or above. 1D thins out on 30s charts and will NOT draw below that; 4H holds down to about 5s. Plans below Premium have half the history or less, so limits hit sooner. If a slot looks empty: raise your chart timeframe or pick a lower HTF - nothing is broken, the history just does not contain the candles.')
hf2Sel = input.string('4H', '', options = ['15m', '1H', '4H', '1D'], inline = 'hf2', group = GRP_HFVG)
hf2Bull = input.color(color.new(#26a69a, 75), '', inline = 'hf2', group = GRP_HFVG)
hf2Bear = input.color(color.new(#000000, 72), '', inline = 'hf2', group = GRP_HFVG, tooltip = 'Bull / bear box colors per slot. Boxes draw where the 3-candle pattern formed and are removed when the gap fully fills.')
hfTxtCol = input.color(color.white, 'Label', group = GRP_HFVG, tooltip = 'Color of the timeframe label inside the HTF FVG boxes.')
 
 
// ═══ Key Levels ═══
string GRP_KL = "Key Levels"
klDayOn = input.bool(false, "Prev Day   H/L", inline = "kld", group = GRP_KL)
klDayCol = input.color(#000000, "", inline = "kld", group = GRP_KL)
klWkOn = input.bool(false, "Prev Week  H/L", inline = "klw", group = GRP_KL)
klWkCol = input.color(#000000, "", inline = "klw", group = GRP_KL)
klMoOn = input.bool(false, "Prev Month H/L", inline = "klm", group = GRP_KL)
klMoCol = input.color(#000000, "", inline = "klm", group = GRP_KL, tooltip = "Previous day, week and month highs and lows. These levels were always computed in here - they are what stops a Nearby-Liquidity pool from being drawn on top of a level you can already see - they were just never shown.\n\nLevels only draw when your chart timeframe is BELOW theirs. Prev Day will not appear on a daily chart.\n\nLevels sharing the same price merge into one line with a combined label, so PDL sitting on PWL reads 'PDL / PWL' instead of two lines a tick apart.")
klStyleIn = input.string("Dotted", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = GRP_KL)
klWidth = input.int(1, "Line Width", minval = 1, maxval = 3, group = GRP_KL)
klLblSz = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal"], group = GRP_KL)
klShorthand = input.bool(true, "Shorthand Labels", group = GRP_KL, tooltip = "On: PDH. Off: Prev Day High.")
klShowPrice = input.bool(true, "Show Price on Labels", group = GRP_KL)
klExtendBars = input.int(30, "Extend Right (bars)", minval = 5, maxval = 200, group = GRP_KL)
klSweptTick = input.bool(true, "Mark Swept Levels", group = GRP_KL, tooltip = "Adds a tick to a level that has been taken since its period opened. Taken liquidity is spent - in this model that is most of why you wanted the level marked. Resets when the period rolls.")
 
// ═══ Alerts ═══
string GRP_AL = "Alerts"
alertGrade = input.string("C", "Alert Min Grade", options=["C","B-","B","B+","A","A+"], group=GRP_AL,
     tooltip="Every alert type (new setup, retest, SD hits, TP hit, stopped) only fires for setups at or above this grade. C = everything. Set B+ to only hear about sweep-quality setups.")
alNewOn   = input.bool(true, "New Setup", inline="al1", group=GRP_AL)
alRetOn   = input.bool(true, "Retest",    inline="al1", group=GRP_AL)
alSdOn    = input.bool(true, "SD Hits",   inline="al2", group=GRP_AL)
alDoneOn  = input.bool(true, "TP Hit",    inline="al2", group=GRP_AL)
alFailOn  = input.bool(true, "Stopped",   inline="al3", group=GRP_AL,
     tooltip="Per-type switches, same idea as the HTF's alert checkboxes. An unticked type never fires no matter what alerts exist in TradingView. Flip one off here instead of deleting the alert. New Setup covers both directions; SD Hits covers all four levels.")
 
// ── v6.32 ALERT TRANSPORT: ported from the sibling raid tool, logic unchanged ──
// Only the quoting was normalised to this file's style. See the banner for the one
// intentional behavioural difference (the confirmed-bar gate is a parameter here).
alerts_on = input.bool(false, "Enable alerts", group=GRP_AL,
     tooltip="Master switch. With this ON, create ONE TradingView alert on this indicator with its condition set to \"Any alert() function call\". That single alert carries every event type you have ticked above, with the actual prices in the message.\n\nOFF by default, same as Maulers Raid to Delivery.")
alert_format = input.string("Plain", "Message format", options=["Plain", "Discord webhook"], group=GRP_AL, active=alerts_on,
     tooltip="Plain = readable text for app push / email / popup. Discord webhook = wraps the same text as {\"content\":\"...\"} JSON, so a Discord channel webhook URL pasted into the TradingView alert Webhook URL field posts straight into the channel.")
al_readme = input.bool(false, "ⓘ  Setting up your alert", group=GRP_AL,
     tooltip="CREATE ONE ALERT, NOT TWELVE.\n\nRight-click the chart → Add alert → set Condition to this indicator, then pick \"Any alert() function call\". That one alert carries every type ticked above. The per-type checkboxes here decide what it sends; you never need a second alert.\n\nSETTINGS ARE FROZEN WHEN YOU CREATE IT.\nTradingView snapshots these settings AND the chart timeframe the moment the alert is created, then runs on that copy forever. Set the indicator up how you want it FIRST, then create the alert.\n\nTo CHANGE what the alert does you must DELETE it and create a new one. Editing settings on the chart never updates a live alert.\n\nThis is the same setup as Maulers Raid to Delivery. Learn it once.")
 
grpLR     = "LRLR · Low Resistance Liquidity Run"
lrOn      = input.bool(true,  "Show LRLR", group=grpLR,
     tooltip="A Low Resistance Liquidity Run is a STAIRCASE of unswept swing extremes. In a bearish run price prints lower lows AND lower highs, and every one of those lower highs is a failure swing: a high that failed to take the previous high, left UNSWEPT. Four or more stacked is no longer a single untouched level, it is a ladder of resting liquidity along one clean diagonal. Bullish is the mirror.\n\nThe line does NOT connect the points. It is fitted through them for the true angle, then floated outward so it hovers clear of the structure. A wick poking through between rungs is normal: the sequence of swings qualifies a run, not whether every bar respects the drawn line.\n\nBy default these only appear while a setup is LIVE. See Draw When.")
lrGate    = input.string("Setup draw only", "Draw When", options=["Setup draw only","Any live setup","Always"], group=grpLR,
     tooltip="SETUP DRAW ONLY (default): a run only appears while an IFVG setup is live AND the run sits on the side that setup is reaching for. A live long shows the ladder ABOVE; a live short shows the ladder BELOW. That is the question worth asking: my target is up there, is the road to it clean?\n\nAn LRLR is liquidity, and a setup is an attempt to RAID it, so the test is which SIDE of price the ladder sits on, not which way its own staircase ran.\n\nANY LIVE SETUP: both sides draw while any setup is live.\n\nALWAYS: ungated, every run all the time. Busy chart.\n\nDetection never stops either way; only visibility is gated. A staircase that formed long before your setup is already on the chart the moment it goes live.")
lrBullCol = input.color(#000000, "Bullish / Bearish ", inline="lrc", group=grpLR)
lrBearCol = input.color(#000000, "", inline="lrc", group=grpLR,
     tooltip="A BULLISH run is higher highs + higher lows and its line hovers BELOW the higher lows, marking unswept sellside under price. A BEARISH run is the mirror, hovering ABOVE the lower highs, marking unswept buyside above.\n\nUnder 'Setup draw only' a live LONG surfaces the runs ABOVE price, which will be the bearish-coloured ones. Not a mix-up: the colour tells you how the ladder was built, the side tells you whether your setup is aiming at it.")
lrWidth   = input.int(2, "Width", minval=1, maxval=4, inline="lrs", group=grpLR)
lrStyleIn = input.string("⎯⎯⎯", "", options=["⎯⎯⎯","----","····"], inline="lrs", group=grpLR)
lrLblBull = input.string("Above", "Label  Bull / Bear", options=["Above","Below"], inline="lrl", group=grpLR)
lrLblBear = input.string("Below", "", options=["Above","Below"], inline="lrl", group=grpLR,
     tooltip="Which side of the LINE the tag hangs on, set separately per direction.\n\nThe default (bull Above, bear Below) puts both tags on the side facing the candles: a bearish line hovers ABOVE price so its tag drops toward the action, and a bullish line hovers BELOW price so its tag lifts toward it. Flip either one if you would rather the tag sit on the outside.")
lrLblH    = input.string("Right", "Tag anchor", options=["Left","Center","Right"], inline="lrl2", group=grpLR,
     tooltip="Which END of the line the tag sits at.\n\nRight is the default and stays out of the price action on both sides. Center is closer to how you would tag it drawing by hand. Left anchors it at the run's ORIGIN, useful when you want your eye pulled to the far rung, since that is the one price has to clear to spend the whole ladder.")
 
 
 
// ═══ LOCKED CALIBRATION (v5.13): constants, deliberately NOT inputs ═══
// Settled during the 2026-07 parity calibration; hardcoded so a TV input
// reset can never touch them.
minTicks  = 2                 // parity floor: below 2, micro-gaps steal economy lanes
minGapAtr = 0.03              // ATR floor: 0.1 silently hid small but valid setups
useDisp   = false             // quiet consolidation gaps are exactly the ones that flip
alignMode = "Chart"           // chart-TF pivots = real-time raid crediting
alignTfIn = "15"              // dead parameter (only read when alignMode was Manual)
sweepWin  = 30                // Setup Window: checklist item freshness
domOn     = false             // dominance filter blocked stair-step continuation raids
domWin    = 12                // dead parameter (only read when domOn)
spcBars   = 5                 // House rule: inversion 2-3 candles after a confirmed one = same move
extWin    = 12                // lag-free raid source lookback
invWin    = 30                // gap must invert within 30 bars of forming
legFrac   = 1                 // v6.28 Series mode: bars each side for the LEG-BOUNDARY
                              // fractal. House rule: "a leg is a swing low to a swing
                              // high. A swing high is 3 candles with the middle or 2nd
                              // candle's wick being higher than the first and last, vice
                              // versa for a swing low." legFrac = 1 IS that 3-candle
                              // fractal. Deliberately NOT swingLen (3 each side = a 7-bar
                              // pivot): that is the liquidity pool's scale, far too
                              // coarse to bound a single displacement leg.
                              // REPLACES seriesAdj (v6.24-v6.27), which bounded the gap
                              // between CONSECUTIVE members and so bounded nothing at all.
dispMult  = 1.2               // candle body >= 1.2x ATR(14) within 5 bars = Displacement
 
 
// ═══════════════════════════════════════════════════════════════════════
//  DATA ARRAYS
// ═══════════════════════════════════════════════════════════════════════
 
// ── Watch pool: plain FVGs tracked silently, waiting for a close-through ──
var array<float> wTop = array.new<float>()   // gap top price
var array<float> wBot = array.new<float>()   // gap bottom price
var array<int>   wDir = array.new<int>()     // ORIGINAL gap direction: 1 = BISI, -1 = SIBI
var array<int>   wBI  = array.new<int>()     // bar_index where the gap pattern formed (left anchor)
var array<int>   wCtB = array.new<int>()     // v5.15: bar of the FIRST confirmed close-through (na until it happens)
var array<float> wCtC = array.new<float>()   // v5.15: close price of that first close-through candle (the true entry)
var array<int>   wMem = array.new<int>()     // v6.27: members in this unit. 1 = a lone gap, 2+ = a SERIES cluster
                                             // v6.31: wLast lived here. Removed - see the banner.
var array<bool>  wSeal= array.new<bool>()    // v6.28: this row's LEG is over. A sealed row neither EXTENDS (as a
                                             // cluster) nor SEEDS (as a lone gap), so a series can never span two
                                             // legs. Deliberately its OWN column, not folded into wMem -
                                             // an overloaded state field is exactly what made the zone lifecycle
                                             // so expensive to work on.
 
// ── Inverted gaps: the visible IFVGs ──
var array<float> iTop = array.new<float>()   // zone top price
var array<float> iBot = array.new<float>()   // zone bottom price
var array<int>   iDir = array.new<int>()     // POST-FLIP direction: 1 = bullish IFVG (support), -1 = bearish IFVG (resistance)
var array<int>   iSt  = array.new<int>()     // 0 = fresh, 1 = retested, 2 = failed (killed)
var array<int>   iBI  = array.new<int>()     // left anchor (clamped original gap formation bar)
var array<int>   iInv = array.new<int>()     // bar_index of the inversion close
var array<int>   iSc  = array.new<int>()     // checklist count at inversion (0–6)
var array<bool>  iDn  = array.new<bool>()    // setup COMPLETE: reached its TP level (v5.7; 1.5×ATR proxy when no pool existed)
var array<float> iTp  = array.new<float>()   // v5.7: the setup's TP level at print (na = no pool in range)
var array<line>  pLE  = array.new<line>()    // v5.0 trade plan: entry line
var array<line>  pLS  = array.new<line>()    // v5.0 trade plan: SL line
var array<line>  pS1  = array.new<line>()    // v5.8 SD projections: 1σ / 2σ / 2.5σ / 4σ lines + tags
var array<line>  pS2  = array.new<line>()
var array<line>  pS3  = array.new<line>()
var array<line>  pS4  = array.new<line>()
var array<label> pT1  = array.new<label>()
var array<label> pT2  = array.new<label>()
var array<label> pT3  = array.new<label>()
var array<label> pT4  = array.new<label>()
var array<label> pLb  = array.new<label>()   // v5.0 trade plan: contracts + $ risk label
var array<float> iS1  = array.new<float>()   // v6.0 alerts: SD -1 level per zone
var array<float> iS2  = array.new<float>()   // v6.0 alerts: SD -2 level
var array<float> iS3  = array.new<float>()   // v6.0 alerts: SD -2.5 level
var array<float> iS4  = array.new<float>()   // v6.0 alerts: SD -4 level
var array<bool>  iH1  = array.new<bool>()    // v6.0 alerts: SD -1 already hit
var array<bool>  iH2  = array.new<bool>()    // v6.0 alerts: SD -2 already hit
var array<bool>  iH3  = array.new<bool>()    // v6.0 alerts: SD -2.5 already hit
var array<bool>  iH4  = array.new<bool>()    // v6.0 alerts: SD -4 already hit
var array<string> iChk = array.new<string>()  // v6.1: checklist rows frozen at print (feeds the trade card)
// v6.43 SETUP PANEL LATCH - a snapshot of the last PRINTED setup. Written only at
// the two print sites (identity) and the lifecycle loop (status word). A snapshot,
// not an index, so the panel outlives its zone being deleted.
var int    cdDir = 0      // 1 long, -1 short, 0 = nothing printed yet
var int    cdInv = na     // inversion bar of the latched zone (identity key with cdDir)
var int    cdCnt = 0      // checklist count at print
var string cdChk = ""     // checklist rows at print
var string cdSt  = ""     // LIVE / RETESTED / COMPLETE / STOPPED
var int    cdSd  = 0      // furthest SD rung tagged: 0 none, 1 = -1, 2 = -2, 3 = -2.5, 4 = -4
var bool   cdTp  = false  // TP (the setup's liquidity target) reached
// v6.43: the rung that makes the panel read COMPLETE is the SAME one 'Trade Is Done At'
// uses to release the direction, so the panel and the entry engine can never disagree
// about whether a trade is finished. 0 = TP ("TP or Stop").
int CD_DONE = laneEnd == "SD -1" ? 1 : laneEnd == "SD -2" ? 2 : laneEnd == "SD -2.5" ? 3 : laneEnd == "SD -4" ? 4 : 0
var array<int>   iPrg = array.new<int>()     // v6.11 lane: bar of the last DELIVERY event (print, then each new SD hit)
var array<box>   iBx  = array.new<box>()     // the zone box (static, origin → inversion)
var array<line>  iLn  = array.new<line>()    // optional CE projection line
 
// ── Liquidity pools: recent unswept levels ──
var array<float> pivHi = array.new<float>()  // unswept swing highs (buyside; equal highs live here too)
var array<float> pivLo = array.new<float>()  // unswept swing lows (sellside)
var array<float> datHi = array.new<float>()  // data highs: extreme-range candle proxy
var array<float> datLo = array.new<float>()  // data lows
 
// ── Pending sweeps: breached levels waiting for the close-back that
//    separates a liquidity grab from a breakout ──
var array<float> psLvl  = array.new<float>() // breached level
var array<int>   psDir  = array.new<int>()   // 1 = buyside raid (high taken), -1 = sellside
var array<int>   psBar  = array.new<int>()   // breach bar
var array<int>   psTier = array.new<int>()   // 1 = key level (PD/PW/PM/session), 0 = swing/data
 
// ── HTF PD arrays: live higher-timeframe FVGs across 15m/1H/4H/D (Delivery) ──
var array<float>  hTop = array.new<float>()  // zone top
var array<float>  hBot = array.new<float>()  // zone bottom
var array<int>    hDir = array.new<int>()    // 1 = demand (BISI), -1 = supply (SIBI)
var array<int>    hBI  = array.new<int>()    // chart bar where the zone appeared (debug draw anchor)
var array<string> hTfN = array.new<string>() // TF name for the debug label
 
 
// ═══════════════════════════════════════════════════════════════════════
//  HELPER FUNCTIONS + CONSTANTS
// ═══════════════════════════════════════════════════════════════════════
 
 
// (v4.10) Zone box spans the real structure: gap origin → inversion
// candle. The sequence lock bounds that span at invWin+2 bars, so the
// old fixed-width stamp (and its visible offset)
// is gone: the box now sits exactly on what happened.
 
// Watch pool hard cap: oldest un-inverted gaps culled first (implicit aging)
var int maxWatch = 200
 
// Swing strength for liquidity pivots (bars each side). Plain const:
// ta.pivothigh/low length args want a simple int.
int swingLen = 3
 
// Pool caps
int maxPiv  = 10
int maxDat  = 6
int maxHtf  = 16
 
// Bars a breached level gets to close back and confirm as a sweep
int sweepConfirmBars = 3
 
// Delivery pairing window: the HTF tap must sit within this many bars of
// the sweep: tap and raid ride the same swing.
int legWin = 15
 
// Data-candle proxy: a bar whose range runs this many ATRs prints a
// "data high/low" (news-style candle). Pine can't see the economic
// calendar: this is the footprint instead of the schedule.
float dataMult = 3.0
 
// Line style from a Solid/Dashed/Dotted input string (v5.16: shared
// by the CE, SL, and SD style pickers)
f_ls(string s) =>
    s == "Solid" ? line.style_solid : s == "Dashed" ? line.style_dashed : line.style_dotted
 
// Glyph style mapper (v5.17): the sibling raid tool picker style ('⎯⎯⎯' / '----' / '····'),
// used by the Nearby Liquidity and EQH/EQL rows so both indicators feel identical
f_lstyle(string s) =>
    s == "----" ? line.style_dashed : s == "····" ? line.style_dotted : line.style_solid
 
// Label size from a Tiny/Small/Medium/Large picker (v5.19: shared)
f_szName(string s) =>
    s == "Large" ? size.large : s == "Medium" ? size.normal : s == "Small" ? size.small : size.tiny
 
// v6.43: panel sizes, stepped off the Panel Text input. step +1 = the grade banner,
// -1 = the footer. Clamped so Tiny never goes smaller and Large never bigger.
f_pnlSz(int step) =>
    int k = (pnlSz == "Tiny" ? 0 : pnlSz == "Small" ? 1 : pnlSz == "Medium" ? 2 : 3) + step
    k <= 0 ? size.tiny : k == 1 ? size.small : k == 2 ? size.normal : size.large
 
// CE line style from input
f_ceLS() =>
    f_ls(ceStyle)
 
// Zone fill by state: one neutral color, no borders.
// 0 fresh, 1 retested (touch softer), 2 failed (frozen ghost).
// v5.15: with borders and labels gone, the fill IS the state signal:
// ghosts fade hard so a stopped zone can't be mistaken for a live one
// that "lost" its entry marker (stopped plans are stripped by design).
f_zFill(int st) =>
    st == 2 ? color.new(zoneCol, 94) : st == 1 ? color.new(zoneCol, 85) : color.new(zoneCol, 78)
 
// Convert timeframe string to readable label
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
 
// ── v6.32 ALERT TRANSPORT: ported from the sibling raid tool, logic unchanged ──
// Only the quoting was normalised to this file's style. The one intentional
// behavioural difference is the confirmed-bar gate being a parameter; see the banner.
// It lives here with the other helpers rather than beside its inputs, because the
// settings section stays a settings section - that readability was bought in v5.22
// and is not getting spent back on a function definition.
// varip, not var, and that is the whole point: a realtime bar can roll back and
// recalculate, and a plain var buffer would roll back with it and let the same event
// alert twice. varip survives the rollback, so an identical message inside the 10-minute
// window is recognised as the repeat it is. Shared across every event type in the file.
varip array<string> g_sentMsg = array.new<string>()
varip array<int>    g_sentT   = array.new<int>()
 
// needConf: pass true for events that only exist on a closed bar, false for the wick
// events (SD taps, retests) whose latch is set the instant the wick lands - gating those
// on a confirmed bar would open the gate after the latch had already closed the door.
f_alert(bool en, string msg, bool needConf) =>
    if alerts_on and en and (not needConf or barstate.isconfirmed)
        bool dup = false
        if g_sentMsg.size() > 0
            for i = g_sentMsg.size() - 1 to 0
                if time - g_sentT.get(i) > 600000
                    break
                if g_sentMsg.get(i) == msg
                    dup := true
                    break
        if not dup
            g_sentMsg.push(msg)
            g_sentT.push(time)
            if g_sentMsg.size() > 40
                g_sentMsg.shift()
                g_sentT.shift()
            string m = "MM IFVG | " + syminfo.ticker + " | " + msg
            if alert_format == "Discord webhook"
                m := '{"content":"' + m + '"}'
            alert(m, alert.freq_all)
 
// Letter grade from the checklist count (1–6). The ladder:
// 6=A+ · 5=A · 4=B+ · 3=B · 2=B- · 1=C
f_grade(int c) =>
    c >= 6 ? "A+" : c == 5 ? "A" : c == 4 ? "B+" : c == 3 ? "B" :
     c == 2 ? "B-" : "C"
 
// Grade tier color: A tiers green, B+ gold, B orange, B-/C red
f_gradeCol(int c) =>
    c >= 5 ? #00e676 : c == 4 ? #f5a800 : c == 3 ? #ff9800 : #ff5252
 
// Panel position from input
f_pnlPos() =>
    pnlPos == "Top Right" ? position.top_right :
     pnlPos == "Bottom Left" ? position.bottom_left :
     pnlPos == "Top Left" ? position.top_left : position.bottom_right
 
// Is a timeframe higher than the chart timeframe? (explicit W/M seconds:
// timeframe.in_seconds("M") is unreliable on variable month length)
f_higher(simple string tf) =>
    isM = tf == "M" or tf == "1M"
    isW = tf == "W" or tf == "1W"
    isD = tf == "D" or tf == "1D"
    c   = timeframe.in_seconds(timeframe.period)
    isM ? c < 2592000 : isW ? c < 604800 : isD ? c < 86400 : timeframe.in_seconds(tf) > c
 
// Liquidity alignment timeframe (v4.11) : swings are detected on
// a HIGHER timeframe (Automatic = one tier up: 5m chart sweeps 15m
// swings). Chart mode returns the chart TF, which disables alignment.
f_alignTf() =>
    c = timeframe.in_seconds(timeframe.period)
    alignMode == "Chart" ? timeframe.period :
     alignMode == "Manual" ? alignTfIn :
     c <= 60 ? "5" : c <= 300 ? "15" : c <= 900 ? "60" : c <= 3600 ? "240" : "D"
 
// SMT correlate: NQ and ES auto-map to each other, everything else uses the input
f_corrSym() =>
    r = syminfo.root
    r == "NQ" or r == "MNQ" ? "CME_MINI:ES1!" :
     r == "ES" or r == "MES" ? "CME_MINI:NQ1!" : corrSym
 
// 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: one running + one committed pair per call site.
// Commits the completed session's extremes when the window closes.
f_sessLvls(bool inSess) =>
    var float runHi = na
    var float runLo = na
    var float comHi = na
    var float comLo = na
    if inSess and not inSess[1]
        runHi := high
        runLo := low
    else if inSess
        runHi := math.max(nz(runHi, high), high)
        runLo := math.min(nz(runLo, low), low)
    if not inSess and inSess[1]
        comHi := runHi
        comLo := runLo
    [comHi, comLo]
 
// Level state: sweep event + taken latch, one latch per call site.
// Resets when the level rolls to a new value. Returns [sweptNow, taken].
// NOTE: call sites must be unconditional top-level assignments: v6
// and/or short-circuits, so burying calls in a boolean chain skips the latch.
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]
 
// Register a raid on a level. If this bar already closed back on the
// original side, the sweep confirms immediately; otherwise it goes to the
// pending list and has sweepConfirmBars closes to come back. Returns
// whether the sweep confirmed NOW. tier: 1 = key level, 0 = swing/data.
f_raid(float lvl, int dirRaid, int tier) =>
    if (dirRaid == 1 and close < lvl) or (dirRaid == -1 and close > lvl)
        true
    else
        array.push(psLvl,  lvl)
        array.push(psDir,  dirRaid)
        array.push(psBar,  bar_index)
        array.push(psTier, tier)
        false
 
// Push a live HTF FVG into the Delivery pool
f_hAdd(float tp, float bt, int dir, string tfn) =>
    array.push(hTop, tp)
    array.push(hBot, bt)
    array.push(hDir, dir)
    array.push(hBI,  bar_index)
    array.push(hTfN, tfn)
    0
 
// v5.5 duplicate check: ONE ACTIVE SETUP PER DIRECTION. A setup is
// ACTIVE until it COMPLETES (ran the target distance) or FAILS (close
// through the far side). A retest does NOT free it: the first wick
// back into a fresh zone is the entry retest, part of the trade, not
// the end of it (v5.4's mitigation escape freed the direction on that
// first touch, which re-printed doubles in chop). No starvation:
// completion catches zones price runs from, failure catches zones
// price breaks; the only zone that's neither is a trade in progress,
// which SHOULD block. Duplicates are CONSUMED at the call site: no
// second chances.
f_dupe(int dir) =>
    hit = false
    int nInv = na
    if array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iSt, j) < 2 and not array.get(iDn, j) and array.get(iDir, j) == dir
                hit := true
                iv = array.get(iInv, j)
                nInv := na(nInv) ? iv : math.max(nInv, iv)
    [hit, nInv]
 
// Is the candidate physically stacked with any active same-direction zone?
// (Stacked candidates take the merge path and bypass setup-economy gates.)
f_stacked(float zt, float zb, int dir, float tol) =>
    hit = false
    if array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iSt, j) < 2 and array.get(iDir, j) == dir
                jt = array.get(iTop, j)
                jb = array.get(iBot, j)
                vGap = zb > jt ? zb - jt : jb > zt ? jb - zt : 0.0
                if vGap <= tol
                    hit := true
    hit
 
// ═══ v6.11 SETUP ECONOMY: one working trade per direction ═══
// House rule: "if an IFVG is still hitting its SD levels another IFVG
// shouldn't fire, unless the previous IFVG was broken or it's a reversal."
//
// Why v6.10 doubled up: f_dupe already blocked same-direction prints, but
// it released the direction on the iDn (TP-reached) latch. The TP level is
// the nearest liquidity past 1.5×ATR: on a real displacement leg price
// tags it within a few candles, long before the SD ladder is worked. The
// lane opened mid-delivery and the next inversion down the same leg printed
// a second entry. So the release condition moves off TP and onto the SD
// ladder: the thing a trader actually manages the trade by.
//
// A live zone HOLDS its lane while all three are true:
//   · not stopped out          (a broken IFVG frees its direction at once)
//   · hasn't reached the rung the user calls "done" (default SD -4)
//   · hasn't stalled           (no new rung in laneStall bars)
 
// Has this setup delivered as far as the user calls finished?
f_laneDone(int j) =>
    laneEnd == "SD -1"   ? array.get(iH1, j) :
         laneEnd == "SD -2"   ? array.get(iH2, j) :
         laneEnd == "SD -2.5" ? array.get(iH3, j) :
         laneEnd == "SD -4"   ? array.get(iH4, j) :
         array.get(iDn, j)
 
// Does any live setup still hold this direction's lane?
f_laneHeld(int dir) =>
    held = false
    if ecoMode == "One Trade At A Time" and array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iDir, j) == dir and array.get(iSt, j) < 2 and not f_laneDone(j)
                // Stall valve: a setup that stopped ticking rungs is over
                // even though nothing stopped it out. Without this a flat
                // zone would lock its direction until the day roll.
                if not (laneStall > 0 and bar_index - array.get(iPrg, j) > laneStall)
                    held := true
    held
 
// The single price a counter-print must close through to invalidate EVERY
// zone holding this lane. A bull zone (support) dies on a close under its
// bottom, a bear zone (resistance) on a close over its top: so beating
// all of them means the deepest bottom / the highest top.
f_laneFar(int dir) =>
    float far = na
    if array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iDir, j) == dir and array.get(iSt, j) < 2 and not f_laneDone(j)
                fv = dir == 1 ? array.get(iBot, j) : array.get(iTop, j)
                far := na(far) ? fv : (dir == 1 ? math.min(far, fv) : math.max(far, fv))
    far
 
// Is any live setup in this direction already in delivery (SD -1 tagged)?
// A supersede REWRITES the entry of the zone it outgrades: fair before the
// trade starts working, a lie once price is running from the first entry.
f_delivering(int dir) =>
    hit = false
    if array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iDir, j) == dir and array.get(iSt, j) < 2 and array.get(iH1, j)
                hit := true
    hit
 
// Reversal gate: has this print earned the right to fire against a live
// opposite-direction trade? `dir` = direction of the NEW setup.
// THE discriminator: a real turn CLOSES through the live zone (the same
// close that stops that trade out). A pullback wicks into the zone and
// closes back on the live trade's side, so it never clears this and the
// counter-entry never prints. Grade + displacement stop a marginal poke
// through the edge from qualifying as a turn.
f_revOk(int dir, int cnt, int minRev, bool disp, float swHi, float swLo) =>
    ok = revMode != "Never" and cnt >= minRev and (not revDisp or disp)
    if ok
        far = f_laneFar(-dir)
        if not na(far)
            ok := dir == -1 ? close < far : close > far
    if ok and revMode == "Structure Shift"
        ok := dir == -1 ? close < swLo : close > swHi
    ok
 
// Nearest-liquidity accumulators for the trade-plan TP (v5.0): fold a
// candidate level into the running nearest-above / nearest-below
f_nUp(float best, float lvl, bool ok, float minPx) =>
    ok and not na(lvl) and lvl > minPx and (na(best) or lvl < best) ? lvl : best
f_nDn(float best, float lvl, bool ok, float maxPx) =>
    ok and not na(lvl) and lvl < maxPx and (na(best) or lvl > best) ? lvl : best
 
// Any pool level beyond a minimum distance? (targets must have room to run)
f_poolAbove(array<float> arr, float minPx) =>
    hit = false
    if array.size(arr) > 0
        for k = 0 to array.size(arr) - 1
            if array.get(arr, k) > minPx
                hit := true
    hit
 
f_poolBelow(array<float> arr, float maxPx) =>
    hit = false
    if array.size(arr) > 0
        for k = 0 to array.size(arr) - 1
            if array.get(arr, k) < maxPx
                hit := true
    hit
 
// Remove a gap from the watch pool
f_wDel(int i) =>
    array.remove(wTop, i)
    array.remove(wBot, i)
    array.remove(wDir, i)
    array.remove(wBI,  i)
    array.remove(wCtB, i)
    array.remove(wCtC, i)
    array.remove(wMem, i)   // v6.27: EVERY column, or the rows desync
    array.remove(wSeal,i)   // v6.28
    0
 
// v6.27: SERIES CLUSTERS.
// A cluster is its OWN watch row, created ALONGSIDE its members rather than replacing
// them. That is the whole architectural change: previously fusion widened an existing row
// in place and never pushed the new gap, so the individual gaps ceased to exist. Series
// could then never show a member's own setup, Singular could never show the cluster's, and
// "Both" could not show both because no version of the pool ever held both at once.
//
// Holding both means the Detection mode reduces to a display filter at print time:
//   Singular -> wMem == 1     Series -> wMem >= 2     Both -> anything
// It also means Series surfaces setups that DO NOT EXIST in Singular: a cluster inverts on
// a close through the far side of the WHOLE union range, which is a different bar and a
// different price from any single member's inversion.
//
// v6.28: SAME LEG is now the REAL thing, not an approximation of it. A row whose leg has
// ended is sealed (wSeal) and is skipped as both an extend target and a seed, so a cluster
// can never cross a swing into the next leg. The old seriesAdj bar-gap test is gone: it
// bounded the distance between consecutive members and therefore bounded nothing, letting a
// chain of gaps every <= 3 bars run across three legs.
// wBI stays pinned at the cluster's ORIGIN so the drawn box spans the whole run.
//
// Returns the resulting member count (0 = no cluster formed).
f_wCluster(int dir, float gTop, float gBot) =>
    int outN = 0
    int hit  = -1
    // Extend the newest still-building cluster of this direction. v6.28: "still building"
    // now means its leg has not closed: nothing to do with how many bars ago it last grew.
    if array.size(wTop) > 0
        for j = array.size(wTop) - 1 to 0
            if hit < 0 and array.get(wDir, j) == dir and array.get(wMem, j) >= 2 and not array.get(wSeal, j)
                hit := j
    if hit >= 0
        array.set(wTop,  hit, math.max(array.get(wTop, hit), gTop))
        array.set(wBot,  hit, math.min(array.get(wBot, hit), gBot))
        array.set(wMem,  hit, array.get(wMem, hit) + 1)
        // A widened range invalidates any close-through already stamped against the old,
        // narrower one: the unit inverts on the far side of the WHOLE run.
        array.set(wCtB,  hit, int(na))
        array.set(wCtC,  hit, float(na))
        outN := array.get(wMem, hit)
    else
        // No open cluster: seed one from the newest LONE same-direction gap still in leg.
        // v6.28: an unsealed lone gap IS "still in leg": sealing it is what stops a gap from
        // the previous leg pairing with one from the new leg across the swing.
        int seed = -1
        if array.size(wTop) > 0
            for j = array.size(wTop) - 1 to 0
                if seed < 0 and array.get(wDir, j) == dir and array.get(wMem, j) == 1 and not array.get(wSeal, j)
                    seed := j
        if seed >= 0
            array.push(wTop,  math.max(array.get(wTop, seed), gTop))
            array.push(wBot,  math.min(array.get(wBot, seed), gBot))
            array.push(wDir,  dir)
            array.push(wBI,   array.get(wBI, seed))   // anchor at the cluster's ORIGIN
            array.push(wCtB,  int(na))
            array.push(wCtC,  float(na))
            array.push(wMem,  2)
            array.push(wSeal, false)   // v6.28: born inside a live leg by construction
            outN := 2
    outN
 
// Add an inverted gap to the visible arrays and draw its visuals.
// v5.14 rendering: ONE clean borderless fill spanning the origin gap
// structure through the inversion candle. Static: never extends, no
// border, no text. Grade + full checklist + plan numbers live in the
// entry-marker (MM± label) hover tooltip.
// One SD level: dotted segment + tiny tag (na line/label when off).
// Styling from the SD Color / Width inputs (v5.10).
f_sdLine(float lvl, int x1, int x2, bool on) =>
    ln = on ? line.new(x1, lvl, x2, lvl, color=sdCol, width=sdWidth, style=f_ls(sdStyle)) : line(na)
    ln
 
// v6.38: position size for one setup. ONE implementation, called by the trade
// plan label and by both New Setup alerts, so the number a member reads on the
// chart and the number in their notification cannot disagree. Returns [contracts,
// dollars at risk]. Guards a zero stop distance rather than dividing by it: an
// exact-entry stop is degenerate, not a reason to throw.
f_size(float ent, float slv) =>
    float perR = math.abs(ent - slv) * syminfo.pointvalue
    // v6.42: "one mini does not fit" is just perR > riskBud. Deliberately NOT a
    // floor()==0 test - the qty expression below keeps the exact shape that has
    // compiled since v5.0, and this avoids introducing a second float-to-int
    // conversion next to it.
    bool  micro = perR > riskBud and microRat > 1
    float uR    = micro ? perR / microRat : perR
    int   qty   = uR > 0 ? math.max(1, math.floor(riskBud / uR)) : 1
    [qty, uR * qty, micro]
 
// The ONLY place the unit noun is chosen. Chart label, hover tooltip and both
// New Setup alerts all read it, so they cannot drift into disagreeing about
// whether a number means minis or micros.
f_sizeUnit(int qty, bool micro) =>
    micro ? (qty == 1 ? " micro" : " micros") : (qty == 1 ? " mini contract" : " mini contracts")
 
f_sdTag(float lvl, int x2, string txt, bool on) =>
    lb = on ? label.new(x2 + 1, lvl, txt, style=label.style_none,
         textcolor=sdCol, size=size.small) : label(na)
    lb
 
// ── v6.34 Track Record counters ──────────────────────────────────────────
// Declared HERE, above f_addIFVG, because a Pine function cannot reference a
// global declared below it. `var` and not `varip`: realtime rollback must rewind
// these exactly as it rewinds the SD latches they are hooked to, or a live bar
// recalculating would count the same event repeatedly.
 
// v6.12: `legOpp` = the OPPOSITE swing extreme from legExt (bear: legLo,
// bull: legHi). Only the "Full Displacement Leg" SD mode reads it: it needs
// both ends of the impulse, not just the half between the extreme and entry.
f_addIFVG(float tp, float bt, int dir, int leftBI, int cnt, string chk, float ent, float slv, float tpv, float legExt, float legOpp, int invB) =>
    // TradingView rejects bar_index drawing coords >10,000 bars back from the
    // current bar. A gap can sit in the watch pool for thousands of bars before
    // it inverts, so clamp the left anchor to a safe distance.
    lb = math.max(leftBI, bar_index - MAX_BACK)   // v6.44: was 9500
    // v5.15: everything anchors to the TRUE inversion bar (first
    // confirmed close-through), not the print bar: a deferred print
    // stamps exactly where the inversion happened.
    int ivB = math.max(invB, lb)
 
    // v5.14 visual overhaul: the zone is a pure borderless fill: no
    // border, no grade letter, no text. The whole setup story moved to
    // the entry-marker tooltip (hover the MM± label).
    bx = box.new(lb, tp, ivB, bt, border_width=0, bgcolor=f_zFill(0))
 
    // Optional CE midline: v5.16: spans exactly the zone box (origin →
    // inversion candle), static like the box itself. No projection past
    // the IFVG.
    mid = (tp + bt) / 2
    ln  = showCE ? line.new(lb, mid, ivB, mid,
         color=color.new(ceCol, ceTransp), style=f_ceLS(), width=1) : line(na)
 
    // v5.0 trade plan: entry @ inversion close, SL beyond the leg
    // extreme, TP at nearest real liquidity, auto contracts + $ risk.
    // Lines extend while the setup lives; SL/TP die with the zone.
    // v6.38: was three inline lines here; now the shared f_size so the label and
    // the alert quote one evaluation.
    [qty, rsk, isMicro] = f_size(ent, slv)
    color pCol = dir == 1 ? peBullCol : peBearCol
    // Fixed-length stamps: v6.8: shortened to 5 bars so the entry/SL
    // lines end with the SD ladder instead of jutting out past the setup
    // (was 12). v5.15: anchored at the TRUE inversion bar, not the print bar.
    int   pX2  = ivB + 5
    pe = showPlan ? line.new(ivB, ent, pX2, ent, color=pCol, width=peWidth) : line(na)
    ps = showPlan and showSLln ? line.new(ivB, slv, pX2, slv,
         color=slCol, width=slWidth, style=f_ls(slStyle)) : line(na)
    // v6.8 SD projections: the spec (marked on a bearish example):
    //   1 = the swing extreme (bear = swing HIGH / bull = swing LOW = legExt)
    //   0 = the IFVG entry (inversion close)
    // unit = that manipulation leg (|swing extreme − entry|). The ladder
    // projects standard deviations PAST the entry in the trade direction:
    // bearish steps DOWN, bullish steps UP: toward the draw. No block, no
    // breaker: just the leg and the entry. Same method as the HTF CISD
    // ladder; only the leg source differs (IFVG swing, not the CISD leg).
    // v6.12: four ways to size one deviation (input "SD Measured From").
    // The ladder multiples and the entry anchor are IDENTICAL in all four:
    // only the unit changes, which is what lets a scalper and a swing trader
    // run the same setup at their own scale.
    //   Swing → Entry ........ |swing extreme − entry|   (v6.8 spec, default)
    //   IFVG Box ............. the inverted gap's height  (tightest)
    //   Full Displacement Leg  swing high → swing low     (widest)
    //   Entry → Stop (R) ..... |entry − SL|, so rungs read 1R/2R/2.5R/4R
    //     and it inherits SL Placement automatically (IFVG stop = tight R,
    //     Swing stop = structural R). slv already carries the tick buffer.
    float sUnit = sdLeg == "IFVG Box"              ? math.abs(tp - bt)      :
         sdLeg == "Full Displacement Leg" ? math.abs(legExt - legOpp) :
         sdLeg == "Entry → Stop (R)"      ? math.abs(ent - slv)       :
         math.abs(legExt - ent)
    // A degenerate unit would stack all four rungs on the entry and, worse,
    // hand the v6.11 lane rule an SD -4 that price tags instantly. Fall back
    // to the v6.8 leg, then to the box, rather than ever projecting zero.
    if na(sUnit) or sUnit <= 0
        sUnit := math.abs(legExt - ent)
    if na(sUnit) or sUnit <= 0
        sUnit := math.abs(tp - bt)
    float sd1 = dir == 1 ? ent + 1.0 * sUnit : ent - 1.0 * sUnit
    float sd2 = dir == 1 ? ent + 2.0 * sUnit : ent - 2.0 * sUnit
    float sd3 = dir == 1 ? ent + 2.5 * sUnit : ent - 2.5 * sUnit
    float sd4 = dir == 1 ? ent + 4.0 * sUnit : ent - 4.0 * sUnit
    bool  sdOn = showPlan and showSD
    // v6.7: SD segments run SHORT (5 bars) to match the HTF ladder: the
    // old +12 stamps bled into the next setup and made a visual mess.
    int   sdX2 = ivB + 5
    q1 = f_sdLine(sd1, ivB, sdX2, sdOn)
    q2 = f_sdLine(sd2, ivB, sdX2, sdOn)
    q3 = f_sdLine(sd3, ivB, sdX2, sdOn)
    q4 = f_sdLine(sd4, ivB, sdX2, sdOn)
    t1 = f_sdTag(sd1, sdX2, "-1",   sdOn)
    t2 = f_sdTag(sd2, sdX2, "-2",   sdOn)
    t3 = f_sdTag(sd3, sdX2, "-2.5", sdOn)
    t4 = f_sdTag(sd4, sdX2, "-4",   sdOn)
    // Label sits past the line end, staggered off the entry price
    // (shorts above, longs below) so clustered lines can't strike
    // through the text. v5.14: the label carries the setup pop-up:
    // hover it and the full graded checklist for THIS zone appears.
    string tipTxt = f_grade(cnt) + " Setup · " + str.tostring(cnt) + "/6" +
         "\n✓ IFVG\n" + chk +
         "\n──────────" +
         "\nEntry " + str.tostring(ent, format.mintick) +
         "\nStop  " + str.tostring(slv, format.mintick) +
         "\nSize  " + str.tostring(qty) + f_sizeUnit(qty, isMicro) +
         " ($" + str.tostring(rsk, "#,###") + " risk)"
    // House rule (v6.9): ONE trade-plan label on the chart at a time: the
    // NEWEST setup carries it. Before drawing this print's label, wipe every
    // prior one (entry/SL lines and the SD ladder all stay; only the MM±
    // label goes). Guard the loop: `for 0 to size-1` runs once when size = 0.
    if showPlan and array.size(pLb) > 0
        for li = 0 to array.size(pLb) - 1
            label.delete(array.get(pLb, li))
            array.set(pLb, li, label(na))
    pb = showPlan ? label.new(pX2 + 1, ent + (dir == 1 ? -1 : 1) * math.abs(ent - slv) * 0.12,
         (dir == 1 ? "MM+" : "MM-") + " • " + str.tostring(qty) +
         f_sizeUnit(qty, isMicro) + " = $" + str.tostring(rsk, "#,###"),
         style=label.style_label_left, color=color.new(color.black, 100),
         textcolor=pCol, size=f_szName(pLblSz), tooltip=tipTxt) : label(na)
 
    // Store in arrays: store the CLAMPED anchor so nothing downstream
    // ever references an out-of-range bar index
    array.push(iTop, tp)
    array.push(iBot, bt)
    array.push(iDir, dir)
    array.push(iSt,  0)
    array.push(iBI,  lb)
    array.push(iInv, ivB)
    array.push(iSc,  cnt)
    array.push(iDn,  false)
    array.push(iTp,  tpv)
    array.push(iBx,  bx)
    array.push(iLn,  ln)
    array.push(pLE,  pe)
    array.push(pLS,  ps)
    array.push(pS1,  q1)
    array.push(pS2,  q2)
    array.push(pS3,  q3)
    array.push(pS4,  q4)
    array.push(pT1,  t1)
    array.push(pT2,  t2)
    array.push(pT3,  t3)
    array.push(pT4,  t4)
    array.push(pLb,  pb)
    array.push(iS1,  sd1)
    array.push(iS2,  sd2)
    array.push(iS3,  sd3)
    array.push(iS4,  sd4)
    array.push(iH1,  false)
    array.push(iH2,  false)
    array.push(iH3,  false)
    array.push(iH4,  false)
    array.push(iChk, chk)
    // v6.11: the lane clock starts at the TRUE inversion bar, not the print
    // bar: a deferred print must not buy itself extra stall time.
    array.push(iPrg, ivB)
    0
 
// Remove an IFVG and clean up its visuals
f_iDel(int i) =>
    box.delete(array.get(iBx, i))
    line.delete(array.get(iLn, i))
    array.remove(iTop, i)
    array.remove(iBot, i)
    array.remove(iDir, i)
    array.remove(iSt,  i)
    array.remove(iBI,  i)
    array.remove(iInv, i)
    array.remove(iSc,  i)
    array.remove(iDn,  i)
    array.remove(iTp,  i)
    array.remove(iBx,  i)
    array.remove(iLn,  i)
    line.delete(array.get(pLE, i))
    line.delete(array.get(pLS, i))
    label.delete(array.get(pLb, i))
    line.delete(array.get(pS1, i))
    line.delete(array.get(pS2, i))
    line.delete(array.get(pS3, i))
    line.delete(array.get(pS4, i))
    label.delete(array.get(pT1, i))
    label.delete(array.get(pT2, i))
    label.delete(array.get(pT3, i))
    label.delete(array.get(pT4, i))
    array.remove(pLE, i)
    array.remove(pLS, i)
    array.remove(pS1, i)
    array.remove(pS2, i)
    array.remove(pS3, i)
    array.remove(pS4, i)
    array.remove(pT1, i)
    array.remove(pT2, i)
    array.remove(pT3, i)
    array.remove(pT4, i)
    array.remove(iS1, i)
    array.remove(iS2, i)
    array.remove(iS3, i)
    array.remove(iS4, i)
    array.remove(iH1, i)
    array.remove(iH2, i)
    array.remove(iH3, i)
    array.remove(iH4, i)
    array.remove(iChk, i)
    array.remove(iPrg, i)
    array.remove(pLb, i)
    0
 
// v6.12: ONE teardown for a plan that is no longer tradeable. Stop-out and
// supersede both land here. Before this, supersede only faded the box: the
// outgraded setup kept its SL line, its full SD ladder and its target labels,
// so a zone the engine had already retired sat on the chart looking exactly
// like a second live trade stacked on the winner. Same death, same footprint.
f_planKill(int i) =>
    line.delete(array.get(pLS, i))
    array.set(pLS, i, line(na))
    line.delete(array.get(pS1, i))
    line.delete(array.get(pS2, i))
    line.delete(array.get(pS3, i))
    line.delete(array.get(pS4, i))
    label.delete(array.get(pT1, i))
    label.delete(array.get(pT2, i))
    label.delete(array.get(pT3, i))
    label.delete(array.get(pT4, i))
    array.set(pS1, i, line(na))
    array.set(pS2, i, line(na))
    array.set(pS3, i, line(na))
    array.set(pS4, i, line(na))
    array.set(pT1, i, label(na))
    array.set(pT2, i, label(na))
    array.set(pT3, i, label(na))
    array.set(pT4, i, label(na))
    // The entry line + risk label are the journal record: they survive only
    // when the user keeps stopped plans (v5.6 semantics, unchanged).
    if not keepPlans
        line.delete(array.get(pLE, i))
        label.delete(array.get(pLb, i))
        array.set(pLE, i, line(na))
        array.set(pLb, i, label(na))
    0
 
// Supersede: a strictly higher-graded setup off the SAME raid replaces
// the zone that spent it. The lesser zone fades (or deletes if failed
// zones aren't kept) with no alert: it wasn't wrong, it was outgraded.
// v6.12: `invBar` is the outgraded zone's INVERSION bar (iInv), never the
// bar its print landed on: a deferred print anchors at the close-through
// (v5.15), so matching on the print bar silently retired nothing.
f_supersede(int dir, int invBar) =>
    if not na(invBar) and array.size(iDir) > 0
        for j = array.size(iDir) - 1 to 0
            if array.get(iDir, j) == dir and array.get(iSt, j) < 2 and array.get(iInv, j) == invBar
                if keepKill
                    array.set(iSt, j, 2)
                    box.set_bgcolor(array.get(iBx, j), f_zFill(2))
                    // v6.12: retire the plan too, or the loser reads as live
                    f_planKill(j)
                else
                    f_iDel(j)
    0
 
// Stacked-gap absorption: THE RULE: "You either have a singular fair
// value gap (preferred) or you have 1-2-3 stacked and that's when you
// combine." A new inversion only swallows an ACTIVE same-direction zone
// it is physically STACKED with: overlapping or edge-to-edge within tol.
// No same-leg merging, no time-based merging: that unioned entire legs.
// Returns the merged [top, bottom, leftAnchor, bestCount] after deleting
// the absorbed zones.
f_absorb(float zt0, float zb0, int dir, int l0, float tol, int cnt0, bool doMerge) =>
    zt  = zt0
    zb  = zb0
    lft = l0
    mx  = cnt0
    if doMerge and array.size(iTop) > 0
        for j = array.size(iTop) - 1 to 0
            if array.get(iSt, j) < 2 and array.get(iDir, j) == dir
                // Vertical distance between the zones (0 = overlapping)
                jt = array.get(iTop, j)
                jb = array.get(iBot, j)
                vGap = zb > jt ? zb - jt : jb > zt ? jb - zt : 0.0
                if vGap <= tol
                    zt  := math.max(zt, jt)
                    zb  := math.min(zb, jb)
                    lft := math.min(lft, array.get(iBI, j))
                    mx  := math.max(mx, array.get(iSc, j))
                    f_iDel(j)
    [zt, zb, lft, mx]
 
 
// ═══════════════════════════════════════════════════════════════════════
//  GLOBAL SERIES: must run every bar
// ═══════════════════════════════════════════════════════════════════════
 
float atrVal = ta.atr(14)
 
// Displacement: an impulsive body inside the last 5 bars
bool bodyOK     = math.abs(close - open) >= dispMult * atrVal
bool dispRecent = bodyOK or bodyOK[1] or bodyOK[2] or bodyOK[3] or bodyOK[4]
 
// Raid extremes: the price printed during a sweep's confirmation window.
// Computed globally (ta.* must run every bar); consumed by the sweep-hold check.
float raidLo = ta.lowest(low,  sweepConfirmBars + 1)
float raidHi = ta.highest(high, sweepConfirmBars + 1)
 
// Regime extremes for MINOR raid dominance (v4.8, window made an input
// in v4.14): a swing/data raid only credits when the raided level IS
// the extreme of the Dominance Window. Offset [1] excludes the raid bar
// itself. History: the original 2× Setup Window (60 bars) killed the
// counter-trend prints but ALSO vetoed every pullback raid inside a
// trend: with-trend continuation setups this tool is meant to catch. The
// default is now ~one-hour scale; the sequence lock is the primary
// counter-trend police. ta.* must run every bar: keep these global.
float domTol = 0.1 * atrVal
float regHi  = ta.highest(high, domWin)[1]
float regLo  = ta.lowest(low,   domWin)[1]
 
// Rolling extremes for the lag-free raid source (v4.16): the prior
// N-bar high/low, excluding the current bar. A breach that closes back
// is a sweep of THE recent extreme regardless of pivot confirmation.
float extHi = ta.highest(high, extWin)[1]
float extLo = ta.lowest(low,  extWin)[1]
 
// Leg extremes for the trade-plan SL (v5.0): the extreme of the move
// that built the setup, window bounded by the max possible gap age
float legHi = ta.highest(high, invWin + 5)
float legLo = ta.lowest(low,  invWin + 5)
 
// ── Previous Day / Week / Month highs & lows ──
// Canonical non-repaint read: offset [1] + lookahead_on = last CONFIRMED
// HTF bar, identical on history and realtime. Levels only count when the
// chart TF is actually below that timeframe.
// v6.33: `time[1]` APPENDED AT THE TAIL of each tuple - the open of the period the
// level came from, used as the drawn line's left anchor. Appending cannot shift an
// existing field under positional destructuring, which is the only safe way to grow
// a security tuple. Still three security calls; elements are free, calls are not.
[pdhR, pdlR, pdT] = request.security(syminfo.tickerid, "D", [high[1], low[1], time[1]], lookahead=barmerge.lookahead_on)
[pwhR, pwlR, pwT] = request.security(syminfo.tickerid, "W", [high[1], low[1], time[1]], lookahead=barmerge.lookahead_on)
[pmhR, pmlR, pmT] = request.security(syminfo.tickerid, "M", [high[1], low[1], time[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
 
// ═══════════════════════════════════════════════════════════════════════
//  KEY LEVEL LINES (v6.33): ported from the levels tool, same-price merging intact
// ═══════════════════════════════════════════════════════════════════════
//  Values above were already here. This is only the drawing.
//  time(tf) is a built-in, not a security request, so the period-roll tests below
//  cost nothing against the 40-call budget.
bool klNewD = nz(ta.change(time("D")), 0) != 0
bool klNewW = nz(ta.change(time("W")), 0) != 0
bool klNewM = nz(ta.change(time("M")), 0) != 0
 
// Swept state. A level taken since its period opened keeps its line and gains a
// tick; the flag clears when the period rolls, never on a timer.
var bool pdhSwept = false
var bool pdlSwept = false
var bool pwhSwept = false
var bool pwlSwept = false
var bool pmhSwept = false
var bool pmlSwept = false
if klNewD
    pdhSwept := false
    pdlSwept := false
if klNewW
    pwhSwept := false
    pwlSwept := false
if klNewM
    pmhSwept := false
    pmlSwept := false
if not na(pdh) and high > pdh
    pdhSwept := true
if not na(pdl) and low < pdl
    pdlSwept := true
if not na(pwh) and high > pwh
    pwhSwept := true
if not na(pwl) and low < pwl
    pwlSwept := true
if not na(pmh) and high > pmh
    pmhSwept := true
if not na(pml) and low < pml
    pmlSwept := true
 
// Left-anchor fallback for when history does not reach the period open.
var int klChartStart = na
if na(klChartStart)
    klChartStart := time
 
// Persistent drawings, wiped and rebuilt on the last bar.
var array<line>  klLines = array.new<line>()
var array<label> klLabels = array.new<label>()
 
// Collection arrays, cleared and repopulated every bar.
var array<float>  klP = array.new<float>()
var array<string> klT = array.new<string>()
var array<color>  klC = array.new<color>()
var array<int>    klA = array.new<int>()
array.clear(klP)
array.clear(klT)
array.clear(klC)
array.clear(klA)
 
// Add a level, or MERGE it into an existing entry at the same price. Two levels a
// tick apart are not two pieces of information, and drawing them as two lines says
// they are. Copied hand for hand from the levels tool. The earlier anchor wins so the
// merged line starts at whichever level formed first.
f_addLevel(array<float> aP, array<string> aT, array<color> aC, array<int> aA, float price, string txt, color col, int anchor) =>
    bool done = false
    int sz = array.size(aP)
    if not na(price) and sz > 0
        for j = 0 to sz - 1
            if not done and math.abs(array.get(aP, j) - price) < syminfo.mintick * 0.5
                array.set(aT, j, array.get(aT, j) + " / " + txt)
                int existA = array.get(aA, j)
                if not na(anchor) and (na(existA) or anchor < existA)
                    array.set(aA, j, anchor)
                done := true
    if not na(price) and not done
        array.push(aP, price)
        array.push(aT, txt)
        array.push(aC, col)
        array.push(aA, anchor)
    0
 
f_klTick(bool swept) =>
    klSweptTick and swept ? " ✓" : ""
 
if klMoOn and not na(pmh)
    f_addLevel(klP, klT, klC, klA, pmh, (klShorthand ? "PMH" : "Prev Month High") + f_klTick(pmhSwept), klMoCol, pmT)
if klMoOn and not na(pml)
    f_addLevel(klP, klT, klC, klA, pml, (klShorthand ? "PML" : "Prev Month Low") + f_klTick(pmlSwept), klMoCol, pmT)
if klWkOn and not na(pwh)
    f_addLevel(klP, klT, klC, klA, pwh, (klShorthand ? "PWH" : "Prev Week High") + f_klTick(pwhSwept), klWkCol, pwT)
if klWkOn and not na(pwl)
    f_addLevel(klP, klT, klC, klA, pwl, (klShorthand ? "PWL" : "Prev Week Low") + f_klTick(pwlSwept), klWkCol, pwT)
if klDayOn and not na(pdh)
    f_addLevel(klP, klT, klC, klA, pdh, (klShorthand ? "PDH" : "Prev Day High") + f_klTick(pdhSwept), klDayCol, pdT)
if klDayOn and not na(pdl)
    f_addLevel(klP, klT, klC, klA, pdl, (klShorthand ? "PDL" : "Prev Day Low") + f_klTick(pdlSwept), klDayCol, pdT)
 
if barstate.islast
    while array.size(klLines) > 0
        line.delete(array.pop(klLines))
    while array.size(klLabels) > 0
        label.delete(array.pop(klLabels))
    if array.size(klP) > 0
        // Bar width from the chart TF, never time - time[1]. That delta equals the
        // weekend gap on the first bar after a reopen, which would throw the right
        // edge tens of days out and silently ignore the user's Extend Right setting.
        // the levels tool scar, inherited rather than re-earned.
        int klTfSec = timeframe.in_seconds()
        int klBarMs = klTfSec > 0 ? klTfSec * 1000 : nz(time - time[1], 60000)
        int klRight = time + klBarMs * klExtendBars
        for i = 0 to array.size(klP) - 1
            float kp = array.get(klP, i)
            string kt = array.get(klT, i)
            color kc = array.get(klC, i)
            int ka = array.get(klA, i)
            string kPx = klShowPrice ? " " + str.tostring(kp, format.mintick) : ""
            int klLeft = time
            if not na(ka) and not na(klChartStart) and ka >= klChartStart
                klLeft := ka
            else if not na(klChartStart)
                klLeft := klChartStart
            array.push(klLines, line.new(klLeft, kp, klRight, kp, xloc = xloc.bar_time, color = kc, style = f_lstyle(klStyleIn == "Dashed" ? "----" : klStyleIn == "Dotted" ? "····" : "⎯⎯⎯"), width = klWidth))
            array.push(klLabels, label.new(klRight, kp, text = kt + kPx, xloc = xloc.bar_time, style = label.style_none, textcolor = kc, size = f_szName(klLblSz == "Tiny" ? "Tiny" : klLblSz == "Normal" ? "Medium" : "Small")))
 
// ── Session extremes (prior completed session): Asia / London / NY ──
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] = f_sessLvls(inAsia)
[lonH,  lonL]  = f_sessLvls(inLon)
[nyH,   nyL]   = f_sessLvls(inNY)
 
// ── Level states: sweep events + taken latches (12 unconditional sites) ──
[swPdh, tkPdh] = f_lvlState(pdh,   true)
[swPwh, tkPwh] = f_lvlState(pwh,   true)
[swPmh, tkPmh] = f_lvlState(pmh,   true)
[swPdl, tkPdl] = f_lvlState(pdl,   false)
[swPwl, tkPwl] = f_lvlState(pwl,   false)
[swPml, tkPml] = f_lvlState(pml,   false)
[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)
 
// ── HTF FVGs for Delivery: same 3-candle logic, scanned on the whole
//    HTF ladder above the chart (15m / 1H / 4H / D). No fractal pairing,
//    no order blocks: any HTF fair value gap is a PD array price can
//    deliver into. ──
// v6.15: same v4.29 timing fix the DRAWN HTF FVG engine got: this pool had its own copy
// of the identical bug. barstate.isconfirmed inside the tuple reads true across the whole
// HTF context on historical bars, so the gap test ran against the DEVELOPING HTF bar's
// running low/high, and the flag could latch mid-bar and carry into the next HTF bar. The
// rising edge `flag and not flag[1]` then never re-fired, so back-to-back gaps in one
// displacement leg added ONE zone for the whole streak. It also made history and realtime
// disagree, live, barstate.isconfirmed is false until the HTF bar closes, which meant a
// Delivery ✓ was not reproducible between a replay and the live chart.
//
// Now non-repaint idiom A: last CLOSED HTF bar via [1] + lookahead_on, fired on the HTF
// bar's TIME changing. The completed 3-candle pattern sits at [3][2][1] relative to the
// developing bar: c1 = [3] (the gap's far side), c2 = [2] (the displacement body),
// c3 = [1] (the near side). time[1] rides in the tuple purely as the fire trigger.
// v6.20: REVERTED to the pre-v6.15 reads. The idiom-A fix is correct in principle: the
// old form evaluates barstate.isconfirmed across the whole HTF context on history, so it
// reads the DEVELOPING HTF bar: but changing it also changes how Delivery grades on
// historical bars, and Delivery feeds cntBear/cntBull, which feed the print gates. A setup
// that printed live can therefore fail to print on a recalculation. Isolating that here.
[h15B, h15BT, h15BB, h15S, h15ST, h15SB] = request.security(syminfo.tickerid, "15",
     [barstate.isconfirmed and low > high[2] and close[1] > open[1], low, high[2],
      barstate.isconfirmed and high < low[2] and close[1] < open[1], low[2], high],
     lookahead=barmerge.lookahead_off)
[h60B, h60BT, h60BB, h60S, h60ST, h60SB] = request.security(syminfo.tickerid, "60",
     [barstate.isconfirmed and low > high[2] and close[1] > open[1], low, high[2],
      barstate.isconfirmed and high < low[2] and close[1] < open[1], low[2], high],
     lookahead=barmerge.lookahead_off)
[h4B, h4BT, h4BB, h4S, h4ST, h4SB] = request.security(syminfo.tickerid, "240",
     [barstate.isconfirmed and low > high[2] and close[1] > open[1], low, high[2],
      barstate.isconfirmed and high < low[2] and close[1] < open[1], low[2], high],
     lookahead=barmerge.lookahead_off)
[hDB, hDBT, hDBB, hDS, hDST, hDSB] = request.security(syminfo.tickerid, "D",
     [barstate.isconfirmed and low > high[2] and close[1] > open[1], low, high[2],
      barstate.isconfirmed and high < low[2] and close[1] < open[1], low[2], high],
     lookahead=barmerge.lookahead_off)
 
// ── Aligned-TF swing pivots for the sweep engine (v4.11): canonical
//    confirmed read: [1] offset + lookahead_on = last CLOSED HTF bar,
//    identical on history and realtime. 9th security call. ──
[alPh, alPl] = request.security(syminfo.tickerid, f_alignTf(),
     [ta.pivothigh(high, swingLen, swingLen)[1], ta.pivotlow(low, swingLen, swingLen)[1]],
     lookahead=barmerge.lookahead_on)
 
// ── SMT correlate: did the other symbol take out ITS own recent
//    extreme? Window matched to our swing scale (2×swingLen+1) so the
//    comparison is like-for-like, not our 3-bar raid vs its 20-bar low.
//    Canonical confirmed read; == true on security bools. ──
[cTL, cTH] = request.security(f_corrSym(), timeframe.period,
     [low[1] < ta.lowest(low, 2 * swingLen + 1)[2], high[1] > ta.highest(high, 2 * swingLen + 1)[2]],
     lookahead=barmerge.lookahead_on)
// == true comparisons: na-safe read of security bools (nz() is numeric-only in v6)
// 6-bar confirmation window: a correlate low printed slightly BEFORE our
// late sweep still counts as "correlate confirmed": timing skew between
// NQ and ES was producing false divergence ✓s (v4.7 calibration finding)
bool corrLowAny  = cTL == true or cTL[1] == true or cTL[2] == true or
     cTL[3] == true or cTL[4] == true or cTL[5] == true
bool corrHighAny = cTH == true or cTH[1] == true or cTH[2] == true or
     cTH[3] == true or cTH[4] == true or cTH[5] == true
 
 
// ═══════════════════════════════════════════════════════════════════════
//  LIQUIDITY SWEEP ENGINE: raid + close-back confirmation
// ═══════════════════════════════════════════════════════════════════════
//  Pools per side: unswept swings, data highs/lows (extreme-candle
//  proxy), session extremes, PD/PW/PM levels. A wick through a level is
//  the RAID; it only becomes a SWEEP when price closes back on the
//  original side: same bar, or within sweepConfirmBars via the pending
//  list. A breach that holds is a breakout and never scores.
// ═══════════════════════════════════════════════════════════════════════
 
// Two tiers of sweep. MINOR (swings, data candles) expire after the Setup
// Window and are dominance-gated at raid time (regHi/regLo): only THE
// regime extreme credits. MAJOR (PDH/PDL, PWH/PWL, PMH/PML, session
// extremes) live while the raid's extreme holds, hard-capped at 2× the
// Setup Window (v4.8): an hour-old raid is context, not a license to
// print zones against the new leg.
bool buyMinNow  = false
bool buyMajNow  = false
bool sellMinNow = false
bool sellMajNow = false
 
// Pending confirmations first: raids from earlier bars get this close
if array.size(psLvl) > 0
    for i = array.size(psLvl) - 1 to 0
        lv = array.get(psLvl, i)
        dr = array.get(psDir, i)
        tr = array.get(psTier, i)
        if (dr == 1 and close < lv) or (dr == -1 and close > lv)
            if dr == 1
                if tr == 1
                    buyMajNow := true
                else
                    buyMinNow := true
            else
                if tr == 1
                    sellMajNow := true
                else
                    sellMinNow := true
            array.remove(psLvl,  i)
            array.remove(psDir,  i)
            array.remove(psBar,  i)
            array.remove(psTier, i)
        else if bar_index - array.get(psBar, i) > sweepConfirmBars
            // Never closed back: breakout, not a grab
            array.remove(psLvl,  i)
            array.remove(psDir,  i)
            array.remove(psBar,  i)
            array.remove(psTier, i)
 
// Collect new confirmed swings (confirms swingLen bars late: inherent
// pivot lag). v4.11: when Liquidity Alignment is active, the pool is fed
// by the ALIGNED timeframe's pivots (the sweep that matters is of an HTF swing);
// Chart mode keeps chart-TF pivots. ta.* must run every bar regardless.
bool useAligned = f_alignTf() != timeframe.period
float phN = ta.pivothigh(high, swingLen, swingLen)
float plN = ta.pivotlow(low,  swingLen, swingLen)
// Aligned stream dedup: the same HTF read repeats on every chart bar
// inside that HTF bar: push only when the value changes.
float phAdd = useAligned ? (not na(alPh) and (na(alPh[1]) or alPh != alPh[1]) ? alPh : na) : phN
float plAdd = useAligned ? (not na(alPl) and (na(alPl[1]) or alPl != alPl[1]) ? alPl : na) : plN
if not na(phAdd)
    array.push(pivHi, phAdd)
    if array.size(pivHi) > maxPiv
        array.shift(pivHi)
if not na(plAdd)
    array.push(pivLo, plAdd)
    if array.size(pivLo) > maxPiv
        array.shift(pivLo)
 
// Collect data highs/lows: extreme-range candles (news footprint proxy)
if barstate.isconfirmed and (high - low) > atrVal * dataMult
    array.push(datHi, high)
    array.push(datLo, low)
    if array.size(datHi) > maxDat
        array.shift(datHi)
    if array.size(datLo) > maxDat
        array.shift(datLo)
 
// Swing + data raids (MINOR tier): remove each swept level so it only
// counts once. Dominance gate (v4.8): the breached level must BE the
// regime extreme or the raid never credits (and never goes pending:
// short-circuit skips f_raid). The level still leaves the pool either
// way: breached is breached. v4.11: aligned-TF pivots BYPASS dominance:
// HTF alignment is one significance filter, dominance is
// the other, for chart-TF pivots; running both double-filters. Data candles
// keep dominance in every mode.
if array.size(pivHi) > 0
    for i = array.size(pivHi) - 1 to 0
        lvlH = array.get(pivHi, i)
        if high > lvlH
            array.remove(pivHi, i)
            if (useAligned or not domOn or lvlH >= regHi - domTol) and f_raid(lvlH, 1, 0)
                buyMinNow := true
if array.size(pivLo) > 0
    for i = array.size(pivLo) - 1 to 0
        lvlL = array.get(pivLo, i)
        if low < lvlL
            array.remove(pivLo, i)
            if (useAligned or not domOn or lvlL <= regLo + domTol) and f_raid(lvlL, -1, 0)
                sellMinNow := true
if array.size(datHi) > 0
    for i = array.size(datHi) - 1 to 0
        lvlH = array.get(datHi, i)
        if high > lvlH
            array.remove(datHi, i)
            if (not domOn or lvlH >= regHi - domTol) and f_raid(lvlH, 1, 0)
                buyMinNow := true
if array.size(datLo) > 0
    for i = array.size(datLo) - 1 to 0
        lvlL = array.get(datLo, i)
        if low < lvlL
            array.remove(datLo, i)
            if (not domOn or lvlL <= regLo + domTol) and f_raid(lvlL, -1, 0)
                sellMinNow := true
 
// Rolling-extreme raids (MINOR tier, v4.16): lag-free: the first bar
// poking beyond the prior N-bar extreme registers a raid of that level;
// f_raid's close-back rule (same bar or ≤3) decides grab vs breakout.
// One credit per breach event: consecutive bars above don't re-fire.
bool breachHi = high > extHi and not (high[1] > extHi[1])
bool breachLo = low  < extLo and not (low[1]  < extLo[1])
if breachHi and f_raid(extHi, 1, 0)
    buyMinNow := true
if breachLo and f_raid(extLo, -1, 0)
    sellMinNow := true
 
// Key-level + session raids (MAJOR tier): f_raid decides grab vs breakout
if swPdh and f_raid(pdh, 1, 1)
    buyMajNow := true
if swPwh and f_raid(pwh, 1, 1)
    buyMajNow := true
if swPmh and f_raid(pmh, 1, 1)
    buyMajNow := true
if swAsH and f_raid(asiaH, 1, 1)
    buyMajNow := true
if swLoH and f_raid(lonH, 1, 1)
    buyMajNow := true
if swNyH and f_raid(nyH, 1, 1)
    buyMajNow := true
if swPdl and f_raid(pdl, -1, 1)
    sellMajNow := true
if swPwl and f_raid(pwl, -1, 1)
    sellMajNow := true
if swPml and f_raid(pml, -1, 1)
    sellMajNow := true
if swAsL and f_raid(asiaL, -1, 1)
    sellMajNow := true
if swLoL and f_raid(lonL, -1, 1)
    sellMajNow := true
if swNyL and f_raid(nyL, -1, 1)
    sellMajNow := true
 
// Per-tier sweep records: bar of the raid + the extreme that must HOLD
var int   buyMinBar  = na
var float buyMinPx   = na
var int   buyMajBar  = na
var float buyMajPx   = na
var int   sellMinBar = na
var float sellMinPx  = na
var int   sellMajBar = na
var float sellMajPx  = na
if buyMinNow
    buyMinBar := bar_index
    buyMinPx  := raidHi
if buyMajNow
    buyMajBar := bar_index
    buyMajPx  := raidHi
if sellMinNow
    sellMinBar := bar_index
    sellMinPx  := raidLo
if sellMajNow
    sellMajBar := bar_index
    sellMajPx  := raidLo
 
// Sweep-hold: THE raid marks the extreme. Price trading past it kills the
// credit: for majors this is the ONLY expiry.
if not sellMinNow and not na(sellMinPx) and low < sellMinPx
    sellMinBar := na
    sellMinPx  := na
if not sellMajNow and not na(sellMajPx) and low < sellMajPx
    sellMajBar := na
    sellMajPx  := na
if not buyMinNow and not na(buyMinPx) and high > buyMinPx
    buyMinBar := na
    buyMinPx  := na
if not buyMajNow and not na(buyMajPx) and high > buyMajPx
    buyMajBar := na
    buyMajPx  := na
 
// Aggregate confirm events (feed SMT + the debug markers + the lanes)
bool buySweep  = buyMinNow or buyMajNow
bool sellSweep = sellMinNow or sellMajNow
 
// ── Print-bar tracking for the spacing rule (v5.7) ──
var int lastPrB = na
var int lastPrU = na
 
// ── v5.1 ECONOMY: one rule.
// Duplicate detections are ignored. A new inversion is blocked ONLY
// if it physically overlaps an ACTIVE same-direction zone (f_stacked,
// same tolerance as the merge rule). Distinct-level setups always
// print; same-level re-detections never do. No lanes, no timers, no
// reopen events. This single mechanism explains every behavior the six
// dead economies chased: one print per vertical move (stacked gaps =
// duplicates), back-to-back trend continuations (different levels =
// not duplicates), and starvation is impossible (a zone only blocks
// at its own price).
 
// ── SMT at the sweep: we raided, the correlate held its own level ──
var int lastSmtBull = na
var int lastSmtBear = na
if sellSweep and not corrLowAny
    lastSmtBull := bar_index
if buySweep and not corrHighAny
    lastSmtBear := bar_index
 
 
// ═══════════════════════════════════════════════════════════════════════
//  DELIVERY ENGINE: HTF FVG pool + tap tracking
// ═══════════════════════════════════════════════════════════════════════
//  Live FVGs from every HTF above the chart, held as price zones (never
//  drawn unless debug is on). A zone dies when chart price CLOSES through
//  its far side. Any bar that trades into a zone stamps the tap for that
//  direction: Delivery ✓ when the tap rides the same swing as the sweep.
//  (== true comparisons are the na-safe read for security bools.)
// ═══════════════════════════════════════════════════════════════════════
 
if f_higher("15")
    if h15B == true and not (h15B[1] == true)
        f_hAdd(nz(h15BT), nz(h15BB), 1, "15m")
    if h15S == true and not (h15S[1] == true)
        f_hAdd(nz(h15ST), nz(h15SB), -1, "15m")
if f_higher("60")
    if h60B == true and not (h60B[1] == true)
        f_hAdd(nz(h60BT), nz(h60BB), 1, "1H")
    if h60S == true and not (h60S[1] == true)
        f_hAdd(nz(h60ST), nz(h60SB), -1, "1H")
if f_higher("240")
    if h4B == true and not (h4B[1] == true)
        f_hAdd(nz(h4BT), nz(h4BB), 1, "4H")
    if h4S == true and not (h4S[1] == true)
        f_hAdd(nz(h4ST), nz(h4SB), -1, "4H")
if f_higher("D")
    if hDB == true and not (hDB[1] == true)
        f_hAdd(nz(hDBT), nz(hDBB), 1, "D")
    if hDS == true and not (hDS[1] == true)
        f_hAdd(nz(hDST), nz(hDSB), -1, "D")
 
while array.size(hTop) > maxHtf
    array.shift(hTop)
    array.shift(hBot)
    array.shift(hDir)
    array.shift(hBI)
    array.shift(hTfN)
 
// Taps + mitigation (backward so removals are safe)
var int lastBullTap = na
var int lastBearTap = na
if array.size(hTop) > 0
    for i = array.size(hTop) - 1 to 0
        ht = array.get(hTop, i)
        hb = array.get(hBot, i)
        hd = array.get(hDir, i)
        if low <= ht and high >= hb
            if hd == 1
                lastBullTap := bar_index
            else
                lastBearTap := bar_index
        if barstate.isconfirmed and ((hd == 1 and close < hb) or (hd == -1 and close > ht))
            array.remove(hTop, i)
            array.remove(hBot, i)
            array.remove(hDir, i)
            array.remove(hBI,  i)
            array.remove(hTfN, i)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  CLEAR TARGETS: real draws with room to run
// ═══════════════════════════════════════════════════════════════════════
//  "Clear" means a pool worth trading toward, at least tgtDist away:
//  equal highs/lows (two unswept pivots within tolerance: single micro
//  pivots do NOT count), data highs/lows, session extremes, PD/PW/PM
//  levels. Unswept high-side levels sit above price by construction:
//  the distance check is what separates a target from a level at entry.
// ═══════════════════════════════════════════════════════════════════════
 
float tgtDist = 1.5 * atrVal
float eqTol   = 0.1 * atrVal
 
// Equal highs/lows: a cluster of unswept pivots within tolerance
bool eqhAbove = false
int _szEH = array.size(pivHi)
if _szEH > 1
    for a = 0 to _szEH - 2
        for b2 = a + 1 to _szEH - 1
            va = array.get(pivHi, a)
            vb = array.get(pivHi, b2)
            if math.abs(va - vb) <= eqTol and math.min(va, vb) > close + tgtDist
                eqhAbove := true
bool eqlBelow = false
int _szEL = array.size(pivLo)
if _szEL > 1
    for a = 0 to _szEL - 2
        for b2 = a + 1 to _szEL - 1
            va = array.get(pivLo, a)
            vb = array.get(pivLo, b2)
            if math.abs(va - vb) <= eqTol and math.max(va, vb) < close - tgtDist
                eqlBelow := true
 
bool targetAbove = eqhAbove or f_poolAbove(datHi, close + tgtDist) or
     (not tkPdh and not na(pdh) and pdh > close + tgtDist) or
     (not tkPwh and not na(pwh) and pwh > close + tgtDist) or
     (not tkPmh and not na(pmh) and pmh > close + tgtDist) or
     (not tkAsH and not na(asiaH) and asiaH > close + tgtDist) or
     (not tkLoH and not na(lonH) and lonH > close + tgtDist) or
     (not tkNyH and not na(nyH) and nyH > close + tgtDist)
 
bool targetBelow = eqlBelow or f_poolBelow(datLo, close - tgtDist) or
     (not tkPdl and not na(pdl) and pdl < close - tgtDist) or
     (not tkPwl and not na(pwl) and pwl < close - tgtDist) or
     (not tkPml and not na(pml) and pml < close - tgtDist) or
     (not tkAsL and not na(asiaL) and asiaL < close - tgtDist) or
     (not tkLoL and not na(lonL) and lonL < close - tgtDist) or
     (not tkNyL and not na(nyL) and nyL < close - tgtDist)
 
 
// ── Nearest real liquidity beyond the target distance: the trade-plan
//    TP levels (v5.0). Same pools the Clear Targets check watches. ──
float _tUpMin = close + tgtDist
float _tDnMax = close - tgtDist
float nTgtUp = na
float nTgtDn = na
if array.size(pivHi) > 0
    for i = 0 to array.size(pivHi) - 1
        nTgtUp := f_nUp(nTgtUp, array.get(pivHi, i), true, _tUpMin)
if array.size(datHi) > 0
    for i = 0 to array.size(datHi) - 1
        nTgtUp := f_nUp(nTgtUp, array.get(datHi, i), true, _tUpMin)
nTgtUp := f_nUp(nTgtUp, pdh,   not tkPdh, _tUpMin)
nTgtUp := f_nUp(nTgtUp, pwh,   not tkPwh, _tUpMin)
nTgtUp := f_nUp(nTgtUp, pmh,   not tkPmh, _tUpMin)
nTgtUp := f_nUp(nTgtUp, asiaH, not tkAsH, _tUpMin)
nTgtUp := f_nUp(nTgtUp, lonH,  not tkLoH, _tUpMin)
nTgtUp := f_nUp(nTgtUp, nyH,   not tkNyH, _tUpMin)
if array.size(pivLo) > 0
    for i = 0 to array.size(pivLo) - 1
        nTgtDn := f_nDn(nTgtDn, array.get(pivLo, i), true, _tDnMax)
if array.size(datLo) > 0
    for i = 0 to array.size(datLo) - 1
        nTgtDn := f_nDn(nTgtDn, array.get(datLo, i), true, _tDnMax)
nTgtDn := f_nDn(nTgtDn, pdl,   not tkPdl, _tDnMax)
nTgtDn := f_nDn(nTgtDn, pwl,   not tkPwl, _tDnMax)
nTgtDn := f_nDn(nTgtDn, pml,   not tkPml, _tDnMax)
nTgtDn := f_nDn(nTgtDn, asiaL, not tkAsL, _tDnMax)
nTgtDn := f_nDn(nTgtDn, lonL,  not tkLoL, _tDnMax)
nTgtDn := f_nDn(nTgtDn, nyL,   not tkNyL, _tDnMax)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  FVG DETECTION: silent watch pool
// ═══════════════════════════════════════════════════════════════════════
 
// Middle candle displacement check: the candle that creates the imbalance
float midBody  = math.abs(close[1] - open[1])
float midRange = high[1] - low[1]
float dispPct  = (midRange / close[1]) * 100
bool  passDisp = useDisp ? (dispPct >= 0.03 and midBody > midRange * 0.25) : true
 
// Gap geometry: wick-to-wick, the classic 3-candle definition. (v6.43: the
// Body branch is gone; its selector was a locked constant and never chose it.)
float bisiTop = low
float bisiBot = high[2]
float sibiTop = low[2]
float sibiBot = high
 
// barstate.isconfirmed = only detect after bar[0] closes (no premature
// gaps). v5.3: the middle-candle DIRECTION requirement (close[1] >
// open[1] for BISI, < for SIBI) is GONE: it was inherited from the
// FVG Finder and never questioned. The pure ICT definition needs only
// the wick gap; on weak overnight pullbacks the middle candle is often
// a doji or wrong-colored while the gap is real, and that filter was
// silently rejecting valid setups at birth.
bool newBisi = barstate.isconfirmed and not na(high[2]) and bisiTop > bisiBot and passDisp
bool newSibi = barstate.isconfirmed and not na(low[2]) and sibiTop > sibiBot and passDisp
 
// BISI inverts into a bearish IFVG → gated by the Bearish toggle
// Gap must clear BOTH floors: absolute ticks and the ATR-relative noise floor
if newBisi and showBear and math.round((bisiTop - bisiBot) / syminfo.mintick) >= minTicks and
     (bisiTop - bisiBot) >= atrVal * minGapAtr
    // v5.15 Series detection: a new gap overlapping (or edge-to-edge
    // within tolerance of) a same-direction WATCHED gap fuses into it:
    // one unit per cluster, birth refreshed while the run keeps building,
    // and the unit only inverts through the far side of the WHOLE range.
    // v6.27: cluster FIRST (so it only ever sees earlier gaps), then always push this gap
    // as its own row. Both populations now coexist; the mode filters at print time.
    f_wCluster(1, bisiTop, bisiBot)   // v6.43: called for its cluster bookkeeping; the count only fed the removed debug chip
    array.push(wTop,  bisiTop)
    array.push(wBot,  bisiBot)
    array.push(wDir,  1)
    array.push(wBI,   bar_index - 2)
    array.push(wCtB,  int(na))
    array.push(wCtC,  float(na))
    array.push(wMem,  1)
    array.push(wSeal, false)   // v6.28: the leg-boundary pass below seals it if its leg just closed
 
// SIBI inverts into a bullish IFVG → gated by the Bullish toggle
if newSibi and showBull and math.round((sibiTop - sibiBot) / syminfo.mintick) >= minTicks and
     (sibiTop - sibiBot) >= atrVal * minGapAtr
    // v6.27: mirror of the BISI branch above.
    f_wCluster(-1, sibiTop, sibiBot)
    array.push(wTop,  sibiTop)
    array.push(wBot,  sibiBot)
    array.push(wDir,  -1)
    array.push(wBI,   bar_index - 2)
    array.push(wCtB,  int(na))
    array.push(wCtC,  float(na))
    array.push(wMem,  1)
    array.push(wSeal, false)   // v6.28: the leg-boundary pass below seals it if its leg just closed
 
// ═══ v6.28: LEG BOUNDARY: seal every row whose leg just ended ═══
// House rule: "a leg is a swing low to a swing high. A swing high is 3 candles
// with the middle candle's wick higher than the first and last." A series is
// gaps stacked inside ONE leg, so the LEG ENDING is what closes the series:
// never a bar count. Gap direction maps to the leg that builds it:
//   BISI (wDir +1) stack on the way UP   -> their leg ends at a swing HIGH
//   SIBI (wDir -1) stack on the way DOWN -> their leg ends at a swing LOW
// Lone gaps are sealed too, not just clusters: otherwise a gap from the old leg
// could still SEED a cluster with one from the new leg, straight across the swing.
// Sealing bounds the series' RANGE, not its lifespan: sealed rows stay in the
// pool and invert normally. A finished leg is exactly what you want to trade.
//
// ORDER MATTERS: this runs AFTER gap birth, and must. The pivot confirmed on this
// bar sits at bar_index - 1, while a gap confirmed on this bar is anchored at
// bar_index - 2. So that gap formed on the final push INTO the swing and belongs
// to the leg that is only now closing; it has to be allowed to join before the seal.
//
// Non-repaint: ta.pivothigh/low with legFrac each side confirm legFrac bars late
// and never revise. Called at top level every bar: never inside a conditional.
bool legSwHi = not na(ta.pivothigh(high, legFrac, legFrac))
bool legSwLo = not na(ta.pivotlow(low,  legFrac, legFrac))
if (legSwHi or legSwLo) and array.size(wTop) > 0
    for j = 0 to array.size(wTop) - 1
        if not array.get(wSeal, j)
            int wdj = array.get(wDir, j)
            if (wdj == 1 and legSwHi) or (wdj == -1 and legSwLo)
                array.set(wSeal, j, true)
 
// Watch pool cap: cull the oldest waiting gaps (a gap that old is stale anyway)
while array.size(wTop) > maxWatch
    f_wDel(0)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  INVERSION: the flip, graded by the live checklist
// ═══════════════════════════════════════════════════════════════════════
//  v4.9: a gap inverts when a FULL candle body closes through its far
//  side (confirmed bars only: no intrabar flicker, no repainting).
//  Close-through with a straddling body is noise and consumes nothing.
//  Sequence lock: the gap must have been born within legWin bars of the
//  sponsoring raid (same leg) and must invert within the Inversion
//  Window of forming: sweep, gap, flip: one event, in order.
//  Checklist counted ON the inversion close (IFVG itself = 1):
//    Sweep · Delivery · Displacement · Clear Targets · SMT
//  Below-threshold inversions still consume the gap: they never print.
// ═══════════════════════════════════════════════════════════════════════
 
// Killzone gate (v6.0): true when filtering is off or the current bar
// sits inside any enabled window (ET, DST-aware via the tz argument)
bool inKz = not kzOn or
     (kz1On and not na(time(timeframe.period, kz1S, "America/New_York"))) or
     (kz2On and not na(time(timeframe.period, kz2S, "America/New_York"))) or
     (kz3On and not na(time(timeframe.period, kz3S, "America/New_York")))
 
// Alert grade floor (v6.0)
int alertCnt = alertGrade == "A+" ? 6 : alertGrade == "A" ? 5 : alertGrade == "B+" ? 4 :
     alertGrade == "B" ? 3 : alertGrade == "B-" ? 2 : 1
 
int minCnt = minGrade == "A+" ? 6 : minGrade == "A" ? 5 : minGrade == "B+" ? 4 :
     minGrade == "B" ? 3 : minGrade == "B-" ? 2 : 1
 
// v6.11: grade floor a reversal must clear to fire against a live trade
int revCnt = revGrade == "A+" ? 6 : revGrade == "A" ? 5 : revGrade == "B+" ? 4 :
     revGrade == "B" ? 3 : revGrade == "B-" ? 2 : 1
 
 
// Minor sweeps expire with the Setup Window; majors live while they hold,
// hard-capped at 2× the window (v4.8): stale raids stop sponsoring zones
bool buyMinOk  = not na(buyMinBar)  and bar_index - buyMinBar  <= sweepWin
bool buyMajOk  = not na(buyMajBar)  and bar_index - buyMajBar  <= sweepWin * 2
bool sellMinOk = not na(sellMinBar) and bar_index - sellMinBar <= sweepWin
bool sellMajOk = not na(sellMajBar) and bar_index - sellMajBar <= sweepWin * 2
bool buySwept  = buyMinOk or buyMajOk
bool sellSwept = sellMinOk or sellMajOk
 
// Freshest valid raid bar per side (delivery pairing + panel direction)
int lastBuySweep  = buyMajOk and buyMinOk ? math.max(buyMajBar, buyMinBar) :
     buyMajOk ? buyMajBar : buyMinOk ? buyMinBar : na
int lastSellSweep = sellMajOk and sellMinOk ? math.max(sellMajBar, sellMinBar) :
     sellMajOk ? sellMajBar : sellMinOk ? sellMinBar : na
 
bool bullTapped = not na(lastBullTap)   and bar_index - lastBullTap   <= sweepWin
bool bearTapped = not na(lastBearTap)   and bar_index - lastBearTap   <= sweepWin
bool smtBullOk  = not na(lastSmtBull)   and bar_index - lastSmtBull   <= sweepWin
bool smtBearOk  = not na(lastSmtBear)   and bar_index - lastSmtBear   <= sweepWin
 
// Delivery. Required mode: the tap rides the SAME swing as the raid:
// tap and sweep belong to one leg (the MM pairing rule). Graded mode
// (v4.19): a recent tap into a live HTF array counts on its own: a
// C-grade setup can show PDA Delivery with NO sweep on
// the board, so the delivery check cannot be sweep-paired.
bool bullDeliv = sweepReq == "Graded" ? bullTapped :
     (bullTapped and sellSwept and math.abs(lastBullTap - lastSellSweep) <= legWin)
bool bearDeliv = sweepReq == "Graded" ? bearTapped :
     (bearTapped and buySwept and math.abs(lastBearTap - lastBuySweep) <= legWin)
 
// Stacked tolerance: zones touching or edge-to-edge within this merge
float proxTol = atrVal * 0.25
 
// v6.11 Structure Shift reference: the swing extreme as of the PRIOR bar.
// legHi/legLo include the current bar, so a close can never beat them; the
// [1] read is what makes "took out the swing" a real, clearable test.
float swHiRef = legHi[1]
float swLoRef = legLo[1]
 
// Checklist counts are bar-level context: compute once per side
int cntBear = 1 + (buySwept ? 1 : 0) + (bearDeliv ? 1 : 0) + (dispRecent ? 1 : 0) +
     (targetBelow ? 1 : 0) + (smtBearOk ? 1 : 0)
int cntBull = 1 + (sellSwept ? 1 : 0) + (bullDeliv ? 1 : 0) + (dispRecent ? 1 : 0) +
     (targetAbove ? 1 : 0) + (smtBullOk ? 1 : 0)
 
// ── Setup economy: SWEEP IS THE ADMISSION PRICE ──
// Trader note: "if there is no real sweep there isn't a setup." A zone only
// prints behind a direction-matched raid, and printing SPENDS that raid:
// the next zone in that direction needs a fresh one. Two exceptions:
// stacked candidates merge into the existing zone, and a STRICTLY
// higher-graded setup off the same raid prints and SUPERSEDES the zone
// that spent it (one live zone per raid: always the best one).
var int usedBuySweep  = na
var int usedSellSweep = na
var int usedBuyCnt    = 0
var int usedSellCnt   = 0
var int usedBuyInv    = na
var int usedSellInv   = na
 
// Checklist strings: one per side, frozen into each zone's entry-marker
// tooltip at print time (v5.14). Full names, one row per check.
string chkBear = (buySwept    ? "✓" : "✗") + " Liquidity Sweep\n" +
     (bearDeliv  ? "✓" : "✗") + " Delivery\n" +
     (dispRecent ? "✓" : "✗") + " Displacement\n" +
     (targetBelow ? "✓" : "✗") + " Clear Targets\n" +
     (smtBearOk  ? "✓" : "✗") + " SMT"
string chkBull = (sellSwept   ? "✓" : "✗") + " Liquidity Sweep\n" +
     (bullDeliv  ? "✓" : "✗") + " Delivery\n" +
     (dispRecent ? "✓" : "✗") + " Displacement\n" +
     (targetAbove ? "✓" : "✗") + " Clear Targets\n" +
     (smtBullOk  ? "✓" : "✗") + " SMT"
 
// Age-out (v4.20): a gap that outlived the Inversion Window can never
// print: cull it silently instead of letting it attempt and spray FRS
// tags. Keeps the watch pool honest and the debug view readable.
if array.size(wTop) > 0
    for i = array.size(wTop) - 1 to 0
        if bar_index - (array.get(wBI, i) + 2) > invWin
            f_wDel(i)
 
// Each inverted gap becomes its OWN zone: singular gaps stay singular.
// f_absorb only fuses it with zones it is physically stacked against
// (including one drawn seconds earlier by the same reversal candle), so
// a 1-2-3 stack collapses to one zone and everything else stands alone.
// v4.20 consumption law: a gap is consumed when it PRINTS (or ages out).
// A close-through that doesn't print leaves the gap live: a setup whose
// confluences tick one bar late prints one bar late instead of never.
if barstate.isconfirmed and array.size(wTop) > 0
    for i = array.size(wTop) - 1 to 0
        wt = array.get(wTop, i)
        wb = array.get(wBot, i)
        wd = array.get(wDir, i)
        wl = array.get(wBI,  i)
        // Sequence lock gates (v4.9, trigger recalibrated v4.18):
        //   fresh: invert within the Inversion Window of FORMING
        //             (birth bar = anchor + 2, the confirm bar)
        //   coupled: the gap rides the raid leg: born within legWin bars
        //             of the sponsoring sweep, either side (the gap
        //             usually forms ON the displacement into the raid)
        //   close: a confirmed CLOSE through the far side. The
        //             trigger fires on candles that OPEN inside the
        //             gap and close through: the v4.9 whole-body rule
        //             skipped the timely bar and matched stale gaps.
        fresh = bar_index - (wl + 2) <= invWin
        // v6.27: DETECTION MODE IS A DISPLAY FILTER, not a merge behaviour. Both
        // populations exist in the pool now (lone gaps at wMem 1, clusters at 2+), so the
        // mode simply chooses which may print. A row the mode excludes is skipped entirely
        //, no evaluation, no print, no rejection tag, and ages out on its own.
        int  wm     = array.get(wMem, i)
        bool modeOk = detMode == "Both" or (detMode == "Series" ? wm >= 2 : wm == 1)
        if wd == 1 and close < wb and modeOk
            // v5.15: stamp the FIRST confirmed close-through: THE
            // inversion candle. A print deferred by spacing/confluence
            // still anchors its entry (price AND bar) right here, so a
            // late print can never drift the entry 2-3 candles forward.
            if na(array.get(wCtB, i))
                array.set(wCtB, i, bar_index)
                array.set(wCtC, i, close)
            int   ctB  = array.get(wCtB, i)
            float ctPx = array.get(wCtC, i)
            coupledB = not na(lastBuySweep) and math.abs(wl + 2 - lastBuySweep) <= legWin
            stackedB = detMode == "Both" and f_stacked(wt, wb, -1, proxTol)
            freshRaidB = nz(usedBuySweep, -1) != lastBuySweep
            // v6.11: an upgrade REPLACES the zone it outgrades rather than
            // adding a second entry: legal only before that zone starts
            // delivering. Once SD -1 is tagged the trade is live and moving
            // its entry backwards would rewrite a fill that already happened.
            upgradeB = not freshRaidB and cntBear > usedBuyCnt and
                 (ecoMode == "All Entries" or not f_delivering(-1))
            // Sponsored = the MM path: raid + coupling + raid economy.
            // Free (v4.17, "Graded" mode) = the sweepless
            // path: no raid credit at all, needs 1+ confluence beyond
            // the IFVG itself, spends nothing from the raid economy.
            sponsoredB = buySwept and coupledB and (stackedB or freshRaidB or upgradeB)
            // Graded free path (v4.19): opens whenever sponsorship fails:
            // coupling is a Required-mode law, Graded mode has no chain.
            freeB = sweepReq == "Graded" and not sponsoredB and cntBear >= 2
            // v5.7 dedup economy: one active setup per direction (active
            // until TP or fail) PLUS the spacing rule: no same-
            // direction setup within spcBars of the last print, period.
            [dupHitB, dupInvB] = f_dupe(-1)
            dupB = sweepReq == "Graded" and not stackedB and
                 (dupHitB or (spcBars > 0 and not na(lastPrB) and bar_index - lastPrB <= spcBars))
            // ── v6.11 LANE RULE ── (see the Setup Economy block above)
            // Same-direction: a short can't print while a short is still
            // working its ladder. Opposite-direction: this bear print is
            // fighting a live BULL setup, so it has to prove a real turn.
            // A supersede is exempt: it deletes the zone it replaces, so
            // it can never be the second entry the rule exists to stop.
            supB   = sponsoredB and upgradeB and not stackedB
            lnOppB = f_laneHeld(1)
            revOkB = lnOppB and f_revOk(-1, cntBear, revCnt, dispRecent, swHiRef, swLoRef)
            laneB  = not stackedB and not supB and
                 (f_laneHeld(-1) or (lnOppB and not revOkB))
            allowB = (sponsoredB or freeB) and not dupB and not laneB
            if fresh and cntBear >= minCnt and allowB and inKz
                if sponsoredB and upgradeB and not stackedB
                    f_supersede(-1, usedBuyInv)
                [mT, mB, mL, mC] = f_absorb(wt, wb, -1, wl, proxTol, cntBear, detMode == "Both")
                // v6.8: SD leg = swing HIGH (legHi) → entry; 0 anchors at entry.
                // v6.32: hoisted so the drawn stop and the quoted stop are the same value,
                // not two evaluations of one expression that could drift if either moves.
                float slvB = (slMode == "IFVG" ? mT : legHi) + slBufT * syminfo.mintick
                f_addIFVG(mT, mB, -1, mL, mC, chkBear, ctPx, slvB, nTgtDn, legHi, legLo, ctB)
                // v6.43: a new print is the ONLY thing that moves the panel latch.
                cdDir := -1
                cdInv := array.get(iInv, array.size(iInv) - 1)
                cdCnt := mC
                cdChk := chkBear
                cdSt  := "LIVE"
                cdSd  := 0
                cdTp  := false
                if mC >= alertCnt
                    [qtyB, rskB, mB] = f_size(ctPx, slvB)
                    f_alert(alNewOn, "Bear IFVG " + f_grade(mC) + " (" + str.tostring(mC) + "/6) - entry " +
                         str.tostring(ctPx, format.mintick) + " · SL " + str.tostring(slvB, format.mintick) +
                         " · target " + (na(nTgtDn) ? "n/a" : str.tostring(nTgtDn, format.mintick)) +
                         " · " + str.tostring(qtyB) + f_sizeUnit(qtyB, mB) + " = $" + str.tostring(rskB, "#,###"), true)
                if sponsoredB
                    usedBuySweep := lastBuySweep
                    usedBuyCnt   := mC
                    // v6.12: stamp the INVERSION bar, not the print bar. The
                    // zone records ctB (v5.15 first close-through); a deferred
                    // print lands later, and the old bar_index stamp made the
                    // next upgrade's f_supersede match nothing at all.
                    // Read the value BACK off the zone rather than reusing ctB:
                    // f_addIFVG stores math.max(invB, lb) after anchor clamping,
                    // so this is the only stamp guaranteed to compare equal.
                    usedBuyInv   := array.get(iInv, array.size(iInv) - 1)
                lastPrB := bar_index
                f_wDel(i)
            else if not inKz
                // Killzone veto: outside every enabled window this trade
                // never existed. Consume so it can't print later at a
                // stale entry when a window opens.
                f_wDel(i)
            else if laneB
                // v6.11: a gap that inverts while a trade is already working
                // belongs to THAT move, not the next one: consume it. It
                // can't be deferred: v5.15 anchors the entry at the first
                // close-through, so printing it later (when the lane frees)
                // would stamp a fill at a price price has long left behind.
                // Ordered AHEAD of dupB deliberately: when a trade is live
                // the lane rule is the authority, and dupB's defer path would
                // otherwise keep the gap alive to print stale.
                f_wDel(i)
            else if dupB
                // v5.10 nuance: consume only SAME-MOVE duplicates (the
                // blocker printed recently). A gap blocked by an OLD
                // active is the next trade waiting its turn: it defers
                // and prints when the lane clears; the spacing rule
                // still prevents doubles.
                int refB = na(dupInvB) ? lastPrB :
                     na(lastPrB) ? dupInvB : math.max(dupInvB, lastPrB)
                if not na(refB) and bar_index - refB <= math.max(2 * spcBars, 10)
                    f_wDel(i)
        else if wd == -1 and close > wt and modeOk
            if na(array.get(wCtB, i))
                array.set(wCtB, i, bar_index)
                array.set(wCtC, i, close)
            int   ctU  = array.get(wCtB, i)
            float ctPxU = array.get(wCtC, i)
            coupledU = not na(lastSellSweep) and math.abs(wl + 2 - lastSellSweep) <= legWin
            stackedU = detMode == "Both" and f_stacked(wt, wb, 1, proxTol)
            freshRaidU = nz(usedSellSweep, -1) != lastSellSweep
            upgradeU = not freshRaidU and cntBull > usedSellCnt and
                 (ecoMode == "All Entries" or not f_delivering(1))
            sponsoredU = sellSwept and coupledU and (stackedU or freshRaidU or upgradeU)
            freeU = sweepReq == "Graded" and not sponsoredU and cntBull >= 2
            [dupHitU, dupInvU] = f_dupe(1)
            dupU = sweepReq == "Graded" and not stackedU and
                 (dupHitU or (spcBars > 0 and not na(lastPrU) and bar_index - lastPrU <= spcBars))
            // v6.11 lane rule: mirror of the bear path, hand for hand
            supU   = sponsoredU and upgradeU and not stackedU
            lnOppU = f_laneHeld(-1)
            revOkU = lnOppU and f_revOk(1, cntBull, revCnt, dispRecent, swHiRef, swLoRef)
            laneU  = not stackedU and not supU and
                 (f_laneHeld(1) or (lnOppU and not revOkU))
            allowU = (sponsoredU or freeU) and not dupU and not laneU
            if fresh and cntBull >= minCnt and allowU and inKz
                if sponsoredU and upgradeU and not stackedU
                    f_supersede(1, usedSellInv)
                [mT, mB, mL, mC] = f_absorb(wt, wb, 1, wl, proxTol, cntBull, detMode == "Both")
                // v6.8: SD leg = swing LOW (legLo) → entry; 0 anchors at entry.
                // v6.32: hoisted - mirror of the bear path above, same reason.
                float slvU = (slMode == "IFVG" ? mB : legLo) - slBufT * syminfo.mintick
                f_addIFVG(mT, mB, 1, mL, mC, chkBull, ctPxU, slvU, nTgtUp, legLo, legHi, ctU)
                // v6.43: mirror of the bear print site.
                cdDir := 1
                cdInv := array.get(iInv, array.size(iInv) - 1)
                cdCnt := mC
                cdChk := chkBull
                cdSt  := "LIVE"
                cdSd  := 0
                cdTp  := false
                if mC >= alertCnt
                    [qtyU, rskU, mU] = f_size(ctPxU, slvU)
                    f_alert(alNewOn, "Bull IFVG " + f_grade(mC) + " (" + str.tostring(mC) + "/6) - entry " +
                         str.tostring(ctPxU, format.mintick) + " · SL " + str.tostring(slvU, format.mintick) +
                         " · target " + (na(nTgtUp) ? "n/a" : str.tostring(nTgtUp, format.mintick)) +
                         " · " + str.tostring(qtyU) + f_sizeUnit(qtyU, mU) + " = $" + str.tostring(rskU, "#,###"), true)
                if sponsoredU
                    usedSellSweep := lastSellSweep
                    usedSellCnt   := mC
                    // v6.12: inversion bar, not print bar: mirror of the bear path
                    usedSellInv   := array.get(iInv, array.size(iInv) - 1)
                lastPrU := bar_index
                f_wDel(i)
            else if not inKz
                f_wDel(i)
            else if laneU
                f_wDel(i)
            else if dupU
                int refU = na(dupInvU) ? lastPrU :
                     na(lastPrU) ? dupInvU : math.max(dupInvU, lastPrU)
                if not na(refU) and bar_index - refU <= math.max(2 * spcBars, 10)
                    f_wDel(i)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  RETEST & FAIL TRACKING
// ═══════════════════════════════════════════════════════════════════════
 
int szI = array.size(iTop)
if szI > 0
    for i = szI - 1 to 0
        t = array.get(iTop, i)
        b = array.get(iBot, i)
        d = array.get(iDir, i)
        s = array.get(iSt,  i)
 
        if s < 2
            ns = s
 
            // Completion latch (v5.7): the setup completes when price
            // reaches ITS TP LEVEL (the liquidity it was drawn toward),
            // not a fixed distance: a two-candle-old setup mid-delivery
            // still owns the direction, a delivered stair-step doesn't.
            // 1.5×ATR proxy only when no pool existed at print. Latched.
            float tpz = array.get(iTp, i)
            float upT = na(tpz) ? t + tgtDist : tpz
            float dnT = na(tpz) ? b - tgtDist : tpz
            if not array.get(iDn, i) and
                 ((d == 1 and close >= upT) or (d == -1 and close <= dnT))
                array.set(iDn, i, true)
                // v6.43: TP is a pip on the progress row. It only reads COMPLETE when
                // 'Trade Is Done At' is set to "TP or Stop".
                if d == cdDir and array.get(iInv, i) == cdInv
                    cdTp := true
                    if CD_DONE == 0
                        cdSt := "COMPLETE"
                if array.get(iSc, i) >= alertCnt
                    f_alert(alDoneOn, (d == 1 ? "Bull" : "Bear") + " IFVG " + f_grade(array.get(iSc, i)) +
                         " TP HIT - delivered to " + str.tostring((d == 1 ? upT : dnT), format.mintick), false)
 
            // v6.0 SD-level hits: latched per level, alert-grade gated
            // v6.11: every new rung also stamps iPrg: that stamp IS the
            // "still moving in the right direction" proof the lane rule
            // reads, and what the stall valve measures its silence from.
            bool aOk = array.get(iSc, i) >= alertCnt
            if not array.get(iH1, i) and ((d == 1 and high >= array.get(iS1, i)) or (d == -1 and low <= array.get(iS1, i)))
                array.set(iH1, i, true)
                if d == cdDir and array.get(iInv, i) == cdInv
                    cdSd := math.max(cdSd, 1)   // v6.43 panel progress
                    if CD_DONE > 0 and cdSd >= CD_DONE
                        cdSt := "COMPLETE"
                array.set(iPrg, i, bar_index)
                // v6.41 break-even cue: a suffix on the MM plan label the moment
                // SD-1 is tagged. No toggle, no colour, no column - it belongs to
                // the plan label and appears and disappears with it. Sits inside
                // the one-shot `if not iH1` guard, so it needs no latch of its own.
                label mmLb = array.get(pLb, i)
                if not na(mmLb)
                    string mmTx = label.get_text(mmLb)
                    // Needle and suffix are the SAME literal on purpose. The latch
                    // rewinds on a live bar; a label mutation does NOT. Without this
                    // guard a live bar stacks one " · BE" per tick. They drifted
                    // apart once already in v6.40 and the guard became a no-op.
                    // Edit one, edit both.
                    if not str.contains(mmTx, " · BE")
                        label.set_text(mmLb, mmTx + " · BE")
                if aOk
                    f_alert(alSdOn, (d == 1 ? "Bull" : "Bear") + " IFVG SD -1 tagged @ " +
                         str.tostring(array.get(iS1, i), format.mintick), false)
            if not array.get(iH2, i) and ((d == 1 and high >= array.get(iS2, i)) or (d == -1 and low <= array.get(iS2, i)))
                array.set(iH2, i, true)
                if d == cdDir and array.get(iInv, i) == cdInv
                    cdSd := math.max(cdSd, 2)   // v6.43 panel progress
                    if CD_DONE > 0 and cdSd >= CD_DONE
                        cdSt := "COMPLETE"
                array.set(iPrg, i, bar_index)
                if aOk
                    f_alert(alSdOn, (d == 1 ? "Bull" : "Bear") + " IFVG SD -2 tagged @ " +
                         str.tostring(array.get(iS2, i), format.mintick), false)
            if not array.get(iH3, i) and ((d == 1 and high >= array.get(iS3, i)) or (d == -1 and low <= array.get(iS3, i)))
                array.set(iH3, i, true)
                if d == cdDir and array.get(iInv, i) == cdInv
                    cdSd := math.max(cdSd, 3)   // v6.43 panel progress
                    if CD_DONE > 0 and cdSd >= CD_DONE
                        cdSt := "COMPLETE"
                array.set(iPrg, i, bar_index)
                if aOk
                    f_alert(alSdOn, (d == 1 ? "Bull" : "Bear") + " IFVG SD -2.5 tagged @ " +
                         str.tostring(array.get(iS3, i), format.mintick), false)
            if not array.get(iH4, i) and ((d == 1 and high >= array.get(iS4, i)) or (d == -1 and low <= array.get(iS4, i)))
                array.set(iH4, i, true)
                if d == cdDir and array.get(iInv, i) == cdInv
                    cdSd := math.max(cdSd, 4)   // v6.43 panel progress
                    if CD_DONE > 0 and cdSd >= CD_DONE
                        cdSt := "COMPLETE"
                array.set(iPrg, i, bar_index)
                if aOk
                    f_alert(alSdOn, (d == 1 ? "Bull" : "Bear") + " IFVG SD -4 tagged @ " +
                         str.tostring(array.get(iS4, i), format.mintick), false)
 
            // Retest: wick touch, only on bars after the inversion close
            if s == 0 and bar_index > array.get(iInv, i)
                if (d == 1 and low <= t) or (d == -1 and high >= b)
                    ns := 1
 
            // Fail: confirmed close through the far side. v5.12: a
            // COMPLETED setup can never fail: it already delivered to
            // its target, and a revisit days later is history touching
            // an old level, not a stop-out. This is the
            // Hide Losing semantics: losers vanish, winners
            // keep their marks. (Pre-5.12, winners were retro-failed on
            // any later close-through and deleted when Keep Failed was
            // off: chart history evaporated from the left.)
            if barstate.isconfirmed and not array.get(iDn, i) and
                 ((d == 1 and close < b) or (d == -1 and close > t))
                ns := 2
 
            if ns != s
                array.set(iSt, i, ns)
 
                // v6.43 panel latch status. Written BEFORE the stop path can delete the
                // zone, which is why the panel still reads STOPPED with Keep Failed off.
                // RETESTED never overwrites COMPLETE: a delivered setup tapped later is
                // still a delivered setup. (v6.43: "delivered" now means SD -1 or TP.)
                if d == cdDir and array.get(iInv, i) == cdInv
                    if ns == 2 and cdSt != "COMPLETE"   // a finished trade stays finished
                        cdSt := "STOPPED"
                    else if ns == 1 and cdSt == "LIVE" and cdSd == 0 and not cdTp
                        cdSt := "RETESTED"
 
                // Recolor the box to reflect the new state
                box.set_bgcolor(array.get(iBx, i), f_zFill(ns))
 
                if ns == 1 and array.get(iSc, i) >= alertCnt
                    f_alert(alRetOn, (d == 1 ? "Bull" : "Bear") + " IFVG " + f_grade(array.get(iSc, i)) +
                         " RETEST - zone " + str.tostring((d == 1 ? t : b), format.mintick) +
                         " tapped. Watch for reaction.", false)
                if ns == 2
                    if array.get(iSc, i) >= alertCnt
                        f_alert(alFailOn, (d == 1 ? "Bull" : "Bear") + " IFVG STOPPED - close back through " +
                             str.tostring((d == 1 ? b : t), format.mintick) + ". Stand down.", true)
                    // Trade plan: stop out: SL + SD ladder die always;
                    // the entry line + label die too unless the user
                    // keeps stopped plans as journal records (v5.6).
                    // v6.12: shared with supersede via f_planKill.
                    f_planKill(i)
                    // Remove the zone unless the user keeps failed zones as faded reference
                    if not keepKill
                        f_iDel(i)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  CLEANUP + LIVE EXTEND
// ═══════════════════════════════════════════════════════════════════════
 
// Day roll: an IFVG is a session object. Clear the board at the futures
// day open (18:00 ET) unless the user wants zones to persist.
bool newTDay = nz(ta.change(time("D")), 0) != 0
if dayOnly and newTDay and array.size(iTop) > 0
    for i = array.size(iTop) - 1 to 0
        f_iDel(i)
 
// Cap: cull DEAD zones first (oldest ghost goes before any live setup);
// a live zone is only removed when the board is full of live zones
while array.size(iTop) > maxShow
    int cull = -1
    for i = 0 to array.size(iTop) - 1
        if array.get(iSt, i) == 2
            cull := i
            break
    f_iDel(cull >= 0 ? cull : 0)
 
// v5.16: nothing live-extends anymore. The zone box, the CE midline,
// and the trade-plan stamps are all drawn once at print and stay put:
// the CE spans exactly the zone box, never past the IFVG.
 
 
// ═══════════════════════════════════════════════════════════════════════
//  TRADE CARD · reports the LAST PRINTED setup, held until a new one prints
// ═══════════════════════════════════════════════════════════════════════
//  v6.43: reads the cd* latch and nothing else. It never looks at watched
//  gaps, candidate inversions or other live zones, so it cannot switch to a
//  setup that has not printed, and it does not drop the one you are in when
//  it completes or its zone is removed.
// ═══════════════════════════════════════════════════════════════════════
 
// v6.0 TRADE CARD: 2 cols x 9 rows:
//   row 0  merged  direction chip (entry colors, ▲/▼)
//   row 1  merged  grade banner (tier color, n/6 progress)
//   rows 2-7       checklist, ✓/✗
//   row 8  merged  v6.43 Target Progress (only when showSdRow is on)
//   last   merged  brand footer
// v6.43: the row count follows the input, so turning the row off leaves no blank band.
int PNL_ROWS = showSdRow ? 10 : 9
int PNL_FOOT = PNL_ROWS - 1
var table pnl = table.new(f_pnlPos(), 2, PNL_ROWS, bgcolor=pnlBg,
     frame_color=color.new(pnlAcc, 40), frame_width=1,
     border_color=color.new(#ffffff, 94), border_width=1)
if barstate.isfirst
    table.merge_cells(pnl, 0, 0, 1, 0)
    table.merge_cells(pnl, 0, 1, 1, 1)
    table.merge_cells(pnl, 0, PNL_FOOT, 1, PNL_FOOT)
    if showSdRow
        table.merge_cells(pnl, 0, 8, 1, 8)
 
f_pnlRow(int row, string name, bool passed) =>
    table.cell(pnl, 0, row, " " + name + " ", text_color=color.new(pnlTxt, passed ? 0 : 45),
         text_size=f_pnlSz(0), text_halign=text.align_left, text_font_family=font.family_monospace)
    table.cell(pnl, 1, row, passed ? "✓" : "✗",
         text_color=passed ? pnlOk : pnlNo,
         text_size=f_pnlSz(0), text_halign=text.align_center, text_font_family=font.family_monospace)
 
if barstate.islast and showPnl
    // v6.43: the latch IS the binding. No search, no re-pick.
    int    sDir = cdDir
    int    sCnt = cdCnt
    string sCk  = cdChk
    string sSt  = cdSt
 
    bool rSweep = str.contains(sCk, "✓ Liquidity Sweep")
    bool rDeliv = str.contains(sCk, "✓ Delivery")
    bool rDisp  = str.contains(sCk, "✓ Displacement")
    bool rTgt   = str.contains(sCk, "✓ Clear Targets")
    bool rSmt   = str.contains(sCk, "✓ SMT")
    bool rIfvg  = sDir != 0
 
    // Direction chip: filled with the entry colors, gray when no setup
    color dirBg  = sDir == 1 ? peBullCol : sDir == -1 ? peBearCol : color.new(#434651, 40)
    // v6.43, House call: a stop after a tagged level is recorded as such. After
    // SD -1 the plan label already said BE, so that is a scratch, not a full loss.
    string sdNm  = cdSd == 4 ? "SD -4" : cdSd == 3 ? "SD -2.5" : cdSd == 2 ? "SD -2" : "SD -1"
    string stTx  = sSt == "STOPPED" and cdSd > 0 ? "STOPPED · after " + sdNm : sSt
    string dirTx = sDir == 1 ? "▲ LONG · " + f_tfName(timeframe.period) + " · " + stTx :
         sDir == -1 ? "▼ SHORT · " + f_tfName(timeframe.period) + " · " + stTx :
         "NO SETUP · " + f_tfName(timeframe.period)
    table.cell(pnl, 0, 0, " " + dirTx + " ", bgcolor=color.new(dirBg, sDir == 0 ? 60 : 15),
         text_color=color.new(color.white, 5), text_size=f_pnlSz(0),
         text_halign=text.align_center, text_font_family=font.family_monospace)
 
    // Grade banner: tier color, big letter, checklist count
    color gCol = sDir == 0 ? color.new(#787b86, 40) : f_gradeCol(sCnt)
    string gTx = sDir == 0 ? "–" : f_grade(sCnt) + "  ·  " + str.tostring(sCnt) + "/6"
    table.cell(pnl, 0, 1, gTx, bgcolor=color.new(gCol, 82),
         text_color=gCol, text_size=f_pnlSz(1),
         text_halign=text.align_center, text_font_family=font.family_monospace)
    table.set_frame_color(pnl, sDir == 0 ? color.new(pnlAcc, 40) : color.new(gCol, 25))
 
    f_pnlRow(2, "Liquidity Sweep", rSweep)
    f_pnlRow(3, "Delivery",        rDeliv)
    f_pnlRow(4, "Displacement",    rDisp)
    f_pnlRow(5, "Clear Targets",   rTgt)
    f_pnlRow(6, "SMT",             rSmt)
    f_pnlRow(7, "IFVG",            rIfvg)
 
    // v6.43 Target Progress. Reads only the latch; one merged cell, so one colour:
    // green once anything has delivered, grey until then.
    if showSdRow
        string pgTx = "TP " + (cdTp ? "✓" : "·") + "  │  -1 " + (cdSd >= 1 ? "✓" : "·") +
             "  -2 " + (cdSd >= 2 ? "✓" : "·") + "  -2.5 " + (cdSd >= 3 ? "✓" : "·") +
             "  -4 " + (cdSd >= 4 ? "✓" : "·")
        bool pgAny = sDir != 0 and (cdTp or cdSd > 0)
        table.cell(pnl, 0, 8, pgTx,
             text_color=pgAny ? pnlOk : color.new(pnlTxt, 45),
             text_size=f_pnlSz(0), text_halign=text.align_center,
             text_font_family=font.family_monospace)
 
    // Brand footer
    table.cell(pnl, 0, PNL_FOOT, "M A R K E T   M A U L E R S",
         text_color=color.new(pnlAcc, 45), text_size=f_pnlSz(-1),
         text_halign=text.align_center, text_font_family=font.family_monospace)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  ALERTS: v6.32
// ═══════════════════════════════════════════════════════════════════════
// There is nothing left to put here. Every alert now fires from the site where its
// event happens, because that is the only place the prices are in scope, and carrying
// the prices is the entire reason for the change. The transport (f_alert, the varip
// dedupe buffer, the master switch and the format picker) lives up in the Alerts input
// group beside the per-type toggles it reads.
// One TradingView alert, condition "Any alert() function call", covers all of it.
 
 
// ═══════════════════════════════════════════════════════════════════════
//  HIGHER TIMEFRAME FVGs (v6.5): ported VERBATIM from the sibling raid tool (whose
//  detection core is itself the FVG finder's HTF mode). Shipped as a separate
//  product, so IFVG carries its own copy: keep the two engines in sync when
//  either changes. barstate.isconfirmed evaluated INSIDE the security tuple
//  fires on the last chart bar of each confirmed HTF bar (zero lookahead, zero
//  repaint); the chart-side rising edge fires once per gap. Boxes anchor where
//  the 3-candle pattern formed, extend right with price, and drop on a full
//  fill (bull: low through the bottom; bear: high through the top). Menu capped
//  at 1D: chart history must hold the HTF candles. Anchor clamped 9,500 bars
//  back (drawings can't reference further than ~10k).
// ═══════════════════════════════════════════════════════════════════════
color HF_NONE = #ffffff00
 
// simple-string qualifiers required: hf1Tf/hf2Tf feed request.security,
// timeframe.in_seconds() and f_tfName(), all of which reject series string.
f_hfTf(simple string sel) =>
    sel == '15m' ? '15' : sel == '1H' ? '60' : sel == '4H' ? '240' : '1D'
 
simple string hf1Tf = f_hfTf(hf1Sel)
simple string hf2Tf = f_hfTf(hf2Sel)
 
// v6.13: back-ported from the sibling raid tool: this copy still carried the ORIGINAL
// detection and had all three of the bugs that fix corrected.
//
// TIMING (v4.29). Detection used barstate.isconfirmed inside the security tuple. That
// reads true across the entire HTF context on historical bars, so the gap test ran against
// the DEVELOPING HTF bar's running low/high: the flag could latch true mid-bar and carry
// into the next HTF bar. The chart-side rising edge `flag and not flag[1]` then never
// re-fired, so back-to-back gaps in a directional run drew ONE box for the whole streak.
// Now on non-repaint idiom A, last CLOSED HTF bar via [1] + lookahead_on, firing when
// the HTF bar's TIME changes. One evaluation per closed HTF bar, on finished data.
//
// The completed 3-candle pattern sits at [3][2][1] relative to the developing HTF bar:
// c1 = [3] (the gap's far side), c2 = [2] (the displacement body), c3 = [1] (the near
// side). time[1] rides along in the tuple purely as the fire trigger.
[hf1_bull, hf1_bT, hf1_bB, hf1_bear, hf1_sT, hf1_sB, hf1_t] = 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]], lookahead = barmerge.lookahead_on)
[hf2_bull, hf2_bT, hf2_bB, hf2_bear, hf2_sT, hf2_sB, hf2_t] = 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]], lookahead = barmerge.lookahead_on)
 
// Fire on the HTF BAR changing, not on the flag's rising edge.
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)
bool newHf1Bull = hf1New and hf1_bull
bool newHf1Bear = hf1New and hf1_bear
bool newHf2Bull = hf2New and hf2_bull
bool newHf2Bear = hf2New and hf2_bear
 
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>()
 
// v4.29: per-SLOT budget. The old cap was 60 across BOTH slots, evicted oldest-first, so a
// busy 4H slot quietly shifted out perfectly valid 1D gaps: an unfilled box removed for a
// reason that has nothing to do with price. Each slot now keeps its own budget and can only
// evict its own oldest.
int HF_CAP = 40
 
// Left anchor = c1 of the pattern. Under idiom A we fire one HTF bar later than the old
// close-of-bar timing, so c1 is 3 HTF bars back, not 2. Clamped to the drawing-reference
// limit. int() cast required: v6 int/int division returns float.
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)   // v6.44: was 9500
 
// House rule (v4.30): when two HTF FVGs OVERLAP IN PRICE, the higher timeframe owns the
// level and the lower one comes off: simple as that. A 4H gap sitting on a daily gap is
// not a second piece of information, it is the same imbalance drawn twice, and the daily
// is the one price is actually working. Direction-agnostic: a bear 4H overlapping a bull
// daily still yields, because the argument is about the level, not the side.
//
// Removal is permanent, not a suppression, and that is consistent: the daily can only die
// by being wicked through end to end, and the same move wicks through anything nested in
// it. Touching edges are NOT an overlap (strict >), so a 4H stacked directly on a daily's
// boundary survives as its own gap.
f_hfOverlap(float t1, float b1, float t2, float b2) =>
    t1 > b2 and t2 > b1
 
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
        // Yield to any higher-TF gap already holding this level.
        bool outranked = false
        if hfBoxes.size() > 0
            for i = 0 to hfBoxes.size() - 1
                if hfSec.get(i) > sec and f_hfOverlap(top, bot, box.get_top(hfBoxes.get(i)), box.get_bottom(hfBoxes.get(i)))
                    outranked := true
                    break
        if not outranked
            // Take the level: clear every lower-TF gap this one overlaps.
            if hfBoxes.size() > 0
                for i = hfBoxes.size() - 1 to 0
                    if hfSec.get(i) < sec and f_hfOverlap(top, bot, box.get_top(hfBoxes.get(i)), box.get_bottom(hfBoxes.get(i)))
                        box.delete(hfBoxes.get(i))
                        box _ob = hfBoxes.remove(i)
                        int _od = hfDirs.remove(i)
                        int _os = hfSlot.remove(i)
                        int _oc = hfSec.remove(i)
            hfBoxes.push(box.new(f_hfLeft(tf), top, bar_index, bot, xloc = xloc.bar_index, bgcolor = col, border_color = HF_NONE, text = f_tfName(tf), text_size = size.tiny, text_halign = text.align_right, text_color = hfTxtCol))
            hfDirs.push(dir)
            hfSlot.push(slot)
            hfSec.push(sec)
            int cnt = 0
            for i = 0 to hfSlot.size() - 1
                if hfSlot.get(i) == slot
                    cnt += 1
            // Evict THIS slot's oldest only: never the other slot's.
            if cnt > HF_CAP
                for i = 0 to hfSlot.size() - 1
                    if hfSlot.get(i) == slot
                        box.delete(hfBoxes.get(i))
                        box _eb = hfBoxes.remove(i)
                        int _ed = hfDirs.remove(i)
                        int _es = hfSlot.remove(i)
                        int _ec = hfSec.remove(i)
                        break
 
// Dedup: two slots on the same timeframe would double every box: slot 2 yields.
// The seconds value is also the PRECEDENCE RANK above: the ruling is 1D > 4H > 1H > 15m
// by actual duration, never by slot number, so it holds whichever way the slots are set.
int hf1Sec = timeframe.in_seconds(hf1Tf)
int hf2Sec = timeframe.in_seconds(hf2Tf)
bool hf1On = useHf1 and hf1Sec > timeframe.in_seconds()
bool hf2On = useHf2 and hf2Sec > timeframe.in_seconds() and not (hf1On and hf2Tf == hf1Tf)
 
// Higher TF FIRST within the bar, so a same-bar daily takes the level before the 4H can
// claim it. Without this the 4H would draw, then get cleared a statement later: same end
// state, but the ordering makes the intent readable.
bool hfHiFirst = hf1Sec >= hf2Sec
 
if hfHiFirst 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 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 not hfHiFirst 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)
 
// Maintain: extend to the current bar, drop ONLY on a full fill (House rule, above).
if hfBoxes.size() > 0
    for i = hfBoxes.size() - 1 to 0
        box hb = hfBoxes.get(i)
        box.set_right(hb, bar_index)
        int hd = hfDirs.get(i)
        if (hd == 1 and low <= box.get_bottom(hb)) or (hd == -1 and high >= box.get_top(hb))
            box.delete(hb)
            box _hb = hfBoxes.remove(i)
            int _hd = hfDirs.remove(i)
            int _hs = hfSlot.remove(i)
            int _hc = hfSec.remove(i)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  NEARBY LIQUIDITY (v5.17; display re-ported from the sibling raid tool at v6.43).
//  Two swing engines run in the backend: MINOR pivots (5 bars each
//  side, default 5) and MAJOR pivots (40 bars each side). Untaken swing levels are
//  POOLED: a new swing landing within an ATR-scaled tolerance of an
//  existing level merges into it: equal highs/lows become one pool,
//  the level sits at the cluster's extreme (the wick a sweep actually
//  has to run), and the merge count is the pool's strength. No
//  timeframe selection by design: pivot spans are chart-bar based and
//  the tolerance self-scales from ATR(200). Display filters to the
//  NEAREST untaken MAJOR pool and up to lqMinN MINOR pools inside it on each side. A trade
//  through a level deletes it instantly: swept liquidity is spent.
// ═══════════════════════════════════════════════════════════════════════
int LIQ_MINOR = lqMinLen
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
// v6.3: the key-level coincidence test uses a TIGHTER band than the pooling
// tolerance. A pool must be genuinely hugging the key line to be suppressed:
// ATR/4 (the pooling tol) is wide enough to eat a distinct pool sitting a
// handful of points off a key level (e.g. a real Major SSL just above PWL),
// which would leave the slot empty with no replacement. ATR/12 ≈ "on the line."
float lqKeyTol = nz(lqAtr, syminfo.mintick * 40) / 12
 
float lqPhMin = ta.pivothigh(high, LIQ_MINOR, LIQ_MINOR)
float lqPhMaj = ta.pivothigh(high, LIQ_MAJOR, LIQ_MAJOR)
float lqPlMin = ta.pivotlow(low,  LIQ_MINOR, LIQ_MINOR)
float lqPlMaj = ta.pivotlow(low,  LIQ_MAJOR, LIQ_MAJOR)
 
// Merge a confirmed swing into the pool (or open a new pool). Highs
// cluster to the HIGHEST wick of the group, lows to the lowest: the
// conservative raid line.
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
 
bool lqAnyOn = lqBMajOn or lqBMinOn or lqSMajOn or lqSMinOn
if lqAnyOn
    if not na(lqPhMin)
        f_lqAdd(true, lqPhMin, time[LIQ_MINOR], false)
    if not na(lqPhMaj)
        f_lqAdd(true, lqPhMaj, time[LIQ_MAJOR], true)
    if not na(lqPlMin)
        f_lqAdd(false, lqPlMin, time[LIQ_MINOR], false)
    if not na(lqPlMaj)
        f_lqAdd(false, lqPlMaj, time[LIQ_MAJOR], true)
 
    // Sweeps: a raw trade through the level spends it: remove instantly
    if lqHiLvl.size() > 0
        for i = lqHiLvl.size() - 1 to 0
            if high > lqHiLvl.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)
                float _s5 = lqLoLvl.remove(i)
                int   _s6 = lqLoT.remove(i)
                int   _s7 = lqLoN.remove(i)
                bool  _s8 = lqLoMaj.remove(i)
 
// v6.43: which key level (if any) a pool sits on, inside the ATR/12 "on the line" band.
// Names only, never hides a pool. Ported from the sibling raid tool's f_lqKeyTag; reads this file's
// pdh..pml, which carry the same chart-TF gating as HTF's lqKeyPdh..lqKeyPml.
// Checks only the matching side (highs vs PDH/PWH/PMH, lows vs PDL/PWL/PML); higher TF wins a tie.
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
 
f_lqDraw(float lvl, int t0, int n, bool isHigh, bool isMaj, color lc, string sty) =>
    if not na(lvl)
        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)))
        // Tags: shorthand = flat "BSL" / "SSL" for major and minor alike ·
        // full = "Major BSL" / "Minor SSL". No pool counts.
        string tag = lqShort ?
             (isHigh ? "BSL" : "SSL") :
             (isMaj ? "Major " : "Minor ") + (isHigh ? "BSL" : "SSL")
        string kt = lqKeyTagOn ? f_lqKeyTag(lvl, isHigh) : ""   // v6.43 (HTF v4.54)
        tag := kt == "" ? tag : tag + " · " + kt
        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))
 
// v6.43: display block replaced with the sibling raid tool's. The v6.3 key-level skip and its v6.4
// fall-through are GONE, matching HTF (removed entirely, on purpose). A pool
// on PDH/PDL/PWH/PWL/PMH/PML now draws like any other and says so in its label. Selection:
// nearest major each side, then up to lqMinN minors inside it. Display only: the pools
// feed no grade, target or lane decision in this file.
if barstate.islast
    while lqLines.size() > 0
        line.delete(lqLines.pop())
    while lqLbls.size() > 0
        label.delete(lqLbls.pop())
    if (lqBMajOn or lqBMinOn) and lqHiLvl.size() > 0
        int bMaj = -1
        int bMin = -1
        for i = 0 to lqHiLvl.size() - 1
            float lv = lqHiLvl.get(i)
            if lv > close
                if lqHiMaj.get(i)
                    if bMaj < 0 or lv < lqHiLvl.get(bMaj)
                        bMaj := i
                else if bMin < 0 or lv < lqHiLvl.get(bMin)
                    bMin := i
        if bMin >= 0 and bMaj >= 0 and math.abs(lqHiLvl.get(bMin) - lqHiLvl.get(bMaj)) <= lqTol
            bMin := -1
        // Hierarchy: Major BSL is the OUTER level. A minor sitting beyond the
        // major never draws; the minor is the stepping stone between price and
        // the major, not past it.
        if bMin >= 0 and bMaj >= 0 and lqHiLvl.get(bMin) > lqHiLvl.get(bMaj)
            bMin := -1
        if bMaj >= 0 and lqBMajOn
            f_lqDraw(lqHiLvl.get(bMaj), lqHiT.get(bMaj), lqHiN.get(bMaj), true, true, lqBMajCol, lqBMajSty)
        // Up to lqMinN minors, nearest first, capped inside the major.
        if bMin >= 0 and lqBMinOn
            float bCap = bMaj >= 0 ? lqHiLvl.get(bMaj) - lqTol : na
            float bLast = na
            for k = 1 to lqMinN
                int lqPick = -1
                for i = 0 to lqHiLvl.size() - 1
                    float lv = lqHiLvl.get(i)
                    if lv > close and not lqHiMaj.get(i) and (na(bLast) or lv > bLast) and (na(bCap) or lv < bCap)
                        if lqPick < 0 or lv < lqHiLvl.get(lqPick)
                            lqPick := i
                if lqPick < 0
                    break
                bLast := lqHiLvl.get(lqPick)
                f_lqDraw(lqHiLvl.get(lqPick), lqHiT.get(lqPick), lqHiN.get(lqPick), true, false, lqBMinCol, lqBMinSty)
    if (lqSMajOn or lqSMinOn) and lqLoLvl.size() > 0
        int sMaj = -1
        int sMin = -1
        for i = 0 to lqLoLvl.size() - 1
            float lv = lqLoLvl.get(i)
            if lv < close
                if lqLoMaj.get(i)
                    if sMaj < 0 or lv > lqLoLvl.get(sMaj)
                        sMaj := i
                else if sMin < 0 or lv > lqLoLvl.get(sMin)
                    sMin := i
        if sMin >= 0 and sMaj >= 0 and math.abs(lqLoLvl.get(sMin) - lqLoLvl.get(sMaj)) <= lqTol
            sMin := -1
        // Hierarchy: Major SSL is the OUTER level. A minor below the major never draws.
        if sMin >= 0 and sMaj >= 0 and lqLoLvl.get(sMin) < lqLoLvl.get(sMaj)
            sMin := -1
        if sMaj >= 0 and lqSMajOn
            f_lqDraw(lqLoLvl.get(sMaj), lqLoT.get(sMaj), lqLoN.get(sMaj), false, true, lqSMajCol, lqSMajSty)
        // Up to lqMinN minors, nearest first, capped inside the major. Mirror of the BSL side.
        if sMin >= 0 and lqSMinOn
            float sCap = sMaj >= 0 ? lqLoLvl.get(sMaj) + lqTol : na
            float sLast = na
            for k = 1 to lqMinN
                int lqPick = -1
                for i = 0 to lqLoLvl.size() - 1
                    float lv = lqLoLvl.get(i)
                    if lv < close and not lqLoMaj.get(i) and (na(sLast) or lv < sLast) and (na(sCap) or lv > sCap)
                        if lqPick < 0 or lv > lqLoLvl.get(lqPick)
                            lqPick := i
                if lqPick < 0
                    break
                sLast := lqLoLvl.get(lqPick)
                f_lqDraw(lqLoLvl.get(lqPick), lqLoT.get(lqPick), lqLoN.get(lqPick), false, false, lqSMinCol, lqSMinSty)
 
 
// ═══════════════════════════════════════════════════════════════════════
//  EQUAL HIGHS / LOWS: ported VERBATIM from the sibling raid tool (itself from MM
//  levels tool; same engine, same behavior, same settings). Tracks
//  consecutive wicks at matching prices on the chart TF. When a new
//  candle exceeds a tracked high (or breaks a tracked low), the level
//  is broken and its line is deleted. Lines extend to the most recent
//  matching candle; optional right-extend keeps active levels visible
//  until taken. An unbroken EQH/EQL on the profit side is the raid
//  target the trade plan is drawn toward.
// ═══════════════════════════════════════════════════════════════════════
type EqlPt
    float price
    int   t
    int   ot
 
var array<EqlPt>     eqlHi    = array.new<EqlPt>()
var array<EqlPt>     eqlLo    = array.new<EqlPt>()
var map<float, line> eqhLnMap = map.new<float, line>()
var map<float, line> eqlLnMap = map.new<float, line>()
 
eqlStyle  = eqlLineStyleStr == 'Solid' ? line.style_solid : eqlLineStyleStr == 'Dashed' ? line.style_dashed : line.style_dotted
eqlExtend = eqlExtendRight ? extend.right : extend.none
eqlTolPx  = syminfo.mintick * eqlTolTicks
eqlBarMs  = timeframe.in_seconds() * 1000
 
if showEql and barstate.isconfirmed
    // Highs: pop tracked highs the current bar exceeded
    while array.size(eqlHi) > 0
        EqlPt topH = array.last(eqlHi)
        if high > topH.price + eqlTolPx
            line lnH = map.get(eqhLnMap, topH.price)
            if not na(lnH)
                line.delete(lnH)
                map.remove(eqhLnMap, topH.price)
            array.pop(eqlHi)
        else
            break
 
    int hiOt = time
    if array.size(eqlHi) > 0
        EqlPt topH2 = array.last(eqlHi)
        if math.abs(high - topH2.price) <= eqlTolPx
            int firstT  = math.min(topH2.ot, topH2.t)
            int gapBars = eqlBarMs > 0 ? int((time - firstT) / eqlBarMs) : 0
            if gapBars >= eqlMinBars
                line ln = map.get(eqhLnMap, topH2.price)
                if na(ln)
                    line newLn = line.new(x1 = firstT, y1 = topH2.price, x2 = time, y2 = topH2.price, xloc = xloc.bar_time, color = eqhColor, width = eqlLineWidth, style = eqlStyle, extend = eqlExtend)
                    map.put(eqhLnMap, topH2.price, newLn)
                else
                    line.set_x2(ln, time)
            hiOt := firstT
    array.push(eqlHi, EqlPt.new(high, time, hiOt))
 
    // Lows: pop tracked lows the current bar broke
    while array.size(eqlLo) > 0
        EqlPt topL = array.last(eqlLo)
        if low < topL.price - eqlTolPx
            line lnL = map.get(eqlLnMap, topL.price)
            if not na(lnL)
                line.delete(lnL)
                map.remove(eqlLnMap, topL.price)
            array.pop(eqlLo)
        else
            break
 
    int loOt = time
    if array.size(eqlLo) > 0
        EqlPt topL2 = array.last(eqlLo)
        if math.abs(low - topL2.price) <= eqlTolPx
            int firstT2  = math.min(topL2.ot, topL2.t)
            int gapBars2 = eqlBarMs > 0 ? int((time - firstT2) / eqlBarMs) : 0
            if gapBars2 >= eqlMinBars
                line ln2 = map.get(eqlLnMap, topL2.price)
                if na(ln2)
                    line newLn2 = line.new(x1 = firstT2, y1 = topL2.price, x2 = time, y2 = topL2.price, xloc = xloc.bar_time, color = eqlColor, width = eqlLineWidth, style = eqlStyle, extend = eqlExtend)
                    map.put(eqlLnMap, topL2.price, newLn2)
                else
                    line.set_x2(ln2, time)
            loOt := firstT2
    array.push(eqlLo, EqlPt.new(low, time, loOt))
 
 
// ═══════════════════════════════════════════════════════════════════════
//  LRLR, LOW RESISTANCE LIQUIDITY RUN (v6.13), ported from the standalone run tool,
//  same engine and same calibration as the copy in the sibling raid tool. Keep the
//  three in sync when any one of them changes.
//
//  A staircase of unswept swing extremes: bearish = lower lows AND lower
//  highs, each of those lower highs a failure swing left unswept. Four or
//  more stacked is a ladder of resting liquidity along one diagonal.
//
//  House rule: no LRLR prints unless a SETUP is present. Loose on the chart
//  it answers "is there a clean ladder somewhere": a question nobody asked.
//  Behind the gate it answers the one that matters: an IFVG setup is live and
//  projecting, so is the road to its target actually clean?
//
//  And the gate is the ladder's SIDE, not its direction: an LRLR IS
//  liquidity and a setup is an attempt to RAID it, so a live long wants what
//  sits ABOVE. Detection runs CONTINUOUSLY and only visibility is gated: a
//  staircase almost always forms before the setup that makes it relevant.
// ═══════════════════════════════════════════════════════════════════════
// v6.31: was its own ta.atr(14). atrVal (declared with the global series near the top of
// the file) is the same call on the same series, so this was a second identical average
// computed every bar. The alias keeps the LRLR block reading exactly as its ported sibling
// in the sibling raid tool does, where lrAtr IS the file's only atr(14) and no such overlap exists.
float lrAtr = atrVal
 
// ═══ LOCKED CALIBRATION (v6.14): constants, deliberately NOT inputs ═══
// The tool does the work. These were tuned against 1m/5m NQ and every one
// that could drift is ATR-scaled, so they travel to other symbols and timeframes on their
// own. There is nothing here a user improves by guessing at it, and a TradingView "reset
// settings" can never undo the tuning. The full set stays exposed as inputs in the
// standalone the standalone run tool: that is the place to experiment, not a live chart.
int   lrPiv   = 3      // pivot half-width. A real run spans 30-50 bars on 1m; above ~5
                       // there is no room for four points inside that window.
int   lrPts   = 4      // House rule: FOUR rungs on the line. Two swings is a single
                       // failure swing, not a run: the mistake every other LRLR makes.
float lrLeg   = 0.75   // min swing depth. Kills the wiggles INSIDE an impulse, which
                       // sequence perfectly and hold nobody's stops.
float lrScat  = 1.0    // max rung scatter off the fitted line. Rejects spike-anchored
                       // runs, whose line floats away from the candles through the middle.
float lrSlope = 0.6    // max ATR/bar. An LRLR is a grind that LEAVES liquidity behind it;
                       // a near-vertical leg is displacement, travelling the same way but
                       // leaving nothing resting.
float lrHover = 0.15   // v6.30: was 0.3, was 0.5 at v6.14. the line was asked for twice
                       // closer. Floor is roughly 0.1: below that the line starts sitting
                       // ON the rungs, and a hovering line that touches its own points is
                       // the one thing this drawing must never do.
int   lrExt   = 5      // bars of overhang past the newest rung.
int   lrMax   = 4      // runs retained at once, collected ones included.
int   lrFade  = 80     // HRLR transparency once a run is collected.
 
// ── Zigzag backbone ──
// Folds the raw pivot stream into an ALTERNATING high-low-high-low skeleton
// (same side twice running -> the more extreme absorbs the other). On that
// skeleton the staircase test collapses to one comparison: every point must
// undercut (bearish) or exceed (bullish) the point TWO places back. Stepping
// the index by one alternates highs and lows, so one walk verifies both.
var array<float> lrZzV = array.new<float>()
var array<int>   lrZzB = array.new<int>()
var array<bool>  lrZzH = array.new<bool>()
 
int   LR_ZZ_CAP    = 60
float LR_SLOPE_EPS = 1e-9
int   LR_BI_CLAMP  = MAX_BACK   // v6.44: was 9500, past the 5,000 history buffer
float LR_OUTLIER_K = 1.2   // v6.14: was 1.5, trimmed with the hover gap to bring the line
                           // in closer. Hover clears 1.2 sd of the residuals, NOT the furthest
                           // point. LSQ residuals sum to zero, so this is ~0 on a tight
                           // ladder (line sits exactly the hover gap off the rungs) while
                           // a lone outlier can no longer drag the line off structure.
 
f_lrPush(bool isHigh, float val, int b, float minLeg) =>
    int n = array.size(lrZzV)
    if n == 0
        array.push(lrZzV, val)
        array.push(lrZzB, b)
        array.push(lrZzH, isHigh)
    else if array.get(lrZzH, n - 1) == isHigh
        if (isHigh and val > array.get(lrZzV, n - 1)) or (not isHigh and val < array.get(lrZzV, n - 1))
            array.set(lrZzV, n - 1, val)
            array.set(lrZzB, n - 1, b)
    else
        // LEG-DEPTH GATE. An opposing pivot only becomes a rung if the leg into it has
        // real depth: otherwise a vertical impulse hands over tiny pullbacks that
        // sequence perfectly and draw a staircase across a move that never staircased.
        // A rejected pivot is dropped and the next same-side pivot absorbs into the rung
        // above, which is right: it was all one leg.
        if math.abs(val - array.get(lrZzV, n - 1)) >= minLeg
            array.push(lrZzV, val)
            array.push(lrZzB, b)
            array.push(lrZzH, isHigh)
    // Trimmed OUTSIDE the branch chain: array.shift() returns the dropped element, and
    // leaving it as a branch's last statement makes that branch evaluate to a value while
    // its siblings are void (CE10235).
    if array.size(lrZzV) > LR_ZZ_CAP
        float _v = array.shift(lrZzV)
        int   _b = array.shift(lrZzB)
        bool  _h = array.shift(lrZzH)
    true
 
float lrPvH = ta.pivothigh(high, lrPiv, lrPiv)
float lrPvL = ta.pivotlow(low, lrPiv, lrPiv)
float lrLegMin = lrLeg * nz(lrAtr, 0.0)
if lrOn and not na(lrPvH)
    f_lrPush(true, lrPvH, bar_index - lrPiv, lrLegMin)
if lrOn and not na(lrPvL)
    f_lrPush(false, lrPvL, bar_index - lrPiv, lrLegMin)
 
// ── Run state ──
type LrRun
    line  ln
    label lb
    int   dir        // 1 = bullish (line under the higher lows), -1 = bearish (over highs)
    int   originBar  // first rung's bar: also the run's identity (same origin = same run)
    float originVal  // first rung's price: the last one price must clear to spend the run
    bool  collected
 
var array<LrRun> lrRuns = array.new<LrRun>()
 
// Fitted in BAR-INDEX space, not time: a straight line in time space bends against the
// candles across session gaps, exactly where a hovering line looks broken. Returns the
// scatter alongside the fit so the quality gate can read it back.
f_lrFit(array<int> xs, array<float> ys, int dir, float gap) =>
    int   n  = array.size(xs)
    float sx = 0.0
    float sy = 0.0
    for i = 0 to n - 1
        sx += array.get(xs, i)
        sy += array.get(ys, i)
    float mx  = sx / n
    float my  = sy / n
    float num = 0.0
    float den = 0.0
    for i = 0 to n - 1
        float dx = array.get(xs, i) - mx
        num += dx * (array.get(ys, i) - my)
        den += dx * dx
    float slope = math.abs(den) < LR_SLOPE_EPS ? 0.0 : num / den
    float icept = my - slope * mx
    float ss = 0.0
    for i = 0 to n - 1
        float r = array.get(ys, i) - (slope * array.get(xs, i) + icept)
        ss += r * r
    float sd  = math.sqrt(ss / n)
    float off = LR_OUTLIER_K * sd + gap
    [slope, icept + (dir == -1 ? off : -off), sd]
 
// Walk back from the newest rung while the staircase holds, then count the LINE side.
// A flag rather than break: an if/else where one arm assigns and the other breaks gives
// the arms different value types, which Pine rejects.
f_lrScan(int dir) =>
    int n = array.size(lrZzV)
    int start = n - 1
    bool broke = false
    if n >= 3
        for i = n - 1 to 2
            if not broke
                if dir == -1 ? array.get(lrZzV, i) < array.get(lrZzV, i - 2) : array.get(lrZzV, i) > array.get(lrZzV, i - 2)
                    start := i - 2
                else
                    broke := true
    bool wantHi = dir == -1
    int  pts = 0
    // Guard on start, not n: below 3 points the walk never ran and start is negative, and
    // Pine runs for(0 to -1) once: straight into a get(-1) abort.
    if start >= 0
        for i = start to n - 1
            if array.get(lrZzH, i) == wantHi
                pts += 1
    [start, pts]
 
// Flat accumulator return rather than nested if/else values: keeps every branch void.
f_lrApply(int dir, color col) =>
    if lrOn and array.size(lrZzV) >= 3 and not na(lrAtr) and lrAtr > 0
        [start, pts] = f_lrScan(dir)
        if pts >= lrPts
            array<int>   xs = array.new<int>()
            array<float> ys = array.new<float>()
            bool wantHi = dir == -1
            for i = start to array.size(lrZzV) - 1
                if array.get(lrZzH, i) == wantHi
                    array.push(xs, array.get(lrZzB, i))
                    array.push(ys, array.get(lrZzV, i))
            int   oBar = array.get(xs, 0)
            float oVal = array.get(ys, 0)
            [slope, icept, scat] = f_lrFit(xs, ys, dir, lrHover * lrAtr)
            // SCATTER rejects a run whose rungs sit too far off their own fitted line:
            // the spike-anchored ones, whose line floats away from the candles. STEEPNESS
            // rejects near-vertical runs: an LRLR is a grind that LEAVES liquidity behind
            // it, and a displacement leg is a different animal going the same way.
            bool okScat  = lrScat <= 0 or scat <= lrScat * lrAtr
            bool okSlope = lrSlope <= 0 or math.abs(slope) <= lrSlope * lrAtr
            if okScat and okSlope
                int   x1 = int(math.max(bar_index - LR_BI_CLAMP, oBar))
                int   x2 = array.get(xs, array.size(xs) - 1) + lrExt
                float y1 = slope * x1 + icept
                float y2 = slope * x2 + icept
                LrRun cur = na
                if array.size(lrRuns) > 0
                    for i = array.size(lrRuns) - 1 to 0
                        LrRun r = array.get(lrRuns, i)
                        if r.dir == dir and r.originBar == oBar and not r.collected
                            cur := r
                            break
                if na(cur)
                    // Born invisible. The visibility pass below is the ONLY thing that
                    // colours a run, so a line can never appear ahead of its setup.
                    line  nl = line.new(x1, y1, x2, y2, xloc=xloc.bar_index, color=color.new(col, 100), width=lrWidth, style=f_lstyle(lrStyleIn))
                    label nb = label.new(x2, y2, "", xloc=xloc.bar_index, style=label.style_label_down, color=HF_NONE, textcolor=color.new(col, 100), size=size.tiny)
                    array.push(lrRuns, LrRun.new(nl, nb, dir, oBar, oVal, false))
                    if array.size(lrRuns) > lrMax
                        LrRun old = array.shift(lrRuns)
                        line.delete(old.ln)
                        label.delete(old.lb)
                else
                    line.set_xy1(cur.ln, x1, y1)
                    line.set_xy2(cur.ln, x2, y2)
    true
 
if barstate.isconfirmed
    f_lrApply(-1, lrBearCol)
    f_lrApply(1, lrBullCol)
 
// ── Collection: LRLR -> HRLR ──
// A collected run is DEMOTED, not deleted. Those extremes are swept now, which makes them
// high-resistance liquidity: stop territory, not target territory. The trigger is the
// ORIGIN rung, the furthest one: price works a ladder from the near end inward, so
// nothing short of the origin means the whole thing is cleared. Wick counts: resting
// liquidity is taken by the trade, not by the close.
if array.size(lrRuns) > 0
    for i = 0 to array.size(lrRuns) - 1
        LrRun r = array.get(lrRuns, i)
        if not r.collected and ((r.dir == -1 and high >= r.originVal) or (r.dir == 1 and low <= r.originVal))
            r.collected := true
 
// ── Setup gate ──
// v6.29: PARITY WITH the sibling raid tool (f_lrBookDirs). Over there a setup is LIVE when a CISD
// has CONFIRMED and not yet died: the book's done pool, pruned only by invalidation and
// the cap. There is no delivery test and no stall timer, because neither answers whether a
// setup EXISTS.
//
// This function had both. It was written as f_laneHeld minus its ecoMode condition, and in
// dropping only that it kept f_laneDone and laneStall: two LANE-RULE concepts that answer
// "may a SECOND entry print", not "is there a setup on the chart". So an IFVG that had
// delivered to laneEnd read as "no setup" and blanked its LRLR, while the identical run kept
// drawing on the sibling raid tool off a still-confirmed C2. That showed on a 15m AM setup, whose
// panel reads COMPLETE: delivered, therefore f_laneDone, therefore hidden.
//
// iSt < 2 stays: that IS the invalidation test, the direct analogue of "not yet died".
f_lrLive(int dir) =>
    live = false
    if array.size(iDir) > 0
        for j = 0 to array.size(iDir) - 1
            if array.get(iDir, j) == dir and array.get(iSt, j) < 2
                live := true
    live
 
bool lrLongLive  = f_lrLive(1)
bool lrShortLive = f_lrLive(-1)
bool lrAnyLive   = lrLongLive or lrShortLive
 
// ── Visibility. State via transparency of ONE base colour, per house convention: the fill
// IS the state signal. Hidden = 100, live = solid, collected = the HRLR fade.
//
// The gate is the ladder's SIDE, measured off the ORIGIN rung: the run's defining extreme
// and the same level that decides collection, so position and lifecycle can never disagree
// about a run. For an UNCOLLECTED run side and direction say the same thing anyway (an
// unswept bearish ladder is above price, or it would have been collected); they diverge
// once collected, and side is the half that stays honest: a swept ladder now below a live
// long is stop reference, which is exactly what HRLR means.
if array.size(lrRuns) > 0
    for i = 0 to array.size(lrRuns) - 1
        LrRun r = array.get(lrRuns, i)
        bool  abv = r.originVal > close
        bool  vis = lrGate == "Always" ? true : lrGate == "Any live setup" ? lrAnyLive : abv ? lrLongLive : lrShortLive
        color bse = r.dir == -1 ? lrBearCol : lrBullCol
        color eff = color.new(bse, not (lrOn and vis) ? 100 : r.collected ? lrFade : 0)
        line.set_color(r.ln, eff)
        label.set_textcolor(r.lb, eff)
        label.set_text(r.lb, not (lrOn and vis) ? "" : r.collected ? "HRLR" : "LRLR")
        // v6.16: user-placed tag. Read straight off the line's own endpoints so it tracks
        // a run that is still growing another rung, and so position stays a pure function
        // of the line: no drawing coordinate is ever derived from another drawing's tag.
        // label_down hangs the body ABOVE its anchor and label_up hangs it BELOW; with a
        // transparent background the pointer never shows, so all you see is the text
        // sitting clear of the line on the chosen side.
        int   lx1 = int(line.get_x1(r.ln))
        int   lx2 = int(line.get_x2(r.ln))
        float ly1 = line.get_y1(r.ln)
        float ly2 = line.get_y2(r.ln)
        // v6.44: a run's line keeps its original x1 while bar_index moves on, so an old run
        // drifts past the history buffer and this per-bar set_xy became a far-back read
        // (the RE10143 crash). Pin the label's x to MAX_BACK and slide y along the line to
        // match, so the tag stays ON the line instead of floating off it.
        if lx1 < bar_index - MAX_BACK
            int   cx  = bar_index - MAX_BACK
            float slp = lx2 != lx1 ? (ly2 - ly1) / (lx2 - lx1) : 0.0
            ly1 := ly1 + slp * (cx - lx1)
            lx1 := cx
        if lx2 < bar_index - MAX_BACK
            lx2 := lx1
            ly2 := ly1
        label.set_xy(r.lb, lrLblH == "Left" ? lx1 : lrLblH == "Center" ? int(math.avg(lx1, lx2)) : lx2, lrLblH == "Left" ? ly1 : lrLblH == "Center" ? math.avg(ly1, ly2) : ly2)
        // v6.30: per-direction tag side. r.dir 1 = bullish run, -1 = bearish.
        label.set_style(r.lb, (r.dir == 1 ? lrLblBull : lrLblBear) == "Above" ? label.style_label_down : label.style_label_up)

← 返回列表