Confluence HUD

Armenzh · study · 1474 行 · 点赞 8 · 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/
// © Armenzh
 
//@version=6
// ============================================================================
// CONFLUENCE HUD v1.1 — indicator only (places no orders)
// Scores C1..C6 on every bar and assigns a tier: C (0-1), B (2-3), A+ (4), A+++ (5-6).
// The tier is a COUNT of conditions met, not a probability or a validated edge.
//
// C1 Macro:        PDH/PDL, PWH/PWL, PMH/PML and W/D/H4 FVGs. Only the FIRST touch
//                  counts (mitigation); after that the level is spent until its period
//                  rolls over.
// C2 Session:      Asia, London and NY (09:30-11:00) highs/lows, frozen when each
//                  session ends. First touch only, same rule as C1.
// C3 FVG:          chart-timeframe FVG (designed for M15). On while a 2-bar "possible"
//                  FVG awaits confirmation, or while the FVG nearest to price is still
//                  unmitigated.
// C4 Delta:        normalized |volume delta| smaller than the previous bar's (fading).
//                  Real lower-timeframe delta, with a body x volume proxy where no
//                  intrabar history exists.
// C5 Displacement: distance from price to the last opposite Williams fractal >= threshold
//                  (ATR multiple by default). Retracements do not invalidate it.
// C6 News:         no high-impact USD event inside the blocking window (-60/+15 min).
//
// Credits:
//   - News: Forex Factory data via Pine Seeds and the forex_factory_utility /
//     forex_factory_decoding libraries by toodegrees.
//   - Volume delta: TradingView's official `ta` library (requestVolumeDelta).
//   - Fractal detection: logic of TradingView's built-in Williams Fractals indicator.
// ============================================================================
indicator("Confluence HUD v1", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500,
     max_bars_back = 600)
 
// Forex Factory news via Pine Seeds (toodegrees) — automatic C6
import toodegrees/forex_factory_utility/17 as ffUtil
import toodegrees/forex_factory_decoding/44 as ffDec
// Real volume delta (same engine as TradingView's "Volume Delta" indicator) — C4
import TradingView/ta/12 as tvta
 
// ==================== INPUTS ====================
gAudit = "Audit"
i_auditMode = input.string("Off", "Audit mode", options = ["Off", "C1", "C2", "C3", "C4", "C5"], group = gAudit,
     tooltip = "Shows the internals of one condition on the chart and in the table. C1 = macro levels. C2 = session levels. C3 = FVGs. C4 = volume delta. C5 = fractals / displacement. Off = normal HUD.")
i_mitHide   = input.bool(false, "Hide mitigated levels (off = dim them)", group = gAudit)
 
bool audC1  = i_auditMode == "C1"
bool audC2  = i_auditMode == "C2"
bool audC3  = i_auditMode == "C3"
bool audC4  = i_auditMode == "C4"
bool audC5  = i_auditMode == "C5"
bool audOff = i_auditMode == "Off"
 
gTouch = "Touch definition"
i_touchLookback = input.int(3, "Touch lookback (bars)", minval = 1, maxval = 20, group = gTouch,
     tooltip = "A touch is EXACT: price must sweep the level (high >= level / low <= level), no tolerance. The first touch keeps C1/C2 on for this many bars.")
 
gC1 = "C1 - Macro levels"
i_useC1      = input.bool(true, "Evaluate C1", group = gC1)
i_showMacro  = input.bool(true, "Draw PDH/PDL/PWH/PWL/PMH/PML lines", group = gC1)
i_showHtfFvg = input.bool(true, "Draw W/D/H4 FVGs", group = gC1)
ZS_1 = "1st bar of the pattern (leftmost)"
ZS_2 = "2nd bar (the gap bar)"
ZS_3 = "3rd bar (the confirming bar)"
i_htfZoneStart = input.string(ZS_3, "Left edge of HTF zones", options = [ZS_1, ZS_2, ZS_3], group = gC1,
     tooltip = "A 3-bar FVG spans bars [3] to [1]. On an M15 chart the 1st bar of a WEEKLY FVG is about 3 weeks back, off screen. The 3rd (confirming) bar is the closest one.")
i_htfFvgMax  = input.int(6, "Max FVGs tracked per timeframe", minval = 1, maxval = 20, group = gC1)
i_mitPurgeBars = input.int(4, "Delete mitigated FVG after N bars", minval = 1, maxval = 500, group = gC1,
     tooltip = "A touched FVG stays gray for this many bars and is then deleted. All mitigated FVGs are also deleted at the daily rollover (18:00 NY on CME futures).")
 
gC2 = "C2 - Session levels"
i_useC2      = input.bool(true, "Evaluate C2", group = gC2)
i_sessAsia   = input.session("2000-0000", "Asia (NY time)", group = gC2)
i_sessLondon = input.session("0200-0500", "London (NY time)", group = gC2)
i_sessNY     = input.session("0930-1100", "New York (NY time)", group = gC2)
i_showSess   = input.bool(true, "Draw session levels", group = gC2)
i_boxAsia    = input.bool(true, "ASIA session box", group = gC2)
i_boxLon     = input.bool(true, "LONDON session box", group = gC2)
i_boxNY      = input.bool(true, "NY session box", group = gC2)
i_boxTrans   = input.int(95, "Box FILL transparency", minval = 50, maxval = 99, group = gC2)
i_boxBorder  = input.int(95, "Box BORDER transparency", minval = 0, maxval = 100, group = gC2,
     tooltip = "100 = invisible border. At 95 it is barely visible and only the fill remains.")
 
gC3 = "C3 - FVG (chart timeframe)"
i_useC3      = input.bool(true, "Evaluate C3", group = gC3)
// FVG size filter: fixed points, % of ATR, or both. ATR % adapts across symbols
// (NQ, ES, YM...) and volatility regimes without manual recalibration.
FVGF_NONE = "None"
FVGF_MIN  = "Min Size"
FVGF_ATR  = "ATR %"
FVGF_BOTH = "Both"
i_fvgFilterMode = input.string(FVGF_ATR, "FVG size filter", options = [FVGF_NONE, FVGF_MIN, FVGF_ATR, FVGF_BOTH], group = gC3,
     tooltip = "Min Size = fixed points (does not adapt across symbols). ATR % = fraction of ATR, self-calibrates per symbol and volatility regime. Both = requires both.")
i_minGap     = input.float(15, "Minimum FVG size (points)", minval = 0, step = 1, group = gC3)
i_minGapAtrPct = input.float(24.0, "Minimum FVG size (% of ATR)", minval = 0, step = 0.5, group = gC3,
     tooltip = "Example: with an ATR of 62 points, 24% is about 15 points.")
i_fvgAtrLen  = input.int(14, "ATR length (FVG filter)", minval = 1, maxval = 200, group = gC3,
     tooltip = "Also used for the drawing window and the audit bands.")
i_fvgSess    = input.session("0700-1500", "FVG detection window (NY time)", group = gC3,
     tooltip = "Also used as the trading window for alerts.")
i_showM15Fvg = input.bool(true, "Draw active FVGs", group = gC3)
i_m15FvgMax  = input.int(10, "Max FVGs tracked", minval = 1, maxval = 40, group = gC3)
i_m15TodayOnly = input.bool(true, "Current trading day only (wiped at the daily rollover)", group = gC3,
     tooltip = "Active FVGs from previous days are dropped at the daily rollover (18:00 NY on CME futures). Without this, a month-old unfilled gap would still count for C3.")
i_c3NearestOnly = input.bool(true, "C3 counts only if the NEAREST FVG is still active", group = gC3,
     tooltip = "If the FVG closest to price has been mitigated, C3 turns off even if other active FVGs remain further away. Note: once that mitigated FVG is purged, the next one becomes the nearest.")
 
gC4 = "C4 - Volume delta"
MODE_REAL  = "Real (proxy fallback without history)"
MODE_PROXY = "Proxy (body x volume)"
MODE_OFF   = "Off (always false)"
i_useC4     = input.bool(true, "Evaluate C4", group = gC4)
i_deltaMode = input.string(MODE_REAL, "Delta mode", options = [MODE_REAL, MODE_PROXY, MODE_OFF], group = gC4,
     tooltip = "Real uses requestVolumeDelta (same engine as TradingView's Volume Delta indicator). Where no lower-timeframe history exists it falls back to the proxy automatically, so older history and recent bars may use different sources.")
i_deltaLtf  = input.timeframe("1", "Lower timeframe for real delta", group = gC4)
i_deltaNormLen = input.int(50, "Delta normalization window (bars)", minval = 5, maxval = 500, group = gC4,
     tooltip = "Each source (real and proxy) is divided by its own moving scale before comparing, so net contracts are never compared against volume x body.")
 
gC5 = "C5 - Displacement"
i_useC5      = input.bool(true, "Evaluate C5", group = gC5)
MODE_PTS = "Fixed points"
MODE_ATR = "ATR multiple"
i_dispMode   = input.string(MODE_ATR, "Displacement threshold in", options = [MODE_PTS, MODE_ATR], group = gC5,
     tooltip = "Fixed points do not adapt to volatility: 250 points is a lot in a quiet market and little in an expanded one. With ATR the threshold recalibrates itself.")
i_dispPts    = input.float(250, "Minimum displacement (points)", minval = 1, step = 5, group = gC5,
     tooltip = "Used only in 'Fixed points' mode.")
i_dispAtrMult= input.float(3.0, "Minimum displacement (x ATR)", minval = 0.1, step = 0.1, group = gC5,
     tooltip = "Used only in 'ATR multiple' mode. Example: with an ATR of 62 points, 3.0x is about 187 points and 4.0x about 250.")
i_atrLen     = input.int(14, "ATR length", minval = 1, maxval = 200, group = gC5)
i_atrTf      = input.timeframe("", "ATR timeframe (empty = chart)", group = gC5)
i_fracLen    = input.int(2, "Fractal strength (bars per side)", minval = 1, maxval = 10, group = gC5,
     tooltip = "A fractal is confirmed this many bars after its pivot bar, and its marker is drawn back on the pivot bar.")
i_c5FlipBroken = input.bool(true, "If price breaks the last fractal, use the previous opposite one", group = gC5,
     tooltip = "Last = LOW and price closes below it -> measure from the last HIGH (and vice versa). Without this the distance turns negative and C5 cannot fire even after a large move.")
 
gC6 = "C6 - News"
i_useC6     = input.bool(true, "Evaluate C6", group = gC6)
i_autoNews  = input.bool(true, "Automatic news (Forex Factory: USD, high impact)", group = gC6,
     tooltip = "Uses toodegrees' Pine Seeds feed. Only high-impact (red) USD events. The manual list below is added on top. Until the feed loads (first weekly rollover in the chart's history), C6 does not score.")
i_newsList  = input.text_area("", "Extra high-impact events (one per line: YYYY-MM-DD HH:MM, NY time)", group = gC6)
i_preMin    = input.int(60, "Block before (min)", minval = 0, group = gC6)
i_postMin   = input.int(15, "Block after (min)", minval = 0, group = gC6)
i_shadeNews = input.bool(true, "Shade the blocking window (gray)", group = gC6)
i_newsMed   = input.bool(true, "Flag medium-impact (orange) news as a warning", group = gC6,
     tooltip = "Orange band only: does NOT block and does NOT affect C6. A heads-up only; blocking still uses high-impact events.")
 
gAlert = "Alerts"
i_alOnlySess = input.bool(true, "Alert only inside the trading window", group = gAlert,
     tooltip = "Uses the FVG detection window (default 07:00-15:00 NY). Avoids overnight alerts.")
i_alC1     = input.bool(false, "Macro level alert (C1)", group = gAlert)
i_alC2     = input.bool(false, "Session level alert (C2)", group = gAlert)
i_alC3     = input.bool(false, "FVG alert (C3)", group = gAlert,
     tooltip = "C3 is on for a large share of bars, so this alert is noisy.")
i_alC4     = input.bool(false, "Fading delta alert (C4)", group = gAlert,
     tooltip = "C4 compares each bar with the previous one, so by construction it is true on roughly half of all bars. The noisiest alert.")
i_alC5     = input.bool(false, "Displacement alert (C5)", group = gAlert)
i_alTierA3 = input.bool(true,  "Tier A+++ alert", group = gAlert)
i_alTierA1 = input.bool(true,  "Tier A+ alert", group = gAlert)
i_alNews   = input.bool(true,  "Upcoming high-impact news alert", group = gAlert)
 
gOpen = "Opens (WO / DO / OP)"
i_showWO = input.bool(true, "WO - Weekly Open (Monday 00:00 NY, kept until Friday 18:00 NY)", group = gOpen)
i_showDO = input.bool(true, "DO - Daily Open (00:00 NY; hidden on Mondays, where it equals WO)", group = gOpen)
i_showOP = input.bool(true, "OP - Opening Print (09:30 NY, cleared at the daily rollover)", group = gOpen)
 
gHud = "HUD"
i_showTable = input.bool(true, "Show table", group = gHud)
i_tblSize   = input.string("Normal", "Table font size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = gHud)
i_colorBars = input.bool(true, "Highlight FVG signal bars with tier A+ or higher", group = gHud)
// Fixed points do not adapt across instruments: 600 points is a small move on NQ and a
// large one on ES. What expands the auto-scale is drawing an object AT that price, so the
// range mode limits drawing, and levels left out are still listed in the table.
PLOT_FIXED = "Fixed points"
PLOT_RANGE = "Recent range + ATR margin"
i_plotMode  = input.string(PLOT_RANGE, "Drawing filter", options = [PLOT_RANGE, PLOT_FIXED], group = gHud)
i_maxPlotDist = input.float(600, "Only draw levels/zones within X points of price", minval = 0, step = 50, group = gHud,
     tooltip = "Used only in 'Fixed points' mode. Scoring always considers every level; this is visual only.")
i_plotLookback  = input.int(10, "Recent range: reference bars", minval = 10, maxval = 1000, group = gHud,
     tooltip = "A fixed number of bars, NOT what is visible on screen; zooming does not change the filter. With a short lookback the window is mostly a band of +-N x ATR around recent price.")
i_plotMarginAtr = input.float(3.0, "Margin beyond the range (x ATR)", minval = 0, step = 0.5, group = gHud,
     tooltip = "How far drawing may extend beyond the recent high/low, in ATR so it behaves the same on NQ, ES or YM. Levels outside the window are listed in the table (LIQ rows) with their distance.")
 
NY = "America/New_York"
string tblSz = i_tblSize == "Tiny" ? size.tiny : i_tblSize == "Small" ? size.small : i_tblSize == "Normal" ? size.normal : i_tblSize == "Large" ? size.large : size.huge
// How far back a drawing may start. Must stay well below max_bars_back (600) so no
// offset beyond the historical buffer is ever requested.
int DRAW_MAX_BACK = 450
bool showSessEff = i_showSess and (audOff or audC2)
bool showMacroEff = i_showMacro and (audOff or audC1)
bool showHtfEff  = i_showHtfFvg and (audOff or audC1)
bool showM15Eff  = i_showM15Fvg and (audOff or audC3)
 
// drawing window: recent high/low stretched by N x ATR
float plotAtr = ta.atr(i_fvgAtrLen)[1]
float plotMrg = na(plotAtr) ? 0.0 : plotAtr * i_plotMarginAtr
float plotHi  = ta.highest(high, i_plotLookback) + plotMrg
float plotLo  = ta.lowest(low, i_plotLookback)  - plotMrg
 
// visual helper: true if the level falls inside the drawing window (or the filter is off)
nearLvl(float lvl) =>
    i_plotMode == PLOT_FIXED ? (i_maxPlotDist <= 0 or math.abs(lvl - close) <= i_maxPlotDist) : (lvl >= plotLo and lvl <= plotHi)
 
// ==================== C1: MACRO LEVELS (with mitigation) ====================
// [1] + lookahead_on = previous COMPLETED higher-timeframe bar: no future data leaks.
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pmh, pml] = request.security(syminfo.tickerid, "M", [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
bool newD = timeframe.change("D")
bool newW = timeframe.change("W")
bool newM = timeframe.change("M")
 
// first bar of each period (the level is drawn only over its own period)
var int dStartBar = 0
var int wStartBar = 0
var int mStartBar = 0
if newD
    dStartBar := bar_index
if newW
    wStartBar := bar_index
if newM
    mStartBar := bar_index
 
// Audit drawings (✗ labels and highlight bands) are registered here and ALL deleted
// at the daily rollover (new trading day).
var audLabels = array.new_label()
var audBands  = array.new_box()
if newD
    if audLabels.size() > 0
        for lb in audLabels
            label.delete(lb)
        audLabels.clear()
    if audBands.size() > 0
        for bx in audBands
            box.delete(bx)
        audBands.clear()
 
// Per-level state: mitBar = bar of the FIRST touch (na = untouched).
// The touch counts only during the i_touchLookback bars that follow it.
levelState(float lvl, bool isHigh, bool newPeriod) =>
    var int mitBar = na
    if newPeriod
        mitBar := na
    bool hitNow = not na(lvl) and (isHigh ? high >= lvl : low <= lvl)
    if na(mitBar) and hitNow
        mitBar := bar_index
    bool fresh = not na(mitBar) and bar_index - mitBar < i_touchLookback
    [mitBar, fresh]
 
[pdhMit, pdhFresh] = levelState(pdh, true,  newD)
[pdlMit, pdlFresh] = levelState(pdl, false, newD)
[pwhMit, pwhFresh] = levelState(pwh, true,  newW)
[pwlMit, pwlFresh] = levelState(pwl, false, newW)
[pmhMit, pmhFresh] = levelState(pmh, true,  newM)
[pmlMit, pmlFresh] = levelState(pml, false, newM)
 
// --- HTF FVGs (3-bar) on confirmed HTF bars, with mitigation state ---
htfData(string tf) =>
    request.security(syminfo.tickerid, tf, [time[1], high[1], low[1], high[3], low[3], time[3], time[2]], lookahead = barmerge.lookahead_on)
 
var wFvgBot = array.new_float()
var wFvgTop = array.new_float()
var wFvgDir = array.new_int()
var wFvgMit = array.new_int()
var dFvgBot = array.new_float()
var dFvgTop = array.new_float()
var dFvgDir = array.new_int()
var dFvgMit = array.new_int()
var hFvgBot = array.new_float()
var hFvgTop = array.new_float()
var hFvgDir = array.new_int()
var hFvgMit = array.new_int()
 
// Returns [anyFresh, anchorT]
//   anyFresh = some zone of this timeframe has a fresh first touch (inside the lookback)
//   anchorT  = left-edge time of the most recently confirmed zone; every zone of this
//              timeframe is drawn from there (common left edge)
procHtf(string tf, array<float> bots, array<float> tops, array<int> dirs, array<int> mits, string tag) =>
    [t1, h1, l1, h3, l3, t3, t2] = htfData(tf)
    // left edge chosen by input: [3] = 1st bar of the pattern, [1] = confirming bar
    int tStart = i_htfZoneStart == ZS_1 ? t3 : i_htfZoneStart == ZS_2 ? t2 : t1
    var float lastT = na
    var int anchorT = na
    bool isNew = not na(t1) and (na(lastT) or t1 != lastT)
    if isNew
        lastT := t1
        if l1 > h3 // bullish FVG: gap [h3, l1]
            bots.push(h3)
            tops.push(l1)
            dirs.push(1)
            mits.push(int(na))
            anchorT := tStart
        if h1 < l3 // bearish FVG: gap [h1, l3]
            bots.push(h1)
            tops.push(l3)
            dirs.push(-1)
            mits.push(int(na))
            anchorT := tStart
        while bots.size() > i_htfFvgMax
            bots.shift()
            tops.shift()
            dirs.shift()
            mits.shift()
    bool anyFresh = false
    if bots.size() > 0
        for j = bots.size() - 1 to 0
            int mb = mits.get(j)
            if na(mb)
                // first touch of the zone = mitigation
                if high >= bots.get(j) and low <= tops.get(j)
                    mits.set(j, bar_index)
                    mb := bar_index
                    if audC1
                        audLabels.push(label.new(bar_index, dirs.get(j) == 1 ? tops.get(j) : bots.get(j), tag + " ✗", style = label.style_label_left, color = color.new(color.gray, 30), textcolor = color.white, size = size.tiny))
            if not na(mb) and bar_index - mb < i_touchLookback
                anyFresh := true
            // purge: N bars after the touch, or at the daily rollover
            if not na(mb) and (bar_index - mb > i_mitPurgeBars or newD)
                bots.remove(j)
                tops.remove(j)
                dirs.remove(j)
                mits.remove(j)
    [anyFresh, anchorT]
 
[hFresh, hAnchorT] = procHtf("240", hFvgBot, hFvgTop, hFvgDir, hFvgMit, "H4 FVG")
[dFresh, dAnchorT] = procHtf("D",   dFvgBot, dFvgTop, dFvgDir, dFvgMit, "D FVG")
[wFresh, wAnchorT] = procHtf("W",   wFvgBot, wFvgTop, wFvgDir, wFvgMit, "W FVG")
 
bool c1LevelFresh = pdhFresh or pdlFresh or pwhFresh or pwlFresh or pmhFresh or pmlFresh
bool c1ZoneFresh  = wFresh or dFresh or hFresh
bool C1 = i_useC1 and (c1LevelFresh or c1ZoneFresh)
 
// ==================== C2: SESSION LEVELS ====================
inAsia   = not na(time(timeframe.period, i_sessAsia,   NY))
inLondon = not na(time(timeframe.period, i_sessLondon, NY))
inNYs    = not na(time(timeframe.period, i_sessNY,     NY))
 
var float asiaH = na
var float asiaL = na
var float asiaHp = na
var float asiaLp = na
var float lonH = na
var float lonL = na
var float lonHp = na
var float lonLp = na
var float nyH = na
var float nyL = na
var float nyHp = na
var float nyLp = na
 
if inAsia
    if not inAsia[1]
        asiaH := high
        asiaL := low
    else
        asiaH := math.max(asiaH, high)
        asiaL := math.min(asiaL, low)
if not inAsia and inAsia[1]
    asiaHp := asiaH
    asiaLp := asiaL
 
if inLondon
    if not inLondon[1]
        lonH := high
        lonL := low
    else
        lonH := math.max(lonH, high)
        lonL := math.min(lonL, low)
if not inLondon and inLondon[1]
    lonHp := lonH
    lonLp := lonL
 
if inNYs
    if not inNYs[1]
        nyH := high
        nyL := low
    else
        nyH := math.max(nyH, high)
        nyL := math.min(nyL, low)
if not inNYs and inNYs[1]
    nyHp := nyH
    nyLp := nyL
 
// --- SESSION BOXES: time range x price range, on top of the H/L lines.
// They grow while the session is open and freeze when it closes. Deleted at the daily
// rollover, like the levels.
var box asiaBox = na
var box lonBox  = na
var box nyBox   = na
 
sessBox(bool inSess, bool started, bool show, box bx, float h, float l, color c, string tag) =>
    box out = bx
    if not show
        if not na(out)
            box.delete(out)
            out := na
    else if inSess and not na(h) and not na(l)
        if started or na(out)
            if not na(out)
                box.delete(out)
            out := box.new(bar_index, h, bar_index, l, border_color = color.new(c, i_boxBorder), bgcolor = color.new(c, i_boxTrans), text = tag, text_color = color.new(c, 15), text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_top)
        else
            box.set_top(out, h)
            box.set_bottom(out, l)
            box.set_right(out, bar_index)
    out
 
bool showBoxEff = audOff or audC2
asiaBox := sessBox(inAsia,   inAsia   and not inAsia[1],   i_boxAsia and showBoxEff, asiaBox, asiaH, asiaL, color.red,  "ASIA")
lonBox  := sessBox(inLondon, inLondon and not inLondon[1], i_boxLon  and showBoxEff, lonBox,  lonH,  lonL,  color.blue, "LON")
nyBox   := sessBox(inNYs,    inNYs    and not inNYs[1],    i_boxNY   and showBoxEff, nyBox,   nyH,   nyL,   color.green, "NY")
 
// Daily wipe: at the daily rollover (new trading day) every session level of the
// previous day is cleared; they reappear as each session completes.
// IMPORTANT: runs BEFORE the use* values are computed, so the rollover bar does not
// evaluate touches against yesterday's levels.
if newD
    asiaHp := na
    asiaLp := na
    lonHp := na
    lonLp := na
    nyHp := na
    nyLp := na
    // boxes go with the same wipe as the levels
    if not na(asiaBox)
        box.delete(asiaBox)
        asiaBox := na
    if not na(lonBox)
        box.delete(lonBox)
        lonBox := na
    if not na(nyBox)
        box.delete(nyBox)
        nyBox := na
 
float useAsiaH = inAsia ? na : asiaHp
float useAsiaL = inAsia ? na : asiaLp
float useLonH  = inLondon ? na : lonHp
float useLonL  = inLondon ? na : lonLp
float useNyH   = inNYs ? na : nyHp
float useNyL   = inNYs ? na : nyLp
 
// moment each session freezes its levels (a new level is born)
bool asiaFroze = not inAsia and inAsia[1]
bool lonFroze  = not inLondon and inLondon[1]
bool nyFroze   = not inNYs and inNYs[1]
 
var int asiaStartBar = 0
var int lonStartBar = 0
var int nyStartBar = 0
if asiaFroze
    asiaStartBar := bar_index
if lonFroze
    lonStartBar := bar_index
if nyFroze
    nyStartBar := bar_index
 
// same semantics as C1: only the FIRST touch + lookback counts; then the level is spent
// (the state also resets with the daily wipe)
[ashMit, ashFresh] = levelState(useAsiaH, true,  asiaFroze or newD)
[aslMit, aslFresh] = levelState(useAsiaL, false, asiaFroze or newD)
[lnhMit, lnhFresh] = levelState(useLonH,  true,  lonFroze or newD)
[lnlMit, lnlFresh] = levelState(useLonL,  false, lonFroze or newD)
[nyhMit, nyhFresh] = levelState(useNyH,   true,  nyFroze or newD)
[nylMit, nylFresh] = levelState(useNyL,   false, nyFroze or newD)
 
bool C2 = i_useC2 and (ashFresh or aslFresh or lnhFresh or lnlFresh or nyhFresh or nylFresh)
 
// ==================== C3: FVG (possible -> confirmed lifecycle) ====================
// Stage 1 (bar 2, "possible FVG"): any bar 1; bar 2 moves IN DIRECTION and closes at
//   least the minimum gap beyond bar 1's extreme.
// Stage 2 (bar 3): if bar 3 does NOT fill the possible FVG, the 3-bar FVG is confirmed
//   with zone [high bar 1, low bar 3] (bull) / [high bar 3, low bar 1] (bear).
//   If bar 3 fills it, the possible FVG dies without leaving a zone.
// Mitigation of a confirmed FVG: TOUCH of the near edge (a full fill is not required).
// Detection runs ONLY inside the time window (default 07:00-15:00 NY).
bool inFvgSess  = not na(time(timeframe.period, i_fvgSess, NY))
// ATR of the CLOSED bar: with the live bar's ATR the threshold would move intrabar and
// the FVG could appear/disappear within the same bar.
float fvgAtr     = ta.atr(i_fvgAtrLen)[1]
float minAtrSize = na(fvgAtr) ? 0.0 : (i_minGapAtrPct / 100.0) * fvgAtr
gapPasses(float sz) =>
    bool passMin = sz >= i_minGap
    bool passAtr = sz >= minAtrSize
    i_fvgFilterMode == FVGF_NONE ? true : i_fvgFilterMode == FVGF_MIN ? passMin : i_fvgFilterMode == FVGF_ATR ? passAtr : (passMin and passAtr)
 
bool newBullFvg = close > open and gapPasses(close - high[1])
bool newBearFvg = close < open and gapPasses(low[1] - close)
 
var m15Bot = array.new_float()
var m15Top = array.new_float()
var m15Dir = array.new_int()
var m15Mit = array.new_int()
var m15Born = array.new_int()
var m15Box = array.new_box()
 
color M15_BULL = color.new(color.red, 0)    // bull FVG => fade SHORT (red)
color M15_BEAR = color.new(color.green, 0)  // bear FVG => fade LONG (green)
 
newM15(float bot, float top, int dir) =>
    m15Bot.push(bot)
    m15Top.push(top)
    m15Dir.push(dir)
    m15Mit.push(int(na))
    m15Born.push(bar_index)
    color c = dir == 1 ? M15_BULL : M15_BEAR
    m15Box.push(showM15Eff ? box.new(bar_index - 2, top, bar_index + 1, bot, border_color = c, bgcolor = color.new(c, 82), text = "FVG", text_color = c, text_size = size.tiny) : box(na))
 
// possible FVG waiting for bar 3
var float pendBullBot = na
var float pendBearTop = na
var box   pendBox = na
var int   pendSigBar = na     // bar that created the possible FVG (not adjusted on that same bar)
bool m15ConfirmedNow = false  // this bar confirmed a 3-bar FVG
 
if barstate.isconfirmed
    // 1) resolve the previous bar's possible FVG (we are at the close of bar 3)
    if not na(pendBox)
        box.delete(pendBox)
        pendBox := na
    if not na(pendBullBot)
        if low > pendBullBot // bar 3 does not fill => 3-bar FVG confirmed
            newM15(pendBullBot, low, 1)
            m15ConfirmedNow := true
        pendBullBot := na
    if not na(pendBearTop)
        if high < pendBearTop
            newM15(high, pendBearTop, -1)
            m15ConfirmedNow := true
        pendBearTop := na
    // 2) new 2-bar signal (possible FVG), only inside the window
    if newBullFvg and inFvgSess
        pendBullBot := high[1]
        pendSigBar := bar_index
        if showM15Eff
            pendBox := box.new(bar_index - 1, close, bar_index + 1, high[1], border_color = color.new(color.red, 20), border_style = line.style_dashed, bgcolor = color.new(color.red, 90), text = "possible", text_color = color.new(color.red, 20), text_size = size.tiny)
    if newBearFvg and inFvgSess
        pendBearTop := low[1]
        pendSigBar := bar_index
        if showM15Eff
            pendBox := box.new(bar_index - 1, low[1], bar_index + 1, close, border_color = color.new(color.green, 20), border_style = line.style_dashed, bgcolor = color.new(color.green, 90), text = "possible", text_color = color.new(color.green, 20), text_size = size.tiny)
 
// The edge of the "possible" box facing the CURRENT bar follows that bar's extreme live,
// because that is exactly the edge that remains if the FVG confirms:
//   BEAR (fade long)  -> the real gap ends up between the current high and pendBearTop
//   BULL (fade short) -> between the current low and pendBullBot
// It is clamped to the fixed edge: if price eats it, the box collapses to zero instead of
// inverting, which visually signals that this FVG will not confirm.
if not na(pendBox) and not na(pendSigBar) and bar_index > pendSigBar
    if not na(pendBearTop)
        box.set_bottom(pendBox, math.min(high, pendBearTop))
    else if not na(pendBullBot)
        box.set_top(pendBox, math.max(low, pendBullBot))
 
// INVARIANT: with no pending FVG, no "possible" box may remain on screen. The deletion
// above lives inside `if barstate.isconfirmed`, so any other path that clears the pending
// state would leave the box orphaned. This enforces it on EVERY bar.
if na(pendBullBot) and na(pendBearTop) and not na(pendBox)
    box.delete(pendBox)
    pendBox := na
 
while m15Bot.size() > i_m15FvgMax
    box.delete(m15Box.shift())
    m15Bot.shift()
    m15Top.shift()
    m15Dir.shift()
    m15Mit.shift()
    m15Born.shift()
 
// FVG life: active (box extends) -> mitigated on touch of the near edge -> gray for N bars
// -> purged (or wiped at the daily rollover)
if m15Bot.size() > 0
    for j = m15Bot.size() - 1 to 0
        int mb = m15Mit.get(j)
        box bx = m15Box.get(j)
        bool drop = false
        if na(mb)
            if i_m15TodayOnly and newD
                drop := true
            else
                // mitigation = TOUCH of the near edge, from the bar after confirmation
                bool filled = bar_index > m15Born.get(j) and (m15Dir.get(j) == 1 ? low <= m15Top.get(j) : high >= m15Bot.get(j))
                if filled
                    m15Mit.set(j, bar_index)
                    if not na(bx)
                        box.set_border_color(bx, color.new(color.gray, 40))
                        box.set_bgcolor(bx, color.new(color.gray, 90))
                        box.set_text(bx, "FVG ✗")
                        box.set_text_color(bx, color.new(color.gray, 30))
                        box.set_right(bx, bar_index)
                else if not na(bx)
                    box.set_right(bx, bar_index + 1)
        else if bar_index - mb > i_mitPurgeBars or newD
            drop := true
        if drop
            box.delete(bx)
            m15Bot.remove(j)
            m15Top.remove(j)
            m15Dir.remove(j)
            m15Mit.remove(j)
            m15Born.remove(j)
            m15Box.remove(j)
 
bool formingBull = barstate.isrealtime and inFvgSess and close > open and gapPasses(close - high[1])
bool formingBear = barstate.isrealtime and inFvgSess and close < open and gapPasses(low[1] - close)
 
// provisional box for the FVG being formed (current bar only, redrawn every tick)
var box formingBox = na
if barstate.islast and showM15Eff
    if not na(formingBox)
        box.delete(formingBox)
        formingBox := na
    if formingBull
        formingBox := box.new(bar_index - 1, close, bar_index + 1, high[1], border_color = color.new(color.red, 20), border_style = line.style_dashed, bgcolor = color.new(color.red, 92), text = "FVG?", text_color = color.new(color.red, 20), text_size = size.tiny)
    if formingBear
        formingBox := box.new(bar_index - 1, low[1], bar_index + 1, close, border_color = color.new(color.green, 20), border_style = line.style_dashed, bgcolor = color.new(color.green, 92), text = "FVG?", text_color = color.new(color.green, 20), text_size = size.tiny)
 
// active FVGs by direction
int stackBull = 0
int stackBear = 0
int m15MitCount = 0
if m15Bot.size() > 0
    for j = 0 to m15Bot.size() - 1
        if na(m15Mit.get(j))
            if m15Dir.get(j) == 1
                stackBull += 1
            else
                stackBear += 1
        else
            m15MitCount += 1
 
// formingBull/formingBear do NOT enter the score: they depend on barstate.isrealtime,
// which is false in replay and on all historical bars, so the same bar would score
// differently live and in replay. They remain a visual cue only (dashed "FVG?" box).
// C3 counts only if the FVG NEAREST to price is still ACTIVE. If the nearest one was
// already mitigated, the condition turns off even if others remain further away.
// Distance is measured to the closest edge of each zone; 0 if price is inside it.
bool  nearestOk = false
int   nearestJ  = -1
float nearestD  = na
if m15Bot.size() > 0
    for j = 0 to m15Bot.size() - 1
        float zb = m15Bot.get(j)
        float zt = m15Top.get(j)
        float d = close >= zb and close <= zt ? 0.0 : math.min(math.abs(close - zb), math.abs(close - zt))
        if na(nearestD) or d < nearestD
            nearestD := d
            nearestJ := j
    if nearestJ >= 0
        nearestOk := na(m15Mit.get(nearestJ))
bool c3Stack = i_c3NearestOnly ? nearestOk : (stackBull + stackBear > 0)
bool C3 = i_useC3 and (c3Stack or not na(pendBullBot) or not na(pendBearTop))
 
// ==================== C4: VOLUME DELTA (real with proxy fallback) ====================
float rng = math.max(high - low, syminfo.mintick)
float proxyDelta = volume * (close - open) / rng
[dOpenV, dMaxV, dMinV, dLastV] = tvta.requestVolumeDelta(i_deltaLtf)
float realDelta = dLastV
bool  usingReal = i_deltaMode == MODE_REAL and not na(realDelta)
float deltaVal = i_deltaMode == MODE_OFF ? na : usingReal ? realDelta : proxyDelta
 
// NORMALIZATION: real delta (net contracts) and proxy (volume x body/range) live on
// incomparable scales, and history may run on the proxy while recent bars use real
// delta. Each source is divided by ITS OWN moving scale so C4 always means the same.
float realAbs  = na(realDelta) ? float(na) : math.abs(realDelta)
float proxyAbs = math.abs(proxyDelta)
var float realScale  = na
var float proxyScale = na
if barstate.isconfirmed
    if not na(realAbs)
        realScale := na(realScale) ? realAbs : realScale + (realAbs - realScale) / i_deltaNormLen
    if not na(proxyAbs)
        proxyScale := na(proxyScale) ? proxyAbs : proxyScale + (proxyAbs - proxyScale) / i_deltaNormLen
bool  realOk = usingReal and not na(realAbs) and not na(realScale) and realScale > 0
float dMag = i_deltaMode == MODE_OFF ? float(na) : realOk ? realAbs / realScale : (not na(proxyScale) and proxyScale > 0 ? proxyAbs / proxyScale : float(na))
string c4Src = i_deltaMode == MODE_OFF ? "off" : realOk ? "real" : "proxy"
// fading = normalized magnitude smaller than the previous bar's; expanding = larger
bool c4Exh = not na(dMag) and not na(dMag[1]) and dMag < dMag[1]
bool c4Exp = not na(dMag) and not na(dMag[1]) and dMag > dMag[1]
bool C4 = i_useC4 and c4Exh
 
// ==================== C5: DISPLACEMENT (Williams Fractals) ====================
// Exact Williams detection (handles equal highs/lows through frontiers), from
// TradingView's built-in Williams Fractals indicator.
// C5 = distance from CURRENT PRICE to the last confirmed fractal
//      (high => bearish displacement; low => bullish) >= threshold.
fN = i_fracLen
 
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to fN
    upflagDownFrontier := upflagDownFrontier and (high[fN - i] < high[fN])
    upflagUpFrontier0 := upflagUpFrontier0 and (high[fN + i] < high[fN])
    upflagUpFrontier1 := upflagUpFrontier1 and (high[fN + 1] <= high[fN] and high[fN + i + 1] < high[fN])
    upflagUpFrontier2 := upflagUpFrontier2 and (high[fN + 1] <= high[fN] and high[fN + 2] <= high[fN] and high[fN + i + 2] < high[fN])
    upflagUpFrontier3 := upflagUpFrontier3 and (high[fN + 1] <= high[fN] and high[fN + 2] <= high[fN] and high[fN + 3] <= high[fN] and high[fN + i + 3] < high[fN])
    upflagUpFrontier4 := upflagUpFrontier4 and (high[fN + 1] <= high[fN] and high[fN + 2] <= high[fN] and high[fN + 3] <= high[fN] and high[fN + 4] <= high[fN] and high[fN + i + 4] < high[fN])
bool flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
bool upFractal = upflagDownFrontier and flagUpFrontier
 
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to fN
    downflagDownFrontier := downflagDownFrontier and (low[fN - i] > low[fN])
    downflagUpFrontier0 := downflagUpFrontier0 and (low[fN + i] > low[fN])
    downflagUpFrontier1 := downflagUpFrontier1 and (low[fN + 1] >= low[fN] and low[fN + i + 1] > low[fN])
    downflagUpFrontier2 := downflagUpFrontier2 and (low[fN + 1] >= low[fN] and low[fN + 2] >= low[fN] and low[fN + i + 2] > low[fN])
    downflagUpFrontier3 := downflagUpFrontier3 and (low[fN + 1] >= low[fN] and low[fN + 2] >= low[fN] and low[fN + 3] >= low[fN] and low[fN + i + 3] > low[fN])
    downflagUpFrontier4 := downflagUpFrontier4 and (low[fN + 1] >= low[fN] and low[fN + 2] >= low[fN] and low[fN + 3] >= low[fN] and low[fN + 4] >= low[fN] and low[fN + i + 4] > low[fN])
bool flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
bool downFractal = downflagDownFrontier and flagDownFrontier
 
// last confirmed fractal (the most recent one, high or low)
var float lastFracPrice = na
var int   lastFracDir   = 0   // 1 = HIGH fractal, -1 = LOW fractal
var int   lastFracBar   = na
if upFractal
    lastFracPrice := high[fN]
    lastFracDir := 1
    lastFracBar := bar_index - fN
if downFractal
    lastFracPrice := low[fN]
    lastFracDir := -1
    lastFracBar := bar_index - fN
 
// Last fractal of each type separately, to jump to the opposite one when price breaks
// the most recent fractal.
var float lastHiPrice = na
var int   lastHiBar   = na
var float lastLoPrice = na
var int   lastLoBar   = na
if upFractal
    lastHiPrice := high[fN]
    lastHiBar   := bar_index - fN
if downFractal
    lastLoPrice := low[fN]
    lastLoBar   := bar_index - fN
 
// fractal markers (audit C5 only), drawn back on the pivot bar; wiped at the rollover
if audC5
    if upFractal
        audLabels.push(label.new(bar_index - fN, high[fN], "", style = label.style_triangledown, color = color.new(color.teal, 0), size = size.tiny))
    if downFractal
        audLabels.push(label.new(bar_index - fN, low[fN], "", style = label.style_triangleup, color = color.new(color.red, 0), size = size.tiny))
 
// EFFECTIVE FRACTAL: if price has already BROKEN the most recent fractal, that fractal no
// longer marks the origin of the leg and the previous OPPOSITE one is used instead.
//   last = LOW  and close < that low  -> use the last HIGH
//   last = HIGH and close > that high -> use the last LOW
// Without this the distance turns NEGATIVE and C5 can never fire, even after a large move.
float effPrice = lastFracPrice
int   effDir   = lastFracDir
int   effBar   = lastFracBar
bool  effFlip  = false
if i_c5FlipBroken and not na(lastFracPrice)
    if lastFracDir == -1 and close < lastFracPrice and not na(lastHiPrice)
        effPrice := lastHiPrice
        effDir   := 1
        effBar   := lastHiBar
        effFlip  := true
    else if lastFracDir == 1 and close > lastFracPrice and not na(lastLoPrice)
        effPrice := lastLoPrice
        effDir   := -1
        effBar   := lastLoBar
        effFlip  := true
 
// distance from current price to the effective fractal. Retracements do NOT invalidate:
// the retracement is precisely what a fade setup looks for.
float c5Dist = effDir == 1 ? effPrice - close : effDir == -1 ? close - effPrice : na
// Threshold as an ATR multiple. ATR of the CLOSED bar ([1] + lookahead_on, the safe idiom)
// so the threshold does not change intrabar.
string atrTfEff = i_atrTf == "" ? timeframe.period : i_atrTf
float  atrVal   = request.security(syminfo.tickerid, atrTfEff, ta.atr(i_atrLen)[1], lookahead = barmerge.lookahead_on)
float  dispThr  = i_dispMode == MODE_ATR and not na(atrVal) and atrVal > 0 ? atrVal * i_dispAtrMult : i_dispPts
bool C5 = i_useC5 and not na(c5Dist) and c5Dist >= dispThr
 
// current leg line (audit C5 only)
var line c5Ln = na
if barstate.islast and audC5
    if not na(c5Ln)
        line.delete(c5Ln)
        c5Ln := na
    if not na(effPrice) and not na(effBar)
        // clamped like drawLevel: an old fractal may fall outside the historical buffer
        c5Ln := line.new(math.max(effBar, bar_index - DRAW_MAX_BACK), effPrice, bar_index, close, color = C5 ? color.new(color.green, 0) : color.new(color.gray, 30), width = 2, style = line.style_arrow_right)
 
// ==================== C6: NEWS ====================
// --- Automatic Forex Factory feed (toodegrees' Pine Seeds): USD + high impact ---
requestFF() =>
    [request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_1", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_2", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_3", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_4", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_5", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_6", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_7", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_8", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume)),
     request.seed("seed_toodegrees_toogit", "TOODEGREES_FOREX_FACTORY_SLOT_9", str.tostring(open) + "," + str.tostring(high) + "," + str.tostring(low) + "," + str.tostring(close) + "," + str.tostring(volume))]
 
method processFF(ffUtil.News[] N, string S1, string S2, string S3, string S4, string S5, string S6, string S7, string S8, string S9) =>
    ffDec.readNews(N, S1)
    ffDec.readNews(N, S2)
    ffDec.readNews(N, S3)
    ffDec.readNews(N, S4)
    ffDec.readNews(N, S5)
    ffDec.readNews(N, S6)
    ffDec.readNews(N, S7)
    ffDec.readNews(N, S8)
    ffDec.readNews(N, S9)
 
var ffNextWeek = array.new<ffUtil.News>()
var ffCurrWeek = array.new<ffUtil.News>()
// fixed filter: USD only (AUTO off) + high impact (red) only
var ffCurF = ffUtil.curFilter(false, false, false, false, false, false, false, false, false, true)
var ffImpF = ffUtil.impFilter(false, false, false, true)
// same feed, second filter: medium impact (orange) only. Warning only.
var ffImpMed = ffUtil.impFilter(false, false, true, false)
var ffMedWeek = array.new<ffUtil.News>()
 
var newsTimes  = array.new_int()   // automatic feed (Forex Factory)
var newsManual = array.new_int()   // manual list: SEPARATE array, not subject to the cap
var newsTimesMed = array.new_int() // orange events: warning only, never block
 
[ffS1, ffS2, ffS3, ffS4, ffS5, ffS6, ffS7, ffS8, ffS9] = requestFF()
// guarded by isconfirmed (like the FVG section) so var arrays are not mutated on the
// live bar
if i_autoNews and barstate.isconfirmed
    if timeframe.change("W")
        ffNextWeek := ffUtil.bubbleSort_News(ffNextWeek)
        ffCurrWeek := ffNextWeek.copy()
        ffCurrWeek := ffUtil.weekNews(ffCurrWeek, ffCurF, ffImpF)
        if ffCurrWeek.size() > 0
            for n in ffCurrWeek
                newsTimes.push(n.tmst)
        // purge by AGE, not by position
        while newsTimes.size() > 0 and newsTimes.get(0) < time - 7 * 24 * 60 * 60000
            newsTimes.shift()
        while newsTimes.size() > 400
            newsTimes.shift()
        // second pass over the SAME week with the orange filter
        if i_newsMed
            ffMedWeek := ffNextWeek.copy()
            ffMedWeek := ffUtil.weekNews(ffMedWeek, ffCurF, ffImpMed)
            if ffMedWeek.size() > 0
                for n in ffMedWeek
                    newsTimesMed.push(n.tmst)
            while newsTimesMed.size() > 0 and newsTimesMed.get(0) < time - 7 * 24 * 60 * 60000
                newsTimesMed.shift()
            while newsTimesMed.size() > 400
                newsTimesMed.shift()
        ffNextWeek.clear()
    ffNextWeek.processFF(ffS1, ffS2, ffS3, ffS4, ffS5, ffS6, ffS7, ffS8, ffS9)
 
// --- Manual list (added on top of the automatic feed) ---
if barstate.isfirst and str.length(i_newsList) > 0
    lines = str.split(i_newsList, "\n")
    for ln in lines
        s = str.trim(ln)
        if str.length(s) >= 16
            float y  = str.tonumber(str.substring(s, 0, 4))
            float mo = str.tonumber(str.substring(s, 5, 7))
            float dd = str.tonumber(str.substring(s, 8, 10))
            float hh = str.tonumber(str.substring(s, 11, 13))
            float mi = str.tonumber(str.substring(s, 14, 16))
            if not na(y) and not na(mo) and not na(dd) and not na(hh) and not na(mi)
                newsManual.push(timestamp(NY, int(y), int(mo), int(dd), int(hh), int(mi)))
 
bool newsBlocked = false
bool newsSoon = false
if newsTimes.size() > 0
    for j = 0 to newsTimes.size() - 1
        int et = newsTimes.get(j)
        // `time` is the bar OPEN. The exit bound is strict: with news at 10:00 and
        // postMin = 15, the bar opening at 10:15 already covers 10:15-10:30, outside the block.
        if time >= et - i_preMin * 60000 and time < et + i_postMin * 60000
            newsBlocked := true
        if et > time and et - time <= i_preMin * 60000
            newsSoon := true
if newsManual.size() > 0
    for j = 0 to newsManual.size() - 1
        int et = newsManual.get(j)
        if time >= et - i_preMin * 60000 and time < et + i_postMin * 60000
            newsBlocked := true
        if et > time and et - time <= i_preMin * 60000
            newsSoon := true
// Orange window: same logic as the red one but it only WARNS. It never enters C6.
bool newsWarn = false
if i_newsMed and newsTimesMed.size() > 0
    for j = 0 to newsTimesMed.size() - 1
        int et = newsTimesMed.get(j)
        if time >= et - i_preMin * 60000 and time < et + i_postMin * 60000
            newsWarn := true
 
// The feed only fills on the first timeframe.change("W"). Before that the array is empty
// and C6 would be a free point. Without a loaded feed, C6 does not score.
bool newsReady = (not i_autoNews) or newsTimes.size() > 0 or newsManual.size() > 0
bool C6 = i_useC6 and newsReady and not newsSoon and not newsBlocked
 
// ==================== SCORING ====================
int score = (C1 ? 1 : 0) + (C2 ? 1 : 0) + (C3 ? 1 : 0) + (C4 ? 1 : 0) + (C5 ? 1 : 0) + (C6 ? 1 : 0)
string tier = score >= 5 ? "A+++" : score == 4 ? "A+" : score >= 2 ? "B" : "C"
color tierCol = score >= 5 ? color.new(color.lime, 0) : score == 4 ? color.new(color.green, 0) : score >= 2 ? color.new(color.orange, 0) : color.new(color.gray, 0)
 
// --- CONFIRMED vs IN-PROGRESS TIER ---
// C4 uses a delta that accumulates tick by tick, so the score can change WITHIN a bar:
// the tier read mid-bar is not necessarily the one that remains at the close.
var int    scoreConf = 0
var string tierConf  = "C"
if barstate.isconfirmed
    scoreConf := score
    tierConf  := tier
color tierConfCol = scoreConf >= 5 ? color.new(color.lime, 0) : scoreConf == 4 ? color.new(color.green, 0) : scoreConf >= 2 ? color.new(color.orange, 0) : color.new(color.gray, 0)
 
// ==================== ALERTS ====================
// Alerts fire on the EDGE (when a condition turns on), not while it stays on: C6 and C4
// are on for a large share of bars, so state-based alerts would be constant noise.
// The session gate avoids overnight alerts.
bool alSessOk = (not i_alOnlySess or inFvgSess) and barstate.isconfirmed
bool trigC1   = alSessOk and i_alC1 and C1 and not C1[1]
bool trigC2   = alSessOk and i_alC2 and C2 and not C2[1]
bool trigC3   = alSessOk and i_alC3 and C3 and not C3[1]
bool trigC4   = alSessOk and i_alC4 and C4 and not C4[1]
bool trigC5   = alSessOk and i_alC5 and C5 and not C5[1]
bool trigA3   = alSessOk and i_alTierA3 and tier == "A+++" and tier[1] != "A+++"
bool trigA1   = alSessOk and i_alTierA1 and tier == "A+"   and tier[1] != "A+"
bool trigNews = alSessOk and i_alNews and newsSoon and not newsSoon[1]
 
// 1) individual alerts: they appear in the condition dropdown when creating an alert.
//    The message must be constant, so it carries no price or tier.
alertcondition(trigC1,   "C1 Macro",          "Confluence HUD: macro level touched (C1)")
alertcondition(trigC2,   "C2 Session",        "Confluence HUD: session level touched (C2)")
alertcondition(trigC3,   "C3 FVG",            "Confluence HUD: active FVG (C3)")
alertcondition(trigC4,   "C4 Delta",          "Confluence HUD: fading delta (C4)")
alertcondition(trigC5,   "C5 Displacement",   "Confluence HUD: displacement from the last fractal (C5)")
alertcondition(trigA3,   "Tier A+++",         "Confluence HUD: tier A+++ (5-6 conditions)")
alertcondition(trigA1,   "Tier A+",           "Confluence HUD: tier A+ (4 conditions)")
alertcondition(trigNews, "Upcoming news",     "Confluence HUD: high-impact USD event coming up")
 
// 2) single alert with a dynamic message: create the alert with "Any alert() function
//    call". It gathers everything that fired on the bar into one notification, naming
//    WHICH level was swept (no prices).
string c1Det = ""
if pdhFresh
    c1Det := c1Det + "PDH, "
if pdlFresh
    c1Det := c1Det + "PDL, "
if pwhFresh
    c1Det := c1Det + "PWH, "
if pwlFresh
    c1Det := c1Det + "PWL, "
if pmhFresh
    c1Det := c1Det + "PMH, "
if pmlFresh
    c1Det := c1Det + "PML, "
if wFresh
    c1Det := c1Det + "W FVG, "
if dFresh
    c1Det := c1Det + "D FVG, "
if hFresh
    c1Det := c1Det + "H4 FVG, "
string c2Det = ""
if ashFresh
    c2Det := c2Det + "Asia H, "
if aslFresh
    c2Det := c2Det + "Asia L, "
if lnhFresh
    c2Det := c2Det + "London H, "
if lnlFresh
    c2Det := c2Det + "London L, "
if nyhFresh
    c2Det := c2Det + "NY H, "
if nylFresh
    c2Det := c2Det + "NY L, "
// drop the trailing ", "
c1Det := str.length(c1Det) > 1 ? str.substring(c1Det, 0, str.length(c1Det) - 2) : ""
c2Det := str.length(c2Det) > 1 ? str.substring(c2Det, 0, str.length(c2Det) - 2) : ""
 
string alMsg = ""
if trigA3
    alMsg := alMsg + "TIER A+++ | "
if trigA1
    alMsg := alMsg + "TIER A+ | "
if trigNews
    alMsg := alMsg + "NEWS SOON | "
if trigC1
    alMsg := alMsg + "C1 Macro" + (str.length(c1Det) > 0 ? " (" + c1Det + ")" : "") + " | "
if trigC2
    alMsg := alMsg + "C2 Session" + (str.length(c2Det) > 0 ? " (" + c2Det + ")" : "") + " | "
if trigC3
    alMsg := alMsg + "C3 FVG | "
if trigC4
    alMsg := alMsg + "C4 Delta | "
if trigC5
    alMsg := alMsg + "C5 Displacement | "
if str.length(alMsg) > 0
    alert(syminfo.ticker + " " + timeframe.period + "  " + alMsg + "tier " + tier + " (" + str.tostring(score) + "/6)", alert.freq_once_per_bar_close)
 
// ==================== OPENS: WO / DO / OP ====================
// Detects the change of NY CALENDAR date (not the 18:00 futures rollover), so it works on
// any timeframe without needing a bar exactly at 00:00.
int  nyDate  = year(time, NY) * 10000 + month(time, NY) * 100 + dayofmonth(time, NY)
bool newNyDay = nyDate != nyDate[1]
int  nyMinOfDay = hour(time, NY) * 60 + minute(time, NY)
// crossing of 09:30 NY (570 min), robust if the timeframe does not land exactly on :30
bool isOpenPrint = nyMinOfDay >= 570 and not na(nyMinOfDay[1]) and (nyMinOfDay[1] < 570 or newNyDay)
 
var float woPrice = na
var float doPrice = na
var float opPrice = na
// EXACT bar where each open was taken: the line starts there
var int   woBar = na
var int   doBar = na
var int   opBar = na
 
// WO = Monday 00:00 NY. DO = Tuesday to Friday 00:00 NY (Monday is covered by WO).
if newNyDay
    int dwNow = dayofweek(time, NY)
    if dwNow == dayofweek.monday
        woPrice := open
        woBar   := bar_index
    else if dwNow == dayofweek.tuesday or dwNow == dayofweek.wednesday or dwNow == dayofweek.thursday or dwNow == dayofweek.friday
        doPrice := open
        doBar   := bar_index
if isOpenPrint
    opPrice := open
    opBar   := bar_index
// OP goes away with the daily wipe
if newD
    opPrice := na
    opBar   := na
// WO stays until Friday 18:00 NY (1080 min)
if dayofweek(time, NY) == dayofweek.friday and nyMinOfDay >= 1080
    woPrice := na
    woBar   := na
 
var line woLn = na
var line doLn = na
var line opLn = na
var label woLb = na
var label doLb = na
var label opLb = na
 
openLine(line ln, label lb, float px, int startBar, bool show, color c, string tag, bool dashed) =>
    line outL = ln
    label outB = lb
    if not na(outL)
        line.delete(outL)
        outL := na
    if not na(outB)
        label.delete(outB)
        outB := na
    // nearLvl: same distance rule as macro levels and zones, so a distant open (typically
    // WO mid-week) does not expand the auto-scale
    if show and not na(px) and not na(startBar) and nearLvl(px)
        // starts on the bar where the open was taken, clamped to the historical buffer
        outL := line.new(math.max(startBar, bar_index - DRAW_MAX_BACK), px, bar_index + 12, px, color = c, style = dashed ? line.style_dashed : line.style_solid, width = 1)
        outB := label.new(bar_index + 12, px, tag, style = label.style_none, textcolor = c, size = size.small)
    [outL, outB]
 
if barstate.islast
    [a1, b1] = openLine(woLn, woLb, woPrice, woBar, i_showWO, color.new(color.black, 0), "WO", true)
    woLn := a1
    woLb := b1
    // on Mondays DO and WO share the same price: DO is hidden
    bool doVisible = i_showDO and dayofweek(time, NY) != dayofweek.monday
    [a2, b2] = openLine(doLn, doLb, doPrice, doBar, doVisible, color.new(color.black, 0), "DO", true)
    doLn := a2
    doLb := b2
    [a3, b3] = openLine(opLn, opLb, opPrice, opBar, i_showOP, color.new(color.teal, 0), "OP", false)
    opLn := a3
    opLb := b3
 
// ==================== MACRO LEVELS (lines: current period only) ====================
// active = solid and colored; mitigated = gray dashed (or hidden with i_mitHide)
var line pdhLn = na
var line pdlLn = na
var line pwhLn = na
var line pwlLn = na
var line pmhLn = na
var line pmlLn = na
var label pdhLb = na
var label pdlLb = na
var label pwhLb = na
var label pwlLb = na
var label pmhLb = na
var label pmlLb = na
 
drawLevel(line ln, label lb, float lvl, int startBar, int mitBar, color base, string name) =>
    line newLn = na
    label newLb = na
    if not na(ln)
        line.delete(ln)
    if not na(lb)
        label.delete(lb)
    bool isMit = not na(mitBar)
    if not na(lvl) and not (i_mitHide and isMit) and nearLvl(lvl)
        color c = isMit ? color.new(color.gray, 50) : base
        // The period start can lie beyond the historical buffer (PMH/PML start on the
        // first bar of the MONTH, ~2000 bars back on M15), which throws a runtime error.
        // It is clamped; where the line starts is cosmetic, the level is the same.
        int safeStart = math.max(startBar, bar_index - DRAW_MAX_BACK)
        newLn := line.new(safeStart, lvl, bar_index + 8, lvl, color = c, style = isMit ? line.style_dashed : line.style_solid, width = 1)
        newLb := label.new(bar_index + 8, lvl, name + (isMit ? " ✗" : ""), style = label.style_none, textcolor = c, size = size.small)
    [newLn, newLb]
 
if barstate.islast and showMacroEff
    [a1, b1] = drawLevel(pdhLn, pdhLb, pdh, dStartBar, pdhMit, color.new(color.blue, 0),   "PDH")
    pdhLn := a1
    pdhLb := b1
    [a2, b2] = drawLevel(pdlLn, pdlLb, pdl, dStartBar, pdlMit, color.new(color.blue, 20),  "PDL")
    pdlLn := a2
    pdlLb := b2
    [a3, b3] = drawLevel(pwhLn, pwhLb, pwh, wStartBar, pwhMit, color.new(color.purple, 0), "PWH")
    pwhLn := a3
    pwhLb := b3
    [a4, b4] = drawLevel(pwlLn, pwlLb, pwl, wStartBar, pwlMit, color.new(color.purple, 20),"PWL")
    pwlLn := a4
    pwlLb := b4
    [a5, b5] = drawLevel(pmhLn, pmhLb, pmh, mStartBar, pmhMit, color.new(color.maroon, 0), "PMH")
    pmhLn := a5
    pmhLb := b5
    [a6, b6] = drawLevel(pmlLn, pmlLb, pml, mStartBar, pmlMit, color.new(color.maroon, 20),"PML")
    pmlLn := a6
    pmlLb := b6
 
// ✗ mark on the first touch of each level (audit C1 only)
if audC1 and i_showMacro
    if pdhMit == bar_index
        audLabels.push(label.new(bar_index, pdh, "PDH ✗", style = label.style_label_down, color = color.new(color.blue, 30), textcolor = color.white, size = size.tiny))
    if pdlMit == bar_index
        audLabels.push(label.new(bar_index, pdl, "PDL ✗", style = label.style_label_up, color = color.new(color.blue, 30), textcolor = color.white, size = size.tiny))
    if pwhMit == bar_index
        audLabels.push(label.new(bar_index, pwh, "PWH ✗", style = label.style_label_down, color = color.new(color.purple, 30), textcolor = color.white, size = size.tiny))
    if pwlMit == bar_index
        audLabels.push(label.new(bar_index, pwl, "PWL ✗", style = label.style_label_up, color = color.new(color.purple, 30), textcolor = color.white, size = size.tiny))
    if pmhMit == bar_index
        audLabels.push(label.new(bar_index, pmh, "PMH ✗", style = label.style_label_down, color = color.new(color.maroon, 30), textcolor = color.white, size = size.tiny))
    if pmlMit == bar_index
        audLabels.push(label.new(bar_index, pml, "PML ✗", style = label.style_label_up, color = color.new(color.maroon, 30), textcolor = color.white, size = size.tiny))
 
// ==================== SESSION LEVELS (lines: current level only) ====================
var line ashLn = na
var line aslLn = na
var line lnhLn = na
var line lnlLn = na
var line nyhLn = na
var line nylLn = na
var label ashLb = na
var label aslLb = na
var label lnhLb = na
var label lnlLb = na
var label nyhLb = na
var label nylLb = na
 
if barstate.islast and showSessEff
    [s1, t1l] = drawLevel(ashLn, ashLb, useAsiaH, asiaStartBar, ashMit, color.new(color.orange, 0),  "Asia H")
    ashLn := s1
    ashLb := t1l
    [s2, t2l] = drawLevel(aslLn, aslLb, useAsiaL, asiaStartBar, aslMit, color.new(color.orange, 30), "Asia L")
    aslLn := s2
    aslLb := t2l
    [s3, t3l] = drawLevel(lnhLn, lnhLb, useLonH, lonStartBar, lnhMit, color.new(color.aqua, 0),   "London H")
    lnhLn := s3
    lnhLb := t3l
    [s4, t4l] = drawLevel(lnlLn, lnlLb, useLonL, lonStartBar, lnlMit, color.new(color.aqua, 30),  "London L")
    lnlLn := s4
    lnlLb := t4l
    [s5, t5l] = drawLevel(nyhLn, nyhLb, useNyH, nyStartBar, nyhMit, color.new(#5d4037, 0),  "NY H")
    nyhLn := s5
    nyhLb := t5l
    [s6, t6l] = drawLevel(nylLn, nylLb, useNyL, nyStartBar, nylMit, color.new(#5d4037, 30), "NY L")
    nylLn := s6
    nylLb := t6l
 
// ✗ mark on the first touch of each session level (audit C2 only)
if audC2 and i_showSess
    if ashMit == bar_index
        audLabels.push(label.new(bar_index, useAsiaH, "Asia H ✗", style = label.style_label_down, color = color.new(color.orange, 30), textcolor = color.white, size = size.tiny))
    if aslMit == bar_index
        audLabels.push(label.new(bar_index, useAsiaL, "Asia L ✗", style = label.style_label_up, color = color.new(color.orange, 30), textcolor = color.white, size = size.tiny))
    if lnhMit == bar_index
        audLabels.push(label.new(bar_index, useLonH, "London H ✗", style = label.style_label_down, color = color.new(color.aqua, 30), textcolor = color.black, size = size.tiny))
    if lnlMit == bar_index
        audLabels.push(label.new(bar_index, useLonL, "London L ✗", style = label.style_label_up, color = color.new(color.aqua, 30), textcolor = color.black, size = size.tiny))
    if nyhMit == bar_index
        audLabels.push(label.new(bar_index, useNyH, "NY H ✗", style = label.style_label_down, color = color.new(#5d4037, 20), textcolor = color.white, size = size.tiny))
    if nylMit == bar_index
        audLabels.push(label.new(bar_index, useNyL, "NY L ✗", style = label.style_label_up, color = color.new(#5d4037, 20), textcolor = color.white, size = size.tiny))
 
// HTF FVG boxes (redrawn on the last bar); mitigated = gray + ✗
var fvgBoxes = array.new_box()
 
drawZones(array<float> bots, array<float> tops, array<int> dirs, array<int> mits, int zoneLeftT, color cBull, color cBear, string tag, array<box> store) =>
    if bots.size() > 0
        for j = 0 to bots.size() - 1
            float zb = bots.get(j)
            float zt = tops.get(j)
            bool isMit = not na(mits.get(j))
            bool near = nearLvl(zb) or nearLvl(zt) or (close >= zb and close <= zt)
            if near and not (i_mitHide and isMit)
                color c = isMit ? color.gray : dirs.get(j) == 1 ? cBull : cBear
                string txt = tag + (isMit ? " ✗" : "")
                // Every active zone starts at the LATEST confirmed zone of its timeframe,
                // not at its own origin: otherwise an old unmitigated zone would stretch the
                // drawing weeks back and squash the chart.
                int leftT  = zoneLeftT
                int rightT = time + 10 * timeframe.in_seconds() * 1000
                if not na(leftT)
                    store.push(box.new(leftT, zt, rightT, zb, xloc = xloc.bar_time, border_color = color.new(c, isMit ? 60 : 0), bgcolor = color.new(c, isMit ? 92 : 85), text = txt, text_color = color.new(c, isMit ? 40 : 0), text_size = size.tiny))
 
if barstate.islast
    if fvgBoxes.size() > 0
        for b in fvgBoxes
            box.delete(b)
        fvgBoxes.clear()
    if showHtfEff
        drawZones(wFvgBot, wFvgTop, wFvgDir, wFvgMit, wAnchorT, color.teal,  color.fuchsia, "W FVG",  fvgBoxes)
        drawZones(dFvgBot, dFvgTop, dFvgDir, dFvgMit, dAnchorT, color.green, color.red,     "D FVG",  fvgBoxes)
        drawZones(hFvgBot, hFvgTop, hFvgDir, hFvgMit, hAnchorT, color.olive, color.orange,  "H4 FVG", fvgBoxes)
 
bgcolor(i_shadeNews and audOff and newsBlocked ? color.new(color.gray, 80) : na, title = "News block")
// orange = warning. Drawn only when there is NO red block on top.
bgcolor(i_newsMed and audOff and newsWarn and not newsBlocked ? color.new(color.orange, 85) : na, title = "News warning")
// formingBull/Bear excluded here too, so the highlight never contradicts the score.
bool fadeCandidate = newBullFvg or newBearFvg
bgcolor(i_colorBars and audOff and fadeCandidate and score >= 4 ? color.new(tierCol, 75) : na, title = "Tier A+ signal")
// Audit: band on every bar where the audited condition counts. Drawn as boxes registered
// in audBands so they are deleted at the daily rollover.
var int lastBandBar = na
// audit C4: band on FVG signal bars — green = fading delta, orange = expanding
bool c4Band = audC4 and inFvgSess and (newBullFvg or newBearFvg or m15ConfirmedNow)
bool bandNow = (audC1 and C1) or (audC2 and C2) or (audC3 and inFvgSess and (newBullFvg or newBearFvg)) or (audC5 and C5) or c4Band
color bandCol = c4Band ? (c4Exh ? color.green : color.orange) : color.yellow
// padding in ATR so the band looks the same on any symbol
float bandPad = na(plotAtr) ? 0.0 : plotAtr * 0.25
if bandNow and (na(lastBandBar) or lastBandBar != bar_index)
    lastBandBar := bar_index
    audBands.push(box.new(bar_index, high + bandPad, bar_index + 1, low - bandPad, border_color = color.new(bandCol, 100), bgcolor = color.new(bandCol, 75)))
 
// ==================== TABLE ====================
// --- LIQUIDITY OUTSIDE THE DRAWING WINDOW ---
// A distant level is not drawn (so it does not expand the auto-scale), but it still
// matters: in a trend the target is often exactly the level left out of range. The nearest
// unmitigated one above and below is listed with its distance.
// Adds the ACTIVE HTF zones that are not being drawn, using the NEAR edge (the one price
// would touch first).
addLiqZones(array<float> bots, array<float> tops, array<int> mits, string tag, array<float> outPx, array<string> outNm) =>
    if bots.size() > 0
        for j = 0 to bots.size() - 1
            if na(mits.get(j))
                float zb = bots.get(j)
                float zt = tops.get(j)
                if not na(zb) and not na(zt)
                    bool drawn = nearLvl(zb) or nearLvl(zt) or (close >= zb and close <= zt)
                    if not drawn
                        array.push(outPx, zb > close ? zb : zt)
                        array.push(outNm, tag)
    array.size(outPx)
 
string liqUpTxt = "-"
string liqDnTxt = "-"
if barstate.islast
    lvArr = array.from(pdh, pdl, pwh, pwl, pmh, pml)
    lnArr = array.from("PDH", "PDL", "PWH", "PWL", "PMH", "PML")
    mtArr = array.from(na(pdhMit) ? 0 : 1, na(pdlMit) ? 0 : 1, na(pwhMit) ? 0 : 1, na(pwlMit) ? 0 : 1, na(pmhMit) ? 0 : 1, na(pmlMit) ? 0 : 1)
    liqPx = array.new_float()
    liqNm = array.new_string()
    for i = 0 to 5
        float v = array.get(lvArr, i)
        if not na(v) and array.get(mtArr, i) == 0 and not nearLvl(v)
            array.push(liqPx, v)
            array.push(liqNm, array.get(lnArr, i))
    addLiqZones(wFvgBot, wFvgTop, wFvgMit, "W FVG",  liqPx, liqNm)
    addLiqZones(dFvgBot, dFvgTop, dFvgMit, "D FVG",  liqPx, liqNm)
    addLiqZones(hFvgBot, hFvgTop, hFvgMit, "H4 FVG", liqPx, liqNm)
    float bestUp  = na
    float bestDn  = na
    string bestUpN = ""
    string bestDnN = ""
    if array.size(liqPx) > 0
        for i = 0 to array.size(liqPx) - 1
            float v = array.get(liqPx, i)
            if v > close and (na(bestUp) or v < bestUp)
                bestUp  := v
                bestUpN := array.get(liqNm, i)
            if v < close and (na(bestDn) or v > bestDn)
                bestDn  := v
                bestDnN := array.get(liqNm, i)
    liqUpTxt := na(bestUp) ? "-" : bestUpN + " " + str.tostring(bestUp, "#.##") + "  (+" + str.tostring(bestUp - close, "#") + ")"
    liqDnTxt := na(bestDn) ? "-" : bestDnN + " " + str.tostring(bestDn, "#.##") + "  (-" + str.tostring(close - bestDn, "#") + ")"
 
// 6 columns so C1..C6 can sit as a row of rectangles. Wide rows use merge_cells:
// TradingView sizes each column to its content, so without merging the condition strip
// would not line up with the rest.
var table hud = table.new(position.top_right, 6, 16, border_width = 1)
var bool hudMerged = false
 
cell(int r, string a, string b, color bg) =>
    hud.cell(0, r, a, text_color = color.white, bgcolor = color.new(color.black, 20), text_size = tblSz, text_halign = text.align_left)
    hud.cell(1, r, b, text_color = color.white, bgcolor = bg, text_size = tblSz, text_halign = text.align_left)
    for c = 2 to 5
        hud.cell(c, r, "", bgcolor = bg)
 
// wide row: a single text spanning all 6 columns
wide(int r, string txt, color bg) =>
    hud.cell(0, r, txt, text_color = color.white, bgcolor = bg, text_size = tblSz, text_halign = text.align_left)
    for c = 1 to 5
        hud.cell(c, r, "", bgcolor = bg)
 
// half row: text spanning 3 columns (col 0-2 or col 3-5)
half(int c0, int r, string txt, color bg) =>
    hud.cell(c0, r, txt, text_color = color.white, bgcolor = bg, text_size = tblSz, text_halign = text.align_left)
    hud.cell(c0 + 1, r, "", bgcolor = bg)
    hud.cell(c0 + 2, r, "", bgcolor = bg)
 
// one condition's rectangle spanning 2 columns so the name fits; the cell itself
// changes color with the state
confCell(int c0, int r, string nm, color cbg) =>
    hud.cell(c0, r, nm, text_color = color.white, bgcolor = cbg, text_size = tblSz, text_halign = text.align_center)
    hud.cell(c0 + 1, r, "", bgcolor = cbg)
 
// level state for the audit table
lvlStateTxt(int mitBar, bool fresh) =>
    fresh ? "SWEPT ►counts" : not na(mitBar) ? "mitigated" : "untouched"
 
lvlStateCol(int mitBar, bool fresh) =>
    fresh ? color.new(color.green, 30) : not na(mitBar) ? color.new(color.gray, 50) : color.new(color.blue, 50)
 
zoneCounts(array<int> mits) =>
    int vig = 0
    int mit = 0
    if mits.size() > 0
        for j = 0 to mits.size() - 1
            if na(mits.get(j))
                vig += 1
            else
                mit += 1
    [vig, mit]
 
if barstate.islast and i_showTable
    color yes = color.new(color.green, 40)
    color no  = color.new(color.gray, 40)
    string cSum = (C1 ? "C1✓ " : "C1✗ ") + (C2 ? "C2✓ " : "C2✗ ") + (C3 ? "C3✓ " : "C3✗ ") + (C4 ? "C4✓ " : "C4✗ ") + (C5 ? "C5✓ " : "C5✗ ") + (C6 ? "C6✓" : "C6✗")
    if audC2
        cell(0,  "TIER", tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        cell(1,  "Count", cSum, color.new(color.black, 40))
        cell(2,  "AUDIT C2", C2 ? "ACTIVE now" : "inactive", C2 ? yes : no)
        cell(3,  "Asia H " + (na(useAsiaH) ? "(in progress)" : str.tostring(useAsiaH, "#.##")), lvlStateTxt(ashMit, ashFresh), lvlStateCol(ashMit, ashFresh))
        cell(4,  "Asia L " + (na(useAsiaL) ? "(in progress)" : str.tostring(useAsiaL, "#.##")), lvlStateTxt(aslMit, aslFresh), lvlStateCol(aslMit, aslFresh))
        cell(5,  "London H " + (na(useLonH) ? "(in progress)" : str.tostring(useLonH, "#.##")), lvlStateTxt(lnhMit, lnhFresh), lvlStateCol(lnhMit, lnhFresh))
        cell(6,  "London L " + (na(useLonL) ? "(in progress)" : str.tostring(useLonL, "#.##")), lvlStateTxt(lnlMit, lnlFresh), lvlStateCol(lnlMit, lnlFresh))
        cell(7,  "NY H " + (na(useNyH) ? "(in progress)" : str.tostring(useNyH, "#.##")), lvlStateTxt(nyhMit, nyhFresh), lvlStateCol(nyhMit, nyhFresh))
        cell(8,  "NY L " + (na(useNyL) ? "(in progress)" : str.tostring(useNyL, "#.##")), lvlStateTxt(nylMit, nylFresh), lvlStateCol(nylMit, nylFresh))
        cell(9,  "Sessions", "Asia " + i_sessAsia + " / London " + i_sessLondon + " / NY " + i_sessNY + " (NY time)", no)
        cell(10, "Lookback", str.tostring(i_touchLookback) + " bars / exact touch", no)
        cell(11, "", "", color.new(color.black, 100))
        cell(12, "", "", color.new(color.black, 100))
        cell(13, "", "", color.new(color.black, 100))
    if audC3
        cell(0,  "TIER", tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        cell(1,  "Count", cSum, color.new(color.black, 40))
        cell(2,  "AUDIT C3", C3 ? "ACTIVE now" : "inactive", C3 ? yes : no)
        cell(3,  "Bear FVG (fade LONG)", str.tostring(stackBear) + " active", stackBear > 0 ? color.new(color.green, 50) : no)
        cell(4,  "Bull FVG (fade SHORT)", str.tostring(stackBull) + " active", stackBull > 0 ? color.new(color.red, 50) : no)
        cell(5,  "Mitigated (pending purge)", str.tostring(m15MitCount), no)
        cell(6,  "Forming (bar 2)", formingBull ? "BULL (fade short)" : formingBear ? "BEAR (fade long)" : "no", (formingBull or formingBear) ? yes : no)
        cell(7,  "Possible FVG (bar 3)", not na(pendBullBot) ? "BULL awaiting bar 3" : not na(pendBearTop) ? "BEAR awaiting bar 3" : "no", (not na(pendBullBot) or not na(pendBearTop)) ? yes : no)
        cell(8,  "Min gap / Window", i_fvgFilterMode + ": " + str.tostring(i_minGap) + " pts / " + str.tostring(i_minGapAtrPct, "#.#") + "% of ATR " + str.tostring(fvgAtr, "#.#") + " = " + str.tostring(minAtrSize, "#.#") + " pts / " + i_fvgSess + " NY", no)
        cell(9,  "Mitigated purge", str.tostring(i_mitPurgeBars) + " bars / daily rollover", no)
        cell(10, "News events (auto+manual)", str.tostring(newsTimes.size() + newsManual.size()), no)
        cell(11, "", "", color.new(color.black, 100))
        cell(12, "", "", color.new(color.black, 100))
        cell(13, "", "", color.new(color.black, 100))
    if audC4
        cell(0,  "TIER", tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        cell(1,  "Count", cSum, color.new(color.black, 40))
        cell(2,  "AUDIT C4", C4 ? "ACTIVE (fading)" : "inactive", C4 ? yes : no)
        cell(3,  "Delta source", c4Src == "real" ? "REAL (LTF " + i_deltaLtf + ")" : c4Src == "off" ? "OFF" : "PROXY (body x volume)", c4Src == "real" ? yes : color.new(color.orange, 50))
        cell(4,  "Current bar delta", na(deltaVal) ? "-" : str.tostring(deltaVal, format.volume), no)
        cell(5,  "Previous bar delta", na(deltaVal[1]) ? "-" : str.tostring(deltaVal[1], format.volume), no)
        cell(6,  "State", c4Exh ? "FADING" : c4Exp ? "EXPANDING" : "-", c4Exh ? yes : c4Exp ? color.new(color.orange, 40) : no)
        cell(7,  "Green band", "FVG signal with fading delta", color.new(color.green, 60))
        cell(8,  "Orange band", "FVG signal with expanding delta", color.new(color.orange, 60))
        cell(9,  "", "", color.new(color.black, 100))
        cell(10, "", "", color.new(color.black, 100))
        cell(11, "", "", color.new(color.black, 100))
        cell(12, "", "", color.new(color.black, 100))
        cell(13, "", "", color.new(color.black, 100))
    if audC5
        string fracTxt = effDir == 1 ? "HIGH " + str.tostring(effPrice, "#.##") : effDir == -1 ? "LOW " + str.tostring(effPrice, "#.##") : "none yet"
        string agoTxt  = (not na(effBar) ? " (" + str.tostring(bar_index - effBar) + " bars ago)" : "") + (effFlip ? "  [flipped: price broke the latest]" : "")
        cell(0,  "TIER", tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        cell(1,  "Count", cSum, color.new(color.black, 40))
        cell(2,  "AUDIT C5", C5 ? "ACTIVE now" : "inactive", C5 ? yes : no)
        cell(3,  "Last fractal", fracTxt + agoTxt, effDir == 1 ? color.new(color.teal, 50) : effDir == -1 ? color.new(color.red, 50) : no)
        // compared against dispThr (the EFFECTIVE threshold), never the raw input
        cell(4,  "Distance to price", (na(c5Dist) ? "-" : str.tostring(c5Dist, "#.##") + " pts") + "  (threshold " + str.tostring(dispThr, "#") + (i_dispMode == MODE_ATR ? " = " + str.tostring(i_dispAtrMult, "#.#") + "x ATR " + str.tostring(atrVal, "#.#") : " fixed pts") + ")", not na(c5Dist) and c5Dist >= dispThr ? yes : no)
        cell(5,  "Leg direction", effDir == 1 ? "BEARISH (fade LONG)" : effDir == -1 ? "BULLISH (fade SHORT)" : "-", no)
        cell(6,  "Fractal n", str.tostring(i_fracLen) + " bars per side", no)
        cell(7,  "", "", color.new(color.black, 100))
        cell(8,  "", "", color.new(color.black, 100))
        cell(9,  "", "", color.new(color.black, 100))
        cell(10, "", "", color.new(color.black, 100))
        cell(11, "", "", color.new(color.black, 100))
        cell(12, "", "", color.new(color.black, 100))
        cell(13, "", "", color.new(color.black, 100))
    if audC1
        [wVig, wMit] = zoneCounts(wFvgMit)
        [dVig, dMit] = zoneCounts(dFvgMit)
        [hVig, hMit] = zoneCounts(hFvgMit)
        cell(0,  "TIER", tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        cell(1,  "Count", cSum, color.new(color.black, 40))
        cell(2,  "AUDIT C1", C1 ? "ACTIVE now" : "inactive", C1 ? yes : no)
        cell(3,  "PDH " + str.tostring(pdh, "#.##"), lvlStateTxt(pdhMit, pdhFresh), lvlStateCol(pdhMit, pdhFresh))
        cell(4,  "PDL " + str.tostring(pdl, "#.##"), lvlStateTxt(pdlMit, pdlFresh), lvlStateCol(pdlMit, pdlFresh))
        cell(5,  "PWH " + str.tostring(pwh, "#.##"), lvlStateTxt(pwhMit, pwhFresh), lvlStateCol(pwhMit, pwhFresh))
        cell(6,  "PWL " + str.tostring(pwl, "#.##"), lvlStateTxt(pwlMit, pwlFresh), lvlStateCol(pwlMit, pwlFresh))
        cell(7,  "PMH " + str.tostring(pmh, "#.##"), lvlStateTxt(pmhMit, pmhFresh), lvlStateCol(pmhMit, pmhFresh))
        cell(8,  "PML " + str.tostring(pml, "#.##"), lvlStateTxt(pmlMit, pmlFresh), lvlStateCol(pmlMit, pmlFresh))
        cell(9,  "W FVG",  str.tostring(wVig) + " active / " + str.tostring(wMit) + " mitigated" + (wFresh ? " ►C1" : ""), wFresh ? yes : wVig > 0 ? color.new(color.teal, 50) : no)
        cell(10, "D FVG",  str.tostring(dVig) + " active / " + str.tostring(dMit) + " mitigated" + (dFresh ? " ►C1" : ""), dFresh ? yes : dVig > 0 ? color.new(color.teal, 50) : no)
        cell(11, "H4 FVG", str.tostring(hVig) + " active / " + str.tostring(hMit) + " mitigated" + (hFresh ? " ►C1" : "") + (not na(hAnchorT) ? "  since " + str.format_time(hAnchorT, "MM-dd HH:mm", NY) : ""), hFresh ? yes : hVig > 0 ? color.new(color.teal, 50) : no)
        cell(12, "Lookback", str.tostring(i_touchLookback) + " bars / exact touch", no)
        cell(13, "", "", color.new(color.black, 100))
    if audOff
        // rows 0-1: conditions in two rows of 3, with names. Each spans 2 columns so all
        // six have the same width.
        color okC  = color.new(color.green, 25)
        color offC = color.new(color.gray, 55)
        color badC = color.new(color.red, 20)
        confCell(0, 0, "C1 Macro",   C1 ? okC : offC)
        confCell(2, 0, "C2 Session", C2 ? okC : offC)
        confCell(4, 0, "C3 FVG",     C3 ? okC : offC)
        confCell(0, 1, "C4 Delta",   C4 ? okC : offC)
        confCell(2, 1, "C5 Disp",    C5 ? okC : offC)
        // C6 in RED when news is near (blocking window): an active veto, not just "off".
        // Gray only if the feed did not load or C6 is disabled.
        confCell(4, 1, "C6 News",    (newsBlocked or newsSoon) ? badC : (C6 ? okC : offC))
        // row 2: in-progress tier | confirmed tier
        half(0, 2, "TIER " + tier + " (" + str.tostring(score) + "/6)", color.new(tierCol, 40))
        half(3, 2, "closed " + tierConf + " (" + str.tostring(scoreConf) + "/6)", color.new(tierConfCol, 40))
        // row 3: which MACRO or SESSION level was swept (C1/C2 detail, same as the alert).
        // "-" = no fresh touch.
        string nivTxt = str.length(c1Det) > 0 ? c1Det : ""
        nivTxt := str.length(c2Det) > 0 ? (str.length(nivTxt) > 0 ? nivTxt + "  ·  " + c2Det : c2Det) : nivTxt
        wide(3, str.length(nivTxt) > 0 ? "LEVEL SWEPT  " + nivTxt : "LEVEL SWEPT  -", str.length(nivTxt) > 0 ? color.new(color.green, 45) : no)
        // rows 4-5: liquidity outside the drawing window
        wide(4, "LIQ ^  " + liqUpTxt, liqUpTxt == "-" ? no : color.new(color.blue, 45))
        wide(5, "LIQ v  " + liqDnTxt, liqDnTxt == "-" ? no : color.new(color.maroon, 45))
        if not hudMerged
            hud.merge_cells(0, 0, 1, 0)
            hud.merge_cells(2, 0, 3, 0)
            hud.merge_cells(4, 0, 5, 0)
            hud.merge_cells(0, 1, 1, 1)
            hud.merge_cells(2, 1, 3, 1)
            hud.merge_cells(4, 1, 5, 1)
            hud.merge_cells(0, 2, 2, 2)
            hud.merge_cells(3, 2, 5, 2)
            for r = 3 to 5
                hud.merge_cells(0, r, 5, r)
            hudMerged := true
    // in AUDIT mode the label|value layout is kept: the value spans col 1..5 so it is not
    // squashed by the 6-column strip.
    if not audOff and not hudMerged
        for r = 0 to 13
            hud.merge_cells(1, r, 5, r)
        hudMerged := true

← 返回列表