Dynamite MGC - Master POI Tracker

otssb228 · study · 2087 行 · 点赞 39 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © otssb228
//@version=6
// =====================================================================================
//  Dynamite MGC — Master POI Tracker  (v1.0)
//
//  A CONTEXT indicator: higher-timeframe points of interest (POIs) and Dynamite levels for Micro Gold (MGC).
//  It produces NO entry, exit, stop, target or trade-management output and places no orders.
//
//  Built from the POI modules of two earlier scripts by the same author (otssb228, MPL-2.0):
//    [A] "Dynamite MGC Setup Assistant — Mobile Refresh + 15M FVG + MTF Sync" v1.5 RC (SHA-256 7cd76a8c…):
//        Dynamite levels (presets / custom, role colours), the 1H / 4H FVG + order-block POI engine
//        (built inside each timeframe, mirrored on the chart, 1m-level touch / mitigation, invalidation on a
//        close of the POI's own timeframe, lower-timeframe rebuild on charts above 1H / 4H) and the
//        display-only 15M FVG module. Code is carried over unchanged; the setup / A+ engine, liquidity
//        sweeps, MSS, DXY, trade management, journal and setup alerts are NOT included.
//    [B] "Dynamite MGC — Daily, Weekly & Monthly POI Tracker" v2.0 (SHA-256 a2eb4b43…): 1D / 1W / 1M FVGs and
//        order blocks, confirmed-close lifecycle, MTF sync, stable selection, context, POI alerts. Unchanged
//        except nine identifiers renamed with a "pt" prefix where they collided with [A].
//  The two engines keep their OWN detection, lifecycle and mitigation rules (they are not unified):
//    [A] 1H/4H : FVG mitigated at the far edge, OB at 50 %; removed when mitigated / invalidated / older than
//                the age limit; max live per type; touch tracked on confirmed chart candles.
//    [B] D/W/M : FILL % lifecycle ACTIVE / TOUCHED / PARTIAL / MITIGATED / INVALIDATED on closed source candles.
//  [A]'s optional 1D POI layer (off by default in [A]) is not included: daily POIs come from [B].
//
//  Display (section "0 · MASTER"): one compact dashboard on the LEFT, white zone descriptions as independent
//  labels at the RIGHT edge of their zones, per-timeframe visibility toggles. Display options never change any
//  zone, state or alert. Educational / analytical tool, not financial advice.
// =====================================================================================
indicator("Dynamite MGC — Master POI Tracker", shorttitle = "DynMGC POI Master", overlay = true, max_boxes_count = 500, max_lines_count = 150, max_labels_count = 300)
 
// =====================================================================================
// 0 · MASTER — display-only settings (never read by any POI calculation or alert)
// =====================================================================================
const string G_M     = "0 · MASTER — dashboard & zone labels"
const string G_MTF   = "0 · MASTER — zone visibility per timeframe"
const string M_LBL_RIGHT = "Right edge (labels)"
const string M_LBL_BOX   = "Inside box (original)"
const string M_LBL_OFF   = "Off"
 
mDashOn  = input.bool(true, "Show dashboard", group = G_M)
mDashPos = input.string("Bottom Left", "Dashboard position", options = ["Top Left", "Middle Left", "Bottom Left"], group = G_M)
mDashPre = input.string("Compact", "Dashboard layout", options = ["Minimal", "Compact", "Full"], group = G_M, tooltip = "Minimal: interaction, confluence, nearest D/W/M and 4H/1H POI, context arrows. Compact (default): M/W/D context + nearest M / W / D / 4H / 1H POI + interaction + confluence. Full: every row of the D/W/M tracker dashboard plus nearest bull / bear 4H, 1H, 15M and Dynamite levels and the legend.")
mDashSz  = input.string("Small", "Dashboard text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_M)
mLblMode = input.string(M_LBL_RIGHT, "Zone label placement", options = [M_LBL_RIGHT, M_LBL_BOX, M_LBL_OFF], group = G_M, tooltip = "Right edge: every FVG / order-block / Dynamite description is an independent white label just right of the latest candle (the visible right edge of each extended zone), vertically centred on its zone; zones whose labels would collide are stacked into one multi-line label in the same top-to-bottom order. Zones are never hidden to resolve label overlap. Inside box: the original box text. Off: no zone text.")
mLblWord = input.string("Compact", "Zone label wording", options = ["Compact", "Full"], group = G_M, tooltip = "Compact: 4H BEAR OB, 1W BULL FVG · P 62%. Full: the original wording of each module.")
mLblOff  = input.int(3, "Right-edge label anchor (bars right of the latest candle)", minval = 0, maxval = 250, group = G_M, tooltip = "Where each label is anchored, in bars right of the latest candle.")
mLblDir  = input.string("Text ends at anchor (never clipped)", "Right-edge text direction", options = ["Text ends at anchor (never clipped)", "Text starts at anchor"], group = G_M, tooltip = "Text ends at anchor: the label ends just right of the latest candle and extends left, so it is never cut off by the price scale, whatever your chart right margin. Text starts at anchor: the label starts right of the latest candle and extends right; it needs a chart right margin (Chart settings > Canvas > Right margin) wide enough for the text.")
mLblSz   = input.string("Small", "Zone label size", options = ["Tiny", "Small", "Normal", "Large"], group = G_M)
mLblGap  = input.float(0.03, "Label line height (× price range of the last 200 bars)", minval = 0.0, step = 0.005, group = G_M, tooltip = "Approximate height of one text line, as a fraction of the recent 200-bar price range (about what a default chart shows). Labels closer than this are stacked into one label so they never overlap. Raise it if labels touch when you zoom out; lower it to see more separate labels.")
mLblMax  = input.int(5, "Max names per stacked label", minval = 1, maxval = 10, group = G_M, tooltip = "Higher timeframes keep priority (1M > 1W > 1D > 4H > 1H > 15M > Dynamite); the rest are counted as '+n more'. Every zone is still drawn.")
mShow15  = input.bool(true, "15M", inline = "mtf1", group = G_MTF)
mShow1H  = input.bool(true, "1H", inline = "mtf1", group = G_MTF)
mShow4H  = input.bool(true, "4H", inline = "mtf1", group = G_MTF)
mShow1D  = input.bool(true, "1D", inline = "mtf2", group = G_MTF)
mShow1W  = input.bool(true, "1W", inline = "mtf2", group = G_MTF)
mShow1M  = input.bool(true, "1M", inline = "mtf2", group = G_MTF)
mShowDyn = input.bool(true, "Dynamite levels", inline = "mtf3", group = G_MTF, tooltip = "Visibility only: hidden zones keep being tracked and alerted exactly as before.")
 
// display-only visibility of a zone timeframe
mTfVis(string tf) =>
    tf == "15M" ? mShow15 : tf == "1H" ? mShow1H : tf == "4H" ? mShow4H : tf == "1D" ? mShow1D : tf == "1W" ? mShow1W : tf == "1M" ? mShow1M : true
 
// =====================================================================================
// [A] FROM THE SETUP ASSISTANT v1.5 RC — Dynamite levels, 1H/4H POI engine, 15M FVGs (verbatim)
// =====================================================================================
const string R_AUTO = "Auto (both)"
const string R_BEAR = "Bearish (shorts)"
const string R_BULL = "Bullish (longs)"
const string PS_CUR = "Current — 09/29"
const string PS_LEG = "Legacy — 09/23"
const string PS_CUS = "Custom"
const string G_ZDISP = "2 · Dynamite zone display"
const string G_HTF   = "13 · HTF POI 1H+ (FVG / Order Block)"
tickOverride = input.float(0.0, "Tick size override (0 = symbol min tick)", minval = 0.0, step = 0.01, group = G_ZDISP, tooltip = "MGC min tick is 0.10. Leave 0 to use the chart symbol's min tick.")
colHist     = input.color(#787b86, "Mitigated 1H/4H POI colour", group = G_HTF)
// ---- 2 · Dynamite zones ----
// Zone preset:
//   Current — 09/29 : TradingView "MGCZ2026 30M Dynamite Levels" v9 (saved 2026-09-29)  [default]
//   Legacy  — 09/23 : dynamite-levels-mgc.js "MGC OCT Z1..Z6" (2026-09-23), kept for comparison
//   Custom          : the Top / Mid / Bot / Name inputs below (they default to the 09/29 set)
// In every preset the per-zone Enable / Role / Colour inputs still apply.
// Mid = 0 means "auto midpoint". A zone with Top or Bottom <= 0 is ignored.
zonePreset = input.string(PS_CUR, "Zone preset", options = [PS_CUR, PS_LEG, PS_CUS], group = "Zone preset", tooltip = "Current / Legacy use built-in level sets. Custom uses the Top/Mid/Bot/Name values typed in Zone 1-8.")
 
z1On = input.bool(true, "", inline = "z1a", group = "Zone 1")
z1Nm = input.string("Major upper supply", "", inline = "z1a", group = "Zone 1")
z1Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z1a", group = "Zone 1")
z1Cl = input.color(#4b7dff, "", inline = "z1a", group = "Zone 1")
z1T  = input.float(4730.0, "Top", inline = "z1b", group = "Zone 1")
z1M  = input.float(4705.0, "Mid", inline = "z1b", group = "Zone 1")
z1B  = input.float(4680.0, "Bot", inline = "z1b", group = "Zone 1")
 
z2On = input.bool(true, "", inline = "z2a", group = "Zone 2")
z2Nm = input.string("Major S/R pivot", "", inline = "z2a", group = "Zone 2")
z2Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z2a", group = "Zone 2")
z2Cl = input.color(#4b7dff, "", inline = "z2a", group = "Zone 2")
z2T  = input.float(4545.0, "Top", inline = "z2b", group = "Zone 2")
z2M  = input.float(4525.0, "Mid", inline = "z2b", group = "Zone 2")
z2B  = input.float(4505.0, "Bot", inline = "z2b", group = "Zone 2")
 
z3On = input.bool(true, "", inline = "z3a", group = "Zone 3")
z3Nm = input.string("Upper decision / supply", "", inline = "z3a", group = "Zone 3")
z3Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z3a", group = "Zone 3")
z3Cl = input.color(#4b7dff, "", inline = "z3a", group = "Zone 3")
z3T  = input.float(4460.0, "Top", inline = "z3b", group = "Zone 3")
z3M  = input.float(4440.0, "Mid", inline = "z3b", group = "Zone 3")
z3B  = input.float(4420.0, "Bot", inline = "z3b", group = "Zone 3")
 
z4On = input.bool(true, "", inline = "z4a", group = "Zone 4")
z4Nm = input.string("Primary S/R decision", "", inline = "z4a", group = "Zone 4")
z4Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z4a", group = "Zone 4")
z4Cl = input.color(#4b7dff, "", inline = "z4a", group = "Zone 4")
z4T  = input.float(4350.0, "Top", inline = "z4b", group = "Zone 4")
z4M  = input.float(4325.0, "Mid", inline = "z4b", group = "Zone 4")
z4B  = input.float(4300.0, "Bot", inline = "z4b", group = "Zone 4")
 
z5On = input.bool(true, "", inline = "z5a", group = "Zone 5")
z5Nm = input.string("Current breakdown / reclaim", "", inline = "z5a", group = "Zone 5")
z5Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z5a", group = "Zone 5")
z5Cl = input.color(#4b7dff, "", inline = "z5a", group = "Zone 5")
z5T  = input.float(4200.0, "Top", inline = "z5b", group = "Zone 5")
z5M  = input.float(4180.0, "Mid", inline = "z5b", group = "Zone 5")
z5B  = input.float(4160.0, "Bot", inline = "z5b", group = "Zone 5")
 
z6On = input.bool(true, "", inline = "z6a", group = "Zone 6")
z6Nm = input.string("Major lower demand", "", inline = "z6a", group = "Zone 6")
z6Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z6a", group = "Zone 6")
z6Cl = input.color(#4b7dff, "", inline = "z6a", group = "Zone 6")
z6T  = input.float(4085.0, "Top", inline = "z6b", group = "Zone 6")
z6M  = input.float(4060.0, "Mid", inline = "z6b", group = "Zone 6")
z6B  = input.float(4035.0, "Bot", inline = "z6b", group = "Zone 6")
 
z7On = input.bool(false, "", inline = "z7a", group = "Zone 7")
z7Nm = input.string("Zone 7", "", inline = "z7a", group = "Zone 7")
z7Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z7a", group = "Zone 7")
z7Cl = input.color(#4b7dff, "", inline = "z7a", group = "Zone 7")
z7T  = input.float(0.0, "Top", inline = "z7b", group = "Zone 7")
z7M  = input.float(0.0, "Mid", inline = "z7b", group = "Zone 7")
z7B  = input.float(0.0, "Bot", inline = "z7b", group = "Zone 7")
 
z8On = input.bool(false, "", inline = "z8a", group = "Zone 8")
z8Nm = input.string("Zone 8", "", inline = "z8a", group = "Zone 8")
z8Rl = input.string(R_AUTO, "", options = [R_AUTO, R_BEAR, R_BULL], inline = "z8a", group = "Zone 8")
z8Cl = input.color(#4b7dff, "", inline = "z8a", group = "Zone 8")
z8T  = input.float(0.0, "Top", inline = "z8b", group = "Zone 8")
z8M  = input.float(0.0, "Mid", inline = "z8b", group = "Zone 8")
z8B  = input.float(0.0, "Bot", inline = "z8b", group = "Zone 8")
 
zoneTransp     = input.int(88, "Zone fill transparency", minval = 0, maxval = 100, group = G_ZDISP)
zoneBorderW    = input.int(1, "Zone border width", minval = 1, maxval = 4, group = G_ZDISP)
showZoneLabels = input.bool(true, "Show zone labels (right side)", group = G_ZDISP)
labelOffset    = input.int(2, "Label anchor (bars right of last bar)", minval = 0, maxval = 200, group = G_ZDISP, tooltip = "Labels end at this point and extend LEFT, so they stay visible even with a small right margin.")
labelClearTk   = input.int(30, "Move label below zone when price is this close above the top (ticks)", minval = 0, group = G_ZDISP)
proxTicks      = input.int(40, "Approaching threshold (ticks)", minval = 0, group = G_ZDISP, tooltip = "Display only: price within this distance of a zone is labelled APPROACHING.")
// ---- 13 · HTF POI (1H and above) ----
// HTF FVGs / Order Blocks (1H and above). In the two HTF-POI arming modes they are the
// location anchor of every setup; display toggles below never affect arming.
htfOn        = input.bool(true, "Enable HTF POI module", group = G_HTF)
htf1hOn      = input.bool(true, "1H", inline = "htftf", group = G_HTF)
htf4hOn      = input.bool(true, "4H", inline = "htftf", group = G_HTF)
bool htf1dOn = false   // MASTER: daily POIs come from the D/W/M tracker [B]; [A]'s optional 1D layer is not included
htfShowFvg   = input.bool(true, "Show HTF FVGs", inline = "htfshow", group = G_HTF)
htfShowOb    = input.bool(true, "Show HTF Order Blocks", inline = "htfshow", group = G_HTF)
htfFvgMinAtr = input.float(0.10, "HTF FVG minimum gap (× HTF ATR14)", minval = 0.0, step = 0.05, group = G_HTF)
obDispAtr    = input.float(1.0, "OB: displacement body >= × HTF ATR14", minval = 0.1, step = 0.1, group = G_HTF)
obPivLen     = input.int(3, "OB: structure pivot length (HTF bars each side)", minval = 1, group = G_HTF)
obMaxCluster = input.int(3, "OB: max opposing candles in the block", minval = 1, maxval = 5, group = G_HTF)
htfMaxLive   = input.int(4, "Keep max live POIs per timeframe & type", minval = 1, maxval = 4, group = G_HTF)
htfWideAtr   = input.float(1.5, "OB marked WIDE when height > × HTF ATR14", minval = 0.5, step = 0.1, group = G_HTF)
htfMaxAge    = input.int(60, "Drop POIs older than (HTF bars)", minval = 5, group = G_HTF)
htfShowMitig = input.bool(false, "Keep MITIGATED POIs on chart", group = G_HTF)
htfNearTk    = input.int(20, "POI to Dynamite overlap tolerance (ticks)", minval = 0, group = G_HTF)
htfBearCol   = input.color(#ff1744, "Bearish POI", inline = "htfcol", group = G_HTF)
htfBullCol   = input.color(#00c853, "Bullish POI", inline = "htfcol", group = G_HTF)
// ---- 16 · Visual Refresh (display only; declared last so every original input id is unchanged) ----
const string G_VR = "16 · Visual Refresh (display only)"
vrDirZones = input.bool(true, "Colour Dynamite zones by role (Bearish = red, Bullish = green, Auto = neutral)", group = G_VR, tooltip = "Display only. Zones whose role is 'Auto (both)' are dual-purpose and stay NEUTRAL; no direction is assigned. Turn off to use the per-zone colours from section 2.")
vrBull     = input.color(#00e676, "Bullish zone", group = G_VR)
vrBear     = input.color(#ff1744, "Bearish zone", group = G_VR)
vrNeut     = input.color(#ffd166, "Neutral zone (Auto role)", group = G_VR)
vrTextCol  = input.color(#ffffff, "Level label text colour", group = G_VR, tooltip = "All Dynamite-level and POI labels use this one colour (white by default). Direction is shown by the zone, boundary and shading colour.")
vrLblSize  = input.string("Small", "Level label text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_VR)
vrTxtTr    = input.int(0, "Level label text transparency", minval = 0, maxval = 90, group = G_VR)
vrPoiFill  = input.int(82, "HTF POI fill transparency (active)", minval = 50, maxval = 98, group = G_VR, tooltip = "Touched / mitigated POIs are drawn progressively lighter from this value. 82 = original.")
 
vrSize(string s) =>
    s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : s == "Large" ? size.large : size.small
float tick        = tickOverride > 0 ? tickOverride : syminfo.mintick
float tolProx     = proxTicks * tick
// =====================================================================================
// DYNAMITE ZONES (built once; inputs are constant for the life of the script)
// =====================================================================================
var array<bool>   zOn = array.from(z1On, z2On, z3On, z4On, z5On, z6On, z7On, z8On)
var array<string> zRl = array.from(z1Rl, z2Rl, z3Rl, z4Rl, z5Rl, z6Rl, z7Rl, z8Rl)
var array<color>  zCl = array.from(z1Cl, z2Cl, z3Cl, z4Cl, z5Cl, z6Cl, z7Cl, z8Cl)
// Level sets. Slots 7-8 are empty in the built-in presets (0 = ignored).
var array<string> zNm = zonePreset == PS_CUR ? array.from("Major upper supply", "Major S/R pivot", "Upper decision / supply", "Primary S/R decision", "Current breakdown / reclaim", "Major lower demand", "Zone 7", "Zone 8") : zonePreset == PS_LEG ? array.from("MGC OCT Z1", "MGC OCT Z2", "MGC OCT Z3", "MGC OCT Z4", "MGC OCT Z5", "MGC OCT Z6", "Zone 7", "Zone 8") : array.from(z1Nm, z2Nm, z3Nm, z4Nm, z5Nm, z6Nm, z7Nm, z8Nm)
var array<float>  zT  = zonePreset == PS_CUR ? array.from(4730.0, 4545.0, 4460.0, 4350.0, 4200.0, 4085.0, 0.0, 0.0) : zonePreset == PS_LEG ? array.from(4405.0, 4380.0, 4355.0, 4320.0, 4290.0, 4240.0, 0.0, 0.0) : array.from(z1T, z2T, z3T, z4T, z5T, z6T, z7T, z8T)
var array<float>  zM  = zonePreset == PS_CUR ? array.from(4705.0, 4525.0, 4440.0, 4325.0, 4180.0, 4060.0, 0.0, 0.0) : zonePreset == PS_LEG ? array.from(4400.0, 4370.0, 4350.0, 4318.5, 4280.0, 4233.5, 0.0, 0.0) : array.from(z1M, z2M, z3M, z4M, z5M, z6M, z7M, z8M)
var array<float>  zB  = zonePreset == PS_CUR ? array.from(4680.0, 4505.0, 4420.0, 4300.0, 4160.0, 4035.0, 0.0, 0.0) : zonePreset == PS_LEG ? array.from(4390.0, 4360.0, 4345.0, 4317.0, 4270.0, 4230.0, 0.0, 0.0) : array.from(z1B, z2B, z3B, z4B, z5B, z6B, z7B, z8B)
 
// Display colour of zone i (Visual Refresh): role Bearish -> red, Bullish -> green, Auto -> neutral.
vrZoneCol(int i) =>
    string r = zRl.get(i)
    vrDirZones ? (r == R_BEAR ? vrBear : r == R_BULL ? vrBull : vrNeut) : zCl.get(i)
 
// Fixed-size drawing pools: exactly one box / mid line / label per zone slot, created
// once and only re-positioned afterwards, so they can never accumulate.
var array<box>   zBoxes = array.new<box>()
var array<line>  zMids  = array.new<line>()
var array<label> zLbls  = array.new<label>()
 
if barstate.isfirst
    for i = 0 to 7
        float t = zT.get(i)
        float b = zB.get(i)
        if t < b
            zT.set(i, b)
            zB.set(i, t)
        if zT.get(i) <= 0 or zB.get(i) <= 0
            zOn.set(i, false)
        float m = zM.get(i)
        if m <= 0 or m > zT.get(i) or m < zB.get(i)
            zM.set(i, (zT.get(i) + zB.get(i)) / 2)
        if zOn.get(i)
            color c = vrZoneCol(i)
            zBoxes.push(box.new(bar_index, zT.get(i), bar_index + 1, zB.get(i), border_color = color.new(c, mShowDyn ? 0 : 100), border_width = zoneBorderW, bgcolor = color.new(c, mShowDyn ? zoneTransp : 100), extend = extend.both))
            zMids.push(line.new(bar_index, zM.get(i), bar_index + 1, zM.get(i), color = color.new(c, mShowDyn ? 15 : 100), style = line.style_dotted, width = 1, extend = extend.both))
            zLbls.push(showZoneLabels ? label.new(bar_index, zT.get(i), "", style = label.style_label_lower_right, color = color.new(c, 100), textcolor = color.new(vrTextCol, vrTxtTr), size = vrSize(vrLblSize)) : na)
        else
            zBoxes.push(na)
            zMids.push(na)
            zLbls.push(na)
 
// Where is price relative to zone i?  (INTRABAR: uses the live close; display only)
zoneStatus(int i) =>
    float t = zT.get(i)
    float b = zB.get(i)
    string s = ""
    if close >= b and close <= t
        s := "INSIDE"
    else if close > t
        s := close - t <= tolProx ? "APPROACHING from above (" + str.tostring(math.round((close - t) / tick)) + "t)" : "price ABOVE zone"
    else
        s := b - close <= tolProx ? "APPROACHING from below (" + str.tostring(math.round((b - close) / tick)) + "t)" : "price BELOW zone"
    s
 
zoneDist(int i) =>
    float t = zT.get(i)
    float b = zB.get(i)
    close > t ? close - t : close < b ? b - close : 0.0
 
roleTag(string r) =>
    r == R_BEAR ? "SELL" : r == R_BULL ? "BUY" : "AUTO"
 
// Index-safe zone readers (never touch the arrays with an out-of-range index).
zName(int i) =>
    string r = "—"
    if i >= 0 and i < 8
        r := zNm.get(i)
    r
 
zRangeTxt(int i) =>
    string r = "—"
    if i >= 0 and i < 8
        r := zNm.get(i) + " " + str.tostring(zB.get(i), format.mintick) + "–" + str.tostring(zT.get(i), format.mintick)
    r
fmtP(float x) =>
    na(x) ? "—" : str.tostring(x, format.mintick)
// =====================================================================================
// HTF POI MODULE (1H / 4H / 1D) — v1.2: HTF-native tracking; arms setups in POI modes
// -------------------------------------------------------------------------------------
// Hierarchy: DYNAMITE / MACRO CONTEXT -> 1H+ FVG OR ORDER BLOCK (this module)
//   -> manipulation INTO that POI -> 1m displacement -> 1m MSS -> NEW 1m FVG -> retrace
//   -> DXY -> user decision.  The 1m FVG of the state machine is NOT the HTF POI.
//
// POIs are built and aged INSIDE each higher timeframe's own history (request.security
// context), so an unfilled 4H / 1D FVG or OB that formed long before the 1m chart history
// still exists. Each timeframe returns its 4 most recent live FVGs + 4 most recent live
// OBs as fixed slots of the LAST CLOSED HTF candle ([1] + lookahead_on = no future leak).
// The chart side mirrors them, adds 1m touch / mitigation detail and draws them.
// =====================================================================================
htfRemove(array<float> aTop, array<float> aBot, array<int> aT, array<int> aDir, array<int> aKind, array<int> aSt, array<bool> aWide, array<int> aBorn, int i) =>
    aTop.remove(i)
    aBot.remove(i)
    aT.remove(i)
    aDir.remove(i)
    aKind.remove(i)
    aSt.remove(i)
    aWide.remove(i)
    aBorn.remove(i)
    aTop.size()
 
htfPush(array<float> aTop, array<float> aBot, array<int> aT, array<int> aDir, array<int> aKind, array<int> aSt, array<bool> aWide, array<int> aBorn, float top, float bot, int t, int dir, int kind, bool wide) =>
    if not na(top) and not na(bot) and top > bot
        aTop.push(top)
        aBot.push(bot)
        aT.push(t)
        aDir.push(dir)
        aKind.push(kind)
        aSt.push(0)
        aWide.push(wide)
        aBorn.push(bar_index)
    aTop.size()
 
htfPoiPack(int off) =>
    float a = ta.atr(14)
    var array<float> aTop  = array.new<float>()
    var array<float> aBot  = array.new<float>()
    var array<int>   aT    = array.new<int>()
    var array<int>   aDir  = array.new<int>()
    var array<int>   aKind = array.new<int>()
    var array<int>   aSt   = array.new<int>()
    var array<bool>  aWide = array.new<bool>()
    var array<int>   aBorn = array.new<int>()
    // ---- 1) lifecycle of existing POIs on this closed HTF candle ----
    //   touched     : candle trades into the POI
    //   mitigated   : FVG traded to its far edge / OB traded to its 50% -> removed
    //   invalidated : candle CLOSES beyond the far edge                -> removed
    //   stale       : older than htfMaxAge HTF bars                    -> removed
    int n0 = aTop.size()
    if n0 > 0
        for i = n0 - 1 to 0
            float t    = aTop.get(i)
            float b    = aBot.get(i)
            bool  bear = aDir.get(i) < 0
            float deep = aKind.get(i) == 0 ? (bear ? t : b) : (t + b) / 2
            if bear ? high >= b : low <= t
                aSt.set(i, 1)
            bool mitig = bear ? high >= deep : low <= deep
            bool inval = bear ? close > t : close < b
            bool stale = bar_index - aBorn.get(i) > htfMaxAge
            if mitig or inval or stale
                htfRemove(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, i)
    // ---- 2) new 3-candle FVG completed by this candle ----
    float bullGapH = low - high[2]
    float bearGapH = low[2] - high
    if bullGapH > 0 and bullGapH >= a * htfFvgMinAtr
        htfPush(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, low, high[2], time[2], 1, 0, false)
    if bearGapH > 0 and bearGapH >= a * htfFvgMinAtr
        htfPush(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, low[2], high, time[2], -1, 0, false)
    // ---- 3) conservative order block: opposing candle(s) -> displacement -> BOS close ----
    float hPl = ta.pivotlow(low, obPivLen, obPivLen)
    float hPh = ta.pivothigh(high, obPivLen, obPivLen)
    var float swL = na
    var float swH = na
    var bool  swLUsed = true
    var bool  swHUsed = true
    if not na(hPl)
        swL := hPl
        swLUsed := false
    if not na(hPh)
        swH := hPh
        swHUsed := false
    bool bosDn = not swLUsed and close < swL
    bool bosUp = not swHUsed and close > swH
    if bosDn
        swLUsed := true
    if bosUp
        swHUsed := true
    bool dDn = false
    bool dUp = false
    for i = 0 to 2
        float bd = open[i] - close[i]
        if bd >= a[i] * obDispAtr
            dDn := true
        if -bd >= a[i] * obDispAtr
            dUp := true
    if bosDn and dDn
        // bearish OB = last bullish candle (or cluster) before the drop; range = OPEN -> HIGH
        int k = -1
        for i = 0 to 8
            if close[i] > open[i]
                k := i
                break
        if k >= 0
            float t  = high[k]
            float b  = open[k]
            int   tt = time[k]
            int   n  = 1
            int   j  = k + 1
            while n < obMaxCluster and close[j] > open[j]
                t  := math.max(t, high[j])
                b  := math.min(b, open[j])
                tt := time[j]
                n  += 1
                j  += 1
            htfPush(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, t, b, tt, -1, 1, (t - b) > htfWideAtr * a)
    if bosUp and dUp
        // bullish OB = last bearish candle (or cluster) before the rally; range = OPEN -> LOW
        int k = -1
        for i = 0 to 8
            if close[i] < open[i]
                k := i
                break
        if k >= 0
            float t  = open[k]
            float b  = low[k]
            int   tt = time[k]
            int   n  = 1
            int   j  = k + 1
            while n < obMaxCluster and close[j] < open[j]
                t  := math.max(t, open[j])
                b  := math.min(b, low[j])
                tt := time[j]
                n  += 1
                j  += 1
            htfPush(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, t, b, tt, 1, 1, (t - b) > htfWideAtr * a)
    // ---- 4) keep only the most recent htfMaxLive per type ----
    int keepF = 0
    int keepO = 0
    int n2 = aTop.size()
    if n2 > 0
        for i = n2 - 1 to 0
            bool isF = aKind.get(i) == 0
            if isF
                keepF += 1
            else
                keepO += 1
            if (isF and keepF > htfMaxLive) or (not isF and keepO > htfMaxLive)
                htfRemove(aTop, aBot, aT, aDir, aKind, aSt, aWide, aBorn, i)
    // ---- 5) export: slots 0-3 = FVGs, 4-7 = OBs (newest first); code = dir*(1+kind+2*touched+4*wide)
    array<float> sl = array.new<float>(32, na)
    for q = 0 to 7
        sl.set(q * 4 + 3, 0.0)
    int fi = 0
    int oi = 0
    int n3 = aTop.size()
    if n3 > 0
        for i = n3 - 1 to 0
            int kk = aKind.get(i)
            if (kk == 0 and fi < 4) or (kk == 1 and oi < 4)
                int slot = kk == 0 ? fi : 4 + oi
                sl.set(slot * 4, aTop.get(i))
                sl.set(slot * 4 + 1, aBot.get(i))
                sl.set(slot * 4 + 2, float(aT.get(i)))
                sl.set(slot * 4 + 3, float(aDir.get(i) * (1 + kk + 2 * aSt.get(i) + (aWide.get(i) ? 4 : 0))))
                if kk == 0
                    fi += 1
                else
                    oi += 1
    float x0 = sl.get(0)
    float x1 = sl.get(1)
    float x2 = sl.get(2)
    float x3 = sl.get(3)
    float x4 = sl.get(4)
    float x5 = sl.get(5)
    float x6 = sl.get(6)
    float x7 = sl.get(7)
    float x8 = sl.get(8)
    float x9 = sl.get(9)
    float x10 = sl.get(10)
    float x11 = sl.get(11)
    float x12 = sl.get(12)
    float x13 = sl.get(13)
    float x14 = sl.get(14)
    float x15 = sl.get(15)
    float x16 = sl.get(16)
    float x17 = sl.get(17)
    float x18 = sl.get(18)
    float x19 = sl.get(19)
    float x20 = sl.get(20)
    float x21 = sl.get(21)
    float x22 = sl.get(22)
    float x23 = sl.get(23)
    float x24 = sl.get(24)
    float x25 = sl.get(25)
    float x26 = sl.get(26)
    float x27 = sl.get(27)
    float x28 = sl.get(28)
    float x29 = sl.get(29)
    float x30 = sl.get(30)
    float x31 = sl.get(31)
    [time[off], close[off], a[off], x0[off], x1[off], x2[off], x3[off], x4[off], x5[off], x6[off], x7[off], x8[off], x9[off], x10[off], x11[off], x12[off], x13[off], x14[off], x15[off], x16[off], x17[off], x18[off], x19[off], x20[off], x21[off], x22[off], x23[off], x24[off], x25[off], x26[off], x27[off], x28[off], x29[off], x30[off], x31[off]]
 
[h1T, h1C, h1A, h1x0, h1x1, h1x2, h1x3, h1x4, h1x5, h1x6, h1x7, h1x8, h1x9, h1x10, h1x11, h1x12, h1x13, h1x14, h1x15, h1x16, h1x17, h1x18, h1x19, h1x20, h1x21, h1x22, h1x23, h1x24, h1x25, h1x26, h1x27, h1x28, h1x29, h1x30, h1x31] = request.security(syminfo.tickerid, "60", htfPoiPack(1), lookahead = barmerge.lookahead_on)
[h4T, h4C, h4A, h4x0, h4x1, h4x2, h4x3, h4x4, h4x5, h4x6, h4x7, h4x8, h4x9, h4x10, h4x11, h4x12, h4x13, h4x14, h4x15, h4x16, h4x17, h4x18, h4x19, h4x20, h4x21, h4x22, h4x23, h4x24, h4x25, h4x26, h4x27, h4x28, h4x29, h4x30, h4x31] = request.security(syminfo.tickerid, "240", htfPoiPack(1), lookahead = barmerge.lookahead_on)
int   hDT = na   // MASTER: [A]'s 1D request removed (layer not included)
float hDC = na
 
// a new CLOSED HTF candle became available on this chart bar
bool h1New = htfOn and htf1hOn and not na(h1T) and h1T != nz(h1T[1])
bool h4New = htfOn and htf4hOn and not na(h4T) and h4T != nz(h4T[1])
bool hDNew = htfOn and htf1dOn and not na(hDT) and hDT != nz(hDT[1])
 
// ---- MTF Sync v1.4-dev: which POI timeframes are LOWER than the chart timeframe ----
// Only those use the request.security_lower_tf() rebuild below. On a 1m chart all three are false.
int  mtfChartSec = timeframe.in_seconds()
bool h1Ltf = htfOn and htf1hOn and mtfChartSec > 3600
bool h4Ltf = htfOn and htf4hOn and mtfChartSec > 14400
bool hDLtf = htfOn and htf1dOn and mtfChartSec > 86400
 
poiIsLtf(string tf) =>
    tf == "1H" ? h1Ltf : tf == "4H" ? h4Ltf : hDLtf
 
const int PK_FVG = 0
const int PK_OB  = 1
const int PS_ACTIVE  = 0
const int PS_TOUCHED = 1
const int PS_MITIG   = 2
const int PS_INVALID = 3
 
type Poi
    string tf
    int    kind
    int    dir
    float  top
    float  bot
    float  mid
    int    tStart
    int    tConfirm
    int    state     = 0
    int    statePrev = 0
    bool   wide      = false
    bool   armed     = false   // display only: a running setup is tied to this POI
    bool   dyn       = false
    int    dynIdx    = -1
    string dynName   = ""
    box    bx
 
var array<Poi> pois = array.new<Poi>()
// per-bar touch flags: [bear POI, bull POI, bear POI ∩ Dynamite, bull POI ∩ Dynamite]
var array<bool> poiTouch = array.from(false, false, false, false)
var array<int> poiMade = array.from(0, 0)   // [FVGs loaded, OBs loaded]
var int firstBarTime = time
 
tfRank(string tf) =>
    tf == "1D" ? 3 : tf == "4H" ? 2 : 1
 
poiName(Poi p) =>
    p.tf + " " + (p.dir > 0 ? "BULLISH" : "BEARISH") + " " + (p.kind == PK_FVG ? "FVG" : "OB") + (p.wide ? " (WIDE)" : "")
 
poiStateTxt(int st) =>
    st == PS_ACTIVE ? "ACTIVE" : st == PS_TOUCHED ? "TOUCHED" : st == PS_MITIG ? "MITIGATED" : "INVALIDATED"
 
method poiStyle(Poi p) =>
    if not na(p.bx)
        // the POI a running setup is armed on stays visible (even when MITIGATED) until that
        // setup completes / expires / invalidates — display only, never affects signals
        bool  hide = (p.state == PS_MITIG and not htfShowMitig and not p.armed) or not mTfVis(p.tf)   // MASTER: + TF toggle
        color c  = p.state == PS_MITIG and not p.armed ? colHist : p.dir > 0 ? htfBullCol : htfBearCol
        int   tr = hide ? 100 : p.armed ? math.max(vrPoiFill - 2, 0) : p.state == PS_ACTIVE ? vrPoiFill : p.state == PS_TOUCHED ? math.min(vrPoiFill + 6, 100) : math.min(vrPoiFill + 12, 100)
        box.set_bgcolor(p.bx, color.new(c, tr))
        box.set_border_color(p.bx, color.new(c, hide ? 100 : p.armed ? 0 : p.state == PS_ACTIVE ? 20 : 50))
        box.set_border_width(p.bx, p.armed ? 3 : p.tf == "1H" ? 1 : 2)
        bool htfLbl = mLblMode != M_LBL_BOX   // MASTER: descriptions drawn as right-edge labels (or Off)
        box.set_text(p.bx, hide or htfLbl ? "" : (p.armed ? "ARMED POI ▸ " : "") + poiName(p) + (p.dyn ? " ◆ " + p.dynName : "") + (p.state == PS_ACTIVE ? "" : " · " + poiStateTxt(p.state)))
    p
 
method poiDrop(array<Poi> arr, int i) =>
    Poi p = arr.get(i)
    box.delete(p.bx)
    arr.remove(i)
    arr.size()
 
poiCreate(string tf, int kind, int dir, float top, float bot, int tStart, int st, bool wide) =>
    Poi p = Poi.new(tf, kind, dir, top, bot, (top + bot) / 2, tStart, time, st, st, wide)
    // Dynamite confluence: POI overlaps (or sits within tolerance of) an enabled zone
    float tol = htfNearTk * tick
    for i = 0 to 7
        if zOn.get(i) and not p.dyn and top >= zB.get(i) - tol and bot <= zT.get(i) + tol
            p.dyn     := true
            p.dynIdx  := i
            p.dynName := zNm.get(i)
    bool show = kind == PK_FVG ? htfShowFvg : htfShowOb
    if show
        color c = dir > 0 ? htfBullCol : htfBearCol
        p.bx := box.new(math.max(tStart, firstBarTime), top, time, bot, xloc = xloc.bar_time, extend = extend.right, border_color = color.new(c, 20), border_width = tf == "1H" ? 1 : 2, border_style = kind == PK_FVG ? line.style_dashed : line.style_solid, bgcolor = color.new(c, vrPoiFill), text = "", text_size = vrSize(vrLblSize), text_color = color.new(vrTextCol, vrTxtTr), text_halign = text.align_left, text_valign = text.align_top)
        p.poiStyle()
    pois.push(p)
    p
 
// Mirror one timeframe's exported live list (called on each new closed HTF candle).
poiSync(string tf, array<float> v) =>
    int n = pois.size()
    array<bool> seen = array.new<bool>(math.max(n, 1), false)
    for q = 0 to 7
        float code = v.get(q * 4 + 3)
        if not na(code) and code != 0
            float top  = v.get(q * 4)
            float bot  = v.get(q * 4 + 1)
            int   ts   = int(v.get(q * 4 + 2))
            int   c    = int(math.abs(code)) - 1
            int   dir  = code > 0 ? 1 : -1
            int   kind = c % 2
            int   st   = int(math.floor(c / 2.0)) % 2
            bool  wide = int(math.floor(c / 4.0)) % 2 == 1
            int   found = -1
            if n > 0
                for i = 0 to n - 1
                    Poi e = pois.get(i)
                    if e.tf == tf and e.kind == kind and e.dir == dir and e.tStart == ts
                        found := i
                        break
            if found >= 0
                seen.set(found, true)
                Poi e = pois.get(found)
                if e.state < st
                    e.state := st
                    e.poiStyle()
            else
                poiCreate(tf, kind, dir, top, bot, ts, st, wide)
                poiMade.set(kind, poiMade.get(kind) + 1)
    // drop this timeframe's POIs that the HTF list no longer carries (mitigated / invalid / stale / capped)
    if n > 0
        for i = n - 1 to 0
            if pois.get(i).tf == tf and not seen.get(i) and not pois.get(i).armed
                pois.poiDrop(i)
    pois.size()
 
htfCloseFor(string tf) =>
    tf == "1H" ? h1C : tf == "4H" ? h4C : hDC
 
htfNewFor(string tf) =>
    tf == "1H" ? h1New : tf == "4H" ? h4New : hDNew
 
// 1m-level lifecycle on CONFIRMED chart bars (between HTF closes):
//   ACTIVE -> TOUCHED (1m range enters the POI) -> MITIGATED (FVG traded to far edge / OB to 50%)
//   -> INVALIDATED (a candle of the POI's own timeframe CLOSES beyond the far edge -> removed).
//   Mitigated POIs stay in the list (hidden unless "Keep MITIGATED") until the HTF list drops them,
//   but can no longer arm a new setup.
poiUpdate() =>
    for f = 0 to 3
        poiTouch.set(f, false)
    int n = pois.size()
    if n > 0
        for i = n - 1 to 0
            Poi p = pois.get(i)
            p.statePrev := p.state
            if time > p.tConfirm and not poiIsLtf(p.tf)
                if high >= p.bot and low <= p.top
                    poiTouch.set(p.dir < 0 ? 0 : 1, true)
                    if p.dyn
                        poiTouch.set(p.dir < 0 ? 2 : 3, true)
                int old = p.state
                bool bear = p.dir < 0
                float near = bear ? p.bot : p.top
                float deep = p.kind == PK_FVG ? (bear ? p.top : p.bot) : p.mid
                if (bear ? high >= near : low <= near) and p.state < PS_TOUCHED
                    p.state := PS_TOUCHED
                if (bear ? high >= deep : low <= deep) and p.state < PS_MITIG
                    p.state := PS_MITIG
                if htfNewFor(p.tf) and (bear ? htfCloseFor(p.tf) > p.top : htfCloseFor(p.tf) < p.bot)
                    p.state := PS_INVALID
                if p.state == PS_INVALID
                    pois.poiDrop(i)
                else if p.state != old
                    p.poiStyle()
    pois.size()
 
// Display focus: the POI price is in (highest timeframe wins), else the nearest one.
poiFocus() =>
    int best = -1
    float bestD = na
    int n = pois.size()
    if n > 0
        for i = 0 to n - 1
            Poi p = pois.get(i)
            if p.state <= PS_TOUCHED
                float d = close > p.top ? close - p.top : close < p.bot ? p.bot - close : 0.0
                float score = d - tfRank(p.tf) * 0.001
                if na(bestD) or score < bestD
                    bestD := score
                    best  := i
    best
 
poiFind(string tf, int kind, int dir, int tStart) =>
    int r = -1
    int n = pois.size()
    if n > 0
        for i = 0 to n - 1
            Poi p = pois.get(i)
            if p.tf == tf and p.kind == kind and p.dir == dir and p.tStart == tStart
                r := i
                break
    r
 
// POI mirror + lifecycle (confirmed chart bars only). 1m lifecycle runs first, so a POI is
// never touched by the bar that delivered it.
if barstate.isconfirmed and htfOn
    poiUpdate()
    if h1New and not h1Ltf
        poiSync("1H", array.from(h1x0, h1x1, h1x2, h1x3, h1x4, h1x5, h1x6, h1x7, h1x8, h1x9, h1x10, h1x11, h1x12, h1x13, h1x14, h1x15, h1x16, h1x17, h1x18, h1x19, h1x20, h1x21, h1x22, h1x23, h1x24, h1x25, h1x26, h1x27, h1x28, h1x29, h1x30, h1x31))
    if h4New and not h4Ltf
        poiSync("4H", array.from(h4x0, h4x1, h4x2, h4x3, h4x4, h4x5, h4x6, h4x7, h4x8, h4x9, h4x10, h4x11, h4x12, h4x13, h4x14, h4x15, h4x16, h4x17, h4x18, h4x19, h4x20, h4x21, h4x22, h4x23, h4x24, h4x25, h4x26, h4x27, h4x28, h4x29, h4x30, h4x31))
    if false   // [A] 1D layer not included
        na
 
// =====================================================================================
// MTF SYNC v1.4-dev - rebuild of POI timeframes that are LOWER than the chart timeframe
// -------------------------------------------------------------------------------------
// request.security() to a lower timeframe returns ONE value per chart bar (with lookahead_on: the first
// intrabar), i.e. the POI list as it was when the chart bar OPENED. On a weekly chart that hid every
// 1H/4H creation, mitigation and invalidation of the week (the 2026-11-15 stale-zone finding).
// request.security_lower_tf() returns the list after EVERY intrabar; we take the newest intrabar whose
// candle has CLOSED (time_close <= timenow), so a forming 1H/4H candle never creates, touches or removes
// a POI (non-repainting). Same htfPoiPack engine and lifecycle as the 1m chart -> same boundaries/states.
// Runs on every chart bar incl. the realtime one, so a weekly chart is current to the last closed 4H.
// Historical limit: TradingView caps intrabars per request (see MTF_SYNC_README.md); chart bars older
// than the cap get empty arrays and simply keep the previous list.
// =====================================================================================
htfPoiPackLtf() =>
    [t, c, a, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, x31] = htfPoiPack(0)
    [t, time_close, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, x31]
 
// newest intrabar whose candle has closed (-1 = none closed yet inside this chart bar)
mtfPick(array<int> tc) =>
    int k = tc.size() - 1
    while k >= 0 and tc.get(k) > timenow
        k -= 1
    k
 
var int h1LtfAsOf = na   // open time of the source candle the rebuilt list is current to (debug)
var int h4LtfAsOf = na
var int hDLtfAsOf = na
if h1Ltf
    [lt, ltc, l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24, l25, l26, l27, l28, l29, l30, l31] = request.security_lower_tf(syminfo.tickerid, "60", htfPoiPackLtf())
    int k = mtfPick(ltc)
    if k >= 0
        poiSync("1H", array.from(l0.get(k), l1.get(k), l2.get(k), l3.get(k), l4.get(k), l5.get(k), l6.get(k), l7.get(k), l8.get(k), l9.get(k), l10.get(k), l11.get(k), l12.get(k), l13.get(k), l14.get(k), l15.get(k), l16.get(k), l17.get(k), l18.get(k), l19.get(k), l20.get(k), l21.get(k), l22.get(k), l23.get(k), l24.get(k), l25.get(k), l26.get(k), l27.get(k), l28.get(k), l29.get(k), l30.get(k), l31.get(k)))
        h1LtfAsOf := lt.get(k)
if h4Ltf
    [lt, ltc, l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24, l25, l26, l27, l28, l29, l30, l31] = request.security_lower_tf(syminfo.tickerid, "240", htfPoiPackLtf())
    int k = mtfPick(ltc)
    if k >= 0
        poiSync("4H", array.from(l0.get(k), l1.get(k), l2.get(k), l3.get(k), l4.get(k), l5.get(k), l6.get(k), l7.get(k), l8.get(k), l9.get(k), l10.get(k), l11.get(k), l12.get(k), l13.get(k), l14.get(k), l15.get(k), l16.get(k), l17.get(k), l18.get(k), l19.get(k), l20.get(k), l21.get(k), l22.get(k), l23.get(k), l24.get(k), l25.get(k), l26.get(k), l27.get(k), l28.get(k), l29.get(k), l30.get(k), l31.get(k)))
        h4LtfAsOf := lt.get(k)
// (MASTER: [A]'s 1D lower-timeframe rebuild not included; the layer is off)
plot(h4Ltf ? h4LtfAsOf : h1Ltf ? h1LtfAsOf : na, "dbg MTF LTF POI list as-of (4H, else 1H source candle open time)", display = display.data_window, editable = false)
 
// Diagnostics (Data Window only; two values packed per plot to stay under the 64-plot limit)
int poiDynLive = 0
if barstate.islast or barstate.isconfirmed
    for p in pois
        if p.dyn and p.state <= PS_TOUCHED
            poiDynLive += 1
int poiLive = 0
for p in pois
    if p.state <= PS_TOUCHED
        poiLive += 1
plot(poiMade.get(0) * 1000 + poiMade.get(1), "dbg HTF POIs loaded cum (FVG×1000 + OB)", display = display.data_window, editable = false)
plot(poiLive * 1000 + poiDynLive, "dbg HTF live (count×1000 + overlapping Dynamite)", display = display.data_window, editable = false)
plot(barstate.isconfirmed and htfOn ? (poiTouch.get(0) ? 1 : 0) + (poiTouch.get(1) ? 2 : 0) + (poiTouch.get(2) ? 4 : 0) + (poiTouch.get(3) ? 8 : 0) : na, "dbg 1m bar touches live HTF POI (1 bear, 2 bull, +4 bear∩Dyn, +8 bull∩Dyn)", display = display.data_window, editable = false)
 
// =====================================================================================
// ZONE LABELS (last bar only; fixed pool, re-positioned not re-created)
// INTRABAR: status text follows the live price; it is display-only.
// =====================================================================================
if barstate.islast and showZoneLabels and mLblMode == M_LBL_BOX and mShowDyn
    for i = 0 to 7
        label lb = zLbls.get(i)
        if not na(lb)
            // Text-only label sitting just above the zone top, ending at the anchor and
            // extending left. If live price sits in that band, flip it under the zone.
            float t = zT.get(i)
            bool  priceInBand = close >= t and close <= t + labelClearTk * tick
            label.set_xy(lb, bar_index + labelOffset, priceInBand ? zB.get(i) : t)
            label.set_style(lb, priceInBand ? label.style_label_upper_right : label.style_label_lower_right)
            label.set_text(lb, zNm.get(i) + " [" + roleTag(zRl.get(i)) + "]  " + fmtP(zB.get(i)) + " – " + fmtP(zT.get(i)) + "  ·  " + zoneStatus(i))
 
// =====================================================================================
// 17 · 15M FAIR VALUE GAPS (DISPLAY ONLY)
// Informational areas for discretionary confirmation. Nothing in this section is read by
// the setup engine, HTF POI arming, entries, DXY context, alerts, journal or trade
// management, and nothing here calls alert() / alertcondition().
// Repaint policy: the 15M candles come from request.security() with [1] + lookahead_on,
// i.e. only CLOSED 15M candles are used (the standard non-leaking pattern). Creation,
// touch, partial fill, mitigation and invalidation are evaluated on CONFIRMED 1m bars
// only. Boxes are only (re)drawn on the latest bar, from a capped pool.
//   Bullish 15M FVG : low(newest closed 15M) > high(two candles earlier)
//   Bearish 15M FVG : high(newest closed 15M) < low(two candles earlier)
//   TOUCHED   : a 1m wick entered the gap (< 50 % filled)
//   PARTIAL   : the gap is >= 50 % filled (consequent encroachment reached)
//   MITIGATED : the gap is 100 % filled by wicks, but no 15M candle has closed through it
//   INVALID   : a 15M candle CLOSED beyond the far edge of the gap
// =====================================================================================
const string G_F15 = "17 · 15M FVG (display only, informational)"
f15On      = input.bool(true, "Show 15M FVGs (1m-5m charts)", group = G_F15, tooltip = "Display only. 15M FVGs are informational context; they never generate a signal or an alert.")
f15Bulls   = input.bool(true, "Bullish", inline = "f15d", group = G_F15)
f15Bears   = input.bool(true, "Bearish", inline = "f15d", group = G_F15)
f15MinTk   = input.int(2, "Minimum gap size (ticks)", minval = 0, group = G_F15)
f15Max     = input.int(6, "Maximum active 15M FVGs on chart", minval = 1, maxval = 20, group = G_F15, tooltip = "Oldest FVGs beyond this count are removed (object pool, keeps drawings light).")
f15MaxAge  = input.int(96, "Remove 15M FVGs older than (15M candles)", minval = 4, maxval = 500, group = G_F15, tooltip = "96 = 24 hours.")
f15KeepMit = input.bool(true, "Keep MITIGATED FVGs (fully filled, not closed through)", group = G_F15)
f15KeepInv = input.bool(false, "Keep INVALIDATED FVGs for 1 hour (faded)", group = G_F15)
f15BullCol = input.color(#00e676, "Bull colour", inline = "f15c", group = G_F15)
f15BearCol = input.color(#ff1744, "Bear colour", inline = "f15c", group = G_F15)
f15FillTr  = input.int(84, "Shading transparency", minval = 50, maxval = 98, group = G_F15, tooltip = "Touched / partial / mitigated FVGs are drawn progressively lighter from this value.")
f15BordTr  = input.int(10, "Border transparency", minval = 0, maxval = 90, group = G_F15)
f15Lbl     = input.bool(true, "Show 15M FVG labels", group = G_F15)
f15LblSz   = input.string("Tiny", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = G_F15)
f15LblTxt  = input.string("Short", "Label text", options = ["Full", "Short"], group = G_F15, tooltip = "Full: 15M BULL FVG · PARTIAL 62%. Short: 15M ▲ PARTIAL 62%.")
f15LblGap  = input.int(15, "Merge labels closer than (ticks)", minval = 0, group = G_F15, tooltip = "When two 15M FVGs sit closer than this, only the newer one is labelled, so labels never overlap.")
 
const int F15_ACT = 0
const int F15_TCH = 1
const int F15_PRT = 2
const int F15_MIT = 3
const int F15_INV = 4
 
type F15Gap
    int   dir
    float top
    float bot
    int   tLeft
    int   tBorn
    int   st   = 0
    float fill = 0.0
    int   tEnd
    box   bx
 
var array<F15Gap> f15 = array.new<F15Gap>()
 
// Last CLOSED 15M candle (c1) and the two before it (c2 middle, c3 oldest). Non-repainting.
[f15T2, f15H3, f15L3, f15H1, f15L1, f15C1, f15T1] = request.security(syminfo.tickerid, "15", [time[2], high[3], low[3], high[1], low[1], close[1], time[1]], lookahead = barmerge.lookahead_on)
 
bool f15Tf = timeframe.in_seconds() < 900
var int f15LastT = na
 
f15StTxt(F15Gap g) =>
    g.st == F15_ACT ? "ACTIVE" : g.st == F15_TCH ? "TOUCHED" : g.st == F15_PRT ? "PARTIAL" : g.st == F15_MIT ? "MITIGATED" : "INVALID"
 
f15Txt(F15Gap g) =>
    string pct = g.st == F15_TCH or g.st == F15_PRT ? " " + str.tostring(math.round(g.fill)) + "%" : ""
    f15LblTxt == "Full" ? "15M " + (g.dir > 0 ? "BULL" : "BEAR") + " FVG · " + f15StTxt(g) + pct : "15M " + (g.dir > 0 ? "▲ " : "▼ ") + (g.st == F15_ACT ? "FVG" : f15StTxt(g)) + pct
 
f15Tr(F15Gap g) =>
    g.st == F15_ACT ? f15FillTr : g.st == F15_TCH ? math.min(f15FillTr + 3, 98) : g.st == F15_PRT ? math.min(f15FillTr + 6, 98) : g.st == F15_MIT ? math.min(f15FillTr + 9, 98) : 96
 
if barstate.isconfirmed and f15On and f15Tf
    int  nowT  = time
    bool new15 = not na(f15T1) and (na(f15LastT) or f15T1 != f15LastT)
    // 1) creation from the newly closed 15M candle
    if new15
        f15LastT := f15T1
        float minGap = f15MinTk * tick
        if f15Bulls and not na(f15H3) and f15L1 > f15H3 and f15L1 - f15H3 >= minGap
            f15.push(F15Gap.new(1, f15L1, f15H3, f15T2, f15T1))
        if f15Bears and not na(f15L3) and f15H1 < f15L3 and f15L3 - f15H1 >= minGap
            f15.push(F15Gap.new(-1, f15L3, f15H1, f15T2, f15T1))
    // 2) lifecycle on this closed 1m bar
    if f15.size() > 0
        for i = f15.size() - 1 to 0
            F15Gap g = f15.get(i)
            if g.st != F15_INV
                float h   = math.max(g.top - g.bot, tick)
                float pen = g.dir > 0 ? g.top - low : high - g.bot
                if pen > 0
                    g.fill := math.max(g.fill, math.min(100.0, pen / h * 100.0))
                if new15 and f15T1 > g.tBorn and (g.dir > 0 ? f15C1 < g.bot : f15C1 > g.top)
                    g.st   := F15_INV
                    g.tEnd := nowT
                else
                    g.st := g.fill >= 100.0 ? F15_MIT : g.fill >= 50.0 ? F15_PRT : g.fill > 0 ? F15_TCH : F15_ACT
    // 3) cleanup / object pool: age, finished FVGs, max active count (oldest first)
    if f15.size() > 0
        for i = f15.size() - 1 to 0
            F15Gap g = f15.get(i)
            bool drop = nowT - g.tBorn > f15MaxAge * 900000 or (g.st == F15_INV and (not f15KeepInv or nowT - g.tEnd > 3600000)) or (g.st == F15_MIT and not f15KeepMit)
            if drop
                box.delete(g.bx)
                f15.remove(i)
    int live = 0
    for g in f15
        live += g.st != F15_INV ? 1 : 0
    while live > f15Max
        for i = 0 to f15.size() - 1
            if f15.get(i).st != F15_INV
                box.delete(f15.get(i).bx)
                f15.remove(i)
                break
        live -= 1
 
// Draw / refresh only on the latest bar (no per-bar drawing churn on history).
if f15On and f15Tf and barstate.islast
    array<float> lblMid = array.new<float>()
    if f15.size() > 0
        for i = f15.size() - 1 to 0
            F15Gap g = f15.get(i)
            color c   = g.dir > 0 ? f15BullCol : f15BearCol
            bool  inv = g.st == F15_INV
            float mid = (g.top + g.bot) / 2
            bool  near = false
            for m in lblMid
                if math.abs(m - mid) < f15LblGap * tick
                    near := true
            string t = f15Lbl and not near ? f15Txt(g) : ""
            if f15Lbl and not near
                lblMid.push(mid)
            if na(g.bx)
                g.bx := box.new(g.tLeft, g.top, time, g.bot, xloc = xloc.bar_time, text_halign = text.align_right, text_valign = text.align_center)
            box.set_lefttop(g.bx, g.tLeft, g.top)
            box.set_rightbottom(g.bx, inv ? g.tEnd : time, g.bot)
            box.set_extend(g.bx, inv ? extend.none : extend.right)
            box.set_border_color(g.bx, color.new(c, not mShow15 ? 100 : inv ? 70 : f15BordTr))
            box.set_border_style(g.bx, inv ? line.style_dotted : g.st == F15_MIT ? line.style_dashed : line.style_solid)
            box.set_border_width(g.bx, 1)
            box.set_bgcolor(g.bx, color.new(c, mShow15 ? f15Tr(g) : 100))
            box.set_text(g.bx, mLblMode == M_LBL_BOX and mShow15 ? t : "")
            box.set_text_color(g.bx, color.new(#ffffff, 0))
            box.set_text_size(g.bx, vrSize(f15LblSz))
 
 
// =====================================================================================
// [B] D/W/M POI TRACKER v2.0 (verbatim except renamed identifiers / display hooks) — INPUTS
// =====================================================================================
const string G_SRC = "B1 · D/W/M — sources"
const string G_DET = "B2 · D/W/M — detection"
const string G_LIF = "B3 · D/W/M — lifecycle"
const string G_DSP = "B4 · D/W/M — display"
const string PT_G_VIS = "B5 · D/W/M — colours & labels"
const string G_XTR = "B6 · D/W/M — optional extra levels (off by default)"
const string G_DSH = "B7 · (dashboard: see 0 · MASTER)"
const string G_ALR = "B8 · D/W/M — POI alerts"
const string G_DLY = "B3b · D/W/M — daily (1D) layer"
 
wOn      = input.bool(true, "Weekly (1W) POIs", inline = "src", group = G_SRC)
mOn      = input.bool(true, "Monthly (1M) POIs", inline = "src", group = G_SRC, tooltip = "1M here is the ONE-MONTH timeframe, not 1 minute.")
symIn    = input.symbol("", "POI data symbol (empty = chart symbol)", group = G_SRC, tooltip = "Empty = the chart's own contract (e.g. MGCZ2026). A single contract only has ~2 years of weekly / monthly history; a continuous symbol (e.g. COMEX_MINI:MGC1!) gives more monthly POIs but its prices can differ from the chart contract by the roll spread.")
 
ptFvgMinAtr  = input.float(0.10, "FVG minimum gap (× source ATR14)", minval = 0.0, step = 0.05, group = G_DET)
ptObDispAtr  = input.float(1.0, "OB: displacement body >= × source ATR14", minval = 0.1, step = 0.1, group = G_DET)
ptObPivLen   = input.int(3, "OB / swing: pivot length (source candles each side)", minval = 1, maxval = 10, group = G_DET)
obMaxClust = input.int(3, "OB: max opposing candles in the block", minval = 1, maxval = 5, group = G_DET)
wideAtr    = input.float(1.5, "Mark zone WIDE when height > × source ATR14", minval = 0.5, step = 0.1, group = G_DET)
 
fvgPrtPct = input.float(50.0, "FVG PARTIAL at fill %", minval = 1, maxval = 100, step = 5, inline = "fp", group = G_LIF)
fvgMitPct = input.float(100.0, "MITIGATED at %", minval = 1, maxval = 100, step = 5, inline = "fp", group = G_LIF, tooltip = "Fill % = deepest wick penetration from the near edge ÷ zone height. Default: FVG partial at 50 % (consequent encroachment), mitigated at 100 % (far edge reached).")
obPrtPct  = input.float(25.0, "OB PARTIAL at fill %", minval = 1, maxval = 100, step = 5, inline = "op", group = G_LIF)
obMitPct  = input.float(50.0, "MITIGATED at %", minval = 1, maxval = 100, step = 5, inline = "op", group = G_LIF, tooltip = "Default: OB partial at 25 %, mitigated at 50 % (mean threshold) - the Setup Assistant also mitigates OBs at 50 %.")
maxAgeW   = input.int(156, "Forget 1W POIs older than (weeks)", minval = 4, group = G_LIF)
maxAgeM   = input.int(60, "Forget 1M POIs older than (months)", minval = 3, group = G_LIF)
trackMax  = input.int(24, "Max POIs tracked per timeframe", minval = 4, maxval = 30, group = G_LIF, tooltip = "When the list is full the oldest INVALIDATED, then oldest MITIGATED, then oldest active POI is dropped, so distant unfilled targets survive longest.")
 
activeOnly = input.bool(false, "Display only ACTIVE / TOUCHED / PARTIAL POIs", group = G_DSP)
showMit    = input.bool(true, "Show MITIGATED POIs (gray)", group = G_DSP)
showInv    = input.bool(false, "Retain INVALIDATED POIs for research (faded, dotted)", group = G_DSP)
invKeep    = input.int(26, "…keep invalidated POIs for (source candles)", minval = 1, group = G_DSP)
maxShowW   = input.int(6, "Max displayed 1W POIs", minval = 1, maxval = 24, group = G_DSP, tooltip = "Nearest to price first. Each timeframe has its own cap, so weekly zones never push distant monthly targets off the chart.")
maxShowM   = input.int(4, "Max displayed 1M POIs", minval = 1, maxval = 24, group = G_DSP)
showLive   = input.bool(true, "Show live (unconfirmed) interaction", group = G_DSP, tooltip = "Charts below the source timeframe only: deepest penetration by CONFIRMED chart candles since the last closed source candle. Informational - the confirmed state only changes when a 1W / 1M candle closes.")
 
bullCol   = input.color(#00c853, "Bullish", inline = "c", group = PT_G_VIS)
bearCol   = input.color(#ff1744, "Bearish", inline = "c", group = PT_G_VIS)
mitCol    = input.color(#787b86, "Mitigated", inline = "c", group = PT_G_VIS)
fillTr    = input.int(85, "Shading transparency (active)", minval = 50, maxval = 98, group = PT_G_VIS)
txtCol    = input.color(#ffffff, "Label text colour", group = PT_G_VIS)
lblOn     = input.bool(true, "Show zone labels", group = PT_G_VIS)
lblSize   = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = PT_G_VIS)
lblStyle  = input.string("Full", "Label wording", options = ["Full", "Short"], group = PT_G_VIS, tooltip = "Full: 1W BULL FVG · PARTIAL 62%. Short: 1W ▲ FVG · P 62%.")
lblHal    = input.string("Right", "Label position (Inside box mode)", options = ["Left", "Center", "Right"], inline = "lp", group = PT_G_VIS)
lblVal    = input.string("Center", "", options = ["Top", "Center", "Bottom"], inline = "lp", group = PT_G_VIS)
lblGapTk  = input.int(40, "Hide a label when another sits closer than (ticks)", minval = 0, group = PT_G_VIS, tooltip = "Monthly labels win over weekly, nearer zones over farther ones. The zone itself is still drawn.")
wBorderW  = input.int(2, "1W border width", minval = 1, maxval = 4, inline = "bw", group = PT_G_VIS)
mBorderW  = input.int(3, "1M border width", minval = 1, maxval = 4, inline = "bw", group = PT_G_VIS, tooltip = "Default 1D thin (1), 1W medium (2), 1M thick (3). FVG borders are dashed, OB borders solid, invalidated zones dotted.")
 
xSwing  = input.bool(false, "Swing highs / lows", group = G_XTR)
xLiq    = input.bool(false, "Liquidity pools (unswept swing extremes)", group = G_XTR)
xPrev   = input.bool(false, "Previous day / week / month high & low", group = G_XTR)
xMax    = input.int(4, "Max swing / liquidity levels per timeframe", minval = 1, maxval = 8, group = G_XTR)
 
 
alOn      = input.bool(true, "Enable alerts", group = G_ALR, tooltip = "Create ONE alert with condition 'Any alert() function call'. Every message names the timeframe and POI type. Each event fires once (re-armed only after price moves away), never on every candle inside a zone.")
alAppr    = input.bool(true, "Approaching POI", inline = "a1", group = G_ALR)
alEnter   = input.bool(true, "Entering POI", inline = "a1", group = G_ALR)
alMit     = input.bool(true, "Mitigation", inline = "a2", group = G_ALR)
alInv     = input.bool(true, "Confirmed invalidation", inline = "a2", group = G_ALR)
alOvl     = input.bool(true, "Confluence (1W/1M and 1D/HTF overlap)", group = G_ALR)
apprAtr   = input.float(0.10, "Approach distance (× source ATR14)", minval = 0.01, step = 0.01, group = G_ALR, tooltip = "1W ATR14 on MGC is ~200 pts, so 0.10 ≈ 20 pts for weekly POIs and proportionally more for monthly POIs.")
 
// ---- inputs added after v1 (declared last so v1 chart settings keep their input positions) ----
dOn      = input.bool(true, "Daily (1D) POIs", inline = "src", group = G_SRC)
selHyst    = input.float(0.10, "Zone selection hysteresis (× source ATR14)", minval = 0.0, step = 0.01, group = G_DSP, tooltip = "Display only. A zone already on the chart keeps its slot until another zone is closer by more than this distance, so two similar-distance zones do not swap back and forth. The nearest live bullish and bearish zone of each timeframe are always shown.")
dFvg      = input.bool(true, "1D FVGs", inline = "dk", group = G_DLY)
dOb       = input.bool(true, "1D order blocks", inline = "dk", group = G_DLY, tooltip = "Daily-layer visibility only (chart, dashboard, alerts). Detection uses the same rules as 1W / 1M.")
maxShowD  = input.int(6, "Max displayed 1D POIs", minval = 1, maxval = 24, group = G_DLY, tooltip = "Own cap: daily zones can never push weekly or monthly zones off the chart.")
maxAgeD   = input.int(120, "Forget 1D POIs older than (days)", minval = 5, group = G_DLY)
dShowMit  = input.bool(true, "Show MITIGATED 1D POIs (gray)", group = G_DLY)
dShowInv  = input.bool(false, "Retain INVALIDATED 1D POIs (faded, dotted)", group = G_DLY)
dLtfPre   = input.string("All", "1D POIs on 1m-5m charts", options = ["All", "Nearest 3 live only"], group = G_DLY, tooltip = "Optional execution-chart preset: on 1m-5m charts show only the 3 nearest ACTIVE / TOUCHED / PARTIAL daily zones. Other charts are not affected.")
dBorderW  = input.int(1, "1D border width", minval = 1, maxval = 4, group = PT_G_VIS, tooltip = "1D thin (1), 1W medium (2), 1M thick (3) by default.")
alDaily   = input.bool(true, "Include 1D POIs in approach / enter alerts", group = G_ALR)
 
// =====================================================================================
// CONSTANTS / HELPERS
// =====================================================================================
const int ST_ACT = 0
const int ST_TCH = 1
const int ST_PRT = 2
const int ST_MIT = 3
const int ST_INV = 4
const int K_FVG = 0
const int K_OB  = 1
 
string poiSym = symIn == "" ? syminfo.tickerid : symIn
float  ptTick   = syminfo.mintick
 
szOf(string s) =>
    s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : size.large
 
posOf(string s) =>
    s == "Top Right" ? position.top_right : s == "Middle Right" ? position.middle_right : s == "Bottom Right" ? position.bottom_right : s == "Top Left" ? position.top_left : position.bottom_left
 
ptFmtP(float p) =>
    str.tostring(p, format.mintick)
 
numS(float v) =>
    na(v) ? "" : str.tostring(v, "#.######")
 
intS(int v) =>
    na(v) ? "" : str.tostring(v)
 
stTxt(int st) =>
    st == ST_ACT ? "ACTIVE" : st == ST_TCH ? "TOUCHED" : st == ST_PRT ? "PARTIAL" : st == ST_MIT ? "MITIGATED" : "INVALIDATED"
 
stShort(int st) =>
    st == ST_ACT ? "A" : st == ST_TCH ? "T" : st == ST_PRT ? "P" : st == ST_MIT ? "M" : "X"
 
stateFrom(float f, int kind) =>
    f >= (kind == K_FVG ? fvgMitPct : obMitPct) ? ST_MIT : f >= (kind == K_FVG ? fvgPrtPct : obPrtPct) ? ST_PRT : f > 0 ? ST_TCH : ST_ACT
 
// =====================================================================================
// SOURCE-TIMEFRAME ENGINE  (runs INSIDE the 1W / 1M context, one call per closed source candle)
// Returns the complete POI list as one record string:
//   header  : asOfTime|asOfClose|ATR|lastBOSdir|lastBOStime|high|low
//   #pois   : dir,kind,state,top,bottom,originTime,bornTime,fill%,endTime,wide ; …   (newest first)
//   #swings : dir,price,time,sweptTime ; …                                            (newest first)
// =====================================================================================
wmRemove(array<float> aT, array<float> aB, array<int> aTS, array<int> aTB, array<int> aD, array<int> aK, array<int> aSt, array<float> aF, array<int> aE, array<bool> aW, array<int> aBi, array<int> aEi, int i) =>
    aT.remove(i)
    aB.remove(i)
    aTS.remove(i)
    aTB.remove(i)
    aD.remove(i)
    aK.remove(i)
    aSt.remove(i)
    aF.remove(i)
    aE.remove(i)
    aW.remove(i)
    aBi.remove(i)
    aEi.remove(i)
    aT.size()
 
wmEngine(int maxAge, bool keepInv) =>
    float a = ta.atr(14)
    var array<float> aT  = array.new<float>()
    var array<float> aB  = array.new<float>()
    var array<int>   aTS = array.new<int>()
    var array<int>   aTB = array.new<int>()
    var array<int>   aD  = array.new<int>()
    var array<int>   aK  = array.new<int>()
    var array<int>   aSt = array.new<int>()
    var array<float> aF  = array.new<float>()
    var array<int>   aE  = array.new<int>()
    var array<bool>  aW  = array.new<bool>()
    var array<int>   aBi = array.new<int>()   // bar_index born
    var array<int>   aEi = array.new<int>()   // bar_index invalidated
    // ---- 1) lifecycle of existing POIs on this CLOSED candle (before any new POI is added) ----
    int n0 = aT.size()
    if n0 > 0
        for i = 0 to n0 - 1
            int st = aSt.get(i)
            if st != ST_INV
                float t    = aT.get(i)
                float b    = aB.get(i)
                bool  bull = aD.get(i) > 0
                float h    = math.max(t - b, syminfo.mintick)
                float pen  = bull ? t - low : high - b
                if pen > 0
                    aF.set(i, math.max(aF.get(i), math.min(100.0, pen / h * 100.0)))
                if bull ? close < b : close > t
                    aSt.set(i, ST_INV)
                    aE.set(i, time)
                    aEi.set(i, bar_index)
                else
                    int ns = stateFrom(aF.get(i), aK.get(i))
                    if ns == ST_MIT and st != ST_MIT
                        aE.set(i, time)
                    aSt.set(i, math.max(st, ns))
    // ---- 2) new 3-candle FVG completed by this candle ----
    float bullGap = low - high[2]
    float bearGap = low[2] - high
    if not na(a) and bullGap > 0 and bullGap >= a * ptFvgMinAtr
        aT.push(low), aB.push(high[2]), aTS.push(time[2]), aTB.push(time), aD.push(1), aK.push(K_FVG), aSt.push(ST_ACT), aF.push(0.0), aE.push(na), aW.push(bullGap > wideAtr * a), aBi.push(bar_index), aEi.push(na)
    if not na(a) and bearGap > 0 and bearGap >= a * ptFvgMinAtr
        aT.push(low[2]), aB.push(high), aTS.push(time[2]), aTB.push(time), aD.push(-1), aK.push(K_FVG), aSt.push(ST_ACT), aF.push(0.0), aE.push(na), aW.push(bearGap > wideAtr * a), aBi.push(bar_index), aEi.push(na)
    // ---- 3) conservative order block: swing pivot broken by a CLOSE + displacement ----
    float pl = ta.pivotlow(low, ptObPivLen, ptObPivLen)
    float ph = ta.pivothigh(high, ptObPivLen, ptObPivLen)
    var float swL = na
    var float swH = na
    var bool  swLUsed = true
    var bool  swHUsed = true
    var int   bosDir = 0
    var int   bosT   = na
    if not na(pl)
        swL := pl
        swLUsed := false
    if not na(ph)
        swH := ph
        swHUsed := false
    bool bosDn = not swLUsed and close < swL
    bool bosUp = not swHUsed and close > swH
    if bosDn
        swLUsed := true
        bosDir  := -1
        bosT    := time
    if bosUp
        swHUsed := true
        bosDir  := 1
        bosT    := time
    bool dDn = false
    bool dUp = false
    for i = 0 to 2
        float bd = open[i] - close[i]
        if not na(a[i]) and bd >= a[i] * ptObDispAtr
            dDn := true
        if not na(a[i]) and -bd >= a[i] * ptObDispAtr
            dUp := true
    if bosDn and dDn
        int k = -1
        for i = 0 to 8
            if close[i] > open[i]
                k := i
                break
        if k >= 0
            float t  = high[k]
            float b  = open[k]
            int   tt = time[k]
            int   n  = 1
            int   j  = k + 1
            while n < obMaxClust and close[j] > open[j]
                t  := math.max(t, high[j])
                b  := math.min(b, open[j])
                tt := time[j]
                n  += 1
                j  += 1
            if t > b
                aT.push(t), aB.push(b), aTS.push(tt), aTB.push(time), aD.push(-1), aK.push(K_OB), aSt.push(ST_ACT), aF.push(0.0), aE.push(na), aW.push((t - b) > wideAtr * a), aBi.push(bar_index), aEi.push(na)
    if bosUp and dUp
        int k = -1
        for i = 0 to 8
            if close[i] < open[i]
                k := i
                break
        if k >= 0
            float t  = open[k]
            float b  = low[k]
            int   tt = time[k]
            int   n  = 1
            int   j  = k + 1
            while n < obMaxClust and close[j] < open[j]
                t  := math.max(t, open[j])
                b  := math.min(b, low[j])
                tt := time[j]
                n  += 1
                j  += 1
            if t > b
                aT.push(t), aB.push(b), aTS.push(tt), aTB.push(time), aD.push(1), aK.push(K_OB), aSt.push(ST_ACT), aF.push(0.0), aE.push(na), aW.push((t - b) > wideAtr * a), aBi.push(bar_index), aEi.push(na)
    // ---- 4) retire: age (source candles), invalidated retention, list cap (invalid -> mitigated -> active) ----
    int n1 = aT.size()
    if n1 > 0
        for i = n1 - 1 to 0
            bool old = bar_index - aBi.get(i) > maxAge
            bool gone = aSt.get(i) == ST_INV and (not keepInv or bar_index - aEi.get(i) > invKeep)
            if old or gone
                wmRemove(aT, aB, aTS, aTB, aD, aK, aSt, aF, aE, aW, aBi, aEi, i)
    while aT.size() > trackMax
        int victim = -1
        for pass = 0 to 2
            if victim < 0
                for i = 0 to aT.size() - 1
                    int s = aSt.get(i)
                    if (pass == 0 and s == ST_INV) or (pass == 1 and s == ST_MIT) or pass == 2
                        victim := i
                        break
        wmRemove(aT, aB, aTS, aTB, aD, aK, aSt, aF, aE, aW, aBi, aEi, victim)
    // ---- 5) swing extremes (for the optional swing / liquidity layers) ----
    var array<int>   sD  = array.new<int>()
    var array<float> sP  = array.new<float>()
    var array<int>   sT  = array.new<int>()
    var array<int>   sSw = array.new<int>()
    int ns0 = sD.size()
    if ns0 > 0
        for i = 0 to ns0 - 1
            if na(sSw.get(i)) and (sD.get(i) > 0 ? high > sP.get(i) : low < sP.get(i))
                sSw.set(i, time)
    if not na(ph)
        sD.push(1), sP.push(ph), sT.push(time[ptObPivLen]), sSw.push(na)
    if not na(pl)
        sD.push(-1), sP.push(pl), sT.push(time[ptObPivLen]), sSw.push(na)
    while sD.size() > 16
        sD.shift(), sP.shift(), sT.shift(), sSw.shift()
    // ---- 6) export (newest first) ----
    string out = intS(time) + "|" + intS(time_close) + "|" + numS(a) + "|" + str.tostring(bosDir) + "|" + intS(bosT) + "|" + numS(high) + "|" + numS(low) + "#"
    int n2 = aT.size()
    if n2 > 0
        for i = n2 - 1 to 0
            out += str.tostring(aD.get(i)) + "," + str.tostring(aK.get(i)) + "," + str.tostring(aSt.get(i)) + "," + numS(aT.get(i)) + "," + numS(aB.get(i)) + "," + intS(aTS.get(i)) + "," + intS(aTB.get(i)) + "," + str.tostring(aF.get(i), "#.#") + "," + intS(aE.get(i)) + "," + (aW.get(i) ? "1" : "0") + (i > 0 ? ";" : "")
    out += "#"
    int n3 = sD.size()
    if n3 > 0
        for i = n3 - 1 to 0
            out += str.tostring(sD.get(i)) + "," + numS(sP.get(i)) + "," + intS(sT.get(i)) + "," + intS(sSw.get(i)) + (i > 0 ? ";" : "")
    out
 
// request wrappers (each call site owns its own engine state)
wmPackHtf(int maxAge, bool keepInv) =>
    string s = wmEngine(maxAge, keepInv)
    [s[1], s, time_close]
 
wmPackLtf(int maxAge, bool keepInv) =>
    string s = wmEngine(maxAge, keepInv)
    [s, time_close]
 
// =====================================================================================
// DATA PATHS (see header: no future data, consistent on every chart timeframe)
// =====================================================================================
int  cSec = timeframe.in_seconds()
bool dLtf = cSec > timeframe.in_seconds("D")
bool wLtf = cSec > timeframe.in_seconds("W")
bool mLtf = cSec > timeframe.in_seconds("M")
int  barEnd = na(time_close) ? time : time_close
 
// newest record whose source candle has CLOSED by min(chart bar close, now)
ltfPick(array<string> ss, array<int> tc) =>
    string r = na
    int lim = math.min(barEnd, timenow)
    if not na(tc) and tc.size() > 0
        for i = tc.size() - 1 to 0
            if tc.get(i) <= lim
                r := ss.get(i)
                break
    r
 
var string dRec = na
var string wRec = na
var string mRec = na
if dOn
    if not dLtf
        [s1, s0, tc0] = request.security(poiSym, "D", wmPackHtf(maxAgeD, dShowInv), lookahead = barmerge.lookahead_on)
        string r = not na(tc0) and tc0 <= barEnd and tc0 <= timenow ? s0 : s1
        if not na(r)
            dRec := r
    else
        // weekly / monthly chart: rebuild the newest CLOSED daily state from the daily intrabars
        [ls, ltc] = request.security_lower_tf(poiSym, "D", wmPackLtf(maxAgeD, dShowInv))
        string r = ltfPick(ls, ltc)
        if not na(r)
            dRec := r
if wOn
    if not wLtf
        [s1, s0, tc0] = request.security(poiSym, "W", wmPackHtf(maxAgeW, showInv), lookahead = barmerge.lookahead_on)
        string r = not na(tc0) and tc0 <= barEnd and tc0 <= timenow ? s0 : s1
        if not na(r)
            wRec := r
    else
        [ls, ltc] = request.security_lower_tf(poiSym, "W", wmPackLtf(maxAgeW, showInv))
        string r = ltfPick(ls, ltc)
        if not na(r)
            wRec := r
if mOn
    if not mLtf
        [s1, s0, tc0] = request.security(poiSym, "M", wmPackHtf(maxAgeM, showInv), lookahead = barmerge.lookahead_on)
        string r = not na(tc0) and tc0 <= barEnd and tc0 <= timenow ? s0 : s1
        if not na(r)
            mRec := r
    else
        [ls, ltc] = request.security_lower_tf(poiSym, "M", wmPackLtf(maxAgeM, showInv))
        string r = ltfPick(ls, ltc)
        if not na(r)
            mRec := r
 
// =====================================================================================
// CHART-SIDE MIRROR (parsed only when the source record changes)
// =====================================================================================
type WPoi
    string tf
    int    dir
    int    kind
    int    st
    float  top
    float  bot
    int    tS
    int    tB
    float  fill
    int    tEnd
    bool   wide
    string key
    float  live     = 0.0
    bool   apprArm  = false
    bool   enterArm = false
    bool   inside   = false
 
type WHdr
    int   asOf
    int   asOfClose
    float atr
    int   bosDir
    int   bosT
    float hi
    float lo
 
type WSwing
    string tf
    int    dir
    float  px
    int    t
    int    swept
 
tonum(string s) =>
    s == "" ? na : str.tonumber(s)
 
toint(string s) =>
    s == "" ? int(na) : int(str.tonumber(s))
 
parseHdr(string rec) =>
    WHdr h = WHdr.new()
    if not na(rec)
        array<string> parts = str.split(rec, "#")
        array<string> f = str.split(parts.get(0), "|")
        if f.size() >= 7
            h.asOf      := toint(f.get(0))
            h.asOfClose := toint(f.get(1))
            h.atr       := tonum(f.get(2))
            h.bosDir    := toint(f.get(3))
            h.bosT      := toint(f.get(4))
            h.hi        := tonum(f.get(5))
            h.lo        := tonum(f.get(6))
    h
 
parsePois(string tf, string rec) =>
    array<WPoi> out = array.new<WPoi>()
    if not na(rec)
        array<string> parts = str.split(rec, "#")
        if parts.size() >= 2 and parts.get(1) != ""
            for item in str.split(parts.get(1), ";")
                array<string> f = str.split(item, ",")
                if f.size() >= 10
                    int d = toint(f.get(0))
                    int k = toint(f.get(1))
                    int ts = toint(f.get(5))
                    out.push(WPoi.new(tf, d, k, toint(f.get(2)), tonum(f.get(3)), tonum(f.get(4)), ts, toint(f.get(6)), tonum(f.get(7)), toint(f.get(8)), f.get(9) == "1", tf + "|" + str.tostring(d) + "|" + str.tostring(k) + "|" + str.tostring(ts)))
    out
 
parseSwings(string tf, string rec) =>
    array<WSwing> out = array.new<WSwing>()
    if not na(rec)
        array<string> parts = str.split(rec, "#")
        if parts.size() >= 3 and parts.get(2) != ""
            for item in str.split(parts.get(2), ";")
                array<string> f = str.split(item, ",")
                if f.size() >= 4
                    out.push(WSwing.new(tf, toint(f.get(0)), tonum(f.get(1)), toint(f.get(2)), toint(f.get(3))))
    out
 
var array<WPoi>   dP = array.new<WPoi>()
var array<WPoi>   wP = array.new<WPoi>()
var array<WPoi>   mP = array.new<WPoi>()
var array<WSwing> dS = array.new<WSwing>()
var array<WSwing> wS = array.new<WSwing>()
var array<WSwing> mS = array.new<WSwing>()
var WHdr dH = WHdr.new()
var WHdr wH = WHdr.new()
var WHdr mH = WHdr.new()
var string dParsed = na
var string wParsed = na
var string mParsed = na
 
// per-bar event flags (alerts)
var array<string> evMsg = array.new<string>()
bool evApprW = false
bool evApprM = false
bool evEnterW = false
bool evEnterM = false
bool evApprD = false
bool evEnterD = false
bool evMit = false
bool evInv = false
bool evOvl = false
 
ptPoiName(WPoi p) =>
    p.tf + " " + (p.dir > 0 ? "BULL" : "BEAR") + " " + (p.kind == K_FVG ? "FVG" : "OB") + (p.wide ? " (WIDE)" : "")
 
poiRange(WPoi p) =>
    ptFmtP(p.bot) + "–" + ptFmtP(p.top)
 
isLive(WPoi p) =>
    p.st <= ST_PRT
 
// daily-layer kind toggles (1W / 1M always visible by kind, as in v1.1)
kindVis(WPoi p) =>
    p.tf != "1D" or (p.kind == K_FVG ? dFvg : dOb)
 
findKey(array<WPoi> arr, string key) =>
    WPoi r = na
    for q in arr
        if q.key == key
            r := q
            break
    r
 
overlaps(WPoi a, WPoi b) =>
    a.top >= b.bot and a.bot <= b.top
 
// Re-sync one timeframe from a new source record: carry the per-POI alert/live memory over by key,
// raise confirmed MITIGATED / INVALIDATED / overlap events.
resync(array<WPoi> cur, string tf, string rec, array<WPoi> other) =>
    array<WPoi> nw = parsePois(tf, rec)
    float band = 0.0
    WHdr hh = parseHdr(rec)
    band := nz(hh.atr) * apprAtr
    for p in nw
        WPoi o = findKey(cur, p.key)
        if not na(o)
            p.apprArm  := o.apprArm
            p.enterArm := o.enterArm
            p.inside   := o.inside
            if o.st != ST_MIT and p.st == ST_MIT
                evMsg.push("DYNAMITE MGC " + tf + " POI MITIGATED (confirmed " + tf + " close): " + ptPoiName(p) + " " + poiRange(p))
            if o.st != ST_INV and p.st == ST_INV
                evMsg.push("DYNAMITE MGC " + tf + " POI INVALIDATED (confirmed " + tf + " close beyond far edge): " + ptPoiName(p) + " " + poiRange(p))
        else
            float d = close > p.top ? close - p.top : close < p.bot ? p.bot - close : 0.0
            p.apprArm  := d > band
            p.enterArm := d > 0
            if isLive(p)
                for q in other
                    if isLive(q) and overlaps(p, q)
                        evMsg.push("DYNAMITE MGC " + (tf == "1D" ? "1D/HTF" : "1W/1M") + " POI OVERLAP: new " + ptPoiName(p) + " " + poiRange(p) + " overlaps " + ptPoiName(q) + " " + poiRange(q))
                        break
        p.live := p.fill
    nw
 
int nMsg0 = 0
if wOn and not na(wRec) and (na(wParsed) or wRec != wParsed)
    nMsg0 := evMsg.size()
    wP := resync(wP, "1W", wRec, mP)
    wS := parseSwings("1W", wRec)
    wH := parseHdr(wRec)
    wParsed := wRec
if dOn and not na(dRec) and (na(dParsed) or dRec != dParsed)
    array<WPoi> htf = array.new<WPoi>()
    for q in wP
        htf.push(q)
    for q in mP
        htf.push(q)
    dP := resync(dP, "1D", dRec, htf)
    dS := parseSwings("1D", dRec)
    dH := parseHdr(dRec)
    dParsed := dRec
if mOn and not na(mRec) and (na(mParsed) or mRec != mParsed)
    mP := resync(mP, "1M", mRec, wP)
    mS := parseSwings("1M", mRec)
    mH := parseHdr(mRec)
    mParsed := mRec
 
// ---- live layer + approach / enter tracking on CONFIRMED chart candles ----
bool wLiveOk = showLive and cSec < timeframe.in_seconds("W")
bool mLiveOk = showLive and cSec < timeframe.in_seconds("M")
bool dLiveOk = showLive and cSec < timeframe.in_seconds("D")
 
track(array<WPoi> arr, WHdr hh, bool liveOk) =>
    float band = nz(hh.atr) * apprAtr
    bool ap = false
    bool en = false
    for p in arr
        if p.st != ST_INV
            // live (unconfirmed) penetration: only candles after the source candle the state is current to
            if liveOk and time >= nz(hh.asOfClose)
                float h = math.max(p.top - p.bot, ptTick)
                float pen = p.dir > 0 ? p.top - low : high - p.bot
                if pen > 0
                    p.live := math.max(p.live, math.min(100.0, pen / h * 100.0))
            float d = high < p.bot ? p.bot - high : low > p.top ? low - p.top : 0.0
            bool inNow = d == 0.0
            if isLive(p) and kindVis(p) and (p.tf != "1D" or alDaily)
                if inNow and p.enterArm
                    evMsg.push("DYNAMITE MGC: ENTERING " + ptPoiName(p) + " " + poiRange(p) + " · " + stTxt(p.st) + " @ " + ptFmtP(close))
                    p.enterArm := false
                    en := true
                else if not inNow and d <= band and p.apprArm
                    evMsg.push("DYNAMITE MGC: APPROACHING " + ptPoiName(p) + " " + poiRange(p) + " · " + str.tostring(d, format.mintick) + " away @ " + ptFmtP(close))
                    p.apprArm := false
                    ap := true
            if d > band
                p.enterArm := true
            if d > 2 * band
                p.apprArm := true
            p.inside := inNow
    [ap, en]
 
if barstate.isconfirmed
    [a1, e1] = track(wP, wH, wLiveOk)
    [a2, e2] = track(mP, mH, mLiveOk)
    evApprW := a1
    evEnterW := e1
    evApprM := a2
    evEnterM := e2
    [a3, e3] = track(dP, dH, dLiveOk)
    evApprD := a3
    evEnterD := e3
 
// =====================================================================================
// ALERTS (dynamic alert() messages; fired once per event on the closing tick)
// =====================================================================================
if barstate.isconfirmed and evMsg.size() > 0
    for m in evMsg
        bool isAppr  = str.contains(m, "APPROACHING")
        bool isEnter = str.contains(m, "ENTERING")
        bool isMit   = str.contains(m, "MITIGATED")
        bool isInv   = str.contains(m, "INVALIDATED")
        bool isOvl   = str.contains(m, "OVERLAP")
        evMit := evMit or isMit
        evInv := evInv or isInv
        evOvl := evOvl or isOvl
        bool want = alOn and ((isAppr and alAppr) or (isEnter and alEnter) or (isMit and alMit) or (isInv and alInv) or (isOvl and alOvl))
        if want
            alert(m + " · " + syminfo.ticker, alert.freq_once_per_bar_close)
evMsg.clear()
 
alertcondition(evApprD, "1D POI approaching", "DYNAMITE MGC: approaching a 1D (daily) POI on {{ticker}} @ {{close}}")
alertcondition(evEnterD, "1D POI entered", "DYNAMITE MGC: entered a 1D (daily) POI on {{ticker}} @ {{close}}")
alertcondition(evApprW, "1W POI approaching", "DYNAMITE MGC: approaching a 1W POI on {{ticker}} @ {{close}}")
alertcondition(evEnterW, "1W POI entered", "DYNAMITE MGC: entered a 1W POI on {{ticker}} @ {{close}}")
alertcondition(evApprM, "1M POI approaching", "DYNAMITE MGC: approaching a 1M (monthly) POI on {{ticker}} @ {{close}}")
alertcondition(evEnterM, "1M POI entered", "DYNAMITE MGC: entered a 1M (monthly) POI on {{ticker}} @ {{close}}")
alertcondition(evMit, "D/W/M POI mitigated", "DYNAMITE MGC: a 1D / 1W / 1M POI was mitigated (confirmed source close) on {{ticker}}")
alertcondition(evInv, "D/W/M POI invalidated", "DYNAMITE MGC: a 1D / 1W / 1M POI was invalidated (confirmed source close beyond far edge) on {{ticker}}")
alertcondition(evOvl, "POI confluence (overlap)", "DYNAMITE MGC: a new POI overlaps a POI of a higher / the other timeframe (1W/1M or 1D/HTF) on {{ticker}}")
 
// =====================================================================================
// DRAWING (latest bar only; full redraw from a small pool -> no history churn)
// =====================================================================================
bool dLtfLiveOnly = dLtfPre == "Nearest 3 live only" and cSec <= 300
 
dispOk(WPoi p) =>
    bool isD = p.tf == "1D"
    bool mitOk = isD ? dShowMit and not dLtfLiveOnly : showMit
    bool invOk = isD ? dShowInv and not dLtfLiveOnly : showInv
    kindVis(p) and (p.st <= ST_PRT or (p.st == ST_MIT and mitOk and not activeOnly) or (p.st == ST_INV and invOk and not activeOnly))
 
distTo(WPoi p) =>
    close > p.top ? close - p.top : close < p.bot ? p.bot - close : 0.0
 
// Stable zone selection (display only; own cap per timeframe). Deterministic rules:
//   1. candidates = displayable zones (state filter / display options)
//   2. the nearest LIVE bullish and the nearest LIVE bearish zone are always taken first (if cap >= 2)
//   3. remaining slots: smallest effective distance, where a zone shown on the previous confirmed bar
//      gets a bonus of selHyst × source ATR14 (hysteresis); ties -> older origin time, then FVG before OB, then bull before bear
//   4. the chosen zones are drawn in a fixed order (monthly first, then top price descending)
// Detection, boundaries, lifecycle states and alerts are not touched.
pickShown(array<WPoi> arr, int cap, array<string> prev, float band) =>
    array<WPoi> c = array.new<WPoi>()
    for p in arr
        if dispOk(p)
            c.push(p)
    array<WPoi> out = array.new<WPoi>()
    array<bool> used = array.new<bool>(math.max(c.size(), 1), false)
    if c.size() > 0 and cap >= 2
        for dir in array.from(1, -1)
            int bi = -1
            float bd = na
            for i = 0 to c.size() - 1
                WPoi p = c.get(i)
                if p.dir == dir and p.st <= ST_PRT
                    float d = distTo(p)
                    if na(bd) or d < bd or (d == bd and p.tS < c.get(bi).tS)
                        bd := d
                        bi := i
            if bi >= 0
                out.push(c.get(bi))
                used.set(bi, true)
    while out.size() < cap and c.size() > 0
        int bi = -1
        float be = na
        for i = 0 to c.size() - 1
            if not used.get(i)
                WPoi p = c.get(i)
                float e = distTo(p) - (prev.includes(p.key) ? band : 0.0)
                bool better = na(be) or e < be or (e == be and (p.tS < c.get(bi).tS or (p.tS == c.get(bi).tS and (p.kind < c.get(bi).kind or (p.kind == c.get(bi).kind and p.dir > c.get(bi).dir)))))
                if better
                    be := e
                    bi := i
        if bi < 0
            break
        out.push(c.get(bi))
        used.set(bi, true)
    // fixed render order: top price descending
    array<WPoi> sorted = array.new<WPoi>()
    if out.size() > 0
        array<float> tops = array.new<float>()
        for p in out
            tops.push(p.top)
        for i in tops.sort_indices(order.descending)
            sorted.push(out.get(i))
    sorted
 
keysOf(array<WPoi> arr) =>
    array<string> k = array.new<string>()
    for p in arr
        k.push(p.key)
    k
 
var array<string> dPrevKeys = array.new<string>()
var array<string> wPrevKeys = array.new<string>()
var array<string> mPrevKeys = array.new<string>()
array<WPoi> dSel = array.new<WPoi>()
array<WPoi> wSel = array.new<WPoi>()
array<WPoi> mSel = array.new<WPoi>()
if (barstate.isconfirmed and bar_index >= last_bar_index - 300) or barstate.islast
    wSel := wOn ? pickShown(wP, maxShowW, wPrevKeys, nz(wH.atr) * selHyst) : wSel
    mSel := mOn ? pickShown(mP, maxShowM, mPrevKeys, nz(mH.atr) * selHyst) : mSel
    dSel := dOn ? pickShown(dP, dLtfLiveOnly ? math.min(3, maxShowD) : maxShowD, dPrevKeys, nz(dH.atr) * selHyst) : dSel
    dPrevKeys := keysOf(dSel)
    wPrevKeys := keysOf(wSel)
    mPrevKeys := keysOf(mSel)
 
lblText(WPoi p, bool liveOk) =>
    bool  liveMore = liveOk and p.st <= ST_PRT and p.live > p.fill
    int   lst      = stateFrom(p.live, p.kind)
    string pct     = p.st == ST_TCH or p.st == ST_PRT ? " " + str.tostring(math.round(p.fill)) + "%" : ""
    string livePart = liveMore ? (lblStyle == "Full" ? " · live " + stTxt(lst) + " " + str.tostring(math.round(p.live)) + "%" : " · L" + str.tostring(math.round(p.live)) + "%") : ""
    lblStyle == "Full" ? ptPoiName(p) + (p.st == ST_ACT ? "" : " · " + stTxt(p.st) + pct) + livePart : p.tf + " " + (p.dir > 0 ? "▲ " : "▼ ") + (p.kind == K_FVG ? "FVG" : "OB") + (p.st == ST_ACT ? "" : " · " + stShort(p.st) + pct) + livePart
 
var array<box>   boxes = array.new<box>()
var array<WPoi>  mTShown = array.new<WPoi>()   // MASTER: zones drawn on the latest bar (right-edge labels)
var array<line>  xLines = array.new<line>()
var array<label> xLbls = array.new<label>()
var int firstT = time
 
if barstate.islast
    for b in boxes
        b.delete()
    boxes.clear()
    for l in xLines
        l.delete()
    xLines.clear()
    for l in xLbls
        l.delete()
    xLbls.clear()
    mTShown.clear()
    array<WPoi> shown = array.new<WPoi>()
    for p in mSel
        shown.push(p)
    for p in wSel
        shown.push(p)
    for p in dSel
        shown.push(p)
    // label priority = monthly, then weekly, then daily (shown[] is in that order; boxes are always drawn)
    array<float> lblMid = array.new<float>()
    string hal = lblHal == "Left" ? text.align_left : lblHal == "Center" ? text.align_center : text.align_right
    string val = lblVal == "Top" ? text.align_top : lblVal == "Center" ? text.align_center : text.align_bottom
    for p in shown
        bool liveOk = p.tf == "1W" ? wLiveOk : p.tf == "1M" ? mLiveOk : dLiveOk
        color base = p.st == ST_MIT ? mitCol : p.dir > 0 ? bullCol : bearCol
        bool  inv  = p.st == ST_INV
        int   tr   = inv ? 95 : p.st == ST_MIT ? math.min(fillTr + 8, 98) : p.st == ST_PRT ? math.min(fillTr + 5, 98) : p.st == ST_TCH ? math.min(fillTr + 3, 98) : fillTr
        float mid  = (p.top + p.bot) / 2
        bool  near = false
        for m in lblMid
            if math.abs(m - mid) < lblGapTk * ptTick
                near := true
        bool  showL = lblOn and not near
        if showL
            lblMid.push(mid)
        int left = math.max(p.tS, firstT)
        if mTfVis(p.tf)   // MASTER: per-timeframe visibility (display only)
            box bx = box.new(left, p.top, inv ? math.max(nz(p.tEnd, time), left) : time, p.bot, xloc = xloc.bar_time, extend = inv ? extend.none : extend.right, border_color = color.new(base, inv ? 70 : p.st == ST_MIT ? 50 : 15), border_width = p.tf == "1M" ? mBorderW : p.tf == "1W" ? wBorderW : dBorderW, border_style = inv ? line.style_dotted : p.kind == K_FVG ? line.style_dashed : line.style_solid, bgcolor = color.new(base, tr), text = showL and mLblMode == M_LBL_BOX ? lblText(p, liveOk) : "", text_size = szOf(lblSize), text_color = color.new(txtCol, 0), text_halign = hal, text_valign = val)
            boxes.push(bx)
            mTShown.push(p)
    // ---- optional extra POIs (lines) ----
    for tfI = 0 to 2
        bool  on  = tfI == 0 ? wOn : tfI == 1 ? mOn : dOn
        string tf = tfI == 0 ? "1W" : tfI == 1 ? "1M" : "1D"
        array<WSwing> sw = tfI == 0 ? wS : tfI == 1 ? mS : dS
        WHdr  hh  = tfI == 0 ? wH : tfI == 1 ? mH : dH
        int   lw  = tfI == 1 ? 2 : 1
        if on and (xSwing or xLiq)
            int cnt = 0
            for s in sw
                bool unswept = na(s.swept)
                if cnt < xMax and (xSwing or (xLiq and unswept))
                    color c = s.dir > 0 ? bearCol : bullCol
                    string nm = xLiq and unswept ? tf + (s.dir > 0 ? " BSL " : " SSL ") + ptFmtP(s.px) : tf + (s.dir > 0 ? " SWING H " : " SWING L ") + ptFmtP(s.px) + (unswept ? "" : " (swept)")
                    xLines.push(line.new(math.max(s.t, firstT), s.px, unswept ? time : nz(s.swept, time), s.px, xloc = xloc.bar_time, extend = unswept ? extend.right : extend.none, color = color.new(c, unswept ? 20 : 60), style = unswept ? line.style_dotted : line.style_dashed, width = lw))
                    xLbls.push(label.new(time, s.px, nm, xloc = xloc.bar_time, style = label.style_none, textcolor = color.new(txtCol, 0), size = szOf(lblSize)))
                    cnt += 1
        if on and xPrev and not na(hh.hi)
            string pn = tfI == 0 ? "PREV WEEK" : tfI == 1 ? "PREV MONTH" : "PREV DAY"
            xLines.push(line.new(math.max(hh.asOf, firstT), hh.hi, time, hh.hi, xloc = xloc.bar_time, extend = extend.right, color = color.new(bearCol, 30), style = line.style_solid, width = lw))
            xLines.push(line.new(math.max(hh.asOf, firstT), hh.lo, time, hh.lo, xloc = xloc.bar_time, extend = extend.right, color = color.new(bullCol, 30), style = line.style_solid, width = lw))
            xLbls.push(label.new(time, hh.hi, pn + " HIGH " + ptFmtP(hh.hi), xloc = xloc.bar_time, style = label.style_none, textcolor = color.new(txtCol, 0), size = szOf(lblSize)))
            xLbls.push(label.new(time, hh.lo, pn + " LOW " + ptFmtP(hh.lo), xloc = xloc.bar_time, style = label.style_none, textcolor = color.new(txtCol, 0), size = szOf(lblSize)))
 
// =====================================================================================
// [B] DASHBOARD HELPERS (rendered by the master dashboard)
// =====================================================================================
nearestDir(array<WPoi> arr, int dir) =>
    WPoi best = na
    float bd = na
    for p in arr
        if p.dir == dir and p.st <= ST_PRT and kindVis(p)
            float d = distTo(p)
            if na(bd) or d < bd
                bd := d
                best := p
    best
 
poiCell(WPoi p, bool compact) =>
    na(p) ? "none live" : (compact ? (p.kind == K_FVG ? "FVG " : "OB ") : (p.kind == K_FVG ? "FVG " : "OB ")) + poiRange(p) + " · " + (compact ? stShort(p.st) : stTxt(p.st)) + (p.st == ST_TCH or p.st == ST_PRT ? " " + str.tostring(math.round(p.fill)) + "%" : "") + " · " + (distTo(p) == 0 ? "IN" : str.tostring(distTo(p), format.mintick) + " pts")
 
ctxTxt(WHdr hh, array<WPoi> arr, string tf) =>
    WPoi nb = nearestDir(arr, 1)
    WPoi nr = nearestDir(arr, -1)
    string bos = nz(hh.bosDir) > 0 ? "last BOS ↑" : nz(hh.bosDir) < 0 ? "last BOS ↓" : "no BOS yet"
    string bt  = na(hh.bosT) ? "" : " (" + str.format_time(hh.bosT, "yyyy-MM-dd", "America/New_York") + ")"
    bos + bt + " · " + (na(nb) ? "no bull POI" : "bull POI " + (close >= nb.bot ? "below/at" : "above")) + " · " + (na(nr) ? "no bear POI" : "bear POI " + (close <= nr.top ? "above/at" : "below"))
 
// =====================================================================================
// DIAGNOSTICS (Data Window only)
// =====================================================================================
cntLive(array<WPoi> arr) =>
    int n = 0
    for p in arr
        n += p.st <= ST_PRT ? 1 : 0
    n
plot(dOn ? cntLive(dP) : na, "dbg 1D live POIs", display = display.data_window, editable = false)
plot(dOn ? dH.asOf : na, "dbg 1D state as-of (source candle open time)", display = display.data_window, editable = false)
plot(wOn ? cntLive(wP) : na, "dbg 1W live POIs", display = display.data_window, editable = false)
plot(mOn ? cntLive(mP) : na, "dbg 1M live POIs", display = display.data_window, editable = false)
plot(wOn ? wH.asOf : na, "dbg 1W state as-of (source candle open time)", display = display.data_window, editable = false)
plot(mOn ? mH.asOf : na, "dbg 1M state as-of (source candle open time)", display = display.data_window, editable = false)
 
// =====================================================================================
// 0 · MASTER — RIGHT-EDGE ZONE LABELS (display only; latest bar; small pool, fully rebuilt)
// -------------------------------------------------------------------------------------
// Why independent labels: the zones extend to the right (extend.right), so a box has no finite
// right edge for text_halign = text.align_right to attach to. Each description is therefore an
// independent label anchored mLblOff bars right of the latest candle (the visible right edge of
// every extended zone), at the zone's mid price. By default the text ENDS at that anchor and runs left
// (style_label_right), so it can never be clipped by the price scale whatever the chart's right margin;
// optionally it starts at the anchor and runs right. Items are sorted top -> bottom; items whose text lines
// would overlap are stacked into one multi-line label (same top -> bottom order; first line at the
// top zone's price, one text line lower per name), so labels never overlap each other. Nothing here is read by any calculation, signal, alert or journal.
// =====================================================================================
var array<label> mLbls = array.new<label>()
float mSpan = ta.highest(high, math.min(200, bar_index + 1)) - ta.lowest(low, math.min(200, bar_index + 1))   // recent price range, only used to size label line height
 
// setup-module POI drawn on the chart (same rule as poiStyle's hide flag, plus the master TF toggle)
mPoiVisible(Poi p) =>
    not na(p.bx) and not (p.state == PS_MITIG and not htfShowMitig and not p.armed) and mTfVis(p.tf)
 
 
mRank(string tf) =>
    tf == "1M" ? 7 : tf == "1W" ? 6 : tf == "1D" ? 5 : tf == "4H" ? 4 : tf == "1H" ? 3 : tf == "15M" ? 2 : 1
 
mPoiFullTxt(Poi p) =>
    (p.armed ? "ARMED POI ▸ " : "") + poiName(p) + (p.dyn ? " ◆ " + p.dynName : "") + (p.state == PS_ACTIVE ? "" : " · " + poiStateTxt(p.state))
 
mPoiCompactTxt(Poi p) =>
    p.tf + " " + (p.dir > 0 ? "BULL" : "BEAR") + " " + (p.kind == PK_FVG ? "FVG" : "OB") + (p.wide ? " W" : "") + (p.state == PS_TOUCHED ? " · T" : p.state == PS_MITIG ? " · M" : "") + (p.armed ? " ▸ ARMED" : "") + (p.dyn ? " ◆" : "")
 
mTrkCompactTxt(WPoi p, bool liveOk) =>
    bool   liveMore = liveOk and p.st <= ST_PRT and p.live > p.fill
    string pct = p.st == ST_TCH or p.st == ST_PRT ? " " + str.tostring(math.round(p.fill)) + "%" : ""
    p.tf + " " + (p.dir > 0 ? "BULL" : "BEAR") + " " + (p.kind == K_FVG ? "FVG" : "OB") + (p.wide ? " W" : "") + (p.st == ST_ACT ? "" : " · " + stShort(p.st) + pct) + (liveMore ? " · L" + str.tostring(math.round(p.live)) + "%" : "")
 
mF15CompactTxt(F15Gap g) =>
    string pct = g.st == F15_TCH or g.st == F15_PRT ? " " + str.tostring(math.round(g.fill)) + "%" : ""
    "15M " + (g.dir > 0 ? "BULL" : "BEAR") + " FVG" + (g.st == F15_ACT ? "" : " · " + (g.st == F15_TCH ? "T" : g.st == F15_PRT ? "P" : g.st == F15_MIT ? "M" : "X") + pct)
 
// one stacked label for the items g (indices into ys / tx / rk, already ordered top -> bottom)
mFlush(array<int> g, array<float> ys, array<string> tx, array<int> rk, float h) =>
    int n = g.size()
    array<bool> sel = array.new<bool>(n, true)
    if n > mLblMax
        array<float> pr = array.new<float>()
        for j = 0 to n - 1
            pr.push(rk.get(g.get(j)) * 1000.0 - j)
        array<int> idx = pr.sort_indices(order.descending)
        sel := array.new<bool>(n, false)
        for j = 0 to mLblMax - 1
            sel.set(idx.get(j), true)
    string txt = ""
    for j = 0 to n - 1
        if sel.get(j)
            txt += (txt == "" ? "" : "\n") + tx.get(g.get(j))
    if n > mLblMax
        txt += "\n+" + str.tostring(n - mLblMax) + " more"
    // first line at the top item's price, following lines one text line (h) lower each
    int   nl = math.min(n, mLblMax) + (n > mLblMax ? 1 : 0)
    float y  = ys.get(g.first()) - (nl - 1) * h / 2
    mLbls.push(label.new(bar_index + mLblOff, y, txt, xloc = xloc.bar_index, style = mLblDir == "Text starts at anchor" ? label.style_label_left : label.style_label_right, color = color.new(#000000, 100), textcolor = color.new(vrTextCol, vrTxtTr), size = vrSize(mLblSz), textalign = mLblDir == "Text starts at anchor" ? text.align_left : text.align_right))
 
if barstate.islast
    for l in mLbls
        l.delete()
    mLbls.clear()
    if mLblMode == M_LBL_RIGHT
        bool mFullW = mLblWord == "Full"
        array<float>  ys = array.new<float>()
        array<string> tx = array.new<string>()
        array<int>    rk = array.new<int>()
        // 1) setup module HTF POIs (1H / 4H / 1D) that are drawn
        if htfOn
            for p in pois
                if mPoiVisible(p)
                    ys.push(p.mid)
                    tx.push(mFullW ? mPoiFullTxt(p) : mPoiCompactTxt(p))
                    rk.push(mRank(p.tf))
        // 2) D/W/M tracker zones that are drawn (after its stable selection and de-duplication)
        if lblOn
            for q in mTShown
                bool liveOk = q.tf == "1W" ? wLiveOk : q.tf == "1M" ? mLiveOk : dLiveOk
                ys.push((q.top + q.bot) / 2)
                tx.push(mFullW ? lblText(q, liveOk) : mTrkCompactTxt(q, liveOk))
                rk.push(mRank(q.tf))
        // 3) 15M FVGs (display-only module)
        if f15On and f15Tf and f15Lbl and mShow15
            for g in f15
                ys.push((g.top + g.bot) / 2)
                tx.push(mFullW ? f15Txt(g) : mF15CompactTxt(g))
                rk.push(2)
        // 4) Dynamite zones
        if showZoneLabels and mShowDyn
            for i = 0 to 7
                if zOn.get(i)
                    ys.push((zT.get(i) + zB.get(i)) / 2)
                    tx.push(mFullW ? zNm.get(i) + " [" + roleTag(zRl.get(i)) + "]  " + fmtP(zB.get(i)) + " – " + fmtP(zT.get(i)) + "  ·  " + zoneStatus(i) : "DYN " + zNm.get(i) + " [" + roleTag(zRl.get(i)) + "]")
                    rk.push(1)
        // stack top -> bottom; a new label starts only where it cannot overlap the previous one
        if ys.size() > 0
            float h = math.max(nz(mSpan) * mLblGap, syminfo.mintick)
            array<int> grp = array.new<int>()
            float gTop = na
            for i in ys.sort_indices(order.descending)
                float y = ys.get(i)
                if grp.size() > 0
                    int   lines  = math.min(grp.size(), mLblMax) + (grp.size() > mLblMax ? 1 : 0)
                    float bottom = gTop - (lines - 1) * h - h / 2
                    if bottom - (y + h / 2) < 0
                        grp.push(i)
                    else
                        mFlush(grp, ys, tx, rk, h)
                        grp := array.new<int>()
                        grp.push(i)
                        gTop := y
                else
                    grp.push(i)
                    gTop := y
            if grp.size() > 0
                mFlush(grp, ys, tx, rk, h)
 
// =====================================================================================
// 0 · MASTER — ONE COMPACT DASHBOARD ON THE LEFT (latest bar only; context, never a trade signal)
// =====================================================================================
string mPos = mDashPos == "Top Left" ? position.top_left : mDashPos == "Middle Left" ? position.middle_left : position.bottom_left
string mTxt = mDashSz == "Tiny" ? size.tiny : mDashSz == "Normal" ? size.normal : mDashSz == "Large" ? size.large : size.small
color  mKeyC = color.new(#d1d4dc, 0)
color  mOffC = color.new(#9598a1, 0)
 
// distance from price to a zone (0 = inside)
mDist(float top, float bot) =>
    close > top ? close - top : close < bot ? bot - close : 0.0
 
// nearest LIVE (ACTIVE / TOUCHED) 1H or 4H POI of the [A] engine, optionally one direction (0 = either)
mNearPoi(string tf, int dir) =>
    Poi best = na
    float bd = na
    for p in pois
        if p.tf == tf and p.state <= PS_TOUCHED and (dir == 0 or p.dir == dir)
            float d = mDist(p.top, p.bot)
            if na(bd) or d < bd
                bd := d
                best := p
    best
 
mPoiCell(Poi p) =>
    na(p) ? "none live" : (p.dir > 0 ? "▲ " : "▼ ") + (p.kind == PK_FVG ? "FVG " : "OB ") + fmtP(p.bot) + "–" + fmtP(p.top) + (p.state == PS_TOUCHED ? " · T" : "") + (p.wide ? " · W" : "") + " · " + (mDist(p.top, p.bot) == 0 ? "IN" : str.tostring(mDist(p.top, p.bot), format.mintick))
 
// nearest live zone of one tracker timeframe, either direction
mNearOf(array<WPoi> arr) =>
    WPoi b = nearestDir(arr, 1)
    WPoi r = nearestDir(arr, -1)
    na(b) ? r : na(r) ? b : distTo(b) <= distTo(r) ? b : r
 
mTrkCell(WPoi p, bool on) =>
    not on ? "off" : na(p) ? "none live" : (p.dir > 0 ? "▲ " : "▼ ") + (p.kind == K_FVG ? "FVG " : "OB ") + ptFmtP(p.bot) + "–" + ptFmtP(p.top) + (p.st == ST_ACT ? "" : " · " + stShort(p.st) + (p.st == ST_TCH or p.st == ST_PRT ? " " + str.tostring(math.round(p.fill)) + "%" : "")) + " · " + (distTo(p) == 0 ? "IN" : str.tostring(distTo(p), format.mintick))
 
// compact market context of one tracker timeframe (same facts as the tracker's "context" row)
mCtx(WHdr hh, array<WPoi> arr, bool on) =>
    WPoi nb = nearestDir(arr, 1)
    WPoi nr = nearestDir(arr, -1)
    not on ? "off" : (nz(hh.bosDir) > 0 ? "BOS ↑" : nz(hh.bosDir) < 0 ? "BOS ↓" : "no BOS") + (na(hh.bosT) ? "" : " " + str.format_time(hh.bosT, "yy-MM-dd", "America/New_York")) + " · ▲ " + (na(nb) ? "none" : close >= nb.bot ? "below" : "above") + " · ▼ " + (na(nr) ? "none" : close <= nr.top ? "above" : "below")
 
mCtxCol(WHdr hh, bool on) =>
    not on ? mOffC : nz(hh.bosDir) > 0 ? bullCol : nz(hh.bosDir) < 0 ? bearCol : mOffC
 
// current interaction: every zone (any module / timeframe) price is inside, highest timeframe first
mInteraction(bool shortForm) =>
    string s = ""
    int    n = 0
    color  c = mOffC
    for tfI = 0 to 2
        for q in (tfI == 0 ? mP : tfI == 1 ? wP : dP)
            if kindVis(q) and distTo(q) == 0 and (q.st <= ST_MIT or (q.st == ST_INV and (q.tf == "1D" ? dShowInv : showInv)))
                if n == 0
                    c := q.st <= ST_PRT ? (q.dir > 0 ? bullCol : bearCol) : q.st == ST_MIT ? mitCol : mOffC
                s += (n > 0 ? " + " : "") + q.tf + (q.dir > 0 ? "▲" : "▼") + (q.kind == K_FVG ? "FVG" : "OB") + (q.st == ST_ACT ? "" : shortForm ? " " + stShort(q.st) : " " + stTxt(q.st))
                n += 1
    for tf in array.from("4H", "1H")
        for p in pois
            if p.tf == tf and p.state <= PS_MITIG and mDist(p.top, p.bot) == 0
                if n == 0
                    c := p.state <= PS_TOUCHED ? (p.dir > 0 ? htfBullCol : htfBearCol) : colHist
                s += (n > 0 ? " + " : "") + p.tf + (p.dir > 0 ? "▲" : "▼") + (p.kind == PK_FVG ? "FVG" : "OB") + (p.state == PS_TOUCHED ? " T" : p.state == PS_MITIG ? " M" : "")
                n += 1
    if f15On and f15Tf
        for g in f15
            if g.st != F15_INV and close >= g.bot and close <= g.top
                if n == 0
                    c := g.dir > 0 ? f15BullCol : f15BearCol
                s += (n > 0 ? " + " : "") + "15M" + (g.dir > 0 ? "▲" : "▼") + "FVG"
                n += 1
    for i = 0 to 7
        if zOn.get(i) and close >= zB.get(i) and close <= zT.get(i)
            if n == 0
                c := vrZoneCol(i)
            s += (n > 0 ? " + " : "") + "DYN " + (shortForm ? roleTag(zRl.get(i)) : zNm.get(i))
            n += 1
    [n, n == 0 ? "outside all POIs" : s, c]
 
// timeframe confluence: live zones of DIFFERENT timeframes overlapping each other at / nearest to price
mConfluence() =>
    array<float>  tps = array.new<float>()
    array<float>  bts = array.new<float>()
    array<string> tgs = array.new<string>()
    for tfI = 0 to 2
        for q in (tfI == 0 ? mP : tfI == 1 ? wP : dP)
            if q.st <= ST_PRT and kindVis(q)
                tps.push(q.top), bts.push(q.bot), tgs.push(q.tf + (q.dir > 0 ? "▲" : "▼") + (q.kind == K_FVG ? "FVG" : "OB"))
    for p in pois
        if p.state <= PS_TOUCHED
            tps.push(p.top), bts.push(p.bot), tgs.push(p.tf + (p.dir > 0 ? "▲" : "▼") + (p.kind == PK_FVG ? "FVG" : "OB"))
    // the overlap cluster closest to price (2+ timeframes)
    string best = ""
    float  bestD = na
    int    nz_ = tps.size()
    if nz_ > 1
        for i = 0 to nz_ - 1
            string tfi = str.substring(tgs.get(i), 0, 2)
            string grp = tgs.get(i)
            int    cnt = 1
            for j = 0 to nz_ - 1
                if j != i and str.substring(tgs.get(j), 0, 2) != tfi and tps.get(j) >= bts.get(i) and bts.get(j) <= tps.get(i) and not str.contains(grp, str.substring(tgs.get(j), 0, 2))
                    grp += " + " + tgs.get(j)
                    cnt += 1
            float d = mDist(tps.get(i), bts.get(i))
            if cnt >= 2 and (na(bestD) or d < bestD)
                bestD := d
                best := grp + " · " + (d == 0 ? "IN" : str.tostring(d, format.mintick) + " away")
    best == "" ? "no multi-TF overlap" : best
 
// Bottom Left: one transparent spacer row under the table so TradingView's own corner logo never covers text
int  mRows = mDashPre == "Full" ? 22 : mDashPre == "Compact" ? 12 : 6
bool mSpacer = mDashPos == "Bottom Left"
var table mDash = mDashOn ? table.new(mPos, 2, mRows + (mSpacer ? 1 : 0), bgcolor = color.new(#0b0e14, 8), frame_color = color.new(#787b86, 45), frame_width = 1, border_color = color.new(#787b86, 80), border_width = 1) : na
 
mCell(int r, string k, string v, color vc) =>
    table.cell(mDash, 0, r, k, text_color = mKeyC, text_size = mTxt, text_halign = text.align_left)
    table.cell(mDash, 1, r, v, text_color = vc, text_size = mTxt, text_halign = text.align_left)
 
if barstate.islast and mDashOn and not na(mDash)
    if mSpacer
        table.cell(mDash, 0, mRows, "", height = 4, bgcolor = color.new(#000000, 100))
        table.cell(mDash, 1, mRows, "", height = 4, bgcolor = color.new(#000000, 100))
    bool full = mDashPre == "Full"
    bool mini = mDashPre == "Minimal"
    [iN, iTxt, iCol] = mInteraction(not full)
    string conf = mConfluence()
    Poi n4 = htfOn and htf4hOn ? mNearPoi("4H", 0) : na
    Poi n1 = htfOn and htf1hOn ? mNearPoi("1H", 0) : na
    table.cell(mDash, 0, 0, mini ? "DYN POI" : "DYNAMITE MGC POI", text_color = color.white, text_size = mTxt, text_halign = text.align_left, text_formatting = text.format_bold)
    table.cell(mDash, 1, 0, ptFmtP(close) + " · context only", text_color = color.white, text_size = mTxt, text_halign = text.align_left, text_formatting = text.format_bold)
    if mini
        WPoi nz0 = na
        float nd0 = na
        for tfI = 0 to 2
            for q in (tfI == 0 ? mP : tfI == 1 ? wP : dP)
                if q.st <= ST_PRT and kindVis(q) and (na(nd0) or distTo(q) < nd0)
                    nd0 := distTo(q)
                    nz0 := q
        string arrows = (mOn ? "M" + (nz(mH.bosDir) > 0 ? "↑ " : nz(mH.bosDir) < 0 ? "↓ " : "· ") : "") + (wOn ? "W" + (nz(wH.bosDir) > 0 ? "↑ " : nz(wH.bosDir) < 0 ? "↓ " : "· ") : "") + (dOn ? "D" + (nz(dH.bosDir) > 0 ? "↑" : nz(dH.bosDir) < 0 ? "↓" : "·") : "")
        mCell(1, "Ctx", arrows, color.white)
        mCell(2, "Now", iTxt, iCol)
        mCell(3, "D/W/M", na(nz0) ? "none live" : nz0.tf + " " + mTrkCell(nz0, true), na(nz0) ? mOffC : nz0.dir > 0 ? bullCol : bearCol)
        Poi nh = na(n4) ? n1 : na(n1) ? n4 : mDist(n4.top, n4.bot) <= mDist(n1.top, n1.bot) ? n4 : n1
        mCell(4, "4H/1H", na(nh) ? "none live" : nh.tf + " " + mPoiCell(nh), na(nh) ? mOffC : nh.dir > 0 ? htfBullCol : htfBearCol)
        mCell(5, "Conf", conf, conf == "no multi-TF overlap" ? mOffC : color.white)
    else if not full
        WPoi nM = mOn ? mNearOf(mP) : na
        WPoi nW = wOn ? mNearOf(wP) : na
        WPoi nD = dOn ? mNearOf(dP) : na
        mCell(1, "1M ctx", mCtx(mH, mP, mOn), mCtxCol(mH, mOn))
        mCell(2, "1W ctx", mCtx(wH, wP, wOn), mCtxCol(wH, wOn))
        mCell(3, "1D ctx", mCtx(dH, dP, dOn), mCtxCol(dH, dOn))
        mCell(4, "1M", mTrkCell(nM, mOn), na(nM) ? mOffC : nM.dir > 0 ? bullCol : bearCol)
        mCell(5, "1W", mTrkCell(nW, wOn), na(nW) ? mOffC : nW.dir > 0 ? bullCol : bearCol)
        mCell(6, "1D", mTrkCell(nD, dOn), na(nD) ? mOffC : nD.dir > 0 ? bullCol : bearCol)
        mCell(7, "4H", htfOn and htf4hOn ? mPoiCell(n4) : "off", na(n4) ? mOffC : n4.dir > 0 ? htfBullCol : htfBearCol)
        mCell(8, "1H", htfOn and htf1hOn ? mPoiCell(n1) : "off", na(n1) ? mOffC : n1.dir > 0 ? htfBullCol : htfBearCol)
        mCell(9, "Now", iTxt, iCol)
        mCell(10, "Conf", conf, conf == "no multi-TF overlap" ? mOffC : color.white)
        mCell(11, "Note", "POI context only · not a trade signal", mOffC)
    else
        // Full: the D/W/M tracker's Full dashboard rows (same wording), then the 1H / 4H / 15M / Dynamite rows
        WPoi wb = wOn ? nearestDir(wP, 1) : na
        WPoi wr = wOn ? nearestDir(wP, -1) : na
        WPoi mb = mOn ? nearestDir(mP, 1) : na
        WPoi mr = mOn ? nearestDir(mP, -1) : na
        WPoi db = dOn ? nearestDir(dP, 1) : na
        WPoi dr = dOn ? nearestDir(dP, -1) : na
        int r = 1
        mCell(r, "1M context", mOn ? ctxTxt(mH, mP, "1M") : "off", mOffC)
        r += 1
        mCell(r, "1W context", wOn ? ctxTxt(wH, wP, "1W") : "off", mOffC)
        r += 1
        mCell(r, "1D context", dOn ? ctxTxt(dH, dP, "1D") : "off", mOffC)
        r += 1
        mCell(r, "1M bull (nearest)", mOn ? poiCell(mb, false) : "off", na(mb) ? mOffC : bullCol)
        r += 1
        mCell(r, "1M bear (nearest)", mOn ? poiCell(mr, false) : "off", na(mr) ? mOffC : bearCol)
        r += 1
        mCell(r, "1W bull (nearest)", wOn ? poiCell(wb, false) : "off", na(wb) ? mOffC : bullCol)
        r += 1
        mCell(r, "1W bear (nearest)", wOn ? poiCell(wr, false) : "off", na(wr) ? mOffC : bearCol)
        r += 1
        mCell(r, "1D bull (nearest)", dOn ? poiCell(db, false) : "off", na(db) ? mOffC : bullCol)
        r += 1
        mCell(r, "1D bear (nearest)", dOn ? poiCell(dr, false) : "off", na(dr) ? mOffC : bearCol)
        r += 1
        Poi b4 = mNearPoi("4H", 1)
        Poi s4 = mNearPoi("4H", -1)
        Poi b1 = mNearPoi("1H", 1)
        Poi s1 = mNearPoi("1H", -1)
        mCell(r, "4H bull (nearest)", htfOn and htf4hOn ? mPoiCell(b4) : "off", na(b4) ? mOffC : htfBullCol)
        r += 1
        mCell(r, "4H bear (nearest)", htfOn and htf4hOn ? mPoiCell(s4) : "off", na(s4) ? mOffC : htfBearCol)
        r += 1
        mCell(r, "1H bull (nearest)", htfOn and htf1hOn ? mPoiCell(b1) : "off", na(b1) ? mOffC : htfBullCol)
        r += 1
        mCell(r, "1H bear (nearest)", htfOn and htf1hOn ? mPoiCell(s1) : "off", na(s1) ? mOffC : htfBearCol)
        r += 1
        // nearest live 15M FVG and nearest Dynamite level
        F15Gap g15 = na
        float g15d = na
        if f15On and f15Tf
            for g in f15
                if g.st < F15_MIT and (na(g15d) or mDist(g.top, g.bot) < g15d)
                    g15d := mDist(g.top, g.bot)
                    g15 := g
        mCell(r, "15M FVG (nearest)", not (f15On and f15Tf) ? "shown on 1m-5m charts" : na(g15) ? "none live" : (g15.dir > 0 ? "▲ " : "▼ ") + fmtP(g15.bot) + "–" + fmtP(g15.top) + " · " + f15StTxt(g15) + " · " + (g15d == 0 ? "IN" : str.tostring(g15d, format.mintick)), na(g15) ? mOffC : g15.dir > 0 ? f15BullCol : f15BearCol)
        r += 1
        int zi = -1
        float zd = na
        for i = 0 to 7
            if zOn.get(i) and (na(zd) or zoneDist(i) < zd)
                zd := zoneDist(i)
                zi := i
        mCell(r, "Dynamite (nearest)", zi < 0 ? "none" : zRangeTxt(zi) + " [" + roleTag(zRl.get(zi)) + "] · " + zoneStatus(zi), zi < 0 ? mOffC : vrZoneCol(zi))
        r += 1
        mCell(r, "Interaction", iTxt, iCol)
        r += 1
        mCell(r, "TF confluence", conf, conf == "no multi-TF overlap" ? mOffC : color.white)
        r += 1
        string wA = na(wH.asOfClose) ? "1W n/a" : "1W closed " + str.format_time(wH.asOfClose - 1, "yyyy-MM-dd", "America/New_York") + " (wk of " + str.format_time(wH.asOfClose - 1 - 4 * 86400000, "MM-dd", "America/New_York") + ")"
        string mA = na(mH.asOfClose) ? "1M n/a" : "1M closed " + str.format_time(mH.asOfClose - 1, "yyyy-MM-dd", "America/New_York") + " (" + str.format_time(mH.asOfClose - 1, "MMM", "America/New_York") + ")"
        string dA = na(dH.asOfClose) ? "1D n/a" : "1D closed " + str.format_time(dH.asOfClose - 1, "MM-dd", "America/New_York")
        mCell(r, "Confirmed (close)", dA + " · " + wA + " · " + mA, mOffC)
        r += 1
        mCell(r, "Note", "context only · not a trade signal", mOffC)
        r += 1
        mCell(r, "Legend", "▮ bull  ▮ bear  ▮ mitigated · FVG dashed · OB solid · invalid dotted", color.white)
        r += 1
        mCell(r, "", "borders: 1H 1 · 4H 2 · 1D 1 · 1W 2 · 1M 3 (defaults) · live % = unconfirmed", color.white)

← 返回列表