Level Respect Map [ML]

Market_Logic_India · study · 558 行 · 点赞 69 · 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/
//@version=6
// ═════════════════════════════════════════════════════════════════════════════
//  © Market_Logic_India                                                  MPL-2.0
//  Level Respect Map [ML] — Volume-Snapped Levels, Measured              v6
//  shorttitle: LvlRespect
//  OPEN-SOURCE (MPL-2.0). Free to study, use and adapt under the licence terms;
//  attribution appreciated.
// -----------------------------------------------------------------------------
//  ★ WHAT THIS TOOL DOES ★
//    Most support/resistance tools plot many possible lines and assert a score.
//    This one does the opposite: it draws fewer, more precise levels and grades
//    each by its OWN measured respect-rate — how often THIS exact level has held.
//
//    1. DISCOVER — confirmed swing pivots (ATR-prominence).
//    2. RELOCATE — each pivot is pulled onto the nearest high-volume NODE within
//       an ATR radius (pull scaled by node evidence), so a level is where
//       structure turned AND where size changed hands. Provenance is recorded
//       (pivot-only / node-snapped / strong-node). No volume → price-interaction
//       nodes, flagged DATA: price-only.
//    3. LIFECYCLE — every level is tracked bar-by-bar from birth using only past
//       information: touches counted, holds vs breaks resolved by a triple
//       barrier, role flipped on break-and-retest (FRESH / TESTED / HELD /
//       BROKEN / FLIPPED). Reconstructed, never recomputed on the last bar.
//    4. MEASURE — each level carries a Wilson lower-bound hold-rate (age-decayed;
//       the single strongest level is deflated for best-of-many). A grade blends
//       that measured truth with structural evidence, measured-weight rising as
//       tests accrue (BUILDING → MEASURED).
//
//  ★ DESIGN PRINCIPLE ★  MEASURE, DON'T ASSERT.
//
//  ★ DATA (reality) ★  Volume-at-price for the node relocation comes from the
//    flow symbol — NIFTY current-month FUTURES by default (the cash index has no
//    real volume); the chart symbol is the price axis. Nothing uses an options /
//    open-interest feed. Set Asset mode = Generic for any liquid instrument.
//
//  NON-REPAINT — levels, lifecycle, the hold test, calibration and deflation all
//    resolve on CONFIRMED bars; the live bar is provisional; Wilson LB is lagged.
//
//  CONCEPT CREDITS (public techniques synthesised here)
//    • Levels predict turns + post-break acceleration — C. Osler (2000, 2001).
//    • Bounce probability decays with age — Chung & Bellotti (2021).
//    • Volume-weighted level potential — Martyushev et al. (2025).
//    • Market/Volume Profile, POC — J. P. Steidlmayer.
//    • Binomial proportion confidence interval — E. B. Wilson (1927).
//    • Triple-barrier labelling & deflation — M. López de Prado.
//      Implementation is the author's own.
//
//  DISCLAIMER — Research and education only. Not financial advice, not a signal
//    service, not a guarantee of future results. Respect-rates are descriptive,
//    deflated, limited-sample frequencies on this chart — context, not a promise.
//    Validate independently and manage your own risk.
// ═════════════════════════════════════════════════════════════════════════════
indicator("Level Respect Map [ML]", "LvlRespect", overlay = true,
     max_lines_count = 500, max_labels_count = 500, max_boxes_count = 100,
     max_bars_back = 3000, dynamic_requests = true)
 
// ═════════════════════════ 00 · ASSET & FLOW SOURCE ═════════════════════════
g0 = "00 · Asset & flow source"
assetMode = input.string("NIFTY", "Asset mode", options = ["NIFTY", "Generic"], group = g0,
     tooltip = "NIFTY: flow volume from NSE:NIFTY1! (cash index has no real volume); chart symbol is the price axis. Generic: flow volume from the chart symbol.")
flowOverride = input.string("", "Flow symbol (volume source) — blank = auto", group = g0,
     tooltip = "Volume-bearing symbol for the node profile. Blank + NIFTY = NSE:NIFTY1!. Blank + Generic = the chart symbol.")
 
// ═════════════════════════ 01 · PIVOTS ══════════════════════════════════════
g1 = "01 · Pivots"
pivL = input.int(10, "Pivot left bars", minval = 2, maxval = 60, group = g1)
pivR = input.int(10, "Pivot right bars", minval = 2, maxval = 60, group = g1,
     tooltip = "A pivot is confirmed this many bars after it forms (signals are delayed by this much — the honest cost of a confirmed swing).")
promATR = input.float(1.0, "Min pivot prominence (× ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = g1,
     tooltip = "Ignore shallow swings: the pivot must stand at least this far (in ATR) above/below its own window.")
 
// ═════════════════════════ 02 · RELOCATION (node snap) ══════════════════════
g2 = "02 · Relocation (node snap)"
profLook = input.int(500, "Volume profile window (bars)", minval = 100, maxval = 2000, group = g2,
     tooltip = "Rolling, decayed volume-at-price window used to find high-volume nodes.")
binMultATR = input.float(0.20, "Bin height (× ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = g2)
relocRadATR = input.float(1.5, "Relocation search radius (× ATR)", minval = 0.3, maxval = 5.0, step = 0.1, group = g2,
     tooltip = "A pivot snaps only to a node within this distance; otherwise it stays at the raw pivot.")
relocPull = input.float(0.6, "Snap pull (0 = none, 1 = full)", minval = 0.0, maxval = 1.0, step = 0.05, group = g2,
     tooltip = "How far a pivot is pulled toward a moderate node. A strong node snaps fully regardless.")
evidMin = input.float(0.15, "Min node evidence to snap", minval = 0.02, maxval = 0.9, step = 0.01, group = g2)
evidStrong = input.float(0.40, "Strong-node evidence", minval = 0.1, maxval = 1.0, step = 0.05, group = g2)
 
// ═════════════════════════ 03 · LIFECYCLE & HOLD TEST ═══════════════════════
g3 = "03 · Lifecycle & hold test"
touchTol = input.float(0.25, "Touch tolerance (× ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = g3)
holdM    = input.float(0.8, "Hold barrier (bounce ≥ × ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = g3)
breakS   = input.float(0.5, "Break barrier (close through ≥ × ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = g3)
holdH    = input.int(20, "Hold-test horizon (bars)", minval = 3, maxval = 100, group = g3)
mergeTol = input.float(0.4, "Merge tolerance (× ATR)", minval = 0.1, maxval = 2.0, step = 0.1, group = g3,
     tooltip = "A new pivot within this distance of an existing level is merged, not added.")
maxLevels = input.int(30, "Max levels tracked", minval = 6, maxval = 80, group = g3)
 
// ═════════════════════════ 04 · STRENGTH & GRADE ════════════════════════════
g4 = "04 · Strength & grade"
minN   = input.int(3, "Min tests before a hold-% is shown", minval = 1, maxval = 20, group = g4,
     tooltip = "Below this many resolved tests a level reads BUILDING — a grade shows, a hold-% does not.")
priorK = input.float(4.0, "Measured-vs-prior crossover (k)", minval = 1.0, maxval = 20.0, step = 1.0, group = g4,
     tooltip = "Measured weight = n / (n + k). Higher k = the structural prior dominates longer before the measured hold-rate takes over.")
ageHalf = input.int(500, "Age half-life (bars)", minval = 50, maxval = 3000, group = g4,
     tooltip = "A level's grade decays with age (older levels respected less, per Chung-Bellotti).")
 
// ═════════════════════════ 05 · DISPLAY ═════════════════════════════════════
g5 = "05 · Display"
showMinGrade = input.int(30, "Only draw levels grade ≥", minval = 0, maxval = 90, group = g5)
showReloc = input.bool(false, "Show relocation ticks (pivot → node)", group = g5)
showHUD   = input.bool(true, "Dashboard HUD", group = g5)
hudPos    = input.string("Top Right", "HUD position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = g5)
hudSize   = input.string("Small", "HUD text size", options = ["Tiny", "Small", "Normal"], group = g5)
rightOff  = input.int(14, "Label right offset (bars)", minval = 2, maxval = 60, group = g5)
 
g6 = "06 · Colors"
colSup = input.color(#089981, "Support", group = g6)
colRes = input.color(#F23645, "Resistance", group = g6)
colTxt = input.color(#FFFFFF, "Label text", group = g6)
 
g7 = "07 · Alerts"
alApproach = input.bool(true, "Approach a Strong+ level", group = g7)
alHold     = input.bool(true, "Hold confirmed", group = g7)
alBreak    = input.bool(true, "Break (close-through)", group = g7)
alFlip     = input.bool(false, "Flip (role reversal)", group = g7)
strongGrade = input.int(60, "  └ 'Strong' grade threshold", minval = 30, maxval = 95, group = g7)
 
// ═════════════════════════ HELPERS (top-level) ══════════════════════════════
f_txtSize(string s) => s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
f_px(float v) => na(v) ? "–" : str.tostring(v, format.mintick)
f_pct(float v) => na(v) ? "–" : str.tostring(v * 100.0, "#") + "%"
 
// approximate Bonferroni/Šidák z for best-of-M deflation (monotone, conservative)
f_defZ(float m) => m > 1.0 ? 1.96 + 0.42 * math.log(m) : 1.96
 
f_wilsonZ(float k, float n, float z) =>
    float out = 0.0
    if n > 0
        float p = k / n
        float den = 1.0 + z*z/n
        float ctr = p + z*z/(2.0*n)
        float mrg = z * math.sqrt(math.max(p*(1.0-p)/n + z*z/(4.0*n*n), 0.0))
        out := math.max((ctr - mrg)/den, 0.0)
    out
f_wilson(float k, float n) => f_wilsonZ(k, n, 1.96)
 
// ═════════════════════════ FLOW SYMBOL & PROFILE ════════════════════════════
string _flowSym = flowOverride != "" ? flowOverride : (assetMode == "NIFTY" ? "NSE:NIFTY1!" : syminfo.tickerid)
float fVol = request.security(_flowSym, timeframe.period, volume, lookahead = barmerge.lookahead_off)
 
float _rng = math.max(high - low, syminfo.mintick)
float safeAtr = nz(ta.atr(14), _rng)
 
var float binH   = na
var float anchor = na
var float binMaxV = 0.0
var map<int, float> binTot = map.new<int, float>()
float decay = profLook > 0 ? math.pow(0.5, 1.0 / profLook) : 1.0
var bool hasAnyVol = false
 
// deposit one bar into bin k (reference-mutates binTot; tracks running max)
// deposit one bar into bin k (map mutation is allowed in a function); returns the new bin value
f_depositBin(int k, float add) =>
    float nv = nz(binTot.get(k)) + add
    binTot.put(k, nv)
    nv
 
// relocation scan: nearest high-volume node (excess over neighbourhood) within radius
// returns [nodeCenter, excess]
f_relocate(float px) =>
    float bestExcess = 0.0
    float bestCenter = px
    if not na(binH) and binTot.size() > 0
        int k0 = int(math.floor((px - anchor) / binH))
        int rad = math.max(1, int(math.ceil(relocRadATR * safeAtr / binH)))
        for k = k0 - rad to k0 + rad
            if binTot.contains(k)
                float v = binTot.get(k)
                float sum = 0.0
                int cnt = 0
                for j = k - 3 to k + 3
                    sum += nz(binTot.get(j))
                    cnt += 1
                float avg = cnt > 0 ? sum / cnt : 0.0
                float excess = v - avg
                if excess > bestExcess
                    bestExcess := excess
                    bestCenter := anchor + (k + 0.5) * binH
    [bestCenter, bestExcess]
 
// ═════════════════════════ LEVEL TYPE & REGISTRY ════════════════════════════
type Lvl
    float px
    float rawPx = na
    int   originSide
    int   birthBar
    int   touches = 0
    int   holds = 0
    float evidence = 0.5
    int   prov = 0
    bool  pend = false
    int   pendBar = na
    int   pendDir = 0
    float pendPred = 0.5
    bool  brokenEver = false
    int   lastOutcome = 0
    int   lastTouchBar = na
    bool  inBand = false
 
var array<Lvl> reg = array.new<Lvl>()
var float calErr = 0.0
var float calN = 0.0
 
// composite grade 0..1 (measured-primary, structural prior, age-decayed)
f_grade01(Lvl L) =>
    int n = L.touches
    float hLB = f_wilson(L.holds, n)
    float a = n / (n + priorK)
    float base = a * hLB + (1.0 - a) * L.evidence
    float ageB = bar_index - L.birthBar
    float ageMult = math.pow(0.5, ageB / math.max(ageHalf, 1))
    math.max(0.0, math.min(1.0, base * (0.6 + 0.4 * ageMult)))
 
f_status(Lvl L) =>
    L.touches == 0 ? "FRESH" : (L.brokenEver and L.lastOutcome == 1) ? "FLIPPED" : L.lastOutcome == -1 ? "BROKEN" : L.lastOutcome == 1 ? "HELD" : "TESTED"
 
f_provTxt(int p) => p == 2 ? "strong-node" : p == 1 ? "node-snapped" : "pivot-only"
 
// ═════════════════════════ REGIME ══════════════════════════════════════════
float erNet  = math.abs(close - nz(close[10], close))
float erPath = math.sum(math.abs(close - nz(close[1], close)), 10)
float er = erPath > 0 ? erNet / erPath : 0.0
bool  trending = er >= 0.35
 
// ═════════════════════════ ENGINE (confirmed bars) ══════════════════════════
float ph = ta.pivothigh(high, pivL, pivR)
float pl = ta.pivotlow(low, pivL, pivR)
float promHi = (nz(ph) - ta.lowest(low, pivL + pivR + 1)) / safeAtr
float promLo = (ta.highest(high, pivL + pivR + 1) - nz(pl)) / safeAtr
 
if barstate.isconfirmed
    // anchor/bin init
    if na(anchor) and not na(safeAtr)
        anchor := close
        binH   := math.max(binMultATR * safeAtr, syminfo.mintick)
 
    // profile deposit (decay + prune, then add this bar)
    if not na(binH)
        if decay < 1.0 and binTot.size() > 0
            array<int> dk = binTot.keys()
            for di = 0 to dk.size() - 1
                int k = dk.get(di)
                float nv = binTot.get(k) * decay
                if nv < 0.000001
                    binTot.remove(k)
                else
                    binTot.put(k, nv)
            binMaxV := binMaxV * decay
        float add = (not na(fVol) and fVol > 0) ? fVol : 1.0
        if not na(fVol) and fVol > 0
            hasAnyVol := true
        int kLo = int(math.floor((low  - anchor) / binH))
        int kHi = int(math.floor((high - anchor) / binH))
        int span = math.max(kHi - kLo, 0)
        if span <= 300
            float perBin = span == 0 ? 1.0 : 1.0 / (span + 1)
            for k = kLo to kHi
                binMaxV := math.max(binMaxV, f_depositBin(k, add * perBin))
 
    // new pivots → relocate → create (with merge guard)
    if not na(ph) and promHi >= promATR
        [nodeC, excess] = f_relocate(ph)
        float evid = binMaxV > 0 ? math.min(1.0, excess / binMaxV) : 0.0
        float newPx = ph
        int prov = 0
        if evid >= evidStrong
            newPx := nodeC
            prov := 2
        else if evid >= evidMin
            newPx := ph + relocPull * (nodeC - ph)
            prov := 1
        bool dup = false
        if reg.size() > 0
            for i = 0 to reg.size() - 1
                if math.abs(reg.get(i).px - newPx) <= mergeTol * safeAtr
                    dup := true
        if not dup
            reg.push(Lvl.new(px = newPx, rawPx = ph, originSide = 1, birthBar = bar_index - pivR, evidence = math.min(1.0, 0.4 + 0.3 * (prov / 2.0) + 0.3 * math.min(1.0, promHi / 3.0)), prov = prov))
 
    if not na(pl) and promLo >= promATR
        [nodeC, excess] = f_relocate(pl)
        float evid = binMaxV > 0 ? math.min(1.0, excess / binMaxV) : 0.0
        float newPx = pl
        int prov = 0
        if evid >= evidStrong
            newPx := nodeC
            prov := 2
        else if evid >= evidMin
            newPx := pl + relocPull * (nodeC - pl)
            prov := 1
        bool dup = false
        if reg.size() > 0
            for i = 0 to reg.size() - 1
                if math.abs(reg.get(i).px - newPx) <= mergeTol * safeAtr
                    dup := true
        if not dup
            reg.push(Lvl.new(px = newPx, rawPx = pl, originSide = -1, birthBar = bar_index - pivR, evidence = math.min(1.0, 0.4 + 0.3 * (prov / 2.0) + 0.3 * math.min(1.0, promLo / 3.0)), prov = prov))
 
    // lifecycle: touches + triple-barrier per level
    if reg.size() > 0
        float tolA = touchTol * safeAtr
        float mA = holdM * safeAtr
        float sA = breakS * safeAtr
        for i = 0 to reg.size() - 1
            Lvl L = reg.get(i)
            bool nowIn = low <= L.px + tolA and high >= L.px - tolA
            bool fresh = nowIn and not L.inBand
            L.inBand := nowIn
            if fresh and not L.pend and bar_index > L.birthBar
                L.pend := true
                L.pendBar := bar_index
                L.pendDir := close[1] > L.px ? 1 : -1
                L.pendPred := f_grade01(L)
                L.lastTouchBar := bar_index
            if L.pend
                bool broke = L.pendDir > 0 ? close < L.px - sA : close > L.px + sA
                bool held  = L.pendDir > 0 ? high >= L.px + mA : low <= L.px - mA
                bool expired = bar_index - L.pendBar >= holdH
                if broke or held or expired
                    bool isHold = broke ? false : held ? true : (L.pendDir > 0 ? close > L.px : close < L.px)
                    L.touches := L.touches + 1
                    if isHold
                        L.holds := L.holds + 1
                        L.lastOutcome := 1
                    else
                        L.lastOutcome := -1
                        L.brokenEver := true
                    calN := calN + 1.0
                    calErr := calErr + math.abs(L.pendPred - (isHold ? 1.0 : 0.0))
                    L.pend := false
 
    // trim to cap: drop the lowest-grade level when over
    if reg.size() > maxLevels
        int worst = 0
        float worstG = 1.1
        for i = 0 to reg.size() - 1
            float gg = f_grade01(reg.get(i))
            if gg < worstG
                worstG := gg
                worst := i
        reg.remove(worst)
 
// ═════════════════════════ NEAREST / EXP READS ══════════════════════════════
var float nSupPx = na
var float nResPx = na
var float nSupG = na
var float nResG = na
var float nSupLB = na
var float nResLB = na
 
if barstate.isconfirmed
    nSupPx := na
    nResPx := na
    nSupG := na
    nResG := na
    nSupLB := na
    nResLB := na
    if reg.size() > 0
        for i = 0 to reg.size() - 1
            Lvl L = reg.get(i)
            float g = f_grade01(L)
            float lb = f_wilson(L.holds, L.touches)
            if L.px <= close
                if na(nSupPx) or L.px > nSupPx
                    nSupPx := L.px
                    nSupG := g
                    nSupLB := lb
            else
                if na(nResPx) or L.px < nResPx
                    nResPx := L.px
                    nResG := g
                    nResLB := lb
 
float calib = calN > 0 ? 1.0 - calErr / calN : na
string dataMode = hasAnyVol ? "futures-vol" : "price-only"
 
// ═════════════════════════ DRAWING ══════════════════════════════════════════
var array<line>  dLn = array.new<line>()
var array<label> dLb = array.new<label>()
 
f_clear() =>
    if dLn.size() > 0
        for i = 0 to dLn.size() - 1
            line.delete(dLn.get(i))
        dLn.clear()
    if dLb.size() > 0
        for i = 0 to dLb.size() - 1
            label.delete(dLb.get(i))
        dLb.clear()
    0
 
var table hud = na
if barstate.islast and na(hud)
    hud := table.new(hudPos == "Top Left" ? position.top_left : hudPos == "Bottom Right" ? position.bottom_right : hudPos == "Bottom Left" ? position.bottom_left : position.top_right, 7, 16, bgcolor = color.new(#0B0E14, 8), frame_color = color.new(#2A3447, 40), frame_width = 1, border_color = color.new(#2A3447, 60), border_width = 1)
 
if barstate.islast
    f_clear()
    int xR = bar_index + rightOff
    if reg.size() > 0
        for i = 0 to reg.size() - 1
            Lvl L = reg.get(i)
            int grade = int(math.round(f_grade01(L) * 100))
            if grade >= showMinGrade
                bool isSup = L.px <= close
                color col = isSup ? colSup : colRes
                int n = L.touches
                float lb = f_wilson(L.holds, n)
                int trans = math.max(0, 70 - grade)
                int wid = grade >= 66 ? 2 : 1
                int x1 = math.max(L.birthBar, bar_index - 2000)
                line ln = line.new(x1, L.px, xR, L.px, xloc = xloc.bar_index, color = color.new(col, math.min(80, trans)), width = wid, style = trending ? line.style_dashed : line.style_solid)
                dLn.push(ln)
                string hold = n < minN ? "BUILDING" : str.tostring(L.holds) + "/" + str.tostring(n) + " (LB " + f_pct(lb) + ")"
                string txt = (isSup ? "▲ S " : "▼ R ") + f_px(L.px) + " · " + str.tostring(grade) + " · " + hold + " · " + f_provTxt(L.prov) + " · " + f_status(L)
                dLb.push(label.new(xR, L.px, txt, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(col, 12), textcolor = colTxt, size = size.tiny))
                if showReloc and L.prov > 0 and not na(L.rawPx)
                    dLn.push(line.new(math.max(L.birthBar, bar_index - 2000), L.rawPx, math.max(L.birthBar, bar_index - 2000), L.px, xloc = xloc.bar_index, color = color.new(col, 40), width = 1, style = line.style_dotted))
 
// ═════════════════════════ HUD ══════════════════════════════════════════════
f_cell(int c, int r, string t, color bg, color fg) =>
    table.cell(hud, c, r, t, bgcolor = bg, text_color = fg, text_size = f_txtSize(hudSize), text_halign = text.align_left)
    0
 
if barstate.islast and showHUD and not na(hud)
    table.clear(hud, 0, 0, 6, 15)
    color hb = color.new(#182030, 0)
    color rb = color.new(#10141C, 20)
    color fg = color.new(#E0E0E0, 0)
    int building = 0
    if reg.size() > 0
        for i = 0 to reg.size() - 1
            if reg.get(i).touches < minN
                building := building + 1
    int rr = 0
 
    // ① context header
    f_cell(0, rr, "LEVEL RESPECT · " + (trending ? "TREND" : "RANGE") + " · DATA: " + dataMode + " · levels " + str.tostring(reg.size()) + " · calib " + (na(calib) ? "–" : str.tostring(calib, "0.00")), hb, fg)
    table.merge_cells(hud, 0, rr, 6, rr)
    rr += 1
 
    // ② ladder header
    f_cell(0, rr, "Side", rb, color.silver)
    f_cell(1, rr, "Price", rb, color.silver)
    f_cell(2, rr, "Grade", rb, color.silver)
    f_cell(3, rr, "Hold (Wil)", rb, color.silver)
    f_cell(4, rr, "Age", rb, color.silver)
    f_cell(5, rr, "Status", rb, color.silver)
    f_cell(6, rr, "From", rb, color.silver)
    rr += 1
 
    // ladder: top 6 by grade
    if reg.size() > 0
        int shown = 0
        array<bool> usedL = array.new<bool>(reg.size(), false)
        for pass = 0 to 5
            if shown < 6
                int best = -1
                float bestG = -1.0
                for i = 0 to reg.size() - 1
                    if not usedL.get(i)
                        float g = f_grade01(reg.get(i))
                        if g > bestG
                            bestG := g
                            best := i
                if best >= 0
                    usedL.set(best, true)
                    Lvl L = reg.get(best)
                    int grade = int(math.round(bestG * 100))
                    if grade >= showMinGrade
                        bool isSup = L.px <= close
                        color sc = isSup ? colSup : colRes
                        int n = L.touches
                        string hold = n < minN ? "BUILDING" : str.tostring(L.holds) + "/" + str.tostring(n) + " · " + f_pct(f_wilson(L.holds, n))
                        f_cell(0, rr, isSup ? "S" : "R", rb, sc)
                        table.cell(hud, 1, rr, f_px(L.px), bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 2, rr, str.tostring(grade), bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 3, rr, hold, bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 4, rr, str.tostring(bar_index - L.birthBar) + "b", bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 5, rr, f_status(L), bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 6, rr, f_provTxt(L.prov), bgcolor = rb, text_color = color.silver, text_size = f_txtSize(hudSize))
                        rr += 1
                        shown += 1
 
    // ③ nearest S/R
    f_cell(0, rr, "Nearest  S " + f_px(nSupPx) + " (g " + (na(nSupG) ? "–" : str.tostring(int(math.round(nSupG * 100)))) + ")   R " + f_px(nResPx) + " (g " + (na(nResG) ? "–" : str.tostring(int(math.round(nResG * 100)))) + ")", hb, fg)
    table.merge_cells(hud, 0, rr, 6, rr)
    rr += 1
 
    // ④ plain read
    string read = na(nSupPx) and na(nResPx) ? "No graded levels yet — building history." : "Price " + f_px(close) + (not na(nSupPx) ? " · S " + f_px(nSupPx) + " below" : "") + (not na(nResPx) ? " · R " + f_px(nResPx) + " above" : "") + (trending ? " · trend: levels more likely to give way" : " · range: levels tend to hold")
    f_cell(0, rr, read, rb, fg)
    table.merge_cells(hud, 0, rr, 6, rr)
    rr += 1
 
    // ⑤ confidence footer — deflated best-level LB
    float bestLB = na
    int measured = 0
    if reg.size() > 0
        for i = 0 to reg.size() - 1
            if reg.get(i).touches >= minN
                measured += 1
        float zdef = f_defZ(measured)
        for i = 0 to reg.size() - 1
            Lvl L = reg.get(i)
            if L.touches >= minN
                float dlb = f_wilsonZ(L.holds, L.touches, zdef)
                if na(bestLB) or dlb > bestLB
                    bestLB := dlb
    f_cell(0, rr, "Calibration " + (na(calib) ? "–" : str.tostring(calib, "0.00")) + " · deflated best LB " + (na(bestLB) ? "–" : f_pct(bestLB)) + " · measured " + str.tostring(measured) + " · BUILDING " + str.tostring(building), hb, color.new(#9AE6B4, 0))
    table.merge_cells(hud, 0, rr, 6, rr)
    rr += 1
 
// ═════════════════════════ EXP BUS ══════════════════════════════════════════
color exC = color.new(color.gray, 100)
plot(nSupPx, "EXP_NearSupport", exC, display = display.data_window)
plot(nResPx, "EXP_NearResist",  exC, display = display.data_window)
plot(na(nSupG) ? na : nSupG * 100, "EXP_SupGrade", exC, display = display.data_window)
plot(na(nResG) ? na : nResG * 100, "EXP_ResGrade", exC, display = display.data_window)
plot(na(nSupLB) ? na : nSupLB * 100, "EXP_SupHoldLB", exC, display = display.data_window)
plot(na(nResLB) ? na : nResLB * 100, "EXP_ResHoldLB", exC, display = display.data_window)
plot(trending ? 1 : 0, "EXP_Regime", exC, display = display.data_window)
plot(na(calib) ? na : calib, "EXP_Calib", exC, display = display.data_window)
 
// ═════════════════════════ ALERTS ═══════════════════════════════════════════
float approxA = 0.5 * safeAtr
bool nearStrongSup = alApproach and not na(nSupPx) and not na(nSupG) and nSupG * 100 >= strongGrade and close - nSupPx <= approxA and nz(close[1] - nSupPx, 99) > approxA
bool nearStrongRes = alApproach and not na(nResPx) and not na(nResG) and nResG * 100 >= strongGrade and nResPx - close <= approxA and nz(nResPx - close[1], 99) > approxA
 
// hold / break / flip events this bar (any level)
var bool evHold = false
var bool evBreak = false
var bool evFlip = false
if barstate.isconfirmed
    evHold := false
    evBreak := false
    evFlip := false
    if reg.size() > 0
        for i = 0 to reg.size() - 1
            Lvl L = reg.get(i)
            if L.lastTouchBar == bar_index and not L.pend and L.touches > 0
                if L.lastOutcome == 1 and f_grade01(L) * 100 >= strongGrade
                    evHold := true
                    if L.brokenEver
                        evFlip := true
                if L.lastOutcome == -1 and f_grade01(L) * 100 >= strongGrade
                    evBreak := true
 
alertcondition(nearStrongSup or nearStrongRes, "Level Respect · approach", "Level Respect Map: price is approaching a Strong level on {{ticker}} {{interval}}.")
alertcondition(evHold, "Level Respect · hold", "Level Respect Map: a Strong level held the test on {{ticker}} {{interval}}.")
alertcondition(evBreak, "Level Respect · break", "Level Respect Map: a Strong level broke (close-through) on {{ticker}} {{interval}}.")
alertcondition(evFlip, "Level Respect · flip", "Level Respect Map: a level flipped role (support↔resistance) on {{ticker}} {{interval}}.")

← 返回列表