Dynamite DXY - Daily, Weekly & Monthly POI Tracker

otssb228 · study · 1031 行 · 点赞 15 · 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 DXY — Daily, Weekly & Monthly POI Tracker
//    (version 2 of the saved script 'Dynamite DXY — Weekly & Monthly POI Tracker v1', updated in place.
//     Adds a third, independent DAILY (1D) layer = the validated Daily engine of the Dynamite MGC
//     Daily, Weekly & Monthly POI Tracker (v1.2 RC). Inputs that existed in v1 keep their original order;
//     the new Daily inputs are declared after them so settings stored on charts stay attached.)
//  Independent CONTEXT indicator for the U.S. Dollar Index (DXY). Built on the validated architecture of the
//  Dynamite MGC — Weekly & Monthly POI Tracker v1.1 RC (same detection, lifecycle, MTF synchronisation,
//  stable zone selection) and the zone philosophy of the Dynamite DXY POI Assistant v1, calibrated for DXY:
//  index-point precision (syminfo.mintick, e.g. 0.001 on TVC:DXY), ATR-scaled thresholds, ATR-scaled label
//  spacing, optional absolute DXY-point approach distance, data-feed / history disclosure on the dashboard.
//  It places no orders and produces NO trade signals - for DXY or for gold. A POI is a location, not a
//  confirmation. The optional gold-context panel is informational only.
//
//  WHAT IT TRACKS (per source timeframe: 1W = one-week candles, 1M = one-MONTH candles)
//    FVG  : 3-candle fair value gap, detected when the 3rd candle CLOSES.
//           bull: low(c) > high(c-2)  ->  zone high(c-2) .. low(c)
//           bear: high(c) < low(c-2)  ->  zone high(c) .. low(c-2)
//           gap must be >= "FVG minimum gap × source ATR14" (same filter as the assistant).
//    OB   : conservative order block (same philosophy as the assistant's HTF POI module):
//           a confirmed swing pivot (pivot length each side) is broken by a candle CLOSE,
//           AND one of the last 3 candles is a displacement candle (body >= k × ATR14).
//           bull OB = last bearish candle(s) (max N cluster) before the rally, OPEN -> LOW
//           bear OB = last bullish candle(s) before the drop, OPEN -> HIGH
//    Optional (off by default): swing highs/lows, liquidity pools (unswept swing extremes),
//           previous week / month high & low.
//
//  LIFECYCLE (evaluated ONLY on CLOSED source candles, so it is identical on every chart)
//    fill % = deepest penetration from the near edge / zone height (wicks count)
//    ACTIVE      : fill = 0
//    TOUCHED     : 0 < fill < partial threshold
//    PARTIAL     : fill >= partial threshold          (default FVG 50 %, OB 25 %)
//    MITIGATED   : fill >= mitigation threshold       (default FVG 100 % = far edge, OB 50 % = mid)
//    INVALIDATED : a source candle CLOSES beyond the far edge (bull: close < bottom, bear: close > top)
//    A touch is never treated as an invalidation; only a confirmed source close invalidates.
//    Extra "live" layer (display + dashboard + alerts only): on charts BELOW the source timeframe the
//    deepest penetration by CONFIRMED chart candles since the last closed source candle is shown as
//    "live …". It never changes the confirmed state and never invalidates.
//
//  TIMEFRAME CONSISTENCY / NO FUTURE DATA
//    The whole POI list is built inside the source-timeframe context and exported as one record.
//    * chart TF <= source TF : request.security(lookahead_on) with the PREVIOUS source candle's list,
//      or the current one only once that candle has closed (its time_close <= chart bar close AND
//      <= timenow). No value from a still-forming source candle is ever used.
//    * chart TF  > source TF (1W POIs on a monthly chart): request.security_lower_tf() returns the
//      list after every weekly candle; the newest one CLOSED by the chart bar's close / now is used.
//      (A single request.security() sample per monthly candle would be up to a month stale.)
//    Same engine, same candles -> same boundaries and states on 1m … 1M charts.
// =====================================================================================
indicator("Dynamite DXY — Daily, Weekly & Monthly POI Tracker", shorttitle = "DynDXY D/W/M POI", overlay = true, max_boxes_count = 300, max_lines_count = 100, max_labels_count = 100)
 
// =====================================================================================
// INPUTS
// =====================================================================================
const string G_SRC = "1 · Sources"
const string G_DET = "2 · Detection (same philosophy as the Setup Assistant)"
const string G_LIF = "3 · Lifecycle"
const string G_DSP = "4 · Display"
const string G_VIS = "5 · Colours & labels"
const string G_XTR = "6 · Optional extra POIs (off by default)"
const string G_DSH = "7 · Dashboard & legend"
const string G_ALR = "8 · Alerts (alert() messages)"
const string G_DLY = "3b · 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 DXY feed (recommended: TVC:DXY, the feed used by the Dynamite DXY POI Assistant). Only set a symbol on purpose: zones are computed from THIS feed but drawn on the chart's price scale, so a different provider (e.g. ICE dollar-index futures DX1!) can sit at a different price level. The dashboard Data row warns when the feeds differ, when the chart is not DXY, or when history is short.")
showFvg  = input.bool(true, "Fair value gaps", inline = "kind", group = G_SRC)
showOb   = input.bool(true, "Order blocks", inline = "kind", group = G_SRC, tooltip = "Hides a POI type everywhere at once: chart, dashboard rows, interaction and alerts. Detection itself is unchanged.")
 
fvgMinAtr  = input.float(0.10, "FVG minimum gap (× source ATR14)", minval = 0.0, step = 0.05, group = G_DET)
obDispAtr  = input.float(1.0, "OB: displacement body >= × source ATR14", minval = 0.1, step = 0.1, group = G_DET)
obPivLen   = 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)
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.")
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 = G_VIS)
bearCol   = input.color(#ff1744, "Bearish", inline = "c", group = G_VIS)
mitCol    = input.color(#787b86, "Mitigated", inline = "c", group = G_VIS)
fillTr    = input.int(85, "Shading transparency (active)", minval = 50, maxval = 98, group = G_VIS)
txtCol    = input.color(#ffffff, "Label text colour", group = G_VIS)
lblOn     = input.bool(true, "Show zone labels", group = G_VIS)
lblSize   = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = G_VIS)
lblStyle  = input.string("Full", "Label wording", options = ["Full", "Short"], group = G_VIS, tooltip = "Full: 1W BULL FVG · PARTIAL 62%. Short: 1W ▲ FVG · P 62%.")
lblHal    = input.string("Right", "Label position", options = ["Left", "Center", "Right"], inline = "lp", group = G_VIS)
lblVal    = input.string("Center", "", options = ["Top", "Center", "Bottom"], inline = "lp", group = G_VIS)
lblGapAtr = input.float(0.15, "Hide a label when another sits closer than (× chart ATR14)", minval = 0.0, step = 0.01, group = G_VIS, tooltip = "Scale-free: works on DXY (0.001 ticks) and on every chart timeframe. 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 = G_VIS)
mBorderW  = input.int(3, "1M border width", minval = 1, maxval = 4, inline = "bw", group = G_VIS, tooltip = "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)
 
dashOn   = input.bool(true, "Show dashboard", group = G_DSH)
dashLay  = input.string("Full", "Dashboard layout", options = ["Full", "Compact", "Mobile"], group = G_DSH)
dashPosS = input.string("Top Right", "Dashboard position", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Bottom Left"], group = G_DSH)
dashSz   = input.string("Small", "Dashboard text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_DSH)
legOn    = input.bool(true, "Show legend", group = G_DSH)
goldCtx  = input.bool(false, "Gold (MGC) context panel - informational", group = G_DSH, tooltip = "OFF by default. Adds one dashboard row describing where DXY sits relative to its nearest weekly/monthly POI (e.g. approaching a bearish POI = an area to monitor for possible dollar weakness). It never generates gold buy/sell signals, does not assume DXY and gold always move inversely, and does not affect the MGC strategy.")
legPosS  = input.string("Bottom Right", "Legend position", options = ["Top Right", "Middle Right", "Bottom Right", "Top Left", "Bottom Left"], group = G_DSH)
 
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)
apprMode  = input.string("× source ATR14", "Approach distance mode", options = ["× source ATR14", "Absolute DXY points"], group = G_ALR)
apprAtr   = input.float(0.10, "Approach distance (× source ATR14)", minval = 0.01, step = 0.01, group = G_ALR, tooltip = "DXY 1W ATR14 is typically ~1.0-1.6 index points and 1M ~2-3.5, so 0.10 ≈ 0.10-0.16 points for weekly POIs and ≈ 0.2-0.35 for monthly POIs.")
apprAbs   = input.float(0.10, "Approach distance (absolute DXY points)", minval = 0.001, step = 0.01, group = G_ALR, tooltip = "Used when the mode is Absolute DXY points. The Dynamite DXY POI Assistant uses 0.05 for 1H-1D POIs; weekly/monthly zones are wider, so 0.10 is the default here.")
 
// ---- inputs added in version 2 (declared last so v1 chart settings keep their input positions) ----
dOn      = input.bool(true, "Daily (1D) POIs", group = G_SRC)
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); the global FVG / OB switches still apply. 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 = 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  tick   = syminfo.mintick
float  chartAtr = ta.atr(14)
 
apprBand(float atrSrc) =>
    apprMode == "Absolute DXY points" ? apprAbs : nz(atrSrc) * apprAtr
 
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
 
fmtP(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 * fvgMinAtr
        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 * fvgMinAtr
        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, obPivLen, obPivLen)
    float ph = ta.pivothigh(high, obPivLen, obPivLen)
    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] * obDispAtr
            dDn := true
        if not na(a[i]) and -bd >= a[i] * obDispAtr
            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[obPivLen]), sSw.push(na)
    if not na(pl)
        sD.push(-1), sP.push(pl), sT.push(time[obPivLen]), 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) + "|" + str.tostring(bar_index + 1) + "#"
    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
    int   n      // source candles available in the request context (history disclosure)
 
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.n         := f.size() >= 8 ? toint(f.get(7)) : int(na)
    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
 
poiName(WPoi p) =>
    p.tf + " " + (p.dir > 0 ? "BULL" : "BEAR") + " " + (p.kind == K_FVG ? "FVG" : "OB") + (p.wide ? " (WIDE)" : "")
 
poiRange(WPoi p) =>
    fmtP(p.bot) + "–" + fmtP(p.top)
 
isLive(WPoi p) =>
    p.st <= ST_PRT
 
// POI-type visibility: global FVG / OB switches, plus the daily layer's own FVG / OB switches
kindVis(WPoi p) =>
    (p.kind == K_FVG ? showFvg : showOb) and (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 := apprBand(hh.atr)
    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 DXY " + tf + " POI MITIGATED (confirmed " + tf + " close): " + poiName(p) + " " + poiRange(p))
            if o.st != ST_INV and p.st == ST_INV
                evMsg.push("DYNAMITE DXY " + tf + " POI INVALIDATED (confirmed " + tf + " close beyond far edge): " + poiName(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 DXY " + (tf == "1D" ? "1D/HTF" : "1W/1M") + " POI OVERLAP: new " + poiName(p) + " " + poiRange(p) + " overlaps " + poiName(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 = apprBand(hh.atr)
    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, tick)
                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 DXY: ENTERING " + poiName(p) + " " + poiRange(p) + " · " + stTxt(p.st) + " @ " + fmtP(close))
                    p.enterArm := false
                    en := true
                else if not inNow and d <= band and p.apprArm
                    evMsg.push("DYNAMITE DXY: APPROACHING " + poiName(p) + " " + poiRange(p) + " · " + str.tostring(d, format.mintick) + " away @ " + fmtP(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 DXY: approaching a 1D (daily) POI on {{ticker}} @ {{close}}")
alertcondition(evEnterD, "1D POI entered", "DYNAMITE DXY: entered a 1D (daily) POI on {{ticker}} @ {{close}}")
alertcondition(evApprW, "1W POI approaching", "DYNAMITE DXY: approaching a 1W POI on {{ticker}} @ {{close}}")
alertcondition(evEnterW, "1W POI entered", "DYNAMITE DXY: entered a 1W POI on {{ticker}} @ {{close}}")
alertcondition(evApprM, "1M POI approaching", "DYNAMITE DXY: approaching a 1M (monthly) POI on {{ticker}} @ {{close}}")
alertcondition(evEnterM, "1M POI entered", "DYNAMITE DXY: entered a 1M (monthly) POI on {{ticker}} @ {{close}}")
alertcondition(evMit, "D/W/M POI mitigated", "DYNAMITE DXY: a 1D / 1W / 1M POI was mitigated (confirmed source close) on {{ticker}}")
alertcondition(evInv, "D/W/M POI invalidated", "DYNAMITE DXY: a 1D / 1W / 1M POI was invalidated (confirmed source close beyond far edge) on {{ticker}}")
alertcondition(evOvl, "POI confluence (overlap)", "DYNAMITE DXY: 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" ? poiName(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<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()
    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) < lblGapAtr * nz(chartAtr)
                near := true
        bool  showL = lblOn and not near
        if showL
            lblMid.push(mid)
        int left = math.max(p.tS, firstT)
        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 ? lblText(p, liveOk) : "", text_size = szOf(lblSize), text_color = color.new(txtCol, 0), text_halign = hal, text_valign = val)
        boxes.push(bx)
    // ---- 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 ") + fmtP(s.px) : tf + (s.dir > 0 ? " SWING H " : " SWING L ") + fmtP(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 " + fmtP(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 " + fmtP(hh.lo), xloc = xloc.bar_time, style = label.style_none, textcolor = color.new(txtCol, 0), size = szOf(lblSize)))
 
// =====================================================================================
// DASHBOARD + LEGEND (latest bar only)
// =====================================================================================
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"))
 
var table dash = na
var table leg  = na
if barstate.islast
    color hdrC = color.new(#131722, 10)
    color keyC = color.new(#d1d4dc, 0)
    color offC = color.new(#9598a1, 0)
    if dashOn
        bool full = dashLay == "Full"
        bool mob  = dashLay == "Mobile"
        int  rows = full ? 17 : mob ? 10 : 13
        if na(dash)
            dash := table.new(posOf(dashPosS), 2, rows, bgcolor = color.new(#0b0e14, 5), frame_color = color.new(#787b86, 40), frame_width = 1, border_color = color.new(#787b86, 75), border_width = 1)
        table.clear(dash, 0, 0, 1, rows - 1)
        string tsz = mob and dashSz == "Small" ? size.normal : szOf(dashSz)
        bool  cmp = not full
        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
        // interaction + nearest zone overall
        string inter = "outside all D/W/M POIs"
        color  interC = offC
        WPoi   nz0 = na
        float  nd0 = na
        int interRk = 0     // 3 live (ACTIVE/TOUCHED/PARTIAL) > 2 MITIGATED > 1 INVALIDATED (only if shown)
        int interN  = 0
        for tfI = 0 to 2
            for p in (tfI == 0 ? mP : tfI == 1 ? wP : dP)
                float d = distTo(p)
                if p.st <= ST_PRT and kindVis(p) and (na(nd0) or d < nd0)
                    nd0 := d
                    nz0 := p
                int rk = not kindVis(p) ? 0 : p.st <= ST_PRT ? 3 : p.st == ST_MIT ? 2 : (p.tf == "1D" ? dShowInv : showInv) ? 1 : 0
                if d == 0 and rk > 0
                    interN += 1
                    if rk > interRk
                        interRk := rk
                        bool liveOk = p.tf == "1W" ? wLiveOk : p.tf == "1M" ? mLiveOk : dLiveOk
                        string pct = p.st == ST_TCH or p.st == ST_PRT ? " " + str.tostring(math.round(p.fill)) + "%" : ""
                        string lv  = rk == 3 and liveOk and p.live > p.fill ? " · live " + str.tostring(math.round(p.live)) + "%" : ""
                        inter  := mob ? "IN " + p.tf + (p.dir > 0 ? " ▲ " : " ▼ ") + (p.kind == K_FVG ? "FVG" : "OB") + " · " + stShort(p.st) + pct : "INSIDE " + poiName(p) + " — " + stTxt(p.st) + pct + lv
                        interC := rk == 3 ? (p.dir > 0 ? bullCol : bearCol) : rk == 2 ? mitCol : offC
        if interN > 1
            inter += " (+" + str.tostring(interN - 1) + ")"
        int r = 0
        table.cell(dash, 0, r, mob ? "DXY D/W/M" : "DYNAMITE DXY D/W/M POI", text_color = color.white, text_size = tsz, text_halign = text.align_left, text_formatting = text.format_bold)
        table.cell(dash, 1, r, fmtP(close), text_color = color.white, text_size = tsz, text_halign = text.align_right, text_formatting = text.format_bold)
        r += 1
        if full
            table.cell(dash, 0, r, "1W context", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, wOn ? ctxTxt(wH, wP, "1W") : "off", text_color = offC, text_size = tsz, text_halign = text.align_left)
            r += 1
            table.cell(dash, 0, r, "1M context", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, mOn ? ctxTxt(mH, mP, "1M") : "off", text_color = offC, text_size = tsz, text_halign = text.align_left)
            r += 1
            table.cell(dash, 0, r, "1D context", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, dOn ? ctxTxt(dH, dP, "1D") : "off", text_color = offC, text_size = tsz, text_halign = text.align_left)
            r += 1
        table.cell(dash, 0, r, mob ? "W ▲" : "1W bull (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, wOn ? poiCell(wb, cmp) : "off", text_color = na(wb) ? offC : bullCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "W ▼" : "1W bear (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, wOn ? poiCell(wr, cmp) : "off", text_color = na(wr) ? offC : bearCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "M ▲" : "1M bull (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, mOn ? poiCell(mb, cmp) : "off", text_color = na(mb) ? offC : bullCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "M ▼" : "1M bear (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, mOn ? poiCell(mr, cmp) : "off", text_color = na(mr) ? offC : bearCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "D ▲" : "1D bull (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, dOn ? poiCell(db, cmp) : "off", text_color = na(db) ? offC : bullCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "D ▼" : "1D bear (nearest)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, dOn ? poiCell(dr, cmp) : "off", text_color = na(dr) ? offC : bearCol, text_size = tsz, text_halign = text.align_left)
        r += 1
        table.cell(dash, 0, r, mob ? "Now" : "Interaction", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, inter, text_color = interC, text_size = tsz, text_halign = text.align_left)
        r += 1
        if not mob
            table.cell(dash, 0, r, "Nearest zone", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, na(nz0) ? "—" : poiName(nz0) + " · " + (nd0 == 0 ? "IN" : str.tostring(nd0, format.mintick) + " pts"), text_color = na(nz0) ? offC : color.white, text_size = tsz, text_halign = text.align_left)
            r += 1
        if full
            table.cell(dash, 0, r, "Confirmed (close)", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            // time_close of the last CLOSED source candle, minus 1 ms so the date is the last session day of that
            // candle (not the next calendar day). 'wk of' = the week's opening session day (open time + 12 h).
            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.asOf + 12 * 3600000, "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")
            table.cell(dash, 1, r, dA + " · " + wA + " · " + mA, text_color = offC, text_size = tsz, text_halign = text.align_left)
            r += 1
        color warnC = color.new(#ff9800, 0)
        if not mob
            string dw = ""
            if wOn and na(wH.n)
                dw += " · no 1W data"
            else if wOn and wH.n < 60
                dw += " · short 1W history"
            if dOn and (na(dH.n) or dH.n < 60)
                dw += " · short 1D history"
            if mOn and (na(mH.n) or mH.n < 30)
                dw += " · short 1M history (monthly POIs limited)"
            if symIn != "" and symIn != syminfo.prefix + ":" + syminfo.ticker
                dw += " · data feed ≠ chart feed"
            if not str.contains(syminfo.ticker, "DX")
                dw += " · chart is not DXY"
            table.cell(dash, 0, r, "Data", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, poiSym + " · 1D " + (na(dH.n) ? "n/a" : str.tostring(dH.n)) + " · 1W " + (na(wH.n) ? "n/a" : str.tostring(wH.n)) + " · 1M " + (na(mH.n) ? "n/a" : str.tostring(mH.n)) + " candles" + dw, text_color = dw == "" ? offC : warnC, text_size = tsz, text_halign = text.align_left)
            r += 1
        if goldCtx
            string g = "DXY not near a 1W / 1M POI"
            if not na(nz0)
                float gb = nz0.tf == "1D" ? apprBand(dH.atr) : nz0.tf == "1W" ? apprBand(wH.atr) : apprBand(mH.atr)
                if nd0 <= gb
                    string wh = (nd0 == 0 ? "inside " : "approaching ") + poiName(nz0)
                    g := nz0.dir < 0 ? (mob ? "USD-weakness watch · " + nz0.tf + " ▼" : "DXY " + wh + " → area to monitor for possible dollar weakness (MGC may find support - not guaranteed)") : (mob ? "USD-strength watch · " + nz0.tf + " ▲" : "DXY " + wh + " → area to monitor for possible dollar strength (MGC may face pressure - not guaranteed)")
            table.cell(dash, 0, r, mob ? "Gold" : "Gold context", text_color = keyC, text_size = tsz, text_halign = text.align_left)
            table.cell(dash, 1, r, g + (mob ? "" : " · informational, not a gold signal"), text_color = offC, text_size = tsz, text_halign = text.align_left)
            r += 1
        table.cell(dash, 0, r, mob ? "" : "Note", text_color = keyC, text_size = tsz, text_halign = text.align_left)
        table.cell(dash, 1, r, "context only · not a trade signal", text_color = offC, text_size = tsz, text_halign = text.align_left)
    if legOn
        if na(leg)
            leg := table.new(posOf(legPosS), 1, 4, bgcolor = color.new(#0b0e14, 15), frame_color = color.new(#787b86, 60), frame_width = 1)
        string lsz = szOf(dashSz == "Large" ? "Normal" : "Tiny")
        table.cell(leg, 0, 0, "▮ bull   ▮ bear   ▮ mitigated", text_color = color.white, text_size = lsz, text_halign = text.align_left)
        table.cell_set_text_color(leg, 0, 0, color.white)
        table.cell(leg, 0, 1, "1D thin · 1W medium · 1M thick border", text_color = color.white, text_size = lsz, text_halign = text.align_left)
        table.cell(leg, 0, 2, "FVG = dashed · OB = solid · invalid = dotted", text_color = color.white, text_size = lsz, text_halign = text.align_left)
        table.cell(leg, 0, 3, "live % = unconfirmed (since last D/W/M close)", text_color = color.white, text_size = lsz, text_halign = text.align_left)
 
// =====================================================================================
// 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)

← 返回列表