Unbroke Auto S/R Zones

bryanhulinsky23 · study · 649 行 · 点赞 13 · 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.
// sr zones 1.1
//@version=6
indicator("Unbroke Auto S/R Zones", shorttitle = "UB SR Zones", overlay = true, behind_chart = false, max_boxes_count = 500, max_lines_count = 100, max_labels_count = 100)
 
//==============================================================================
// INPUTS
//==============================================================================
G_ZN = "1. Zones"
pivL     = input.int(5, "Pivot bars left", minval = 1, maxval = 50, group = G_ZN, tooltip = "A swing high/low must be higher/lower than this many bars on its left.", display = display.none)
pivR     = input.int(5, "Pivot bars right (confirmation delay)", minval = 1, maxval = 50, group = G_ZN, tooltip = "...and than this many bars on its right. A swing is only used once these bars have CLOSED, so every zone appears this many bars after its swing. No look-ahead.", display = display.none)
mergeAtr = input.float(0.5, "Merge swings within x ATR", minval = 0.05, step = 0.05, group = G_ZN, tooltip = "A new swing joins the nearest existing zone if it is within this many ATR(14) of the zone's average price. Otherwise it starts a new zone.", display = display.none)
widthAtr = input.float(0.1, "Zone padding x ATR", minval = 0, step = 0.05, group = G_ZN, tooltip = "Padding added above the highest and below the lowest swing in a zone, in ATR(14) at the time the zone is created.", display = display.none)
minT     = input.int(2, "Minimum swings to show and test", minval = 1, maxval = 10, group = G_ZN, tooltip = "A zone needs at least this many confirmed swings before it is drawn or counted in the Proof panel. It is drawn from the bar it reached this count.", display = display.none)
maxFlips = input.int(2, "Remove after x breaks", minval = 1, maxval = 10, group = G_ZN, tooltip = "Each close through the whole zone is a break and flips its role (support becomes resistance and back). After more than this many breaks the zone is removed.", display = display.none)
maxAge   = input.int(600, "Remove after x bars without a new swing", minval = 50, maxval = 5000, group = G_ZN, tooltip = "Zones with no new swing for this many bars are removed as stale.", display = display.none)
halfLife = input.int(300, "Strength half-life (bars)", minval = 10, maxval = 5000, group = G_ZN, tooltip = "Strength = swings x 0.5^(bars since last swing / half-life). Used only to fade weak and old zones. It is a display heuristic and has NOT been tested.", display = display.none)
maxStore = input.int(50, "Max zones kept in memory", minval = 10, maxval = 100, group = G_ZN, tooltip = "When more zones exist, the one with the oldest last swing is dropped.", display = display.none)
startT   = input.time(timestamp("01 Jan 2000 00:00 +0000"), "Start building zones from", group = G_ZN, tooltip = "Swings before this time are ignored. Default = all loaded bars. Set a later date when matching an export against the Python mirror.", display = display.none)
 
G_DSP = "2. Display"
maxShow  = input.int(6, "Max zones shown", minval = 1, maxval = 20, group = G_DSP, tooltip = "Only the zones nearest to price are drawn.", display = display.none)
hideAtr  = input.float(6.0, "Hide zones farther than x ATR", minval = 0.5, step = 0.5, group = G_DSP, tooltip = "Zones farther than this many ATR(14) from the last close are hidden (same idea as Key Levels).", display = display.none)
glowOn   = input.bool(true, "Glow on the nearest zone per side", group = G_DSP, tooltip = "Soft halo on the price-facing side of the nearest support and the nearest resistance only.", display = display.none)
showLbl  = input.bool(true, "Zone labels", group = G_DSP, tooltip = "Tag inside each zone, near its left side, so it never collides with the Key Levels tags at the right side. 3x = 3 swings (not touches).", display = display.none)
lblBack  = input.int(30, "Label bars back from last bar", minval = 5, maxval = 300, group = G_DSP, tooltip = "Labels sit this many bars left of the last bar (or at the zone start if it is newer).", display = display.none)
lblSize  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_DSP, display = display.none)
 
G_PRF = "3. Proof"
showPanel = input.bool(true, "Show panel", inline = "pp", group = G_PRF, tooltip = "Compact Proof panel. Default Bottom Center so it does not cover the newest candles and sits clear of Key Levels (top right), Risk Guard (top center) and the Backtester (bottom left).", display = display.none)
panelPos  = input.string("Bottom Center", "", options = ["Bottom Center", "Middle Right", "Bottom Right", "Middle Left", "Top Left"], inline = "pp", group = G_PRF, display = display.none)
detailed  = input.bool(false, "Detailed panel", group = G_PRF, tooltip = "Adds the Wilson 95% intervals and the definitions rows.", 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, "Reaction = move of x ATR", minval = 0.1, step = 0.1, group = G_PRF, tooltip = "A touch is a REACTION if price then moves this many ATR(14) (of the bar before the touch) away from the zone on the side it came from, before any bar closes through the whole zone.", display = display.none)
statBars  = input.int(12, "Within N bars", minval = 1, maxval = 200, group = G_PRF, tooltip = "Bars allowed for the reaction, counting the touch bar. A close through the zone first is a BREAK. Neither = no reaction.", display = display.none)
minN      = input.int(20, "Minimum touches for a verdict", minval = 5, maxval = 500, group = G_PRF, display = display.none)
oosT      = input.time(timestamp("26 Oct 2026 00:00 -0400"), "Forward test starts (fixed date)", group = G_PRF, tooltip = "Pre-registered forward date (prereg rev2). Touches from this date on are the forward test.", display = display.none)
readT     = input.time(timestamp("01 Feb 2027 00:00 -0500"), "Registered read (fixed date)", group = G_PRF, tooltip = "The forward result is hidden until this date or until both sides reach the read n, whichever comes first. Before that the panel only shows the n collected.", display = display.none)
readN     = input.int(400, "Read at n per side", minval = 20, group = G_PRF, display = display.none)
kGhost    = input.int(20, "Random levels per zone", minval = 1, maxval = 20, group = G_PRF, tooltip = "Same-side random levels matched on distance, age and width, one per lane. The zone's hit rate is ranked against the lane rates (percentile).", display = display.none)
gCap      = input.int(400, "Max random levels at once", minval = 20, maxval = 400, group = G_PRF, tooltip = "Keeps the script inside TradingView's time limits. When full, new zones get fewer lanes (counted as skipped).", display = display.none)
seed      = input.int(7, "Random seed", minval = 1, group = G_PRF, tooltip = "Seed for the random comparison levels.", display = display.none)
 
G_XP = "4. Export"
xpOn = input.bool(false, "Export mode (data window plots)", group = G_XP, tooltip = "Adds XP plots to the data window and chart export so every touch can be matched one-for-one with tools/sr_zones_mirror.py.", display = display.none)
ubThemeMode = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = G_XP, 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)
 
// 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 ===================
 
//==============================================================================
// ENGINE (closed bars only)
//==============================================================================
type Zone
    int   id
    float hiP
    float loP
    float hw
    float sumP
    int   n
    int   firstBar
    int   lastTouch
    int   pos
    int   flips = 0
    int   busyR = -1
    bool  spawned = false
    int   eligBar = -1
 
// Random comparison level: same side as its parent zone, own width, own breaks, own age.
type Ghost
    int   pid
    int   lane
    float gc
    float up
    float dn
    int   ref
    int   pos
    int   flips = 0
    int   busy = -1
 
type Ev
    float top
    float bot
    int   dir
    int   start
    float m
    int   lane
    bool  fwd
 
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)
 
f_top(Zone z) => z.hiP + z.hw
f_bot(Zone z) => z.loP - z.hw
f_mid(Zone z) => z.sumP / z.n
g_top(Ghost g) => g.gc + g.up
g_bot(Ghost g) => g.gc - g.dn
 
f_isPiv(bool isHigh) =>
    float c = isHigh ? high[pivR] : low[pivR]
    bool ok = not na(c) and bar_index >= pivL + pivR
    if ok
        for j = 0 to pivL + pivR
            if j != pivR
                float v = isHigh ? high[j] : low[j]
                if isHigh ? not (v < c) : not (v > c)
                    ok := false
                    break
    ok
 
float atr = ta.atr(14)
float atrPrev = atr[1]
float prevC = close[1]
bool isPH = f_isPiv(true)
bool isPL = f_isPiv(false)
 
var array<Zone>  zs  = array.new<Zone>()
var array<Ghost> gs  = array.new<Ghost>()
var array<Ev>    evs = array.new<Ev>()
var array<int> idCtr = array.new_int(1, 0)
var array<int> skipCtr = array.new_int(1, 0)
// index: 0 real all, 1 random all, 2 real forward, 3 random forward
var array<int> aN  = array.new_int(4, 0)
var array<int> aRe = array.new_int(4, 0)
var array<int> aBr = array.new_int(4, 0)
// per random lane: index s * 20 + lane, s = 0 all bars, 1 forward
var array<int> lN  = array.new_int(40, 0)
var array<int> lRe = array.new_int(40, 0)
// per-bar export counters: 0 r_new 1 r_res 2 r_react 3 r_break 4 g_new 5 g_res 6 g_react 7 g_break
array<int> xc = array.new_int(8, 0)
 
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_rec(Ev e, int out) =>
    bool g = e.lane >= 0
    int ix = g ? 1 : 0
    for s = 0 to (e.fwd ? 1 : 0)
        int j = ix + 2 * s
        aN.set(j, aN.get(j) + 1)
        if out == 1
            aRe.set(j, aRe.get(j) + 1)
        if out == 2
            aBr.set(j, aBr.get(j) + 1)
        if g
            int li = s * 20 + e.lane
            lN.set(li, lN.get(li) + 1)
            if out == 1
                lRe.set(li, lRe.get(li) + 1)
    int o = g ? 4 : 0
    xc.set(o + 1, xc.get(o + 1) + 1)
    if out == 1
        xc.set(o + 2, xc.get(o + 2) + 1)
    if out == 2
        xc.set(o + 3, xc.get(o + 3) + 1)
 
f_startEv(float t, float b, int d, int lane) =>
    Ev e = Ev.new(t, b, d, bar_index, reactAtr * atrPrev, lane, time >= oosT)
    evs.push(e)
    int o = lane >= 0 ? 4 : 0
    xc.set(o, xc.get(o) + 1)
    int out0 = f_eval(e, 0)
    if out0 > 0
        f_rec(e, out0)
        evs.pop()
 
f_touch(float t, float b, int busy) =>
    int d = 0
    if bar_index > busy
        d := prevC > t ? 1 : prevC < b ? -1 : 0
        if not ((d == 1 and low <= t) or (d == -1 and high >= b))
            d := 0
    d
 
// K same-side random levels at distance |close - mid| x U(0.5, 1.5), never overlapping the zone
f_spawn(Zone z) =>
    z.spawned := true
    z.eligBar := bar_index
    float c = f_mid(z)
    float h = f_top(z) - f_bot(z)
    for k = 0 to kGhost - 1
        if gs.size() >= gCap
            skipCtr.set(0, skipCtr.get(0) + kGhost - k)
            break
        bool ok = false
        float gc = na
        for a = 0 to 2
            float u = 0.5 + f_rand(z.id, 10 + 30 * a + k)
            gc := close + (c - close) * u
            if math.abs(gc - c) >= h
                ok := true
                break
        if ok
            float up = f_top(z) - c
            float dn = c - f_bot(z)
            int ps = close > gc + up ? 1 : close < gc - dn ? -1 : z.pos
            gs.push(Ghost.new(z.id, k, gc, up, dn, z.lastTouch, ps))
        else
            skipCtr.set(0, skipCtr.get(0) + 1)
 
f_addPiv(float p, bool isHigh, int pb) =>
    int best = -1
    float bd = 0.0
    for [i, z] in zs
        float d = math.abs(f_mid(z) - p)
        if best < 0 or d < bd
            best := i
            bd := d
    if best >= 0 and bd <= mergeAtr * atr
        Zone zm = zs.get(best)
        zm.sumP += p
        zm.n += 1
        zm.hiP := math.max(zm.hiP, p)
        zm.loP := math.min(zm.loP, p)
        zm.lastTouch := bar_index
        // F1: random levels follow the parent's new width and age
        for g in gs
            if g.pid == zm.id
                g.up := f_top(zm) - f_mid(zm)
                g.dn := f_mid(zm) - f_bot(zm)
                g.ref := bar_index
        if zm.n >= minT and not zm.spawned
            f_spawn(zm)
    else
        float hw = widthAtr * atr
        int ps = close > p + hw ? 1 : close < p - hw ? -1 : (isHigh ? -1 : 1)
        Zone z = Zone.new(idCtr.get(0), p, p, hw, p, 1, pb, bar_index, ps)
        idCtr.set(0, idCtr.get(0) + 1)
        zs.push(z)
        if minT <= 1
            f_spawn(z)
 
bool act = time >= startT and not na(atr) and not na(atrPrev) and barstate.isconfirmed 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 (levels as of the previous close)
    for z in zs
        if z.n >= minT
            int d = f_touch(f_top(z), f_bot(z), z.busyR)
            if d != 0
                z.busyR := bar_index + statBars - 1
                f_startEv(f_top(z), f_bot(z), d, -1)
    for g in gs
        int d = f_touch(g_top(g), g_bot(g), g.busy)
        if d != 0
            g.busy := bar_index + statBars - 1
            f_startEv(g_top(g), g_bot(g), d, g.lane)
    // 3. breaks flip the role (zones and random levels alike)
    for z in zs
        int np = close > f_top(z) ? 1 : close < f_bot(z) ? -1 : z.pos
        if np != z.pos
            z.flips += 1
            z.pos := np
    for g in gs
        int np = close > g_top(g) ? 1 : close < g_bot(g) ? -1 : g.pos
        if np != g.pos
            g.flips += 1
            g.pos := np
    // 4. remove broken or stale levels
    if zs.size() > 0
        for k = zs.size() - 1 to 0
            Zone z = zs.get(k)
            if z.flips > maxFlips or bar_index - z.lastTouch > maxAge
                zs.remove(k)
    if gs.size() > 0
        for k = gs.size() - 1 to 0
            Ghost g = gs.get(k)
            if g.flips > maxFlips or bar_index - g.ref > maxAge
                gs.remove(k)
    // 5. confirmed swings (seen pivR bars late)
    if isPH
        f_addPiv(high[pivR], true, bar_index - pivR)
    if isPL
        f_addPiv(low[pivR], false, bar_index - pivR)
    // 6. memory cap
    while zs.size() > maxStore
        int o = 0
        for [k, z] in zs
            if z.lastTouch < zs.get(o).lastTouch
                o := k
        zs.remove(o)
 
f_dist(Zone z) =>
    float t = f_top(z)
    float b = f_bot(z)
    close > t ? close - t : close < b ? b - close : 0.0
 
f_near(int side) =>
    float best = na
    float bd = na
    for z in zs
        if z.n >= minT and z.pos == side
            float d = f_dist(z)
            if na(bd) or d < bd
                bd := d
                best := f_mid(z)
    best
 
//==============================================================================
// EXPORT (data window)
//==============================================================================
int xElig = 0
if xpOn
    for z in zs
        if z.n >= minT
            xElig += 1
plot(xpOn ? 110 : na, "XP ver", display = display.data_window)
plot(xpOn ? xc.get(0) : na, "XP r_new", display = display.data_window)
plot(xpOn ? xc.get(1) : na, "XP r_res", display = display.data_window)
plot(xpOn ? xc.get(2) : na, "XP r_react", display = display.data_window)
plot(xpOn ? xc.get(3) : na, "XP r_break", display = display.data_window)
plot(xpOn ? xc.get(4) : na, "XP g_new", display = display.data_window)
plot(xpOn ? xc.get(5) : na, "XP g_res", display = display.data_window)
plot(xpOn ? xc.get(6) : na, "XP g_react", display = display.data_window)
plot(xpOn ? xc.get(7) : na, "XP g_break", display = display.data_window)
plot(xpOn ? zs.size() : na, "XP zones", display = display.data_window)
plot(xpOn ? xElig : na, "XP elig", display = display.data_window)
plot(xpOn ? gs.size() : na, "XP ghosts", display = display.data_window)
plot(xpOn ? skipCtr.get(0) : na, "XP g_skip", display = display.data_window)
plot(xpOn ? f_near(1) : na, "XP nearS", display = display.data_window)
plot(xpOn ? f_near(-1) : na, "XP nearR", display = display.data_window)
 
//==============================================================================
// 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_rate(int j) => aN.get(j) > 0 ? float(aRe.get(j)) / aN.get(j) : na
f_pct(float v) => na(v) ? "-" : str.tostring(v * 100, "0.0") + "%"
 
// Wilson score 95% interval
f_wilson(int h, int n) =>
    float lo = na
    float hi = na
    if n > 0
        float z = 1.96
        float p = float(h) / n
        float d = 1 + z * z / n
        float c = (p + z * z / (2.0 * n)) / d
        float w = z * math.sqrt(p * (1 - p) / n + z * z / (4.0 * n * n)) / d
        lo := c - w
        hi := c + w
    [lo, hi]
 
// percentile of the zone hit rate among the lane rates (ties count half)
f_pctile(int s, float zr) =>
    int m = 0
    float below = 0.0
    for k = 0 to kGhost - 1
        int n = lN.get(s * 20 + k)
        if n > 0
            float r = float(lRe.get(s * 20 + k)) / n
            m += 1
            below += r < zr ? 1.0 : r == zr ? 0.5 : 0.0
    m > 0 and not na(zr) ? 100.0 * below / m : na
 
f_laneMeanN(int s) =>
    int m = 0
    int t = 0
    for k = 0 to kGhost - 1
        int n = lN.get(s * 20 + k)
        if n > 0
            m += 1
            t += n
    m > 0 ? float(t) / m : 0.0
 
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)
 
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_ciTxt(int j) =>
    [lo, hi] = f_wilson(aRe.get(j), aN.get(j))
    na(lo) ? "-" : f_pct(lo) + " to " + f_pct(hi)
 
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()
    // nearest eligible zones within the ATR window
    array<Zone> pick = array.new<Zone>()
    array<float> pd = array.new_float()
    for z in zs
        float d = f_dist(z)
        if z.n >= minT and d <= hideAtr * atr
            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 glowS = false
    bool glowR = false
    if shown > 0
        for k = 0 to shown - 1
            Zone z = pick.get(k)
            float t = f_top(z)
            float b = f_bot(z)
            float h = t - b
            color c = z.pos == 1 ? UB_BULL : UB_BEAR
            float st = z.n * math.pow(0.5, float(bar_index - z.lastTouch) / halfLife)
            float sn = math.min(1.0, st / 4.0)
            // F4: drawn from the bar the zone became usable, not from its first swing
            int x1 = math.max(z.eligBar >= 0 ? z.eligBar : z.firstBar, bar_index - 4000)
            // reaction side = the side facing price (top of support, bottom of resistance)
            float dlt = z.pos == 1 ? t : b
            float sgn = z.pos == 1 ? -1.0 : 1.0
            int layT = int(86 + 8 * (1 - sn))
            // smooth gradient: 5 stacked layers, all starting at the reaction side, so opacity fades inward
            for j = 1 to 5
                float far = dlt + sgn * h * j / 5.0
                dBox.push(box.new(x1, math.max(dlt, far), bar_index, math.min(dlt, far), border_color = color.new(c, 100), bgcolor = color.new(c, layT)))
            dLin.push(line.new(x1, dlt, bar_index, dlt, color = color.new(c, int(30 * (1 - sn))), width = 1))
            bool isNear = z.pos == 1 ? not glowS : not glowR
            if glowOn and isNear
                dLin.push(line.new(x1, dlt, bar_index, dlt, color = color.new(c, 88), width = 7))
                dLin.push(line.new(x1, dlt, bar_index, dlt, color = color.new(c, 75), width = 4))
            if z.pos == 1
                glowS := true
            else
                glowR := true
            if showLbl
                string txt = (z.pos == 1 ? "S " : "R ") + str.tostring(f_mid(z), format.mintick) + " | " + str.tostring(z.n) + "x" + (z.flips > 0 ? " | flip" : "")
                string tip = (z.pos == 1 ? "Support" : "Resistance") + " zone " + str.tostring(b, format.mintick) + " - " + str.tostring(t, format.mintick) + "\n" + str.tostring(z.n) + "x = " + str.tostring(z.n) + " confirmed swings (not touches). Breaks: " + str.tostring(z.flips) + "\nFade strength " + str.tostring(st, "0.0") + " (display heuristic, untested). Bars since last swing: " + str.tostring(bar_index - z.lastTouch) + "\nDrawn from the bar it became usable. Old chart history is not evidence; see the Proof panel."
                dLbl.push(label.new(math.max(x1, bar_index - lblBack), f_mid(z), txt, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(T_BG, 25), 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, "Auto S/R Zones", timeframe.period, ub_sizeUp(dashSize))
        float nS = f_near(1)
        float nR = f_near(-1)
        f_cell(0, 1, "Nearest", T_MUTED)
        f_cell(1, 1, na(nS) ? "S none" : "S " + str.tostring(nS, format.mintick) + " (" + str.tostring((close - nS) / atr, "0.0") + " ATR)", f_shade(UB_BULL))
        panel.merge_cells(1, 1, 2, 1)
        f_cell(3, 1, na(nR) ? "R none" : "R " + str.tostring(nR, format.mintick) + " (" + str.tostring((nR - close) / atr, "0.0") + " ATR)", f_shade(UB_BEAR))
        panel.merge_cells(3, 1, 4, 1)
        ub_proofHead(panel, 2, "Proof", ub_size(dashSize))
        string defTip = "Hit = price moves " + str.tostring(reactAtr) + " ATR away within " + str.tostring(statBars) + " bars before closing through. Random = " + str.tostring(kGhost) + " same-side levels per zone matched on distance, age and width."
        // random baseline first (design system rule)
        f_cell(0, 3, "Random (" + str.tostring(kGhost) + " lanes)", T_MUTED, defTip)
        f_cell(1, 3, str.tostring(aN.get(1)), T_MUTED, defTip)
        f_cell(2, 3, f_pct(f_rate(1)), T_MUTED, defTip)
        f_cell(3, 3, "-", T_MUTED, defTip)
        f_cell(4, 3, "baseline", T_MUTED, defTip)
        // in-sample: descriptive only (F9)
        float p0 = f_rate(0)
        float pc0 = f_pctile(0, p0)
        string isTip = "Loaded history, including bars used while building the tool. Descriptive only, no verdict. Zones " + str.tostring(aRe.get(0)) + " hits of " + str.tostring(aN.get(0)) + "; random " + str.tostring(aRe.get(1)) + " of " + str.tostring(aN.get(1)) + "."
        f_cell(0, 4, "Zones, history", T_MUTED, isTip)
        f_cell(1, 4, str.tostring(aN.get(0)), T_MUTED, isTip)
        f_cell(2, 4, f_pct(p0), T_MUTED, isTip)
        f_cell(3, 4, na(p0) or na(f_rate(1)) ? "-" : (p0 >= f_rate(1) ? "+" : "") + str.tostring((p0 - f_rate(1)) * 100, "0.0") + " pts", T_MUTED, isTip)
        f_cell(4, 4, "descriptive" + (na(pc0) ? "" : " | pct " + str.tostring(pc0, "0")), T_MUTED, isTip)
        // forward: hidden until the registered read (F10)
        float lmF = f_laneMeanN(1)
        bool ready = time >= readT or (aN.get(2) >= readN and lmF >= readN)
        string fTip = "Pre-registered forward test from the fixed start date. The result stays hidden until the read date or until zones and the random-lane mean both reach n >= " + str.tostring(readN) + ", so it cannot be peeked at. The panel shows an approximate difference and CI only; the registered pass/fail (Python mirror session bootstrap and random-lane percentile) is reported in the published read, not on the chart."
        f_cell(0, 5, "Zones, forward", T_TEXT, fTip)
        f_cell(1, 5, str.tostring(aN.get(2)), T_TEXT, fTip)
        if ready
            float p2 = f_rate(2)
            float p3 = f_rate(3)
            float pc2 = f_pctile(1, p2)
            [zl, zh] = f_wilson(aRe.get(2), aN.get(2))
            [rl, rh] = f_wilson(aRe.get(3), aN.get(3))
            string vt = "insufficient data"
            color vc = UB_NEUTRAL
            if aN.get(2) >= minN and aN.get(3) >= minN
                bool beat = zl > rh and pc2 > 97.5
                bool worse = zh < rl
                // display-only CI from the existing Wilson bounds; feeds no signal, alert, plot or export
                float hw = math.sqrt(math.pow((zh - zl) / 2, 2) + math.pow((rh - rl) / 2, 2))
                float dl = (p2 - p3) - hw
                float dh = (p2 - p3) + hw
                vt := "vs random: " + (p2 >= p3 ? "+" : "") + str.tostring((p2 - p3) * 100, "0.0") + " pts (approx. 95% CI " + str.tostring(dl * 100, "0.0") + " to " + str.tostring(dh * 100, "0.0") + "), this chart's history only, not a forecast"
            f_cell(2, 5, f_pct(p2), T_TEXT, fTip)
            f_cell(3, 5, na(p2) or na(p3) ? "-" : (p2 >= p3 ? "+" : "") + str.tostring((p2 - p3) * 100, "0.0") + " pts", T_TEXT, fTip)
            f_cell(4, 5, vt, f_shade(vc), fTip)
        else
            f_cell(2, 5, "hidden", T_MUTED, fTip)
            f_cell(3, 5, "-", T_MUTED, fTip)
            f_cell(4, 5, "recording " + str.tostring(math.min(aN.get(2), int(lmF))) + "/" + str.tostring(readN), UB_AMBER, fTip)
        int r = 6
        if detailed
            f_cell(0, r, "95% Wilson, history: zones " + f_ciTxt(0) + " | random " + f_ciTxt(1) + " (touches cluster, so these are too narrow)", T_MUTED)
            panel.merge_cells(0, r, 4, r)
            r += 1
            f_cell(0, r, ready ? "95% Wilson, forward: zones " + f_ciTxt(2) + " | random " + f_ciTxt(3) : "95% Wilson, forward: hidden until the registered read", T_MUTED)
            panel.merge_cells(0, r, 4, r)
            r += 1
            f_cell(0, r, "hit = " + str.tostring(reactAtr) + " ATR in " + str.tostring(statBars) + " bars | swings " + str.tostring(pivR) + " bars late | lanes skipped " + str.tostring(skipCtr.get(0)) + " | live random " + str.tostring(gs.size()), T_MUTED)
            panel.merge_cells(0, r, 4, r)
            r += 1
        // one readable footer line (kit footer is size.tiny)
        panel.cell(0, r, "sr zones 1.1 | Educational, not financial advice. Past results don't predict future results.", text_color = T_MUTED, bgcolor = T_BG, text_size = size.small, text_halign = text.align_left)
        panel.merge_cells(0, r, 4, r)

← 返回列表