Liquidity Draw

HS_16 · study · 327 行 · 点赞 65 · TradingView 原页

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

Pine Script

//@version=6
// Liquidity Draw v2 (TradingView, Pine v6) - "Draw on Liquidity" style, built for the 1-minute chart.
// Targets (BSL / SSL pools and untouched FVGs) are found on a higher timeframe (default 15m),
// then ONE target is LOCKED on the chart and kept until price hits it, the SL breaks, or it expires.
// PoT = probability of touch: the chance a random walk with recent volatility reaches the level
// within the horizon. It is a statistical estimate, NOT a prediction of direction.
indicator("Liquidity Draw", shorttitle="LiqDraw", overlay=true, max_boxes_count=20, max_lines_count=20, max_labels_count=20)
 
// ── Inputs ─────────────────────────────────────────────
grpA = "Analysis"
tfIn       = input.timeframe("15", "Timeframe used to find targets", group=grpA)
lookback   = input.int(300, "Bars to scan (on that timeframe)", minval=50, group=grpA)
n          = input.int(3, "Swing strength (bars each side)", minval=1, group=grpA)
atrLen     = input.int(14, "ATR period", minval=1, group=grpA)
clusterATR = input.float(0.30, "Merge equal highs/lows within (x ATR)", step=0.05, group=grpA)
maxDistATR = input.float(8.0, "Ignore targets further than (x ATR)", group=grpA)
useFVG     = input.bool(true, "Use fair value gaps as targets", group=grpA)
fvgMinATR  = input.float(0.15, "Minimum FVG size (x ATR)", step=0.05, group=grpA)
 
grpS = "Signal"
biasMin  = input.float(55.0, "Min % of liquidity on one side", group=grpS)
horizon  = input.int(24, "PoT horizon (bars of analysis TF)", minval=1, group=grpS)
minPoT   = input.float(40.0, "Minimum PoT % to lock a target", group=grpS)
slBufATR = input.float(0.30, "SL buffer beyond structure (x ATR)", step=0.05, group=grpS)
minSLATR = input.float(1.0, "Minimum SL distance (x ATR)", step=0.1, group=grpS)
minRR    = input.float(1.0, "Minimum R:R to lock a target", step=0.1, group=grpS)
 
grpL = "Target lock"
holdBars   = input.int(24, "Drop target after N bars (analysis TF)", minval=1, group=grpL)
resultBars = input.int(4, "Show Hit/Invalidated for N bars (analysis TF)", minval=1, group=grpL)
 
grpD = "Display"
showSL  = input.bool(true, "Show SL line", group=grpD)
zoneExt = input.int(8, "Extend zone right (chart bars)", minval=1, maxval=200, group=grpD)
dnCol   = input.color(#E53935, "Down target colour", group=grpD)
upCol   = input.color(#00966E, "Up target colour", group=grpD)
tagBg   = input.color(#26262A, "Tag background", group=grpD)
 
// ── Maths ──────────────────────────────────────────────
erf(float x0) =>
    float s = x0 < 0 ? -1.0 : 1.0
    float x = math.abs(x0)
    float t = 1.0 / (1.0 + 0.3275911 * x)
    float y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * math.exp(-x * x)
    s * y
 
potPct(float d, float sigma, int H) =>
    float res = 0.0
    if d <= 0
        res := 100.0
    else if sigma > 0 and H > 0
        float z = d / (sigma * math.sqrt(H))
        res := 100.0 * 2.0 * (1.0 - 0.5 * (1.0 + erf(z / math.sqrt(2.0))))
    res
 
typeName(int t) =>
    t == 1 ? "BSL" : t == 2 ? "SSL" : t == 3 ? "Bear FVG" : t == 4 ? "Bull FVG" : "-"
 
// ── Higher-timeframe scan (closed bars only) ───────────
// types: 1 = BSL (above), 2 = SSL (below), 3 = Bear FVG (above), 4 = Bull FVG (below)
scan() =>
    float h  = high[1]
    float l  = low[1]
    float c  = close[1]
    float v  = nz(volume[1])
    float a  = ta.sma(ta.tr(true), atrLen)[1]
    float sg = ta.stdev(ta.change(close), 100)[1]
    float rLow  = ta.lowest(l, 2 * n + 1)
    float rHigh = ta.highest(h, 2 * n + 1)
 
    var array<float> iLo = array.new<float>()
    var array<float> iHi = array.new<float>()
    var array<float> iW  = array.new<float>()
    var array<int>   iT  = array.new<int>()
    var array<int>   iTy = array.new<int>()
    var array<int>   iB  = array.new<int>()
 
    // remove swept / touched / too old items
    if iTy.size() > 0
        for i = iTy.size() - 1 to 0
            int ty = iTy.get(i)
            float lo = iLo.get(i)
            float hi = iHi.get(i)
            bool gone = bar_index - iB.get(i) > lookback
            gone := gone or (ty == 1 and h >= hi) or (ty == 2 and l <= lo) or (ty == 3 and h >= lo) or (ty == 4 and l <= hi)
            if gone
                iLo.remove(i)
                iHi.remove(i)
                iW.remove(i)
                iT.remove(i)
                iTy.remove(i)
                iB.remove(i)
 
    // swing highs / lows
    bool ready = bar_index >= 2 * n + 3
    bool isPH = ready
    bool isPL = ready
    if ready
        for k = 1 to n
            if h[n - k] >= h[n] or h[n + k] > h[n]
                isPH := false
            if l[n - k] <= l[n] or l[n + k] < l[n]
                isPL := false
    if isPH or isPL
        float w = v[n - 1] + v[n] + v[n + 1]
        w := w > 0 ? w : 1.0
        if isPH
            iLo.push(h[n])
            iHi.push(h[n])
            iW.push(w)
            iT.push(time[n + 1])
            iTy.push(1)
            iB.push(bar_index - n - 1)
        if isPL
            iLo.push(l[n])
            iHi.push(l[n])
            iW.push(w)
            iT.push(time[n + 1])
            iTy.push(2)
            iB.push(bar_index - n - 1)
 
    // fair value gaps
    if useFVG and bar_index >= 4 and not na(a)
        float fw = v + v[1] + v[2]
        fw := fw > 0 ? fw : 1.0
        if l - h[2] >= fvgMinATR * a
            iLo.push(h[2])
            iHi.push(l)
            iW.push(fw)
            iT.push(time[2])
            iTy.push(4)
            iB.push(bar_index - 2)
        if l[2] - h >= fvgMinATR * a
            iLo.push(h)
            iHi.push(l[2])
            iW.push(fw)
            iT.push(time[2])
            iTy.push(3)
            iB.push(bar_index - 2)
 
    // pick the best target
    int   rDir = 0
    int   rTy  = 0
    float rTp  = na
    float rLo  = na
    float rHi  = na
    float rSl  = na
    int   rT   = 0
    int   sz   = iTy.size()
    if sz > 0 and not na(a) and a > 0 and not na(c) and not na(sg)
        float tol  = clusterATR * a
        float maxD = maxDistATR * a
        array<float> cLo = array.new<float>()
        array<float> cHi = array.new<float>()
        array<float> cW  = array.new<float>()
        array<int>   cT  = array.new<int>()
        array<int>   cTy = array.new<int>()
        for i = sz - 1 to 0
            int ty = iTy.get(i)
            float lo = iLo.get(i)
            float hi = iHi.get(i)
            bool up = ty == 1 or ty == 3
            float lvl = ty == 1 ? lo : ty == 2 ? hi : ty == 3 ? lo : hi
            float d = up ? lvl - c : c - lvl
            if d > 0 and d <= maxD
                int hit = -1
                int m = cTy.size()
                if ty <= 2 and m > 0
                    for k = 0 to m - 1
                        if cTy.get(k) == ty and lvl >= cLo.get(k) - tol and lvl <= cHi.get(k) + tol
                            hit := k
                            break
                if hit >= 0
                    cLo.set(hit, math.min(cLo.get(hit), lo))
                    cHi.set(hit, math.max(cHi.get(hit), hi))
                    cW.set(hit, cW.get(hit) + iW.get(i))
                    cT.set(hit, math.min(cT.get(hit), iT.get(i)))
                else
                    cLo.push(lo)
                    cHi.push(hi)
                    cW.push(iW.get(i))
                    cT.push(iT.get(i))
                    cTy.push(ty)
 
        int m2 = cTy.size()
        if m2 > 0
            float above = 0.0
            float below = 0.0
            for k = 0 to m2 - 1
                int ty = cTy.get(k)
                if ty == 1 or ty == 3
                    above += cW.get(k)
                else
                    below += cW.get(k)
            float upPct = above + below > 0 ? 100.0 * above / (above + below) : 50.0
            int bias = upPct >= biasMin ? 1 : 100.0 - upPct >= biasMin ? -1 : 0
            if bias != 0
                float stop = bias == 1 ? math.min(rLow - slBufATR * a, c - minSLATR * a) : math.max(rHigh + slBufATR * a, c + minSLATR * a)
                float risk = math.abs(c - stop)
                int best = -1
                float bestS = -1.0
                for k = 0 to m2 - 1
                    int ty = cTy.get(k)
                    bool up = ty == 1 or ty == 3
                    if (bias == 1) == up and risk > 0
                        float lvl = ty == 1 ? cLo.get(k) : ty == 2 ? cHi.get(k) : ty == 3 ? cLo.get(k) : cHi.get(k)
                        float d = up ? lvl - c : c - lvl
                        float p = potPct(d, sg, horizon)
                        if d > 0 and p >= minPoT and d / risk >= minRR
                            float s = cW.get(k) * p
                            if s > bestS
                                bestS := s
                                best := k
                if best >= 0
                    int bTy = cTy.get(best)
                    float minH = 0.12 * a
                    rDir := bias
                    rTy  := bTy
                    rTp  := bTy == 1 ? cLo.get(best) : bTy == 2 ? cHi.get(best) : bTy == 3 ? cLo.get(best) : cHi.get(best)
                    rLo  := bTy == 2 ? cLo.get(best) - minH : cLo.get(best)
                    rHi  := bTy == 1 ? cHi.get(best) + minH : cHi.get(best)
                    rSl  := stop
                    rT   := cT.get(best)
    [rDir, rTy, rTp, rLo, rHi, rT, rSl, sg]
 
[hDir, hTy, hTp, hLo, hHi, hT, hSl, hSig] = request.security(syminfo.tickerid, tfIn, scan(), lookahead=barmerge.lookahead_off)
 
// ── Locked state on the chart ──────────────────────────
// st: 0 = idle, 1 = active, 2 = hit, 3 = invalidated
var int   st       = 0
var int   dir      = 0
var int   typ      = 0
var float tp       = na
var float zlo      = na
var float zhi      = na
var float sl       = na
var float pot      = na
var float rr       = na
var int   zoneT    = 0
var int   lockT    = 0
var int   htfCount = 0
var int   lockHtf  = 0
var int   endHtf   = 0
 
bool htfNew = timeframe.change(tfIn)
 
// 1) new bar on the analysis timeframe: expiry, result timeout, PoT refresh
if htfNew
    htfCount += 1
    if st == 1
        if htfCount - lockHtf > holdBars
            st := 0
        else
            pot := potPct(math.abs(tp - close), hSig, horizon)
    if (st == 2 or st == 3) and htfCount - endHtf > resultBars
        st := 0
 
// 2) hit / invalidation on every chart bar (SL checked first = conservative)
if st == 1
    bool slHit = dir == 1 ? low <= sl : high >= sl
    bool tpHit = dir == 1 ? high >= tp : low <= tp
    if slHit
        st := 3
        endHtf := htfCount
        alert("Liquidity Draw " + syminfo.ticker + ": " + typeName(typ) + " INVALIDATED (SL " + str.tostring(sl, format.mintick) + ")", alert.freq_once_per_bar)
    else if tpHit
        st := 2
        endHtf := htfCount
        alert("Liquidity Draw " + syminfo.ticker + ": " + typeName(typ) + " " + str.tostring(tp, format.mintick) + " target HIT", alert.freq_once_per_bar)
 
// 3) lock a new target on a closed chart bar
if st == 0 and barstate.isconfirmed and hDir != 0 and not na(hTp) and not na(hSl)
    float d    = hDir == 1 ? hTp - close : close - hTp
    float risk = hDir == 1 ? close - hSl : hSl - close
    if d > 0 and risk > 0
        float p = potPct(d, hSig, horizon)
        float r = d / risk
        if p >= minPoT and r >= minRR
            st      := 1
            dir     := hDir
            typ     := hTy
            tp      := hTp
            zlo     := hLo
            zhi     := hHi
            sl      := hSl
            pot     := p
            rr      := r
            zoneT   := hT
            lockT   := time
            lockHtf := htfCount
            alert("Liquidity Draw " + syminfo.ticker + ": new target " + typeName(typ) + " " + str.tostring(tp, format.mintick) + (dir == 1 ? " (UP)" : " (DOWN)") + "  PoT " + str.tostring(pot, "#.#") + "%  SL " + str.tostring(sl, format.mintick) + "  R:R " + str.tostring(rr, "#.#"), alert.freq_once_per_bar)
 
// ── Drawing ────────────────────────────────────────────
var box   zBox  = na
var line  zMid  = na
var line  zPath = na
var line  zSl   = na
var label zTag  = na
var label zSlT  = na
var label zArr  = na
 
if barstate.islast
    box.delete(zBox)
    line.delete(zMid)
    line.delete(zPath)
    line.delete(zSl)
    label.delete(zTag)
    label.delete(zSlT)
    label.delete(zArr)
    if st != 0
        color col = st == 3 ? color.gray : dir == 1 ? upCol : dnCol
        int tR = time + zoneExt * timeframe.in_seconds() * 1000
        int tL = zoneT > 0 and zoneT < time ? zoneT : time
        zBox := box.new(tL, zhi, tR, zlo, xloc=xloc.bar_time, border_color=color.new(col, 70), bgcolor=color.new(col, 80))
        zMid := line.new(tL, tp, tR, tp, xloc=xloc.bar_time, color=col, width=2)
        if lockT > 0
            zArr := label.new(lockT, close, "", xloc=xloc.bar_time, yloc=dir == 1 ? yloc.belowbar : yloc.abovebar, style=dir == 1 ? label.style_arrowup : label.style_arrowdown, color=col, size=size.normal)
        string txt = "Target: " + typeName(typ)
        if st == 1
            txt += "\nPoT: " + str.tostring(pot, "#.0") + "%\nR:R " + str.tostring(rr, "#.0")
            zPath := line.new(time, close, tR, tp, xloc=xloc.bar_time, color=col, width=1, style=line.style_dashed)
            if showSL
                zSl  := line.new(lockT, sl, tR, sl, xloc=xloc.bar_time, color=col, width=1, style=line.style_dotted)
                zSlT := label.new(tR, sl, "SL " + str.tostring(sl, format.mintick), xloc=xloc.bar_time, style=label.style_none, textcolor=col, size=size.small, textalign=text.align_left)
        else
            txt += st == 2 ? "\nTarget hit" : "\nInvalidated"
        zTag := label.new(tR, tp, txt, xloc=xloc.bar_time, style=label.style_label_left, color=tagBg, textcolor=col, size=size.normal, textalign=text.align_left)

← 返回列表