Eye Liquidity Heatmap [EyeAlgo]

eyealgo · study · 614 行 · 点赞 1,056 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EyeAlgo
//@version=6
indicator("Eye Liquidity Heatmap [EyeAlgo]", "Eye Liquidity Heatmap [EyeAlgo]", overlay=true, max_boxes_count=500, max_lines_count=100, max_labels_count=200, max_bars_back=5000)
 
// ═════════════════════════ INPUTS ═════════════════════════
grpS = "Liquidity sources"
lockTf   = input.timeframe("30", "Build levels on timeframe", group=grpS, tooltip="Levels, heat, sweeps and magnets are built from this timeframe, so every chart at or below it (1m, 5m, 15m, 30m) shows the same map. Charts above it use their own timeframe. Leave empty to always use the chart timeframe.")
pivLen   = input.int(5, "Swing length", minval=2, maxval=30, group=grpS, tooltip="A swing high/low needs this many bars on each side. Stops sit just beyond these swings.")
mergeTol = input.float(0.30, "Equal highs/lows tolerance (× ATR)", minval=0.05, step=0.05, group=grpS, tooltip="Swings closer than this join into one level and its heat stacks up (equal highs / equal lows = more stops).")
useVol   = input.bool(true, "Weight by volume at the swing", group=grpS)
useRound = input.bool(true, "Boost levels near round numbers", group=grpS)
roundStp = input.float(0.0, "Round number step (0 = auto)", minval=0.0, group=grpS, tooltip="Auto picks a step from the price size: about 25 on gold, 250 on Nifty, 2500 on BTC, 0.025 on EURUSD.")
touchAdd = input.float(0.3, "Heat added per touch without break", minval=0.0, step=0.1, group=grpS)
 
grpH = "Heat"
halfLife = input.int(150, "Heat half-life (bars of the build timeframe)", minval=10, maxval=2000, group=grpH, tooltip="A pool loses half of its heat after this many bars of the build timeframe without a new stacked swing or touch.")
maxLv    = input.int(120, "Max active levels", minval=10, maxval=200, group=grpH)
maxDist  = input.float(16.0, "Show levels within (× ATR of price)", minval=2.0, step=0.5, group=grpH, tooltip="Far-away levels are hidden so the chart scale stays clean.")
minShow  = input.int(15, "Hide levels below heat", minval=0, maxval=100, group=grpH)
 
grpV = "Visuals"
showBands = input.bool(true, "Heat bands", group=grpV)
bandW     = input.float(0.6, "Band thickness at full heat (× ATR)", minval=0.1, step=0.1, group=grpV, tooltip="Hotter levels are drawn thicker. Cold levels are about one quarter of this. Heat 70+ bands get a thin outline.")
showText  = input.bool(true, "Name the hot bands (heat ≥ 70)", group=grpV)
showSwept = input.bool(true, "Show swept (cooled) levels", group=grpV)
keepSwept = input.int(30, "Swept levels kept", minval=0, maxval=100, group=grpV)
showProf  = input.bool(true, "Heat profile on the right", group=grpV)
profBins  = input.int(40, "Profile rows", minval=10, maxval=80, group=grpV)
profWidth = input.int(12, "Profile width (bars)", minval=5, maxval=100, group=grpV)
extRight  = input.int(3, "Extend bands right (bars)", minval=0, maxval=50, group=grpV)
showMag   = input.bool(true, "Magnets (hottest level above / below)", group=grpV)
showSwpL  = input.bool(true, "Sweep marks", group=grpV)
hotCandle = input.bool(true, "Color candles inside hot zones", group=grpV)
showPath  = input.bool(true, "Path arrow to the stronger magnet", group=grpV)
 
grpT = "Stats"
hotPct  = input.int(60, "Hot zone = heat ≥", minval=10, maxval=100, group=grpT)
revBars = input.int(10, "Sweep → reversal window (bars)", minval=2, maxval=100, group=grpT)
revAtr  = input.float(0.5, "Reversal = close back beyond level by (× ATR)", minval=0.1, step=0.1, group=grpT)
magBars = input.int(50, "Magnet reached within (bars)", minval=5, maxval=500, group=grpT)
 
grpD = "Dashboard"
dashStyle = input.string("Beside last candle", "Dashboard style", options=["Beside last candle", "Panel (always visible)", "Off"], group=grpD, tooltip="Beside last candle: the dashboard is drawn on the chart right next to the latest candle, with the heat profile and magnet labels after it. Panel: a table fixed to a corner of the screen.")
hudGap  = input.int(6, "Dashboard distance from last candle (bars)", minval=2, maxval=60, group=grpD)
bool showTbl = dashStyle == "Panel (always visible)"
bool showHud = dashStyle == "Beside last candle"
tblPos  = input.string("Top Right", "Panel position", options=["Top Right", "Middle Right", "Bottom Right", "Top Left", "Bottom Left"], group=grpD)
tblSize = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=grpD)
 
grpK = "Colors"
cSwept = input.color(#B2B5BE, "Swept (cooled) level", group=grpK)
cBuy  = input.color(#089981, "Sell-side liquidity (below price)", group=grpK, tooltip="Heat is shown as strength of the colour: light = cold, strong = hot.")
cSell = input.color(#F23645, "Buy-side liquidity (above price)", group=grpK)
 
// ═════════════════════════ TYPES ═════════════════════════
// side  1 = buy stops above a swing high · -1 = sell stops below a swing low
type Liq
    float price
    int   side
    float w
    int   born
    int   bornT
    float half
    bool  rnd = false
    int   sweptBar = na
    box   bx = na
    int   stacks = 1
    int   addB = na
 
// ═════════════════════════ CORE ═════════════════════════
// build timeframe: the same map on every chart at or below it
int    chSec  = timeframe.in_seconds()
int    lkSec  = lockTf == "" ? chSec : timeframe.in_seconds(lockTf)
string effTf  = lkSec > chSec ? lockTf : timeframe.period
int    effSec = math.max(lkSec, chSec)
float  tfMult = float(effSec) / chSec
 
// values of the last CLOSED bar of the build timeframe (no repaint)
f_src() =>
    float a   = ta.atr(14)
    float va  = ta.sma(nz(volume), 50)
    float vfx = va[pivLen] > 0 ? math.min(math.max(nz(volume[pivLen]) / va[pivLen], 0.5), 3.0) : 1.0
    float p1  = ta.pivothigh(high, pivLen, pivLen)
    float p2  = ta.pivotlow(low, pivLen, pivLen)
    int   tp  = time[pivLen]
    [p1[1], p2[1], tp[1], a[1], vfx[1], high[1], low[1]]
[ph, pl, pivT, atrL, vfL, hiL, loL] = request.security(syminfo.tickerid, effTf, f_src(), lookahead=barmerge.lookahead_on)
bool  tfCh = timeframe.change(effTf)
bool  newL = effTf == timeframe.period ? true : tfCh
float atr  = atrL
bool  conf = barstate.isconfirmed
bool  hasVol = ta.cum(nz(volume)) > 0
 
// chart bar index of a given time (for drawing)
f_idxAt(int t) =>
    int k = 0
    while k < 4900 and bar_index - k > 0 and time[k] > t
        k += 1
    bar_index - k
 
var array<Liq> act = array.new<Liq>()
var array<Liq> swp = array.new<Liq>()
 
f_step() =>
    float s = roundStp
    if s <= 0
        s := math.pow(10, math.floor(math.log10(math.max(close, 1e-10))) - 2) * 2.5
    s
 
f_heat(Liq l) =>
    float age = (time - l.bornT) / (effSec * 1000.0)
    l.w * math.pow(0.5, age / halfLife)
 
f_addLevel(float p, int side, int bornBar, int bornT, float wNew) =>
    float tol = mergeTol * atr
    int hit = -1
    float best = tol
    if act.size() > 0
        for i = 0 to act.size() - 1
            Liq l = act.get(i)
            float d = math.abs(l.price - p)
            if l.side == side and d <= best
                best := d
                hit := i
    if hit >= 0
        Liq l = act.get(hit)
        // rebase the current (decayed) heat, then add the new swing; equal highs / lows get a 50% stacking bonus
        float cur = f_heat(l)
        float tw = cur + wNew
        l.price := (l.price * cur + p * wNew) / tw
        l.w := tw + wNew * 0.5
        l.stacks += 1
        l.born := math.max(l.born, bornBar)
        l.bornT := math.max(l.bornT, bornT)
        l.addB := bar_index
    else
        float st = f_step()
        bool r = useRound and math.abs(p - math.round(p / st) * st) <= mergeTol * atr
        Liq nl = Liq.new(p, side, wNew * (r ? 1.3 : 1.0), bornBar, bornT, bandW * atr / 2, r)
        nl.addB := bar_index
        act.push(nl)
    hit
 
// new swings → liquidity levels
if conf and newL and not na(atr) and not na(pivT)
    float vf = useVol and hasVol ? nz(vfL, 1.0) : 1.0
    int bi = na(ph) and na(pl) ? na : f_idxAt(pivT)
    if not na(ph)
        f_addLevel(ph, 1, bi, pivT, vf)
    if not na(pl)
        f_addLevel(pl, -1, bi, pivT, vf)
 
// ═════════════════════════ SWEEPS, TOUCHES, HEAT ═════════════════════════
float maxH = 0.0
if act.size() > 0
    for i = 0 to act.size() - 1
        maxH := math.max(maxH, f_heat(act.get(i)))
 
// pending stat tests
var array<float> rvP = array.new<float>()
var array<int>   rvS = array.new<int>()
var array<int>   rvB = array.new<int>()
var array<int>   hRes = array.new<int>()
var array<int>   hSide = array.new<int>()
var int nRev = 0
var int nRevOk = 0
var array<label> swLbls = array.new<label>()
bool hotSweepUp = false
bool hotSweepDn = false
string hotMsg = ""
 
if conf and act.size() > 0 and not na(atr)
    for i = act.size() - 1 to 0
        Liq l = act.get(i)
        if l.born < bar_index
            bool broke = l.side == 1 ? high > l.price + 0.05 * atr : low < l.price - 0.05 * atr
            bool touch = newL and not na(hiL) and l.addB != bar_index and (l.side == 1 ? hiL >= l.price - l.half : loL <= l.price + l.half)
            if broke
                float hp = maxH > 0 ? 100 * math.sqrt(f_heat(l) / maxH) : 0
                l.sweptBar := bar_index
                if not na(l.bx)
                    l.bx.set_right(bar_index)
                    l.bx.set_top(l.price + l.half)
                    l.bx.set_bottom(l.price - l.half)
                    l.bx.set_bgcolor(color.new(cSwept, 60))
                    l.bx.set_border_color(color(na))
                    l.bx.set_text("")
                act.remove(i)
                swp.push(l)
                if hp >= hotPct
                    hotMsg += (l.side == 1 ? "BUY-SIDE " : "SELL-SIDE ") + str.tostring(l.price, format.mintick) + " (heat " + str.tostring(hp, "0") + ")  "
                    // one reversal test per side per bar (two pools swept by one candle are one event)
                    if rvB.size() == 0 or rvB.last() != bar_index or rvS.last() != l.side
                        rvP.push(l.price)
                        rvS.push(l.side)
                        rvB.push(bar_index)
                    if l.side == 1
                        hotSweepUp := true
                    else
                        hotSweepDn := true
                    if showSwpL
                        bool up = l.side == 1
                        swLbls.push(label.new(bar_index, up ? high : low, "⚡", yloc=up ? yloc.abovebar : yloc.belowbar, style=label.style_none, textcolor=up ? cSell : cBuy, size=size.normal, tooltip=(up ? "Buy-side liquidity swept" : "Sell-side liquidity swept") + " · " + str.tostring(l.price, format.mintick) + " · heat " + str.tostring(hp, "0")))
                        while swLbls.size() > 30
                            swLbls.shift().delete()
            else if touch
                l.w := f_heat(l) + touchAdd
                l.bornT := time
    // too many levels → drop the coldest
    while act.size() > maxLv
        int ci = 0
        float ch = 1e30
        for j = 0 to act.size() - 1
            float h = f_heat(act.get(j))
            if h < ch
                ch := h
                ci := j
        Liq d = act.remove(ci)
        if not na(d.bx)
            d.bx.delete()
    while swp.size() > keepSwept
        Liq d = swp.shift()
        if not na(d.bx)
            d.bx.delete()
 
// sweep → reversal tests
if conf and rvP.size() > 0
    for i = rvP.size() - 1 to 0
        float p = rvP.get(i)
        int s = rvS.get(i)
        bool ok = bar_index > rvB.get(i) and (s == 1 ? close <= p - revAtr * atr : close >= p + revAtr * atr)
        bool out = bar_index - rvB.get(i) >= revBars * tfMult
        if ok or out
            nRev += 1
            nRevOk += ok ? 1 : 0
            hRes.push(ok ? 1 : 0)
            hSide.push(s)
            if hRes.size() > 12
                hRes.shift()
                hSide.shift()
            rvP.remove(i)
            rvS.remove(i)
            rvB.remove(i)
 
// ═════════════════════════ MAGNETS + BIAS ═════════════════════════
float maxH2 = 0.0
if act.size() > 0
    for i = 0 to act.size() - 1
        maxH2 := math.max(maxH2, f_heat(act.get(i)))
float hAbove = 0.0
float hBelow = 0.0
int iUp = -1
int iDn = -1
float bUp = 0.0
float bDn = 0.0
int iUpA = -1
int iDnA = -1
float bUpA = 0.0
float bDnA = 0.0
float lim = maxDist * nz(atr)
float inHotP = 0.0
int   inHotS = 0
float nearP = na
float nearH = 0.0
float nearD = 1e30
int nAboveAll = 0
int nBelowAll = 0
if act.size() > 0
    for i = 0 to act.size() - 1
        Liq l = act.get(i)
        float h = f_heat(l)
        float hp = maxH2 > 0 ? 100 * math.sqrt(h / maxH2) : 0
        float dd = math.abs(l.price - close)
        if hp >= hotPct and not na(atr)
            if dd <= bandW * atr * (0.25 + 0.75 * hp / 100) / 2 and hp > inHotP
                inHotP := hp
                inHotS := l.side
            if dd < nearD
                nearD := dd
                nearP := l.price
                nearH := hp
        if l.price > close
            nAboveAll += 1
            if h > bUpA
                bUpA := h
                iUpA := i
        else
            nBelowAll += 1
            if h > bDnA
                bDnA := h
                iDnA := i
        if math.abs(l.price - close) <= lim
            if l.price > close
                hAbove += h
                if h > bUp
                    bUp := h
                    iUp := i
            else
                hBelow += h
                if h > bDn
                    bDn := h
                    iDn := i
// magnet = hottest level in view; if none in view, the hottest level beyond it (marked "far")
bool  magUpFar = iUp < 0 and iUpA >= 0
bool  magDnFar = iDn < 0 and iDnA >= 0
float magUp = iUp >= 0 ? act.get(iUp).price : magUpFar ? act.get(iUpA).price : na
float magDn = iDn >= 0 ? act.get(iDn).price : magDnFar ? act.get(iDnA).price : na
float pUp = maxH2 > 0 ? 100 * math.sqrt((magUpFar ? bUpA : bUp) / maxH2) : 0
float pDn = maxH2 > 0 ? 100 * math.sqrt((magDnFar ? bDnA : bDn) / maxH2) : 0
// far magnets are drawn at the edge of the view so the chart scale stays clean
float yUp = magUpFar ? math.min(magUp, close + lim) : magUp
float yDn = magDnFar ? math.max(magDn, close - lim) : magDn
// beside-candle dashboard: magnet labels sit next to the candles; if one falls inside the dashboard height, the dashboard moves right
float hudH = math.max(3.0, 0.4 * maxDist) * nz(atr)
bool magInHud = showMag and not na(atr) and ((not na(yUp) and math.abs(yUp - close) <= 1.2 * hudH) or (not na(yDn) and math.abs(yDn - close) <= 1.2 * hudH))
int  hudX0 = bar_index + hudGap + (magInHud ? 22 : 0)
 
// candles inside a hot zone glow (warm → hot)
bool  paintHot = hotCandle and inHotP > 0
color hotC = color.new(inHotS == 1 ? cSell : cBuy, math.round(55 - inHotP * 0.4))
plotcandle(paintHot ? open : na, paintHot ? high : na, paintHot ? low : na, paintHot ? close : na, "Hot-zone candles", color=hotC, wickcolor=hotC, bordercolor=hotC, editable=true)
 
// magnet reached test (one pending per direction)
var float mtUpP = na
var int   mtUpB = na
var float mtDnP = na
var int   mtDnB = na
var int nMag = 0
var int nMagOk = 0
bool magHitUp = false
bool magHitDn = false
if conf
    if not na(mtUpP)
        if high >= mtUpP
            nMag += 1
            nMagOk += 1
            magHitUp := true
            mtUpP := na
        else if bar_index - mtUpB >= magBars * tfMult
            nMag += 1
            mtUpP := na
    if not na(mtDnP)
        if low <= mtDnP
            nMag += 1
            nMagOk += 1
            magHitDn := true
            mtDnP := na
        else if bar_index - mtDnB >= magBars * tfMult
            nMag += 1
            mtDnP := na
    if na(mtUpP) and not na(magUp) and not magUpFar and pUp >= hotPct and magUp - close >= atr
        mtUpP := magUp
        mtUpB := bar_index
    if na(mtDnP) and not na(magDn) and not magDnFar and pDn >= hotPct and close - magDn >= atr
        mtDnP := magDn
        mtDnB := bar_index
 
// ═════════════════════════ DRAW ═════════════════════════
f_sideC(int side) =>
    side == 1 ? cSell : cBuy
f_base(float p, int side) =>
    color.new(f_sideC(side), math.round(80 - p * 0.6))
// band fill: cold = very light, hot = strong but still see-through (clean on a white chart)
f_col(float p, int side) =>
    color.new(f_sideC(side), math.round(90 - p * 0.55))
// heat 0-100 on a square-root scale so one giant level does not make every other level look cold
f_pct(float h, float mx) =>
    mx > 0 ? 100 * math.sqrt(math.max(h, 0) / mx) : 0.0
 
var array<box>   prof = array.new<box>()
var bool bandsOn = false
var bool profOn = false
var array<line>  mLines = array.new<line>()
var array<label> mLbls  = array.new<label>()
 
if barstate.islast and not na(atr)
    bandsOn := false
    profOn := false
    int x0 = bar_index - 4900
    int xr = bar_index + extRight
    // beside-candle mode: dashboard sits next to the candles, profile + magnets come after it
    int xAfter = hudX0 + 60
    // active heat bands
    if act.size() > 0
        for i = 0 to act.size() - 1
            Liq l = act.get(i)
            float p = f_pct(f_heat(l), maxH2)
            bool vis = showBands and p >= minShow and math.abs(l.price - close) <= lim
            float hh = bandW * atr * (0.25 + 0.75 * p / 100) / 2
            if not vis
                if not na(l.bx)
                    l.bx.delete()
                    l.bx := na
            else
                bandsOn := true
                int xl = math.max(l.born, x0)
                color bd = p >= 70 ? color.new(f_sideC(l.side), 25) : color(na)
                string tx = showText and p >= 70 ? (l.side == 1 ? "Buy-side liquidity " : "Sell-side liquidity ") + str.tostring(p, "0") + (l.stacks > 1 ? " · ×" + str.tostring(l.stacks) : "") + (l.rnd ? " · round" : "") : ""
                if na(l.bx)
                    l.bx := box.new(xl, l.price + hh, xr, l.price - hh, border_color=bd, border_width=1, bgcolor=f_col(p, l.side), text=tx, text_size=size.tiny, text_halign=text.align_right, text_color=color.new(chart.fg_color, 15))
                else
                    l.bx.set_lefttop(xl, l.price + hh)
                    l.bx.set_rightbottom(xr, l.price - hh)
                    l.bx.set_bgcolor(f_col(p, l.side))
                    l.bx.set_border_color(bd)
                    l.bx.set_text(tx)
    // swept levels: faded grey band that stops at the sweep bar
    if swp.size() > 0
        for i = 0 to swp.size() - 1
            Liq l = swp.get(i)
            bool vis = showSwept and math.abs(l.price - close) <= lim and l.sweptBar > x0
            if not vis
                if not na(l.bx)
                    l.bx.delete()
                    l.bx := na
            else if na(l.bx)
                l.bx := box.new(math.max(l.born, x0), l.price + l.half, l.sweptBar, l.price - l.half, border_color=color(na), bgcolor=color.new(cSwept, 60))
    // right-side heat profile
    while prof.size() > 0
        prof.shift().delete()
    if showProf and act.size() > 0
        float lo = close - lim
        float binH = 2 * lim / profBins
        array<float> bins = array.new<float>(profBins, 0.0)
        for i = 0 to act.size() - 1
            Liq l = act.get(i)
            if math.abs(l.price - close) <= lim
                int b = math.min(math.max(int(math.floor((l.price - lo) / binH)), 0), profBins - 1)
                bins.set(b, bins.get(b) + f_heat(l))
        float bm = bins.max()
        if bm > 0
            int px = showHud ? xAfter : xr + 1
            for b = 0 to profBins - 1
                float v = bins.get(b)
                if v > 0
                    float p = f_pct(v, bm)
                    int len = math.max(1, int(math.round(profWidth * p / 100)))
                    profOn := true
                    prof.push(box.new(px, lo + (b + 1) * binH - binH * 0.1, px + len, lo + b * binH + binH * 0.1, border_color=color(na), bgcolor=f_base(math.max(p, 20), lo + (b + 0.5) * binH > close ? 1 : -1)))
    // magnets
    while mLines.size() > 0
        mLines.shift().delete()
    while mLbls.size() > 0
        mLbls.shift().delete()
    int xm = showHud ? bar_index + 3 : math.max(profOn ? xr + profWidth + 2 : bandsOn ? xr + 1 : bar_index + 4, bar_index + 6)
    int xs = bar_index
    if showPath and not showHud and (not na(magUp) or not na(magDn))
        bool goUp = na(magDn) or (not na(magUp) and pUp >= pDn)
        float tg = goUp ? yUp : yDn
        mLines.push(line.new(bar_index, close, xm - 1, tg, color=color.new(goUp ? cSell : cBuy, 30), width=1, style=line.style_arrow_right))
    if showMag
        if not na(magUp)
            mLines.push(line.new(xs, yUp, xm, yUp, color=cSell, width=1, style=magUpFar ? line.style_dotted : line.style_dashed))
            mLbls.push(label.new(xm, yUp, (magUpFar ? "MAGNET ↑ far  " : "MAGNET ↑  ") + str.tostring(magUp, format.mintick), style=label.style_label_left, color=cSell, textcolor=color.white, size=size.small))
        if not na(magDn)
            mLines.push(line.new(xs, yDn, xm, yDn, color=cBuy, width=1, style=magDnFar ? line.style_dotted : line.style_dashed))
            mLbls.push(label.new(xm, yDn, (magDnFar ? "MAGNET ↓ far  " : "MAGNET ↓  ") + str.tostring(magDn, format.mintick), style=label.style_label_left, color=cBuy, textcolor=color.white, size=size.small))
 
// ═════════════════════════ SHARED DASHBOARD VALUES ═════════════════════════
float  dTot  = hAbove + hBelow
float  dUpS  = dTot > 0 ? 100 * hAbove / dTot : 50
bool   dDisD = nBelowAll == 0 and nAboveAll > 0
bool   dDisU = nAboveAll == 0 and nBelowAll > 0
string dStat = dDisD ? "NO POOLS BELOW · all tracked lows swept" : dDisU ? "NO POOLS ABOVE · all tracked highs swept" : dTot == 0 ? "NO POOLS IN VIEW" : dUpS >= 60 ? "MORE LIQUIDITY ABOVE" : dUpS <= 40 ? "MORE LIQUIDITY BELOW" : "BALANCED"
color  dCol  = dTot == 0 ? color.new(chart.fg_color, 40) : dUpS >= 60 ? cSell : dUpS <= 40 ? cBuy : color.new(chart.fg_color, 30)
color  dTxt  = dTot == 0 or (dUpS > 40 and dUpS < 60) ? chart.bg_color : color.white
string dTf   = effTf == timeframe.period ? "chart timeframe" : lkSec % 3600 == 0 and lkSec < 86400 ? str.tostring(lkSec / 3600) + "h" : str.contains("DWMS", str.substring(effTf, str.length(effTf) - 1)) ? effTf : effTf + "m"
f_magTxt(float m, bool far, float pp, bool up) =>
    na(m) ? (up ? "no stops above" : "no stops below") : str.tostring(m, format.mintick) + "  ·  heat " + str.tostring(pp, "0") + "  ·  " + str.tostring(math.abs(m - close) / atr, "0.0") + " ATR" + (far ? "  ·  far" : "")
string dRev  = nRev > 0 ? "Reversal " + str.tostring(100.0 * nRevOk / nRev, "0") + "% (n " + str.tostring(nRev) + ")" : "Reversal –"
string dMag  = nMag > 0 ? "Magnet hit " + str.tostring(100.0 * nMagOk / nMag, "0") + "% (n " + str.tostring(nMag) + ")" : "Magnet hit –"
 
// ═════════════════════════ PANEL (fixed on screen, always visible) ═════════════════════════
f_pos() =>
    switch tblPos
        "Top Left"     => position.top_left
        "Bottom Left"  => position.bottom_left
        "Bottom Right" => position.bottom_right
        "Middle Right" => position.middle_right
        => position.top_right
f_size() =>
    switch tblSize
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
var table tb = table.new(f_pos(), 13, 10, bgcolor=chart.bg_color, frame_width=1, frame_color=color.new(chart.fg_color, 80), border_width=1, border_color=chart.bg_color)
var bool merged = false
if showTbl and not merged
    table.merge_cells(tb, 0, 0, 12, 0)
    table.merge_cells(tb, 11, 1, 12, 1)
    for r in array.from(2, 3, 4, 6, 8)
        table.merge_cells(tb, 1, r, 12, r)
    table.merge_cells(tb, 11, 5, 12, 5)
    table.merge_cells(tb, 0, 9, 12, 9)
    merged := true
 
f_key(int r, string k) =>
    table.cell(tb, 0, r, k, text_color=color.new(chart.fg_color, 35), text_halign=text.align_left, text_size=f_size(), bgcolor=chart.bg_color)
f_val(int r, string v, color vc) =>
    table.cell(tb, 1, r, v, text_color=vc, text_halign=text.align_left, text_size=f_size(), bgcolor=chart.bg_color)
f_blk(int c, int r, color bg) =>
    table.cell(tb, c, r, "", bgcolor=bg, width=0.9, text_size=f_size())
 
if barstate.islast and showTbl and not na(atr)
    color fg = chart.fg_color
    table.cell(tb, 0, 0, "EYE LIQUIDITY HEATMAP   ·   " + dStat, text_color=dTxt, text_size=f_size(), bgcolor=dCol, text_halign=text.align_left)
    // liquidity tug-of-war: red cells = share above, green = share below
    f_key(1, "Liquidity  ↑ / ↓")
    int nUp = dTot > 0 ? int(math.round(dUpS / 10)) : 0
    for i = 1 to 10
        f_blk(i, 1, dTot == 0 ? color.new(fg, 88) : i <= nUp ? color.new(cSell, 10) : color.new(cBuy, 10))
    table.cell(tb, 11, 1, dTot > 0 ? str.tostring(dUpS, "0") + "% / " + str.tostring(100 - dUpS, "0") + "%" : "–", text_color=fg, text_size=f_size(), bgcolor=chart.bg_color)
    f_key(2, "Magnet ↑")
    f_val(2, f_magTxt(magUp, magUpFar, pUp, true), cSell)
    f_key(3, "Magnet ↓")
    f_val(3, f_magTxt(magDn, magDnFar, pDn, false), cBuy)
    f_key(4, "Nearest hot zone")
    f_val(4, na(nearP) ? "–" : str.tostring(nearP, format.mintick) + "  ·  " + str.tostring(nearD / atr, "0.0") + " ATR away", fg)
    f_key(5, "Heat")
    int cells = na(nearP) ? 0 : math.min(10, int(math.round(nearH / 10)))
    for i = 1 to 10
        f_blk(i, 5, i <= cells ? f_base(i * 10, nearP > close ? 1 : -1) : color.new(fg, 90))
    table.cell(tb, 11, 5, na(nearP) ? "–" : str.tostring(nearH, "0"), text_color=fg, text_size=f_size(), bgcolor=chart.bg_color)
    f_key(6, "Price")
    table.cell(tb, 1, 6, inHotP > 0 ? "INSIDE A HOT ZONE  (heat " + str.tostring(inHotP, "0") + ")" : "In clear air", text_color=inHotP > 0 ? color.white : fg, text_halign=text.align_left, text_size=f_size(), bgcolor=inHotP > 0 ? f_sideC(inHotS) : chart.bg_color)
    f_key(7, "Last " + str.tostring(hRes.size()) + " hot sweeps")
    for i = 0 to 11
        color sbg = color.new(fg, 92)
        if i < hRes.size()
            color sc = hSide.get(i) == 1 ? cSell : cBuy
            sbg := hRes.get(i) == 1 ? sc : color.new(sc, 70)
        f_blk(i + 1, 7, sbg)
    f_key(8, "Stats")
    f_val(8, dRev + "   ·   " + dMag, fg)
    table.cell(tb, 0, 9, "Sweeps: solid = reversed, faded = kept going  ·  levels built on " + dTf + "  ·  in-sample", text_color=color.new(fg, 45), text_size=size.tiny, text_halign=text.align_left, bgcolor=chart.bg_color)
 
// ═════════════════════════ HUD BESIDE THE LAST CANDLE (optional) ═════════════════════════
var array<box>   hudB  = array.new<box>()
var array<label> hudL  = array.new<label>()
var array<line>  hudLn = array.new<line>()
 
f_hy(float r, float b, float t) =>
    b + (t - b) * r / 100.0
f_hbox(int l, float y1, int r, float y2, color bg) =>
    hudB.push(box.new(l, math.max(y1, y2), r, math.min(y1, y2), border_color=color(na), bgcolor=bg))
f_hlab(int x, float y, string t, string st, color bg, color tc, string s) =>
    hudL.push(label.new(x, y, t, style=st, color=bg, textcolor=tc, size=s))
 
if barstate.islast
    while hudB.size() > 0
        hudB.shift().delete()
    while hudL.size() > 0
        hudL.shift().delete()
    while hudLn.size() > 0
        hudLn.shift().delete()
    if showHud and not na(atr) and atr > 0
        float bot = close - hudH
        float top = close + hudH
        color fg  = chart.fg_color
        color dim = color.new(chart.fg_color, 40)
        color non = #00000000
        int x0 = hudX0
        int x1 = x0 + 6
        f_hlab(x0, f_hy(100, bot, top) + 0.04 * hudH, "EYE LIQUIDITY HEATMAP  ·  " + dStat, label.style_label_lower_left, dCol, dTxt, size.normal)
        if dTot > 0
            f_hbox(x0, f_hy(100, bot, top), x0 + 2, f_hy(100 - dUpS, bot, top), color.new(cSell, 20))
            f_hbox(x0, f_hy(100 - dUpS, bot, top), x0 + 2, f_hy(0, bot, top), color.new(cBuy, 20))
        else
            f_hbox(x0, f_hy(100, bot, top), x0 + 2, f_hy(0, bot, top), color.new(fg, 85))
        hudLn.push(line.new(x0 - 1, f_hy(50, bot, top), x0 + 3, f_hy(50, bot, top), color=color.new(fg, 30), width=1))
        f_hlab(x0, f_hy(97, bot, top), dTot > 0 ? "↑ " + str.tostring(dUpS, "0") + "%" : "↑ –", label.style_label_right, non, cSell, size.small)
        f_hlab(x0, f_hy(3, bot, top), dTot > 0 ? "↓ " + str.tostring(100 - dUpS, "0") + "%" : "↓ –", label.style_label_right, non, cBuy, size.small)
        f_hlab(x1, f_hy(93, bot, top), "MAGNET ↑  " + f_magTxt(magUp, magUpFar, pUp, true), label.style_label_left, non, cSell, size.small)
        f_hlab(x1, f_hy(85, bot, top), "MAGNET ↓  " + f_magTxt(magDn, magDnFar, pDn, false), label.style_label_left, non, cBuy, size.small)
        f_hlab(x1, f_hy(76, bot, top), "NEAREST HOT ZONE" + (na(nearP) ? "  –" : "  " + str.tostring(nearP, format.mintick) + "  · " + str.tostring(nearD / atr, "0.0") + " ATR"), label.style_label_left, non, dim, size.small)
        int cells = na(nearP) ? 0 : math.min(10, int(math.round(nearH / 10)))
        for i = 0 to 9
            f_hbox(x1 + 1 + i * 2, f_hy(71, bot, top), x1 + 2 + i * 2, f_hy(64, bot, top), i < cells ? f_base((i + 1) * 10, nearP > close ? 1 : -1) : color.new(fg, 90))
        f_hlab(x1 + 22, f_hy(67.5, bot, top), na(nearP) ? "" : "heat " + str.tostring(nearH, "0"), label.style_label_left, non, fg, size.small)
        f_hlab(x1, f_hy(56, bot, top), inHotP > 0 ? "PRICE INSIDE A HOT ZONE (" + str.tostring(inHotP, "0") + ")" : "Price in clear air", label.style_label_left, inHotP > 0 ? f_sideC(inHotS) : non, inHotP > 0 ? color.white : dim, size.small)
        float base = f_hy(26, bot, top)
        float hgt  = f_hy(40, bot, top) - base
        f_hlab(x1, f_hy(46, bot, top), "LAST " + str.tostring(hRes.size()) + " HOT SWEEPS", label.style_label_left, non, dim, size.small)
        hudLn.push(line.new(x1, base, x1 + 26, base, color=color.new(fg, 60), width=1))
        if hRes.size() > 0
            for i = 0 to hRes.size() - 1
                bool okR = hRes.get(i) == 1
                color sc = hSide.get(i) == 1 ? cSell : cBuy
                f_hbox(x1 + 1 + i * 2, base, x1 + 2 + i * 2, okR ? base + hgt : base - hgt * 0.5, okR ? sc : color.new(sc, 65))
        f_hlab(x1, f_hy(10, bot, top), dRev + "    " + dMag, label.style_label_left, non, fg, size.small)
        f_hlab(x1, f_hy(2, bot, top), "up = reversed · down = kept going · levels on " + dTf + " · in-sample", label.style_label_left, non, dim, size.tiny)
 
// ═════════════════════════ ALERTS ═════════════════════════
alertcondition(hotSweepUp, "Hot buy-side liquidity swept",  "Eye Liquidity Heatmap: hot buy-side liquidity swept on {{ticker}} {{interval}}")
alertcondition(hotSweepDn, "Hot sell-side liquidity swept", "Eye Liquidity Heatmap: hot sell-side liquidity swept on {{ticker}} {{interval}}")
alertcondition(magHitUp,   "Magnet above reached", "Eye Liquidity Heatmap: magnet above reached on {{ticker}} {{interval}}")
alertcondition(magHitDn,   "Magnet below reached", "Eye Liquidity Heatmap: magnet below reached on {{ticker}} {{interval}}")
bool nearUpNow = not na(magUp) and magUp - close <= 0.5 * atr
bool nearDnNow = not na(magDn) and close - magDn <= 0.5 * atr
var float lastNearUp = na
var float lastNearDn = na
bool nearUp = conf and nearUpNow and magUp != lastNearUp
bool nearDn = conf and nearDnNow and magDn != lastNearDn
if nearUp
    lastNearUp := magUp
if nearDn
    lastNearDn := magDn
alertcondition(nearUp, "Price near magnet above", "Eye Liquidity Heatmap: {{ticker}} within 0.5 ATR of the magnet above")
alertcondition(nearDn, "Price near magnet below", "Eye Liquidity Heatmap: {{ticker}} within 0.5 ATR of the magnet below")
 
if hotMsg != ""
    alert("Eye Liquidity Heatmap | " + syminfo.ticker + " | hot liquidity swept: " + hotMsg, alert.freq_once_per_bar_close)

← 返回列表