Liquidity Map | Sattam

S4tt4m · study · 796 行 · 点赞 119 · TradingView 原页

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

Pine Script

//@version=6
indicator("Liquidity Map | Sattam", "Liquidity Map", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 100)
 
// ─────────────────────────────────────────────────────────────────────────────
// Liquidity Map — four independent modules that map resting liquidity:
//   ① Pivot Rays          rays from fractal highs/lows, removed once traded through,
//                         numbered series of consecutive higher lows / lower highs
//   ② Session Highs/Lows  dotted high and low of each session, series, trade level line
//   ③ Resting Stops       equal highs / lows with touch count, dashed until swept
//   ④ TPO Poor Highs/Lows session TPO profile, poor extremes (≥ N periods on the extreme row)
// Shared rules: pivot = strictly above every bar on the left and at least equal to every bar on
// the right; a level is swept the first time a wick trades strictly through it; a series is a
// run of chronologically consecutive active levels, each beyond the previous, within a closeness
// band and with a clear gap before the next level on the far side. Numbers count from the newest
// member (1) to the oldest, which is the trade level. A series stays armed until its trade level
// is traded through, even after the members in front of it are swept; only a newer series replaces it.
// ─────────────────────────────────────────────────────────────────────────────
 
// ═══════════════════════════════════ INPUTS ══════════════════════════════════
G1 = "① Pivot Rays"
m1On    = input.bool(true, "Enable", group = G1)
m1Left  = input.int(3, "Pivot left / right", minval = 1, maxval = 50, group = G1, inline = "m1p", tooltip = "Bars on each side of a fractal high/low")
m1Right = input.int(3, "", minval = 1, maxval = 50, group = G1, inline = "m1p")
m1ColH  = input.color(#D9A441, "Ray colors: highs / lows", group = G1, inline = "m1c")
m1ColL  = input.color(#4CAF7D, "", group = G1, inline = "m1c")
m1Width = input.int(1, "Width", minval = 1, maxval = 4, group = G1)
m1Swept = input.string("Hide", "Swept rays", options = ["Hide", "Keep dimmed"], group = G1)
m1Max   = input.int(50, "Max rays per side", minval = 5, maxval = 200, group = G1)
m1SerOn = input.bool(true, "Series numbering", group = G1)
m1Min   = input.int(3, "Series: min count", minval = 2, maxval = 10, group = G1)
m1Close = input.float(2.0, "Series: closeness (× ATR)", minval = 0.1, step = 0.1, group = G1)
m1Gap   = input.float(2.0, "Series: gap before (× ATR)", minval = 0.1, step = 0.1, group = G1)
m1BoxCol = input.color(#F5C518, "Trade level box", group = G1)
 
G2 = "② Session Highs / Lows"
m2On    = input.bool(true, "Enable", group = G2)
m2Tz    = input.string("UTC", "Timezone", options = ["UTC", "Exchange", "America/New_York", "Europe/London", "Asia/Riyadh", "Asia/Dubai", "Asia/Tokyo", "Australia/Sydney"], group = G2)
s1On    = input.bool(true, "", group = G2, inline = "s1")
s1Name  = input.string("Asia", "", group = G2, inline = "s1")
s1Rng   = input.session("0000-0800", "", group = G2, inline = "s1")
s2On    = input.bool(true, "", group = G2, inline = "s2")
s2Name  = input.string("London", "", group = G2, inline = "s2")
s2Rng   = input.session("0800-1600", "", group = G2, inline = "s2")
s3On    = input.bool(true, "", group = G2, inline = "s3")
s3Name  = input.string("New York", "", group = G2, inline = "s3")
s3Rng   = input.session("1600-0000", "", group = G2, inline = "s3")
m2ColH  = input.color(#26A69A, "Session high / low", group = G2, inline = "m2c")
m2ColL  = input.color(#EF5350, "", group = G2, inline = "m2c")
m2Width = input.int(1, "Width", minval = 1, maxval = 4, group = G2)
m2ExtAll = input.bool(false, "Extend every untested level", group = G2)
m2Max   = input.int(40, "Max session levels per side", minval = 5, maxval = 200, group = G2)
m2SerOn = input.bool(true, "Series numbering", group = G2)
m2Min   = input.int(3, "Series: min count", minval = 2, maxval = 10, group = G2)
m2Close = input.float(2.0, "Series: closeness (× ATR)", minval = 0.1, step = 0.1, group = G2)
m2Gap   = input.float(2.0, "Series: gap before (× ATR)", minval = 0.1, step = 0.1, group = G2)
m2TradeAuto = input.bool(true, "Trade level line follows theme", group = G2, inline = "m2t")
m2TradeCol  = input.color(#1E1E1E, "", group = G2, inline = "m2t")
 
G3 = "③ Resting Stops (equal highs / lows)"
m3On    = input.bool(true, "Enable", group = G3)
m3Left  = input.int(2, "Pivot left / right", minval = 1, maxval = 50, group = G3, inline = "m3p")
m3Right = input.int(2, "", minval = 1, maxval = 50, group = G3, inline = "m3p")
m3TolMode = input.string("ATR ×", "Tolerance", options = ["ATR ×", "Ticks"], group = G3, inline = "m3t", tooltip = "Equal-level tolerance: ATR multiple, or a number of ticks")
m3TolAtr  = input.float(0.10, "", minval = 0.01, step = 0.01, group = G3, inline = "m3t")
m3TolTicks = input.int(5, "", minval = 1, group = G3, inline = "m3t")
m3MinT  = input.int(2, "Min touches", minval = 2, maxval = 10, group = G3)
m3Col   = input.color(#787B86, "Line / sweep ▼ / sweep ▲", group = G3, inline = "m3c")
m3ArrH  = input.color(#EF5350, "", group = G3, inline = "m3c")
m3ArrL  = input.color(#26A69A, "", group = G3, inline = "m3c")
m3Width = input.int(1, "Width", minval = 1, maxval = 4, group = G3)
m3Max   = input.int(15, "Max active pools per side", minval = 1, maxval = 100, group = G3)
m3Keep  = input.int(5, "Swept pools kept per side", minval = 0, maxval = 100, group = G3)
 
G4 = "④ TPO Poor Highs / Lows"
m4On    = input.bool(true, "Enable", group = G4)
m4Mode  = input.string("Daily", "Profile per", options = ["Daily", "Sessions (②)"], group = G4)
m4RowMode = input.string("Auto", "Row size", options = ["Auto", "Ticks"], group = G4, inline = "m4r", tooltip = "Auto: session range ÷ rows (min 1 tick). Ticks: fixed row height")
m4Rows  = input.int(30, "", minval = 5, maxval = 200, group = G4, inline = "m4r")
m4RowTicks = input.int(10, "", minval = 1, group = G4, inline = "m4r")
m4Per   = input.int(30, "TPO period (minutes)", minval = 1, maxval = 1440, group = G4, tooltip = "Bars inside the same period count as one TPO. Charts above this period use one TPO per bar")
m4MinC  = input.int(2, "Min periods on the extreme row", minval = 2, maxval = 20, group = G4)
m4ColH  = input.color(#EF5350, "Poor high / low", group = G4, inline = "m4c")
m4ColL  = input.color(#26A69A, "", group = G4, inline = "m4c")
m4Width = input.int(1, "Width", minval = 1, maxval = 4, group = G4)
m4Max   = input.int(20, "Max levels per side", minval = 5, maxval = 100, group = G4)
m4SerOn = input.bool(false, "Series numbering", group = G4)
m4Min   = input.int(3, "Series: min count", minval = 2, maxval = 10, group = G4)
m4Close = input.float(2.0, "Series: closeness (× ATR)", minval = 0.1, step = 0.1, group = G4)
m4Gap   = input.float(2.0, "Series: gap before (× ATR)", minval = 0.1, step = 0.1, group = G4)
 
G5 = "Dashboard"
dbOn   = input.bool(true, "Show dashboard", group = G5)
dbPos  = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = G5)
dbSize = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = G5)
// declared last so the ids of the inputs above never move
m2Names = input.bool(true, "Session names", group = G2, tooltip = "Shown on 15-minute and lower charts, where a session is wide enough for its name")
dispMult = input.float(12.0, "Display range (× ATR, 0 = everything)", minval = 0, step = 1, group = "Display", tooltip = "Levels farther than this from the last price are folded away so they do not stretch the price scale. They return when price comes back. Detection, counts and alerts are not affected")
 
// ═══════════════════════════════════ TYPES ═══════════════════════════════════
type Level
    float price
    int   bar          // anchor bar: pivot bar / session start / first touch / session end (TPO)
    int   endBar       // sweeps are checked strictly after this bar
    bool  isHigh
    int   touches
    float tol          // tolerance in whole ticks (resting stops), 0 elsewhere
    int   swept        // bar index of the sweep, -1 while active
    line  ln
    label lb
    label mk = na      // sweep marker (resting stops)
    int   t0 = na      // anchor time (session levels), for drawings that may start far back
 
type Sess
    bool  active
    int   startBar
    float hi
    float lo
    line  lnH
    line  lnL
    array<float> highs
    array<float> lows
    array<int>   keys         // TPO period key of each bar
    label lbN = na            // session name on the running high
    int   t0 = na             // open time of the session's first bar
 
// ═══════════════════════════════════ SHARED ══════════════════════════════════
float atrV = ta.atr(14)
string tzStr = m2Tz == "Exchange" ? syminfo.timezone : m2Tz
color fg = chart.fg_color
color tradeLineCol = m2TradeAuto ? fg : m2TradeCol
string tfKey = timeframe.period
// drawings cannot be anchored more than ~10000 bars back: older anchors are clipped to this bar
oldestX() =>
    bar_index - 9000
// inside the display range of the last price
isNear(float p) =>
    dispMult == 0 or math.abs(p - close) <= dispMult * atrV
int dayKey = year(time, tzStr) * 10000 + month(time, tzStr) * 100 + dayofmonth(time, tzStr)
int tpoKey = int(math.floor(time / (m4Per * 60000.0)))
bool tfRecommended = tfKey == "5" or tfKey == "15" or tfKey == "60" or tfKey == "240" or tfKey == "D" or tfKey == "1D"
 
// pivot candidate at bar_index - right: strictly above the left bars, at least equal to the right bars
isPivot(bool isHigh, int left, int right) =>
    bool ok = bar_index >= left + right
    if ok
        float v = isHigh ? high[right] : low[right]
        for k = 1 to left
            float x = isHigh ? high[right + k] : low[right + k]
            if isHigh ? x >= v : x <= v
                ok := false
                break
        if ok and right > 0
            for k = 0 to right - 1
                float x = isHigh ? high[k] : low[k]
                if isHigh ? x > v : x < v
                    ok := false
                    break
    ok
 
// marks levels traded through on this bar (strict wick break, after endBar)
markSweeps(array<Level> lv) =>
    bool any = false
    int n = lv.size()
    if n > 0
        for k = 0 to n - 1
            Level L = lv.get(k)
            if L.swept < 0 and bar_index > L.endBar
                // with a tolerance the distance is measured in whole ticks, so float noise cannot decide the edge
                bool hit = L.tol == 0 ? (L.isHigh ? high > L.price : low < L.price) : (L.isHigh ? math.round((high - L.price) / syminfo.mintick) > L.tol : math.round((L.price - low) / syminfo.mintick) > L.tol)
                if hit
                    L.swept := bar_index
                    any := true
    any
 
// series of consecutive higher lows (lower highs) among active levels; returns indexes newest-first
findSeries(array<Level> lv, bool isHigh, int minCount, float closeMult, float gapMult) =>
    array<int> act = array.new<int>()
    array<int> out = array.new<int>()
    if lv.size() > 0
        for k = 0 to lv.size() - 1
            if lv.get(k).swept < 0
                act.push(k)
    int n = act.size()
    float sgn = isHigh ? -1.0 : 1.0
    int bestS = -1
    int bestE = -1
    if n > 0 and atrV > 0
        for s = 0 to n - 1
            int e = s
            float ps = lv.get(act.get(s)).price
            while e + 1 < n
                float pe = lv.get(act.get(e)).price
                float pn = lv.get(act.get(e + 1)).price
                if sgn * (pn - pe) > 0 and math.abs(pn - ps) <= closeMult * atrV
                    e += 1
                else
                    break
            if e - s + 1 >= minCount
                float gap = 1.0e300
                for k = 0 to n - 1
                    float d = sgn * (ps - lv.get(act.get(k)).price)
                    if d > 0
                        gap := math.min(gap, d)
                if gap >= gapMult * atrV
                    bestS := s
                    bestE := e
    if bestS >= 0
        for k = bestE to bestS
            out.push(act.get(k))
    out
 
circled(int n) =>
    switch n
        1 => "❶"
        2 => "❷"
        3 => "❸"
        4 => "❹"
        5 => "❺"
        6 => "❻"
        7 => "❼"
        8 => "❽"
        9 => "❾"
        10 => "❿"
        => str.tostring(n)
 
// index of the level anchored at `anchor`, -1 when it is no longer kept
levelAt(array<Level> lv, int anchor) =>
    int idx = -1
    if lv.size() > 0
        for k = lv.size() - 1 to 0
            if lv.get(k).bar == anchor
                idx := k
                break
    idx
 
// A qualifying series stays armed until its trade level is traded through, even after the members
// in front of it are swept one by one. `armed` holds the anchor bars of the members, newest first;
// the last one is the trade level.
// Call right after markSweeps, before swept levels are removed: true when the armed trade level was swept now.
armedSwept(array<Level> lv, array<int> armed) =>
    bool hit = false
    if armed.size() > 0
        int idx = levelAt(lv, armed.last())
        if idx < 0
            armed.clear()
        else if lv.get(idx).swept == bar_index
            hit := true
            armed.clear()
    hit
 
// Call after findSeries: arms the qualifying series; true when its trade level is a new one.
// An armed series is only replaced by a newer one (or refreshed when it grows); an older series
// that qualifies again waits until the armed trade level is swept.
armSeries(array<Level> lv, array<int> ser, array<int> armed) =>
    bool formed = false
    int tb = ser.size() > 0 ? lv.get(ser.last()).bar : -1
    if tb >= 0 and (armed.size() == 0 or tb >= armed.last())
        formed := armed.size() == 0 or armed.last() != tb
        armed.clear()
        for k in ser
            armed.push(lv.get(k).bar)
    else if armed.size() > 0
        if levelAt(lv, armed.last()) < 0
            armed.clear()
    formed
 
// redraws the numbered circles of the armed series (1 = newest) and the box around the trade level
drawSeries(array<Level> lv, array<int> armed, array<label> labs, box bx, bool showNums, color boxCol) =>
    if labs.size() > 0
        for lb in labs
            label.delete(lb)
        labs.clear()
    box.delete(bx)
    box nb = na
    if armed.size() > 0 and showNums
        int px = na
        for k = armed.size() - 1 to 0          // trade level first, so the numbers step to the right
            int idx = levelAt(lv, armed.get(k))
            if idx >= 0
                Level L = lv.get(idx)
                // on the line: middle of a session's segment, 4 bars right of a pivot
                int base = L.bar == L.endBar ? L.bar + 4 : int(math.floor((L.bar + L.endBar) / 2))
                int x = math.max(na(px) ? base : math.max(base, px + 6), oldestX())
                px := x
                if isNear(L.price)
                    labs.push(label.new(x, L.price, circled(k + 1), xloc.bar_index, yloc.price, color(na), label.style_none, fg, size.large))
        int ti = levelAt(lv, armed.last())
        if ti >= 0 and isNear(lv.get(ti).price)
            Level T = lv.get(ti)
            float h = 0.2 * atrV
            nb := box.new(bar_index - 8, T.price + h, bar_index + 4, T.price - h, border_color = boxCol, border_width = 2, bgcolor = color.new(boxCol, 90))
    nb
 
pruneLevels(array<Level> lv, int maxN) =>
    while lv.size() > maxN
        Level L = lv.shift()
        line.delete(L.ln)
        label.delete(L.lb)
        label.delete(L.mk)
 
dimLine(line ln, color c) =>
    line.set_extend(ln, extend.none)
    line.set_x2(ln, bar_index)
    line.set_color(ln, color.new(c, 50))
 
// ═══════════════════════════════ ① PIVOT RAYS ════════════════════════════════
var array<Level> m1H = array.new<Level>()
var array<Level> m1L = array.new<Level>()
var array<int> m1ArmH = array.new<int>()
var array<int> m1ArmL = array.new<int>()
var array<label> m1LabsH = array.new<label>()
var array<label> m1LabsL = array.new<label>()
var box m1BoxH = na
var box m1BoxL = na
bool m1NewSeries  = false
bool m1TradeSwept = false
 
// removes (or dims) the rays swept on this bar
m1Handle(array<Level> lv, color c) =>
    int n = 0
    if lv.size() > 0
        for k = lv.size() - 1 to 0
            Level L = lv.get(k)
            if L.swept == bar_index
                n += 1
                if m1Swept == "Hide"
                    line.delete(L.ln)
                    label.delete(L.lb)
                    lv.remove(k)
                else
                    dimLine(L.ln, c)
    n
 
if m1On
    // (a) sweeps
    markSweeps(m1H)
    markSweeps(m1L)
    bool hitH = armedSwept(m1H, m1ArmH)
    bool hitL = armedSwept(m1L, m1ArmL)
    m1TradeSwept := hitH or hitL
    m1Handle(m1H, m1ColH)
    m1Handle(m1L, m1ColL)
    // (b) new pivots
    if isPivot(true, m1Left, m1Right)
        int pb = bar_index - m1Right
        float p = high[m1Right]
        m1H.push(Level.new(p, pb, pb, true, 1, 0.0, -1, line.new(pb, p, pb + 1, p, xloc.bar_index, extend.right, m1ColH, line.style_solid, m1Width), na))
    if isPivot(false, m1Left, m1Right)
        int pb = bar_index - m1Right
        float p = low[m1Right]
        m1L.push(Level.new(p, pb, pb, false, 1, 0.0, -1, line.new(pb, p, pb + 1, p, xloc.bar_index, extend.right, m1ColL, line.style_solid, m1Width), na))
    pruneLevels(m1H, m1Max)
    pruneLevels(m1L, m1Max)
    // (c) series
    bool fH = armSeries(m1H, findSeries(m1H, true, m1Min, m1Close, m1Gap), m1ArmH)
    bool fL = armSeries(m1L, findSeries(m1L, false, m1Min, m1Close, m1Gap), m1ArmL)
    m1NewSeries := fH or fL
    m1BoxH := drawSeries(m1H, m1ArmH, m1LabsH, m1BoxH, m1SerOn, m1BoxCol)
    m1BoxL := drawSeries(m1L, m1ArmL, m1LabsL, m1BoxL, m1SerOn, m1BoxCol)
 
// ═══════════════════════════ ② SESSION HIGHS / LOWS ══════════════════════════
bool m2Run = m2On and not timeframe.isdwm
var array<Sess> sess = array.new<Sess>()
if barstate.isfirst
    for k = 0 to 3   // 0..2 = sessions ①②③, 3 = daily group for TPO
        sess.push(Sess.new(false, 0, na, na, na, na, array.new<float>(), array.new<float>(), array.new<int>()))
var array<Level> m2H = array.new<Level>()
var array<Level> m2L = array.new<Level>()
var array<int> m2ArmH = array.new<int>()
var array<int> m2ArmL = array.new<int>()
var array<label> m2LabsH = array.new<label>()
var array<label> m2LabsL = array.new<label>()
var box m2BoxH = na
var box m2BoxL = na
var int m2TradeH = -1
var int m2TradeL = -1
var line m2TradeLnH = na
var line m2TradeLnL = na
var array<line> m2FrozenH = array.new<line>()   // trade lines frozen at their sweep bar
var array<line> m2FrozenL = array.new<line>()
bool m2NewSeries  = false
bool m2TradeSwept = false
 
bool in1 = s1On and not na(time(timeframe.period, s1Rng, tzStr))
bool in2 = s2On and not na(time(timeframe.period, s2Rng, tzStr))
bool in3 = s3On and not na(time(timeframe.period, s3Rng, tzStr))
 
// one step of a session tracker; draws the running dotted lines, returns true on the bar the session closes
sessStep(Sess s, bool inside, bool draw, string nm) =>
    bool closed = false
    if inside
        if not s.active
            s.active := true
            s.startBar := bar_index
            s.t0 := time
            s.hi := high
            s.lo := low
            s.highs.clear()
            s.lows.clear()
            s.keys.clear()
            if draw
                s.lnH := line.new(bar_index, high, bar_index, high, xloc.bar_index, extend.none, m2ColH, line.style_dotted, m2Width)
                s.lnL := line.new(bar_index, low, bar_index, low, xloc.bar_index, extend.none, m2ColL, line.style_dotted, m2Width)
                s.lbN := m2Names and timeframe.in_seconds() <= 900 ? label.new(bar_index, high, nm, xloc.bar_index, yloc.price, color(na), label.style_label_lower_left, color.new(m2ColH, 30), size.tiny) : na
        else
            s.hi := math.max(s.hi, high)
            s.lo := math.min(s.lo, low)
            if draw
                line.set_xy1(s.lnH, s.startBar, s.hi)
                line.set_xy2(s.lnH, bar_index, s.hi)
                line.set_xy1(s.lnL, s.startBar, s.lo)
                line.set_xy2(s.lnL, bar_index, s.lo)
                label.set_y(s.lbN, s.hi)
        s.highs.push(high)
        s.lows.push(low)
        s.keys.push(tpoKey)
    else if s.active
        s.active := false
        closed := true
    closed
 
// trade level line of the armed session series (time coordinates): starts at the trade level's session, follows the
// last bar while armed, is frozen at the sweep bar, and is removed when the series is replaced
m2TradeLine(array<Level> lv, array<int> armed, int prevTrade, line prevLn) =>
    int tb = armed.size() > 0 ? armed.last() : -1
    line ln = prevLn
    if tb != prevTrade
        line.delete(ln)
        ln := na
        int ti = tb >= 0 ? levelAt(lv, tb) : -1
        if ti >= 0
            Level T = lv.get(ti)
            ln := line.new(T.t0, T.price, time, T.price, xloc.bar_time, extend.none, tradeLineCol, line.style_solid, m2Width)
    else if not na(ln)
        line.set_x2(ln, time)
    [tb, ln]
 
// with "Extend every untested level": cuts the extended line at the sweep bar
m2Handle(array<Level> lv) =>
    int n = 0
    if lv.size() > 0
        for k = 0 to lv.size() - 1
            Level L = lv.get(k)
            if L.swept == bar_index
                n += 1
                if m2ExtAll
                    line.set_extend(L.ln, extend.none)
                    line.set_x2(L.ln, bar_index)
    n
 
if m2Run
    // close / open sessions, collect levels
    bool c1 = sessStep(sess.get(0), in1, true, s1Name)
    bool c2 = sessStep(sess.get(1), in2, true, s2Name)
    bool c3 = sessStep(sess.get(2), in3, true, s3Name)
    for k = 0 to 2
        bool c = k == 0 ? c1 : k == 1 ? c2 : c3
        if c
            Sess s = sess.get(k)
            if m2ExtAll
                line.set_extend(s.lnH, extend.right)
                line.set_extend(s.lnL, extend.right)
            Level LH = Level.new(s.hi, s.startBar, bar_index - 1, true, 1, 0.0, -1, s.lnH, s.lbN)
            Level LL = Level.new(s.lo, s.startBar, bar_index - 1, false, 1, 0.0, -1, s.lnL, na)
            LH.t0 := s.t0
            LL.t0 := s.t0
            s.lbN := na
            m2H.push(LH)
            m2L.push(LL)
    pruneLevels(m2H, m2Max)
    pruneLevels(m2L, m2Max)
    // sweeps
    markSweeps(m2H)
    markSweeps(m2L)
    bool hitH = armedSwept(m2H, m2ArmH)
    bool hitL = armedSwept(m2L, m2ArmL)
    m2TradeSwept := hitH or hitL
    m2Handle(m2H)
    m2Handle(m2L)
    if hitH
        if not na(m2TradeLnH)
            line.set_x2(m2TradeLnH, time)
            m2FrozenH.push(m2TradeLnH)
            if m2FrozenH.size() > 10
                line.delete(m2FrozenH.shift())
        m2TradeLnH := na
        m2TradeH := -1
    if hitL
        if not na(m2TradeLnL)
            line.set_x2(m2TradeLnL, time)
            m2FrozenL.push(m2TradeLnL)
            if m2FrozenL.size() > 10
                line.delete(m2FrozenL.shift())
        m2TradeLnL := na
        m2TradeL := -1
    // series
    bool fH = armSeries(m2H, findSeries(m2H, true, m2Min, m2Close, m2Gap), m2ArmH)
    bool fL = armSeries(m2L, findSeries(m2L, false, m2Min, m2Close, m2Gap), m2ArmL)
    m2NewSeries := fH or fL
    m2BoxH := drawSeries(m2H, m2ArmH, m2LabsH, m2BoxH, m2SerOn, m1BoxCol)
    m2BoxL := drawSeries(m2L, m2ArmL, m2LabsL, m2BoxL, m2SerOn, m1BoxCol)
    [nTH, lnH] = m2TradeLine(m2H, m2ArmH, m2TradeH, m2TradeLnH)
    [nTL, lnL] = m2TradeLine(m2L, m2ArmL, m2TradeL, m2TradeLnL)
    m2TradeH := nTH
    m2TradeL := nTL
    m2TradeLnH := lnH
    m2TradeLnL := lnL
else
    // keep the session trackers in sync for ④ even when ② is off
    sessStep(sess.get(0), in1, false, s1Name)
    sessStep(sess.get(1), in2, false, s2Name)
    sessStep(sess.get(2), in3, false, s3Name)
 
// ═══════════════════════════════ ③ RESTING STOPS ═════════════════════════════
var array<Level> m3H = array.new<Level>()
var array<Level> m3L = array.new<Level>()
bool m3Swept = false
 
m3PoolDraw(Level P) =>
    color c = m3Col
    int x = math.max(P.bar, oldestX())
    P.ln := line.new(x, P.price, x + 1, P.price, xloc.bar_index, extend.right, c, line.style_dashed, m3Width)
    P.lb := label.new(x, P.price, str.tostring(P.touches) + "x resting stops", xloc.bar_index, yloc.price, color(na), P.isHigh ? label.style_label_lower_left : label.style_label_upper_left, c, size.small)
 
m3Handle(array<Level> lv) =>
    bool any = false
    if lv.size() > 0
        for k = lv.size() - 1 to 0
            Level P = lv.get(k)
            if P.swept == bar_index
                if P.touches >= m3MinT
                    any := true
                    line.set_extend(P.ln, extend.none)
                    line.set_x2(P.ln, bar_index)
                    if P.isHigh
                        P.mk := label.new(bar_index, high, "↓", xloc.bar_index, yloc.price, color(na), label.style_label_down, m3ArrH, size.huge)
                    else
                        P.mk := label.new(bar_index, low, "↑", xloc.bar_index, yloc.price, color(na), label.style_label_up, m3ArrL, size.huge)
                else
                    lv.remove(k)
    any
 
// drawn pools: the newest m3Max active and the newest m3Keep swept stay; candidates are capped at 400
m3Prune(array<Level> lv) =>
    int act = 0
    int swp = 0
    if lv.size() > 0
        for k = lv.size() - 1 to 0
            Level P = lv.get(k)
            if P.touches >= m3MinT
                bool drop = false
                if P.swept < 0
                    act += 1
                    drop := act > m3Max
                else
                    swp += 1
                    drop := swp > m3Keep
                if drop
                    line.delete(P.ln)
                    label.delete(P.lb)
                    label.delete(P.mk)
                    lv.remove(k)
    pruneLevels(lv, 400)
 
m3Add(array<Level> lv, bool isHigh, int pb, float price) =>
    float tol = m3TolMode == "Ticks" ? m3TolTicks : math.max(1, math.round(m3TolAtr * nz(atrV) / syminfo.mintick))
    int found = -1
    if lv.size() > 0
        for k = 0 to lv.size() - 1
            Level P = lv.get(k)
            if P.swept < 0 and math.round(math.abs(price - P.price) / syminfo.mintick) <= P.tol
                found := k
                break
    if found >= 0
        Level P = lv.get(found)
        P.touches += 1
        if P.touches == m3MinT
            m3PoolDraw(P)
        if P.touches > m3MinT
            label.set_text(P.lb, str.tostring(P.touches) + "x resting stops")
    else
        lv.push(Level.new(price, pb, pb, isHigh, 1, tol, -1, na, na))
 
if m3On
    markSweeps(m3H)
    markSweeps(m3L)
    bool sH = m3Handle(m3H)
    bool sL = m3Handle(m3L)
    m3Swept := sH or sL
    if isPivot(true, m3Left, m3Right)
        m3Add(m3H, true, bar_index - m3Right, high[m3Right])
    if isPivot(false, m3Left, m3Right)
        m3Add(m3L, false, bar_index - m3Right, low[m3Right])
    m3Prune(m3H)
    m3Prune(m3L)
 
// ═══════════════════════════ ④ TPO POOR HIGHS / LOWS ═════════════════════════
bool m4Run = m4On and timeframe.isintraday
var array<Level> m4H = array.new<Level>()
var array<Level> m4L = array.new<Level>()
var array<int> m4ArmH = array.new<int>()
var array<int> m4ArmL = array.new<int>()
var array<label> m4LabsH = array.new<label>()
var array<label> m4LabsL = array.new<label>()
var box m4BoxH = na
var box m4BoxL = na
bool m4Revisit = false
 
 
m4Finish(array<float> hs, array<float> ls, array<int> ks, int endBar) =>
    if hs.size() > 0
        float hi = hs.max()
        float lo = ls.min()
        float tick = syminfo.mintick
        // row height in whole ticks; distances are compared in ticks so float noise cannot move a bar across the row edge
        int rowT = m4RowMode == "Ticks" ? m4RowTicks : math.max(1, int(math.round((hi - lo) / m4Rows / tick)))
        int cH = 0
        int cL = 0
        int lastH = -1
        int lastL = -1
        for k = 0 to hs.size() - 1
            int key = ks.get(k)
            if math.round((hi - hs.get(k)) / tick) <= rowT and key != lastH
                cH += 1
                lastH := key
            if math.round((ls.get(k) - lo) / tick) <= rowT and key != lastL
                cL += 1
                lastL := key
        // the line starts at the bar that printed the extreme, so a folded level never sits away from its candles
        int first = endBar - hs.size() + 1
        int xH = math.max(first + hs.indexof(hi), oldestX())
        int xL = math.max(first + ls.indexof(lo), oldestX())
        if cH >= m4MinC
            line ln = line.new(xH, hi, xH + 1, hi, xloc.bar_index, extend.right, m4ColH, line.style_solid, m4Width)
            label lb = label.new(xH, hi, "Poor High ×" + str.tostring(cH), xloc.bar_index, yloc.price, color(na), label.style_label_lower_left, m4ColH, size.small)
            m4H.push(Level.new(hi, endBar, endBar, true, cH, 0.0, -1, ln, lb))
        if cL >= m4MinC
            line ln = line.new(xL, lo, xL + 1, lo, xloc.bar_index, extend.right, m4ColL, line.style_solid, m4Width)
            label lb = label.new(xL, lo, "Poor Low ×" + str.tostring(cL), xloc.bar_index, yloc.price, color(na), label.style_label_upper_left, m4ColL, size.small)
            m4L.push(Level.new(lo, endBar, endBar, false, cL, 0.0, -1, ln, lb))
 
m4Handle(array<Level> lv, color c) =>
    bool any = false
    if lv.size() > 0
        for k = 0 to lv.size() - 1
            Level L = lv.get(k)
            if L.swept == bar_index
                any := true
                dimLine(L.ln, c)
    any
 
if m4Run
    // close groups first (a group closes on the first bar outside it), then sweeps, then series
    if m4Mode == "Daily"
        Sess d = sess.get(3)
        bool newDay = bar_index > 0 and dayKey != dayKey[1]
        if newDay
            m4Finish(d.highs, d.lows, d.keys, bar_index - 1)
            d.highs.clear()
            d.lows.clear()
            d.keys.clear()
        d.highs.push(high)
        d.lows.push(low)
        d.keys.push(tpoKey)
    else
        for k = 0 to 2
            Sess s = sess.get(k)
            bool inside = k == 0 ? in1 : k == 1 ? in2 : in3
            // sessStep already ran this bar: a session that closed now is inactive with its arrays intact
            bool closedNow = not inside and not s.active and s.highs.size() > 0 and s.startBar + s.highs.size() == bar_index
            if closedNow
                m4Finish(s.highs, s.lows, s.keys, bar_index - 1)
    pruneLevels(m4H, m4Max)
    pruneLevels(m4L, m4Max)
    markSweeps(m4H)
    markSweeps(m4L)
    armedSwept(m4H, m4ArmH)
    armedSwept(m4L, m4ArmL)
    bool rH = m4Handle(m4H, m4ColH)
    bool rL = m4Handle(m4L, m4ColL)
    m4Revisit := rH or rL
    armSeries(m4H, findSeries(m4H, true, m4Min, m4Close, m4Gap), m4ArmH)
    armSeries(m4L, findSeries(m4L, false, m4Min, m4Close, m4Gap), m4ArmL)
    m4BoxH := drawSeries(m4H, m4ArmH, m4LabsH, m4BoxH, m4SerOn, m1BoxCol)
    m4BoxL := drawSeries(m4L, m4ArmL, m4LabsL, m4BoxL, m4SerOn, m1BoxCol)
 
// ═════════════════════════════════ DISPLAY RANGE ═════════════════════════════
// A ray far from price stretches the chart's auto-scale. Beyond the display range an active ray
// stops extending (it stays as a stub on its anchor bar) and extends again when price returns.
// Only the drawing changes.
foldRays(array<Level> lv) =>
    int n = 0
    if lv.size() > 0
        for L in lv
            if L.swept < 0 and not na(L.ln)
                if isNear(L.price)
                    line.set_extend(L.ln, extend.right)
                else
                    line.set_extend(L.ln, extend.none)
                    n += 1
    n
 
foldTradeLine(line ln) =>
    if not na(ln)
        if not isNear(line.get_y1(ln))
            line.set_x2(ln, line.get_x1(ln))
 
if barstate.islast
    if m1On
        foldRays(m1H)
        foldRays(m1L)
    if m2Run
        if m2ExtAll
            foldRays(m2H)
            foldRays(m2L)
        foldTradeLine(m2TradeLnH)
        foldTradeLine(m2TradeLnL)
    if m3On
        foldRays(m3H)
        foldRays(m3L)
    if m4Run
        foldRays(m4H)
        foldRays(m4L)
 
// ═══════════════════════════════════ DASHBOARD ═══════════════════════════════
countActive(array<Level> lv, int minT) =>
    int n = 0
    if lv.size() > 0
        for L in lv
            if L.swept < 0 and L.touches >= minT
                n += 1
    n
 
// nearest active level above / below the close across the given arrays
nearest(array<Level> a, array<Level> b, int minT) =>
    float up = na
    float dn = na
    for i = 0 to 1
        array<Level> lv = i == 0 ? a : b
        if lv.size() > 0
            for L in lv
                if L.swept < 0 and L.touches >= minT
                    if L.price > close and (na(up) or L.price < up)
                        up := L.price
                    if L.price < close and (na(dn) or L.price > dn)
                        dn := L.price
    [up, dn]
 
fmtDist(float p) =>
    na(p) ? "—" : str.tostring(p, format.mintick) + "   " + (p > close ? "+" : "−") + str.tostring(math.abs(p - close) / close * 100, "0.00") + "%"
 
if dbOn and barstate.islast
    var table tb = table.new(dbPos == "Top right" ? position.top_right : dbPos == "Top left" ? position.top_left : dbPos == "Bottom right" ? position.bottom_right : position.bottom_left, 5, 7, bgcolor = chart.bg_color, border_width = 1, border_color = color.new(fg, 85), frame_color = color.new(fg, 70), frame_width = 1)
    string sz = dbSize == "Tiny" ? size.tiny : dbSize == "Small" ? size.small : size.normal
    color hdr = color.new(fg, 88)
    table.cell(tb, 0, 0, "Liquidity Map", text_color = fg, text_size = sz, bgcolor = hdr, text_halign = text.align_left)
    table.cell(tb, 1, 0, "Highs", text_color = fg, text_size = sz, bgcolor = hdr)
    table.cell(tb, 2, 0, "Lows", text_color = fg, text_size = sz, bgcolor = hdr)
    table.cell(tb, 3, 0, "Nearest above", text_color = fg, text_size = sz, bgcolor = hdr)
    table.cell(tb, 4, 0, "Nearest below", text_color = fg, text_size = sz, bgcolor = hdr)
    float up = na
    float dn = na
    for r = 1 to 4
        bool on = r == 1 ? m1On : r == 2 ? m2Run : r == 3 ? m3On : m4Run
        array<Level> a = r == 1 ? m1H : r == 2 ? m2H : r == 3 ? m3H : m4H
        array<Level> b = r == 1 ? m1L : r == 2 ? m2L : r == 3 ? m3L : m4L
        string nm = r == 1 ? "① Pivot rays" : r == 2 ? "② Sessions" : r == 3 ? "③ Resting stops" : "④ TPO poor H/L"
        int minT = r == 3 ? m3MinT : 1
        [u, d] = nearest(a, b, minT)
        table.cell(tb, 0, r, nm, text_color = on ? fg : color.new(fg, 60), text_size = sz, text_halign = text.align_left)
        table.cell(tb, 1, r, on ? str.tostring(countActive(a, minT)) : "off", text_color = m1ColH, text_size = sz)
        table.cell(tb, 2, r, on ? str.tostring(countActive(b, minT)) : "off", text_color = m1ColL, text_size = sz)
        table.cell(tb, 3, r, on ? fmtDist(u) : "—", text_color = fg, text_size = sz)
        table.cell(tb, 4, r, on ? fmtDist(d) : "—", text_color = fg, text_size = sz)
        if on
            if not na(u) and (na(up) or u < up)
                up := u
            if not na(d) and (na(dn) or d > dn)
                dn := d
    table.cell(tb, 0, 5, "Nearest liquidity", text_color = fg, text_size = sz, bgcolor = hdr, text_halign = text.align_left)
    table.cell(tb, 1, 5, "", bgcolor = hdr)
    table.cell(tb, 2, 5, "", bgcolor = hdr)
    table.cell(tb, 3, 5, fmtDist(up), text_color = fg, text_size = sz, bgcolor = hdr)
    table.cell(tb, 4, 5, fmtDist(dn), text_color = fg, text_size = sz, bgcolor = hdr)
    if not tfRecommended
        table.cell(tb, 0, 6, "Timeframe " + tfKey + " is outside the 5m / 15m / 1h / 4h / D set", text_color = m3ArrH, text_size = sz, text_halign = text.align_left)
        table.merge_cells(tb, 0, 6, 4, 6)
 
// ═══════════════════════════════════ ALERTS ══════════════════════════════════
alertcondition(m1NewSeries,  "① Pivot rays: series formed",      "Liquidity Map: a new pivot-ray series formed on {{ticker}} {{interval}}")
alertcondition(m1TradeSwept, "① Pivot rays: trade level swept",  "Liquidity Map: pivot-ray trade level swept on {{ticker}} {{interval}}")
alertcondition(m2NewSeries,  "② Sessions: series formed",        "Liquidity Map: a new session-level series formed on {{ticker}} {{interval}}")
alertcondition(m2TradeSwept, "② Sessions: trade level swept",    "Liquidity Map: session trade level swept on {{ticker}} {{interval}}")
alertcondition(m3Swept,      "③ Resting stops: pool swept",      "Liquidity Map: equal highs/lows pool swept on {{ticker}} {{interval}}")
alertcondition(m4Revisit,    "④ TPO: poor high/low revisited",   "Liquidity Map: poor high/low revisited on {{ticker}} {{interval}}")
alertcondition(m1TradeSwept or m2TradeSwept or m3Swept or m4Revisit, "Any liquidity event", "Liquidity Map: liquidity event on {{ticker}} {{interval}}")

← 返回列表