PT Zone Sniper - MTF Support/Resistance & FVG Retests

MoAlqaq · study · 1390 行 · 点赞 50 · TradingView 原页

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

Pine Script

//@version=6
// ════════════════════════════════════════════════════════════════════
//  PT Zone Sniper - MTF Support/Resistance & FVG Retests
//  Version V26.04  ·  By Mo Alqaq
//
//  Support / resistance zones from matching swing pairs, buy/sell volume
//  balance, bounce and break-and-retest tests, 4H / 1H / 15M levels on the
//  execution chart, pending and confirmed entry arrows, and Fair Value Gaps
//  (FVG / iFVG). All signals confirm on bar close; HTF data never repaints.
//
//  Sections: Inputs · Lower-timeframe volume · Helpers · Swing engine ·
//  Data requests · S/R zone model · Zone life cycle · Fair Value Gaps ·
//  Drawing · Entry arrows · Alert conditions
//
//  Changelog
//  V26.04  Release version. Signal check panel: every confirmed entry arrow
//          is tracked until price moves a set ATR distance for or against it,
//          split by S/R zones and FVGs (5M and higher timeframes).
//  V26.03  Published name: "PT Zone Sniper - MTF Support/Resistance & FVG
//          Retests" (short name "PT Zone Sniper"); version kept here only.
//          Fair Value Gap module: 5M FVGs with adjustable strictness filters,
//          4H/1H/15M FVG lines, partial-fill shading, CE (50%) entries,
//          inversions (iFVG) with retests, finished FVGs left in place,
//          "FVG overlap" confluence option, new FVG alerts. Code clean-up.
//  V26.02  New engine (matching swing pairs), buy/sell balance bars,
//          bounces and break & retests, grouped lines and broken levels,
//          pending (grey) and confirmed (green/red) entry arrows,
//          formation swings shown on zone labels.
//  V26.01  First release: HTF S/R zones, strength score, trade setups.
// ════════════════════════════════════════════════════════════════════
indicator("PT Zone Sniper - MTF Support/Resistance & FVG Retests", shorttitle = "PT Zone Sniper", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
import TradingView/ta/12
 
// ───────────────────────────── Inputs ─────────────────────────────
grpZ           = "Zone detection (chart timeframe)"
timeHorizon    = input.int(7, "Time horizon (bars each side of a swing)", minval = 1, group = grpZ, tooltip = "Bars needed on each side to confirm a swing high/low. Higher = fewer, more significant zones. Lower = more frequent zones.")
tolMode        = input.string("Std dev", "Tolerance based on", options = ["Std dev", "ATR"], group = grpZ, tooltip = "How close two swings must be to count as the same level.\nStd dev (original): standard deviation of the close; it widens in trends.\nATR: average candle range; steadier in trends.")
volLookback    = input.int(40, "Std dev lookback", minval = 2, group = grpZ, tooltip = "Candles used for the standard deviation when tolerance is based on Std dev.")
atrLen         = input.int(14, "ATR length", minval = 1, group = grpZ, tooltip = "Period of every ATR used by the indicator (tolerances, distances, FVG filters).")
zoneTolerance  = input.float(1.0, "Zone match tolerance (multiplier)", minval = 0.05, step = 0.05, group = grpZ, tooltip = "Multiplies the tolerance. Higher = wider matches and slightly thicker zones.")
matchDepth     = input.int(3, "Compare with the last N swings", minval = 1, maxval = 10, group = grpZ, tooltip = "1 = only the previous swing (original behaviour). 3 = also catches triple tops/bottoms and matches that are not back-to-back.")
preventOverlap = input.bool(true, "Avoid overlapping zones", group = grpZ, tooltip = "A new zone is skipped if it overlaps an active zone of the same timeframe.")
maxAge         = input.int(500, "Max zone age (bars of its own timeframe)", minval = 20, group = grpZ, tooltip = "Zones stay until they are broken. This is only a backup limit.")
 
grpH       = "Higher timeframe lines"
useH1      = input.bool(true, "HTF 1", inline = "h1", group = grpH)
tfH1       = input.timeframe("240", "", inline = "h1", group = grpH)
useH2      = input.bool(true, "HTF 2", inline = "h2", group = grpH)
tfH2       = input.timeframe("60", "", inline = "h2", group = grpH)
useH3      = input.bool(true, "HTF 3", inline = "h3", group = grpH)
tfH3       = input.timeframe("15", "", inline = "h3", group = grpH)
htfHorizon = input.int(5, "HTF time horizon (bars each side)", minval = 1, group = grpH, tooltip = "Swing confirmation on the higher timeframes.")
lineLvl    = input.string("Mid", "Line level", options = ["Mid", "Near edge", "Far edge"], group = grpH, tooltip = "Where the single line sits inside the higher-timeframe zone. Near edge = the side price reaches first.")
htfSignals = input.bool(true, "Diamonds from HTF line tests", group = grpH, tooltip = "Also shows diamonds and entry arrows for 4H / 1H / 15M lines and FVG lines.")
lineMerge  = input.float(1.0, "Group active lines closer than (x ATR)", minval = 0, step = 0.25, group = grpH, tooltip = "Active lines of the same timeframe and role that sit close together are drawn as one line with one label. 0 = never group.")
 
grpT        = "Tests and signals"
leaveAtr    = input.float(0.5, "New test only after price leaves by (x ATR)", minval = 0, step = 0.05, group = grpT, tooltip = "Price must move this far away from a zone before its next visit counts. Stops a signal on the candle right after a breakout.")
breakBuf    = input.float(0.0, "Break = close beyond the zone by (x ATR)", minval = 0, step = 0.05, group = grpT, tooltip = "Extra distance a close must clear to count as a break. 0 = any close beyond the edge.")
showRetest  = input.bool(true, "Show break & retest diamonds (filled)", group = grpT)
showBounce  = input.bool(true, "Show bounce diamonds (outline)", group = grpT)
maxSignals  = input.int(150, "Max diamonds kept", minval = 10, maxval = 300, group = grpT)
rmBroken    = input.bool(true, "Remove broken zones at end of day", group = grpT, tooltip = "Broken zones are drawn as a dotted grey line labelled Broken until the day ends.")
brkMerge    = input.float(1.0, "Group broken levels closer than (x ATR)", minval = 0, step = 0.25, group = grpT, tooltip = "Broken levels of the same timeframe that sit close together are drawn as one grey zone with a single label. 0 = never group.")
alertBounce = input.bool(false, "Alert on bounces too", group = grpT)
 
grpE         = "Entry arrows"
showArrows   = input.bool(true, "Show entry arrows", group = grpE, tooltip = "Grey arrow = pending entry at the edge of the nearest qualifying zone (live, moves with price).\nGreen / red arrow = confirmed entry, left on the trigger candle.\nA zone qualifies after one confirmed test in its current role, or after it broke and flipped (break & retest setup).")
pendReach    = input.float(1.0, "Pending arrow only when price is within (x daily ATR)", minval = 0.1, step = 0.1, group = grpE, tooltip = "A grey pending arrow is shown only for qualifying zones or FVGs this close to price.")
flipQual     = input.bool(true, "Broken & flipped zones qualify (break & retest entries)", group = grpE)
confMode     = input.string("Off", "Confluence filter (S/R zones)", options = ["Off", "HTF line overlap", "Volume balance agrees", "FVG overlap", "Either"], group = grpE, tooltip = "HTF line overlap: a 5M zone must overlap a 15M/1H/4H line of the same role (HTF lines pass by themselves).\nVolume balance agrees: Buy > Sell for buy entries, Sell > Buy for sell entries.\nFVG overlap: an active FVG of the same role overlaps the zone.\nEither: any one of the three.")
colPend      = input.color(#787b86, "Pending arrow colour", group = grpE)
maxArrows    = input.int(100, "Confirmed arrows kept", minval = 10, maxval = 300, group = grpE)
alertEntry   = input.bool(true, "Alert on confirmed entries", group = grpE)
 
grpF        = "Fair Value Gaps (FVG)"
fvgOn       = input.bool(true, "Enable FVGs", group = grpF)
fvgChart    = input.bool(true, "Chart-timeframe FVGs (5M)", group = grpF)
fvgHtf      = input.bool(true, "FVG lines from the HTF slots (4H / 1H / 15M)", group = grpF)
fvgIfvg     = input.bool(true, "Track inverted FVGs (iFVG)", group = grpF, tooltip = "On: an FVG that a candle body closes through flips role (iFVG) and waits for a retest from the other side.\nOff: it is simply removed.")
fvgMaxTests = input.int(2, "Entry arrows only on the first N tests", minval = 1, maxval = 10, group = grpF, tooltip = "FVGs weaken with every touch: the first retrace matters most.")
fvgShowFill = input.bool(true, "Show partial-fill shading", group = grpF)
fvgShowCE   = input.bool(true, "Show CE line (50%)", group = grpF)
fvgMaxEach  = input.int(3, "Max 5M FVGs each side of price", minval = 0, maxval = 10, group = grpF)
fvgHtfEach  = input.int(1, "Max FVG lines each side per HTF", minval = 0, maxval = 5, group = grpF)
fvgAlertNew = input.bool(false, "Alert on new FVGs", group = grpF)
grpF5       = "FVG filters (5M) — how strict"
fvgMinGap   = input.float(0.3, "Min gap size (x ATR)", minval = 0, step = 0.05, group = grpF5, tooltip = "Gaps smaller than this are ignored. 0 = no minimum.")
fvgDispAtr  = input.float(1.5, "Middle candle range at least (x ATR)", minval = 0, step = 0.1, group = grpF5, tooltip = "Displacement: the impulse candle must be large. 0 = off.")
fvgBodyPct  = input.int(60, "Middle candle body at least (% of its range)", minval = 0, maxval = 100, group = grpF5, tooltip = "A strong body, not a wick. 0 = off.")
fvgVolAgree = input.bool(true, "Volume must agree with the direction", group = grpF5)
fvgMinVol   = input.int(50, "Min buy share for bullish / sell share for bearish (%)", minval = 0, maxval = 100, group = grpF5)
fvgMaxAge   = input.int(144, "5M FVG expires after N bars", minval = 10, group = grpF5, tooltip = "144 × 5M = 12 hours. Higher-timeframe FVGs use the general max zone age.")
fvgHtfGap   = input.float(0.2, "HTF FVG min gap size (x HTF ATR)", minval = 0, step = 0.05, group = grpF5)
grpFA       = "FVG appearance"
colFvgBull  = input.color(#089981, "Bullish FVG / support", group = grpFA)
colFvgBear  = input.color(#f23645, "Bearish FVG / resistance", group = grpFA)
fvgFillTr   = input.int(80, "FVG fill transparency (unfilled part)", minval = 0, maxval = 100, group = grpFA)
fvgBorderTr = input.int(40, "FVG border transparency", minval = 0, maxval = 100, group = grpFA)
 
grpV         = "Volume balance"
volMode      = input.string("At touches", "Measure volume", options = ["At touches", "Between swings"], group = grpV, tooltip = "At touches: volume on the candles around each swing that formed the zone (who defended the level).\nBetween swings (original): all volume from the first swing to the second.")
volPad       = input.int(2, "Candles around each touch", minval = 0, maxval = 10, group = grpV)
allowSeconds = input.bool(false, "Allow seconds data", group = grpV, tooltip = "Allows seconds-based lower timeframes. Disable if seconds data causes errors on your account or symbol.")
intragran    = input.int(10, "Bar granularity", minval = 1, maxval = 100, group = grpV, tooltip = "Lower timeframe used for buy/sell volume ≈ chart timeframe ÷ this value.")
 
grpK       = "Display filter"
maxEach    = input.int(5, "Max chart-TF zones each side of price", minval = 1, maxval = 20, group = grpK)
maxHtfEach = input.int(2, "Max lines each side per HTF", minval = 0, maxval = 10, group = grpK)
rangeAtr   = input.float(2.0, "Only within (x daily ATR) of price", minval = 0.25, step = 0.25, group = grpK, tooltip = "Zones, lines and FVGs further away from price are not drawn.")
showAll    = input.bool(false, "Show all zones (ignore filter)", group = grpK)
 
grpS        = "Signal check panel"
showStats   = input.bool(true, "Show signal check panel", group = grpS, tooltip = "Tracks every confirmed entry arrow on the loaded chart history: a win if price moves the target distance in the arrow's direction first, a loss if it moves the stop distance against it first, expired if neither happens in time. A measurement aid, not a backtest: no costs, spreads or position management.")
stTgt       = input.float(1.0, "Win when price moves (x ATR) in favour", minval = 0.1, step = 0.1, group = grpS)
stStp       = input.float(1.0, "Loss when price moves (x ATR) against", minval = 0.1, step = 0.1, group = grpS)
stBars      = input.int(48, "Expire after N bars", minval = 2, group = grpS)
stPos       = input.string("Bottom right", "Panel position", options = ["Top right", "Bottom right", "Bottom left", "Top left"], group = grpS)
 
grpA       = "Appearance"
greyFirst  = input.bool(true, "Grey until the first test", group = grpA, tooltip = "On: a new zone stays grey until price tests it, then turns green (support) or red (resistance). Off: zones show their role colour from the start.")
colNeutral = input.color(#5d606b, "Untested zone", group = grpA)
colSup     = input.color(#089981, "Support / bullish", group = grpA)
colRes     = input.color(#f23645, "Resistance / bearish", group = grpA)
borderTr   = input.int(50, "Zone border transparency", minval = 0, maxval = 100, group = grpA)
fillTr     = input.int(80, "Zone fill transparency", minval = 0, maxval = 100, group = grpA)
showBars   = input.bool(true, "Show buy / sell balance bars", group = grpA)
barTr      = input.int(50, "Balance bar transparency", minval = 0, maxval = 100, group = grpA)
showMid    = input.bool(true, "Show zone centre line", group = grpA)
extendBars = input.int(40, "Extend zones N bars past the current bar", minval = 0, maxval = 300, group = grpA)
txtSizeIn  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grpA)
 
// ───────────────────────────── Lower-timeframe volume (chart zones) ─────────────────────────────
chartTfSeconds  = timeframe.in_seconds()
targetTfSeconds = math.max(1, int(chartTfSeconds * 1.0 / intragran))
useChartTf      = not allowSeconds and timeframe.isseconds
tfSeconds       = useChartTf ? chartTfSeconds : allowSeconds ? targetTfSeconds : math.max(60, targetTfSeconds)
ltf_            = useChartTf ? timeframe.period : timeframe.from_seconds(tfSeconds)
[upv, downv, deltav] = ta.requestUpAndDownVolume(ltf_)
 
// ───────────────────────────── Helpers ─────────────────────────────
string tSize = txtSizeIn == "Tiny" ? size.tiny : txtSizeIn == "Normal" ? size.normal : size.small
int    chartMs = int(chartTfSeconds) * 1000
 
tfName(string tf) =>
    int m = int(timeframe.in_seconds(tf) / 60)
    m >= 1440 ? str.tostring(int(m / 1440)) + "D" : m >= 60 ? str.tostring(int(m / 60)) + "H" : m >= 1 ? str.tostring(m) + "M" : tf
 
tfOk(string tf) =>
    timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
 
fmt(float p) =>
    str.tostring(p, format.mintick)
 
pct(float p) =>
    str.tostring(p, "#") + "%"
 
// ───────────────────────────── Swing points and zone bounds ─────────────────────────────
type Piv
    int   idx
    int   t
    float price
    float o
    float h
    float l
    float c
 
includeDistance(float currentMax, bool isRes, float edge, float val, float tol) =>
    float d = isRes ? edge - val : val - edge
    d >= 0.0 and d <= tol ? math.max(currentMax, d) : currentMax
 
// edge = extreme wick of the two swings; depth = furthest O/H/L/C of the two swing candles within tolerance
zoneBounds(Piv p1, Piv p2, bool isRes, float tol) =>
    float edge = isRes ? math.max(p1.h, p2.h) : math.min(p1.l, p2.l)
    float d = 0.0
    d := includeDistance(d, isRes, edge, p1.o, tol)
    d := includeDistance(d, isRes, edge, p1.h, tol)
    d := includeDistance(d, isRes, edge, p1.l, tol)
    d := includeDistance(d, isRes, edge, p1.c, tol)
    d := includeDistance(d, isRes, edge, p2.o, tol)
    d := includeDistance(d, isRes, edge, p2.h, tol)
    d := includeDistance(d, isRes, edge, p2.l, tol)
    d := includeDistance(d, isRes, edge, p2.c, tol)
    d := math.max(d, syminfo.mintick)
    float top = isRes ? edge : edge + d
    float bot = isRes ? edge - d : edge
    [top, bot]
 
// Zigzag swings; a zone is born when a new swing matches one of the last `depth` swings on the same side
zoneEngine(int th, string tm, float tmul, int sdLen, int aLen, int depth) =>
    float ph  = ta.pivothigh(high, th, th)
    float pl  = ta.pivotlow(low, th, th)
    float atr = ta.atr(aLen)
    float sd  = ta.stdev(close, sdLen)
    float tol = (tm == "ATR" ? atr : sd) * tmul
    var int        lastType = 0
    var Piv        pendH    = na
    var Piv        pendL    = na
    var array<Piv> zzH      = array.new<Piv>()
    var array<Piv> zzL      = array.new<Piv>()
    int prevType = lastType
    if not na(ph)
        Piv hp = Piv.new(bar_index - th, time[th], ph, open[th], high[th], low[th], close[th])
        if lastType != 1 or na(pendH)
            pendH := hp
        else if ph > pendH.price
            pendH := hp
        lastType := 1
    if not na(pl)
        Piv lp = Piv.new(bar_index - th, time[th], pl, open[th], high[th], low[th], close[th])
        if lastType != -1 or na(pendL)
            pendL := lp
        else if pl < pendL.price
            pendL := lp
        lastType := -1
    int   evt  = 0
    float zTop = na
    float zBot = na
    int   i1   = na
    int   i2   = na
    int   t1   = na
    int   nSw  = 0
    if lastType != prevType and not na(pendH) and not na(pendL) and not na(tol)
        bool       isRes = lastType == -1   // a low arrived, so the previous swing high is confirmed
        Piv        cur   = isRes ? pendH : pendL
        array<Piv> zz    = isRes ? zzH : zzL
        int   best = -1
        float bd   = 1.0e10
        int   cnt  = 0
        int   n    = math.min(zz.size(), depth)
        if n > 0
            for k = 0 to n - 1
                Piv   q = zz.get(k)
                float d = math.abs(q.price - cur.price)
                if d <= tol
                    cnt += 1
                    if d < bd
                        bd   := d
                        best := k
        zz.unshift(cur)
        if zz.size() > 50
            zz.pop()
        if best >= 0
            Piv p = zz.get(best + 1)
            [tp, bt] = zoneBounds(p, cur, isRes, tol)
            evt  := isRes ? 1 : -1
            zTop := tp
            zBot := bt
            i1   := p.idx
            i2   := cur.idx
            t1   := math.min(p.t, cur.t)
            nSw  := cnt + 1
    [evt, zTop, zBot, i1, i2, t1, nSw, atr]
 
// Real buy/sell volume from lower-timeframe data (chart zones)
ltfVol(bool active, int i1, int i2, string mode, int pad) =>
    float up  = 0.0
    float dn  = 0.0
    float vv  = 0.0
    int   cnt = 0
    if not active or na(i1) or na(i2)
        cnt := 0
    else if mode == "Between swings"
        int fromB = math.max(bar_index - math.max(i1, i2), 0)
        int toB   = math.min(bar_index - math.min(i1, i2), 1000)
        if toB >= fromB
            for k = fromB to toB
                up  += nz(upv[k])
                dn  += math.abs(nz(downv[k]))
                vv  += nz(volume[k])
                cnt += 1
    else
        for j = 0 to 1
            int off = bar_index - (j == 0 ? i1 : i2)
            int a   = math.max(off - pad, 0)
            int b   = math.min(off + pad, bar_index)
            if b >= a
                for k = a to b
                    up  += nz(upv[k])
                    dn  += math.abs(nz(downv[k]))
                    vv  += nz(volume[k])
                    cnt += 1
    [up, dn, vv, cnt]
 
// Estimated buy/sell volume from candles (higher-timeframe lines): buy share = (close - low) / range
candleVol(int i1, int i2, string mode, int pad) =>
    float up  = 0.0
    float dn  = 0.0
    float vv  = 0.0
    int   cnt = 0
    int a0 = 0
    int b0 = -1
    int a1 = 0
    int b1 = -1
    if mode == "Between swings"
        a0 := math.max(bar_index - math.max(i1, i2), 0)
        b0 := math.min(bar_index - math.min(i1, i2), 300)
    else
        int o1 = bar_index - i1
        int o2 = bar_index - i2
        a0 := math.max(o1 - pad, 0)
        b0 := math.min(o1 + pad, bar_index)
        a1 := math.max(o2 - pad, 0)
        b1 := math.min(o2 + pad, bar_index)
    for j = 0 to 1
        int a = j == 0 ? a0 : a1
        int b = j == 0 ? b0 : b1
        if b >= a
            for k = a to b
                float rng = high[k] - low[k]
                float v   = nz(volume[k])
                float bu  = rng > 0 ? v * (close[k] - low[k]) / rng : v * 0.5
                up  += bu
                dn  += v - bu
                vv  += v
                cnt += 1
    [up, dn, vv, cnt]
 
// Runs on the higher timeframe; returns the zone born on the LAST CONFIRMED HTF bar (no repainting)
htfEvt(int th, string tm, float tmul, int sdLen, int aLen, int depth, string vMode, int pad) =>
    [evt, zTop, zBot, i1, i2, t1, nSw, atr] = zoneEngine(th, tm, tmul, sdLen, aLen, depth)
    float avgV = ta.sma(volume, 50)
    float bu   = na
    float se   = na
    float vx   = na
    if evt != 0
        [a, b, v, c] = candleVol(i1, i2, vMode, pad)
        bu := a
        se := b
        vx := c > 0 and avgV > 0 ? (v / c) / avgV : na
    [evt[1], zTop[1], zBot[1], t1[1], nSw[1], atr[1], bu[1], se[1], vx[1]]
 
// Runs on the higher timeframe; returns the FVG completed on the LAST CONFIRMED HTF bar (no repainting)
fvgHtfEvt(float mg, int aLen) =>
    float atr  = ta.atr(aLen)
    int   dir  = 0
    float fTop = na
    float fBot = na
    if low > high[2] and close[1] > open[1] and low - high[2] >= mg * atr
        dir  := 1
        fTop := low
        fBot := high[2]
    else if high < low[2] and close[1] < open[1] and low[2] - high >= mg * atr
        dir  := -1
        fTop := low[2]
        fBot := high
    float bu = 0.0
    float se = 0.0
    for k = 0 to 2
        float rng = high[k] - low[k]
        float vk  = nz(volume[k])
        float b   = rng > 0 ? vk * (close[k] - low[k]) / rng : vk * 0.5
        bu += b
        se += vk - b
    [dir[1], fTop[1], fBot[1], time[3], atr[1], bu[1], se[1]]
 
// ───────────────────────────── Data requests ─────────────────────────────
[cEvt, cTop, cBot, cI1, cI2, cT1, cNSw, cAtr] = zoneEngine(timeHorizon, tolMode, zoneTolerance, volLookback, atrLen, matchDepth)
[h1Evt, h1Top, h1Bot, h1T, h1N, h1Atr, h1Bu, h1Se, h1Vx] = request.security(syminfo.tickerid, tfH1, htfEvt(htfHorizon, tolMode, zoneTolerance, volLookback, atrLen, matchDepth, volMode, volPad), lookahead = barmerge.lookahead_on)
[h2Evt, h2Top, h2Bot, h2T, h2N, h2Atr, h2Bu, h2Se, h2Vx] = request.security(syminfo.tickerid, tfH2, htfEvt(htfHorizon, tolMode, zoneTolerance, volLookback, atrLen, matchDepth, volMode, volPad), lookahead = barmerge.lookahead_on)
[h3Evt, h3Top, h3Bot, h3T, h3N, h3Atr, h3Bu, h3Se, h3Vx] = request.security(syminfo.tickerid, tfH3, htfEvt(htfHorizon, tolMode, zoneTolerance, volLookback, atrLen, matchDepth, volMode, volPad), lookahead = barmerge.lookahead_on)
float dAtr = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
[f1Dir, f1Top, f1Bot, f1T, f1Atr, f1Bu, f1Se] = request.security(syminfo.tickerid, tfH1, fvgHtfEvt(fvgHtfGap, atrLen), lookahead = barmerge.lookahead_on)
[f2Dir, f2Top, f2Bot, f2T, f2Atr, f2Bu, f2Se] = request.security(syminfo.tickerid, tfH2, fvgHtfEvt(fvgHtfGap, atrLen), lookahead = barmerge.lookahead_on)
[f3Dir, f3Top, f3Bot, f3T, f3Atr, f3Bu, f3Se] = request.security(syminfo.tickerid, tfH3, fvgHtfEvt(fvgHtfGap, atrLen), lookahead = barmerge.lookahead_on)
 
bool  nbH1     = timeframe.change(tfH1)
bool  nbH2     = timeframe.change(tfH2)
bool  nbH3     = timeframe.change(tfH3)
float avgVol50 = ta.sma(volume, 50)
float atrC     = ta.atr(atrLen)
float fvgUp3   = math.sum(nz(upv), 3)
float fvgDn3   = math.sum(math.abs(nz(downv)), 3)
 
// ───────────────────────────── S/R zone model ─────────────────────────────
// state: 0 active · 1 broken and flipped, waiting for retest · 2 break & retest confirmed · 5 broken (no longer active)
type Zone
    float  top
    float  bot
    bool   isRes
    bool   origRes
    int    rank          // 0 chart TF · 1 HTF 3 · 2 HTF 2 · 3 HTF 1
    string tf
    int    t0
    float  buyV
    float  sellV
    float  volX
    int    nSw
    float  zAtr
    int    createdT
    int    bullB    = 0  // bull bounces
    int    bullR    = 0  // bull break & retests
    int    bearB    = 0
    int    bearR    = 0
    int    state    = 0
    bool   armed    = false
    bool   tested   = false
    bool   brokeRes = false
    bool   vis      = false
    int    grpN     = 1
    string grpTip   = ""
    box    bx
    box    bullBx
    box    bearBx
    line   mid
    line   ln
    label  bullL
    label  bearL
    label  lnL
 
var array<Zone>  zones = array.new<Zone>()
var array<label> sigs  = array.new<label>()
 
// FVG state: 0 active (fresh / partially filled) · 1 inverted (iFVG), waiting for retest · 2 iFVG retest confirmed · 5 broken · 6 mitigated (fully filled)
type Fvg
    float  top
    float  bot
    bool   bull          // original direction: bullish gap = support
    bool   isRes         // current role
    int    rank
    string tf
    int    t0
    float  buyV
    float  sellV
    float  fAtr
    int    createdT
    int    createdBar
    float  deep          // deepest price reached into the gap (fill tracking)
    int    tests    = 0
    int    state    = 0
    bool   armed    = true
    bool   vis      = false
    int    endT     = na    // when it was mitigated / broken
    box    bx
    box    unf
    box    bullBx
    box    bearBx
    line   ce
    line   ln
    label  lb
 
var array<Fvg> fvgs = array.new<Fvg>()
 
isActive(Zone z) =>
    z.state == 0 or z.state == 1 or z.state == 2
 
rankTfSec(int rk) =>
    rk == 3 ? timeframe.in_seconds(tfH1) : rk == 2 ? timeframe.in_seconds(tfH2) : rk == 1 ? timeframe.in_seconds(tfH3) : timeframe.in_seconds(timeframe.period)
 
delBoxParts(Zone z) =>
    box.delete(z.bx)
    box.delete(z.bullBx)
    box.delete(z.bearBx)
    line.delete(z.mid)
    label.delete(z.bullL)
    label.delete(z.bearL)
    z.bx     := na
    z.bullBx := na
    z.bearBx := na
    z.mid    := na
    z.bullL  := na
    z.bearL  := na
 
delLineParts(Zone z) =>
    line.delete(z.ln)
    label.delete(z.lnL)
    z.ln  := na
    z.lnL := na
 
delDraw(Zone z) =>
    delBoxParts(z)
    delLineParts(z)
 
addZone(float top, float bot, bool isRes, int rank, string tfN, int t0, float bu, float se, float vx, int nSw, float za) =>
    bool ok = top > bot and not na(za)
    if ok and preventOverlap
        for z in zones
            if z.rank == rank and isActive(z) and math.min(z.top, top) > math.max(z.bot, bot)
                ok := false
    if ok
        zones.push(Zone.new(top = top, bot = bot, isRes = isRes, origRes = isRes, rank = rank, tf = tfN, t0 = t0, buyV = nz(bu), sellV = nz(se), volX = vx, nSw = nSw, zAtr = za, createdT = time))
        int cnt   = 0
        int first = -1
        for [i, z] in zones
            if z.rank == rank
                cnt += 1
                if first < 0
                    first := i
        if cnt > (rank == 0 ? 60 : 25) and first >= 0
            delDraw(zones.get(first))
            zones.remove(first)
        alert("PT Zone Sniper: " + syminfo.ticker + " new " + tfN + (isRes ? " resistance" : " support") + " zone " + fmt(bot) + " – " + fmt(top), alert.freq_once_per_bar_close)
    ok
 
addSig(bool bull, bool filled, string tip) =>
    label lb = na
    // same glyph size for both; anchored at the wick tip, drawn just beyond it
    lb := label.new(bar_index, bull ? low : high, filled ? "◆" : "◇", style = bull ? label.style_label_up : label.style_label_down, color = color.new(color.black, 100), textcolor = bull ? colSup : colRes, size = size.normal, tooltip = tip)
    sigs.push(lb)
    if sigs.size() > maxSignals
        label.delete(sigs.shift())
 
var array<label> arrows = array.new<label>()
 
// confluence: an HTF line of the same role overlapping the zone, and/or the volume balance agreeing
confOk(Zone z) =>
    bool volOk = z.isRes ? z.sellV > z.buyV : z.buyV > z.sellV
    bool htfOk = z.rank > 0
    if not htfOk and (confMode == "HTF line overlap" or confMode == "Either")
        for o in zones
            if o.rank > 0 and isActive(o) and o.isRes == z.isRes and math.min(o.top, z.top) - math.max(o.bot, z.bot) > -lineMerge * o.zAtr
                htfOk := true
    bool fvgOk = false
    if confMode == "FVG overlap" or confMode == "Either"
        for f in fvgs
            if f.state <= 2 and f.isRes == z.isRes and math.min(f.top, z.top) > math.max(f.bot, z.bot)
                fvgOk := true
    confMode == "Off" ? true : confMode == "HTF line overlap" ? htfOk : confMode == "Volume balance agrees" ? volOk : confMode == "FVG overlap" ? fvgOk : (htfOk or volOk or fvgOk)
 
// a zone qualifies for entries after one confirmed test in its current role, or once broken and flipped
qualified(Zone z) =>
    bool roleTested = z.isRes ? z.bearB + z.bearR > 0 : z.bullB + z.bullR > 0
    bool q = ((z.state == 0 or z.state == 2) and roleTested) or (z.state == 1 and flipQual)
    q and confOk(z)
 
// signal check: each confirmed arrow is followed until it reaches the win or loss distance, or expires
type Sig
    bool  bull
    float tgt
    float stp
    int   bar
    int   src      // 0 S/R 5M · 1 S/R HTF · 2 FVG 5M · 3 FVG HTF
 
var array<Sig> openSigs = array.new<Sig>()
var array<int> stN      = array.new<int>(4, 0)
var array<int> stW      = array.new<int>(4, 0)
var array<int> stL      = array.new<int>(4, 0)
var array<int> stE      = array.new<int>(4, 0)
 
addArrow(bool bull, string tip, int src) =>
    float off = nz(atrC, 0) * 0.6
    label lb  = label.new(bar_index, bull ? low - off : high + off, bull ? "▲" : "▼", style = bull ? label.style_label_up : label.style_label_down, color = color.new(color.black, 100), textcolor = bull ? colSup : colRes, size = size.normal, tooltip = tip)
    arrows.push(lb)
    if arrows.size() > maxArrows
        label.delete(arrows.shift())
    if not na(atrC)
        openSigs.push(Sig.new(bull, bull ? close + stTgt * atrC : close - stTgt * atrC, bull ? close - stStp * atrC : close + stStp * atrC, bar_index, src))
        stN.set(src, stN.get(src) + 1)
 
procHTF(bool use, string tf, int rank, bool nb, int evt, float top, float bot, int t, int n, float a, float bu, float se, float vx) =>
    bool made = false
    if use and tfOk(tf) and nb and evt != 0 and not na(top)
        made := addZone(top, bot, evt == 1, rank, tfName(tf), t, bu, se, vx, n, a)
    made
 
// ───────────────────────────── Create zones ─────────────────────────────
bool evNewRes = false
bool evNewSup = false
bool cNew     = barstate.isconfirmed and cEvt != 0
[u, d, v, c] = ltfVol(cNew, cI1, cI2, volMode, volPad)
if cNew
    float vx = c > 0 and avgVol50 > 0 ? (v / c) / avgVol50 : na
    if addZone(cTop, cBot, cEvt == 1, 0, tfName(timeframe.period), cT1, u, d, vx, cNSw, cAtr)
        evNewRes := cEvt == 1
        evNewSup := cEvt == -1
procHTF(useH1, tfH1, 3, nbH1, h1Evt, h1Top, h1Bot, h1T, h1N, h1Atr, h1Bu, h1Se, h1Vx)
procHTF(useH2, tfH2, 2, nbH2, h2Evt, h2Top, h2Bot, h2T, h2N, h2Atr, h2Bu, h2Se, h2Vx)
procHTF(useH3, tfH3, 1, nbH3, h3Evt, h3Top, h3Bot, h3T, h3N, h3Atr, h3Bu, h3Se, h3Vx)
 
// ───────────────────────────── Remove broken zones at the start of a new day ─────────────────────────────
if rmBroken and timeframe.change("D") and zones.size() > 0
    for i = zones.size() - 1 to 0
        Zone zr = zones.get(i)
        if zr.state == 5
            delDraw(zr)
            zones.remove(i)
 
// ───────────────────────────── Zone life cycle: tests, breaks and retests (confirmed bars only) ─────────────────────────────
bool evBullRetest = false
bool evBearRetest = false
bool evBounce     = false
bool evBroken     = false
if barstate.isconfirmed and zones.size() > 0
    for i = zones.size() - 1 to 0
        Zone z = zones.get(i)
        if time - z.createdT > maxAge * rankTfSec(z.rank) * 1000
            delDraw(z)
            zones.remove(i)
            continue
        if z.state == 5
            continue
        float  lv     = leaveAtr * z.zAtr
        float  bb     = breakBuf * z.zAtr
        bool   inside = high >= z.bot and low <= z.top
        bool   sup    = not z.isRes
        bool   sigOk  = z.rank == 0 or htfSignals
        string zName  = z.tf + " zone " + fmt(z.bot) + " – " + fmt(z.top)
        bool   wasQ   = showArrows and qualified(z)
        if sup and close < z.bot - bb
            if z.state == 0
                // support broken: flips to resistance, waiting for a retest from below
                z.isRes  := true
                z.state  := 1
                z.armed  := false
                z.tested := true
            else
                z.state    := 5
                z.brokeRes := false
                evBroken   := true
                alert("PT Zone Sniper: " + syminfo.ticker + " " + zName + " broken — no longer active", alert.freq_once_per_bar_close)
        else if not sup and close > z.top + bb
            if z.state == 0
                // resistance broken: flips to support, waiting for a retest from above
                z.isRes  := false
                z.state  := 1
                z.armed  := false
                z.tested := true
            else
                z.state    := 5
                z.brokeRes := true
                evBroken   := true
                alert("PT Zone Sniper: " + syminfo.ticker + " " + zName + " broken — no longer active", alert.freq_once_per_bar_close)
        else if z.armed and inside
            if sup and close > z.top
                // bull test: price came down into support and closed back above it
                if z.state == 1
                    z.bullR      += 1
                    z.state      := 2
                    evBullRetest := true
                    if showRetest and sigOk
                        addSig(true, true, "Bullish break & retest\n" + zName + "\nResistance broken, retested from above and held")
                    alert("PT Zone Sniper: " + syminfo.ticker + " bullish break & retest at " + zName, alert.freq_once_per_bar_close)
                else
                    z.bullB  += 1
                    evBounce := true
                    if showBounce and sigOk
                        addSig(true, false, "Bullish bounce\n" + zName + "\nPrice tested support and closed back above")
                    if alertBounce
                        alert("PT Zone Sniper: " + syminfo.ticker + " bullish bounce at " + zName, alert.freq_once_per_bar_close)
                if wasQ and sigOk
                    addArrow(true, "Buy entry confirmed\nEntry: " + fmt(close) + " (close of this candle)\n" + zName + "\n" + (z.bullR > 0 and z.bullB == 0 ? "Break & retest held" : "Support held again"), z.rank == 0 ? 0 : 1)
                    if alertEntry
                        alert("PT Zone Sniper: " + syminfo.ticker + " BUY entry confirmed at " + fmt(close) + " · " + zName, alert.freq_once_per_bar_close)
                z.armed  := false
                z.tested := true
            else if not sup and close < z.bot
                // bear test: price came up into resistance and closed back below it
                if z.state == 1
                    z.bearR      += 1
                    z.state      := 2
                    evBearRetest := true
                    if showRetest and sigOk
                        addSig(false, true, "Bearish break & retest\n" + zName + "\nSupport broken, retested from below and held")
                    alert("PT Zone Sniper: " + syminfo.ticker + " bearish break & retest at " + zName, alert.freq_once_per_bar_close)
                else
                    z.bearB  += 1
                    evBounce := true
                    if showBounce and sigOk
                        addSig(false, false, "Bearish rejection\n" + zName + "\nPrice tested resistance and closed back below")
                    if alertBounce
                        alert("PT Zone Sniper: " + syminfo.ticker + " bearish rejection at " + zName, alert.freq_once_per_bar_close)
                if wasQ and sigOk
                    addArrow(false, "Sell entry confirmed\nEntry: " + fmt(close) + " (close of this candle)\n" + zName + "\n" + (z.bearR > 0 and z.bearB == 0 ? "Break & retest held" : "Resistance held again"), z.rank == 0 ? 0 : 1)
                    if alertEntry
                        alert("PT Zone Sniper: " + syminfo.ticker + " SELL entry confirmed at " + fmt(close) + " · " + zName, alert.freq_once_per_bar_close)
                z.armed  := false
                z.tested := true
        // re-arm once price has moved away from the zone
        if not z.armed and (low > z.top + lv or high < z.bot - lv)
            z.armed := true
 
// ───────────────────────────── Fair Value Gaps ─────────────────────────────
fvgActive(Fvg f) =>
    f.state <= 2
 
fvgName(Fvg f) =>
    (f.state == 0 or f.state == 6 ? "FVG" : "iFVG")
 
delFvgDraw(Fvg f) =>
    box.delete(f.bx)
    box.delete(f.unf)
    box.delete(f.bullBx)
    box.delete(f.bearBx)
    line.delete(f.ce)
    line.delete(f.ln)
    label.delete(f.lb)
    f.bx     := na
    f.unf    := na
    f.bullBx := na
    f.bearBx := na
    f.ce     := na
    f.ln     := na
    f.lb     := na
 
// entries: an FVG qualifies on its first N tests (fresh gaps qualify straight away); an iFVG qualifies while waiting for its retest
fvgQualified(Fvg f) =>
    f.state == 0 ? f.tests < fvgMaxTests : f.state == 1 ? fvgIfvg : f.state == 2 ? f.tests < fvgMaxTests : false
 
fvgFillPct(Fvg f) =>
    float h = math.max(f.top - f.bot, syminfo.mintick)
    f.state != 0 ? 0.0 : f.bull ? math.max(0.0, math.min(1.0, (f.top - f.deep) / h)) : math.max(0.0, math.min(1.0, (f.deep - f.bot) / h))
 
addFvg(bool bull, float top, float bot, int rank, string tfN, int t0, float bu, float se, float fa) =>
    bool ok = fvgOn and top > bot and not na(fa)
    if ok
        for f in fvgs
            if f.rank == rank and fvgActive(f) and f.bull == bull and math.min(f.top, top) > math.max(f.bot, bot)
                ok := false
    if ok
        fvgs.push(Fvg.new(top = top, bot = bot, bull = bull, isRes = not bull, rank = rank, tf = tfN, t0 = t0, buyV = nz(bu), sellV = nz(se), fAtr = fa, createdT = time, createdBar = bar_index, deep = bull ? top : bot))
        int cnt   = 0
        int first = -1
        for [i, f] in fvgs
            if f.rank == rank
                cnt += 1
                if first < 0
                    first := i
        if cnt > (rank == 0 ? 40 : 15) and first >= 0
            delFvgDraw(fvgs.get(first))
            fvgs.remove(first)
        if fvgAlertNew
            alert("PT Zone Sniper: " + syminfo.ticker + " new " + tfN + (bull ? " bullish" : " bearish") + " FVG " + fmt(bot) + " – " + fmt(top), alert.freq_once_per_bar_close)
    ok
 
procFvgHtf(bool use, string tf, int rank, bool nb, int dir, float top, float bot, int t, float a, float bu, float se) =>
    bool made = false
    if fvgOn and fvgHtf and use and tfOk(tf) and nb and dir != 0 and not na(top)
        made := addFvg(dir == 1, top, bot, rank, tfName(tf), t, bu, se, a)
    made
 
// create 5M FVGs (candle 1 = [2], impulse = [1], candle 3 = [0])
bool evFvgNew = false
if fvgOn and fvgChart and barstate.isconfirmed and bar_index > 3
    float rng1  = high[1] - low[1]
    float body1 = math.abs(close[1] - open[1])
    bool  dispOk = (fvgDispAtr <= 0 or rng1 >= fvgDispAtr * atrC) and (fvgBodyPct <= 0 or (rng1 > 0 and body1 / rng1 * 100 >= fvgBodyPct))
    float tot3  = fvgUp3 + fvgDn3
    float buyShare = tot3 > 0 ? 100 * fvgUp3 / tot3 : 50.0
    if low > high[2] and close[1] > open[1] and low - high[2] >= fvgMinGap * atrC and dispOk and (not fvgVolAgree or buyShare >= fvgMinVol)
        evFvgNew := addFvg(true, low, high[2], 0, tfName(timeframe.period), time[2], fvgUp3, fvgDn3, atrC)
    else if high < low[2] and close[1] < open[1] and low[2] - high >= fvgMinGap * atrC and dispOk and (not fvgVolAgree or 100 - buyShare >= fvgMinVol)
        evFvgNew := addFvg(false, low[2], high, 0, tfName(timeframe.period), time[2], fvgUp3, fvgDn3, atrC)
procFvgHtf(useH1, tfH1, 3, nbH1, f1Dir, f1Top, f1Bot, f1T, f1Atr, f1Bu, f1Se)
procFvgHtf(useH2, tfH2, 2, nbH2, f2Dir, f2Top, f2Bot, f2T, f2Atr, f2Bu, f2Se)
procFvgHtf(useH3, tfH3, 1, nbH3, f3Dir, f3Top, f3Bot, f3T, f3Atr, f3Bu, f3Se)
 
// remove mitigated / broken FVGs at the start of a new day
if rmBroken and timeframe.change("D") and fvgs.size() > 0
    for i = fvgs.size() - 1 to 0
        Fvg fr = fvgs.get(i)
        if fr.state >= 5
            delFvgDraw(fr)
            fvgs.remove(i)
 
// FVG life cycle (confirmed bars only)
bool evFvgTest   = false
bool evIfvgRet   = false
if barstate.isconfirmed and fvgs.size() > 0
    for i = fvgs.size() - 1 to 0
        Fvg f = fvgs.get(i)
        bool expired = f.rank == 0 ? bar_index - f.createdBar > fvgMaxAge : time - f.createdT > maxAge * rankTfSec(f.rank) * 1000
        if expired
            delFvgDraw(f)
            fvgs.remove(i)
            continue
        if f.state >= 5 or bar_index <= f.createdBar
            continue
        float  ce     = (f.top + f.bot) / 2
        float  lv     = leaveAtr * f.fAtr
        float  bb     = breakBuf * f.fAtr
        bool   sup    = not f.isRes
        bool   inside = high >= f.bot and low <= f.top
        bool   sigOk  = f.rank == 0 or htfSignals
        bool   wasQ   = showArrows and fvgQualified(f)
        string fName  = f.tf + " " + (f.bull ? "bullish " : "bearish ") + fvgName(f) + " " + fmt(f.bot) + " – " + fmt(f.top)
        if f.state == 0
            if sup and close < f.bot - bb
                // inversion: bullish FVG closed through → resistance (iFVG)
                f.state := fvgIfvg ? 1 : 5
                f.endT  := time
                f.isRes := true
                f.armed := false
                f.tests := 0
            else if not sup and close > f.top + bb
                f.state := fvgIfvg ? 1 : 5
                f.endT  := time
                f.isRes := false
                f.armed := false
                f.tests := 0
            else
                if sup and inside
                    f.deep := math.max(math.min(f.deep, low), f.bot)
                if not sup and inside
                    f.deep := math.min(math.max(f.deep, high), f.top)
                if (sup and low <= f.bot) or (not sup and high >= f.top)
                    // gap completely filled without a close beyond: imbalance used up
                    f.state := 6
                    f.endT  := time
                else if f.armed and (sup ? (low <= ce and close > ce and close > open) : (high >= ce and close < ce and close < open))
                    // respected: price reached the CE and closed back on the FVG's side
                    f.tests  += 1
                    f.armed  := false
                    evFvgTest := true
                    if showBounce and sigOk
                        addSig(sup, false, (sup ? "Bullish" : "Bearish") + " FVG respected at CE\n" + fName + "\nCE " + fmt(ce) + " · test " + str.tostring(f.tests))
                    if wasQ and sigOk
                        addArrow(sup, (sup ? "Buy" : "Sell") + " entry confirmed (FVG)\nEntry: " + fmt(close) + " (close of this candle)\n" + fName + "\nCE " + fmt(ce) + " held · test " + str.tostring(f.tests), f.rank == 0 ? 2 : 3)
                        if alertEntry
                            alert("PT Zone Sniper: " + syminfo.ticker + (sup ? " BUY" : " SELL") + " entry confirmed at " + fmt(close) + " · " + fName, alert.freq_once_per_bar_close)
        else
            if (f.isRes and close > f.top + bb) or (not f.isRes and close < f.bot - bb)
                f.state := 5
                f.endT  := time
            else if f.armed and inside and (f.isRes ? close < f.bot : close > f.top)
                bool first = f.state == 1
                f.tests += 1
                f.state := 2
                f.armed := false
                if first
                    evIfvgRet := true
                    if showRetest and sigOk
                        addSig(not f.isRes, true, (f.isRes ? "Bearish" : "Bullish") + " iFVG retest\n" + fName + "\nGap closed through, retested from the other side and held")
                    alert("PT Zone Sniper: " + syminfo.ticker + (f.isRes ? " bearish" : " bullish") + " iFVG retest at " + fName, alert.freq_once_per_bar_close)
                else if showBounce and sigOk
                    addSig(not f.isRes, false, (f.isRes ? "Bearish" : "Bullish") + " iFVG test\n" + fName)
                if wasQ and sigOk
                    addArrow(not f.isRes, (f.isRes ? "Sell" : "Buy") + " entry confirmed (iFVG)\nEntry: " + fmt(close) + " (close of this candle)\n" + fName, f.rank == 0 ? 2 : 3)
                    if alertEntry
                        alert("PT Zone Sniper: " + syminfo.ticker + (f.isRes ? " SELL" : " BUY") + " entry confirmed at " + fmt(close) + " · " + fName, alert.freq_once_per_bar_close)
        if not f.armed and (low > f.top + lv or high < f.bot - lv)
            f.armed := true
 
// ───────────────────────────── Drawing (last bar only) ─────────────────────────────
zDist(Zone z) =>
    z.bot > close ? z.bot - close : z.top < close ? close - z.top : 0.0
 
zAbove(Zone z) =>
    z.bot > close or (z.top >= close and z.bot <= close and z.isRes)
 
zoneTip(Zone z, string role, float bp, float sp) =>
    int    bullT = z.bullB + z.bullR
    int    bearT = z.bearB + z.bearR
    string st    = z.state == 0 ? (z.tested ? "Active — tested" : "Active — untested") : z.state == 1 ? "Broken and flipped to " + role + " — waiting for a retest" : z.state == 2 ? "Break & retest confirmed — acting as " + role : "Broken — no longer active"
    z.tf + " " + role + (z.rank > 0 ? " Line" : " Zone") +
     "\nRange: " + fmt(z.bot) + " – " + fmt(z.top) +
     "\nFormed by " + str.tostring(z.nSw) + " matching swing " + (z.origRes ? "highs" : "lows") + " (the touches before the zone was confirmed)" +
     "\nTests count only after confirmation" +
     "\nVolume (" + (volMode == "At touches" ? "at touches" : "between swings") + (z.rank > 0 ? ", estimated from candles" : "") + "):" +
     "\n  Buy " + pct(bp) + " (" + str.tostring(z.buyV, format.volume) + ") · Sell " + pct(sp) + " (" + str.tostring(z.sellV, format.volume) + ")" +
     "\n  Delta " + (bp >= sp ? "+" : "") + pct(bp - sp) + (na(z.volX) ? "" : " · " + str.tostring(z.volX, "#.#") + "× average volume") +
     "\nBull tests: " + str.tostring(bullT) + " (" + str.tostring(z.bullB) + " bounce, " + str.tostring(z.bullR) + " break & retest)" +
     "\nBear tests: " + str.tostring(bearT) + " (" + str.tostring(z.bearB) + " rejection, " + str.tostring(z.bearR) + " break & retest)" +
     "\nState: " + st
 
drawZone(Zone z, int xr) =>
    bool   broken = z.state == 5
    bool   asLine = broken or z.rank > 0
    color  roleC  = broken ? color.gray : (greyFirst and not z.tested) ? colNeutral : z.isRes ? colRes : colSup
    string role   = (broken ? z.brokeRes : z.isRes) ? "Resistance" : "Support"
    float  tot    = math.max(z.buyV + z.sellV, 1.0e-10)
    float  bp     = z.buyV + z.sellV > 0 ? 100 * z.buyV / tot : 50.0
    float  sp     = 100 - bp
    int    bullT  = z.bullB + z.bullR
    int    bearT  = z.bearB + z.bearR
    string tip    = zoneTip(z, role, bp, sp) + (z.grpN > 1 ? z.grpTip : "")
    if asLine
        delBoxParts(z)
        float lvl = lineLvl == "Mid" ? (z.top + z.bot) / 2 : lineLvl == "Near edge" ? (z.isRes ? z.bot : z.top) : (z.isRes ? z.top : z.bot)
        if na(z.ln)
            z.ln := line.new(z.t0, lvl, xr, lvl, xloc = xloc.bar_time)
        line.set_xy1(z.ln, z.t0, lvl)
        line.set_xy2(z.ln, xr, lvl)
        line.set_color(z.ln, roleC)
        line.set_style(z.ln, broken ? line.style_dotted : line.style_solid)
        line.set_width(z.ln, broken ? 1 : z.rank == 3 ? 2 : 1)
        string txt = broken ? z.tf + " " + role + (z.rank > 0 ? " Line" : "") + " - Broken" : z.tf + " " + role + " Line" + (z.grpN > 1 ? " (" + str.tostring(z.grpN) + " levels)" : "") + " - Buy " + pct(bp) + " · Sell " + pct(sp) + " - Tests ▲" + str.tostring(bullT) + " ▼" + str.tostring(bearT)
        if na(z.lnL)
            z.lnL := label.new(xr, lvl, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), size = tSize)
        label.set_xy(z.lnL, xr, lvl)
        label.set_text(z.lnL, txt)
        label.set_textcolor(z.lnL, roleC)
        label.set_tooltip(z.lnL, tip)
    else
        delLineParts(z)
        float midY = (z.top + z.bot) / 2
        if na(z.bx)
            z.bx := box.new(z.t0, z.top, xr, z.bot, xloc = xloc.bar_time)
        box.set_lefttop(z.bx, z.t0, z.top)
        box.set_rightbottom(z.bx, xr, z.bot)
        box.set_bgcolor(z.bx, color.new(roleC, fillTr))
        box.set_border_color(z.bx, color.new(roleC, borderTr))
        if showMid
            if na(z.mid)
                z.mid := line.new(z.t0, midY, xr, midY, xloc = xloc.bar_time, style = line.style_dotted)
            line.set_xy1(z.mid, z.t0, midY)
            line.set_xy2(z.mid, xr, midY)
            line.set_color(z.mid, color.new(roleC, borderTr))
        else
            line.delete(z.mid)
            z.mid := na
        if showBars
            // red (bear) bar in the top half, green (bull) bar in the bottom half; the larger side spans half the zone
            int span  = math.max(int((xr - z.t0) / 2), 1)
            int bullX = z.t0 + (bp >= sp ? span : int(span * bp / math.max(sp, 1.0e-10)))
            int bearX = z.t0 + (sp >= bp ? span : int(span * sp / math.max(bp, 1.0e-10)))
            if na(z.bearBx)
                z.bearBx := box.new(z.t0, z.top, bearX, midY, xloc = xloc.bar_time, border_color = color.new(colRes, 100))
            if na(z.bullBx)
                z.bullBx := box.new(z.t0, midY, bullX, z.bot, xloc = xloc.bar_time, border_color = color.new(colSup, 100))
            box.set_lefttop(z.bearBx, z.t0, z.top)
            box.set_rightbottom(z.bearBx, bearX, midY)
            box.set_bgcolor(z.bearBx, color.new(colRes, barTr))
            box.set_lefttop(z.bullBx, z.t0, midY)
            box.set_rightbottom(z.bullBx, bullX, z.bot)
            box.set_bgcolor(z.bullBx, color.new(colSup, barTr))
            // the swings that formed the zone are shown on their own side: lows with Buy, highs with Sell
            string swTxt   = str.tostring(z.nSw) + (z.origRes ? " highs · " : " lows · ")
            string bullTxt = "Buy " + pct(bp) + " · " + str.tostring(z.buyV, format.volume) + " · " + (z.origRes ? "" : swTxt) + str.tostring(bullT) + (bullT == 1 ? " test" : " tests")
            string bearTxt = "Sell " + pct(sp) + " · " + str.tostring(z.sellV, format.volume) + " · " + (z.origRes ? swTxt : "") + str.tostring(bearT) + (bearT == 1 ? " test" : " tests")
            // text sits at the far right of the zone, close to the live candles
            if na(z.bullL)
                z.bullL := label.new(xr, (midY + z.bot) / 2, bullTxt, xloc = xloc.bar_time, style = label.style_label_right, color = color.new(color.black, 100), textcolor = colSup, size = tSize)
            if na(z.bearL)
                z.bearL := label.new(xr, (z.top + midY) / 2, bearTxt, xloc = xloc.bar_time, style = label.style_label_right, color = color.new(color.black, 100), textcolor = colRes, size = tSize)
            label.set_xy(z.bullL, xr, (midY + z.bot) / 2)
            label.set_text(z.bullL, bullTxt)
            label.set_tooltip(z.bullL, tip)
            label.set_xy(z.bearL, xr, (z.top + midY) / 2)
            label.set_text(z.bearL, bearTxt)
            label.set_tooltip(z.bearL, tip)
        else
            box.delete(z.bullBx)
            box.delete(z.bearBx)
            label.delete(z.bullL)
            label.delete(z.bearL)
            z.bullBx := na
            z.bearBx := na
            z.bullL  := na
            z.bearL  := na
    true
 
var array<box>   brkB  = array.new<box>()
var array<line>  brkLn = array.new<line>()
var array<label> brkLb = array.new<label>()
 
// one grey zone (or one dotted line) per group of nearby broken levels of the same timeframe
drawBroken(string tfN, bool isLine, float cBot, float cTop, int cnt, int t0, bool sRes, string tip, int xr) =>
    float mid = (cTop + cBot) / 2
    string txt = cnt == 1 ? tfN + " " + (sRes ? "Resistance" : "Support") + (isLine ? " Line" : "") + " - Broken" : tfN + " Broken zone - " + str.tostring(cnt) + " levels"
    if cnt == 1
        brkLn.push(line.new(t0, mid, xr, mid, xloc = xloc.bar_time, color = color.gray, style = line.style_dotted))
    else
        brkB.push(box.new(t0, cTop, xr, cBot, xloc = xloc.bar_time, border_color = color.new(color.gray, 30), border_style = line.style_dotted, bgcolor = color.new(color.gray, 90)))
    brkLb.push(label.new(xr, mid, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.gray, size = tSize, tooltip = tip))
    true
 
if barstate.islast
    for b in brkB
        box.delete(b)
    for l in brkLn
        line.delete(l)
    for lb in brkLb
        label.delete(lb)
    brkB.clear()
    brkLn.clear()
    brkLb.clear()
 
if barstate.islast and zones.size() > 0
    float rangeP = rangeAtr * nz(dAtr, 50 * atrC)
    for z in zones
        z.vis := showAll
    if not showAll
        // nearest active zones on each side of price, per timeframe, within range
        for rk = 0 to 3
            int lim = rk == 0 ? maxEach : maxHtfEach
            for side = 0 to 1
                int picked = 0
                while picked < lim
                    int   bi = -1
                    float bd = 1.0e10
                    for [i, z] in zones
                        if z.rank == rk and isActive(z) and not z.vis and zAbove(z) == (side == 0) and zDist(z) <= rangeP and zDist(z) < bd
                            bi := i
                            bd := zDist(z)
                    if bi < 0
                        break
                    Zone zb = zones.get(bi)
                    zb.vis := true
                    picked += 1
        for z in zones
            if z.state == 5 and zDist(z) <= rangeP
                z.vis := true
    // group close active lines of the same timeframe and role: one line, one label
    for z in zones
        z.grpN   := 1
        z.grpTip := ""
    if lineMerge > 0
        for rk = 1 to 3
            array<Zone> az = array.new<Zone>()
            for z in zones
                if z.rank == rk and z.vis and isActive(z)
                    az.push(z)
            if az.size() > 1
                array<Zone> srt = array.new<Zone>()
                while az.size() > 0
                    int   mi = 0
                    float mv = 1.0e10
                    for [i, z] in az
                        if z.bot < mv
                            mv := z.bot
                            mi := i
                    srt.push(az.remove(mi))
                int   gStart = 0
                float gTop   = srt.get(0).top
                bool  gRes   = srt.get(0).isRes
                for k = 1 to srt.size()
                    bool endGrp = k == srt.size()
                    if not endGrp
                        Zone nx = srt.get(k)
                        endGrp := nx.isRes != gRes or nx.bot - gTop > lineMerge * nx.zAtr
                    if endGrp
                        int n = k - gStart
                        if n > 1
                            // keep the most tested (then newest) line as the representative
                            int    rep = gStart
                            string gt  = "\n\nGrouped levels (" + str.tostring(n) + "):"
                            for m = gStart to k - 1
                                Zone zm = srt.get(m)
                                Zone zr = srt.get(rep)
                                int  tm = zm.bullB + zm.bullR + zm.bearB + zm.bearR
                                int  tr = zr.bullB + zr.bullR + zr.bearB + zr.bearR
                                if tm > tr or (tm == tr and zm.createdT > zr.createdT)
                                    rep := m
                                gt += "\n• " + fmt(zm.bot) + " – " + fmt(zm.top) + " · tests ▲" + str.tostring(zm.bullB + zm.bullR) + " ▼" + str.tostring(zm.bearB + zm.bearR)
                            for m = gStart to k - 1
                                Zone zm = srt.get(m)
                                if m == rep
                                    zm.grpN   := n
                                    zm.grpTip := gt
                                else
                                    zm.vis := false
                        if k < srt.size()
                            gStart := k
                            gTop   := srt.get(k).top
                            gRes   := srt.get(k).isRes
                    else
                        gTop := math.max(gTop, srt.get(k).top)
    int xr = time + extendBars * chartMs
    for z in zones
        if z.vis and z.state != 5
            drawZone(z, xr)
        else
            delDraw(z)
    // group visible broken levels per timeframe, lowest first
    for rk = 0 to 3
        array<Zone> bz = array.new<Zone>()
        for z in zones
            if z.state == 5 and z.vis and z.rank == rk
                bz.push(z)
        if bz.size() > 0
            array<Zone> srt = array.new<Zone>()
            while bz.size() > 0
                int   mi = 0
                float mv = 1.0e10
                for [i, z] in bz
                    if z.bot < mv
                        mv := z.bot
                        mi := i
                srt.push(bz.remove(mi))
            float  cBot = na
            float  cTop = na
            int    cnt  = 0
            int    ct0  = na
            bool   sRes = false
            string tip  = ""
            string tfN  = srt.get(0).tf
            for z in srt
                float tol = brkMerge * z.zAtr
                if cnt > 0 and z.bot - cTop > tol
                    drawBroken(tfN, rk > 0, cBot, cTop, cnt, ct0, sRes, tip, xr)
                    cnt := 0
                if cnt == 0
                    cBot := z.bot
                    cTop := z.top
                    ct0  := z.t0
                    sRes := z.brokeRes
                    tip  := tfN + " broken levels:"
                else
                    cBot := math.min(cBot, z.bot)
                    cTop := math.max(cTop, z.top)
                    ct0  := math.min(ct0, z.t0)
                cnt += 1
                tip += "\n• " + (z.brokeRes ? "Resistance " : "Support ") + fmt(z.bot) + " – " + fmt(z.top)
            if cnt > 0
                drawBroken(tfN, rk > 0, cBot, cTop, cnt, ct0, sRes, tip, xr)
 
// ───────────────────────────── FVG drawing (last bar only) ─────────────────────────────
fDist(Fvg f) =>
    f.bot > close ? f.bot - close : f.top < close ? close - f.top : 0.0
 
fAbove(Fvg f) =>
    f.bot > close or (f.top >= close and f.bot <= close and f.isRes)
 
fvgTip(Fvg f, float bp, float sp) =>
    float  ce = (f.top + f.bot) / 2
    string st = f.state == 0 ? (f.tests == 0 ? "Fresh — untested" : "Respected " + str.tostring(f.tests) + "×") : f.state == 1 ? "Inverted (iFVG) — waiting for a retest from the other side" : f.state == 2 ? "iFVG retest confirmed — acting as " + (f.isRes ? "resistance" : "support") : f.state == 6 ? "Mitigated — gap fully filled" : "Broken — no longer active"
    f.tf + " " + (f.bull ? "Bullish " : "Bearish ") + fvgName(f) + (f.rank > 0 ? " Line" : "") +
     "\nRange: " + fmt(f.bot) + " – " + fmt(f.top) + " · CE (50%) " + fmt(ce) +
     (f.state == 0 ? "\nFilled: " + str.tostring(fvgFillPct(f) * 100, "#") + "%" : "") +
     "\nVolume of the 3 formation candles" + (f.rank > 0 ? " (estimated from candles)" : "") + ":" +
     "\n  Buy " + pct(bp) + " (" + str.tostring(f.buyV, format.volume) + ") · Sell " + pct(sp) + " (" + str.tostring(f.sellV, format.volume) + ")" +
     "\nTests: " + str.tostring(f.tests) + " · entry arrows on the first " + str.tostring(fvgMaxTests) +
     "\nState: " + st
 
drawFvg(Fvg f, int xr) =>
    bool   dead  = f.state >= 5
    color  roleC = dead ? color.gray : f.isRes ? colFvgBear : colFvgBull
    float  tot   = math.max(f.buyV + f.sellV, 1.0e-10)
    float  bp    = f.buyV + f.sellV > 0 ? 100 * f.buyV / tot : 50.0
    float  sp    = 100 - bp
    float  ce    = (f.top + f.bot) / 2
    float  fp    = fvgFillPct(f)
    string tip   = fvgTip(f, bp, sp)
    string nm    = fvgName(f)
    if dead
        // finished FVG: grey dotted box left where it was, from candle 1 to the candle that mitigated / broke it
        box.delete(f.unf)
        box.delete(f.bullBx)
        box.delete(f.bearBx)
        line.delete(f.ce)
        line.delete(f.ln)
        label.delete(f.lb)
        f.unf    := na
        f.bullBx := na
        f.bearBx := na
        f.ce     := na
        f.ln     := na
        f.lb     := na
        int    endX = na(f.endT) ? time : f.endT
        string dTxt = nm + (f.state == 6 ? " · Mitigated" : " · Broken")
        if na(f.bx)
            f.bx := box.new(f.t0, f.top, endX, f.bot, xloc = xloc.bar_time)
        box.set_lefttop(f.bx, f.t0, f.top)
        box.set_rightbottom(f.bx, endX, f.bot)
        box.set_border_color(f.bx, color.new(color.gray, 30))
        box.set_border_style(f.bx, line.style_dotted)
        box.set_bgcolor(f.bx, color.new(color.gray, 90))
        box.set_text(f.bx, dTxt)
        box.set_text_size(f.bx, size.tiny)
        box.set_text_color(f.bx, color.new(color.gray, 20))
        box.set_text_halign(f.bx, text.align_center)
        box.set_text_valign(f.bx, text.align_center)
    else if f.rank > 0
        // a single dashed line at the CE for higher-timeframe FVGs
        box.delete(f.bx)
        box.delete(f.unf)
        box.delete(f.bullBx)
        box.delete(f.bearBx)
        line.delete(f.ce)
        f.bx     := na
        f.unf    := na
        f.bullBx := na
        f.bearBx := na
        f.ce     := na
        if na(f.ln)
            f.ln := line.new(f.t0, ce, xr, ce, xloc = xloc.bar_time)
        line.set_xy1(f.ln, f.t0, ce)
        line.set_xy2(f.ln, xr, ce)
        line.set_color(f.ln, roleC)
        line.set_style(f.ln, line.style_dashed)
        line.set_width(f.ln, f.rank == 3 ? 2 : 1)
        string txt = f.tf + " " + nm + " Line - Buy " + pct(bp) + " · Sell " + pct(sp) + (f.state == 0 ? " - " + str.tostring(fp * 100, "#") + "% filled" : "") + " - Tests " + str.tostring(f.tests)
        if na(f.lb)
            f.lb := label.new(xr, ce, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), size = tSize)
        label.set_xy(f.lb, xr, ce)
        label.set_text(f.lb, txt)
        label.set_textcolor(f.lb, roleC)
        label.set_tooltip(f.lb, tip)
    else
        line.delete(f.ln)
        f.ln := na
        // whole gap: dashed border, faint fill; unfilled part: stronger fill
        if na(f.bx)
            f.bx := box.new(f.t0, f.top, xr, f.bot, xloc = xloc.bar_time, border_style = line.style_dashed)
        box.set_border_style(f.bx, line.style_dashed)
        box.set_text(f.bx, "")
        box.set_lefttop(f.bx, f.t0, f.top)
        box.set_rightbottom(f.bx, xr, f.bot)
        box.set_border_color(f.bx, color.new(roleC, fvgBorderTr))
        box.set_bgcolor(f.bx, color.new(roleC, fvgShowFill and f.state == 0 ? math.min(fvgFillTr + 12, 100) : fvgFillTr))
        if fvgShowFill and f.state == 0 and fp > 0
            float uTop = f.bull ? f.deep : f.top
            float uBot = f.bull ? f.bot : f.deep
            if na(f.unf)
                f.unf := box.new(f.t0, uTop, xr, uBot, xloc = xloc.bar_time, border_color = color.new(roleC, 100))
            box.set_lefttop(f.unf, f.t0, uTop)
            box.set_rightbottom(f.unf, xr, uBot)
            box.set_bgcolor(f.unf, color.new(roleC, fvgFillTr))
        else if fvgShowFill and f.state == 0
            if na(f.unf)
                f.unf := box.new(f.t0, f.top, xr, f.bot, xloc = xloc.bar_time, border_color = color.new(roleC, 100))
            box.set_lefttop(f.unf, f.t0, f.top)
            box.set_rightbottom(f.unf, xr, f.bot)
            box.set_bgcolor(f.unf, color.new(roleC, fvgFillTr))
        else
            box.delete(f.unf)
            f.unf := na
        if fvgShowCE
            if na(f.ce)
                f.ce := line.new(f.t0, ce, xr, ce, xloc = xloc.bar_time, style = line.style_dotted)
            line.set_xy1(f.ce, f.t0, ce)
            line.set_xy2(f.ce, xr, ce)
            line.set_color(f.ce, color.new(roleC, 20))
        else
            line.delete(f.ce)
            f.ce := na
        if showBars
            int span  = math.max(int((xr - f.t0) / 2), 1)
            int bullX = f.t0 + (bp >= sp ? span : int(span * bp / math.max(sp, 1.0e-10)))
            int bearX = f.t0 + (sp >= bp ? span : int(span * sp / math.max(bp, 1.0e-10)))
            if na(f.bearBx)
                f.bearBx := box.new(f.t0, f.top, bearX, ce, xloc = xloc.bar_time, border_color = color.new(colRes, 100))
            if na(f.bullBx)
                f.bullBx := box.new(f.t0, ce, bullX, f.bot, xloc = xloc.bar_time, border_color = color.new(colSup, 100))
            box.set_lefttop(f.bearBx, f.t0, f.top)
            box.set_rightbottom(f.bearBx, bearX, ce)
            box.set_bgcolor(f.bearBx, color.new(colFvgBear, math.min(barTr + 15, 100)))
            box.set_lefttop(f.bullBx, f.t0, ce)
            box.set_rightbottom(f.bullBx, bullX, f.bot)
            box.set_bgcolor(f.bullBx, color.new(colFvgBull, math.min(barTr + 15, 100)))
        else
            box.delete(f.bullBx)
            box.delete(f.bearBx)
            f.bullBx := na
            f.bearBx := na
        // one label at the far right (FVGs are thin, so one line of text)
        string txt = nm + " · Buy " + pct(bp) + " / Sell " + pct(sp) + (f.state == 0 ? " · " + str.tostring(fp * 100, "#") + "% filled" : "") + " · " + str.tostring(f.tests) + (f.tests == 1 ? " test" : " tests")
        if na(f.lb)
            f.lb := label.new(xr, ce, txt, xloc = xloc.bar_time, style = label.style_label_right, color = color.new(color.black, 100), size = tSize)
        label.set_xy(f.lb, xr, ce)
        label.set_text(f.lb, txt)
        label.set_textcolor(f.lb, roleC)
        label.set_tooltip(f.lb, tip)
    true
 
if barstate.islast and fvgs.size() > 0
    float rangeF = rangeAtr * nz(dAtr, 50 * atrC)
    for f in fvgs
        f.vis := fvgOn and ((f.state >= 5 and f.rank == 0) or (showAll and f.state < 5))
    if fvgOn and not showAll
        for rk = 0 to 3
            int lim = rk == 0 ? fvgMaxEach : fvgHtfEach
            for side = 0 to 1
                int picked = 0
                while picked < lim
                    int   bi = -1
                    float bd = 1.0e10
                    for [i, f] in fvgs
                        if f.rank == rk and fvgActive(f) and not f.vis and fAbove(f) == (side == 0) and fDist(f) <= rangeF and fDist(f) < bd
                            bi := i
                            bd := fDist(f)
                    if bi < 0
                        break
                    Fvg fb = fvgs.get(bi)
                    fb.vis := true
                    picked += 1
    int xrF = time + extendBars * chartMs
    for f in fvgs
        if f.vis
            drawFvg(f, xrF)
        else
            delFvgDraw(f)
 
// ───────────────────────────── Entry arrows: pending (live, last bar) ─────────────────────────────
var label pendB = na
var label pendS = na
if barstate.islast
    label.delete(pendB)
    label.delete(pendS)
    pendB := na
    pendS := na
    if showArrows and (zones.size() > 0 or fvgs.size() > 0)
        float reach = pendReach * nz(dAtr, 50 * atrC)
        int   bi    = -1
        int   si    = -1
        float bd    = 1.0e10
        float sd2   = 1.0e10
        float bLvl  = na
        float sLvl  = na
        string bTip = ""
        string sTip = ""
        for [i, z] in zones
            if z.vis and isActive(z) and (z.rank == 0 or htfSignals) and qualified(z)
                float dB = math.max(close - z.top, 0)
                float dS = math.max(z.bot - close, 0)
                if not z.isRes and z.bot <= close and dB <= reach and dB < bd
                    bi   := i
                    bd   := dB
                    bLvl := z.top
                    bTip := "Pending buy entry\nEntry: " + fmt(z.top) + " (top of the " + z.tf + " support)\nWaiting for price to test the zone and close back above"
                if z.isRes and z.top >= close and dS <= reach and dS < sd2
                    si   := i
                    sd2  := dS
                    sLvl := z.bot
                    sTip := "Pending sell entry\nEntry: " + fmt(z.bot) + " (bottom of the " + z.tf + " resistance)\nWaiting for price to test the zone and close back below"
        // FVGs: entry at the CE (50%)
        for f in fvgs
            if f.vis and fvgActive(f) and (f.rank == 0 or htfSignals) and fvgQualified(f)
                float ceF = (f.top + f.bot) / 2
                if not f.isRes and ceF <= close and close - ceF <= reach and close - ceF < bd
                    bi   := 0
                    bd   := close - ceF
                    bLvl := ceF
                    bTip := "Pending buy entry (" + fvgName(f) + ")\nEntry: " + fmt(ceF) + " (CE of the " + f.tf + " " + fvgName(f) + ")\nWaiting for price to reach the CE and close back above"
                if f.isRes and ceF >= close and ceF - close <= reach and ceF - close < sd2
                    si   := 0
                    sd2  := ceF - close
                    sLvl := ceF
                    sTip := "Pending sell entry (" + fvgName(f) + ")\nEntry: " + fmt(ceF) + " (CE of the " + f.tf + " " + fvgName(f) + ")\nWaiting for price to reach the CE and close back below"
        int xp = time + 3 * chartMs
        if bi >= 0 and not na(bLvl)
            pendB := label.new(xp, bLvl, "▲", xloc = xloc.bar_time, style = label.style_label_up, color = color.new(color.black, 100), textcolor = colPend, size = size.normal, tooltip = bTip)
        if si >= 0 and not na(sLvl)
            pendS := label.new(xp, sLvl, "▼", xloc = xloc.bar_time, style = label.style_label_down, color = color.new(color.black, 100), textcolor = colPend, size = size.normal, tooltip = sTip)
 
// ───────────────────────────── Signal check panel ─────────────────────────────
if barstate.isconfirmed and openSigs.size() > 0
    for i = openSigs.size() - 1 to 0
        Sig  sg   = openSigs.get(i)
        if bar_index > sg.bar
            bool hitT = sg.bull ? high >= sg.tgt : low <= sg.tgt
            bool hitS = sg.bull ? low <= sg.stp : high >= sg.stp
            int  res  = hitS ? 2 : hitT ? 1 : bar_index - sg.bar >= stBars ? 3 : 0   // both in one candle counts as a loss
            if res == 1
                stW.set(sg.src, stW.get(sg.src) + 1)
            else if res == 2
                stL.set(sg.src, stL.get(sg.src) + 1)
            else if res == 3
                stE.set(sg.src, stE.get(sg.src) + 1)
            if res != 0
                openSigs.remove(i)
 
var table statT = na
if barstate.islast
    table.delete(statT)
    statT := na
    if showStats
        string ps = stPos == "Top right" ? position.top_right : stPos == "Bottom left" ? position.bottom_left : stPos == "Top left" ? position.top_left : position.bottom_right
        statT := table.new(ps, 6, 7, bgcolor = color.new(color.black, 25), border_width = 1, border_color = color.new(color.gray, 70))
        color hc = color.new(color.white, 0)
        table.cell(statT, 0, 0, "Signal check · win +" + str.tostring(stTgt) + " / loss -" + str.tostring(stStp) + " ATR · " + str.tostring(stBars) + " bars", text_color = hc, text_size = size.small, text_halign = text.align_left)
        table.merge_cells(statT, 0, 0, 5, 0)
        array<string> hd = array.from("Source", "Signals", "Win", "Loss", "Open / exp.", "Win %")
        for c = 0 to 5
            table.cell(statT, c, 1, hd.get(c), text_color = color.gray, text_size = size.small)
        array<string> nm = array.from("S/R zones 5M", "S/R lines HTF", "FVG 5M", "FVG lines HTF")
        int tN = 0
        int tW = 0
        int tL = 0
        int tE = 0
        for r = 0 to 4
            int n  = r < 4 ? stN.get(r) : tN
            int w  = r < 4 ? stW.get(r) : tW
            int l  = r < 4 ? stL.get(r) : tL
            int e  = r < 4 ? stE.get(r) : tE
            int op = n - w - l - e
            string wp = w + l > 0 ? str.tostring(100.0 * w / (w + l), "#") + "%" : "—"
            color tc = r < 4 ? color.white : color.yellow
            table.cell(statT, 0, r + 2, r < 4 ? nm.get(r) : "Total", text_color = tc, text_size = size.small, text_halign = text.align_left)
            table.cell(statT, 1, r + 2, str.tostring(n), text_color = tc, text_size = size.small)
            table.cell(statT, 2, r + 2, str.tostring(w), text_color = colSup, text_size = size.small)
            table.cell(statT, 3, r + 2, str.tostring(l), text_color = colRes, text_size = size.small)
            table.cell(statT, 4, r + 2, str.tostring(op) + " / " + str.tostring(e), text_color = color.gray, text_size = size.small)
            table.cell(statT, 5, r + 2, wp, text_color = tc, text_size = size.small)
            if r < 4
                tN += n
                tW += w
                tL += l
                tE += e
 
// ───────────────────────────── Alert conditions ─────────────────────────────
alertcondition(evNewRes, "New resistance zone", "PT Zone Sniper: new resistance zone from matching swing highs")
alertcondition(evNewSup, "New support zone", "PT Zone Sniper: new support zone from matching swing lows")
alertcondition(evBullRetest, "Bullish break & retest", "PT Zone Sniper: resistance broken, retested from above and held")
alertcondition(evBearRetest, "Bearish break & retest", "PT Zone Sniper: support broken, retested from below and held")
alertcondition(evBounce, "Zone bounce / rejection", "PT Zone Sniper: price tested a zone and closed back out")
alertcondition(evBroken, "Zone broken", "PT Zone Sniper: a zone broke and is no longer active")
alertcondition(evFvgNew, "New 5M FVG", "PT Zone Sniper: a new fair value gap formed")
alertcondition(evFvgTest, "FVG respected at CE", "PT Zone Sniper: price reached the FVG midpoint and closed back out")
alertcondition(evIfvgRet, "iFVG retest", "PT Zone Sniper: an inverted FVG was retested from the other side and held")

← 返回列表