FVG, IFVG & Key Liquidity Levels

lucymatos · study · 1508 行 · 点赞 733 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0
//@version=6
indicator("FVG · IFVG · Key Liquidity Levels", "FVG+IFVG+KL", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ═════════════════════════════════════════════════════════════════════════════
// INPUTS
// ═════════════════════════════════════════════════════════════════════════════
 
var string g_lab  = "═══════ Labels (all of them) ═══════"
var string g_gen  = "═══════ General ═══════"
var string g_fvg  = "═══════ FVG / IFVG engine ═══════"
var string g_tf   = "═══════ FVG timeframes ═══════"
var string g_prev = "═══════ Previous period high / low ═══════"
var string g_sess = "═══════ Sessions ═══════"
var string g_gap  = "═══════ Opening gaps (NDOG / NWOG) ═══════"
var string g_open = "═══════ Opens ═══════"
var string g_vwap = "═══════ VWAP ═══════"
var string g_ma   = "═══════ Moving averages ═══════"
var string g_max  = "═══════ MA type-specific settings ═══════"
var string g_imp  = "═══════ Impulse / displacement ═══════"
var string g_swp  = "═══════ Liquidity sweeps ═══════"
var string g_tbl  = "═══════ Stats table ═══════"
var string g_lvl  = "═══════ Level lines ═══════"
 
// One size, one toggle, one offset for every piece of text this script writes:
labShow  = input.bool(true, "Show labels", inline = "lb", group = g_lab)
labPrice = input.bool(false, "with price", inline = "lb", group = g_lab)
labSize  = input.string("Small", "Size — level labels and zone captions",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = g_lab)
labOff   = input.int(38, "Level label offset (bars right)", minval = 0, maxval = 300,
     group = g_lab, tooltip = "How far past the last bar the level labels sit. Does not affect the zone captions, which are pinned inside their own boxes.")
 
TZ = input.string("America/New_York", "Timezone", group = g_gen,
     options = ["America/New_York", "America/Chicago", "America/Los_Angeles",
                "Europe/London", "Europe/Berlin", "Asia/Tokyo", "UTC"],
     tooltip = "Every session, anchor and gap time below is read in this timezone.")
 
sessOpen = input.string("18:00", "Session day opens at", options = ["18:00", "17:00"], group = g_gen,
     tooltip = "The futures day boundary. Everything in this script — previous day/week/month/year ranges, the daily and weekly opens, both VWAP anchors and both opening gaps — is cut here. A bar at or after this time belongs to the NEXT trade date, so Sunday 18:00 is Monday's session.")
 
// ── FVG engine ───────────────────────────────────────────────────────────────
fvgOn      = input.bool(true,  "Enable the FVG / IFVG engine", group = g_fvg)
keepIFVG   = input.bool(true,  "Keep gaps as IFVG once closed through", group = g_fvg,
     tooltip = "Off = the gap is simply deleted when a HTF bar closes through it.")
onlyIFVG   = input.bool(false, "Only display inverted gaps", group = g_fvg,
     tooltip = "Intact gaps are tracked silently and only appear once they invert.")
invFlip    = input.bool(true,  "Recolour an inverted gap to the opposite side", group = g_fvg,
     tooltip = "On  = an inverted bullish gap is painted with the bearish colour.\nOff = it is painted with the neutral inverted colour.")
boxMode    = input.string("To the current candle", "Box right edge", group = g_fvg,
     options = ["To the current candle", "Fixed length", "Infinite right"],
     tooltip = "To the current candle: the zone grows with the chart and its caption rides the right-hand edge, next to live price.\nInfinite right: the old behaviour — the box runs off the chart and the caption sits at the far right.")
boxBars    = input.int(6, "Box length in HTF bars (Fixed length only)", minval = 1, maxval = 200, group = g_fvg)
showMidFvg = input.bool(false, "Show gap midpoint (CE)", group = g_fvg)
showTfTxt  = input.bool(true,  "Write the timeframe on the box", group = g_fvg)
borderOn   = input.bool(true,  "Box borders", group = g_fvg)
minTicks   = input.float(0, "Minimum gap size (ticks)", minval = 0, step = 1, group = g_fvg,
     tooltip = "Filters out micro gaps. 0 keeps everything.")
alertFvg   = input.bool(false, "Alert on new gaps / inversions", group = g_fvg)
 
// ── FVG timeframe slots ──────────────────────────────────────────────────────
// Each row: enable | timeframe | max kept, then bull | bear | inverted colours.
en1 = input.bool(true,  "TF 1", inline = "t1", group = g_tf)
tf1 = input.timeframe("5",  "", inline = "t1", group = g_tf)
n1  = input.int(12, "", minval = 1, maxval = 60, inline = "t1", group = g_tf, tooltip = "Max gaps kept on this timeframe")
c1b = input.color(color.new(#089981, 82), "", inline = "t1c", group = g_tf)
c1s = input.color(color.new(#f23645, 82), "", inline = "t1c", group = g_tf)
c1i = input.color(color.new(#787b86, 80), "", inline = "t1c", group = g_tf)
 
en2 = input.bool(true,  "TF 2", inline = "t2", group = g_tf)
tf2 = input.timeframe("15", "", inline = "t2", group = g_tf)
n2  = input.int(10, "", minval = 1, maxval = 60, inline = "t2", group = g_tf)
c2b = input.color(color.new(#2962ff, 84), "", inline = "t2c", group = g_tf)
c2s = input.color(color.new(#ff6d00, 84), "", inline = "t2c", group = g_tf)
c2i = input.color(color.new(#787b86, 82), "", inline = "t2c", group = g_tf)
 
en3 = input.bool(false, "TF 3", inline = "t3", group = g_tf)
tf3 = input.timeframe("60", "", inline = "t3", group = g_tf)
n3  = input.int(8,  "", minval = 1, maxval = 60, inline = "t3", group = g_tf)
c3b = input.color(color.new(#9c27b0, 86), "", inline = "t3c", group = g_tf)
c3s = input.color(color.new(#795548, 86), "", inline = "t3c", group = g_tf)
c3i = input.color(color.new(#787b86, 84), "", inline = "t3c", group = g_tf)
 
// ── Previous period high / low ───────────────────────────────────────────────
showPD = input.bool(true,  "Prev day   H/L", inline = "pd", group = g_prev)
colPD  = input.color(#2962ff, "", inline = "pd", group = g_prev)
styPD  = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "pd", group = g_prev)
 
showPW = input.bool(true,  "Prev week  H/L", inline = "pw", group = g_prev)
colPW  = input.color(#089981, "", inline = "pw", group = g_prev)
styPW  = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "pw", group = g_prev)
 
showPM = input.bool(true,  "Prev month H/L", inline = "pm", group = g_prev)
colPM  = input.color(#f23645, "", inline = "pm", group = g_prev)
styPM  = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "pm", group = g_prev)
 
showPY = input.bool(false, "Prev year  H/L", inline = "py", group = g_prev)
colPY  = input.color(#000000, "", inline = "py", group = g_prev)
styPY  = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "py", group = g_prev)
 
htfFallback = input.bool(true, "Fall back to calendar month / year when history is short", group = g_prev,
     tooltip = "The month and year ranges are built from the 18:00→17:00 session days on your chart, which needs a full prior month or year of loaded bars. Until that exists this borrows the calendar-period value from a higher timeframe instead of showing nothing. The day and week ranges never fall back.")
 
// ── Sessions ─────────────────────────────────────────────────────────────────
showAsia = input.bool(true, "Asia   H/L", inline = "as", group = g_sess)
colAsia  = input.color(#ff9800, "", inline = "as", group = g_sess)
styAsia  = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "as", group = g_sess)
sessAsia = input.session("1800-0200", "Asia session", group = g_sess)
 
showLon  = input.bool(true, "London H/L", inline = "ln", group = g_sess)
colLon   = input.color(#7e57c2, "", inline = "ln", group = g_sess)
styLon   = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "ln", group = g_sess)
sessLon  = input.session("0200-0800", "London session", group = g_sess)
 
// ── Opening gaps ─────────────────────────────────────────────────────────────
showNDOG = input.bool(true, "New Day Opening Gap", inline = "nd", group = g_gap)
colNDOG  = input.color(color.new(#9598a1, 70), "", inline = "nd", group = g_gap)
nNDOG    = input.int(3, "keep", minval = 1, maxval = 20, inline = "nd", group = g_gap)
 
showNWOG = input.bool(true, "New Week Opening Gap", inline = "nw", group = g_gap)
colNWOG  = input.color(color.new(#e1bee7, 60), "", inline = "nw", group = g_gap)
nNWOG    = input.int(5, "keep", minval = 1, maxval = 20, inline = "nw", group = g_gap)
gapMid   = input.bool(true, "Show gap midpoints (CE)", group = g_gap,
     tooltip = "The gap runs from the 17:00 close to the 18:00 open. Sunday's gap is drawn as the NWOG only, not twice.")
 
// ── Opens ────────────────────────────────────────────────────────────────────
showDO = input.bool(true, "Daily open  (18:00)", inline = "do", group = g_open)
colDO  = input.color(#ffb300, "", inline = "do", group = g_open)
styDO  = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "do", group = g_open)
 
showWO = input.bool(true, "Weekly open (Sun 18:00)", inline = "wo", group = g_open)
colWO  = input.color(#00897b, "", inline = "wo", group = g_open)
styWO  = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "wo", group = g_open)
 
// ── VWAP ─────────────────────────────────────────────────────────────────────
vwapSrc  = input.source(hlc3, "VWAP source", group = g_vwap)
showDV   = input.bool(true,  "Daily VWAP",  inline = "dv", group = g_vwap)
colDV    = input.color(#2962ff, "", inline = "dv", group = g_vwap)
showPDV  = input.bool(true,  "Prev day VWAP close", inline = "pdv", group = g_vwap)
colPDV   = input.color(color.new(#2962ff, 40), "", inline = "pdv", group = g_vwap)
showWV   = input.bool(true,  "Weekly VWAP", inline = "wv", group = g_vwap)
colWV    = input.color(#e91e63, "", inline = "wv", group = g_vwap)
showPWV  = input.bool(false, "Prev week VWAP close", inline = "pwv", group = g_vwap)
colPWV   = input.color(color.new(#e91e63, 40), "", inline = "pwv", group = g_vwap)
 
// ── Moving averages ──────────────────────────────────────────────────────────
maSrc  = input.source(close, "Source", group = g_ma)
maPlot = input.bool(true, "Plot the averages on the chart", group = g_ma)
maWait = input.bool(true, "Wait for the higher-timeframe bar to close", group = g_ma,
     tooltip = "On: an MA on a higher timeframe only updates when that bar closes, so its last segment never repaints. Off: it updates tick by tick. Ignored when the MA's timeframe matches the chart's.")
 
maT1 = input.string("EMA", "MA 1", inline = "m1", group = g_ma,
     options = ["SMA", "EMA", "WMA", "RMA", "HMA", "DEMA", "TEMA", "VWMA", "ALMA", "T3", "ZLEMA", "KAMA"])
maL1 = input.int(20, "", minval = 1, maxval = 2000, inline = "m1", group = g_ma)
maF1 = input.timeframe("", "", inline = "m1", group = g_ma)
maOn1 = input.bool(true, "", inline = "m1c", group = g_ma)
maCol1 = input.color(#42a5f5, "", inline = "m1c", group = g_ma)
maW1 = input.int(1, "", minval = 1, maxval = 4, inline = "m1c", group = g_ma,
     tooltip = "Enable · colour · line width for MA 1. Leave the timeframe blank to use the chart's.")
 
maT2 = input.string("EMA", "MA 2", inline = "m2", group = g_ma,
     options = ["SMA", "EMA", "WMA", "RMA", "HMA", "DEMA", "TEMA", "VWMA", "ALMA", "T3", "ZLEMA", "KAMA"])
maL2 = input.int(50, "", minval = 1, maxval = 2000, inline = "m2", group = g_ma)
maF2 = input.timeframe("", "", inline = "m2", group = g_ma)
maOn2 = input.bool(true, "", inline = "m2c", group = g_ma)
maCol2 = input.color(#ab47bc, "", inline = "m2c", group = g_ma)
maW2 = input.int(1, "", minval = 1, maxval = 4, inline = "m2c", group = g_ma)
 
maT3 = input.string("EMA", "MA 3", inline = "m3", group = g_ma,
     options = ["SMA", "EMA", "WMA", "RMA", "HMA", "DEMA", "TEMA", "VWMA", "ALMA", "T3", "ZLEMA", "KAMA"])
maL3 = input.int(200, "", minval = 1, maxval = 2000, inline = "m3", group = g_ma)
maF3 = input.timeframe("", "", inline = "m3", group = g_ma)
maOn3 = input.bool(true, "", inline = "m3c", group = g_ma)
maCol3 = input.color(#ef5350, "", inline = "m3c", group = g_ma)
maW3 = input.int(1, "", minval = 1, maxval = 4, inline = "m3c", group = g_ma)
 
// Shared by whichever MAs use those types, rather than three copies of each.
almaOff = input.float(0.85, "ALMA offset", minval = 0, maxval = 1, step = 0.05, group = g_max)
almaSig = input.float(6.0, "ALMA sigma", minval = 1, step = 0.5, group = g_max)
t3Fac   = input.float(0.7, "T3 factor", minval = 0, maxval = 1, step = 0.05, group = g_max)
kFast   = input.int(2, "KAMA fast length", minval = 1, group = g_max)
kSlow   = input.int(30, "KAMA slow length", minval = 1, group = g_max)
 
// ── Sweeps ───────────────────────────────────────────────────────────────────
// ── Impulse / displacement ───────────────────────────────────────────────────
impOn    = input.bool(true, "Mark impulse candles on the chart timeframe", group = g_imp,
     tooltip = "Any candle whose CLOSE travels at least this far from its OPEN, in ATR. Independent of gaps — this is the raw ingredient the research kept pointing at.")
impMin   = input.float(1.0, "Impulse threshold (ATR)", minval = 0.2, step = 0.1, group = g_imp)
impPaint = input.bool(true, "Colour the impulse candles", group = g_imp)
impMark  = input.bool(false, "Also mark them with a triangle", group = g_imp)
colImpU  = input.color(#089981, "Up  ·  down", inline = "ic", group = g_imp)
colImpD  = input.color(#f23645, "", inline = "ic", group = g_imp)
 
sweepOn   = input.bool(true, "Detect key-level sweeps", group = g_swp,
     tooltip = "A sweep is a bar that trades THROUGH a level and closes back on the original side. The most recent one is stamped onto any gap that forms shortly after.")
sweepBars = input.int(10, "Stamp a gap if a sweep happened within this many of its own bars", minval = 1, maxval = 100, group = g_swp)
sweepMark = input.bool(false, "Mark sweeps on the chart", group = g_swp)
colSweep  = input.color(#ff5252, "", inline = "sw", group = g_swp)
 
// ── Stats table ──────────────────────────────────────────────────────────────
tblOn    = input.bool(true, "Show the stats table", group = g_tbl)
tblPos   = input.string("Top right", "Position", group = g_tbl,
     options = ["Top right", "Top left", "Middle right", "Middle left",
                "Bottom right", "Bottom left"])
tblSize  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = g_tbl)
tblRows  = input.int(6, "Zones to list (nearest first)", minval = 1, maxval = 14, group = g_tbl)
tblIFVG  = input.bool(false, "List inverted gaps only", group = g_tbl)
tblPct   = input.bool(true, "Rank SIZE and MOVE against past zones (percentile)", group = g_tbl,
     tooltip = "Each timeframe keeps a rolling record of every gap it has produced on the loaded history, so a zone can be called big or small against that instrument's own habits rather than a fixed number.\n\np50 is typical, p90 is bigger than nine in ten, p10 smaller than nine in ten.")
pctMinN  = input.int(40, "Minimum sample before a percentile is shown", minval = 10, maxval = 400, group = g_tbl,
     tooltip = "Below this many recorded gaps the percentile is left blank rather than quoted off a handful of observations. Short chart history means fewer samples.")
tblLink  = input.bool(true, "Number the listed zones on the chart", group = g_tbl,
     tooltip = "Writes #1, #2 … onto the boxes themselves, matching the table rows, so you can tell which zone each row is talking about. The numbers are a ranking by distance from price, so they shuffle as price moves.")
tblMA    = input.bool(true, "Include the moving-average block", group = g_tbl)
tblDark  = input.bool(false, "Dark table", group = g_tbl)
 
// ── Level style ──────────────────────────────────────────────────────────────
lvlWidth   = input.int(1, "Line width", minval = 1, maxval = 4, group = g_lvl)
lvlExt     = input.int(30, "Extend right (bars)", minval = 0, maxval = 300, group = g_lvl)
lvlAnchor  = input.bool(true, "Start each line at its period open", group = g_lvl,
     tooltip = "Off = every line starts a fixed number of bars back.")
lvlBack    = input.int(80, "Fixed start (bars back)", minval = 5, maxval = 1000, group = g_lvl)
 
// ═════════════════════════════════════════════════════════════════════════════
// TYPES AND SMALL HELPERS
// ═════════════════════════════════════════════════════════════════════════════
 
type FVG
    box    bx
    line   ml
    float  top
    float  bot
    int    t          // open time of bar C — when the gap itself printed
    int    tInv       // open time of the bar whose close inverted it, na while intact
    bool   bull
    bool   inv
    string tfs        // timeframe label, for the table
    int    tfms       // that timeframe in ms — timeframe.in_seconds() needs a
                      // simple string, and a UDT field is series, so the bar
                      // length is resolved once here and stored
    int    slot
    float  atrF       // HTF ATR at the moment the gap formed
    float  atrRel     // and that ATR against its own 100-bar average
    bool   hit        // has price come back and touched the near edge yet
    bool   done       // outcome already banked into the pooled stats
    int    pband      // proximity band at inversion, 0 nearest … 4 isolated
    int    szq        // size tercile at inversion, 0 small … 2 big
    float  pen        // deepest point of the first visit, in zone heights
    bool   penDone    // that visit has ended and been recorded
    int    band       // READ band, fixed at inversion: 3 p90+ … 0 p0-30, -1 none
    float  thrust     // the three-bar move that made it, in ATR
    float  disp       // how far the inverting close went past it, in ATR
    string swept      // key level taken out just before it formed, "" if none
    bool   swAlign    // that sweep ran against the gap's own direction
 
type Gap
    box  bx
    line ml
 
type Lvl
    line  ln
    label lb
 
// One period's running range, plus the completed previous one.
type Rng
    float ch
    float cl
    float ph
    float pl
    int   bi
    bool  full = false
 
f_style(string s) =>
    s == "Solid" ? line.style_solid : s == "Dashed" ? line.style_dashed : line.style_dotted
 
f_lblsz(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
        => size.small
 
f_t3(float src, simple int len, float fac) =>
    float e1a = ta.ema(src, len)
    float e1b = ta.ema(e1a, len)
    float gd1 = e1a * (1 + fac) - e1b * fac
    float e2a = ta.ema(gd1, len)
    float e2b = ta.ema(e2a, len)
    float gd2 = e2a * (1 + fac) - e2b * fac
    float e3a = ta.ema(gd2, len)
    float e3b = ta.ema(e3a, len)
    e3a * (1 + fac) - e3b * fac
 
f_zlema(float src, simple int len) =>
    int lag = int(math.floor((len - 1) / 2))
    ta.ema(src + src - src[lag], len)
 
f_kama(float src, simple int len, simple int fast, simple int slow) =>
    float mom = math.abs(ta.change(src, len))
    float vol = math.sum(math.abs(ta.change(src)), len)
    float er  = vol != 0 ? mom / vol : 0
    float fa  = 2.0 / (fast + 1)
    float sa  = 2.0 / (slow + 1)
    float alp = math.pow(er * (fa - sa) + sa, 2)
    var float k = na
    k := alp * src + (1 - alp) * nz(k[1], src)
    k
 
// Every variant is evaluated on every bar and the active one picked with a
// switch. 
f_ma(string t, float src, simple int len) =>
    float e1 = ta.ema(src, len)
    float e2 = ta.ema(e1, len)
    float e3 = ta.ema(e2, len)
    switch t
        "SMA"   => ta.sma(src, len)
        "EMA"   => e1
        "WMA"   => ta.wma(src, len)
        "RMA"   => ta.rma(src, len)
        "HMA"   => ta.hma(src, len)
        "DEMA"  => 2 * e1 - e2
        "TEMA"  => 3 * (e1 - e2) + e3
        "VWMA"  => ta.vwma(src, len)
        "ALMA"  => ta.alma(src, len, almaOff, almaSig)
        "T3"    => f_t3(src, len, t3Fac)
        "ZLEMA" => f_zlema(src, len)
        "KAMA"  => f_kama(src, len, kFast, kSlow)
        => e1
 
f_tfHigher(simple string tf) =>
    timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
 
f_tblPos(string p) =>
    switch p
        "Top left"      => position.top_left
        "Middle right"  => position.middle_right
        "Middle left"   => position.middle_left
        "Bottom right"  => position.bottom_right
        "Bottom left"   => position.bottom_left
        => position.top_right
 
f_tblSz(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
var color CLEAR = color.new(color.gray, 100)
 
// Settled outcomes, pooled across the loaded history. 
var int STMAX = 4000
var array<int>    zrSlot  = array.new<int>()
var array<int>    zrSz    = array.new<int>()
var array<string> zrSwp   = array.new<string>()
var array<int>    zrPB    = array.new<int>()
var array<bool>   zrTouch = array.new<bool>()
var array<float>  zrDepth = array.new<float>()   // zone heights, na if untouched
 
// A zone owns two drawings; forgetting one leaves litter on the chart, so
// removal goes through a single door.
refOn = input.bool(true, "Fall back to NQ reference figures until the sample fills",
     group = g_tbl,
     tooltip = "RETEST, DEPTH and THROUGH are measured from your own chart, so they start empty and build slowly. Until a row has enough matches of its own it shows figures from the study instead, marked with a leading dot.\n\nThose come from 261,256 inverted gaps on NQ, 2010-2025, grouped only by distance to the nearest key level — the one effect in that study large and consistent enough to quote. Median first-visit depth ran 42% with a level inside the zone against 158% when the nearest was beyond 0.15%, and the through-rate 37% to 60%.\n\nThey are NQ's habits, not this instrument's. A dotted figure is a placeholder; an undotted one is yours.")
 
// NQ 2010-2025 by distance band, the fallback. Five bands of three: retest %,
// median first-visit depth %, through %.
var array<float> REF5  = array.from(95.3,  42.0, 37.5,
                                    96.0,  67.0, 47.5,
                                    95.7, 100.0, 50.2,
                                    94.3, 117.0, 55.5,
                                    92.5, 158.0, 59.9)
var array<float> REF15 = array.from(91.4,  30.0, 31.6,
                                    92.9,  67.0, 46.3,
                                    91.9,  79.0, 48.0,
                                    89.9, 100.0, 50.6,
                                    87.0, 120.0, 54.3)
 
// The 15m table for anything 15 minutes or slower, the 5m table below that.
f_ref(string tfs, int band, int which) =>
    array<float> t = timeframe.in_seconds(tfs) >= 900 ? REF15 : REF5
    array.get(t, band * 3 + which)
 
simMin = input.int(15, "Minimum matching zones before figures are quoted",
     minval = 5, maxval = 200, group = g_tbl,
     tooltip = "RETEST, DEPTH and THROUGH describe past zones that formed with the same setup as the one on that row. Below this many matches the test is loosened a step at a time rather than quoting numbers off a handful of cases.")
 
// Past zones with the SAME SETUP as the one being shown: same timeframe, same
// size tercile, same level swept before forming, same distance band. 
f_simZone(int slot, int szq, string swp, int pb) =>
    float rt = na
    float dp = na
    float th = na
    int cnt = 0
    int tier = -1
    int n = array.size(zrSlot)
    for lvl = 3 to 0
        if cnt >= simMin
            break
        int tot = 0
        int tch = 0
        int thr = 0
        array<float> dep = array.new<float>()
        if n > 0
            for i = 0 to n - 1
                if array.get(zrSlot, i) == slot
                    bool ok = true
                    if lvl >= 1 and array.get(zrPB, i) != pb
                        ok := false
                    if ok and lvl >= 2 and array.get(zrSz, i) != szq
                        ok := false
                    if ok and lvl >= 3 and array.get(zrSwp, i) != swp
                        ok := false
                    if ok
                        tot += 1
                        if array.get(zrTouch, i)
                            tch += 1
                            float dv = array.get(zrDepth, i)
                            if not na(dv)
                                array.push(dep, dv)
                                if dv >= 1.0
                                    thr += 1
        if tot >= simMin or (lvl == 0 and tot > 0)
            cnt := tot
            tier := lvl
            rt := 100.0 * tch / tot
            if array.size(dep) > 0
                dp := array.median(dep) * 100.0
                th := 100.0 * thr / array.size(dep)
    [rt, dp, th, cnt, tier]
 
// Which edge price meets first, and which way is "in favour" for this zone.
// An intact bullish gap is support, so price arrives at its TOP and favourable
// is up. Inverting flips both.
f_actBull(FVG g) => g.bull != g.inv
f_nearEdge(FVG g) => f_actBull(g) ? g.top : g.bot
 
// Written at the earlier of: the first visit ending, or the zone being removed.
// Recording on removal matters — a zone price closed straight through is
// deleted on the spot, and those are exactly the ones that went through.
f_recordZone(FVG g) =>
    if g.inv and not g.done
        g.done := true
        array.push(zrSlot, g.slot)
        array.push(zrSz, g.szq)
        array.push(zrSwp, g.swept)
        array.push(zrPB, g.pband)
        array.push(zrTouch, g.hit)
        array.push(zrDepth, g.hit ? nz(g.pen) : na)
        while array.size(zrSlot) > STMAX
            array.shift(zrSlot)
            array.shift(zrSz)
            array.shift(zrSwp)
            array.shift(zrPB)
            array.shift(zrTouch)
            array.shift(zrDepth)
    g.done
 
f_killZone(FVG g) =>
    f_recordZone(g)
    box.delete(g.bx)
    line.delete(g.ml)
    true
 
// Monospace keeps the table's numeric columns in vertical register.
var string MONO = font.family_monospace
 
// Fill colour for a gap on a given slot, in a given state.
f_fvgCol(int slot, bool bull, bool inv) =>
    color cb = slot == 1 ? c1b : slot == 2 ? c2b : c3b
    color cs = slot == 1 ? c1s : slot == 2 ? c2s : c3s
    color ci = slot == 1 ? c1i : slot == 2 ? c2i : c3i
    color out = inv ? (invFlip ? (bull ? cs : cb) : ci) : (bull ? cb : cs)
    onlyIFVG and not inv ? CLEAR : out
 
f_fvgBorder(int slot, bool bull, bool inv) =>
    (onlyIFVG and not inv) or not borderOn ? CLEAR : color.new(f_fvgCol(slot, bull, inv), 25)
 
f_fvgTxt(string tfs, bool inv) =>
    not labShow or not showTfTxt or (onlyIFVG and not inv) ? "" :
         tfs + (inv ? " IFVG" : " FVG")
 
// Rolling record of what this timeframe's gaps normally look like, so "big" and
// "small" mean something relative to the instrument rather than a fixed number
// of points. Capped so the oldest regime eventually drops out.
var int HISTN = 500
 
f_pushHist(array<float> a, float v) =>
    if not na(v) and v > 0
        array.push(a, v)
        while array.size(a) > HISTN
            array.shift(a)
    array.size(a)
 
// Percentile rank of v within a: the share of recorded gaps at or below it.
f_pctRank(array<float> a, float v) =>
    float out = na
    int n = array.size(a)
    if n >= pctMinN and not na(v)
        int c = 0
        for i = 0 to n - 1
            if array.get(a, i) <= v
                c += 1
        out := 100.0 * c / n
    out
 
// The verdict. Only the displacement percentile feeds it: size showed no
// predictive value over 15 years of NQ, so including it would dilute the one
// measure that did. Returns the word and a tier for colouring.
f_read(bool inv, float p) =>
    string t = "–"
    int tier = 0
    if not inv
        t := "pending"
    else if not na(p)
        if p >= 90
            t := "STRONG"
            tier := 4
        else if p >= 70
            t := "fair"
            tier := 3
        else if p >= 30
            t := "average"
            tier := 2
        else
            t := "poor"
            tier := 1
    [t, tier]
 
// "0.61  p72" — the raw multiple, then where it sits in that record.
f_withPct(float v, float p) =>
    na(v) ? "–" : str.tostring(v, "#.##") +
         (na(p) ? "" : "  p" + str.tostring(math.round(p)))
 
// ═════════════════════════════════════════════════════════════════════════════
// THE SESSION DAY — 18:00 → 17:00 ET
// ═════════════════════════════════════════════════════════════════════════════
 
int SOPEN = sessOpen == "17:00" ? 1020 : 1080
 
int md     = hour(time, TZ) * 60 + minute(time, TZ)
int noonTs = timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ), 12, 0)
 
int tradeTs = md >= SOPEN ? noonTs + 86400000 : noonTs   // noon of this bar's trade date
int tDow    = dayofweek(tradeTs, TZ)
int tMon    = month(tradeTs, TZ)
int tYr     = year(tradeTs, TZ)
 
// Trade week is identified by the Monday it contains, so a missing Sunday open
// (holiday, outage) still rolls the week over on the first session that trades.
int weekTs = tradeTs - ((tDow - dayofweek.monday + 7) % 7) * 86400000
int monId  = tYr * 12 + tMon
 
bool newSD = not na(tradeTs[1]) and tradeTs != tradeTs[1]
bool newSW = not na(weekTs[1])  and weekTs  != weekTs[1]
bool newSM = not na(monId[1])   and monId   != monId[1]
bool newSY = not na(tYr[1])     and tYr     != tYr[1]
 
// ═════════════════════════════════════════════════════════════════════════════
// PREVIOUS PERIOD HIGH / LOW — accumulated on the session day
// ═════════════════════════════════════════════════════════════════════════════
 
method roll(Rng r, bool isNew) =>
    if isNew
        // Only publish the period that just ended if it began at its own open.
        r.ph   := r.full ? r.ch : na
        r.pl   := r.full ? r.cl : na
        r.full := true
        r.ch := high
        r.cl := low
        r.bi := bar_index
    else
        r.ch := na(r.ch) ? high : math.max(r.ch, high)
        r.cl := na(r.cl) ? low  : math.min(r.cl, low)
        r.bi := na(r.bi) ? bar_index : r.bi
    r
 
var Rng rD = Rng.new()
var Rng rW = Rng.new()
var Rng rM = Rng.new()
var Rng rY = Rng.new()
 
rD.roll(newSD)
rW.roll(newSW)
rM.roll(newSM)
rY.roll(newSY)
 
// Month and year need a full prior period of loaded bars. Until the chart has
// one, borrow the calendar-period value rather than draw nothing.
[secMH, secML] = request.security(syminfo.tickerid, "M",   [high[1], low[1]], lookahead = barmerge.lookahead_on)
[secYH, secYL] = request.security(syminfo.tickerid, "12M", [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
float pmH = na(rM.ph) and htfFallback ? secMH : rM.ph
float pmL = na(rM.pl) and htfFallback ? secML : rM.pl
float pyH = na(rY.ph) and htfFallback ? secYH : rY.ph
float pyL = na(rY.pl) and htfFallback ? secYL : rY.pl
 
// ═════════════════════════════════════════════════════════════════════════════
// SESSION HIGH / LOW — Asia and London
// ═════════════════════════════════════════════════════════════════════════════
// The running extremes simply stop updating when the session ends, so what is on
// screen during the day is the last completed session.
 
bool inAsia = not na(time(timeframe.period, sessAsia + ":1234567", TZ))
bool inLon  = not na(time(timeframe.period, sessLon  + ":1234567", TZ))
 
var float asiaH = na, var float asiaL = na, var int asiaBar = na
var float lonH  = na, var float lonL  = na, var int lonBar  = na
 
if inAsia
    if not inAsia[1]
        asiaH   := high
        asiaL   := low
        asiaBar := bar_index
    else
        asiaH := na(asiaH) ? high : math.max(asiaH, high)
        asiaL := na(asiaL) ? low  : math.min(asiaL, low)
        asiaBar := na(asiaBar) ? bar_index : asiaBar
 
if inLon
    if not inLon[1]
        lonH   := high
        lonL   := low
        lonBar := bar_index
    else
        lonH := na(lonH) ? high : math.max(lonH, high)
        lonL := na(lonL) ? low  : math.min(lonL, low)
        lonBar := na(lonBar) ? bar_index : lonBar
 
// running session high / low, for the sweep test
var float sessH = na, var float sessL = na
if newSD
    sessH := high
    sessL := low
else
    sessH := na(sessH) ? high : math.max(sessH, high)
    sessL := na(sessL) ? low  : math.min(sessL, low)
 
// ═════════════════════════════════════════════════════════════════════════════
// VWAP — anchored on the same session day and session week
// ═════════════════════════════════════════════════════════════════════════════
 
// Cumulative, not per-bar: a thin overnight bar can legitimately print zero
// volume, and testing that bar alone would blank the whole VWAP on it.
bool hasVol = not na(ta.cum(volume)) and ta.cum(volume) > 0
float dVwap = ta.vwap(vwapSrc, newSD)
float wVwap = ta.vwap(vwapSrc, newSW)
 
var float pdVwap = na
var float pwVwap = na
if newSD
    pdVwap := dVwap[1]
if newSW
    pwVwap := wVwap[1]
 
// linebr + a gap on the anchor bar, so the reset is a break rather than a
// vertical line joining yesterday's last value to today's first.
plot(showDV and hasVol and not newSD ? dVwap : na, "Daily VWAP",
     color = colDV, linewidth = 1, style = plot.style_linebr)
plot(showWV and hasVol and not newSW ? wVwap : na, "Weekly VWAP",
     color = colWV, linewidth = 1, style = plot.style_linebr)
 
// Distance from a zone to the nearest of the twelve key levels, as a percent of
// price. 
f_lvlGap(float lv, float tp, float bt) =>
    na(lv) ? 1e9 : lv >= bt and lv <= tp ? 0.0 :
         math.min(math.abs(lv - bt), math.abs(lv - tp))
 
f_nearDist(float tp, float bt) =>
    float m = 1e9
    m := math.min(m, f_lvlGap(rD.ph, tp, bt))
    m := math.min(m, f_lvlGap(rD.pl, tp, bt))
    m := math.min(m, f_lvlGap(rW.ph, tp, bt))
    m := math.min(m, f_lvlGap(rW.pl, tp, bt))
    m := math.min(m, f_lvlGap(dVwap, tp, bt))
    m := math.min(m, f_lvlGap(wVwap, tp, bt))
    m := math.min(m, f_lvlGap(asiaH, tp, bt))
    m := math.min(m, f_lvlGap(asiaL, tp, bt))
    m := math.min(m, f_lvlGap(lonH, tp, bt))
    m := math.min(m, f_lvlGap(lonL, tp, bt))
    m >= 1e8 or close <= 0 ? na : m / close * 100.0
 
// 0 inside · 1 to 0.02% · 2 to 0.06% · 3 to 0.15% · 4 beyond
f_band(float dpc) =>
    na(dpc) ? 4 : dpc <= 0.0 ? 0 : dpc <= 0.02 ? 1 : dpc <= 0.06 ? 2 : dpc <= 0.15 ? 3 : 4
 
// ═════════════════════════════════════════════════════════════════════════════
// LIQUIDITY SWEEPS
// ═════════════════════════════════════════════════════════════════════════════
// A sweep is a bar that trades THROUGH a level and closes back on the side it
// came from. 
 
f_sweptHi(float lvl) => not na(lvl) and high > lvl and close < lvl
f_sweptLo(float lvl) => not na(lvl) and low  < lvl and close > lvl
 
var int    swTs   = na       // when the most recent sweep happened
var int    swBar  = na       // and on which bar, for "n bars ago"
var string swName = ""       // which level it took out
var bool   swHi   = false    // true = a high was swept (liquidity above)
 
if sweepOn
    string nm = ""
    bool hiSide = false
    // checked in order; the first hit on this bar is the one recorded
    if f_sweptHi(rD.ph)
        nm := "PDH", hiSide := true
    else if f_sweptLo(rD.pl)
        nm := "PDL", hiSide := false
    else if f_sweptHi(rW.ph)
        nm := "PWH", hiSide := true
    else if f_sweptLo(rW.pl)
        nm := "PWL", hiSide := false
    else if f_sweptHi(asiaH[1])
        nm := "ASH", hiSide := true
    else if f_sweptLo(asiaL[1])
        nm := "ASL", hiSide := false
    else if f_sweptHi(lonH[1])
        nm := "LNH", hiSide := true
    else if f_sweptLo(lonL[1])
        nm := "LNL", hiSide := false
    else if f_sweptHi(sessH[1])
        nm := "SH", hiSide := true
    else if f_sweptLo(sessL[1])
        nm := "SL", hiSide := false
    if nm != ""
        swTs   := time
        swBar  := bar_index
        swName := nm
        swHi   := hiSide
        if sweepMark
            label.new(bar_index, hiSide ? high : low, nm,
                 style = hiSide ? label.style_label_down : label.style_label_up,
                 color = color.new(colSweep, 20), textcolor = color.white,
                 size = size.tiny)
 
// ═════════════════════════════════════════════════════════════════════════════
// FVG / IFVG ENGINE
// ═════════════════════════════════════════════════════════════════════════════
 
[t1, a1, h1C, l1C, c1C, h1A, l1A, o1A, at1, av1] = request.security(syminfo.tickerid, tf1,
     [time[1], time[3], high[1], low[1], close[1], high[3], low[3], open[3], ta.atr(14)[1],
      ta.atr(14)[1] / ta.sma(ta.atr(14), 100)[1]],
     lookahead = barmerge.lookahead_on)
[t2, a2, h2C, l2C, c2C, h2A, l2A, o2A, at2, av2] = request.security(syminfo.tickerid, tf2,
     [time[1], time[3], high[1], low[1], close[1], high[3], low[3], open[3], ta.atr(14)[1],
      ta.atr(14)[1] / ta.sma(ta.atr(14), 100)[1]],
     lookahead = barmerge.lookahead_on)
[t3, a3, h3C, l3C, c3C, h3A, l3A, o3A, at3, av3] = request.security(syminfo.tickerid, tf3,
     [time[1], time[3], high[1], low[1], close[1], high[3], low[3], open[3], ta.atr(14)[1],
      ta.atr(14)[1] / ta.sma(ta.atr(14), 100)[1]],
     lookahead = barmerge.lookahead_on)
 
var array<FVG> st1 = array.new<FVG>()
var array<FVG> st2 = array.new<FVG>()
var array<FVG> st3 = array.new<FVG>()
 
// one record of gap sizes and one of break displacements, per timeframe slot
var array<float> szH1 = array.new<float>(), var array<float> dsH1 = array.new<float>()
var array<float> szH2 = array.new<float>(), var array<float> dsH2 = array.new<float>()
var array<float> szH3 = array.new<float>(), var array<float> dsH3 = array.new<float>()
 
// A requested timeframe below the chart's own resolution cannot be resolved
// honestly, so those slots are skipped rather than drawn wrong.
tfOK1 = timeframe.in_seconds(tf1) >= timeframe.in_seconds()
tfOK2 = timeframe.in_seconds(tf2) >= timeframe.in_seconds()
tfOK3 = timeframe.in_seconds(tf3) >= timeframe.in_seconds()
 
new1 = not na(t1) and (na(t1[1]) or t1 != t1[1])
new2 = not na(t2) and (na(t2[1]) or t2 != t2[1])
new3 = not na(t3) and (na(t3[1]) or t3 != t3[1])
 
f_runFvg(int slot, bool en, string tfs, bool isNew, int tC, int tA, float hC, float lC,
         float cC, float hA, float lA, float oA, float atrH, float atrRel,
         int maxN, array<FVG> st, array<float> szH, array<float> dsH) =>
    bool made = false
    bool invd = false
    if en and fvgOn and isNew and not na(tC) and not na(hA) and not na(lA)
        int tfms = timeframe.in_seconds(tfs) * 1000
 
        // ── 1. inversion and retirement, judged on this HTF bar's close
        if array.size(st) > 0
            for i = array.size(st) - 1 to 0
                FVG g = array.get(st, i)
                if g.t < tC
                    if not g.inv
                        bool through = g.bull ? cC < g.bot : cC > g.top
                        if through
                            if keepIFVG
                                g.inv  := true
                                g.tInv := tC
                                invd   := true
                                // the zone now faces the other way, so its near
                                // edge is the opposite one and anything measured
                                // against the old edge no longer applies
                                g.hit  := false
                                g.done := false
                                g.pband := f_band(f_nearDist(g.top, g.bot))
                                float szp = na(g.atrF) or g.atrF <= 0 ? na :
                                     f_pctRank(szH, (g.top - g.bot) / g.atrF)
                                g.szq := na(szp) ? 1 : szp >= 67 ? 2 : szp >= 33 ? 1 : 0
                                g.pen := na
                                g.penDone := false
                                // how decisively the break closed through, in ATR.
                                g.band := -1
                                if not na(atrH) and atrH > 0
                                    g.disp := (g.bull ? g.bot - cC : cC - g.top) / atrH
                                    float bp = f_pctRank(dsH, g.disp)
                                    g.band := na(bp) ? -1 :
                                         bp >= 90 ? 3 : bp >= 70 ? 2 : bp >= 30 ? 1 : 0
                                    f_pushHist(dsH, g.disp)
                                box.set_bgcolor(g.bx, f_fvgCol(slot, g.bull, true))
                                box.set_border_color(g.bx, f_fvgBorder(slot, g.bull, true))
                                box.set_text(g.bx, f_fvgTxt(tfs, true))
                                box.set_text_color(g.bx, color.new(f_fvgCol(slot, g.bull, true), 20))
                                if not na(g.ml)
                                    line.set_color(g.ml, color.new(f_fvgCol(slot, g.bull, true), 30))
                            else
                                f_killZone(g)
                                array.remove(st, i)
                    else
                        // an IFVG is spent once price closes back through it
                        bool spent = g.bull ? cC > g.top : cC < g.bot
                        if spent
                            f_killZone(g)
                            array.remove(st, i)
 
        // ── 2. a new gap on the bar that just closed
        bool isBull = lC > hA
        bool isBear = hC < lA
        if isBull or isBear
            float gt = isBull ? lC : lA
            float gb = isBull ? hA : hC
            if gt - gb >= minTicks * syminfo.mintick and gt > gb
                FVG g = FVG.new()
                g.top  := gt
                g.bot  := gb
                g.t    := tC
                g.tInv := int(na)
                g.bull := isBull
                g.inv  := false
                g.tfs  := tfs
                g.tfms := tfms
                g.slot := slot
                g.atrF := atrH
                g.atrRel := atrRel
                g.hit := false
                g.done := false
                g.pband := f_band(f_nearDist(gt, gb))
                g.szq := 1
                g.pen := na
                g.penDone := false
                g.thrust := float(na)
                g.disp   := float(na)
                if not na(atrH) and atrH > 0 and not na(oA)
                    g.thrust := (cC - oA) / atrH
                if not na(atrH) and atrH > 0
                    f_pushHist(szH, (gt - gb) / atrH)
                // stamp any sweep that happened shortly before this gap formed
                g.swept := ""
                g.swAlign := false
                // The window is measured back from the END of bar C, so a sweep
                // made by the displacement candle itself still counts — that is
                // the "swept the lows then ran" pattern people mean.
                int tEnd = tC + tfms
                if sweepOn and not na(swTs) and swTs <= tEnd and tEnd - swTs <= sweepBars * tfms
                    g.swept := swName
                    // a sweep of lows before a bullish gap (and the mirror) is
                    // the alignment people mean by "swept then displaced"
                    g.swAlign := isBull ? not swHi : swHi
                int lf = na(tA) ? tC - 2 * tfms : tA
                int rt = boxMode == "Fixed length" ? tC + boxBars * tfms : tC + tfms
                g.bx := box.new(lf, gt, rt, gb, xloc = xloc.bar_time,
                     bgcolor      = f_fvgCol(slot, isBull, false),
                     border_color = f_fvgBorder(slot, isBull, false),
                     border_width = 1,
                     extend       = boxMode == "Infinite right" ? extend.right : extend.none,
                     text         = f_fvgTxt(tfs, false),
                     text_size    = f_lblsz(labSize),
                     text_color   = color.new(f_fvgCol(slot, isBull, false), 20),
                     text_halign  = text.align_right,
                     text_valign  = text.align_center)
                if showMidFvg
                    float ce = (gt + gb) / 2
                    g.ml := line.new(lf, ce, rt, ce, xloc = xloc.bar_time,
                         color = color.new(f_fvgCol(slot, isBull, false), 30),
                         style = line.style_dotted,
                         extend = boxMode == "Infinite right" ? extend.right : extend.none)
                array.push(st, g)
                made := true
 
        // ── 3. keep the stack within its limit, oldest out first
        while array.size(st) > maxN
            FVG g0 = array.shift(st)
            f_killZone(g0)
    [made, invd]
 
f_clearFvg(bool live, array<FVG> st) =>
    if not live
        while array.size(st) > 0
            FVG g0 = array.shift(st)
            f_killZone(g0)
    st
 
f_stretch(array<FVG> st, bool live, int rightTs) =>
    if live and boxMode == "To the current candle" and array.size(st) > 0
        for i = 0 to array.size(st) - 1
            FVG g = array.get(st, i)
            if g.t <= rightTs
                box.set_right(g.bx, rightTs)
                if not na(g.ml)
                    line.set_x2(g.ml, rightTs)
    array.size(st)
 
// Retest tracking on the ZONE'S OWN timeframe, not the chart's.
 
f_track(array<FVG> st, bool live, bool isNew, int tC, float hC, float lC) =>
    if live and isNew and not na(hC) and array.size(st) > 0
        for i = 0 to array.size(st) - 1
            FVG g = array.get(st, i)
            bool fresh = g.t >= tC or (g.inv and not na(g.tInv) and g.tInv >= tC)
            if not fresh and not na(g.atrF) and g.atrF > 0
                bool up = f_actBull(g)
                float ed = f_nearEdge(g)
                // penetration in zone heights: 0 at the near edge, 1 at the far
                // edge, above 1 once price is through
                float hh = math.max(g.top - g.bot, syminfo.mintick)
                float pn = (up ? ed - lC : hC - ed) / hh
                if not g.hit
                    if up ? lC <= ed : hC >= ed
                        g.hit := true
                        g.pen := math.max(pn, 0.0)
                else
                    if not g.penDone
                        if pn > 0
                            g.pen := math.max(nz(g.pen), pn)
                        else
                            g.penDone := true
                            f_recordZone(g)
    array.size(st)
 
f_clearFvg(fvgOn and en1 and tfOK1, st1)
f_clearFvg(fvgOn and en2 and tfOK2, st2)
f_clearFvg(fvgOn and en3 and tfOK3, st3)
 
[mk1, iv1] = f_runFvg(1, en1 and tfOK1, tf1, new1, t1, a1, h1C, l1C, c1C, h1A, l1A, o1A, at1, av1, n1, st1, szH1, dsH1)
[mk2, iv2] = f_runFvg(2, en2 and tfOK2, tf2, new2, t2, a2, h2C, l2C, c2C, h2A, l2A, o2A, at2, av2, n2, st2, szH2, dsH2)
[mk3, iv3] = f_runFvg(3, en3 and tfOK3, tf3, new3, t3, a3, h3C, l3C, c3C, h3A, l3A, o3A, at3, av3, n3, st3, szH3, dsH3)
 
// A timeframe below the chart's resolution is skipped silently otherwise.
var label lbWarn = na
if barstate.islast
    string warn = ""
    warn += en1 and not tfOK1 ? "TF1 " + tf1 + "  " : ""
    warn += en2 and not tfOK2 ? "TF2 " + tf2 + "  " : ""
    warn += en3 and not tfOK3 ? "TF3 " + tf3 + "  " : ""
    label.delete(lbWarn)
    if fvgOn and warn != ""
        lbWarn := label.new(bar_index, high, "⚠ below chart TF, skipped:  " + warn,
             xloc = xloc.bar_index, style = label.style_label_down,
             color = color.new(color.orange, 20), textcolor = color.white, size = size.small)
 
f_track(st1, fvgOn and en1 and tfOK1, new1, t1, h1C, l1C)
f_track(st2, fvgOn and en2 and tfOK2, new2, t2, h2C, l2C)
f_track(st3, fvgOn and en3 and tfOK3, new3, t3, h3C, l3C)
 
int nowRight = time + timeframe.in_seconds() * 1000
f_stretch(st1, fvgOn and en1 and tfOK1, nowRight)
f_stretch(st2, fvgOn and en2 and tfOK2, nowRight)
f_stretch(st3, fvgOn and en3 and tfOK3, nowRight)
 
if alertFvg and (mk1 or mk2 or mk3)
    alert("New FVG on " + syminfo.ticker, alert.freq_once_per_bar_close)
if alertFvg and (iv1 or iv2 or iv3)
    alert("FVG inverted (IFVG) on " + syminfo.ticker, alert.freq_once_per_bar_close)
 
// ═════════════════════════════════════════════════════════════════════════════
// OPENING GAPS — 17:00 close to 18:00 open
// ═════════════════════════════════════════════════════════════════════════════
 
var array<Gap> ndogs = array.new<Gap>()
var array<Gap> nwogs = array.new<Gap>()
 
f_newGap(array<Gap> store, int keep, color css, float a, float b) =>
    float gt = math.max(a, b)
    float gb = math.min(a, b)
    if gt - gb >= syminfo.mintick
        Gap g = Gap.new()
        g.bx := box.new(bar_index - 1, gt, bar_index, gb, xloc = xloc.bar_index,
             bgcolor = css, border_color = color.new(css, 40), border_width = 1,
             extend = extend.right)
        if gapMid
            float ce = (gt + gb) / 2
            g.ml := line.new(bar_index - 1, ce, bar_index, ce, xloc = xloc.bar_index,
                 color = color.new(css, 30), style = line.style_dotted, extend = extend.right)
        array.push(store, g)
    while array.size(store) > keep
        Gap g0 = array.shift(store)
        box.delete(g0.bx)
        line.delete(g0.ml)
    store
 
// Sunday's gap is a NWOG, so it is not also drawn as a NDOG.
if showNDOG and newSD and not newSW and not na(close[1])
    f_newGap(ndogs, nNDOG, colNDOG, close[1], open)
if showNWOG and newSW and not na(close[1])
    f_newGap(nwogs, nNWOG, colNWOG, close[1], open)
 
// ═════════════════════════════════════════════════════════════════════════════
// OPENS
// ═════════════════════════════════════════════════════════════════════════════
 
var float dOpen = na
var float wOpen = na
 
if newSD
    dOpen := open
if newSW
    wOpen := open
 
// ═════════════════════════════════════════════════════════════════════════════
// MOVING AVERAGES
// ═════════════════════════════════════════════════════════════════════════════
 
float raw1 = f_ma(maT1, maSrc, maL1)
float raw2 = f_ma(maT2, maSrc, maL2)
float raw3 = f_ma(maT3, maSrc, maL3)
 
cf1 = request.security(syminfo.tickerid, maF1, raw1[1], lookahead = barmerge.lookahead_on)
lv1 = request.security(syminfo.tickerid, maF1, raw1,    lookahead = barmerge.lookahead_off)
cf2 = request.security(syminfo.tickerid, maF2, raw2[1], lookahead = barmerge.lookahead_on)
lv2 = request.security(syminfo.tickerid, maF2, raw2,    lookahead = barmerge.lookahead_off)
cf3 = request.security(syminfo.tickerid, maF3, raw3[1], lookahead = barmerge.lookahead_on)
lv3 = request.security(syminfo.tickerid, maF3, raw3,    lookahead = barmerge.lookahead_off)
 
float ma1 = maWait and f_tfHigher(maF1) ? cf1 : lv1
float ma2 = maWait and f_tfHigher(maF2) ? cf2 : lv2
float ma3 = maWait and f_tfHigher(maF3) ? cf3 : lv3
 
var label lbMaWarn = na
if barstate.islast
    string bad = ""
    bad += maOn1 and timeframe.in_seconds(maF1) < timeframe.in_seconds() ? "MA1 " : ""
    bad += maOn2 and timeframe.in_seconds(maF2) < timeframe.in_seconds() ? "MA2 " : ""
    bad += maOn3 and timeframe.in_seconds(maF3) < timeframe.in_seconds() ? "MA3 " : ""
    label.delete(lbMaWarn)
    if bad != ""
        lbMaWarn := label.new(bar_index, low,
             "⚠ below chart TF, under-sampled:  " + bad, xloc = xloc.bar_index,
             style = label.style_label_up, color = color.new(color.orange, 20),
             textcolor = color.white, size = size.small)
 
float atrChart = ta.atr(14)
float atrChartAvg = ta.sma(atrChart, 100)
 
plot(maPlot and maOn1 ? ma1 : na, "MA 1", color = maCol1, linewidth = maW1)
plot(maPlot and maOn2 ? ma2 : na, "MA 2", color = maCol2, linewidth = maW2)
plot(maPlot and maOn3 ? ma3 : na, "MA 3", color = maCol3, linewidth = maW3)
 
// ═════════════════════════════════════════════════════════════════════════════
// IMPULSE CANDLES
// ═════════════════════════════════════════════════════════════════════════════
 
float impAtr = na(atrChart) or atrChart <= 0 ? na :
     math.abs(close - open) / atrChart
bool isImp = impOn and not na(impAtr) and impAtr >= impMin
 
var array<float> impHist = array.new<float>()
var int   impBar = na
var float impSz  = na
var bool  impUp  = false
if isImp
    f_pushHist(impHist, impAtr)
    impBar := bar_index
    impSz  := impAtr
    impUp  := close > open
 
barcolor(impPaint and isImp ? (close > open ? colImpU : colImpD) : na,
     title = "Impulse candles")
plotshape(impMark and isImp and close > open, "Impulse up", shape.triangleup,
     location.belowbar, colImpU, size = size.tiny)
plotshape(impMark and isImp and close < open, "Impulse down", shape.triangledown,
     location.abovebar, colImpD, size = size.tiny)
 
// ═════════════════════════════════════════════════════════════════════════════
// LEVEL DRAWING
// ═════════════════════════════════════════════════════════════════════════════
 
f_lvl(Lvl lv, bool show, float y, int x1, string txt, color css, string sty) =>
    if not show or na(y)
        line.delete(lv.ln)
        label.delete(lv.lb)
        lv.ln := na
        lv.lb := na
    else
        int x2 = bar_index + lvlExt
        int xl = lvlAnchor and not na(x1) ? math.min(x1, bar_index) : bar_index - lvlBack
        if na(lv.ln)
            lv.ln := line.new(xl, y, x2, y, xloc = xloc.bar_index, color = css,
                 style = f_style(sty), width = lvlWidth)
        else
            line.set_xy1(lv.ln, xl, y)
            line.set_xy2(lv.ln, x2, y)
            line.set_color(lv.ln, css)
            line.set_style(lv.ln, f_style(sty))
            line.set_width(lv.ln, lvlWidth)
        if labShow
            string full = txt + (labPrice ? "  " + str.tostring(y, format.mintick) : "")
            if na(lv.lb)
                lv.lb := label.new(bar_index + labOff, y, full, xloc = xloc.bar_index,
                     style = label.style_none, color = CLEAR, textcolor = css,
                     size = f_lblsz(labSize), textalign = text.align_left)
            else
                label.set_xy(lv.lb, bar_index + labOff, y)
                label.set_text(lv.lb, full)
                label.set_textcolor(lv.lb, css)
                label.set_size(lv.lb, f_lblsz(labSize))
        else
            label.delete(lv.lb)
            lv.lb := na
    lv
 
var Lvl L_pdh = Lvl.new(), var Lvl L_pdl = Lvl.new()
var Lvl L_pwh = Lvl.new(), var Lvl L_pwl = Lvl.new()
var Lvl L_pmh = Lvl.new(), var Lvl L_pml = Lvl.new()
var Lvl L_pyh = Lvl.new(), var Lvl L_pyl = Lvl.new()
var Lvl L_ah  = Lvl.new(), var Lvl L_al  = Lvl.new()
var Lvl L_lh  = Lvl.new(), var Lvl L_ll  = Lvl.new()
var Lvl L_do  = Lvl.new(), var Lvl L_wo  = Lvl.new()
var Lvl L_pdv = Lvl.new(), var Lvl L_pwv = Lvl.new()
 
if barstate.islast
    f_lvl(L_pdh, showPD, rD.ph, rD.bi, "PDH", colPD, styPD)
    f_lvl(L_pdl, showPD, rD.pl, rD.bi, "PDL", colPD, styPD)
    f_lvl(L_pwh, showPW, rW.ph, rW.bi, "PWH", colPW, styPW)
    f_lvl(L_pwl, showPW, rW.pl, rW.bi, "PWL", colPW, styPW)
    f_lvl(L_pmh, showPM, pmH,   rM.bi, "PMH", colPM, styPM)
    f_lvl(L_pml, showPM, pmL,   rM.bi, "PML", colPM, styPM)
    f_lvl(L_pyh, showPY, pyH,   rY.bi, "PYH", colPY, styPY)
    f_lvl(L_pyl, showPY, pyL,   rY.bi, "PYL", colPY, styPY)
 
    f_lvl(L_ah, showAsia, asiaH, asiaBar, "Asia High",   colAsia, styAsia)
    f_lvl(L_al, showAsia, asiaL, asiaBar, "Asia Low",    colAsia, styAsia)
    f_lvl(L_lh, showLon,  lonH,  lonBar,  "London High", colLon,  styLon)
    f_lvl(L_ll, showLon,  lonL,  lonBar,  "London Low",  colLon,  styLon)
 
    f_lvl(L_do, showDO, dOpen, rD.bi, "Daily Open",  colDO, styDO)
    f_lvl(L_wo, showWO, wOpen, rW.bi, "Weekly Open", colWO, styWO)
 
    f_lvl(L_pdv, showPDV and hasVol, pdVwap, rD.bi, "Prev D VWAP", colPDV, "Dotted")
    f_lvl(L_pwv, showPWV and hasVol, pwVwap, rW.bi, "Prev W VWAP", colPWV, "Dotted")
 
// Labels for the two live VWAP curves, parked at the last bar.
var label lbDV = na
var label lbWV = na
if barstate.islast
    label.delete(lbDV)
    label.delete(lbWV)
    if showDV and hasVol and not na(dVwap) and labShow
        lbDV := label.new(bar_index + labOff, dVwap, "D VWAP", xloc = xloc.bar_index,
             style = label.style_none, color = CLEAR, textcolor = colDV,
             size = f_lblsz(labSize), textalign = text.align_left)
    if showWV and hasVol and not na(wVwap) and labShow
        lbWV := label.new(bar_index + labOff, wVwap, "W VWAP", xloc = xloc.bar_index,
             style = label.style_none, color = CLEAR, textcolor = colWV,
             size = f_lblsz(labSize), textalign = text.align_left)
 
// ═════════════════════════════════════════════════════════════════════════════
// STATS TABLE
// ═════════════════════════════════════════════════════════════════════════════
// Every live zone across the enabled timeframes, sorted by how far price is from
// it, nearest first. Distance is to the NEAR edge, so a zone price is sitting
// inside reads 0.00% and is marked IN.
 
// distance from price to the near edge of a zone, in percent of price
f_zdist(float tp, float bt) =>
    close >= bt and close <= tp ? 0.0 :
         close < bt ? (bt - close) / close * 100.0 : (close - tp) / close * 100.0
 
var table ST = na
 
var array<float>  zTop = array.new<float>()
var array<float>  zBot = array.new<float>()
var array<float>  zDst = array.new<float>()
var array<bool>   zBul = array.new<bool>()
var array<bool>   zInv = array.new<bool>()
var array<string> zTf  = array.new<string>()
var array<float>  zThr = array.new<float>()
var array<float>  zDsp = array.new<float>()
var array<float>  zAtr = array.new<float>()
var array<box>    zBx  = array.new<box>()   // so a row can label its own box
var array<string> zSw  = array.new<string>()
var array<bool>   zSwA = array.new<bool>()
var array<int>    zPB  = array.new<int>()   // proximity band
var array<int>    zSlot = array.new<int>()
var array<int>    zSzq = array.new<int>()
var array<float>  zVol = array.new<float>() // ATR at formation vs its own average
var array<float>  zSzP = array.new<float>() // size as a percentile of past gaps
var array<float>  zDsP = array.new<float>() // displacement, same idea
var array<int>    zAge = array.new<int>()   // bars since the gap printed
var array<int>    zAgI = array.new<int>()   // bars since it inverted, -1 if intact
 
// Box caption. rank > 0 prefixes the table's row number, which is what ties a
// row to the box it describes; rank 0 restores the plain caption.
f_rankTxt(string tfs, bool inv, int rank) =>
    string out = ""
    if labShow and not (onlyIFVG and not inv)
        if showTfTxt
            out := tfs + (inv ? " IFVG" : " FVG")
        if tblLink and rank > 0
            out := "#" + str.tostring(rank) + (out == "" ? "" : "  " + out)
    out
 
f_resetTxt(array<FVG> st, bool live) =>
    if live and array.size(st) > 0
        for i = 0 to array.size(st) - 1
            FVG g = array.get(st, i)
            box.set_text(g.bx, f_rankTxt(g.tfs, g.inv, 0))
    array.size(st)
 
f_gather(array<FVG> st, bool live, array<float> szH, array<float> dsH) =>
    if live and array.size(st) > 0
        for i = 0 to array.size(st) - 1
            FVG g = array.get(st, i)
            if not (tblIFVG or onlyIFVG) or g.inv
                array.push(zTop, g.top)
                array.push(zBot, g.bot)
                array.push(zDst, f_zdist(g.top, g.bot))
                array.push(zBul, g.bull)
                array.push(zInv, g.inv)
                array.push(zTf, g.tfs)
                array.push(zThr, g.thrust)
                array.push(zDsp, g.disp)
                array.push(zAtr, g.atrF)
                array.push(zVol, g.atrRel)
                array.push(zPB, g.pband)
                array.push(zSlot, g.slot)
                array.push(zSzq, g.szq)
                float szA = na(g.atrF) or g.atrF <= 0 ? na : (g.top - g.bot) / g.atrF
                array.push(zSzP, f_pctRank(szH, szA))
                array.push(zDsP, f_pctRank(dsH, g.disp))
                array.push(zBx, g.bx)
                array.push(zSw, g.swept)
                array.push(zSwA, g.swAlign)
                array.push(zAge, g.tfms > 0 ? int((time - g.t) / g.tfms) : 0)
                array.push(zAgI, g.tfms > 0 and not na(g.tInv) ?
                     int((time - g.tInv) / g.tfms) : -1)
    array.size(zDst)
 
// one moving-average row; returns 1 if it drew, so the caller can advance
f_maRow(bool on, float v, string ty, int len, string tf, color cm, int rr,
        string tsz, color cAlt, color cRow0, color cDim) =>
    int used = 0
    if on and not na(v)
        float dd = (close - v) / close * 100.0
        color cRow = rr % 2 == 0 ? cAlt : cRow0
        table.cell(ST, 0, rr, ty + " " + str.tostring(len), bgcolor = cRow,
             text_color = cm, text_size = tsz, text_halign = text.align_left, text_font_family = MONO)
        table.cell(ST, 1, rr, tf == "" ? "chart" : tf, bgcolor = cRow,
             text_color = cDim, text_size = tsz, text_font_family = MONO)
        table.cell(ST, 2, rr, (dd >= 0 ? "+" : "") + str.tostring(dd, "#.###") + "%",
             bgcolor = cRow, text_size = tsz,
             text_color = dd >= 0 ? #089981 : #f23645, text_font_family = MONO)
        table.cell(ST, 3, rr, str.tostring(v, format.mintick) +
             (close > v ? "  price above" : "  price below"), bgcolor = cRow,
             text_color = cDim, text_size = tsz, text_halign = text.align_left,
             text_font_family = MONO)
        for cc = 4 to 11
            table.cell(ST, cc, rr, "", bgcolor = cRow, text_size = tsz,
                 text_font_family = MONO)
        table.merge_cells(ST, 3, rr, 11, rr)
        used := 1
    used
 
if tblOn and barstate.islast
    color bgHdr  = tblDark ? #1e222d : #e8eaf0
    color bgRow  = tblDark ? #131722 : #ffffff
    color bgAlt  = tblDark ? #181c27 : #f6f7f9
    color txHdr  = tblDark ? #d1d4dc : #2a2e39
    color txDim  = tblDark ? #787b86 : #6a6d78
    color txMain = tblDark ? #d1d4dc : #131722
    color bord   = tblDark ? #2a2e39 : #d6d9e0
    string tsz = f_tblSz(tblSize)
 
    table.delete(ST)
    ST := table.new(f_tblPos(tblPos), 12, 24, border_width = 1,
         border_color = bord, frame_color = bord, frame_width = 1)
 
    array.clear(zTop)
    array.clear(zBot)
    array.clear(zDst)
    array.clear(zBul)
    array.clear(zInv)
    array.clear(zTf)
    array.clear(zThr)
    array.clear(zDsp)
    array.clear(zAtr)
    array.clear(zBx)
    array.clear(zSw)
    array.clear(zSwA)
    array.clear(zPB)
    array.clear(zSlot)
    array.clear(zSzq)
    array.clear(zVol)
    array.clear(zSzP)
    array.clear(zDsP)
    array.clear(zAge)
    array.clear(zAgI)
 
    f_resetTxt(st1, fvgOn and en1 and tfOK1)
    f_resetTxt(st2, fvgOn and en2 and tfOK2)
    f_resetTxt(st3, fvgOn and en3 and tfOK3)
 
    f_gather(st1, fvgOn and en1 and tfOK1, szH1, dsH1)
    f_gather(st2, fvgOn and en2 and tfOK2, szH2, dsH2)
    f_gather(st3, fvgOn and en3 and tfOK3, szH3, dsH3)
 
    // ── header ───────────────────────────────────────────────────────────────
    table.cell(ST, 0, 0, "ZONE", bgcolor = bgHdr, text_color = txHdr,
         text_size = tsz, text_halign = text.align_left, text_font_family = MONO,
         tooltip = "FVG = an intact gap. IFVG = a gap a later close went through, so it now faces the other way.\nThe arrow is the side the zone acts on NOW: an inverted bullish gap shows ↓.")
    table.cell(ST, 1, 0, "TF", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO, tooltip = "The timeframe the gap was found on.")
    table.cell(ST, 2, 0, "SIZE ATR", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "Height of the zone in ATR of its OWN timeframe, fixed when it formed, followed by its percentile against that timeframe's past gaps.\n0.60 p72 = six tenths of an ATR tall, bigger than 72% of them.")
    table.cell(ST, 3, 0, "READ", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "A verdict from how hard the close broke through the gap — its displacement, as a percentile of past breaks on this timeframe.\n\nSTRONG p90+ · fair p70-90 · average p30-70 · poor below p30 · pending = still an intact gap.\n\nOn NQ out of sample these reached +1 ATR before −1 ATR 52.0 / 50.8 / 50.5 / 49.4% of the time. An ordering, not an edge.")
    table.cell(ST, 4, 0, "VOL ×avg", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "How busy the market was when this zone formed: ATR of its own timeframe at that moment divided by that ATR's own 100-bar average.\n1.00× is normal, 1.50× half again as volatile, 0.60× quiet.\n\nContext only — sorting NQ by this changed nothing.")
    table.cell(ST, 5, 0, "SWEPT", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "A key level traded through and closed back out of, shortly before this gap formed. Green when the sweep ran against the gap's own direction — lows swept, then a bullish gap.")
    table.cell(ST, 6, 0, "AGE", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "Bars of the zone's own timeframe since the three-candle GAP printed. Counts from birth whether or not it has since inverted.")
    table.cell(ST, 7, 0, "INV AGE", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "Bars of the zone's own timeframe since the close that INVERTED it — that is, how long it has existed as an IFVG rather than as a gap.\n\nA dash means it has not inverted; it is still an intact FVG, so there is nothing to count. AGE and INV AGE differ by however long the gap sat before being broken.")
    table.cell(ST, 8, 0, "RETEST", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "From here on the figures describe PAST zones on this chart that formed with the same setup as this row — same timeframe, size, swept level and distance to a key level. They are not about this zone itself.\n\nRETEST: the share of them price came back to at all.")
    table.cell(ST, 9, 0, "DEPTH", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "Median depth of the FIRST retest, as a percent of the zone's own height. 40% = price pushed four tenths of the way in and left. 100% = it reached the far edge. Lower means that kind of zone was rejected harder.")
    table.cell(ST, 10, 0, "THROUGH", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "Share of those first retests that carried clean out the far side. This is the rejection rate inverted, and it was the clearest effect in the NQ data: 28% with a level inside the zone against 60% when the nearest was far away.")
    table.cell(ST, 11, 0, "n", bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
         text_font_family = MONO,
         tooltip = "How many past zones matched. Hover any RETEST cell to see what the match was made on — exact matches are scarce, so the test loosens one attribute at a time when the sample is thin.")
 
    int nz = array.size(zDst)
    int shown = int(math.min(nz, tblRows))
    int r = 1
 
    if nz > 0
        array<int> ord = array.sort_indices(zDst, order.ascending)
        for k = 0 to shown - 1
            int i = array.get(ord, k)
            bool inv = array.get(zInv, i)
            bool bul = array.get(zBul, i)
            // an inverted bullish gap acts bearish, and the reverse
            bool actBear = inv ? bul : not bul
            color cRow = r % 2 == 0 ? bgAlt : bgRow
            color cDir = actBear ? #f23645 : #089981
            float dst = array.get(zDst, i)
            float tp = array.get(zTop, i)
            float bt = array.get(zBot, i)
            float at = array.get(zAtr, i)
            float thr = array.get(zThr, i)
            float dsp = array.get(zDsp, i)
            string sw = array.get(zSw, i)
 
            string arrow = close > tp ? "▼" : close < bt ? "▲" : "●"
            box.set_text(array.get(zBx, i), f_rankTxt(array.get(zTf, i), inv, k + 1))
            string rk = (k + 1 < 10 ? " " : "") + str.tostring(k + 1)
            table.cell(ST, 0, r, (tblLink ? "#" + rk + " " : "") +
                 (inv ? "IFVG" : "FVG ") + (actBear ? " ↓" : " ↑"),
                 bgcolor = cRow, text_color = cDir, text_size = tsz,
                 text_halign = text.align_left, text_font_family = MONO)
            table.cell(ST, 1, r, array.get(zTf, i), bgcolor = cRow,
                 text_color = txDim, text_size = tsz, text_font_family = MONO)
 
            float szA = na(at) or at <= 0 ? na : (tp - bt) / at
            float szP = tblPct ? array.get(zSzP, i) : na
            table.cell(ST, 2, r, f_withPct(szA, szP), bgcolor = cRow, text_size = tsz,
                 text_color = txMain, text_font_family = MONO)
 
            // READ is the displacement percentile put into words; the raw
            // figure no longer has a column of its own but still drives this
            float mvP = inv ? array.get(zDsP, i) : na
            [rdTxt, rdTier] = f_read(inv, mvP)
            table.cell(ST, 3, r, rdTxt, bgcolor = cRow, text_size = tsz,
                 text_color = rdTier == 4 ? #ffb300 : rdTier == 3 ? #26a69a :
                      rdTier == 1 ? #f23645 : txDim,
                 text_font_family = MONO)
 
            float vr = array.get(zVol, i)
            table.cell(ST, 4, r, na(vr) ? "–" : str.tostring(vr, "#.00") + "×",
                 bgcolor = cRow, text_size = tsz,
                 text_color = na(vr) ? txDim : vr >= 1.5 ? #ffb300 :
                      vr >= 1.2 ? #26a69a : vr <= 0.7 ? txDim : txMain,
                 text_font_family = MONO)
 
            table.cell(ST, 5, r, sw == "" ? "–" : sw, bgcolor = cRow, text_size = tsz,
                 text_color = sw == "" ? txDim : array.get(zSwA, i) ? #089981 : txDim,
                 text_font_family = MONO)
            table.cell(ST, 6, r, str.tostring(array.get(zAge, i)), bgcolor = cRow,
                 text_color = txDim, text_size = tsz, text_font_family = MONO)
            int agI = array.get(zAgI, i)
            table.cell(ST, 7, r, agI < 0 ? "–" : str.tostring(agI), bgcolor = cRow,
                 text_color = agI < 0 ? txDim : cDir, text_size = tsz,
                 text_font_family = MONO)
 
            // ── what past zones with this same setup went on to do ──────
            [sRt, sDp, sTh, sN, sTier] = f_simZone(array.get(zSlot, i),
                 array.get(zSzq, i), sw, array.get(zPB, i))
            string tierTx = sTier == 3 ? "timeframe + size + swept level + distance to a level" :
                 sTier == 2 ? "timeframe + size + distance (swept level relaxed)" :
                 sTier == 1 ? "timeframe + distance (size and swept level relaxed)" :
                 sTier == 0 ? "timeframe only — everything else relaxed" : "nothing comparable yet"
            string tipTx = sN == 0 ?
                 "No past zone on this chart has recorded a result with a setup like this one yet." :
                 str.tostring(sN) + " past zones matched.\nMatched on: " + tierTx
            // thin sample: show the study's figures, dotted, until yours fill
            bool useRef = refOn and (sN < simMin or na(sRt))
            int pbr = array.get(zPB, i)
            float oRt = useRef ? f_ref(array.get(zTf, i), pbr, 0) : sRt
            float oDp = useRef ? f_ref(array.get(zTf, i), pbr, 1) : sDp
            float oTh = useRef ? f_ref(array.get(zTf, i), pbr, 2) : sTh
            string dot = useRef ? "·" : ""
            string refTip = useRef ?
                 "NQ reference, not measured here — this chart has only " +
                 str.tostring(sN) + " comparable zones so far, against a floor of " +
                 str.tostring(simMin) + ".\n\nGrouped by distance to the nearest key level alone, from 261,256 inverted gaps, 2010-2025. Replaced by your own figures as they accumulate." :
                 tipTx
            table.cell(ST, 8, r, na(oRt) ? "–" : dot + str.tostring(oRt, "#") + "%",
                 bgcolor = cRow, text_color = na(oRt) ? txDim : useRef ? txDim : txMain,
                 text_size = tsz, text_font_family = MONO, tooltip = refTip)
            table.cell(ST, 9, r, na(oDp) ? "–" : dot + str.tostring(oDp, "#") + "%",
                 bgcolor = cRow, text_size = tsz, text_font_family = MONO,
                 tooltip = refTip,
                 text_color = na(oDp) or useRef ? txDim :
                      oDp <= 50 ? #26a69a : oDp >= 100 ? #f23645 : txMain)
            table.cell(ST, 10, r, na(oTh) ? "–" : dot + str.tostring(oTh, "#") + "%",
                 bgcolor = cRow, text_size = tsz, text_font_family = MONO,
                 tooltip = refTip,
                 text_color = na(oTh) or useRef ? txDim :
                      oTh <= 40 ? #26a69a : oTh >= 55 ? #f23645 : txMain)
            table.cell(ST, 11, r, useRef ? "ref" : str.tostring(sN), bgcolor = cRow,
                 text_color = useRef or sTier < 3 ? txDim : txMain, text_size = tsz,
                 text_font_family = MONO, tooltip = refTip)
            r += 1
    else
        table.cell(ST, 0, r, "no live zones", bgcolor = bgRow, text_color = txDim,
             text_size = tsz, text_halign = text.align_left, text_font_family = MONO)
        r += 1
 
    // ── moving averages ──────────────────────────────────────────────────────
    if tblMA
        table.cell(ST, 0, r, "MOVING AVERAGES   —   distance from price",
             bgcolor = bgHdr, text_color = txHdr, text_size = tsz,
             text_halign = text.align_left, text_font_family = MONO)
        for cc = 1 to 11
            table.cell(ST, cc, r, "", bgcolor = bgHdr, text_size = tsz, text_font_family = MONO)
        table.merge_cells(ST, 0, r, 11, r)
        r += 1
        r += f_maRow(maOn1, ma1, maT1, maL1, maF1, maCol1, r, tsz, bgAlt, bgRow, txDim)
        r += f_maRow(maOn2, ma2, maT2, maL2, maF2, maCol2, r, tsz, bgAlt, bgRow, txDim)
        r += f_maRow(maOn3, ma3, maT3, maL3, maF3, maCol3, r, tsz, bgAlt, bgRow, txDim)
 
    // ── footer: volatility state and the last sweep ──────────────────────────
    // ── impulse line: the raw ingredient, independent of any gap ─────────
    if impOn
        float impP = f_pctRank(impHist, impSz)
        string impTxt = na(impBar) ? "IMPULSE   none on the loaded history" :
             "IMPULSE   last " + str.tostring(impSz, "#.##") + " ATR " +
             (impUp ? "up" : "down") +
             (na(impP) ? "" : "  p" + str.tostring(math.round(impP))) +
             ",  " + str.tostring(bar_index - impBar) + " bars ago" +
             "   ·   " + str.tostring(array.size(impHist)) + " seen"
        table.cell(ST, 0, r, impTxt, bgcolor = bgHdr,
             text_color = na(impBar) ? txDim : impUp ? #089981 : #f23645,
             text_size = tsz, text_halign = text.align_left, text_font_family = MONO,
             tooltip = "The most recent candle whose close travelled at least the threshold from its open, on the chart timeframe. Nothing to do with gaps — displacement was the one measurement that separated outcomes on NQ, and this is it in its raw form.")
        for cc = 1 to 11
            table.cell(ST, cc, r, "", bgcolor = bgHdr, text_size = tsz, text_font_family = MONO)
        table.merge_cells(ST, 0, r, 11, r)
        r += 1
 
    string volTxt = na(atrChart) ? "ATR –" :
         "ATR " + str.tostring(atrChart, format.mintick) +
         (na(atrChartAvg) or atrChartAvg <= 0 ? "" :
              " (" + str.tostring(atrChart / atrChartAvg, "#.##") + "× avg)")
    string swTxt = na(swTs) ? "no sweep yet" :
         "last sweep " + swName +
         (na(swBar) ? "" : ", " + str.tostring(bar_index - swBar) + " bars ago")
    table.cell(ST, 0, r, volTxt + "     ·     " + swTxt, bgcolor = bgHdr,
         text_color = txDim, text_size = tsz, text_halign = text.align_left,
         text_font_family = MONO,
         tooltip = "Chart-timeframe ATR(14) against its own 100-bar average, and the most recent key level that was taken out and closed back through. Neither belongs to any one zone above.")
    for cc = 1 to 11
        table.cell(ST, cc, r, "", bgcolor = bgHdr, text_size = tsz, text_font_family = MONO)
    // one cell across the whole width, so no value sits under a heading that
    // does not describe it
    table.merge_cells(ST, 0, r, 11, r)

← 返回列表