Liquidity Depth Walls [JOAT]

officialjackofalltrades · study · 1194 行 · 点赞 248 · 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/
// © officialjackofalltrades
//@version=6
indicator("Liquidity Depth Walls [JOAT]", "Liquidity Depth Walls", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 5000)
// Scale anchor: a script that only draws boxes / lines / labels can land on its own price scale on a customer's
// chart. One invisible plot pins it to the price scale. display.pane keeps it out of the status line and data window.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
 
float atrK = ta.atr(14)          // shared ATR for glow padding, lane gaps, wall distances and pool tolerance
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. THEME
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G1 = "Theme"
string theme  = input.string("Delta Cyan / Pink", "Theme", group = G1,
     options = ["JOAT Signature", "Midnight Blue / Red", "Aurora Night", "Delta Cyan / Pink", "Paper & Ink", "Lime Ember", "Custom"],
     tooltip = "Named presets. Delta Cyan / Pink is the depth-map default here. Paper & Ink is the clean black / white preset: direction is carried by position and line style, not colour. Custom uses the colour pickers below.")
int    bright = input.int(3, "Brightness", minval = 1, maxval = 5, group = G1,
     tooltip = "1 = faint, 3 = as designed, 5 = vivid. Scales every fill and glow transparency; solid lines and plates stay solid.")
string bgMode = input.string("Auto", "Chart background", options = ["Auto", "Dark", "Light"], group = G1,
     tooltip = "Auto reads the luminance of the chart background and swaps every role so it stays readable on a white chart.")
color  inBull  = input.color(#5CF0D7, "Custom bull / bear",     group = G1, inline = "c1")
color  inBear  = input.color(#B32AC3, "",                       group = G1, inline = "c1")
color  inAcc   = input.color(#FFFFFF, "Custom accent / neutral", group = G1, inline = "c2")
color  inNeu   = input.color(#787B86, "",                       group = G1, inline = "c2")
color  inTxt   = input.color(#D1D4DC, "Custom text / panel",    group = G1, inline = "c3")
color  inPanel = input.color(#0E1116, "",                       group = G1, inline = "c3")
color  inGlow  = input.color(#5CF0D7, "Custom glow",            group = G1, inline = "c4")
 
// f_lum: relative luminance 0..1 of any colour (Rec. 601 weights). Used for light / dark awareness and plate ink.
f_lum(color c) =>
    (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255.0
 
bool isLight = bgMode == "Light" ? true : bgMode == "Dark" ? false : f_lum(chart.bg_color) > 0.5
bool isMono  = theme == "Paper & Ink"
 
// Roles, resolved once. Defaults = JOAT Signature. Each preset overrides every role, with the white-chart swap.
color cBull   = isLight ? #12B5A0 : #5CF0D7
color cBear   = isLight ? #8E1FA0 : #B32AC3
color cAcc    = isLight ? #131722 : #FFFFFF
color cNeu    = #787B86
color cTxt    = isLight ? #131722 : #D1D4DC
color cPanel  = isLight ? #FFFFFF : #0E1116
color cGlow   = isLight ? #12B5A0 : #5CF0D7
color cCandle = cAcc                       // colour for the "Mono" candle paint (white bodies on black, ink on white)
if theme == "Midnight Blue / Red"
    cBull   := #2962FF
    cBear   := #F23645
    cAcc    := isLight ? #131722 : #FFFFFF
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #D1D4DC
    cPanel  := isLight ? #FFFFFF : #0B0F13
    cGlow   := #2962FF
    cCandle := cAcc
else if theme == "Aurora Night"
    cBull   := isLight ? #00A86B : #00E676
    cBear   := isLight ? #C2185B : #E040FB
    cAcc    := isLight ? #B59A00 : #FDD835
    cNeu    := #5C6BC0
    cTxt    := isLight ? #1A1F2E : #E6F1FF
    cPanel  := isLight ? #F4F6FB : #0A0E17
    cGlow   := isLight ? #0097A7 : #00BCD4   // the outer aurora hue (cyan); bear outer is #7C4DFF
    cCandle := cNeu
else if theme == "Delta Cyan / Pink"
    cBull   := isLight ? #0097A7 : #00E5FF
    cBear   := isLight ? #D81B60 : #FF2E88
    cAcc    := isLight ? #B59A00 : #FFD600
    cNeu    := #6B7280
    cTxt    := isLight ? #111827 : #F8FAFC
    cPanel  := isLight ? #FFFFFF : #111827
    cGlow   := isLight ? #0097A7 : #00E5FF
    cCandle := cNeu
else if theme == "Paper & Ink"
    color ink = isLight ? #111827 : #F0F3FA
    cBull   := ink
    cBear   := ink                            // same ink; bear objects carry direction by DASHED style (kBearStyle)
    cAcc    := #2962FF                        // the one accent: "live / nearest"; #F23645 is reserved for "broken"
    cNeu    := #B2B5BE
    cTxt    := ink
    cPanel  := isLight ? #FFFFFF : #131722
    cGlow   := #2962FF
    cCandle := ink
else if theme == "Lime Ember"
    cBull   := isLight ? #64DD17 : #B2FF59    // below-price liquidity
    cBear   := isLight ? #2962FF : #448AFF    // above-price liquidity
    cAcc    := #FF9800                        // ember: POC / peak row
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #E0E0E0
    cPanel  := isLight ? #FFFFFF : #161A25
    cGlow   := #FF9800
    cCandle := cNeu
else if theme == "Custom"
    cBull   := inBull
    cBear   := inBear
    cAcc    := inAcc
    cNeu    := inNeu
    cTxt    := inTxt
    cPanel  := inPanel
    cGlow   := inGlow
    cCandle := inAcc
 
color  cBroken   = #F23645                                            // grey-or-red for dead things; Paper & Ink "broken"
string kBearStyle = isMono ? line.style_dashed : line.style_solid    // Paper & Ink: direction by style, not hue
int    kPanelT    = isLight ? 8 : 15                                  // panel alpha: 92 % on white, 85 % on dark
 
// f_t: brightness-aware transparency. Scales the OPACITY (100 - t) by 0.5x .. 1.5x so faint things stay faint
// and solid things stay solid; fills (t >= 40) get +4 on a white chart and are floored at 92 in Paper & Ink.
f_t(int t) =>
    float op = 100.0 - t
    float k  = 1.0 + (bright - 3) * 0.25
    float tt = 100.0 - op * k
    if t >= 40
        if isMono
            tt := math.max(tt, 92.0)
        if isLight
            tt += 4.0
    math.min(100, math.max(0, math.round(tt)))
 
// f_ink: black or white text for a solid plate of colour c, by luminance.
f_ink(color c) =>
    f_lum(c) > 0.55 ? #0B0F13 : #FFFFFF
 
// f_grad: 3-stop gradient c1 (t = 0) -> c2 (t = 0.5) -> c3 (t = 1).
f_grad(color c1, color c2, color c3, float t) =>
    float tt = math.min(1.0, math.max(0.0, nz(t, 0.5)))
    tt < 0.5 ? color.from_gradient(tt, 0.0, 0.5, c1, c2) : color.from_gradient(tt, 0.5, 1.0, c2, c3)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4a. LAYOUT — clamps (defined early because the glow and text helpers use them)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_xo: a drawing anchored further back than ~5,000 bars kills the script on a LIVE bar (RE10143) and a Basic
// account only has 5,000 bars anyway. f_xr: nothing may be drawn more than 500 bars ahead.
f_xo(int b) =>
    math.max(b, bar_index - 4990)
f_xr(int b) =>
    math.min(b, bar_index + 490)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 2. GLOW
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_glowBox: N concentric boxes. Halo h (1..layers-1) is padded h * 0.05 ATR outward and fades toward 97;
// the last element of the returned array is the CORE box (fill baseT, 1-px border). Keep the array so the
// retirement helpers can delete all layers together.
f_glowBox(int x1, float top, int x2, float bot, color c, int layers, int baseT) =>
    array<box> out = array.new<box>()
    int   xl  = f_xo(math.min(x1, x2))
    int   xr  = f_xr(math.max(x1, x2))
    float hi  = math.max(top, bot)
    float lo  = math.min(top, bot)
    float pad = nz(atrK, (hi - lo) * 0.2) * 0.05
    int   n   = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i                                        // outermost first so the core draws on top
            int tH = f_t(math.min(99, baseT + math.round(float(97 - baseT) * h / n)))
            array.push(out, box.new(xl, hi + pad * h, xr, lo - pad * h,
                 border_color = color.new(c, 100), border_width = 1, bgcolor = color.new(c, tH)))
    array.push(out, box.new(xl, hi, xr, lo,
         border_color = color.new(c, f_t(math.max(0, baseT - 50))), border_width = 1, bgcolor = color.new(c, f_t(baseT))))
    out
 
// f_glowLine: a solid core line of `width` with layers-1 wider, fainter halos beneath it. Last element = core.
f_glowLine(int x1, float y1, int x2, float y2, color c, int layers, int width) =>
    array<line> out = array.new<line>()
    int xl = f_xo(x1)
    int xr = f_xr(x2)
    int n  = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i
            int tH = f_t(math.min(99, 70 + math.round(27.0 * h / n)))
            array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, tH), width = math.max(1, width + 2 * h)))
    array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, f_t(0)), width = math.max(1, width)))
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. TEXT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_plate: label on a SOLID plate of colour c, text in f_ink(c). sty = label.style_*, sz = size.*
f_plate(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = c, style = sty,
         textcolor = f_ink(c), size = sz)
 
// f_tag: plateless text (transparent background, coloured text). Evolves f_tag of [JOAT] Fibonacci Vault.
f_tag(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100),
         style = sty, textcolor = c, size = sz)
 
// f_px: price with thousands separators at mintick precision: 24,550.25  /  1.08432  /  —
f_px(float p) =>
    string out = "—"
    if not na(p)
        string s = str.tostring(math.abs(p), format.mintick)
        array<string> parts = str.split(s, ".")
        string ip = array.get(parts, 0)
        string fp = ""
        if array.size(parts) > 1
            fp := "." + array.get(parts, 1)
        string g = ""
        int n = str.length(ip)
        if n > 0
            for i = 0 to n - 1
                g += str.substring(ip, i, i + 1)
                int rem = n - 1 - i
                if rem > 0 and rem % 3 == 0
                    g += ","
        out := (p < 0 ? "-" : "") + g + fp
    out
 
// f_k: compact numbers: 1.2K  3.4M  2.1B  (below 1,000: up to two decimals)
f_k(float v) =>
    string out = "—"
    if not na(v)
        float  a   = math.abs(v)
        string sgn = v < 0 ? "-" : ""
        if a >= 1e9
            out := sgn + str.tostring(a / 1e9, "#.#") + "B"
        else if a >= 1e6
            out := sgn + str.tostring(a / 1e6, "#.#") + "M"
        else if a >= 1e3
            out := sgn + str.tostring(a / 1e3, "#.#") + "K"
        else
            out := sgn + str.tostring(a, "#.##")
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4b. LAYOUT — label lane de-collision + object retirement
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Lane register: every right-edge label asks f_lane for a y. The register holds the price BAND each placed tag
// covers (one text height), so a tag that sits above its anchor and one that sits below are both respected. It is
// cleared at the start of each last-bar redraw (f_laneReset) so the slots are recomputed from scratch every tick.
var array<float> laneLo = array.new<float>()
var array<float> laneHi = array.new<float>()
 
f_laneReset() =>
    array.clear(laneLo)
    array.clear(laneHi)
 
// f_lane: the nearest free anchor y to `y`. dir = 1: the text sits ABOVE the anchor (label_lower_*), -1: BELOW it
// (label_upper_*), 0: centred (label_left / right). gap = one text height in price. Candidates step half a text
// height at a time, away from price first (up for dir 1 / 0, down for dir -1), then toward it.
f_lane(float y, int dir, float gap) =>
    float out = y
    for k = 0 to 48
        float off  = math.ceil(k / 2.0) * gap * 0.5
        bool  away = k % 2 == 1
        float cand = dir == -1 ? (away ? y - off : y + off) : (away ? y + off : y - off)
        float lo   = dir == 1 ? cand : dir == -1 ? cand - gap : cand - gap * 0.5
        float hi   = lo + gap
        bool  free = true
        int   n    = array.size(laneLo)
        if n > 0
            for j = 0 to n - 1
                if lo < array.get(laneHi, j) - gap * 0.001 and hi > array.get(laneLo, j) + gap * 0.001
                    free := false
                    break
        if free
            out := cand
            break
    float lo0 = dir == 1 ? out : dir == -1 ? out - gap : out - gap * 0.5
    array.push(laneLo, lo0)
    array.push(laneHi, lo0 + gap)
    out
 
// Retirement: push every new object into one array per kind, then cap it. Oldest leaves first (array.shift).
string G3 = "Limits (free account)"
int maxBoxes  = input.int(300, "Max boxes kept",  minval = 125, maxval = 500, group = G3, tooltip = "The depth ladder uses one box per gradient step per row, plus two for the balance bar. When the cap cannot hold every row at the chosen steps, the steps are lowered (never the rows).")
int maxLines  = input.int(120, "Max lines kept",  minval = 4, maxval = 500, group = G3, tooltip = "Walls (one line per glow layer) plus pools. Over the cap, swept objects leave first, then the oldest pools.")
int maxLabels = input.int(80, "Max labels kept", minval = 4, maxval = 500, group = G3, tooltip = "One label per wall and pool plus the POC and balance tags. Over the cap, swept objects leave first, then the oldest pools.")
 
f_capBoxes(array<box> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        box.delete(array.shift(a))
f_capLines(array<line> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        line.delete(array.shift(a))
f_capLabels(array<label> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        label.delete(array.shift(a))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G2 = "Dashboard"
bool   showDash    = input.bool(true, "Show dashboard", group = G2)
string dashPos     = input.string("Top Right", "Dashboard position", group = G2,
     options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
string dashSize    = input.string("Small", "Dashboard size", options = ["Small", "Normal", "Large"], group = G2,
     tooltip = "Small is the smallest size: every number on the panel stays readable.")
bool   dashCompact = input.bool(false, "Compact dashboard", group = G2, tooltip = "Fewer rows for phones: header, one key row and the Read line.")
bool   dashTint    = input.bool(true, "Tinted value cells", group = G2, tooltip = "Value cells carry a faint tint of their own colour.")
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
// no size.tiny anywhere: every label and cell carries data, so size.small is the floor
f_size(string s) =>
    switch s
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
// f_dashNew: panel in cPanel at the theme alpha, 1-px neutral frame. Rows = header + data rows + Read line.
f_dashNew(string pos, int cols, int rows) =>
    table.new(f_pos(pos), cols, rows, bgcolor = color.new(cPanel, kPanelT), frame_color = color.new(cNeu, 40),
         frame_width = 1, border_color = color.new(cNeu, 78), border_width = 1)
 
int dashRows = dashCompact ? 3 : 8                 // header + 6 rows (Sell wall, Buy wall, Balance, POC, Pools in view, Nearest pool) + Read
var table dash = f_dashNew(dashPos, 2, dashRows)
var array<int> dCur    = array.from(0)     // row cursor (arrays are the only globals a function may mutate)
var array<int> dMerged = array.from(-1)    // row already merged for the Read line
 
// f_dBegin: clear and rewind; call once per last-bar redraw before f_dHead.
f_dBegin() =>
    table.clear(dash, 0, 0, 1, dashRows - 1)
    array.set(dCur, 0, 0)
 
// f_dHead: title band (bold, glow tint) with symbol · timeframe on the right.
f_dHead(string title) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + title + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             bgcolor = color.new(cGlow, isLight ? 80 : 70), text_formatting = text.format_bold)
        table.cell(dash, 1, r, syminfo.ticker + " · " + timeframe.period + " ", text_color = cTxt, text_halign = text.align_right,
             text_size = f_size(dashSize), bgcolor = color.new(cGlow, isLight ? 88 : 80))
        array.set(dCur, 0, r + 1)
 
// f_dRow: name | value, value text in valueColor with an optional tint cell (evolves the 51-series f_row / f_pill).
f_dRow(string name, string value, color valueColor, string tip) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + name, text_color = color.new(cTxt, 25), text_halign = text.align_left,
             text_size = f_size(dashSize), tooltip = tip)
        table.cell(dash, 1, r, value + " ", text_color = valueColor, text_halign = text.align_right, text_size = f_size(dashSize),
             bgcolor = dashTint ? color.new(valueColor, isLight ? 90 : 86) : color.new(cPanel, 100), tooltip = tip)
        array.set(dCur, 0, r + 1)
 
// f_dRead: the one-line "Read" sentence, merged across both columns, italic. Always the last row.
f_dRead(string txt) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        if array.get(dMerged, 0) != r
            table.merge_cells(dash, 0, r, 1, r)
            array.set(dMerged, 0, r)
        table.cell(dash, 0, r, " " + txt + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             text_formatting = text.format_italic)
        array.set(dCur, 0, r + 1)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLES
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G4 = "Candles"
string paintMode = input.string("Off", "Candle paint", options = ["Off", "Score", "Mono"], group = G4,
     tooltip = "Off = chart candles. Score = bear -> neutral -> bull gradient by the score chosen in 'Score from' (the ladder's up-volume share, or the position between the walls). Mono = one colour so the ladder and walls carry all the colour.")
 
// f_candlePaint: na (Off), f_grad(cBear, cNeu, cBull, score) (Score) or cCandle (Mono). Feed it to barcolor().
f_candlePaint(string mode, float score) =>
    color out = na
    if mode == "Score"
        out := f_grad(cBear, cNeu, cBull, score)
    else if mode == "Mono"
        out := cCandle
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. LIQUIDITY DEPTH WALLS — inputs
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string paintSrc = input.string("Up-volume share", "Score from", options = ["Up-volume share", "Position between walls"], group = G4,
     tooltip = "What the Score paint follows. Up-volume share: the ladder's balance (bear colour when down-close volume leads, bull colour when up-close volume leads). Position between walls: bear colour next to the sell wall, bull colour next to the buy wall, neutral halfway; no paint while either wall is missing.")
 
string GL = "Depth ladder"
bool   showLadder = input.bool(true, "Show depth ladder", group = GL,
     tooltip = "The volume-at-price histogram. Rows above price in the bear colour, rows below price in the bull colour, the heaviest row (POC) in the accent colour. Each row is bright at its base and fades outward; heavier rows are brighter. The walls still work with the ladder hidden.")
string ladPlace   = input.string("Right of price", "Ladder placement", options = ["Right of price", "Over the last bars"], group = GL,
     tooltip = "Right of price: the ladder starts a few bars right of the last candle and grows right, in the empty space. Over the last bars: it sits on top of the latest candles, drawn fainter so they stay readable.")
int    ladGap     = input.int(3, "Gap from the last bar", minval = 1, maxval = 50, group = GL,
     tooltip = "Right of price only: empty bars between the last candle and the base of the ladder. Wall and pool lines run to the base. Gap + ladder width + about 12 bars for the POC tag should fit inside the chart's right margin.")
int    ladBars    = input.int(200, "Bars in the ladder", minval = 50, maxval = 600, group = GL,
     tooltip = "How many of the latest bars feed the ladder. Each bar's volume is spread evenly over the price rows its high-low range covers. The window slides with every bar.")
int    ladRows    = input.int(60, "Rows", minval = 10, maxval = 120, group = GL,
     tooltip = "Price rows between the lowest low and the highest high of those bars. More rows = finer walls, thinner bars.")
int    ladWidth   = input.int(22, "Ladder width (bars)", minval = 5, maxval = 100, group = GL,
     tooltip = "The heaviest row (100 %) is this many bars long; every other row is drawn in proportion to it. The POC tag sits right after the POC row, so with the defaults (gap 3 + width 22) the ladder and its tag fit in about 38 bars of right margin. Widen the chart's right margin before raising this.")
int    ladSteps   = input.int(4, "Gradient steps", minval = 1, maxval = 6, group = GL,
     tooltip = "Each row is drawn as this many segments, bright at the base and fading outward. One box per step per row; lowered automatically when 'Max boxes kept' cannot hold every row.")
int    vaPct      = input.int(70, "Value area %", minval = 50, maxval = 95, group = GL,
     tooltip = "Share of the ladder volume gathered around the heaviest row that counts as the value area. Rows outside it are drawn a little fainter.")
bool   showPoc    = input.bool(true, "POC tag", group = GL, tooltip = "Tag the heaviest row 'POC 24,550.25', right after the end of the POC row. Its distance in ATR is on the dashboard's POC row.")
bool   showBal    = input.bool(true, "Balance bar", group = GL,
     tooltip = "A thin two-tone bar under the ladder: up-close volume share in the bull colour, down-close share in the bear colour, with its tag '58 % up · 42 % down' just under the bar. It is the Balance row of the dashboard.")
 
string GW = "Walls"
bool   showWalls   = input.bool(true, "Show walls", group = GW,
     tooltip = "The strongest ladder row above price is the sell wall, the strongest below price is the buy wall. Strength = that row's volume as a share of the heaviest row.")
int    wallsN      = input.int(1, "Walls per side", minval = 1, maxval = 3, group = GW,
     tooltip = "1 = only the biggest wall above and below. 2 or 3 adds the next heaviest rows on each side.")
float  wallMinAtr  = input.float(0.3, "Minimum distance from price (ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = GW,
     tooltip = "A NEW wall must sit at least this far from the close, so the row price is trading in right now is not called a wall. A wall price walks into keeps living until a bar closes through it.")
int    wallGlowPct = input.int(60, "Glow from strength %", minval = 0, maxval = 100, group = GW,
     tooltip = "Walls at or above this strength get glow halos. Everything weaker is a plain dotted line.")
int    glowLayers  = input.int(3, "Glow layers", minval = 1, maxval = 6, group = GW,
     tooltip = "Halo lines under a glowing wall. Each layer costs one line per wall.")
int    wallExt     = input.int(5, "Extend right (bars)", minval = 1, maxval = 50, group = GW,
     tooltip = "When the ladder is hidden or sits over the last bars: how far past the current bar live walls and pools reach. Right of price they run to the ladder base instead.")
int    sweptKeep   = input.int(20, "Keep swept objects (bars)", minval = 5, maxval = 500, group = GW,
     tooltip = "A swept wall or pool shrinks to a short dim dashed stub ending at the sweep bar and stays for this many bars, then leaves.")
bool   sweptTags   = input.bool(false, "Swept tags", group = GW,
     tooltip = "Off (default): a swept wall or pool is only the dim stub, no text, so the candles stay clean. On: the stub carries a grey 'sell wall swept 24,550.25' / 'EQH x2 swept ...' tag.")
 
string GP = "Pools (equal highs / lows)"
bool   showPools = input.bool(true, "Show pools", group = GP,
     tooltip = "Two or more confirmed swing highs within the tolerance form an EQH pool, two or more swing lows an EQL pool. Rails run from the first swing to the ladder base.")
int    pivL      = input.int(5, "Pivot left bars", minval = 1, maxval = 50, group = GP, tooltip = "Bars to the left that must be lower (for a swing high) or higher (for a swing low).")
int    pivR      = input.int(5, "Pivot right bars", minval = 1, maxval = 50, group = GP, tooltip = "Bars to the right that confirm the swing. A swing is only known this many bars after it printed; nothing is drawn before that, so nothing repaints.")
float  eqTolAtr  = input.float(0.2, "Equal tolerance (ATR)", minval = 0.02, maxval = 2.0, step = 0.05, group = GP,
     tooltip = "Two swings count as equal when their prices are within this fraction of ATR. A wick that goes past a pool by MORE than this sweeps it; a wick inside it is one more equal swing.")
int    poolLook  = input.int(300, "Pair swings within (bars)", minval = 20, maxval = 2000, group = GP,
     tooltip = "A lone swing waits this long for a partner. Older lone swings, and lone swings price has already traded through, are forgotten.")
int    poolMax   = input.int(3, "Pools per side", minval = 1, maxval = 6, group = GP, tooltip = "Live EQH pools and live EQL pools kept at once; the oldest leaves first.")
int    poolAge   = input.int(1000, "Retire pools after (bars)", minval = 50, maxval = 3000, group = GP, tooltip = "A live pool older than this is removed even if it was never swept.")
 
string GT = "Tags"
bool   tagPrice    = input.bool(true, "Price on tags", group = GT, tooltip = "Wall tags read 'sell wall 24,550.25 · 73 % · 1.4 ATR · tested 2x'; pool tags read 'EQH x3 24,550.25 · 0.8 ATR'. The toggles below switch each part on and off.")
bool   tagStrength = input.bool(true, "Strength % on wall tags", group = GT)
bool   tagDist     = input.bool(true, "Distance in ATR on wall and pool tags", group = GT)
bool   tagTests    = input.bool(true, "Tests count on wall tags", group = GT)
string tagSz       = input.string("Small", "Tag size", options = ["Small", "Normal", "Large"], group = GT,
     tooltip = "Small is the smallest size: every tag carries a price, so none is ever drawn tiny.")
float  laneGap     = input.float(0.5, "Tag spacing (ATR)", minval = 0.1, maxval = 3.0, step = 0.1, group = GT,
     tooltip = "Minimum height reserved for one tag, in ATR. The script also reserves at least 1/40 of the ladder's price range (about one text line at the chart's own scale), whichever is larger. A tag that would overlap another in the same column is moved to the nearest free slot, away from price first.")
 
string GE = "Engine"
int    histBars = input.int(1000, "Bars of history to compute", minval = 300, maxval = 3000, group = GE,
     tooltip = "The ladder is rebuilt on each of these latest bars so wall history, sweeps and the candle paint are real. The work grows with this x 'Bars in the ladder'; lower either one if the script is slow to load. With walls and candle paint off, the ladder is only built on the last bar.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. DEPTH LADDER ENGINE — volume at price over the last N bars (ring buffers, no request.* calls)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var array<float> rbH = array.new<float>()
var array<float> rbL = array.new<float>()
var array<float> rbV = array.new<float>()
var array<float> rbU = array.new<float>()      // 1 = up close, 0 = down close
var array<int>   rbB = array.new<int>()        // bar index of each buffered bar
 
// Volume is latched: once the symbol has shown volume, a zero-volume bar (first tick, holiday) weighs 0, not 1.
var bool volSeen = false
volSeen := volSeen or nz(volume) > 0
bool  hasVol = volSeen
float barVol = hasVol ? nz(volume) : 1.0      // volume-less symbols: every bar weighs 1, the ladder becomes time at price
 
array.push(rbH, high)
array.push(rbL, low)
array.push(rbV, barVol)
array.push(rbU, close >= open ? 1.0 : 0.0)
array.push(rbB, bar_index)
if array.size(rbH) > ladBars
    array.shift(rbH)
    array.shift(rbL)
    array.shift(rbV)
    array.shift(rbU)
    array.shift(rbB)
 
var array<float> rowUp    = array.new<float>(ladRows, 0.0)
var array<float> rowDn    = array.new<float>(ladRows, 0.0)
var array<int>   rowFirst = array.new<int>(ladRows, -1)
 
bool  engineOn  = bar_index >= last_bar_index - histBars and not na(atrK)
// history only needs the ladder when something reads it bar by bar (walls, candle paint); otherwise last bar only
bool  engineRun = engineOn and (showWalls or paintMode != "Off" or barstate.islast)
float ladBase   = na
float ladTop    = na
float rowH      = na
float maxRow    = 0.0
float upSum     = 0.0
float dnSum     = 0.0
int   pocIdx    = -1
 
if engineRun
    array.fill(rowUp, 0.0)
    array.fill(rowDn, 0.0)
    array.fill(rowFirst, -1)
    ladBase := array.min(rbL)
    ladTop  := array.max(rbH)
    rowH    := (ladTop - ladBase) / ladRows
    int n = array.size(rbH)
    if rowH > 0 and n > 0
        for j = 0 to n - 1
            float lo = array.get(rbL, j)
            float hi = array.get(rbH, j)
            float v  = array.get(rbV, j)
            bool  up = array.get(rbU, j) > 0.5
            int   bj = array.get(rbB, j)
            int r0 = math.max(0, math.min(ladRows - 1, math.floor((lo - ladBase) / rowH)))
            int r1 = math.max(0, math.min(ladRows - 1, math.floor((hi - ladBase) / rowH)))
            float share = v / (r1 - r0 + 1)
            for r = r0 to r1
                if up
                    array.set(rowUp, r, array.get(rowUp, r) + share)
                else
                    array.set(rowDn, r, array.get(rowDn, r) + share)
                if array.get(rowFirst, r) < 0
                    array.set(rowFirst, r, bj)
            if up
                upSum += v
            else
                dnSum += v
        for r = 0 to ladRows - 1
            float t = array.get(rowUp, r) + array.get(rowDn, r)
            if t > maxRow
                maxRow := t
                pocIdx := r
 
float balance = upSum + dnSum > 0 ? upSum / (upSum + dnSum) : na     // up-volume share of the ladder, 0..1
 
// f_rowOf: ladder row index of a price (only valid while rowH > 0)
f_rowOf(float p) =>
    int r = math.floor((p - ladBase) / rowH)
    math.max(0, math.min(ladRows - 1, r))
 
// f_rowMid: centre price of a row
f_rowMid(int r) =>
    ladBase + (r + 0.5) * rowH
 
// f_atrTxt: a distance in ATR as "1.4" ("—" before ATR exists)
f_atrTxt(float d) =>
    nz(atrK) > 0 and not na(d) ? str.tostring(math.abs(d) / atrK, "0.0") : "—"
 
// Layout of the right edge. Right of price: the ladder base sits ladGap bars right of the last bar, wall and pool
// lines run to it and their tags end at it. Otherwise lines stop wallExt bars past the
// last bar and their tags start right after.
bool ladRight = showLadder and ladPlace == "Right of price"
int  ladX0    = ladRight ? bar_index + ladGap : bar_index - ladWidth + 1
int  lineEnd  = ladRight ? ladX0 : bar_index + wallExt
int  tagX     = ladRight ? lineEnd : lineEnd + 1
int  kStub    = 10          // a swept wall / pool keeps only its last 10 bars, ending at the sweep bar
 
// f_capStyle: tags ride on the OUTSIDE of their line (above for the high / sell side, below for the low / buy side),
// so the text never sits on the dotted line and the area toward price stays clear.
f_capStyle(int side, bool rightAligned) =>
    string s = na
    if side == 1
        s := rightAligned ? label.style_label_lower_right : label.style_label_lower_left
    else
        s := rightAligned ? label.style_label_upper_right : label.style_label_upper_left
    s
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. WALLS — the strongest rows above and below price, with live / tested / swept states (confirmed bars only)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
type Wall
    int         side          // 1 = sell wall (above price), -1 = buy wall (below price)
    float       price         // row centre at creation (kept stable while the row grid slides)
    float       top           // row edges at creation
    float       bot
    float       strength      // 0..100, row volume / heaviest row
    int         firstBar      // first buffered bar that traded in the row
    int         state         // 0 live, 1 swept
    int         sweptBar
    int         tests         // wicks into the row without a close through
    int         lastTestBar
    bool        glow
    int         stack         // swept tag slot when several walls of a side are swept by one bar
    array<line> lns
    label       lbl
 
var array<Wall> walls = array.new<Wall>()
 
f_wallText(Wall w) =>
    string s = w.side == 1 ? "sell wall" : "buy wall"
    if w.state == 1
        s += " swept"
    if tagPrice
        s += " " + f_px(w.price)
    if w.state == 0
        if tagStrength
            s += " · " + str.tostring(math.round(w.strength)) + " %"
        if tagDist and nz(atrK) > 0
            s += " · " + f_atrTxt(w.price - close) + " ATR"
        if tagTests and w.tests > 0
            s += " · tested " + str.tostring(w.tests) + "x"
    s
 
f_wallClear(Wall w) =>
    for ln in w.lns
        line.delete(ln)
    array.clear(w.lns)
    if not na(w.lbl)
        label.delete(w.lbl)
 
// f_wallDraw: (re)build a wall's lines and tag from its state. Live: dotted line from where the wall formed to the
// ladder base (glow halos when strong, dashed and dimmer once tested), tag in the role colour on the outside of the
// line. Swept: a short dim dashed stub (kStub bars) ending at the sweep bar; a grey tag only when "Swept tags" is on.
// Paper & Ink: the sell wall is dashed, the buy wall dotted (direction by style); tested is shown by alpha only.
f_wallDraw(Wall w) =>
    f_wallClear(w)
    color c  = w.side == 1 ? cBear : cBull
    int   xL = f_xo(w.firstBar)
    if w.state == 0
        bool   tested = w.tests > 0
        string sty    = isMono ? (w.side == 1 ? line.style_dashed : line.style_dotted) : tested ? line.style_dashed : line.style_dotted
        if w.glow
            array<line> g = f_glowLine(xL, w.price, lineEnd, w.price, c, glowLayers, 1)
            line.set_style(array.last(g), sty)
            array.concat(w.lns, g)
        else
            array.push(w.lns, line.new(xL, w.price, f_xr(lineEnd), w.price, color = color.new(c, f_t(tested ? 35 : 0)), style = sty, width = 1))
        w.lbl := f_tag(tagX, w.price, f_wallText(w), tested ? color.new(c, 25) : c, f_capStyle(w.side, ladRight), f_size(tagSz))
    else
        int   xR = f_xo(w.sweptBar)
        int   xS = f_xo(math.max(w.firstBar, w.sweptBar - kStub))
        array.push(w.lns, line.new(xS, w.price, xR, w.price, color = color.new(cNeu, f_t(55)), style = line.style_dashed, width = 1))
        if sweptTags
            float y = w.price + w.side * w.stack * nz(atrK) * laneGap
            w.lbl := f_tag(xR, y, f_wallText(w), color.new(cNeu, 20), f_capStyle(w.side, true), f_size(tagSz))
        else
            w.lbl := na
 
f_wallCount(int side) =>
    int n = 0
    for w in walls
        if w.state == 0 and w.side == side
            n += 1
    n
 
f_wallNear(int side, float price, float tol) =>
    bool hit = false
    for w in walls
        if w.state == 0 and w.side == side and math.abs(w.price - price) <= tol
            hit := true
    hit
 
bool sellSweptNow = false
bool buySweptNow  = false
bool poolSweptNow = false
bool newPoolNow   = false
 
// The state machine runs on CONFIRMED bars only: a wall is born, dropped or swept on a closed bar, never on a tick.
if engineRun and showWalls and rowH > 0 and maxRow > 0 and barstate.isconfirmed
    // 1) sweep and test checks on the walls that already exist (before this bar's new walls are born)
    int nSwS = 0
    int nSwB = 0
    for w in walls
        if w.state == 0
            bool through = w.side == 1 ? close > w.top : close < w.bot      // a close beyond the row edge
            if through
                w.state    := 1
                w.sweptBar := bar_index
                if w.side == 1
                    sellSweptNow := true
                    w.stack      := nSwS
                    nSwS         += 1
                else
                    buySweptNow := true
                    w.stack     := nSwB
                    nSwB        += 1
                f_wallDraw(w)
            else
                bool touched = w.side == 1 ? high >= w.bot : low <= w.top
                if touched and w.lastTestBar != bar_index
                    w.tests       += 1
                    w.lastTestBar := bar_index
                    f_wallDraw(w)
 
    // 2) this bar's candidates: the top-K rows at least minDist away on each side of the close
    array<int>  sellC = array.new<int>()
    array<int>  buyC  = array.new<int>()
    array<bool> used  = array.new<bool>(ladRows, false)
    float minD = nz(atrK) * wallMinAtr
    for k = 0 to wallsN - 1
        int   bestS  = -1
        float bestSV = 0.0
        int   bestB  = -1
        float bestBV = 0.0
        for r = 0 to ladRows - 1
            if not array.get(used, r)
                float t  = array.get(rowUp, r) + array.get(rowDn, r)
                float pc = f_rowMid(r)
                if t > 0
                    if pc >= close + minD and t > bestSV
                        bestSV := t
                        bestS  := r
                    else if pc <= close - minD and t > bestBV
                        bestBV := t
                        bestB  := r
        if bestS >= 0
            array.push(sellC, bestS)
            array.set(used, bestS, true)
        if bestB >= 0
            array.push(buyC, bestB)
            array.set(used, bestB, true)
 
    // 3) keep or drop live walls, refresh strength and glow; retire swept walls past their keep time.
    //    Hysteresis: a live wall is only replaced by a row at least 10 % heavier, so two near-equal rows cannot
    //    flip-flop the wall every bar.
    float tol = rowH * 1.01
    int i = 0
    while i < array.size(walls)
        Wall w = array.get(walls, i)
        bool drop = false
        if w.state == 0
            bool  inGrid = w.price >= ladBase and w.price <= ladTop
            float t      = inGrid ? array.get(rowUp, f_rowOf(w.price)) + array.get(rowDn, f_rowOf(w.price)) : 0.0
            w.strength := 100.0 * t / maxRow
            bool  inTop      = false
            float challenger = 0.0
            array<int> cl = w.side == 1 ? sellC : buyC
            for rr in cl
                if math.abs(f_rowMid(rr) - w.price) <= tol
                    inTop := true
                challenger := math.max(challenger, array.get(rowUp, rr) + array.get(rowDn, rr))
            if math.abs(w.price - close) >= minD and not inTop and challenger > t * 1.10
                drop := true                       // beyond the floor and clearly out-weighed: not a wall any more
            else
                bool g = w.strength >= wallGlowPct
                if g != w.glow
                    w.glow := g
                    f_wallDraw(w)
        else if bar_index - w.sweptBar > sweptKeep
            drop := true
        if drop
            f_wallClear(w)
            array.remove(walls, i)
        else
            i += 1
 
    // 4) new walls from unmatched candidates while the side has room
    for rr in sellC
        float pc = f_rowMid(rr)
        if not f_wallNear(1, pc, tol) and f_wallCount(1) < wallsN
            float st = 100.0 * (array.get(rowUp, rr) + array.get(rowDn, rr)) / maxRow
            Wall w = Wall.new(side = 1, price = pc, top = ladBase + (rr + 1) * rowH, bot = ladBase + rr * rowH, strength = st,
                 firstBar = array.get(rowFirst, rr), state = 0, sweptBar = -1, tests = 0, lastTestBar = -1,
                 glow = st >= wallGlowPct, stack = 0, lns = array.new<line>(), lbl = na)
            f_wallDraw(w)
            array.push(walls, w)
    for rr in buyC
        float pc = f_rowMid(rr)
        if not f_wallNear(-1, pc, tol) and f_wallCount(-1) < wallsN
            float st = 100.0 * (array.get(rowUp, rr) + array.get(rowDn, rr)) / maxRow
            Wall w = Wall.new(side = -1, price = pc, top = ladBase + (rr + 1) * rowH, bot = ladBase + rr * rowH, strength = st,
                 firstBar = array.get(rowFirst, rr), state = 0, sweptBar = -1, tests = 0, lastTestBar = -1,
                 glow = st >= wallGlowPct, stack = 0, lns = array.new<line>(), lbl = na)
            f_wallDraw(w)
            array.push(walls, w)
 
// the primary wall on each side = the strongest live one (dashboard, Read line and the "between walls" paint)
Wall sW = na
Wall bW = na
for w in walls
    if w.state == 0
        if w.side == 1 and (na(sW) or w.strength > sW.strength)
            sW := w
        if w.side == -1 and (na(bW) or w.strength > bW.strength)
            bW := w
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. POOLS — equal highs / equal lows from confirmed pivots (evolves the EQH / EQL pairing of our Quant SMC Pro and
//     the swept restyle of our Phantom Liquidity Sniper; pools merge on every further equal swing)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
type Pool
    int   side          // 1 = EQH, -1 = EQL
    float price         // highest high of the EQH swings / lowest low of the EQL swings
    int   count         // swings in the pool
    int   firstBar
    int   lastBar
    int   state         // 0 live, 1 swept
    int   sweptBar
    line  ln
    label lbl
 
var array<Pool>  pools = array.new<Pool>()
var array<float> candP = array.new<float>()    // lone swings waiting for a partner
var array<int>   candB = array.new<int>()
var array<int>   candS = array.new<int>()
 
f_poolText(Pool p) =>
    string s = (p.side == 1 ? "EQH x" : "EQL x") + str.tostring(p.count)
    if p.state == 1
        s += " swept"
    if tagPrice
        s += " " + f_px(p.price)
    if p.state == 0 and tagDist and nz(atrK) > 0
        s += " · " + f_atrTxt(p.price - close) + " ATR"
    s
 
f_poolClear(Pool p) =>
    if not na(p.ln)
        line.delete(p.ln)
    if not na(p.lbl)
        label.delete(p.lbl)
 
// f_poolDraw: thin rail from the first swing to the ladder base, tag in the high (EQH) / low (EQL) colour on the
// outside of the rail; swept = the same short dim dashed stub as a wall, tag only when "Swept tags" is on.
f_poolDraw(Pool p) =>
    f_poolClear(p)
    color c  = p.side == 1 ? cBear : cBull
    int   xL = f_xo(p.firstBar)
    if p.state == 0
        p.ln  := line.new(xL, p.price, f_xr(lineEnd), p.price, color = color.new(c, f_t(p.count >= 3 ? 0 : 20)),
             style = p.side == 1 ? kBearStyle : line.style_solid, width = p.count >= 3 ? 2 : 1)
        p.lbl := f_tag(tagX, p.price, f_poolText(p), c, f_capStyle(p.side, ladRight), f_size(tagSz))
    else
        int xR = f_xo(p.sweptBar)
        int xS = f_xo(math.max(p.firstBar, p.sweptBar - kStub))
        p.ln  := line.new(xS, p.price, xR, p.price, color = color.new(cNeu, f_t(55)), style = line.style_dashed, width = 1)
        p.lbl := sweptTags ? f_tag(xR, p.price, f_poolText(p), color.new(cNeu, 20), f_capStyle(p.side, true), f_size(tagSz)) : na
 
f_poolCount(int side) =>
    int n = 0
    for p in pools
        if p.state == 0 and p.side == side
            n += 1
    n
 
// f_poolPivot: a confirmed swing joins a live pool of its side, or pairs with a waiting lone swing into a new pool,
// or waits as a lone swing. Returns true when a new pool was born.
f_poolPivot(int side, float price, int pBar, float tol) =>
    bool created = false
    int hit = -1
    if array.size(pools) > 0
        for i = 0 to array.size(pools) - 1
            Pool p = array.get(pools, i)
            if hit < 0 and p.state == 0 and p.side == side and math.abs(p.price - price) <= tol
                hit := i
    if hit >= 0
        Pool p = array.get(pools, hit)
        p.count   += 1
        p.price   := side == 1 ? math.max(p.price, price) : math.min(p.price, price)
        p.lastBar := pBar
        f_poolDraw(p)
    else
        int ci = -1
        if array.size(candP) > 0
            for i = 0 to array.size(candP) - 1
                if ci < 0 and array.get(candS, i) == side and math.abs(array.get(candP, i) - price) <= tol
                    ci := i
        if ci >= 0
            float cp = array.get(candP, ci)
            Pool np = Pool.new(side = side, price = side == 1 ? math.max(price, cp) : math.min(price, cp), count = 2,
                 firstBar = array.get(candB, ci), lastBar = pBar, state = 0, sweptBar = -1, ln = na, lbl = na)
            f_poolDraw(np)
            array.push(pools, np)
            array.remove(candP, ci)
            array.remove(candB, ci)
            array.remove(candS, ci)
            created := true
        else
            array.push(candP, price)
            array.push(candB, pBar)
            array.push(candS, side)
    created
 
float ph = ta.pivothigh(high, pivL, pivR)
float pl = ta.pivotlow(low, pivL, pivR)
 
// confirmed bars only, like the walls
if showPools and barstate.isconfirmed
    float tolP = nz(atrK) * eqTolAtr
    // lone swings age out
    while array.size(candB) > 0 and (bar_index - array.get(candB, 0) > poolLook or array.size(candB) > 60)
        array.shift(candP)
        array.shift(candB)
        array.shift(candS)
    // a lone swing price has already traded through can no longer be half of an equal pair
    int ci = 0
    while ci < array.size(candP)
        float cp   = array.get(candP, ci)
        bool  gone = array.get(candS, ci) == 1 ? high > cp + tolP : low < cp - tolP
        if gone
            array.remove(candP, ci)
            array.remove(candB, ci)
            array.remove(candS, ci)
        else
            ci += 1
    // sweeps: a wick BEYOND the equal tolerance spends the pool (a wick inside it is one more equal swing)
    for p in pools
        if p.state == 0
            bool through = p.side == 1 ? high > p.price + tolP : low < p.price - tolP
            if through
                p.state    := 1
                p.sweptBar := bar_index
                poolSweptNow := true
                f_poolDraw(p)
    // new confirmed swings
    if not na(ph)
        if f_poolPivot(1, ph, bar_index - pivR, tolP)
            newPoolNow := true
    if not na(pl)
        if f_poolPivot(-1, pl, bar_index - pivR, tolP)
            newPoolNow := true
    // retirement: swept past keep time, live past age, more live pools per side than allowed (oldest first)
    int i = 0
    while i < array.size(pools)
        Pool p = array.get(pools, i)
        bool drop = p.state == 1 ? bar_index - p.sweptBar > sweptKeep : bar_index - p.firstBar > poolAge
        if drop
            f_poolClear(p)
            array.remove(pools, i)
        else
            i += 1
    for side = 0 to 1
        int sd = side == 0 ? 1 : -1
        while f_poolCount(sd) > poolMax
            int k = 0
            int victim = -1
            while k < array.size(pools) and victim < 0
                Pool p = array.get(pools, k)
                if p.state == 0 and p.side == sd
                    victim := k
                k += 1
            if victim < 0
                break
            f_poolClear(array.get(pools, victim))
            array.remove(pools, victim)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. BUDGET — the kit's line / label caps across walls and pools: swept objects leave first, then the oldest pools
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
f_lineCount() =>
    int n = 0
    for w in walls
        n += array.size(w.lns)
    n + array.size(pools)
 
f_labelCount() =>
    int n = 2                                           // the POC tag and the balance tag
    for w in walls
        if not na(w.lbl)
            n += 1
    for p in pools
        if not na(p.lbl)
            n += 1
    n
 
f_retireOne() =>
    bool done = false
    if array.size(walls) > 0
        for i = 0 to array.size(walls) - 1
            Wall w = array.get(walls, i)
            if w.state == 1
                f_wallClear(w)
                array.remove(walls, i)
                done := true
                break
    if not done and array.size(pools) > 0
        for i = 0 to array.size(pools) - 1
            Pool p = array.get(pools, i)
            if p.state == 1
                f_poolClear(p)
                array.remove(pools, i)
                done := true
                break
    if not done and array.size(pools) > 0
        f_poolClear(array.get(pools, 0))
        array.remove(pools, 0)
        done := true
    done
 
int budgetGuard = 0
while (f_lineCount() > maxLines or f_labelCount() > maxLabels) and budgetGuard < 500
    if not f_retireOne()
        break
    budgetGuard += 1
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. RIGHT-EDGE REFRESH — last bar: live walls and pools run to the ladder base; their tags share one lane column
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// One tag height in price: the larger of "Tag spacing (ATR)" and 1/40 of the ladder's range. The ladder's range is
// on screen (autoscale includes it), so 1/40 of it is about one text line of a Small tag at the chart's own scale.
// Large tags reserve more.
float ladRange = engineRun and not na(ladTop) and not na(ladBase) ? ladTop - ladBase : 0.0
float tagGap   = math.max(nz(atrK) * laneGap, ladRange * (tagSz == "Large" ? 0.04 : tagSz == "Normal" ? 0.032 : 0.025), syminfo.mintick * 2)
 
if barstate.islast
    f_laneReset()
    // nearest to price first, so the tags closest to the action keep their own row and the far ones give way
    array<float> dists = array.new<float>()
    array<int>   kinds = array.new<int>()       // index into walls (>= 0) or -1 - index into pools
    if array.size(walls) > 0
        for i = 0 to array.size(walls) - 1
            Wall w = array.get(walls, i)
            if w.state == 0
                array.push(dists, math.abs(w.price - close))
                array.push(kinds, i)
    if array.size(pools) > 0
        for i = 0 to array.size(pools) - 1
            Pool p = array.get(pools, i)
            if p.state == 0
                array.push(dists, math.abs(p.price - close))
                array.push(kinds, -1 - i)
    if array.size(dists) > 0
        array<int> ord = array.sort_indices(dists, order.ascending)
        for o in ord
            int k = array.get(kinds, o)
            if k >= 0
                Wall w = array.get(walls, k)
                for ln in w.lns
                    line.set_x1(ln, f_xo(w.firstBar))
                    line.set_x2(ln, f_xr(lineEnd))
                label.set_xy(w.lbl, f_xr(tagX), f_lane(w.price, w.side, tagGap))
                label.set_style(w.lbl, f_capStyle(w.side, ladRight))
                label.set_text(w.lbl, f_wallText(w))
            else
                Pool p = array.get(pools, -1 - k)
                line.set_x1(p.ln, f_xo(p.firstBar))
                line.set_x2(p.ln, f_xr(lineEnd))
                label.set_xy(p.lbl, f_xr(tagX), f_lane(p.price, p.side, tagGap))
                label.set_style(p.lbl, f_capStyle(p.side, ladRight))
                label.set_text(p.lbl, f_poolText(p))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 13. DEPTH LADDER DRAWING — last bar only (the ladder is a picture of the current window), redrawn every tick
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var array<box>   ladBoxes  = array.new<box>()
var array<label> ladLabels = array.new<label>()
 
float pocPrice = na
float pocShare = na
int   vaLo     = -1
int   vaHi     = -1
 
if barstate.islast
    f_capBoxes(ladBoxes, 0)
    f_capLabels(ladLabels, 0)
    if engineRun and rowH > 0 and maxRow > 0 and pocIdx >= 0
        pocPrice := f_rowMid(pocIdx)
        float total = upSum + dnSum
        pocShare := total > 0 ? 100.0 * maxRow / total : na
        // value area: grow from the POC toward the heavier neighbour until vaPct of the ladder volume is inside
        float acc = maxRow
        vaLo := pocIdx
        vaHi := pocIdx
        while acc < total * vaPct / 100.0 and (vaLo > 0 or vaHi < ladRows - 1)
            float above = vaHi < ladRows - 1 ? array.get(rowUp, vaHi + 1) + array.get(rowDn, vaHi + 1) : -1.0
            float below = vaLo > 0 ? array.get(rowUp, vaLo - 1) + array.get(rowDn, vaLo - 1) : -1.0
            if above >= below
                vaHi += 1
                acc  += above
            else
                vaLo -= 1
                acc  += below
        int x0 = ladX0
        if showLadder
            float pad   = rowH * 0.1
            int   tOver = ladRight ? 0 : 22                        // fainter when it sits on top of candles
            // every row must fit the box cap: fewer gradient steps before fewer rows (Paper & Ink: one box per row)
            int   steps = isMono ? 1 : math.max(1, math.min(ladSteps, math.floor((maxBoxes - 2) / ladRows)))
            for r = 0 to ladRows - 1
                float t   = array.get(rowUp, r) + array.get(rowDn, r)
                int   len = math.round(t / maxRow * ladWidth)
                if len > 0
                    float mid   = f_rowMid(r)
                    bool  isPoc = r == pocIdx
                    bool  above = mid > close
                    bool  inVA  = r >= vaLo and r <= vaHi
                    color c     = isPoc ? cAcc : above ? cBear : cBull
                    // heaviest rows brightest: base transparency 16 (100 %) .. 70 (thin), +10 outside the value area
                    int   tBase = tOver + math.round(16 + (1.0 - t / maxRow) * 54) + (inVA ? 0 : 10)
                    float yT    = mid + rowH * 0.5 - pad
                    float yB    = mid - rowH * 0.5 + pad
                    int   nSeg  = math.min(steps, len)
                    for k = 0 to nSeg - 1
                        int xa = x0 + math.round(len * k / nSeg)
                        int xb = x0 + math.round(len * (k + 1) / nSeg)
                        if xb > xa
                            // bright at the base, fading outward toward 94
                            int tk = math.min(96, tBase + math.round((94 - math.min(94, tBase)) * k / nSeg))
                            if isMono
                                // direction by style: rows above price are dashed outlines, rows below are filled
                                array.push(ladBoxes, box.new(f_xo(xa), yT, f_xr(xb), yB,
                                     border_color = color.new(c, above ? f_t(15) : 100), border_width = 1,
                                     border_style = above ? line.style_dashed : line.style_solid,
                                     bgcolor = color.new(c, above ? 94 : f_t(tk))))
                            else
                                array.push(ladBoxes, box.new(f_xo(xa), yT, f_xr(xb), yB,
                                     border_color = color.new(c, 100), border_width = 1, bgcolor = color.new(c, f_t(tk))))
            // balance bar under the ladder: up-close share in the bull colour, down-close share in the bear colour
            if showBal and not na(balance)
                float bT = ladBase - rowH * 0.7
                float bB = ladBase - rowH * 1.5
                int   bu = math.round(balance * ladWidth)
                if bu > 0
                    array.push(ladBoxes, box.new(f_xo(x0), bT, f_xr(x0 + bu), bB,
                         border_color = color.new(cBull, 100), border_width = 1, bgcolor = color.new(cBull, f_t(30))))
                if ladWidth - bu > 0
                    array.push(ladBoxes, box.new(f_xo(x0 + bu), bT, f_xr(x0 + ladWidth), bB,
                         border_color = color.new(cBear, isMono ? f_t(15) : 100), border_width = 1,
                         border_style = isMono ? line.style_dashed : line.style_solid,
                         bgcolor = color.new(cBear, isMono ? 94 : f_t(30))))
            f_capBoxes(ladBoxes, maxBoxes)
        // POC tag: short ("POC 24,550.25") and right after the end of the POC row, which is the longest row, so it
        // never sits on the ladder. Right of price that is its own column (fresh lane); otherwise it shares the wall
        // column past the last bar.
        if ladRight
            f_laneReset()
        int xTag = ladRight ? x0 + (showLadder ? ladWidth : 0) + 1 : lineEnd + 1
        if showPoc
            string pTxt = "POC " + f_px(pocPrice)
            array.push(ladLabels, f_tag(xTag, f_lane(pocPrice, 0, tagGap), pTxt, cAcc, label.style_label_left, f_size(tagSz)))
        // balance tag: just UNDER the balance bar, starting at the ladder base, so it stays inside the ladder's width
        if showLadder and showBal and not na(balance)
            string bTxt = str.tostring(math.round(balance * 100)) + " % up · " + str.tostring(100 - math.round(balance * 100)) + " % down" + (hasVol ? "" : " (time)")
            array.push(ladLabels, f_tag(x0, ladBase - rowH * 1.5, bTxt, f_grad(cBear, cNeu, cBull, balance), label.style_label_upper_left, f_size(tagSz)))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 14. DASHBOARD + CANDLES + ALERTS
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Candle score: the ladder's up-volume share, or the close's position between the primary walls (0 = at the sell
// wall -> bear colour, 1 = at the buy wall -> bull colour). na before the engine runs, so old history stays untouched.
float wallPos = na
if not na(sW) and not na(bW) and sW.price > bW.price
    wallPos := math.min(1.0, math.max(0.0, (sW.price - close) / (sW.price - bW.price)))
float paintScore = paintSrc == "Position between walls" ? wallPos : balance
barcolor(paintMode == "Mono" ? f_candlePaint(paintMode, 0.5) : engineOn and not na(paintScore) ? f_candlePaint(paintMode, paintScore) : na)
 
if showDash and barstate.islast
    int nEqh = f_poolCount(1)
    int nEql = f_poolCount(-1)
    Pool  nP = na
    float nD = na
    for p in pools
        if p.state == 0 and (na(nD) or math.abs(p.price - close) < nD)
            nD := math.abs(p.price - close)
            nP := p
    string sTxt = na(sW) ? "—" : f_px(sW.price) + " · " + str.tostring(math.round(sW.strength)) + " % · " + f_atrTxt(sW.price - close) + " ATR"
    string bTxt = na(bW) ? "—" : f_px(bW.price) + " · " + str.tostring(math.round(bW.strength)) + " % · " + f_atrTxt(close - bW.price) + " ATR"
    string balMean = na(balance) ? "" : balance >= 0.55 ? "up-close volume leads" : balance <= 0.45 ? "down-close volume leads" : "two-sided"
    string balTxt  = na(balance) ? "—" : str.tostring(math.round(balance * 100)) + " % up · " + balMean + (hasVol ? "" : " (time)")
    color  balCol  = na(balance) ? cNeu : f_grad(cBear, cNeu, cBull, balance)
    string pocTxt  = na(pocPrice) ? "—" : f_px(pocPrice) + " · " + f_atrTxt(pocPrice - close) + " ATR " + (pocPrice >= close ? "above" : "below")
    string poolTxt = "EQH " + str.tostring(nEqh) + " · EQL " + str.tostring(nEql)
    string nTxt    = na(nP) ? "none live" : (nP.side == 1 ? "EQH x" : "EQL x") + str.tostring(nP.count) + " " + f_px(nP.price) + " · " + f_atrTxt(nD) + " ATR " + (nP.side == 1 ? "above" : "below")
    color  nCol    = na(nP) ? cNeu : nP.side == 1 ? cBear : cBull
    // the Read line is built from parts and wrapped onto a new line before it passes ~60 characters
    array<string> parts = array.new<string>()
    if not na(sW) and not na(bW)
        array.push(parts, f_atrTxt(sW.price - close) + " ATR to the sell wall")
        array.push(parts, f_atrTxt(close - bW.price) + " ATR to the buy wall")
    else if not na(sW)
        array.push(parts, f_atrTxt(sW.price - close) + " ATR to the sell wall")
        array.push(parts, "no buy wall")
    else if not na(bW)
        array.push(parts, "No sell wall")
        array.push(parts, f_atrTxt(close - bW.price) + " ATR to the buy wall")
    else
        array.push(parts, "No walls in the ladder yet")
    if not na(nP)
        array.push(parts, (nP.side == 1 ? "EQH" : "EQL") + " pool " + f_atrTxt(nD) + " ATR")
    string read = ""
    string cur  = ""
    for s in parts
        if cur == ""
            cur := s
        else if str.length(cur) + 3 + str.length(s) > 60
            read += cur + " \n "
            cur  := s
        else
            cur += " · " + s
    read += cur
 
    f_dBegin()
    f_dHead("LIQUIDITY DEPTH")
    if dashCompact
        f_dRow("Walls", (na(sW) ? "—" : f_px(sW.price)) + " / " + (na(bW) ? "—" : f_px(bW.price)), cTxt,
             "Sell wall / buy wall prices: the heaviest volume rows above and below price in the ladder. Drawn as the dotted lines with 'sell wall' / 'buy wall' tags.")
    else
        f_dRow("Sell wall", sTxt, cBear, "The heaviest volume row ABOVE price in the depth ladder: price · strength (that row's volume as a share of the heaviest row) · distance in ATR(14). Liquidity readers see a heavy row as a price where a lot of business was done: price often slows or stalls on the first return there, and a close through it ('swept', the line shrinks to a dim stub) shows the volume there was absorbed. On the chart: the dotted line and its 'sell wall' tag.")
        f_dRow("Buy wall",  bTxt, cBull, "The heaviest volume row BELOW price in the depth ladder: price · strength (that row's volume as a share of the heaviest row) · distance in ATR(14). Read the same way as the sell wall, from below: a heavy row under price that has not been closed through yet. On the chart: the dotted line and its 'buy wall' tag.")
        f_dRow("Balance", balTxt, balCol, hasVol ? "Volume of up-close bars as a share of all the volume in the ladder window. 55 % or more: up-close volume leads; 45 % or less: down-close volume leads; between: two-sided. It describes who printed the volume in the window, not what comes next. On the chart: the two-tone bar under the ladder." : "This symbol has no volume: every bar weighs 1, so the ladder is time at price and the balance is a share of bars, not of volume.")
        f_dRow("POC", pocTxt, cAcc, "Point of control: the single heaviest row of the ladder over the last " + str.tostring(ladBars) + " bars, the price the window traded most. Readers treat it as the window's fair value: far from it price is stretched against the window, around it price is in balance. On the chart: the accent row with the 'POC price' tag at its end.")
        f_dRow("Pools in view", poolTxt, cTxt, "Live equal highs (EQH) and equal lows (EQL): two or more confirmed swings within the equal tolerance. Resting stop orders tend to cluster just beyond such obvious equal levels, which is why liquidity readers watch them; a wick past the tolerance marks the pool 'swept' (a dim stub). Strong one-way moves sweep pools fast, so 0 is a normal reading right after a trend leg. On the chart: the rails with 'EQH x2' / 'EQL x3' tags.")
        f_dRow("Nearest pool", nTxt, nCol, "The live pool closest to the current price, with its distance in ATR(14). On the chart: the same tag, which carries the same ATR distance.")
    f_dRead(read)
 
alertcondition(sellSweptNow, "Sell wall swept", "Liquidity Depth Walls: a bar closed through a sell wall")
alertcondition(buySweptNow,  "Buy wall swept",  "Liquidity Depth Walls: a bar closed through a buy wall")
alertcondition(poolSweptNow, "Pool swept",      "Liquidity Depth Walls: a wick traded through an equal highs / lows pool")
alertcondition(newPoolNow,   "New pool",        "Liquidity Depth Walls: a new equal highs / lows pool formed")

← 返回列表