Pro Trader Liquidity Sweep V26.01 - By: Mo Alqaq

MoAlqaq · study · 917 行 · 点赞 72 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
// Pro Trader Liquidity Sweep V26.01 - By: Mo Alqaq
// © Mo Alqaq
//
// A liquidity map. It marks where stop orders are likely to rest (swing highs / lows, equal highs /
// lows, previous day and week highs / lows, session ranges, M15 / H1 swings, round numbers), measures
// the tick volume traded at each level, classes each level as major (more likely to hold) or minor
// (more likely to be run through), highlights the next liquidity above and below price, and marks
// sweeps — candles that trade through a level and close back inside.
// It does not generate entries or exits.
// All levels and sweeps are confirmed on closed candles; nothing repaints.
// ============================================================================
indicator("Pro Trader Liquidity Sweep V26.01 - By: Mo Alqaq", shorttitle = "PT Liquidity Sweep V26.01", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 1000)
 
// ============================================================================
// 1. INPUTS
// ============================================================================
 
// ── General ──
grpGen = "General"
atrLen = input.int(14, "ATR length", minval = 1, maxval = 100, group = grpGen, display = display.none, tooltip = "Distances, zone heights and tolerances are measured in ATR so they adapt to volatility.")
 
// ── Liquidity pools ──
grpPool    = "Liquidity pools"
swL        = input.int(5, "Swing pivots — left", minval = 1, maxval = 30, group = grpPool, display = display.none)
swR        = input.int(3, "Swing pivots — right", minval = 1, maxval = 20, group = grpPool, display = display.none, tooltip = "A swing high or low becomes a pool once this many candles have closed after it, so pools never repaint.")
eqTol      = input.float(0.1, "Equal-level tolerance (× ATR)", minval = 0.01, maxval = 1.0, step = 0.01, group = grpPool, display = display.none, tooltip = "Two levels this close on the same side merge into one pool (two swings make an EQH / EQL).")
usePW      = input.bool(true, "Previous week high / low", group = grpPool, display = display.none)
usePD      = input.bool(true, "Previous day high / low", group = grpPool, display = display.none)
useTky     = input.bool(true, "Tokyo range", inline = "ses", group = grpPool, display = display.none)
useLdn     = input.bool(true, "London range", inline = "ses", group = grpPool, display = display.none)
useNy      = input.bool(false, "New York range", inline = "ses", group = grpPool, display = display.none, tooltip = "Each session's high and low become pools when the session closes. Tokyo 09:00–18:00 Tokyo time · London 08:00–17:00 London time · New York 09:00–17:00 (gold) or 08:30–17:00 New York time. Daylight saving is handled automatically.")
useRN      = input.bool(false, "Round numbers", inline = "rn", group = grpPool, display = display.none)
rnStep     = input.float(25.0, "Step", minval = 0.0001, inline = "rn", group = grpPool, display = display.none, tooltip = "Marks the nearest round number above and below price, e.g. every 25.0 on gold.")
maxAge     = input.int(300, "Swing pool max age (bars)", minval = 20, maxval = 2000, group = grpPool, display = display.none, tooltip = "A chart-timeframe swing or round-number pool not taken within this many candles is removed.")
maxAgeHtf  = input.int(2000, "Week / day / session / M15 / H1 pool max age (bars)", minval = 100, maxval = 5000, group = grpPool, display = display.none)
maxPerSide = input.int(15, "Max live pools per side", minval = 3, maxval = 40, group = grpPool, display = display.none, tooltip = "When exceeded, the pool with the lowest strength score is dropped.")
 
// ── Higher-timeframe pools ──
grpHtf = "Higher-timeframe pools"
useM15 = input.bool(true, "M15 swing pools", inline = "htf", group = grpHtf, display = display.none)
useH1  = input.bool(true, "H1 swing pools", inline = "htf", group = grpHtf, display = display.none, tooltip = "Swing highs / lows of the M15 and H1 candles, added once the higher-timeframe candle that confirms them has closed, so they never repaint. Shown only on charts below that timeframe.")
htfL   = input.int(3, "Pivots — left", minval = 1, maxval = 20, inline = "htfp", group = grpHtf, display = display.none)
htfR   = input.int(2, "right", minval = 1, maxval = 10, inline = "htfp", group = grpHtf, display = display.none, tooltip = "Higher-timeframe candles on each side of the pivot. Right = confirmation delay: 2 = two H1 candles (2 hours) or two M15 candles (30 minutes).")
 
// ── Major / minor ──
grpStr  = "Major / minor"
majorAt = input.int(45, "Major from score", minval = 10, maxval = 90, group = grpStr, display = display.none, tooltip = "Each pool gets a 0–100 score from its level volume, source and age (weights below). Major levels tend to hold when price reaches them; minor ones tend to be run through.")
wVol    = input.int(40, "Weight: level volume", minval = 0, maxval = 100, group = grpStr, display = display.none, tooltip = "Full points at 1.6× the average tick volume, none at 0.8× or below.")
wSrc    = input.int(40, "Weight: source", minval = 0, maxval = 100, group = grpStr, display = display.none, tooltip = "Previous week 100% · previous day 85% · session high / low and H1 swing 70% · M15 swing 30% · chart swing or round number 0%.")
wAge    = input.int(20, "Weight: age", minval = 0, maxval = 100, group = grpStr, display = display.none)
ageFull = input.int(144, "Age for full points (bars)", minval = 12, maxval = 2000, group = grpStr, display = display.none, tooltip = "144 candles = 12 hours on M5.")
 
// ── Sweep detection ──
grpSw    = "Sweep detection"
minPen   = input.float(0.05, "Min penetration (× ATR)", minval = 0.0, maxval = 1.0, step = 0.01, group = grpSw, display = display.none, tooltip = "Price must trade at least this far beyond the pool. A smaller poke does not count and the pool stays live.")
maxPen   = input.float(1.0, "Max penetration (× ATR)", minval = 0.1, maxval = 5.0, step = 0.1, group = grpSw, display = display.none, tooltip = "A run further than this beyond the pool is a breakout, even if price later closes back.")
closeWin = input.int(1, "Close-back window (bars)", minval = 1, maxval = 3, group = grpSw, display = display.none, tooltip = "1: the candle itself must close back inside the pool. 2 or 3: a close beyond is allowed if price closes back within this many candles.")
 
// ── Zones & tags ──
grpVis     = "Zones & tags"
styleIn    = input.string("Zone", "Pool style", options = ["Zone", "Line"], group = grpVis, display = display.none, tooltip = "Zone: a shaded band from the wick tip to the candle body, with a thin line on the edge facing price. Line: a single line at the pool price.")
colBuy     = input.color(color.rgb(255, 167, 38), "Buy-side pool (above price)", group = grpVis, display = display.none)
colSell    = input.color(color.rgb(41, 182, 246), "Sell-side pool (below price)", group = grpVis, display = display.none)
majorTr    = input.int(55, "Major pool transparency", minval = 0, maxval = 95, group = grpVis, display = display.none)
freshTr    = input.int(72, "Minor pool transparency (fresh → old)", minval = 0, maxval = 98, inline = "mtr", group = grpVis, display = display.none)
oldTr      = input.int(92, "", minval = 0, maxval = 98, inline = "mtr", group = grpVis, display = display.none, tooltip = "Minor pools fade from the first value to the second as they age. Major pools keep their transparency.")
edgeLine   = input.bool(true, "Edge line", group = grpVis, display = display.none, tooltip = "Zone style: a thin line in the zone color on the edge facing price (bottom of buy-side, top of sell-side).")
maxZoneAtr = input.float(1.0, "Max zone height (× ATR)", minval = 0.1, maxval = 5.0, step = 0.1, group = grpVis, display = display.none)
nearestN   = input.int(3, "Pools shown per side (nearest)", minval = 1, maxval = 20, group = grpVis, display = display.none, tooltip = "The nearest pools above and below price are shown; the rest are tracked but hidden.")
showMajor  = input.bool(true, "Always show major pools", group = grpVis, display = display.none)
showNext   = input.bool(true, "Highlight next liquidity", group = grpVis, display = display.none, tooltip = "The nearest pool above and the nearest below get a thicker edge line and a ▲ / ▼ on their tag.")
showTags   = input.bool(true, "Show tags", group = grpVis, display = display.none)
tagText    = input.string("Price + volume", "Tag shows", options = ["Price + volume", "Price", "Type + price + volume"], group = grpVis, display = display.none, tooltip = "Placed on the zone edge facing price. The price is the liquidity level (the wick tip); volume is the level volume relative to average. Hover a tag for the full breakdown.")
tagSizeIn  = input.string("Small", "Tag size", options = ["Tiny", "Small", "Normal"], group = grpVis, display = display.none)
showSwept  = input.bool(true, "Show swept pools", group = grpVis, display = display.none, tooltip = "A swept pool stops at the sweep candle and is drawn very faint.")
showBroken = input.bool(false, "Show broken pools", group = grpVis, display = display.none)
retKeep    = input.int(5, "Swept / broken pools kept", minval = 0, maxval = 100, group = grpVis, display = display.none)
retTr      = input.int(90, "Swept / broken transparency", minval = 0, maxval = 98, group = grpVis, display = display.none)
 
// ── Sweep markers ──
grpMk      = "Sweep markers"
markerIn   = input.string("Diamond", "Marker", options = ["Diamond", "X-cross", "Triangle", "Flag", "Glow dot", "Custom glyph"], group = grpMk, display = display.none, tooltip = "Drawn on the sweep wick tip in the swept zone's color and shade. Hover a marker for the pool, level, volume and score.")
glyphIn    = input.string("✕", "Custom glyph", group = grpMk, display = display.none)
mkMajIn    = input.string("Small", "Size: major", options = ["Tiny", "Small", "Normal", "Large"], inline = "mks", group = grpMk, display = display.none)
mkMinIn    = input.string("Tiny", "minor", options = ["Tiny", "Small", "Normal", "Large"], inline = "mks", group = grpMk, display = display.none, tooltip = "Separate sizes for sweeps of major and minor pools. With Glow dot, the size sets the core and the rings scale from it.")
markMinor  = input.bool(true, "Mark sweeps of minor pools", group = grpMk, display = display.none)
sweepsKept = input.int(30, "Markers kept", minval = 1, maxval = 150, group = grpMk, display = display.none)
 
// ── Dashboard ──
grpDash  = "Dashboard"
showDash = input.bool(true, "Show dashboard", group = grpDash, display = display.none)
dashMode = input.string("Full", "Mode", options = ["Full", "Compact"], group = grpDash, display = display.none, tooltip = "Compact: the next liquidity above and below. Full: adds the nearest major levels, the last sweep and the session.")
dashPos  = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grpDash, display = display.none)
dashSize = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = grpDash, display = display.none)
 
// ── Alerts ──
grpAl     = "Alerts"
alSweep   = input.bool(true, "Pool swept", inline = "al1", group = grpAl, display = display.none)
alBreak   = input.bool(true, "Pool broken", inline = "al1", group = grpAl, display = display.none, tooltip = "Swept: traded through and closed back. Broken: closed through and away.")
alNear    = input.bool(true, "Price near a major pool", inline = "al2", group = grpAl, display = display.none)
nearAtr   = input.float(0.5, "within (× ATR)", minval = 0.1, maxval = 3.0, step = 0.1, inline = "al2", group = grpAl, display = display.none, tooltip = "Once per approach: it re-arms after price moves more than twice this distance away.")
alMinor   = input.bool(false, "Include minor pools (swept / broken)", group = grpAl, display = display.none, tooltip = "Off: only major pools raise swept and broken alerts.")
alNewLvl  = input.bool(false, "New day / week levels", group = grpAl, display = display.none, tooltip = "At the start of each trading day (and week): the new previous-day (and previous-week) high and low.")
alFormat  = input.string("Text", "Payload format", options = ["Text", "JSON"], group = grpAl, display = display.none, tooltip = "Create one alert with the condition 'Any alert() function call' to receive these. JSON is for webhooks and bots.")
 
bool zoneMode = styleIn == "Zone"
 
// ============================================================================
// 2. GLOBAL SERIES — every ta.* call lives here, evaluated on every bar
// ============================================================================
 
float atr = ta.atr(atrLen)
float ph  = ta.pivothigh(high, swL, swR)
float pl  = ta.pivotlow(low, swL, swR)
 
float pivBodyHi = math.max(open[swR], close[swR])
float pivBodyLo = math.min(open[swR], close[swR])
float bodyHi    = math.max(open, close)
float bodyLo    = math.min(open, close)
 
// Relative tick volume: this candle's volume ÷ its 100-bar average (1.0 when the symbol has no volume)
float volSma  = ta.sma(volume, 100)
bool  hasVol  = ta.cum(nz(volume)) > 0
float rv      = hasVol and nz(volSma) > 0 ? volume / volSma : 1.0
float pivRv   = rv[swR]
 
// ---- Higher-timeframe pivots (M15, H1): values of the last CLOSED higher-timeframe candle only ----
// [1] with lookahead_on = the previous, completed HTF bar, so nothing repaints.
htfPiv() =>
    float hp  = ta.pivothigh(high, htfL, htfR)
    float lp  = ta.pivotlow(low, htfL, htfR)
    float vs  = ta.sma(volume, 100)
    float rvH = nz(vs) > 0 ? volume / vs : 1.0
    int   k   = htfR + 1
    [hp[1], lp[1], time[k], math.max(open[k], close[k]), math.min(open[k], close[k]), rvH[k]]
 
int  tfSecChart = timeframe.in_seconds()
bool m15On = useM15 and tfSecChart < 900
bool h1On  = useH1 and tfSecChart < 3600
[m15Hp, m15Lp, m15T, m15BHi, m15BLo, m15Rv] = request.security(syminfo.tickerid, m15On ? "15" : timeframe.period, htfPiv(), lookahead = barmerge.lookahead_on)
[h1Hp, h1Lp, h1T, h1BHi, h1BLo, h1Rv]       = request.security(syminfo.tickerid, h1On ? "60" : timeframe.period, htfPiv(), lookahead = barmerge.lookahead_on)
bool m15New = m15On and timeframe.change("15")
bool h1New  = h1On and timeframe.change("60")
 
// ============================================================================
// 3. MARKET & SESSIONS (ported from PT Smart Patterns, section 4)
// ============================================================================
 
bool isGoldSym = syminfo.basecurrency == "XAU" or str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "GOLD")
 
TZ_TOKYO   = "Asia/Tokyo"
TZ_LONDON  = "Europe/London"
TZ_NY      = "America/New_York"
SES_TOKYO  = "0900-1800"
SES_LONDON = "0800-1700"
SES_ROLL   = "1645-1815"
string sesNY = isGoldSym ? "0900-1700" : "0830-1700"
 
bool inTokyo    = not na(time(timeframe.period, SES_TOKYO, TZ_TOKYO))
bool inLondon   = not na(time(timeframe.period, SES_LONDON, TZ_LONDON))
bool inNewYork  = not na(time(timeframe.period, sesNY, TZ_NY))
bool inRollover = not na(time(timeframe.period, SES_ROLL, TZ_NY))
 
string sessTag = ""
if inTokyo
    sessTag := "Tokyo"
if inLondon
    sessTag := sessTag == "" ? "London" : sessTag + "+London"
if inNewYork
    sessTag := sessTag == "" ? "NY" : sessTag + "+NY"
if sessTag == ""
    sessTag := "Off-hours"
if inRollover
    sessTag := "Rollover"
 
bool newDay  = timeframe.change("1D") and bar_index > 0
bool newWeek = timeframe.change("1W") and bar_index > 0
 
// ============================================================================
// 4. TYPES
// ============================================================================
 
// side: 1 = buy-side (stops above a high), -1 = sell-side (stops below a low)
// price = the liquidity level (wick tip); inner = the zone edge facing price (candle body)
type Pool
    int    id
    int    side
    float  price
    float  inner
    string tags
    int    bornX              // bar where the level formed (zone start)
    int    createdX           // bar where the pool became known (age counts from here)
    int    endX
    int    brX                // close-back window: bar of the first close beyond (na = none pending)
    float  brExt
    float  vSum = 0.0         // level volume: sum of relative volumes of the making and testing candles
    int    vN = 0
    int    tests = 0
    bool   intest = false
    bool   nearSent = false   // "price near" alert already sent for this approach
    string state = "Live"
    line   ln
    line   el
    box    bx
    label  lb
 
type Sweep
    int    side               // side of the swept pool
    int    x
    float  y
    string tags
    float  level
    float  relVol
    int    score
    bool   major
    int    tr                 // marker transparency = the swept zone's edge-line shade at the sweep
    float  penAtr
    int    nPools
    array<label> mk
 
type Registry
    int          seq = 0
    int          nSwept = 0
    int          nSweptMajor = 0
    int          nBroken = 0
    array<Pool>  live
    array<Pool>  retired
    array<Sweep> sweeps
 
type SesTrack
    float hi
    float hiIn
    float hiV
    int   hiX
    float lo
    float loIn
    float loV
    int   loX
    bool  was = false
    bool  full = false
 
// ============================================================================
// 5. POOL SCORE & DRAWING
// ============================================================================
 
int TAG_OFF = 3
 
tagSize() =>
    tagSizeIn == "Tiny" ? size.tiny : tagSizeIn == "Normal" ? size.normal : size.small
 
// Marker size ladder: 0 tiny · 1 small · 2 normal · 3 large · 4+ huge
sizeIdx(string s) =>
    s == "Tiny" ? 0 : s == "Small" ? 1 : s == "Normal" ? 2 : 3
 
szAt(int k) =>
    k <= 0 ? size.tiny : k == 1 ? size.small : k == 2 ? size.normal : k == 3 ? size.large : size.huge
 
sideCol(int side) =>
    side == 1 ? colBuy : colSell
 
pxStr(float x) =>
    str.tostring(x, format.mintick)
 
addTag(string tags, string k) =>
    str.contains(tags, k) ? tags : tags + " · " + k
 
clamp01(float x) =>
    math.max(0.0, math.min(1.0, x))
 
clampInner(int side, float price, float inner) =>
    float res = inner
    if not na(atr) and not na(price)
        float th = na(inner) ? 0.1 * atr : math.abs(price - inner)
        th  := math.max(0.05 * atr, math.min(maxZoneAtr * atr, th))
        res := price - side * th
    res
 
method isHtf(Pool p) =>
    str.contains(p.tags, "PW") or str.contains(p.tags, "PD") or str.contains(p.tags, "TKY") or str.contains(p.tags, "LDN") or str.contains(p.tags, "NY") or str.contains(p.tags, "H1") or str.contains(p.tags, "M15")
 
method relVol(Pool p) =>
    p.vN > 0 ? p.vSum / p.vN : 1.0
 
method srcPct(Pool p) =>
    str.contains(p.tags, "PW") ? 1.0 : str.contains(p.tags, "PD") ? 0.85 : str.contains(p.tags, "TKY") or str.contains(p.tags, "LDN") or str.contains(p.tags, "NY") or str.contains(p.tags, "H1") ? 0.7 : str.contains(p.tags, "M15") ? 0.3 : 0.0
 
method volPts(Pool p) =>
    hasVol ? wVol * clamp01((p.relVol() - 0.8) / 0.8) : wVol * 0.5
 
method srcPts(Pool p) =>
    wSrc * p.srcPct()
 
method agePts(Pool p) =>
    wAge * clamp01((bar_index - p.createdX) / float(ageFull))
 
// Strength score 0–100 (scaled to the weights' total)
method score(Pool p) =>
    float wSum = math.max(wVol + wSrc + wAge, 1)
    int(math.round(100.0 * (p.volPts() + p.srcPts() + p.agePts()) / wSum))
 
method isMajor(Pool p) =>
    p.score() >= majorAt
 
method zTop(Pool p) =>
    p.side == 1 ? p.price : p.inner
 
method zBot(Pool p) =>
    p.side == 1 ? p.inner : p.price
 
// Transparency: major pools fixed; minor pools fade with age over the swing max age
method shadeTr(Pool p) =>
    if p.isMajor()
        majorTr
    else
        float f = clamp01((bar_index - p.createdX) / float(maxAge))
        int(math.round(freshTr + (oldTr - freshTr) * f))
 
volStr(float v) =>
    hasVol ? str.tostring(v, "0.0") + "×" : "n/a"
 
method tipText(Pool p) =>
    float wSum = math.max(wVol + wSrc + wAge, 1)
    (p.side == 1 ? "Buy-side liquidity (stops above)" : "Sell-side liquidity (stops below)") + "\n" + p.tags + "\nLevel " + pxStr(p.price) + " · zone to " + pxStr(p.inner) + "\n" + (p.isMajor() ? "MAJOR — more likely to hold" : "Minor — more likely to be run through") + "\nScore " + str.tostring(p.score()) + " (volume " + str.tostring(math.round(100 * p.volPts() / wSum)) + " · source " + str.tostring(math.round(100 * p.srcPts() / wSum)) + " · age " + str.tostring(math.round(100 * p.agePts() / wSum)) + ")\nLevel volume " + volStr(p.relVol()) + " average · tested " + str.tostring(p.tests) + "×"
 
method drawPool(Pool p) =>
    color c  = sideCol(p.side)
    int   tr = p.shadeTr()
    int   x2 = bar_index + TAG_OFF
    if zoneMode
        p.bx := box.new(p.bornX, p.zTop(), x2, p.zBot(), border_color = color.new(color.black, 100), border_width = 0, bgcolor = color.new(c, tr))
        if edgeLine
            p.el := line.new(p.bornX, p.inner, x2, p.inner, color = color.new(c, math.max(0, tr - 40)), width = 1)
    else
        p.ln := line.new(p.bornX, p.price, x2, p.price, color = color.new(c, math.max(0, tr - 50)), width = 1)
    p
 
method redraw(Pool p) =>
    if not na(p.bx)
        p.bx.set_left(p.bornX)
        p.bx.set_top(p.zTop())
        p.bx.set_bottom(p.zBot())
    if not na(p.el)
        p.el.set_x1(p.bornX)
        p.el.set_y1(p.inner)
        p.el.set_y2(p.inner)
    if not na(p.ln)
        p.ln.set_x1(p.bornX)
        p.ln.set_y1(p.price)
        p.ln.set_y2(p.price)
    p
 
method killPool(Pool p) =>
    line.delete(p.ln)
    line.delete(p.el)
    box.delete(p.bx)
    label.delete(p.lb)
    p
 
// Display on the last bar. vis: shown at all · nxt: next target above / below
method show(Pool p, bool vis, bool nxt) =>
    color c   = sideCol(p.side)
    int   x2  = bar_index + TAG_OFF
    bool  maj = p.isMajor()
    int   tr  = vis ? p.shadeTr() : 100
    if not na(p.bx)
        p.bx.set_right(x2)
        p.bx.set_bgcolor(color.new(c, tr))
    if not na(p.el)
        p.el.set_x2(x2)
        p.el.set_color(color.new(c, vis ? (nxt ? 0 : math.max(0, tr - 40)) : 100))
        p.el.set_width(vis and (nxt or maj) ? 2 : 1)
    if not na(p.ln)
        p.ln.set_x2(x2)
        p.ln.set_color(color.new(c, vis ? (nxt ? 0 : math.max(0, tr - 50)) : 100))
        p.ln.set_width(vis and (nxt or maj) ? 2 : 1)
    if vis and showTags
        float  ty  = zoneMode ? p.inner : p.price
        string vs  = hasVol ? " · " + volStr(p.relVol()) : ""
        string txt = (nxt ? (p.side == 1 ? "▲ " : "▼ ") : "") + (tagText == "Type + price + volume" ? p.tags + " " : "") + pxStr(p.price) + (tagText == "Price" ? "" : vs)
        color  tc  = color.new(c, maj or nxt ? 0 : 35)
        if na(p.lb)
            p.lb := label.new(x2, ty, txt, style = label.style_label_left, color = color.new(color.black, 100), textcolor = tc, size = tagSize(), tooltip = p.tipText())
        else
            p.lb.set_xy(x2, ty)
            p.lb.set_text(txt)
            p.lb.set_textcolor(tc)
            p.lb.set_tooltip(p.tipText())
    else if not na(p.lb)
        p.lb.delete()
        p.lb := na
    p
 
// ============================================================================
// 6. SWEEP MARKERS
// ============================================================================
 
markerStyle(int side) =>
    markerIn == "X-cross" ? label.style_xcross : markerIn == "Diamond" ? label.style_diamond : markerIn == "Triangle" ? (side == 1 ? label.style_triangledown : label.style_triangleup) : markerIn == "Flag" ? label.style_flag : label.style_none
 
method sweepTip(Sweep s) =>
    (s.side == 1 ? "Buy-side liquidity swept (stops above taken)" : "Sell-side liquidity swept (stops below taken)") + "\n" + s.tags + " " + pxStr(s.level) + (s.nPools > 1 ? " (+" + str.tostring(s.nPools - 1) + " more)" : "") + "\n" + (s.major ? "MAJOR" : "Minor") + " · score " + str.tostring(s.score) + " · level volume " + volStr(s.relVol) + "\nWick " + pxStr(s.y) + " · " + str.tostring(s.penAtr, "0.00") + " ATR beyond · closed back inside"
 
method drawMark(Sweep s) =>
    color  c   = sideCol(s.side)
    string tip = s.sweepTip()
    int   k  = sizeIdx(s.major ? mkMajIn : mkMinIn)
    color cc = color.new(c, s.tr)
    if markerIn == "Glow dot"
        // Two faint rings around a core in the zone's shade, all scaled from the size
        s.mk.push(label.new(s.x, s.y, "", style = label.style_circle, color = color.new(c, math.min(95, s.tr + 45)), size = szAt(k + 2), tooltip = tip))
        s.mk.push(label.new(s.x, s.y, "", style = label.style_circle, color = color.new(c, math.min(90, s.tr + 25)), size = szAt(k + 1), tooltip = tip))
        s.mk.push(label.new(s.x, s.y, "", style = label.style_circle, color = cc, size = szAt(k), tooltip = tip))
    else
        s.mk.push(label.new(s.x, s.y, markerIn == "Custom glyph" ? glyphIn : "", style = markerStyle(s.side), color = cc, textcolor = cc, size = szAt(k), tooltip = tip))
    s
 
method killMark(Sweep s) =>
    for lb in s.mk
        lb.delete()
    s.mk.clear()
    s
 
// ============================================================================
// 7. REGISTRY
// ============================================================================
 
// Add a pool, or merge it into a live pool on the same side within the equal-level tolerance.
// The merged pool keeps the outermost level, widens its zone and pools the level volume.
method addPool(Registry r, int side, float price, float innerIn, string kind, int bornX, float v0) =>
    float tol   = eqTol * atr
    Pool  best  = na
    float bestD = na
    if not na(tol) and not na(price)
        for q in r.live
            if q.side == side and na(q.brX)
                float dd = math.abs(q.price - price)
                if dd <= tol and (na(bestD) or dd < bestD)
                    best  := q
                    bestD := dd
    if not na(best)
        string eqName = side == 1 ? "EQH" : "EQL"
        if kind == "SWING" and str.contains(best.tags, "SWING")
            best.tags := str.replace_all(best.tags, "SWING", eqName)
        else if not (kind == "SWING" and str.contains(best.tags, eqName))
            best.tags := addTag(best.tags, kind)
        float newInner = clampInner(side, price, innerIn)
        best.price := side == 1 ? math.max(best.price, price) : math.min(best.price, price)
        best.inner := clampInner(side, best.price, side == 1 ? math.min(best.inner, newInner) : math.max(best.inner, newInner))
        best.bornX := math.min(best.bornX, bornX)
        if not na(v0)
            best.vSum += v0
            best.vN   += 1
        best.redraw()
    else if not na(price)
        r.seq := r.seq + 1
        Pool p = Pool.new(id = r.seq, side = side, price = price, inner = clampInner(side, price, innerIn), tags = kind, bornX = bornX, createdX = bar_index, vSum = nz(v0, 1.0), vN = 1)
        p.drawPool()
        r.live.push(p)
        // Cap per side: drop the lowest score, oldest first among equals
        int nSide = 0
        for q in r.live
            if q.side == side
                nSide += 1
        if nSide > maxPerSide
            int wi = -1
            int ws = 0
            for i = 0 to r.live.size() - 1
                Pool q = r.live.get(i)
                if q.side == side and q.id != p.id and na(q.brX)
                    int sc = q.score()
                    if wi < 0 or sc < ws or (sc == ws and q.createdX < r.live.get(wi).createdX)
                        wi := i
                        ws := sc
            if wi >= 0
                r.live.get(wi).killPool()
                r.live.remove(wi)
    r
 
// Retire a pool as "Swept" or "Broken": it stops at this bar and is drawn very faint, or removed.
method retire(Registry r, Pool p, int idx, string st) =>
    p.state := st
    p.endX  := bar_index
    r.live.remove(idx)
    if st == "Broken"
        r.nBroken := r.nBroken + 1
    bool keep = retKeep > 0 and ((st == "Swept" and showSwept) or (st == "Broken" and showBroken))
    if keep
        color c = color.new(sideCol(p.side), retTr)
        if not na(p.bx)
            p.bx.set_right(bar_index)
            p.bx.set_bgcolor(c)
        if not na(p.el)
            p.el.set_x2(bar_index)
            p.el.set_color(c)
            p.el.set_width(1)
        if not na(p.ln)
            p.ln.set_x2(bar_index)
            p.ln.set_style(line.style_dotted)
            p.ln.set_color(c)
        label.delete(p.lb)
        p.lb := na
        r.retired.push(p)
        while r.retired.size() > retKeep
            r.retired.shift().killPool()
    else
        p.killPool()
    r
 
method addSweep(Registry r, Pool rp, int nPools, float ext) =>
    int  sc  = rp.score()
    bool maj = sc >= majorAt
    r.nSwept := r.nSwept + 1
    if maj
        r.nSweptMajor := r.nSweptMajor + 1
    if maj or markMinor
        Sweep s = Sweep.new(side = rp.side, x = bar_index, y = ext, tags = rp.tags, level = rp.price, relVol = rp.relVol(), score = sc, major = maj, tr = math.max(0, rp.shadeTr() - 40), penAtr = math.abs(ext - rp.price) / atr, nPools = nPools, mk = array.new<label>())
        s.drawMark()
        r.sweeps.push(s)
        while r.sweeps.size() > sweepsKept
            r.sweeps.shift().killMark()
    r
 
// Session range tracking: called once per bar for each session
method step(SesTrack s, Registry r, bool inNow, bool enabled, string hName, string lName) =>
    if inNow
        if not s.was or na(s.hi)
            s.hi   := high
            s.hiIn := bodyHi
            s.hiV  := rv
            s.hiX  := bar_index
            s.lo   := low
            s.loIn := bodyLo
            s.loV  := rv
            s.loX  := bar_index
            s.full := bar_index > 0 and not s.was
        else
            if high > s.hi
                s.hi   := high
                s.hiIn := bodyHi
                s.hiV  := rv
                s.hiX  := bar_index
            if low < s.lo
                s.lo   := low
                s.loIn := bodyLo
                s.loV  := rv
                s.loX  := bar_index
    else if s.was
        if enabled and s.full and not na(s.hi)
            r.addPool(1, s.hi, s.hiIn, hName, s.hiX, s.hiV)
            r.addPool(-1, s.lo, s.loIn, lName, s.loX, s.loV)
        s.hi   := na
        s.lo   := na
        s.full := false
    s.was := inNow
    s
 
// ============================================================================
// 8. POOL SOURCES — new pools are added first, then this bar's tests and sweeps are checked
// ============================================================================
 
// ============================================================================
// 7b. ALERTS — queued during the bar, sent at the end of the script
// ============================================================================
 
array<string> alertQ = array.new<string>()
bool majSweptNow  = false
bool majBrokenNow = false
bool majNearNow   = false
 
sideWord(int side) =>
    side == 1 ? "buy-side" : "sell-side"
 
alertMsg(string ev, Pool p, float wick) =>
    string out = ""
    if alFormat == "JSON"
        out := '{"event":"' + ev + '","side":"' + (p.side == 1 ? "buy" : "sell") + '","class":"' + (p.isMajor() ? "major" : "minor") + '","tags":"' + p.tags + '","level":' + pxStr(p.price) + ',"wick":' + (na(wick) ? "null" : pxStr(wick)) + ',"volume":' + (hasVol ? str.tostring(p.relVol(), "0.00") : "null") + ',"score":' + str.tostring(p.score()) + ',"close":' + pxStr(close) + ',"symbol":"' + syminfo.tickerid + '","tf":"' + timeframe.period + '","bar_time":' + str.tostring(time) + '}'
    else
        string head = ev == "sweep" ? "swept" : ev == "break" ? "broken" : ev == "near" ? "price near" : ev
        out := "PT Liquidity · " + (p.isMajor() ? "MAJOR " : "minor ") + sideWord(p.side) + " " + head + " · " + p.tags + " " + pxStr(p.price) + (hasVol ? " · vol " + volStr(p.relVol()) : "") + " · score " + str.tostring(p.score()) + (na(wick) ? "" : " · wick " + pxStr(wick)) + " · " + syminfo.ticker + " " + timeframe.period
    out
 
var Registry reg = Registry.new(live = array.new<Pool>(), retired = array.new<Pool>(), sweeps = array.new<Sweep>())
 
// ---- Previous week high / low (the first, partial week is skipped) ----
var float wHi   = na
var float wHiIn = na
var float wHiV  = na
var int   wHiX  = na
var float wLo   = na
var float wLoIn = na
var float wLoV  = na
var int   wLoX  = na
var int   weekCount = 0
if newWeek
    weekCount += 1
    if usePW and timeframe.isintraday and weekCount >= 2 and not na(wHi)
        reg.addPool(1, wHi, wHiIn, "PWH", wHiX, wHiV)
        reg.addPool(-1, wLo, wLoIn, "PWL", wLoX, wLoV)
        if alNewLvl
            alertQ.push(alFormat == "JSON" ? '{"event":"new_week","pwh":' + pxStr(wHi) + ',"pwl":' + pxStr(wLo) + ',"symbol":"' + syminfo.tickerid + '","bar_time":' + str.tostring(time) + '}' : "PT Liquidity · new week · PWH " + pxStr(wHi) + " · PWL " + pxStr(wLo) + " · " + syminfo.ticker)
if newWeek or na(wHi)
    wHi   := high
    wHiIn := bodyHi
    wHiV  := rv
    wHiX  := bar_index
    wLo   := low
    wLoIn := bodyLo
    wLoV  := rv
    wLoX  := bar_index
else
    if high > wHi
        wHi   := high
        wHiIn := bodyHi
        wHiV  := rv
        wHiX  := bar_index
    if low < wLo
        wLo   := low
        wLoIn := bodyLo
        wLoV  := rv
        wLoX  := bar_index
 
// ---- Previous day high / low (the first, partial day is skipped) ----
var float dHi   = na
var float dHiIn = na
var float dHiV  = na
var int   dHiX  = na
var float dLo   = na
var float dLoIn = na
var float dLoV  = na
var int   dLoX  = na
var int   dayCount = 0
if newDay
    dayCount += 1
    if usePD and timeframe.isintraday and dayCount >= 2 and not na(dHi)
        reg.addPool(1, dHi, dHiIn, "PDH", dHiX, dHiV)
        reg.addPool(-1, dLo, dLoIn, "PDL", dLoX, dLoV)
        if alNewLvl
            alertQ.push(alFormat == "JSON" ? '{"event":"new_day","pdh":' + pxStr(dHi) + ',"pdl":' + pxStr(dLo) + ',"symbol":"' + syminfo.tickerid + '","bar_time":' + str.tostring(time) + '}' : "PT Liquidity · new day · PDH " + pxStr(dHi) + " · PDL " + pxStr(dLo) + " · " + syminfo.ticker)
if newDay or na(dHi)
    dHi   := high
    dHiIn := bodyHi
    dHiV  := rv
    dHiX  := bar_index
    dLo   := low
    dLoIn := bodyLo
    dLoV  := rv
    dLoX  := bar_index
else
    if high > dHi
        dHi   := high
        dHiIn := bodyHi
        dHiV  := rv
        dHiX  := bar_index
    if low < dLo
        dLo   := low
        dLoIn := bodyLo
        dLoV  := rv
        dLoX  := bar_index
 
// ---- Session ranges ----
var SesTrack sTky = SesTrack.new()
var SesTrack sLdn = SesTrack.new()
var SesTrack sNy  = SesTrack.new()
bool intra = timeframe.isintraday
sTky.step(reg, inTokyo, useTky and intra, "TKY H", "TKY L")
sLdn.step(reg, inLondon, useLdn and intra, "LDN H", "LDN L")
sNy.step(reg, inNewYork, useNy and intra, "NY H", "NY L")
 
// ---- Swing highs / lows (equal ones merge into EQH / EQL); zone = wick tip to body ----
if not na(ph)
    reg.addPool(1, ph, pivBodyHi, "SWING", bar_index - swR, pivRv)
if not na(pl)
    reg.addPool(-1, pl, pivBodyLo, "SWING", bar_index - swR, pivRv)
 
// ---- M15 / H1 swing pools: added on the first chart bar after the confirming HTF candle closes ----
// The zone starts at the HTF pivot candle (bar position estimated from its open time).
htfBorn(int t) =>
    int back = int(math.round((time - t) / (tfSecChart * 1000.0)))
    bar_index - math.max(0, math.min(back, 4900))
 
if m15New
    if not na(m15Hp)
        reg.addPool(1, m15Hp, m15BHi, "M15", htfBorn(m15T), nz(m15Rv, 1.0))
    if not na(m15Lp)
        reg.addPool(-1, m15Lp, m15BLo, "M15", htfBorn(m15T), nz(m15Rv, 1.0))
if h1New
    if not na(h1Hp)
        reg.addPool(1, h1Hp, h1BHi, "H1", htfBorn(h1T), nz(h1Rv, 1.0))
    if not na(h1Lp)
        reg.addPool(-1, h1Lp, h1BLo, "H1", htfBorn(h1T), nz(h1Rv, 1.0))
 
// ---- Round numbers: nearest step strictly above the high and strictly below the low ----
if useRN and rnStep > 0
    float rnUp  = (math.floor(high / rnStep) + 1) * rnStep
    float rnDn  = (math.ceil(low / rnStep) - 1) * rnStep
    float rnTol = math.max(nz(eqTol * atr), syminfo.mintick)
    bool  hasUp = false
    bool  hasDn = false
    for q in reg.live
        if str.contains(q.tags, "RN")
            if q.side == 1 and math.abs(q.price - rnUp) <= rnTol
                hasUp := true
            if q.side == -1 and math.abs(q.price - rnDn) <= rnTol
                hasDn := true
    if not hasUp
        reg.addPool(1, rnUp, na, "RN", bar_index, na)
    if not hasDn
        reg.addPool(-1, rnDn, na, "RN", bar_index, na)
 
// ============================================================================
// 9. TESTS, SWEEPS, BREAKOUTS, EXPIRY — closed bars only, so nothing repaints
// ============================================================================
 
if barstate.isconfirmed and not na(atr)
    float pMin = minPen * atr
    float pMax = maxPen * atr
    Pool  refB = na
    Pool  refS = na
    int   nB   = 0
    int   nS   = 0
    float extB = high
    float extS = low
    if reg.live.size() > 0
        for i = reg.live.size() - 1 to 0
            Pool  p    = reg.live.get(i)
            float ext  = p.side == 1 ? math.max(high, nz(p.brExt, high)) : math.min(low, nz(p.brExt, low))
            float pen  = p.side * (ext - p.price)
            bool  back = p.side == 1 ? close <= p.price : close >= p.price
            if na(p.brX) and pen < pMin
                // Not taken: a candle reaching within 0.15 ATR of the level is a test; its volume joins the level volume
                bool near = bar_index > p.createdX and (p.side == 1 ? high >= p.price - 0.15 * atr : low <= p.price + 0.15 * atr)
                if near and not p.intest
                    p.tests += 1
                    p.vSum  += rv
                    p.vN    += 1
                p.intest := near
                // "Price near a major pool": once per approach, re-armed after moving 2× the distance away
                float dAtr = p.side * (p.price - close) / atr
                if p.isMajor() and dAtr <= nearAtr and not p.nearSent
                    p.nearSent := true
                    majNearNow := true
                    if alNear
                        alertQ.push(alertMsg("near", p, na))
                else if dAtr > 2 * nearAtr
                    p.nearSent := false
                // Expiry: swings and round numbers by the swing max age, week / day / session levels by their own
                if bar_index - p.createdX > (p.isHtf() ? maxAgeHtf : maxAge)
                    p.killPool()
                    reg.live.remove(i)
            else if pen > pMax
                if p.isMajor()
                    majBrokenNow := true
                if alBreak and (p.isMajor() or alMinor)
                    alertQ.push(alertMsg("break", p, ext))
                reg.retire(p, i, "Broken")
            else if back
                if p.side == 1
                    nB   += 1
                    extB := math.max(extB, ext)
                    if na(refB) or p.score() > refB.score()
                        refB := p
                else
                    nS   += 1
                    extS := math.min(extS, ext)
                    if na(refS) or p.score() > refS.score()
                        refS := p
                reg.retire(p, i, "Swept")
            else
                if na(p.brX) and closeWin > 1
                    p.brX   := bar_index
                    p.brExt := ext
                else if not na(p.brX) and bar_index - p.brX < closeWin - 1
                    p.brExt := ext
                else
                    if p.isMajor()
                        majBrokenNow := true
                    if alBreak and (p.isMajor() or alMinor)
                        alertQ.push(alertMsg("break", p, ext))
                    reg.retire(p, i, "Broken")
    // One marker (and one alert) per side per candle, for the strongest pool it swept
    if not na(refB)
        reg.addSweep(refB, nB, extB)
        majSweptNow := majSweptNow or refB.isMajor()
        if alSweep and (refB.isMajor() or alMinor)
            alertQ.push(alertMsg("sweep", refB, extB))
    if not na(refS)
        reg.addSweep(refS, nS, extS)
        majSweptNow := majSweptNow or refS.isMajor()
        if alSweep and (refS.isMajor() or alMinor)
            alertQ.push(alertMsg("sweep", refS, extS))
 
// ============================================================================
// 10. DISPLAY (last bar): nearest N per side + major pools; next target above and below
// ============================================================================
 
if barstate.islast
    int  n     = reg.live.size()
    Pool nxtUp = na
    Pool nxtDn = na
    for p in reg.live
        if na(p.brX)
            if p.side == 1 and (na(nxtUp) or p.price < nxtUp.price)
                nxtUp := p
            if p.side == -1 and (na(nxtDn) or p.price > nxtDn.price)
                nxtDn := p
    if n > 0
        for i = 0 to n - 1
            Pool p      = reg.live.get(i)
            int  nearer = 0
            for j = 0 to n - 1
                if j != i
                    Pool q = reg.live.get(j)
                    if q.side == p.side and math.abs(q.price - close) < math.abs(p.price - close)
                        nearer += 1
            bool nxt = showNext and ((not na(nxtUp) and p.id == nxtUp.id) or (not na(nxtDn) and p.id == nxtDn.id))
            p.show(nearer < nearestN or (showMajor and p.isMajor()), nxt)
 
// ============================================================================
// 11. DASHBOARD — drawn once, on the last bar
// ============================================================================
 
string dPosStr = dashPos == "Top left" ? position.top_left : dashPos == "Bottom right" ? position.bottom_right : dashPos == "Bottom left" ? position.bottom_left : position.top_right
string dSize   = dashSize == "Tiny" ? size.tiny : dashSize == "Normal" ? size.normal : size.small
color  D_TXT   = color.rgb(225, 225, 225)
color  D_MUTED = color.rgb(150, 150, 150)
color  D_BG    = color.new(color.rgb(19, 23, 34), 8)
color  D_HEAD  = color.new(color.rgb(42, 46, 57), 0)
 
var table dash = table.new(dPosStr, 5, 12, bgcolor = D_BG, border_color = color.new(color.gray, 75), border_width = 1)
 
dCell(table t, int c, int r, string txt, color tc, color bg) =>
    t.cell(c, r, txt, text_color = tc, bgcolor = bg, text_size = dSize, text_halign = c == 0 ? text.align_left : text.align_right)
 
// One pool row: name | level | distance (ATR) | class + score | level volume
dPoolRow(table t, int r, string name, Pool p) =>
    color c = na(p) ? D_MUTED : sideCol(p.side)
    dCell(t, 0, r, name, c, D_BG)
    if na(p)
        dCell(t, 1, r, "none", D_MUTED, D_BG)
        for k = 2 to 4
            dCell(t, k, r, "", D_MUTED, D_BG)
    else
        bool maj = p.isMajor()
        dCell(t, 1, r, p.tags + " " + pxStr(p.price), D_TXT, D_BG)
        dCell(t, 2, r, str.tostring(math.abs(p.price - close) / atr, "0.0"), D_TXT, D_BG)
        dCell(t, 3, r, (maj ? "MAJOR " : "minor ") + str.tostring(p.score()), maj ? c : D_MUTED, D_BG)
        dCell(t, 4, r, hasVol ? volStr(p.relVol()) : "–", D_TXT, D_BG)
 
if showDash and barstate.islast and not na(atr)
    dash.clear(0, 0, 4, 11)
    Pool upN = na
    Pool dnN = na
    Pool upM = na
    Pool dnM = na
    for p in reg.live
        if p.side == 1
            if na(upN) or p.price < upN.price
                upN := p
            if p.isMajor() and (na(upM) or p.price < upM.price)
                upM := p
        else
            if na(dnN) or p.price > dnN.price
                dnN := p
            if p.isMajor() and (na(dnM) or p.price > dnM.price)
                dnM := p
    int row = 0
    dCell(dash, 0, row, "PT Liquidity Sweep V26.01", D_TXT, D_HEAD)
    dCell(dash, 1, row, "Level", D_MUTED, D_HEAD)
    dCell(dash, 2, row, "ATR", D_MUTED, D_HEAD)
    dCell(dash, 3, row, "Class", D_MUTED, D_HEAD)
    dCell(dash, 4, row, "Vol", D_MUTED, D_HEAD)
    row += 1
    dPoolRow(dash, row, "▲ Next above", upN)
    row += 1
    dPoolRow(dash, row, "▼ Next below", dnN)
    row += 1
    if dashMode == "Full"
        // Nearest major levels, only when they are not already the next pool
        if not na(upM) and (na(upN) or upM.id != upN.id)
            dPoolRow(dash, row, "▲ Major above", upM)
            row += 1
        if not na(dnM) and (na(dnN) or dnM.id != dnN.id)
            dPoolRow(dash, row, "▼ Major below", dnM)
            row += 1
        Sweep last = reg.sweeps.size() > 0 ? reg.sweeps.last() : na
        dCell(dash, 0, row, "Last sweep", D_MUTED, D_BG)
        if na(last)
            dCell(dash, 1, row, "none", D_MUTED, D_BG)
            for k = 2 to 4
                dCell(dash, k, row, "", D_MUTED, D_BG)
        else
            color lc = sideCol(last.side)
            dCell(dash, 1, row, (last.side == 1 ? "▲ " : "▼ ") + last.tags + " " + pxStr(last.level), lc, D_BG)
            dCell(dash, 2, row, str.tostring(bar_index - last.x) + " bars ago", D_TXT, D_BG)
            dCell(dash, 3, row, last.major ? "MAJOR " + str.tostring(last.score) : "minor " + str.tostring(last.score), last.major ? lc : D_MUTED, D_BG)
            dCell(dash, 4, row, hasVol ? volStr(last.relVol) : "–", D_TXT, D_BG)
        row += 1
        dCell(dash, 0, row, "Session", D_MUTED, D_BG)
        dCell(dash, 1, row, sessTag, D_TXT, D_BG)
        dCell(dash, 2, row, "ATR " + pxStr(atr), D_MUTED, D_BG)
        dCell(dash, 3, row, "", D_MUTED, D_BG)
        dCell(dash, 4, row, syminfo.ticker + " " + timeframe.period, D_MUTED, D_BG)
 
// ============================================================================
// 12. ALERTS — use one alert with the condition "Any alert() function call"
// ============================================================================
 
if alertQ.size() > 0
    for m in alertQ
        alert(m, alert.freq_once_per_bar)
 
// Fixed-text alerts for the "Create alert" dialog (no setup of alert() needed)
alertcondition(majSweptNow, "Major pool swept", "PT Liquidity: major liquidity swept on {{ticker}} at {{close}}")
alertcondition(majBrokenNow, "Major pool broken", "PT Liquidity: major liquidity broken on {{ticker}} at {{close}}")
alertcondition(majNearNow, "Price near a major pool", "PT Liquidity: price near major liquidity on {{ticker}} at {{close}}")

← 返回列表