Eye Liquidity Sweep Map [EyeAlgo]

eyealgo · study · 740 行 · 点赞 117 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EyeAlgo
// Eye Liquidity Sweep Map — by Eye Algo (original code)
//  1. Liquidity pools: swing highs / lows, equal highs / lows (stops stacked at one level), previous day / week / month highs / lows and Asia · London · New York session highs / lows.
//  2. Sweep outcome scoreboard: every time a pool is taken, the script waits and records whether price REVERSED or RAN ON.
//     The dashboard shows each pool type's own measured reversal / run rate on this symbol.
//  3. Reach probability: every open pool shows the chance that price sweeps it within the next N bars, learned from this
//     symbol's own history by distance from price.
//  4. Sweep setup: a wick takes a pool and the candle closes back inside. Stop beyond the wick, target = nearest opposite
//     pool within Min–Max R, else 2R. Every setup is graded ⭐ / ⭐⭐ / ⭐⭐⭐ and tracked to its result.
 
//@version=6
indicator("Eye Liquidity Sweep Map [EyeAlgo]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════════════
//  SETTINGS
// ═══════════════════════════════════════════════════════════════════════════
GP = "💧 Liquidity Pools"
pL     = input.int(5, "Swing left bars", minval = 2, maxval = 30, group = GP, display = display.none)
pR     = input.int(5, "Swing right bars (confirmation)", minval = 1, maxval = 30, group = GP, display = display.none,
     tooltip = "A swing high / low becomes a liquidity pool only after this many bars have confirmed it, so pools never repaint.")
eqTol  = input.float(0.15, "Equal highs / lows tolerance (× 50-bar ATR)", minval = 0.02, step = 0.01, group = GP, display = display.none,
     tooltip = "Two pools on the same side closer than this are merged into one 'equal highs / lows' pool (stops stacked at one level). A merge with a previous-period or session level keeps that level's type.")
showPS = input.bool(true, "Use previous period high / low as pools", group = GP, display = display.none,
     tooltip = "Period = day on intraday charts, week on daily, month on weekly, year on monthly.")
showSes = input.bool(true, "Use Asia / London / New York session highs & lows as pools", group = GP, display = display.none, tooltip = "Intraday charts only. When a session ends, its high and low become liquidity pools. Times below are UTC. A session that crosses UTC midnight is split in two.")
asiaS = input.session("0000-0800", "Asia session (UTC)", group = GP, display = display.none)
lonS  = input.session("0700-1600", "London session (UTC)", group = GP, display = display.none)
nyS   = input.session("1300-2200", "New York session (UTC)", group = GP, display = display.none)
showPW = input.bool(true, "Use previous week high / low as pools (intraday)", group = GP, display = display.none)
showPool = input.bool(true, "Show liquidity pools", group = GP, display = display.none)
showFaint = input.bool(false, "Also show faint lines for the other pools", group = GP, display = display.none, tooltip = "Off = only the highlighted nearest pools are drawn, which keeps the chart clean. All pools still count in the statistics.")
showLad = input.bool(false, "Show liquidity ladder (where stops are stacked)", group = GP, display = display.none,
     tooltip = "A histogram right of the last candle: longer bar = more liquidity stacked at that price (equal highs / lows and previous-session levels count more, near pools with a high reach probability are brighter).")
maxP   = input.int(1, "Highlighted pools per side", minval = 1, maxval = 6, group = GP, display = display.none,
     tooltip = "The nearest N buy-side and N sell-side pools get a bright line, strength zone and label. Other pools are drawn faint only if 'Also show faint lines' is on.")
maxDist = input.float(8.0, "Hide pools further than (× ATR)", minval = 2.0, step = 1.0, group = GP, display = display.none,
     tooltip = "Pools further away than this many ATRs (50-bar ATR) are not drawn, so the price scale is not squeezed. They still count in the statistics.")
 
GW = "⚡ Sweeps & Outcomes"
showSw  = input.bool(true, "Show swept pools and their outcome", group = GW, display = display.none)
penMin  = input.float(0.05, "Minimum sweep depth (× ATR)", minval = 0.0, step = 0.01, group = GW, display = display.none,
     tooltip = "A sweep SETUP needs a wick at least this far beyond the pool and a close back inside. Depth is measured in 14-bar ATR. Any trade beyond a pool (even 1 tick) removes it and counts as 'taken' in the scoreboard and reach probability.")
outW    = input.int(12, "Outcome window (bars)", minval = 3, maxval = 50, group = GW, display = display.none,
     tooltip = "After a pool is taken, price has this many bars (the sweep bar included) to decide: REVERSED or RAN ON.")
revATR  = input.float(1.0, "Reversal / run distance (× ATR)", minval = 0.25, step = 0.25, group = GW, display = display.none,
     tooltip = "REVERSED = a close this many ATRs (14-bar ATR) back on the other side of the pool. RAN ON = a close this many ATRs beyond it. Neither inside the window = no decision (counts as neither).")
keepSw  = input.int(12, "Swept pools kept on chart", minval = 5, maxval = 150, group = GW, display = display.none,
     tooltip = "Swept-pool lines kept on the chart. The ✓ / ✗ labels are limited to the latest 10.")
 
GS = "🎯 Sweep Setups (experimental)"
showSig = input.bool(false, "Show sweep setups", group = GS, display = display.none,
     tooltip = "Experimental. Switching this off also stops setup tracking and the setup alerts. Sweep fades are not a proven edge — see the description.")
slBuf   = input.float(0.2, "Stop buffer (× ATR)", minval = 0.0, step = 0.05, group = GS, display = display.none,
     tooltip = "Setup stop = beyond the sweep wick plus this buffer.")
maxRisk = input.float(3.0, "Maximum stop distance (× ATR)", minval = 0.5, step = 0.5, group = GS, display = display.none,
     tooltip = "Setups whose stop would be wider than this are skipped (giant candles).")
minRR   = input.float(1.0, "Minimum reward : risk", minval = 0.5, step = 0.25, group = GS, display = display.none,
     tooltip = "The nearest opposite pool between Minimum and Maximum R is the target; if there is none, a fixed 2R target (kept inside Min / Max) is used.")
maxRR   = input.float(3.0, "Maximum reward : risk", minval = 1.0, step = 0.5, group = GS, display = display.none,
     tooltip = "Opposite pools further than this many R are not used as the target.")
maxBars = input.int(48, "Time exit after (bars)", minval = 5, maxval = 500, group = GS, display = display.none,
     tooltip = "If neither target nor stop is hit within this many bars, the setup is closed at the bar's close.")
strMin  = input.float(0.5, "⭐ Strong sweep needs (depth × volume)", minval = 0.1, step = 0.1, group = GS, display = display.none,
     tooltip = "Strength = sweep depth in ATR × volume versus its 50-bar average. A setup earns this star when strength reaches this value.")
revMin  = input.int(55, "⭐ Pool type reverses at least (%)", minval = 30, maxval = 95, group = GS, display = display.none,
     tooltip = "A setup earns this star when, on this symbol, this pool type reversed at least this often after being taken (any trade through it) (needs the minimum samples below).")
trendLen = input.int(100, "Trade with the trend only (EMA length, 0 = off)", minval = 0, maxval = 500, group = GS, display = display.none,
     tooltip = "Setups only trade in the direction of this EMA: longs above it, shorts below it. Counter-trend sweeps still count in the scoreboard and statistics.")
minBack = input.float(0.0, "Minimum close back inside (× ATR)", minval = 0.0, step = 0.05, group = GS, display = display.none,
     tooltip = "A sweep setup needs the candle to close at least this far back inside the pool.")
minRelV = input.float(0.0, "Quality filter: sweep candle volume ≥ (× 50-bar average, 0 = off)", minval = 0.0, step = 0.1, group = GS, display = display.none,
     tooltip = "A setup needs the sweep candle's volume to be at least this multiple of its 50-bar average. Needs volume data on the symbol.")
minWick = input.int(0, "Quality filter: rejection wick ≥ (% of candle range, 0 = off)", minval = 0, maxval = 95, group = GS, display = display.none,
     tooltip = "A setup needs the wick that took the pool (lower wick for a sell-side sweep, upper wick for a buy-side sweep) to be at least this share of the candle's full range.")
showEma = input.bool(true, "Show trend EMA line", group = GS, display = display.none, tooltip = "Draws the trend EMA (length above). Green when price is above it (uptrend), red when below (downtrend). Independent of the setups switch.")
showBox = input.bool(true, "Show TP / SL boxes", group = GS, display = display.none)
keepT   = input.int(60, "Setups kept on chart", minval = 1, maxval = 100, group = GS, display = display.none)
 
GN = "📈 Reach Probability"
reachWin = input.int(48, "Reach window (bars)", minval = 5, maxval = 300, group = GN, display = display.none,
     tooltip = "Each open pool shows the chance that price sweeps it within this many bars, measured on this symbol by its distance from price.")
minSamp  = input.int(15, "Min samples per bucket / pool type", minval = 5, maxval = 200, group = GN, display = display.none,
     tooltip = "A hit rate is shown only after this many finished samples, so tiny samples never look like facts.")
 
GC = "🎨 Colours"
bslC  = input.color(#F5B83D, "Buy-side liquidity (above)", inline = "c1", group = GC)
sslC  = input.color(#4DB8FF, "Sell-side liquidity (below)", inline = "c1", group = GC)
goodC = input.color(#26A69A, "Win", inline = "c2", group = GC)
badC  = input.color(#EF5350, "Loss", inline = "c2", group = GC)
hdrC  = input.color(#1E2433, "Header", inline = "c3", group = GC)
 
GT = "📋 Table & Alerts"
showTb = input.bool(true, "Show summary table", group = GT, display = display.none)
showFull = input.bool(false, "Show full statistics rows", group = GT, display = display.none, tooltip = "Adds the hit-rate-by-distance row, the four pool-type outcome rows and the open-pool count to the table.")
tbPos  = input.string("Top right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = GT, display = display.none)
detailAlerts = input.bool(true, "Detailed alert() messages", group = GT, display = display.none,
     tooltip = "Create the alert with 'Any alert() function call' to get entry, stop and target in the message.")
 
// ═══════════════════════════════════════════════════════════════════════════
//  COMMON
// ═══════════════════════════════════════════════════════════════════════════
const int MAXP = 60      // pools kept in memory
const int OFFB = 10      // gap between the last candle and the liquidity ladder
const int LADR = 40      // rows of the liquidity ladder
const int LADW = 12      // width of the liquidity ladder in bars
 
atr    = ta.atr(14)
atrL   = ta.atr(50)
trEma  = ta.ema(close, math.max(trendLen, 1))
avgVol = ta.sma(nz(volume) > 0 ? volume : 1.0, 50)
relV   = (nz(volume) > 0 ? volume : 1.0) / avgVol
sessTf   = timeframe.isintraday ? "D" : timeframe.isdaily ? "W" : timeframe.isweekly ? "M" : "12M"
newS = timeframe.change(sessTf)
newW = timeframe.change("W")
bool inAs = not na(time(timeframe.period, asiaS, "UTC"))
bool inLo = not na(time(timeframe.period, lonS, "UTC"))
bool inNy = not na(time(timeframe.period, nyS, "UTC"))
// dark-first design: panels and text are drawn dark on any chart theme, so they always read as one clean card
color dkBg = #131722
color dkTx = #D1D4DC
color dkMu = #8A93A6
rrLo = math.min(minRR, maxRR)
rrHi = math.max(minRR, maxRR)
px(float p) => str.tostring(p, format.mintick)
f_bk(float d) => d < 2.0 ? 0 : d < 4.0 ? 1 : d < 8.0 ? 2 : 3
f_stars(int n) => n >= 3 ? "⭐⭐⭐" : n == 2 ? "⭐⭐" : "⭐"
f_tyName(int ty, int sd) =>
    ty == 0 ? (sd == 1 ? "Swing high" : "Swing low") : ty == 1 ? (sd == 1 ? "Equal highs" : "Equal lows") : ty == 3 ? "Session " + (sd == 1 ? "high" : "low") : "Previous period " + (sd == 1 ? "high" : "low")
 
// add a pool, or merge it into a pool at (almost) the same price; returns true when a new pool was created
f_add(array<float> aPx, array<int> aSd, array<int> aTy, array<int> aBn, array<int> aLs, float price, int sd, int ty, int born, float tol) =>
    int k = -1
    if aPx.size() > 0
        for i = 0 to aPx.size() - 1
            if aSd.get(i) == sd and math.abs(aPx.get(i) - price) <= tol
                k := i
                break
    bool added = false
    if k >= 0
        aPx.set(k, sd == 1 ? math.max(aPx.get(k), price) : math.min(aPx.get(k), price))
        aTy.set(k, math.max(ty, aTy.get(k)) >= 2 ? math.max(ty, aTy.get(k)) : 1)
    else if not ((sd == 1 and high > price) or (sd == -1 and low < price))
        aPx.push(price)
        aSd.push(sd)
        aTy.push(ty)
        aBn.push(math.max(born, bar_index - 4900))
        aLs.push(bar_index - reachWin)
        added := true
    added
 
// ═══════════════════════════════════════════════════════════════════════════
//  STATE
// ═══════════════════════════════════════════════════════════════════════════
// open liquidity pools (side: 1 = buy-side above highs, -1 = sell-side below lows; type: 0 swing, 1 equal, 2 previous session)
var array<float> pPx = array.new<float>()
var array<int>   pSd = array.new<int>()
var array<int>   pTy = array.new<int>()
var array<int>   pBn = array.new<int>()
var array<int>   pLs = array.new<int>()
// reach-probability samples (one per pool every reach-window, so samples never overlap): distance bucket, start bar, level and side
var array<int>   smB  = array.new<int>()
var array<int>   smS  = array.new<int>()
var array<float> smP  = array.new<float>()   // level of the sampled pool
var array<int>   smD  = array.new<int>()     // its side
var array<bool>  smH  = array.new<bool>()    // already swept inside its window?
var array<float> smQ  = array.new<float>()    // the % this tool showed for that pool when it was sampled (na = not enough data yet)
var int   audN    = 0       // self-audit: sampled pools whose window has ended and that had a shown %
var float audSaid = 0.0     // sum of the % that was shown
var int   audHit  = 0       // how many were actually swept
var array<int>   bHit = array.new<int>(4, 0)
var array<int>   bTot = array.new<int>(4, 0)
// sweeps waiting for their outcome
var array<float> oPx = array.new<float>()
var array<float> oAt = array.new<float>()
var array<int>   oTy = array.new<int>()
var array<int>   oSd = array.new<int>()
var array<int>   oBn = array.new<int>()
var array<int>   oSt = array.new<int>()
var array<float> oMx = array.new<float>()      // deepest trade beyond the pool since the sweep
var array<float> hDp = array.new<float>()      // depth (in ATR) of every sweep that then reversed = stop-hunt depth
// outcome scoreboard per pool type
var array<int>   tN   = array.new<int>(4, 0)
var array<int>   tRev = array.new<int>(4, 0)
var array<int>   tRun = array.new<int>(4, 0)
var array<line>  swLn = array.new<line>()
var array<label> swLb = array.new<label>()
// previous session extremes
var float sHi  = na
var float sLo  = na
var int   sHiB = na
var int   sLoB = na
var float wHi  = na
var float wLo  = na
var int   wHiB = na
var int   wLoB = na
var array<float> ssH  = array.new<float>(3, na)
var array<float> ssL  = array.new<float>(3, na)
var array<int>   ssB  = array.new<int>(3, 0)
var array<bool>  ssIn = array.new<bool>(3, false)
var array<int>   ssD  = array.new<int>(3, -1)
 
f_prob(int b) => bTot.get(b) >= minSamp ? 100.0 * bHit.get(b) / bTot.get(b) : na
f_rev(int t) => tN.get(t) >= minSamp ? 100.0 * tRev.get(t) / tN.get(t) : na
 
// ═══════════════════════════════════════════════════════════════════════════
//  1. SWEEPS: a pool is taken when price trades through it
// ═══════════════════════════════════════════════════════════════════════════
swLong   = false        // sell-side pool swept by a wick that closed back above it
swShort  = false        // buy-side pool swept by a wick that closed back below it
int   cTyL  = 0
int   cTyS  = 0
float cPenL = 0.0
float cPenS = 0.0
float cPxL  = na
float cPxS  = na
 
if pPx.size() > 0
    for i = pPx.size() - 1 to 0
        float lvl = pPx.get(i)
        int   sd  = pSd.get(i)
        if (sd == 1 and high > lvl) or (sd == -1 and low < lvl)
            int   ty  = pTy.get(i)
            float pen = sd == 1 ? high - lvl : lvl - low
            if not na(atr)
                oPx.push(lvl)
                oAt.push(atr)
                oTy.push(ty)
                oSd.push(sd)
                oBn.push(pBn.get(i))
                oSt.push(bar_index)
                oMx.push(pen)
            // wick sweep: closed back inside and deep enough
            float backD = sd == 1 ? lvl - close : close - lvl
            if backD > 0 and not na(atr) and pen >= penMin * atr and backD >= minBack * atr
                if sd == 1
                    if not swShort or ty > cTyS or (ty == cTyS and pen > cPenS)
                        cTyS := ty
                        cPenS := pen
                        cPxS := lvl
                    swShort := true
                else
                    if not swLong or ty > cTyL or (ty == cTyL and pen > cPenL)
                        cTyL := ty
                        cPenL := pen
                        cPxL := lvl
                    swLong := true
            pPx.remove(i)
            pSd.remove(i)
            pTy.remove(i)
            pBn.remove(i)
            pLs.remove(i)
 
// outcome of every sweep: REVERSED, RAN ON, or no decision inside the window
bool outRev = false
bool outRun = false
if oPx.size() > 0 and barstate.isconfirmed
    for k = oPx.size() - 1 to 0
        float lv   = oPx.get(k)
        int   sd2  = oSd.get(k)
        float atP  = oAt.get(k)
        int   stB  = oSt.get(k)
        oMx.set(k, math.max(oMx.get(k), sd2 == 1 ? high - lv : lv - low))
        bool  isRev = sd2 == 1 ? close <= lv - revATR * atP : close >= lv + revATR * atP
        bool  isRun = sd2 == 1 ? close >= lv + revATR * atP : close <= lv - revATR * atP
        if isRev or isRun or bar_index - stB >= outW - 1
            int ty2 = oTy.get(k)
            tN.set(ty2, tN.get(ty2) + 1)
            if isRev
                tRev.set(ty2, tRev.get(ty2) + 1)
                hDp.push(oMx.get(k) / nz(atrL, atP))
                if hDp.size() > 400
                    hDp.shift()
                outRev := true
            else if isRun
                tRun.set(ty2, tRun.get(ty2) + 1)
                outRun := true
            if showSw
                color lc = sd2 == 1 ? bslC : sslC
                int   x1 = math.max(oBn.get(k), bar_index - 4900)
                swLn.push(line.new(x1, lv, stB, lv, color = isRev ? lc : color.new(lc, 40), style = isRev ? line.style_solid : line.style_dotted, width = 2))
                if isRev or isRun
                    swLb.push(label.new(stB, lv, isRev ? "✓" : "✗", style = sd2 == 1 ? label.style_label_down : label.style_label_up,
                         color = color(na), textcolor = isRev ? #3DDC97 : #FF6B6B, size = size.small,
                         tooltip = f_tyName(ty2, sd2) + " " + px(lv) + " was swept. " + (isRev ? "Price REVERSED (closed " : "Price RAN ON (closed ") + str.tostring(revATR, "0.0") + " ATR " + (isRev ? "back inside" : "beyond it") + " within " + str.tostring(outW) + " bars)."))
            oPx.remove(k)
            oAt.remove(k)
            oTy.remove(k)
            oSd.remove(k)
            oBn.remove(k)
            oSt.remove(k)
            oMx.remove(k)
while swLn.size() > keepSw
    swLn.shift().delete()
while swLb.size() > math.min(keepSw, 10)
    swLb.shift().delete()
 
// reach samples: note a hit when price trades through the sampled level, count the sample only when its window ends
if smB.size() > 0
    for q = smB.size() - 1 to 0
        if not smH.get(q)
            float sp = smP.get(q)
            if smD.get(q) == 1 ? high > sp : low < sp
                smH.set(q, true)
        if bar_index - smS.get(q) >= reachWin
            int bk2 = smB.get(q)
            bTot.set(bk2, bTot.get(bk2) + 1)
            if smH.get(q)
                bHit.set(bk2, bHit.get(bk2) + 1)
            float qq = smQ.get(q)
            if not na(qq)
                audN    += 1
                audSaid += qq
                audHit  += smH.get(q) ? 1 : 0
            smQ.remove(q)
            smP.remove(q)
            smD.remove(q)
            smB.remove(q)
            smS.remove(q)
            smH.remove(q)
 
// ═══════════════════════════════════════════════════════════════════════════
//  2. NEW POOLS (confirmed swings, previous session high / low)
// ═══════════════════════════════════════════════════════════════════════════
float tol = na(atrL) ? na : eqTol * atrL
float phv = ta.pivothigh(high, pL, pR)
float plv = ta.pivotlow(low, pL, pR)
if not na(tol)
    if not na(phv) and phv > high
        f_add(pPx, pSd, pTy, pBn, pLs, phv, 1, 0, bar_index - pR, tol)
    if not na(plv) and plv < low
        f_add(pPx, pSd, pTy, pBn, pLs, plv, -1, 0, bar_index - pR, tol)
    if showPS and newS and not na(sHi) and not na(sLo)
        f_add(pPx, pSd, pTy, pBn, pLs, sHi, 1, 2, nz(sHiB, bar_index - 1), tol)
        f_add(pPx, pSd, pTy, pBn, pLs, sLo, -1, 2, nz(sLoB, bar_index - 1), tol)
    if showPW and timeframe.isintraday and newW and not na(wHi) and not na(wLo)
        f_add(pPx, pSd, pTy, pBn, pLs, wHi, 1, 2, nz(wHiB, bar_index - 1), tol)
        f_add(pPx, pSd, pTy, pBn, pLs, wLo, -1, 2, nz(wLoB, bar_index - 1), tol)
    if showSes and timeframe.isintraday
        array<bool> inNow = array.from(inAs, inLo, inNy)
        int dU = dayofmonth(time, "UTC")
        for j = 0 to 2
            bool nowIn = inNow.get(j)
            if nowIn
                if ssIn.get(j) and ssD.get(j) != dU
                    f_add(pPx, pSd, pTy, pBn, pLs, ssH.get(j), 1, 3, ssB.get(j), tol)
                    f_add(pPx, pSd, pTy, pBn, pLs, ssL.get(j), -1, 3, ssB.get(j), tol)
                    ssH.set(j, high)
                    ssL.set(j, low)
                    ssB.set(j, bar_index)
                else if ssIn.get(j)
                    if high > ssH.get(j)
                        ssH.set(j, high)
                    if low < ssL.get(j)
                        ssL.set(j, low)
                else
                    ssH.set(j, high)
                    ssL.set(j, low)
                    ssB.set(j, bar_index)
                ssD.set(j, dU)
            else if ssIn.get(j)
                f_add(pPx, pSd, pTy, pBn, pLs, ssH.get(j), 1, 3, ssB.get(j), tol)
                f_add(pPx, pSd, pTy, pBn, pLs, ssL.get(j), -1, 3, ssB.get(j), tol)
            ssIn.set(j, nowIn)
 
// the oldest pools make room
while pPx.size() > MAXP
    pPx.remove(0)
    pSd.remove(0)
    pTy.remove(0)
    pBn.remove(0)
    pLs.remove(0)
 
// one probability sample per pool every reach window: its distance from price now, in ATRs
if not na(atrL) and atrL > 0 and pPx.size() > 0
    for i = 0 to pPx.size() - 1
        if bar_index - pLs.get(i) >= reachWin
            pLs.set(i, bar_index)
            smB.push(f_bk(math.abs(pPx.get(i) - close) / atrL))
            smS.push(bar_index)
            smP.push(pPx.get(i))
            smD.push(pSd.get(i))
            smH.push(false)
            smQ.push(math.abs(pPx.get(i) - close) / atrL < 4.0 ? f_prob(f_bk(math.abs(pPx.get(i) - close) / atrL)) : na)
 
// previous session extremes (updated after the pools above used the finished session)
if newS or na(sHi)
    sHi  := high
    sLo  := low
    sHiB := bar_index
    sLoB := bar_index
else
    if high > sHi
        sHi  := high
        sHiB := bar_index
    if low < sLo
        sLo  := low
        sLoB := bar_index
if newW or na(wHi)
    wHi  := high
    wLo  := low
    wHiB := bar_index
    wLoB := bar_index
else
    if high > wHi
        wHi  := high
        wHiB := bar_index
    if low < wLo
        wLo  := low
        wLoB := bar_index
 
// ═══════════════════════════════════════════════════════════════════════════
//  3. SWEEP SETUPS + TRACKING
// ═══════════════════════════════════════════════════════════════════════════
var bool  tOn    = false
var int   tDir   = 0
var float tE     = na
var float tSL    = na
var float tTP    = na
var int   tBar   = 0
var int   tTy    = 0
var int   tStars = 1
var box   tbTP   = na
var box   tbSL   = na
var int   wins   = 0
var int   losses = 0
var int   tExits = 0
var float sumR   = 0.0
var array<int>   gN = array.new<int>(3, 0)
var array<int>   gW = array.new<int>(3, 0)
var array<float> gR = array.new<float>(3, 0.0)
var array<box>   tBoxes = array.new<box>()
var array<label> tLbls  = array.new<label>()
 
longSig  = false
shortSig = false
tpHit    = false
slHit    = false
string tpTag = ""
float  sweptPx = na
 
// manage the open setup
if tOn and bar_index > tBar
    if not na(tbTP)
        tbTP.set_right(bar_index)
        tbSL.set_right(bar_index)
    bool hs = tDir == 1 ? low <= tSL : high >= tSL
    bool ht = tDir == 1 ? high >= tTP : low <= tTP
    bool tx = bar_index - tBar >= maxBars
    bool gapTP = tDir == 1 ? open >= tTP : open <= tTP      // a bar that opens beyond the target fills it first
    if hs or ht or tx
        tOn := false
        float risk0 = math.abs(tE - tSL)
        if hs and not gapTP        // stop first when both are touched on one bar (conservative)
            float exS = tDir == 1 ? math.min(open, tSL) : math.max(open, tSL)
            float rS  = tDir * (exS - tE) / risk0
            losses += 1
            sumR += rS
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) + rS)
            slHit := true
            tLbls.push(label.new(bar_index, tSL, "✗ " + str.tostring(rS, "0.0") + "R", color = badC, textcolor = #FFFFFF, style = tDir == 1 ? label.style_label_up : label.style_label_down, size = size.small))
        else if ht
            float rr = math.abs(tTP - tE) / risk0
            wins += 1
            sumR += rr
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gW.set(tStars - 1, gW.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) + rr)
            tpHit := true
            tLbls.push(label.new(bar_index, tTP, "✓ +" + str.tostring(rr, "0.0") + "R", color = goodC, textcolor = #FFFFFF, style = tDir == 1 ? label.style_label_down : label.style_label_up, size = size.small))
        else
            float rr = tDir * (close - tE) / risk0
            tExits += 1
            sumR += rr
            gN.set(tStars - 1, gN.get(tStars - 1) + 1)
            gR.set(tStars - 1, gR.get(tStars - 1) + rr)
            tLbls.push(label.new(bar_index, close, "⏱ " + (rr >= 0 ? "+" : "") + str.tostring(rr, "0.0") + "R", color = color.new(chart.fg_color, 40), textcolor = chart.bg_color,
                 style = tDir == 1 ? label.style_label_down : label.style_label_up, size = size.small))
 
// new setup (bar close only): exactly one side swept by a wick
if showSig and barstate.isconfirmed and not tOn and not na(atr) and atr > 0 and swLong != swShort
    bool  isL   = swLong
    float sl    = isL ? low - atr * slBuf : high + atr * slBuf
    float risk  = isL ? close - sl : sl - close
    if risk > 0 and risk <= maxRisk * atr and (trendLen == 0 or (isL ? close > trEma : close < trEma)) and relV >= minRelV and (isL ? math.min(open, close) - low : high - math.max(open, close)) >= minWick / 100.0 * (high - low)
        float tp = na
        if pPx.size() > 0
            for i = 0 to pPx.size() - 1
                float p = pPx.get(i)
                if isL
                    if pSd.get(i) == 1 and p >= close + risk * rrLo and p <= close + risk * rrHi and (na(tp) or p < tp)
                        tp := p
                        tpTag := "BSL"
                else
                    if pSd.get(i) == -1 and p <= close - risk * rrLo and p >= close - risk * rrHi and (na(tp) or p > tp)
                        tp := p
                        tpTag := "SSL"
        if na(tp)
            float fbR = math.max(rrLo, math.min(2.0, rrHi))
            tp := isL ? close + fbR * risk : close - fbR * risk
            tpTag := str.tostring(fbR, "0.##") + "R"
        longSig  := isL
        shortSig := not isL
        tOn  := true
        tDir := isL ? 1 : -1
        tE   := close
        tSL  := sl
        tTP  := tp
        tBar := bar_index
        tTy  := isL ? cTyL : cTyS
        sweptPx := isL ? cPxL : cPxS
 
// grade the new setup: ⭐ pool swept (always) + ⭐ strong sweep + ⭐ pool type that reverses on this symbol
bool  gStr  = false
bool  gMeas = false
float gStrV = na
float gRevT = na
if longSig or shortSig
    float gPen = longSig ? cPenL : cPenS
    gStrV := atr > 0 ? gPen / atr * relV : na
    gStr  := not na(gStrV) and gStrV >= strMin
    gRevT := f_rev(tTy)
    gMeas := not na(gRevT) and gRevT >= revMin
    tStars := 1 + (gStr ? 1 : 0) + (gMeas ? 1 : 0)
 
// draw a new setup: position-tool style boxes + label
if longSig or shortSig
    tbTP := na
    tbSL := na
if showBox and (longSig or shortSig)
    tbTP := box.new(bar_index, tTP, bar_index + 1, tE, border_color = color.new(goodC, 55), border_width = 1, bgcolor = color.new(goodC, 88),
         text = "TP " + tpTag, text_color = color.new(goodC, 10), text_size = size.small, text_halign = text.align_right, text_valign = longSig ? text.align_top : text.align_bottom)
    tbSL := box.new(bar_index, tE, bar_index + 1, tSL, border_color = color.new(badC, 55), border_width = 1, bgcolor = color.new(badC, 88),
         text = "SL", text_color = color.new(badC, 10), text_size = size.small, text_halign = text.align_right, text_valign = longSig ? text.align_bottom : text.align_top)
    tBoxes.push(tbTP)
    tBoxes.push(tbSL)
if longSig or shortSig
    color c = longSig ? goodC : badC
    tLbls.push(label.new(bar_index, longSig ? low : high, (longSig ? "▲ SWEEP " : "▼ SWEEP ") + f_stars(tStars), yloc = longSig ? yloc.belowbar : yloc.abovebar,
         color = c, textcolor = #FFFFFF, style = longSig ? label.style_label_up : label.style_label_down, size = tStars >= 3 ? size.normal : size.small,
         tooltip = "⭐ Pool swept ✓ (" + f_tyName(tTy, longSig ? -1 : 1) + " " + px(sweptPx) + ")\n⭐ Strong sweep " + (gStr ? "✓" : "✗") + (na(gStrV) ? "" : " (×" + str.tostring(gStrV, "0.0") + ")") +
         "\n⭐ Pool type reverses ≥ " + str.tostring(revMin) + "% " + (gMeas ? "✓" : "✗") + (na(gRevT) ? " (not enough data yet)" : " (" + str.tostring(gRevT, "0") + "%)") +
         "\n\nEntry " + px(tE) + "\nStop " + px(tSL) + "\nTarget " + px(tTP) + " (" + tpTag + ")"))
while tBoxes.size() > keepT * 2
    tBoxes.shift().delete()
while tLbls.size() > keepT * 2
    tLbls.shift().delete()
 
// ═══════════════════════════════════════════════════════════════════════════
//  4. LAST-BAR DRAWING: liquidity pools, table, status banner
// ═══════════════════════════════════════════════════════════════════════════
var array<line>  pLn = array.new<line>()
var array<label> pLb = array.new<label>()
var array<box>   pBx = array.new<box>()
var table bn = table.new(position.top_center, 1, 1, frame_color = color(na), frame_width = 0)
tpos = tbPos == "Top left" ? position.top_left : tbPos == "Bottom right" ? position.bottom_right : tbPos == "Bottom left" ? position.bottom_left : position.top_right
int lgR = showFull ? 12 : 6
var table tb = table.new(tpos, 2, lgR + 1, bgcolor = color.new(dkBg, 4), border_color = color.new(dkTx, 88), border_width = 1, frame_color = color.new(dkTx, 75), frame_width = 1)
 
if barstate.isfirst and showTb
    table.cell(tb, 0, 0, "EYE LIQUIDITY RADAR", text_color = bslC, bgcolor = hdrC, text_size = size.normal, text_halign = text.align_center)
    table.merge_cells(tb, 0, 0, 1, 0)
    table.cell(tb, 0, lgR, "▲ BSL = buy stops above highs · ▼ SSL = sell stops below lows\n✓ reversed · ✗ ran on · % = in-sample, not a forecast", text_color = dkMu, text_size = size.small, text_halign = text.align_left)
    table.merge_cells(tb, 0, lgR, 1, lgR)
 
f_cell(int r, string k, string v, color vc) =>
    table.cell(tb, 0, r, k, text_color = dkMu, text_size = size.normal, text_halign = text.align_left)
    table.cell(tb, 1, r, v, text_color = vc, text_size = size.normal, text_halign = text.align_right)
 
if barstate.islast
    for l in pLn
        l.delete()
    for x in pLb
        x.delete()
    for bx in pBx
        bx.delete()
    pLn.clear()
    pLb.clear()
    pBx.clear()
 
    int   x0    = bar_index + OFFB
    float nbP   = na      // nearest buy-side pool
    float nbQ   = na
    float nsP   = na      // nearest sell-side pool
    float nsQ   = na
    float wUp   = 0.0
    float wDn   = 0.0
    float tgt   = na      // best draw on liquidity: nearest pool with at least 50% reach probability, else the nearest
    float tgtQ  = na
    int   tgtS  = 0
 
    float hdD = hDp.size() >= minSamp ? hDp.percentile_nearest_rank(80) : na
    if pPx.size() > 0 and not na(atrL) and atrL > 0
        // every pool in range: faint line + a row of the liquidity ladder
        float lo  = close - maxDist * atrL
        float stp = 2.0 * maxDist * atrL / LADR
        array<float> lad = array.new<float>(LADR, 0.0)
        for i = 0 to pPx.size() - 1
            float lv0  = pPx.get(i)
            float dst0 = math.abs(lv0 - close)
            if dst0 <= maxDist * atrL
                int   ty0 = pTy.get(i)
                float pb0 = f_prob(f_bk(dst0 / atrL))
                float q0  = na(pb0) ? 30.0 : pb0
                int   k0  = math.max(0, math.min(LADR - 1, int(math.floor((lv0 - lo) / stp))))
                float wt0 = (ty0 == 2 ? 3.0 : ty0 == 3 ? 2.5 : ty0 == 1 ? 2.0 : 1.0) * (0.4 + 0.6 * q0 / 100.0)
                lad.set(k0, lad.get(k0) + wt0)
                if lv0 > close
                    wUp += wt0
                else
                    wDn += wt0
        float mxL = lad.max()
        if showLad and mxL > 0
            for k = 0 to LADR - 1
                float vL = lad.get(k)
                if vL > 0
                    float bot = lo + k * stp
                    int   wd  = math.max(1, int(math.round(LADW * vL / mxL)))
                    pBx.push(box.new(x0 + 1, bot + stp * 0.78, x0 + 1 + wd, bot + stp * 0.22, border_color = color(na), bgcolor = color.new(bot + stp / 2 >= close ? bslC : sslC, int(78 - 55 * vL / mxL))))
        array<float> dd = array.new<float>()
        for i = 0 to pPx.size() - 1
            float dst = math.abs(pPx.get(i) - close)
            dd.push(dst <= maxDist * atrL ? dst : 1e100)      // far pools are skipped
        array<int> shIx = array.new<int>()
        int nB = 0
        int nS = 0
        while dd.min() < 1e99
            int   ix   = dd.indexof(dd.min())
            dd.set(ix, 1e100)
            int   sd3  = pSd.get(ix)
            if (sd3 == 1 ? nB : nS) >= maxP
                continue
            if sd3 == 1
                nB += 1
            else
                nS += 1
            shIx.push(ix)
            float lvl2 = pPx.get(ix)
            int   ty3  = pTy.get(ix)
            float dist = lvl2 - close
            float pb   = f_prob(f_bk(math.abs(dist) / atrL))
            if sd3 == 1 and na(nbP)
                nbP := lvl2
                nbQ := pb
            if sd3 == -1 and na(nsP)
                nsP := lvl2
                nsQ := pb
            if na(tgt) or (not na(pb) and pb >= 50 and (na(tgtQ) or tgtQ < 50))
                tgt  := lvl2
                tgtQ := pb
                tgtS := sd3
            if showPool
                float q  = na(pb) ? 30.0 : pb
                int   w  = q >= 75 ? 3 : q >= 50 ? 2 : 1
                int   tr = int(math.max(0, 75 - 0.75 * q))
                color pc = sd3 == 1 ? bslC : sslC
                int   x1 = math.max(pBn.get(ix), bar_index - 4900)
                float rv = tN.get(ty3) >= minSamp ? 100.0 * tRev.get(ty3) / tN.get(ty3) : na
                float bh = 0.14 * atrL
                if q >= 40
                    // strength fade over the last 90 bars: solid near price, fading to the left; stronger pools stay darker for longer
                    int   segN = 12
                    int   xS   = math.max(x1, x0 - 90)
                    int   segW = math.max(1, x0 - xS)
                    int   trS  = int(math.max(18.0, 72.0 - 0.6 * q))
                    for sg = 0 to segN - 1
                        float fr = (sg + 1) / float(segN)
                        pBx.push(box.new(xS + int(math.round(segW * sg / float(segN))), lvl2 + bh, xS + int(math.round(segW * (sg + 1) / float(segN))), lvl2 - bh,
                             border_color = color(na), bgcolor = color.new(pc, int(97 - (97 - trS) * fr * fr))))
                pLn.push(line.new(x1, lvl2, x0, lvl2, color = color.new(pc, q >= 40 ? 40 : tr), style = q >= 50 ? line.style_solid : line.style_dashed, width = q >= 50 ? 2 : 1))
                if not na(hdD)
                    float sk = sd3 == 1 ? lvl2 + hdD * atrL : lvl2 - hdD * atrL
                    pLn.push(line.new(x0 - 10, sk, x0, sk, color = color.new(dkTx, 25), style = line.style_dotted, width = 2))
                pLb.push(label.new(x0 + LADW + 2, lvl2, (sd3 == 1 ? "▲ BSL " : "▼ SSL ") + px(lvl2) + " · " + px(math.abs(dist)) + " away · " + (na(pb) ? "–" : str.tostring(pb, "0") + "%"),
                     color = color.new(pc, q >= 75 ? 15 : q >= 50 ? 40 : 75), textcolor = q >= 50 ? #000000 : dkTx, style = label.style_label_left, size = q >= 50 ? size.normal : size.small,
                     tooltip = (sd3 == 1 ? "Buy-side liquidity (stops above a high): " : "Sell-side liquidity (stops below a low): ") + f_tyName(ty3, sd3) + "\nChance price sweeps it within " + str.tostring(reachWin) + " bars: " +
                     (na(pb) ? "not enough data yet" : str.tostring(pb, "0") + "%") + "\nAfter this pool type is swept on this chart: " + (na(rv) ? "no samples yet" : str.tostring(rv, "0") + "% reversed (" + str.tostring(tN.get(ty3)) + " sweeps)") +
                     "\nDistance from price: " + px(dist) + (na(hdD) ? "" : "\nStop-hunt depth: 80% of sweeps that reversed went no deeper than " + str.tostring(hdD, "0.00") + " ATR beyond the pool (dotted tick = " + px(sd3 == 1 ? lvl2 + hdD * atrL : lvl2 - hdD * atrL) + "). In-sample, not a guarantee.")))
        // all other pools in range: faint lines only
        if showPool and showFaint
            for i = 0 to pPx.size() - 1
                if math.abs(pPx.get(i) - close) <= maxDist * atrL and not shIx.includes(i)
                    pLn.push(line.new(math.max(pBn.get(i), bar_index - 4900), pPx.get(i), x0, pPx.get(i), color = color.new(pSd.get(i) == 1 ? bslC : sslC, 88), style = line.style_dotted, width = 1))
    if showPool and not na(tgt)
        color tcc = tgtS == 1 ? bslC : sslC
        pLn.push(line.new(bar_index + 1, close, bar_index + 8, tgt, color = tcc, width = 2, style = line.style_arrow_right))
        pLb.push(label.new(bar_index + 4, (close + tgt) / 2, (tgt < close ? "−" : "+") + px(math.abs(tgt - close)) + " · " + str.tostring(math.abs(tgt - close) / atrL, "0.0") + " ATR", style = label.style_label_center, color = color.new(tcc, 15), textcolor = #000000, size = size.small,
             tooltip = "Next stop: distance to the highlighted liquidity pool. The % on the pool tag is the historical hit rate on this chart for pools at this distance (in-sample, not a forecast)."))
 
    if showTb
        table.cell(tb, 0, 0, "EYE LIQUIDITY RADAR", text_color = tgtS == 1 ? bslC : sslC, bgcolor = hdrC, text_size = size.normal, text_halign = text.align_center)
        f_cell(1, "Nearest BSL ▲", na(nbP) ? "none" : px(nbP) + "  ·  " + (na(nbQ) ? "–" : str.tostring(nbQ, "0") + "%"), bslC)
        f_cell(2, "Nearest SSL ▼", na(nsP) ? "none" : px(nsP) + "  ·  " + (na(nsQ) ? "–" : str.tostring(nsQ, "0") + "%"), sslC)
        float wTot = wUp + wDn
        int   nUp  = wTot > 0 ? int(math.round(10.0 * wUp / wTot)) : 5
        f_cell(3, "Stops above ▲ vs below ▼", wTot > 0 ? str.tostring(100.0 * wUp / wTot, "0") + "% " + str.repeat("█", nUp) + str.repeat("░", 10 - nUp) + " " + str.tostring(100.0 * wDn / wTot, "0") + "%" : "–", wTot > 0 ? (wUp > wDn ? bslC : sslC) : dkTx)
        f_cell(4, "Self-check (pools < 4 ATR)", audN >= minSamp ? "said " + str.tostring(audSaid / audN, "0") + "%  →  got " + str.tostring(100.0 * audHit / audN, "0") + "%" + (showFull ? "  (" + str.tostring(audN) + ")" : "") : "collecting…", dkTx)
        f_cell(5, "Stop-hunt depth (80%)", na(hdD) ? "collecting…" : "≤ " + str.tostring(hdD, "0.00") + " ATR beyond pool", dkTx)
        if showFull
            string rb = ""
            for b = 0 to 3
                float pbb = f_prob(b)
                rb += (b > 0 ? "  ·  " : "") + (na(pbb) ? "–" : str.tostring(pbb, "0"))
            f_cell(6, "Hit in " + str.tostring(reachWin) + " bars · <2 · 2–4 · 4–8 · 8+ ATR", rb + " %", dkTx)
            array<string> tName = array.from("Swing high / low", "Equal highs / lows", "Previous period high / low", "Session (Asia·Lon·NY) high / low")
            for t = 0 to 3
                int cnt = tN.get(t)
                f_cell(7 + t, tName.get(t) + " swept", cnt == 0 ? "–" : "↩ " + str.tostring(100.0 * tRev.get(t) / cnt, "0") + "%  ➜ " + str.tostring(100.0 * tRun.get(t) / cnt, "0") + "%  (" + str.tostring(cnt) + ")", dkTx)
            f_cell(11, "Open pools tracked", str.tostring(pPx.size()), dkTx)
 
    // status banner: what is happening now, in one line
    string stt = "NO LIQUIDITY POOL NEARBY"
    color  sc  = #607D8B
    if not na(tgt)
        stt := "NEXT POOL  " + (tgtS == 1 ? "▲ BSL " : "▼ SSL ") + px(tgt) + "  ·  " + px(math.abs(tgt - close)) + " away" + (na(tgtQ) ? "" : "  ·  " + str.tostring(tgtQ, "0") + "% hit rate (history, " + str.tostring(reachWin) + " bars)") + (trendLen > 0 ? "  ·  trend " + (close > trEma ? "▲" : "▼") : "")
        sc  := tgtS == 1 ? bslC : sslC
    if tOn
        stt := (tDir == 1 ? "▲ LONG ACTIVE " : "▼ SHORT ACTIVE ") + f_stars(tStars) + "   TP " + px(tTP) + "   SL " + px(tSL)
        sc  := tDir == 1 ? goodC : badC
    table.cell(bn, 0, 0, stt, text_color = (sc == sslC or sc == bslC) ? #000000 : #FFFFFF, bgcolor = color.new(sc, 12), text_size = size.normal)
 
plot(showEma and trendLen > 0 ? trEma : na, "Trend EMA", color = close > trEma ? color.new(goodC, 10) : color.new(badC, 10), linewidth = 1, style = plot.style_circles)
 
// ═══════════════════════════════════════════════════════════════════════════
//  ALERTS
// ═══════════════════════════════════════════════════════════════════════════
alertcondition(outRev, "Sweep REVERSED", "{{ticker}} a swept liquidity pool was reversed (close back inside)")
alertcondition(outRun, "Sweep RAN ON", "{{ticker}} a swept liquidity pool ran on (close beyond it)")
alertcondition(longSig, "Sweep setup ▲ (needs setups ON)", "{{ticker}} sell-side liquidity swept, long setup")
alertcondition(shortSig, "Sweep setup ▼ (needs setups ON)", "{{ticker}} buy-side liquidity swept, short setup")
alertcondition((longSig or shortSig) and tStars >= 3, "⭐⭐⭐ setup", "{{ticker}} 3-star sweep setup (strong sweep + pool type that reverses)")
alertcondition(barstate.isconfirmed and tpHit, "Setup target hit", "{{ticker}} sweep setup reached its target")
alertcondition(barstate.isconfirmed and slHit, "Setup stop hit", "{{ticker}} sweep setup hit its stop")
alertcondition(barstate.isconfirmed and swShort, "Buy-side liquidity swept", "{{ticker}} wick swept buy-side liquidity and closed back below")
alertcondition(barstate.isconfirmed and swLong, "Sell-side liquidity swept", "{{ticker}} wick swept sell-side liquidity and closed back above")
 
if detailAlerts and (longSig or shortSig)
    alert(syminfo.ticker + " — Eye Liquidity Sweep Map: " + (longSig ? "SELL-SIDE" : "BUY-SIDE") + " liquidity swept " + f_stars(tStars) + ". " + (longSig ? "Long" : "Short") + " entry " + px(tE) + ", stop " + px(tSL) +
         ", target " + px(tTP) + " (" + tpTag + ")", alert.freq_once_per_bar_close)

← 返回列表