Unbroke Volume Zones & Delta

bryanhulinsky23 · study · 722 行 · 点赞 31 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 (MPL 2.0).
// (c) Unbroke - free & open-source. Not financial advice. For educational purposes only.
// volume zones & delta 0.2 (Research review fixes, Oct 26 2026; not yet compiled in TradingView)
// Original code. Delta is an ESTIMATE from lower-timeframe bars (or bar shape), not real bid/ask data.
//@version=6
indicator("Unbroke Volume Zones & Delta", shorttitle = "UB VolZone", overlay = true, max_boxes_count = 300, max_lines_count = 100, max_labels_count = 60)
 
//==============================================================================
// INPUTS
//==============================================================================
G_ZN = "1. Zones"
volLen   = input.int(20, "Volume average length", minval = 5, maxval = 200, group = G_ZN, tooltip = "Average volume of this many earlier bars (the current bar is not included).", display = display.none)
volMult  = input.float(2.0, "Heavy volume = x times average", minval = 1.0, step = 0.1, group = G_ZN, tooltip = "A bar is 'heavy' when its volume is at least this many times the average.", display = display.none)
moveAtr  = input.float(1.0, "Strong move = x ATR beyond the bar", minval = 0.2, step = 0.1, group = G_ZN, tooltip = "A heavy bar becomes a zone only when a later bar CLOSES this many ATR(14) above its high (demand) or below its low (supply).", display = display.none)
moveBars = input.int(5, "Move must happen within x bars", minval = 1, maxval = 20, group = G_ZN, tooltip = "How many bars after the heavy bar the strong move may take. The zone appears on the bar that confirms the move, never earlier.", display = display.none)
maxH     = input.float(1.0, "Max zone height x ATR", minval = 0.1, step = 0.1, group = G_ZN, tooltip = "Very tall bars are trimmed to this height, measured from the side where the move started.", display = display.none)
maxAge   = input.int(500, "Remove zones after x bars", minval = 50, maxval = 5000, group = G_ZN, display = display.none)
 
G_DL = "2. Delta (estimate)"
dMethod  = input.string("Auto", "Buy/sell split", options = ["Auto", "Lower timeframe", "Bar shape"], group = G_DL, tooltip = "Lower timeframe: volume of up intrabars counts as buying, down intrabars as selling, flat ones split half/half. Bar shape: the bar's volume is split by where it closed in its range. Auto uses lower-timeframe bars when available and falls back to bar shape. Both are ESTIMATES, not real bid/ask data.", display = display.none)
ltfIn    = input.timeframe("1", "Lower timeframe", group = G_DL, tooltip = "Must be lower than the chart timeframe. TradingView loads a limited number of intrabars, so older bars use the bar-shape fallback.", display = display.none)
bigDelta = input.float(2.0, "Big delta bar = x times average |delta|", minval = 1.0, step = 0.1, group = G_DL, display = display.none)
 
G_DSP = "3. Display"
maxShow  = input.int(6, "Max zones shown", minval = 1, maxval = 12, group = G_DSP, tooltip = "Only the zones nearest to price are drawn.", display = display.none)
hideAtr  = input.float(8.0, "Hide zones farther than x ATR", minval = 1, step = 0.5, group = G_DSP, display = display.none)
showBrk  = input.bool(true, "Show recently broken zones (dimmed)", group = G_DSP, display = display.none)
showSplit = input.bool(true, "Buy/sell bar inside each zone", group = G_DSP, tooltip = "Green part = estimated buying share of the heavy bar's volume, red = selling share.", display = display.none)
glowOn   = input.bool(true, "Glow on the nearest zone per side", group = G_DSP, display = display.none)
showLbl  = input.bool(true, "Zone labels", group = G_DSP, display = display.none)
lblSize  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_DSP, display = display.none)
markDelta = input.bool(true, "Mark big delta bars", group = G_DSP, tooltip = "Small dot above (buying) or below (selling) bars whose estimated delta is unusually large.", display = display.none)
 
G_PRF = "4. Stats panel"
showPanel = input.bool(true, "Show panel", inline = "pp", group = G_PRF, display = display.none)
panelPos  = input.string("Bottom Right", "", options = ["Bottom Right", "Bottom Center", "Middle Right", "Bottom Left", "Top Left"], inline = "pp", group = G_PRF, display = display.none)
dashSize  = input.string("Tiny", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_PRF, display = display.none)
reactAtr  = input.float(0.5, "Held = move of x ATR away", minval = 0.1, step = 0.1, group = G_PRF, tooltip = "A touch HELD if price then moves this many ATR(14) away from the zone on the side it came from, before any bar closes through the far side.", display = display.none)
statBars  = input.int(12, "Within N bars", minval = 2, maxval = 200, group = G_PRF, tooltip = "A close through the far side first counts as BROKE. Neither within N bars = no result (still counted in n).", display = display.none)
kGhost    = input.int(10, "Random levels per zone", minval = 1, maxval = 20, group = G_PRF, tooltip = "Each new zone gets exactly this many random levels of the same height, on the same side of price, never overlapping the zone. Half sit between price and the zone, half beyond it, so on average they are as far from price as the zone. They are tested exactly like zones.", display = display.none)
gCap      = input.int(300, "Max random levels at once", minval = 20, maxval = 500, group = G_PRF, tooltip = "Safety cap. With 10 per zone and at most 30 zones it is not reached at the defaults.", display = display.none)
seed      = input.int(7, "Random seed", minval = 1, group = G_PRF, display = display.none)
G_MC = "5. Match check (Pine vs Python)"
mcOn   = input.bool(false, "Match check", group = G_MC, tooltip = "OFF by default. Shows a table of integer checksums and a page of individual zones, computed on confirmed bars only, for the free Pine vs Python match (MATCH_FREE_PLAN.md). Does not change any zone or count.", display = display.none)
mcPage = input.int(0, "Match page", minval = 0, group = G_MC, tooltip = "0 = the last 15 zones created. 1 = zones 1-15, 2 = 16-30, and so on.", display = display.none)
mcSize = input.string("Large", "Match text size", options = ["Normal", "Large", "Huge"], group = G_MC, display = display.none)
ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = G_PRF, tooltip = "Auto follows your chart background.", display = display.none)
 
//==============================================================================
// UNBROKE STYLE KIT for Pine v6 - paste this block into every Unbroke script.
// (c) Unbroke - MPL 2.0. Original code. ASCII only.
// Paste it AFTER the inputs. The script must declare, before this block:
//     string ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], ...)
// Libraries need publishing, so for now this is pasted, not imported.
// Version: style kit 1.3 (2026-10-24: all table colors opaque; T_BG follows chart.bg_color in Auto). Keep every copy identical.
//==============================================================================
 
// ---- 1. Palette (fixed brand constants) -------------------------------------
UB_GREEN_DEEP = #1B7A5A   // brand green (light-theme frame, deep fills)
UB_GREEN      = #3FBF8F   // brand green bright (dark-theme frame, bull)
UB_INK        = #141210   // dark background / text on light
UB_PAPER      = #F6F3EC   // light background / text on dark
UB_BULL       = #3FBF8F   // up / safe / reacted
UB_BEAR       = #E5534B   // down / danger / broke
UB_NEUTRAL    = #8C8A85   // mid lines, neutral state, muted marks
UB_AMBER      = #F2A93B   // caution, opening range
UB_SKY        = #4C9AFF   // info levels (previous day), entries
UB_VIOLET     = #8B5CF6   // secondary info (London, previous week)
UB_PINK       = #E0559A   // Asia session
UB_CYAN       = #14B8C4   // overnight session
 
// ---- 2. Theme detection -----------------------------------------------------
ub_lum(color c) =>
    0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)
ub_isLight() =>
    ub_lum(chart.bg_color) > 128
bool UB_LIGHT  = ubThemeMode == "Light" or (ubThemeMode == "Auto" and ub_isLight())
color T_BG     = color.new(ubThemeMode == "Auto" ? chart.bg_color : UB_LIGHT ? UB_PAPER : UB_INK, 0)
color T_ROW    = color.new(UB_LIGHT ? #FFFFFF : #1E1C19, 0)
color T_HEAD   = color.new(UB_LIGHT ? #E3F1EA : #0F2A20, 0)
color T_TEXT   = UB_LIGHT ? UB_INK : UB_PAPER
color T_MUTED  = UB_LIGHT ? #5C574F : #A8A39A
color T_FRAME  = color.new(UB_LIGHT ? UB_GREEN_DEEP : UB_GREEN, 0)
color T_BORDER = color.new(UB_LIGHT ? #E2DCCF : #2A2723, 0)
color T_TRACK  = color.new(UB_LIGHT ? #E2DCCF : #2E2B27, 0)
 
// Readable text on any fill color.
ub_txtOn(color c) =>
    ub_lum(c) > 150 ? UB_INK : #FFFFFF
 
// ---- 3. Sizes and positions -------------------------------------------------
ub_size(string s) =>
    s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Large" ? size.large : size.normal
ub_sizeUp(string s) =>
    s == "Tiny" ? size.small : s == "Small" ? size.normal : s == "Large" ? size.huge : size.large
ub_pos(string s) =>
    s == "Top Right" ? position.top_right : s == "Bottom Right" ? position.bottom_right : s == "Top Left" ? position.top_left : s == "Middle Left" ? position.middle_left : s == "Middle Right" ? position.middle_right : s == "Bottom Center" ? position.bottom_center : s == "Top Center" ? position.top_center : position.bottom_left
 
// ---- 4. Gradient colors -----------------------------------------------------
// Strength color: bear at lo, neutral at the midpoint, bull at hi.
ub_strength(float v, float lo, float hi) =>
    float mid = (lo + hi) / 2.0
    v >= mid ? color.from_gradient(v, mid, hi, UB_NEUTRAL, UB_BULL) : color.from_gradient(v, lo, mid, UB_BEAR, UB_NEUTRAL)
// Room color: 0 = red, 50 = amber, 100 = green (risk meters).
ub_room(float pct) =>
    pct >= 50 ? color.from_gradient(pct, 50, 100, UB_AMBER, UB_BULL) : color.from_gradient(pct, 0, 50, UB_BEAR, UB_AMBER)
 
// ---- 5. Glow for drawn lines (plots: see DESIGN_SYSTEM.md, plot() is global-only) --
// g = a var array<line> owned by the caller (created empty). Two halo lines are
// created once, then moved. Call on barstate.islast. x1 = start bar, y = price.
ub_glow(array<line> g, int x1, float y, color c, int baseW, bool on) =>
    if array.size(g) == 0
        array.push(g, line.new(na, na, na, na, xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 88), width = baseW + 6))
        array.push(g, line.new(na, na, na, na, xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 72), width = baseW + 3))
    bool ok = on and not na(y) and not na(x1)
    for i = 0 to 1
        line gl = array.get(g, i)
        line.set_x1(gl, ok ? x1 : na)
        line.set_x2(gl, ok ? x1 + 1 : na)
        line.set_y1(gl, ok ? y : na)
        line.set_y2(gl, ok ? y : na)
        line.set_color(gl, color.new(c, i == 0 ? 88 : 72))
 
// ---- 6. Dashboard builder ---------------------------------------------------
// Header row: "UNBROKE" | title (merged) | subtitle. ncols >= 2.
ub_header(table t, int ncols, string title, string sub, hsz) =>
    table.cell(t, 0, 0, "UNBROKE", text_color = T_FRAME, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_left, text_formatting = text.format_bold)
    if ncols == 2
        table.cell(t, 1, 0, title, text_color = T_TEXT, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_right, text_formatting = text.format_bold, tooltip = sub)
    else
        table.cell(t, 1, 0, title, text_color = T_TEXT, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_left, text_formatting = text.format_bold)
        table.cell(t, ncols - 1, 0, sub, text_color = T_MUTED, bgcolor = T_HEAD, text_size = hsz, text_halign = text.align_right)
        if ncols > 3
            table.merge_cells(t, 1, 0, ncols - 2, 0)
    0  // explicit return keeps if/else branch types from mismatching (CE10235)
 
// Footer note across all columns (tiny, muted).
ub_footer(table t, int ncols, int row, string txt) =>
    table.cell(t, 0, row, txt, text_color = T_MUTED, bgcolor = T_BG, text_size = size.tiny, text_halign = text.align_left)
    if ncols > 1
        table.merge_cells(t, 0, row, ncols - 1, row)
 
// Segmented progress bar in table cells c0 .. c0+segs-1 of one row.
// Each lit segment takes the room color of its own position (red -> amber -> green).
ub_bar(table t, int c0, int row, int segs, float pct, string tip) =>
    for i = 0 to segs - 1
        float mark = (i + 0.5) * 100.0 / segs
        bool lit = not na(pct) and pct >= mark
        table.cell(t, c0 + i, row, "", bgcolor = lit ? ub_room(mark) : T_TRACK, width = 1.4, height = 1.6, tooltip = tip)
 
// ASCII meter, e.g. "######...." for 60% with n = 10.
ub_meter(float pct, int n) =>
    int k = na(pct) ? 0 : int(math.round(math.max(0.0, math.min(100.0, pct)) / 100.0 * n))
    str.repeat("#", k) + str.repeat(".", n - k)
 
// ---- 7. PROOF panel (signature element of every Unbroke indicator) ----------
// Percent helper: a of b, as 0-100 float, na when b = 0.
ub_pct(int a, int b) =>
    b > 0 ? a * 100.0 / b : na
// Proof column headers (5 columns): Signal | n | Hit % | vs random | Verdict.
ub_proofHead(table t, int row, string c0, tsz) =>
    table.cell(t, 0, row, c0, text_color = T_MUTED, bgcolor = T_BG, text_size = tsz, text_halign = text.align_left)
    table.cell(t, 1, row, "n", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
    table.cell(t, 2, row, "Hit %", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
    table.cell(t, 3, row, "vs random", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
    table.cell(t, 4, row, "Verdict", text_color = T_MUTED, bgcolor = T_BG, text_size = tsz)
 
//==================================== END UNBROKE STYLE KIT ===================
 
//==============================================================================
// DELTA ESTIMATE
//==============================================================================
bool ltfOk = timeframe.in_seconds(ltfIn) < timeframe.in_seconds(timeframe.period)
[ibO, ibC, ibV] = request.security_lower_tf(syminfo.tickerid, ltfIn, [open, close, volume], ignore_invalid_timeframe = true)
float buyV = 0.0
float sellV = 0.0
bool usedIntra = false
float vol = nz(volume)
if dMethod != "Bar shape" and ltfOk and array.size(ibV) > 0
    usedIntra := true
    for k = 0 to array.size(ibV) - 1
        float iv = nz(array.get(ibV, k))
        float d = array.get(ibC, k) - array.get(ibO, k)
        if d > 0
            buyV += iv
        else if d < 0
            sellV += iv
        else
            buyV += iv / 2
            sellV += iv / 2
if not usedIntra
    float rng = high - low
    float f = rng > 0 ? (close - low) / rng : 0.5
    buyV := vol * f
    sellV := vol * (1 - f)
float delta = buyV - sellV
var float cvd = 0.0
cvd += delta
float dAvg = ta.sma(math.abs(delta), 50)
float dEma = ta.ema(delta, 20)
float cvdChg = cvd - nz(cvd[20], cvd)
bool bigBuy = barstate.isconfirmed and not na(dAvg) and delta > bigDelta * dAvg
bool bigSell = barstate.isconfirmed and not na(dAvg) and -delta > bigDelta * dAvg
plotshape(markDelta and bigBuy, "Big buying delta", shape.circle, location.abovebar, color.new(UB_BULL, 15), size = size.tiny, display = display.pane)
plotshape(markDelta and bigSell, "Big selling delta", shape.circle, location.belowbar, color.new(UB_BEAR, 15), size = size.tiny, display = display.pane)
 
//==============================================================================
// ENGINE (closed bars only)
//==============================================================================
type Zone
    int   id
    float top
    float bot
    int   side
    int   born
    int   base
    float vol
    float bv
    float sv
    float bShare
    bool  agree
    bool  broken = false
    int   brokeAt = -1
    int   busy = -1
    int   tests = 0
    int   holds = 0
 
type Ghost
    int   pid
    float top
    float bot
    int   side
    int   born
    bool  broken = false
    int   busy = -1
 
type Ev
    float top
    float bot
    int   dir
    int   start
    float m
    bool  isRand
    bool  agree
    int   zid
 
f_rand(int k, int salt) =>
    float x = math.sin((time / 60000.0) * 12.9898 + k * 78.233 + salt * 37.719 + seed * 4.1414) * 43758.5453
    x - math.floor(x)
 
// ATR copied from vzd_engine.atr_wilder: bar 0 TR = high - low, seed = mean of the first 14 TRs
// (bars 0-13, value on bar 13), then (a*(n-1)+tr)/n. ta.atr would seed one bar later (TR na on bar 0).
f_atrW(int n) =>
    var float a = na
    var float acc = 0.0
    float pcl = close[1]
    float tr = na(pcl) ? high - low : math.max(high - low, math.abs(high - pcl), math.abs(low - pcl))
    if na(a)
        acc += tr
        if bar_index == n - 1
            a := acc / n
    else
        a := (a * (n - 1) + tr) / n
    a
float atr = f_atrW(14)
float atrPrev = atr[1]
float prevC = close[1]
float vAvg = ta.sma(vol, volLen)[1]
bool heavy = not na(vAvg) and vAvg > 0 and vol >= volMult * vAvg
 
var array<Zone>  zs  = array.new<Zone>()
var array<Ghost> gs  = array.new<Ghost>()
var array<Ev>    evs = array.new<Ev>()
var array<int>   usedB = array.new_int()
var int zidCtr = 0
// stats: 0 zones, 1 random, 2 zones delta agrees, 3 zones delta disagrees
var array<int> sN  = array.new_int(4, 0)
var array<int> sH  = array.new_int(4, 0)
var array<int> sB  = array.new_int(4, 0)
// MATCH CHECK bookkeeping (indexed by zone id; integers only; read-only for the engine)
var array<int> pzT   = array.new_int()   // bar time the zone was created
var array<int> pzBi  = array.new_int()   // bar index the zone was created
var array<int> pzTop = array.new_int()   // top in ticks
var array<int> pzBot = array.new_int()   // bottom in ticks
var array<int> pzSd  = array.new_int()   // side
var array<int> pzN   = array.new_int()   // resolved touches
var array<int> pzH   = array.new_int()   // held
var array<int> pzB   = array.new_int()   // broke
var int mcGh = 0
var int mcSumTop = 0
var int mcSumBot = 0
var int mcFirstT = time
var int mcN = 0
var int mcLastT = na
var int MC_P = 1000003   // prime for the order-sensitive hashes (same as kNN H2): h = (h * 131 + x % P) % P stays < 2^31
var int mcHR = 0          // HR: random-level rows in creation order (bar, side, top ticks, bot ticks)
f_hstep(int h, int x) => (h * 131 + x % MC_P) % MC_P
 
f_eval(Ev e, int k) =>
    int r = 0
    if e.dir == 1
        if close < e.bot
            r := 2
        else if k >= 1 and high >= e.top + e.m
            r := 1
    else
        if close > e.top
            r := 2
        else if k >= 1 and low <= e.bot - e.m
            r := 1
    if r == 0 and k >= statBars - 1
        r := 3
    r
 
f_add(int j, int out) =>
    sN.set(j, sN.get(j) + 1)
    if out == 1
        sH.set(j, sH.get(j) + 1)
    if out == 2
        sB.set(j, sB.get(j) + 1)
 
f_rec(Ev e, int out) =>
    if e.isRand
        f_add(1, out)
    else
        f_add(0, out)
        f_add(e.agree ? 2 : 3, out)
        if mcOn and e.zid < pzN.size()
            pzN.set(e.zid, pzN.get(e.zid) + 1)
            pzH.set(e.zid, pzH.get(e.zid) + (out == 1 ? 1 : 0))
            pzB.set(e.zid, pzB.get(e.zid) + (out == 2 ? 1 : 0))
        for z in zs
            if z.id == e.zid and out == 1
                z.holds += 1
    0  // explicit return keeps if/else branch types from mismatching (CE10235)
 
f_start(float t, float b, int d, bool isR, bool ag, int id) =>
    Ev e = Ev.new(t, b, d, bar_index, reactAtr * atrPrev, isR, ag, id)
    int r = f_eval(e, 0)
    if r > 0
        f_rec(e, r)
    else
        evs.push(e)
    0  // explicit return keeps if/else branch types from mismatching (CE10235)
 
f_isUsed(int b) =>
    bool u = false
    for x in usedB
        if x == b
            u := true
            break
    u
 
bool aEnterD = false
bool aEnterS = false
bool aBreak  = false
bool aNew    = false
bool act = barstate.isconfirmed and not na(atr) and not na(atrPrev) and not na(prevC)
if act
    // 1. resolve open touches
    int i = 0
    while i < evs.size()
        Ev e = evs.get(i)
        int out = f_eval(e, bar_index - e.start)
        if out > 0
            f_rec(e, out)
            evs.remove(i)
        else
            i += 1
    // 2. new touches (zone side as of the previous close)
    for z in zs
        if not z.broken and bar_index > z.busy and bar_index > z.born
            bool tD = z.side == 1 and prevC > z.top and low <= z.top
            bool tS = z.side == -1 and prevC < z.bot and high >= z.bot
            if tD or tS
                z.busy := bar_index + statBars - 1
                z.tests += 1
                aEnterD := aEnterD or tD
                aEnterS := aEnterS or tS
                f_start(z.top, z.bot, z.side, false, z.agree, z.id)
    for g in gs
        if not g.broken and bar_index > g.busy and bar_index > g.born
            if (g.side == 1 and prevC > g.top and low <= g.top) or (g.side == -1 and prevC < g.bot and high >= g.bot)
                g.busy := bar_index + statBars - 1
                f_start(g.top, g.bot, g.side, true, false, g.pid)
    // 3. breaks: a close through the far side
    for z in zs
        if not z.broken and bar_index > z.born and ((z.side == 1 and close < z.bot) or (z.side == -1 and close > z.top))
            z.broken := true
            z.brokeAt := bar_index
            aBreak := true
    for g in gs
        if not g.broken and bar_index > g.born and ((g.side == 1 and close < g.bot) or (g.side == -1 and close > g.top))
            g.broken := true
    // 4. expire
    if zs.size() > 0
        for k = zs.size() - 1 to 0
            Zone z = zs.get(k)
            if bar_index - z.born > maxAge or (z.broken and bar_index - z.brokeAt > 50)
                zs.remove(k)
    if gs.size() > 0
        for k = gs.size() - 1 to 0
            Ghost g = gs.get(k)
            if g.broken or bar_index - g.born > maxAge
                gs.remove(k)
    // 5. new zones: heavy bar j bars ago, then this bar closes moveAtr ATR beyond it
    for j = moveBars to 1
        int bj = bar_index - j
        if heavy[j] and not na(atr[j]) and not f_isUsed(bj)
            float mv = moveAtr * atr[j]
            int side = close >= high[j] + mv ? 1 : close <= low[j] - mv ? -1 : 0
            if side != 0
                usedB.push(bj)
                float mh = maxH * atr[j]
                float top = side == 1 ? math.min(high[j], low[j] + mh) : high[j]
                float bot = side == 1 ? low[j] : math.max(low[j], high[j] - mh)
                float minH = 0.05 * atr[j]
                if top - bot < minH
                    if side == 1
                        top := bot + minH
                    else
                        bot := top - minH
                // overlaps an active same-side zone: add this bar's volume to it instead of stacking a new box
                int ovI = -1
                for [q, oz] in zs
                    if ovI < 0 and not oz.broken and oz.side == side and bot <= oz.top and top >= oz.bot
                        ovI := q
                if ovI >= 0
                    Zone oz = zs.get(ovI)
                    oz.vol += vol[j]
                    oz.bv += buyV[j]
                    oz.sv += sellV[j]
                    oz.bShare := oz.bv + oz.sv > 0 ? oz.bv / (oz.bv + oz.sv) : 0.5
                    oz.agree := (oz.bShare > 0.5) == (side == 1)
                    continue
                float bs = buyV[j] + sellV[j] > 0 ? buyV[j] / (buyV[j] + sellV[j]) : 0.5
                Zone z = Zone.new(zidCtr, top, bot, side, bar_index, bj, vol[j], buyV[j], sellV[j], bs, (bs > 0.5) == (side == 1))
                zidCtr += 1
                zs.push(z)
                if mcOn
                    int tTop = math.round(top / syminfo.mintick)
                    int tBot = math.round(bot / syminfo.mintick)
                    pzT.push(time)
                    pzBi.push(bar_index)
                    pzTop.push(tTop)
                    pzBot.push(tBot)
                    pzSd.push(side)
                    pzN.push(0)
                    pzH.push(0)
                    pzB.push(0)
                    mcSumTop := (mcSumTop + tTop) % 1000003
                    mcSumBot := (mcSumBot + tBot) % 1000003
                aNew := true
                float mid = (top + bot) / 2
                float hh = top - bot
                float dz = math.abs(mid - close)
                float sg = mid > close ? 1.0 : -1.0
                // exactly kGhost random levels per zone (mirrors vzd_engine.py): offset from the zone = hh + |u-1| x zone distance,
                // u ~ U(0.5, 1.5). Even lanes try the price side of the zone (redrawn up to 20 times), odd lanes use the far side,
                // so the random distance from price is centred on the zone's own distance. Never overlaps the zone, never dropped.
                for k = 0 to kGhost - 1
                    if gs.size() >= gCap
                        break
                    float gc = na
                    if k % 2 == 0
                        for a = 0 to 19
                            float u = 0.5 + f_rand(z.id, 10 + 30 * a + k)
                            float x = mid - sg * (hh + math.abs(u - 1) * dz)
                            bool okSide = side == -1 ? x - hh / 2 > close : x + hh / 2 < close
                            if okSide
                                gc := x
                                break
                    if na(gc)
                        float u2 = 0.5 + f_rand(z.id, 10 + k)
                        gc := mid + sg * (hh + math.abs(u2 - 1) * dz)
                    gs.push(Ghost.new(z.id, gc + hh / 2, gc - hh / 2, side, bar_index))
                    mcGh += 1
                    if mcOn
                        int gT = math.round((gc + hh / 2) / syminfo.mintick)
                        int gB = math.round((gc - hh / 2) / syminfo.mintick)
                        mcHR := f_hstep(f_hstep(f_hstep(f_hstep(mcHR, bar_index), side > 0 ? 1 : 2), gT), gB)
    while usedB.size() > 40
        usedB.shift()
    // cap: the oldest zone goes, and its random levels with it (same as vzd_engine.py)
    while zs.size() > 30
        Zone gone = zs.shift()
        if gs.size() > 0
            for k = gs.size() - 1 to 0
                if gs.get(k).pid == gone.id
                    gs.remove(k)
 
if mcOn and barstate.isconfirmed
    mcN := bar_index + 1
    mcLastT := time
 
alertcondition(aEnterD, "Price entered a demand zone", "Unbroke Volume Zones: price entered a demand zone on {{ticker}} {{interval}}")
alertcondition(aEnterS, "Price entered a supply zone", "Unbroke Volume Zones: price entered a supply zone on {{ticker}} {{interval}}")
alertcondition(aBreak, "Zone broken", "Unbroke Volume Zones: a zone was broken (close through it) on {{ticker}} {{interval}}")
alertcondition(aNew, "New zone", "Unbroke Volume Zones: new volume zone on {{ticker}} {{interval}}")
alertcondition(bigBuy or bigSell, "Big delta bar", "Unbroke Volume Zones: big estimated delta bar on {{ticker}} {{interval}}")
 
//==============================================================================
// DRAWING (last bar only)
//==============================================================================
var array<box>   dBox = array.new_box()
var array<line>  dLin = array.new_line()
var array<label> dLbl = array.new_label()
var table panel = na
 
f_fmtVol(float v) =>
    v >= 1e9 ? str.tostring(v / 1e9, "0.0") + "B" : v >= 1e6 ? str.tostring(v / 1e6, "0.0") + "M" : v >= 1e3 ? str.tostring(v / 1e3, "0.0") + "K" : str.tostring(v, "0")
f_pct(int a, int b) => b > 0 ? str.tostring(a * 100.0 / b, "0") + "%" : "-"
f_shade(color c) => UB_LIGHT ? color.rgb(color.r(c) * 0.55, color.g(c) * 0.55, color.b(c) * 0.55) : color.new(c, 0)
f_dist(Zone z) => close > z.top ? close - z.top : close < z.bot ? z.bot - close : 0.0
f_wilson(int h, int n) =>
    float lo = na
    float hi = na
    if n > 0
        float zz = 1.96
        float p = float(h) / n
        float d = 1 + zz * zz / n
        float c = (p + zz * zz / (2.0 * n)) / d
        float w = zz * math.sqrt(p * (1 - p) / n + zz * zz / (4.0 * n * n)) / d
        lo := c - w
        hi := c + w
    [lo, hi]
f_cell(int c, int r, string t, color tc, string tip = "") =>
    panel.cell(c, r, t, text_color = tc, bgcolor = r % 2 == 0 ? T_BG : T_ROW, text_size = ub_size(dashSize), text_halign = c == 0 ? text.align_left : text.align_center, tooltip = tip)
// Read: n, the gap vs random and an approximate 95% interval (per-touch normal approximation; touches are not
// independent, so it is too narrow). Always neutral color: it is descriptive, not a verdict.
f_read(int j) =>
    int n = sN.get(j)
    int nr = sN.get(1)
    string s = "too few (n " + str.tostring(n) + ")"
    if n >= 30 and nr >= 30
        float p1 = sH.get(j) / float(n)
        float p0 = sH.get(1) / float(nr)
        float d = (p1 - p0) * 100
        float m = 196.0 * math.sqrt(p1 * (1 - p1) / n + p0 * (1 - p0) / nr)
        float lo = d - m
        float hi = d + m
        string word = lo > 0 ? "above random" : hi < 0 ? "below random" : "inside noise"
        s := word + " (n " + str.tostring(n) + ", " + (d >= 0 ? "+" : "") + str.tostring(d, "0.0") + " pts, approx. 95% " + str.tostring(lo, "0.0") + " to " + str.tostring(hi, "0.0") + ")" + (n < 100 ? " preview" : "")
    s
f_row(int r, string name, int j, color tc, string tip) =>
    f_cell(0, r, name, tc, tip)
    f_cell(1, r, str.tostring(sN.get(j)), tc, tip)
    f_cell(2, r, f_pct(sH.get(j), sN.get(j)), tc, tip)
    f_cell(3, r, f_pct(sB.get(j), sN.get(j)), tc, tip)
    if j == 1
        f_cell(4, r, "baseline", T_MUTED, tip)
    else
        f_cell(4, r, f_read(j), T_MUTED, "Descriptive, loaded chart history only. Approximate interval, touches not independent. Not evidence that zones are Above random.")
    0  // explicit return keeps if/else branch types from mismatching (CE10235)
 
if barstate.islast
    for b in dBox
        b.delete()
    for l in dLin
        l.delete()
    for l in dLbl
        l.delete()
    dBox.clear()
    dLin.clear()
    dLbl.clear()
    array<Zone> pick = array.new<Zone>()
    array<float> pd = array.new_float()
    for z in zs
        float d = f_dist(z)
        if d <= hideAtr * atr and (not z.broken or showBrk)
            int at = pd.size()
            for [k, v] in pd
                if d < v
                    at := k
                    break
            pd.insert(at, d)
            pick.insert(at, z)
    int shown = math.min(pick.size(), maxShow)
    bool glowD = false
    bool glowS = false
    int nD = 0
    int nS = 0
    float nearD = na
    float nearS = na
    for z in zs
        if not z.broken
            if z.side == 1
                nD += 1
                if z.top < close and (na(nearD) or z.top > nearD)
                    nearD := z.top
            else
                nS += 1
                if z.bot > close and (na(nearS) or z.bot < nearS)
                    nearS := z.bot
    if shown > 0
        for k = 0 to shown - 1
            Zone z = pick.get(k)
            color c = z.side == 1 ? UB_BULL : UB_BEAR
            int x1 = math.max(z.base, bar_index - 4000)
            int x2 = bar_index + 3
            float h = z.top - z.bot
            float edge = z.side == 1 ? z.top : z.bot
            float sgn = z.side == 1 ? -1.0 : 1.0
            int dim = z.broken ? 8 : 0
            // gradient: 4 layers anchored at the price-facing edge, fading inward
            for j = 1 to 4
                float far = edge + sgn * h * j / 4.0
                dBox.push(box.new(x1, math.max(edge, far), x2, math.min(edge, far), border_color = color.new(c, 100), bgcolor = color.new(c, 86 + dim)))
            if z.broken
                dBox.push(box.new(x1, z.top, x2, z.bot, border_color = color.new(c, 60), border_style = line.style_dashed, bgcolor = color.new(c, 100)))
            else
                dLin.push(line.new(x1, edge, x2, edge, color = color.new(c, 10), width = 1))
                bool isNear = z.side == 1 ? not glowD : not glowS
                if glowOn and isNear
                    dLin.push(line.new(x1, edge, x2, edge, color = color.new(c, 88), width = 7))
                    dLin.push(line.new(x1, edge, x2, edge, color = color.new(c, 74), width = 4))
                if z.side == 1
                    glowD := true
                else
                    glowS := true
            // buy/sell split bar: a thin strip in the middle of the zone, from the heavy bar, 20 bars wide
            if showSplit
                int w = 20
                int xb = x1 + int(math.round(w * z.bShare))
                float sy1 = z.bot + h * 0.38
                float sy2 = z.bot + h * 0.62
                dBox.push(box.new(x1, sy2, xb, sy1, border_color = color.new(UB_BULL, 100), bgcolor = color.new(UB_BULL, z.broken ? 70 : 25)))
                dBox.push(box.new(xb, sy2, x1 + w, sy1, border_color = color.new(UB_BEAR, 100), bgcolor = color.new(UB_BEAR, z.broken ? 70 : 25)))
            if showLbl
                string txt = (z.side == 1 ? "Demand " : "Supply ") + f_fmtVol(z.vol) + " | buy " + str.tostring(z.bShare * 100, "0") + "%" + (z.broken ? " | broken" : z.tests > 0 ? " | tested " + str.tostring(z.tests) + "x" : "")
                string tip = (z.side == 1 ? "Demand" : "Supply") + " zone " + str.tostring(z.bot, format.mintick) + " - " + str.tostring(z.top, format.mintick) + "\nHeavy bar volume " + f_fmtVol(z.vol) + ", estimated buy " + str.tostring(z.bShare * 100, "0") + "% / sell " + str.tostring(100 - z.bShare * 100, "0") + "% (estimate, not real bid/ask)\nTested " + str.tostring(z.tests) + "x, held " + str.tostring(z.holds) + "x"
                dLbl.push(label.new(bar_index + 4, (z.top + z.bot) / 2, txt, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(T_BG, 20), textcolor = f_shade(c), size = ub_size(lblSize), text_formatting = text.format_bold, tooltip = tip))
    if showPanel
        if na(panel)
            panel := table.new(ub_pos(panelPos), 5, 10, bgcolor = T_BG, frame_color = T_FRAME, frame_width = 1, border_color = T_BORDER, border_width = 1)
        panel.clear(0, 0, 4, 9)
        ub_header(panel, 5, "Volume Zones & Delta", timeframe.period, ub_sizeUp(dashSize))
        f_cell(0, 1, "Active", T_MUTED)
        f_cell(1, 1, str.tostring(nD) + " demand", f_shade(UB_BULL), na(nearD) ? "" : "Nearest demand top " + str.tostring(nearD, format.mintick))
        panel.merge_cells(1, 1, 2, 1)
        f_cell(3, 1, str.tostring(nS) + " supply", f_shade(UB_BEAR), na(nearS) ? "" : "Nearest supply bottom " + str.tostring(nearS, format.mintick))
        panel.merge_cells(3, 1, 4, 1)
        string tr = dEma > 0 and cvdChg > 0 ? "buying" : dEma < 0 and cvdChg < 0 ? "selling" : "mixed"
        color tc = tr == "buying" ? UB_BULL : tr == "selling" ? UB_BEAR : UB_NEUTRAL
        f_cell(0, 2, "Delta trend", T_MUTED)
        f_cell(1, 2, tr + " | bar " + (delta >= 0 ? "+" : "") + f_fmtVol(math.abs(delta)), f_shade(tc), "Trend = 20-bar average of estimated delta and the 20-bar change in cumulative delta agree. Estimate from " + (usedIntra ? ltfIn + " bars" : "bar shape") + ", not real bid/ask.")
        panel.merge_cells(1, 2, 2, 2)
        f_cell(3, 2, usedIntra ? "src " + ltfIn + " bars" : "src bar shape", T_MUTED, "Where the buy/sell split comes from on the last bar. Older bars may use the bar-shape fallback when intrabar history runs out.")
        panel.merge_cells(3, 2, 4, 2)
        f_cell(0, 3, "Touches", T_MUTED)
        f_cell(1, 3, "n", T_MUTED)
        f_cell(2, 3, "Held", T_MUTED)
        f_cell(3, 3, "Broke", T_MUTED)
        f_cell(4, 3, "Read", T_MUTED)
        string def = "Held = price moved " + str.tostring(reactAtr) + " ATR away within " + str.tostring(statBars) + " bars before a close through the zone. Broke = close through first. Loaded chart history only, descriptive."
        f_row(4, "Random levels", 1, T_MUTED, def + " Random = " + str.tostring(kGhost) + " same-size levels per zone, same side of price, random distance.")
        f_row(5, "All zones", 0, T_TEXT, def)
        f_row(6, "Delta agreed", 2, T_TEXT, "Zones whose heavy bar's estimated delta pointed the same way as the move. " + def)
        f_row(7, "Delta disagreed", 3, T_TEXT, "Zones whose heavy bar's estimated delta pointed against the move. " + def)
        string warn = vol == 0 ? "No volume on this symbol: zones cannot form. " : ""
        panel.cell(0, 8, warn + "Zone and volume tool, not a signal. Delta is an estimate from bars, not real bid/ask. Educational, not financial advice. Past results don't predict future results.", text_color = T_MUTED, bgcolor = T_BG, text_size = size.tiny, text_halign = text.align_left)
        panel.merge_cells(0, 8, 4, 8)
 
//==============================================================================
// DEBUG EXPORT (Data Window only, for the Pine vs Python bar-for-bar match; see PINE_MATCH_PLAN.md)
//==============================================================================
dbgOn = input.bool(false, "Debug values in Data Window", group = G_PRF, tooltip = "For checking this script against the Python reference. Adds numbers to the Data Window / chart data export only.", display = display.none)
plot(dbgOn ? zs.size() : na, "dbg zones", display = display.data_window)
plot(dbgOn ? gs.size() : na, "dbg randoms", display = display.data_window)
plot(dbgOn ? zidCtr : na, "dbg zones created", display = display.data_window)
plot(dbgOn and zs.size() > 0 ? zs.last().top : na, "dbg newest top", display = display.data_window)
plot(dbgOn and zs.size() > 0 ? zs.last().bot : na, "dbg newest bot", display = display.data_window)
plot(dbgOn and zs.size() > 0 ? zs.last().side : na, "dbg newest side", display = display.data_window)
plot(dbgOn ? sN.get(0) : na, "dbg zone n", display = display.data_window)
plot(dbgOn ? sH.get(0) : na, "dbg zone held", display = display.data_window)
plot(dbgOn ? sB.get(0) : na, "dbg zone broke", display = display.data_window)
plot(dbgOn ? sN.get(1) : na, "dbg rand n", display = display.data_window)
plot(dbgOn ? sH.get(1) : na, "dbg rand held", display = display.data_window)
plot(dbgOn ? sB.get(1) : na, "dbg rand broke", display = display.data_window)
plot(dbgOn ? (usedIntra ? 1 : 0) : na, "dbg intrabar delta", display = display.data_window)
 
//==============================================================================
// MATCH CHECK TABLE (Match check input; off by default)
//==============================================================================
var table mcTab = na
f_iso(int t) => na(t) ? "-" : str.format_time(t, "yyyy-MM-dd'T'HH:mm'Z'", "UTC")
f_mcLine(int r, string s) =>
    mcTab.cell(0, r, s, text_color = T_TEXT, bgcolor = T_ROW, text_size = mcSize == "Huge" ? size.huge : mcSize == "Large" ? size.large : size.normal, text_halign = text.align_left, text_font_family = font.family_monospace)
    0  // explicit return (CE10235)
if mcOn and barstate.islast
    if na(mcTab)
        mcTab := table.new(position.top_right, 1, 24, bgcolor = T_ROW, frame_color = T_FRAME, frame_width = 1, border_color = T_BORDER, border_width = 0)
    mcTab.clear(0, 0, 0, 23)
    int nZ = pzT.size()
    f_mcLine(0, "MATCH VZD 0.2 | " + syminfo.tickerid + " | " + timeframe.period + " | tick " + str.tostring(syminfo.mintick))
    f_mcLine(1, "first " + f_iso(mcFirstT) + " | bars " + str.tostring(mcN) + " | last " + f_iso(mcLastT))
    f_mcLine(2, "zones created " + str.tostring(zidCtr) + " | randoms created " + str.tostring(mcGh))
    f_mcLine(3, "zone touches n " + str.tostring(sN.get(0)) + " held " + str.tostring(sH.get(0)) + " broke " + str.tostring(sB.get(0)))
    f_mcLine(4, "rand touches n " + str.tostring(sN.get(1)) + " held " + str.tostring(sH.get(1)) + " broke " + str.tostring(sB.get(1)))
    f_mcLine(5, "sum top ticks " + str.tostring(mcSumTop) + " | sum bot ticks " + str.tostring(mcSumBot) + " (mod 1000003)")
    // HZ: zone rows in creation order (time ms, bar, side 1=D 2=S, top ticks, bot ticks, n, held, broke); display-only
    int hz = 0
    if nZ > 0
        for q = 0 to nZ - 1
            hz := f_hstep(hz, pzT.get(q))
            hz := f_hstep(hz, pzBi.get(q))
            hz := f_hstep(hz, pzSd.get(q) > 0 ? 1 : 2)
            hz := f_hstep(hz, pzTop.get(q))
            hz := f_hstep(hz, pzBot.get(q))
            hz := f_hstep(hz, pzN.get(q))
            hz := f_hstep(hz, pzH.get(q))
            hz := f_hstep(hz, pzB.get(q))
    f_mcLine(6, "HZ " + str.tostring(hz) + " | HR " + str.tostring(mcHR) + " (mod 1000003, order-sensitive)")
    int a = mcPage == 0 ? math.max(0, nZ - 15) : (mcPage - 1) * 15
    int b = math.min(nZ, a + 15)
    int nP = int(math.ceil(nZ / 15.0))
    f_mcLine(7, "page " + (mcPage == 0 ? "last" : str.tostring(mcPage)) + " of " + str.tostring(nP) + " | zones " + str.tostring(a + 1) + "-" + str.tostring(b) + " | id time side top bot n/held/broke")
    int r = 8
    if b > a
        for q = a to b - 1
            f_mcLine(r, str.format("{0,number,000}", q + 1) + " " + f_iso(pzT.get(q)) + " bar " + str.tostring(pzBi.get(q)) + (pzSd.get(q) > 0 ? " D " : " S ") + str.tostring(pzTop.get(q)) + " " + str.tostring(pzBot.get(q)) + " " + str.tostring(pzN.get(q)) + "/" + str.tostring(pzH.get(q)) + "/" + str.tostring(pzB.get(q)))
            r += 1

← 返回列表