Step Sonar [Deriv Step Index]

Deriv · study · 429 行 · 点赞 197 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  STEP SONAR v3 — built for Deriv Step Indices (fixed ±step, 50/50 random walk)
//
//   • Every tick moves price by EXACTLY ±step with p = 0.5 → the volatility of a
//     bar is known in advance: σ_bar = step · √(ticks per bar). No ATR guessing.
//   • Price lives on a lattice (multiples of step) → equal highs/lows are normal,
//     so sweeps = strict "wick beyond, close back inside".
//   • No volume, no sessions, no news, 24/7 → none of that is used here.
//   • It is a martingale: the "next move" is a distribution, not a prophecy.
//     The forward map = probability cone + gambler's-ruin planner (fair odds).
//   • Bias gauge = MEASURED hit-rate of "higher N bars later" in the same stretch
//     state across loaded history, with a confidence margin. Not a forecast.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Step Sonar [Deriv Step Index]", shorttitle="STEP SONAR", overlay=true, max_lines_count=500, max_labels_count=500, max_polylines_count=100)
 
// ───────────────────────────── INPUTS ─────────────────────────────
gI = "① Instrument"
step    = input.float(0.1, "Step size (price units per tick)", minval=0.0001, step=0.1, group=gI, tooltip="Price change per tick. Step Index 100 = 0.1. The 'σ sanity check' row tells you if this (or ticks/sec) is wrong.")
tps     = input.float(0.5, "Ticks per second", minval=0.05, step=0.25, group=gI, tooltip="Your feed measured ≈0.5 (one tick per ~2 s). If the sanity check shows ≈1.00× you are calibrated.")
sigMode = input.string("Theoretical", "σ source", options=["Theoretical", "Empirical"], group=gI, tooltip="Theoretical = step·√ticks (exact for fixed-step Step Index). Empirical = measured from bars (use for Multi Step / Skew Step).")
empLen  = input.int(300, "Empirical σ lookback (bars)", minval=30, group=gI)
 
gE = "② Equilibrium & diffusion bands"
eqLen     = input.int(60, "Equilibrium length (bars)", minval=10, group=gE)
k1        = input.float(1.0, "Inner band (σ)", minval=0.25, step=0.25, group=gE)
k2        = input.float(2.0, "Outer band (σ)", minval=0.5, step=0.25, group=gE)
k3        = input.float(3.0, "Extreme band (σ)", minval=1.0, step=0.25, group=gE)
showBands = input.bool(true, "Show bands", group=gE)
 
gS = "③ Signals & levels"
zTh        = input.float(2.0, "Stretch threshold (σ)", minval=1.0, step=0.25, group=gS)
streakTh   = input.int(5, "Streak that counts as extreme (bars)", minval=3, group=gS)
showFade   = input.bool(true, "Exhaustion markers", group=gS)
showSweep  = input.bool(true, "Sweep markers", group=gS)
sweepDepth = input.int(2, "Min sweep depth (steps beyond the level)", minval=1, group=gS, tooltip="A wick must poke at least this many steps past a swing level (and close back) to count as a sweep.")
showConf   = input.bool(true, "Confluence labels (score ≥ 2/3)", group=gS)
reqStretch = input.bool(true, "Confluence requires a σ-stretch", group=gS, tooltip="Fewer, cleaner FADE labels: a stretch beyond the threshold must have happened in the last 3 bars.")
showLevels = input.bool(true, "Show swing levels", group=gS)
pvLen      = input.int(8, "Swing strength (bars each side)", minval=2, group=gS)
maxLv      = input.int(4, "Max live levels per side", minval=1, maxval=20, group=gS)
 
gC = "④ Next-move map"
showCone  = input.bool(true, "Probability cone", group=gC)
coneH     = input.int(30, "Cone horizon (bars)", minval=5, maxval=200, group=gC, tooltip="Needs empty space on the right of the chart. Drag the chart left to make room.")
showPlan  = input.bool(true, "Fair-odds planner (barriers)", group=gC)
tpSteps   = input.int(0, "Upper barrier (steps, 0 = auto 1σ of a bar)", minval=0, group=gC)
slSteps   = input.int(0, "Lower barrier (steps, 0 = auto 1σ of a bar)", minval=0, group=gC)
spreadSt  = input.float(0.0, "Round-trip cost (steps)", minval=0.0, step=0.1, group=gC, tooltip="Spread/commission in steps. Used for the break-even win rate.")
showGrid  = input.bool(true, "Lattice grid", group=gC)
gridSteps = input.int(0, "Grid spacing (steps, 0 = auto from visible range)", minval=0, group=gC)
gridCnt   = input.int(5, "Grid lines each side (fixed spacing only)", minval=1, maxval=15, group=gC)
 
gB = "⑤ Bias gauge (measured, not predicted)"
showBias    = input.bool(true, "Bias rows in dashboard", group=gB)
showBiasLbl = input.bool(true, "Small bias label next to last candle", group=gB)
biasH       = input.int(10, "Bias horizon (bars)", minval=1, maxval=100, group=gB, tooltip="Measures how often price was higher this many bars later, in the same stretch state, across the loaded history.")
 
gV = "⑥ Look"
cUp      = input.color(#19F0C8, "Up / long colour", group=gV)
cDn      = input.color(#FF4F9A, "Down / short colour", group=gV)
cMean    = input.color(#C9B8FF, "Equilibrium colour", group=gV)
cBand    = input.color(#7A5CFF, "Band / cone colour", group=gV)
cAmb     = input.color(#FFC857, "Accent (sweeps)", group=gV)
cTxt     = input.color(#E6E8F5, "Text colour", group=gV)
cPanel   = input.color(#0E1020, "Panel colour", group=gV)
colorCandles = input.bool(true, "Colour candles by stretch", group=gV)
showTint = input.bool(false, "Background tint when stretched", group=gV)
showDash = input.bool(true, "Dashboard", group=gV)
dashPos  = input.string("Auto", "Dashboard position", options=["Auto", "Top left", "Top right", "Bottom left", "Bottom right"], group=gV, tooltip="Auto = moves to the emptiest corner of the visible chart. Updates when you scroll or zoom.")
autoTL   = input.bool(false, "Auto may use top-left", group=gV, tooltip="Off by default: the broker's BUY/SELL panel sits in the top-left corner and can't be moved by scripts.")
dashW    = input.int(36, "Auto: panel footprint, % of chart width", minval=15, maxval=60, group=gV)
dashH    = input.int(34, "Auto: panel footprint, % of chart height", minval=15, maxval=60, group=gV)
dashSize = input.string("Small", "Dashboard text size", options=["Tiny", "Small", "Normal"], group=gV)
 
txtSz = dashSize == "Tiny" ? size.tiny : dashSize == "Normal" ? size.normal : size.small
 
// ───────────────────────────── HELPERS ─────────────────────────────
f_dur(float sec) =>
    sec < 90 ? str.tostring(sec, "0") + " s" : sec < 5400 ? str.tostring(sec / 60.0, "0.0") + " min" : str.tostring(sec / 3600.0, "0.0") + " h"
 
f_nice(float x) =>
    float xs  = math.max(x, 0.0000001)
    float mag = math.pow(10, math.floor(math.log10(xs)))
    float m   = xs / mag
    float nc  = m < 1.5 ? 1.0 : m < 3.5 ? 2.0 : m < 7.5 ? 5.0 : 10.0
    nc * mag
 
f_sg(float x) => (x >= 0 ? "+" : "") + str.tostring(x, "0.00")
 
f_bucket(float zz) => zz <= -zTh ? 0 : zz <= -1.0 ? 1 : zz < 1.0 ? 2 : zz < zTh ? 3 : 4
 
f_meter(float p) =>
    int n = int(math.round(p * 10))
    string s = ""
    for i = 0 to 9
        s := s + (i < n ? "█" : "░")
    s
 
// ───────────────────────────── ENGINE ─────────────────────────────
tfSec   = timeframe.in_seconds()
barSec  = (na(tfSec) or tfSec <= 0) ? 1.0 : float(tfSec)
nTicks  = barSec * tps                       // ticks inside one bar
sigTheo = step * math.sqrt(nTicks)           // exact σ of a bar's net move
chg     = close - close[1]
sigEmp  = ta.stdev(chg, empLen)
sigBar  = sigMode == "Theoretical" ? sigTheo : nz(sigEmp, sigTheo)
 
mean      = ta.sma(close, eqLen)
// std-dev of (close − SMA) for a random walk over L bars: σ·√((L−1)(2L−1)/(6L)) ≈ σ·√(L/3)
devFactor = math.sqrt((eqLen - 1) * (2.0 * eqLen - 1) / (6.0 * eqLen))
sigDev    = sigBar * devFactor
z         = nz((close - mean) / sigDev)
absZ      = math.abs(z)
driftZ    = nz((close - close[eqLen]) / (sigBar * math.sqrt(eqLen)))
 
bool isUp = close >= open
 
var int streak = 0
streak := close > open ? (streak > 0 ? streak + 1 : 1) : close < open ? (streak < 0 ? streak - 1 : -1) : streak
 
// ───────────────────────────── BIAS GAUGE (measured hit-rates) ─────────────────────────────
var array<float> bUp  = array.new<float>(5, 0.0)
var array<float> bTot = array.new<float>(5, 0.0)
 
if barstate.isconfirmed and bar_index >= biasH + eqLen
    int bk = f_bucket(z[biasH])
    float dlt = close - close[biasH]
    bTot.set(bk, bTot.get(bk) + 1.0)
    if dlt > 0
        bUp.set(bk, bUp.get(bk) + 1.0)
    else if dlt == 0
        bUp.set(bk, bUp.get(bk) + 0.5)
 
int   curB  = f_bucket(z)
float nB    = bTot.get(curB)
float pBull = nB > 0 ? bUp.get(curB) / nB : 0.5
float pBear = 1.0 - pBull
float nEff  = math.max(1.0, nB / biasH)               // overlapping windows → discount the sample size
float ciHw  = 1.96 * math.sqrt(0.25 / nEff)           // 95% margin around 50%
bool  biasSig = nEff >= 15 and math.abs(pBull - 0.5) > ciHw
string biasVerdict = nEff < 15 ? "too few samples" : biasSig ? "edge in-sample (don't trust)" : "no significant edge"
color biasCol = biasSig ? (pBull > 0.5 ? cUp : cDn) : cTxt
 
// ───────────────────────────── VISIBLE-RANGE SCAN (for auto layout) ─────────────────────────────
bool inView = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
var array<float> vH = array.new<float>()
var array<float> vL = array.new<float>()
var float rHi = na
var float rLo = na
if inView and barstate.isconfirmed
    vH.push(high)
    vL.push(low)
    float bHi = (showBands and not na(mean)) ? math.max(high, mean + k3 * sigDev) : high
    float bLo = (showBands and not na(mean)) ? math.min(low, mean - k3 * sigDev) : low
    rHi := na(rHi) ? bHi : math.max(rHi, bHi)
    rLo := na(rLo) ? bLo : math.min(rLo, bLo)
 
// ───────────────────────────── BANDS ─────────────────────────────
pMean = plot(showBands ? mean : na, "Equilibrium", color=color.new(cMean, 5), linewidth=2)
pU1   = plot(showBands ? mean + k1 * sigDev : na, "Upper inner", color=color.new(cBand, 50), linewidth=1)
pL1   = plot(showBands ? mean - k1 * sigDev : na, "Lower inner", color=color.new(cBand, 50), linewidth=1)
pU2   = plot(showBands ? mean + k2 * sigDev : na, "Upper outer", color=color.new(cDn, 45), linewidth=1)
pL2   = plot(showBands ? mean - k2 * sigDev : na, "Lower outer", color=color.new(cUp, 45), linewidth=1)
plot(showBands ? mean + k3 * sigDev : na, "Upper extreme", color=color.new(cDn, 75), linewidth=1, style=plot.style_circles)
plot(showBands ? mean - k3 * sigDev : na, "Lower extreme", color=color.new(cUp, 75), linewidth=1, style=plot.style_circles)
fill(pU2, pU1, color=color.new(cDn, 90), title="Upper stretch zone")
fill(pL1, pL2, color=color.new(cUp, 90), title="Lower stretch zone")
fill(pU1, pL1, color=color.new(cBand, 95), title="Equilibrium zone")
 
// Candle intensity = how stretched the market is (calm = faded, stretched = vivid)
candleCol = color.new(isUp ? cUp : cDn, int(math.max(0, 60 - absZ * 20)))
barcolor(colorCandles ? candleCol : na)
bgcolor(showTint ? (z >= zTh ? color.new(cDn, 94) : z <= -zTh ? color.new(cUp, 94) : na) : na)
 
// ───────────────────────────── SWING LEVELS + SWEEPS ─────────────────────────────
ph = ta.pivothigh(high, pvLen, pvLen)
pl = ta.pivotlow(low, pvLen, pvLen)
 
var array<line> hiLv = array.new<line>()
var array<line> loLv = array.new<line>()
 
bool sweepHi = false   // wick above a swing high, close back below → bearish trap
bool sweepLo = false   // wick below a swing low,  close back above → bullish trap
 
color cHiLive = showLevels ? color.new(cDn, 35) : na
color cLoLive = showLevels ? color.new(cUp, 35) : na
color cHiDead = showLevels ? color.new(cDn, 85) : na
color cLoDead = showLevels ? color.new(cUp, 85) : na
color cSweep  = showLevels ? color.new(cAmb, 5) : na
 
if not na(ph)
    hiLv.push(line.new(bar_index - pvLen, ph, bar_index, ph, color=cHiLive, style=line.style_dotted, width=1))
    if hiLv.size() > maxLv
        line.delete(hiLv.shift())
if not na(pl)
    loLv.push(line.new(bar_index - pvLen, pl, bar_index, pl, color=cLoLive, style=line.style_dotted, width=1))
    if loLv.size() > maxLv
        line.delete(loLv.shift())
 
if hiLv.size() > 0
    for i = hiLv.size() - 1 to 0
        line lv = hiLv.get(i)
        float px = line.get_y1(lv)
        line.set_x2(lv, bar_index)
        if high > px
            if close < px and (high - px) >= sweepDepth * step * 0.999
                sweepHi := true
                line.set_color(lv, cSweep)
                line.set_style(lv, line.style_solid)
            else
                line.set_color(lv, cHiDead)
            hiLv.remove(i)
 
if loLv.size() > 0
    for i = loLv.size() - 1 to 0
        line lv = loLv.get(i)
        float px = line.get_y1(lv)
        line.set_x2(lv, bar_index)
        if low < px
            if close > px and (px - low) >= sweepDepth * step * 0.999
                sweepLo := true
                line.set_color(lv, cSweep)
                line.set_style(lv, line.style_solid)
            else
                line.set_color(lv, cLoDead)
            loLv.remove(i)
 
// ───────────────────────────── SIGNALS ─────────────────────────────
bool exhLong  = showFade and z[1] <= -zTh and z > -zTh and close > open
bool exhShort = showFade and z[1] >= zTh and z < zTh and close < open
 
bool sweepLoRecent = nz(ta.barssince(sweepLo), 99) <= 3
bool sweepHiRecent = nz(ta.barssince(sweepHi), 99) <= 3
bool stretchL = ta.lowest(z, 3) <= -zTh
bool stretchS = ta.highest(z, 3) >= zTh
bool streakL  = ta.lowest(streak, 3) <= -streakTh
bool streakS  = ta.highest(streak, 3) >= streakTh
 
int scoreL = (stretchL ? 1 : 0) + (sweepLoRecent ? 1 : 0) + (streakL ? 1 : 0)
int scoreS = (stretchS ? 1 : 0) + (sweepHiRecent ? 1 : 0) + (streakS ? 1 : 0)
bool confL = showConf and scoreL >= 2 and scoreL[1] < 2 and (not reqStretch or stretchL)
bool confS = showConf and scoreS >= 2 and scoreS[1] < 2 and (not reqStretch or stretchS)
 
// thin out repeated SWEEP labels
bool showSwLo = showSweep and sweepLo and not sweepLo[1] and not sweepLo[2] and not confL
bool showSwHi = showSweep and sweepHi and not sweepHi[1] and not sweepHi[2] and not confS
 
plotshape(exhLong, "Exhaustion long", shape.triangleup, location.belowbar, color=cUp, size=size.tiny)
plotshape(exhShort, "Exhaustion short", shape.triangledown, location.abovebar, color=cDn, size=size.tiny)
plotshape(showSwLo, "Sweep low", shape.labelup, location.belowbar, color=color.new(cAmb, 5), textcolor=color.black, text="SWEEP", size=size.tiny)
plotshape(showSwHi, "Sweep high", shape.labeldown, location.abovebar, color=color.new(cAmb, 5), textcolor=color.black, text="SWEEP", size=size.tiny)
plotshape(confL, "Confluence long", shape.labelup, location.belowbar, color=color.new(cUp, 0), textcolor=color.black, text="FADE ▲", size=size.small)
plotshape(confS, "Confluence short", shape.labeldown, location.abovebar, color=color.new(cDn, 0), textcolor=color.black, text="FADE ▼", size=size.small)
 
alertcondition(exhLong, "Step Sonar: exhaustion LONG", "Step Sonar: price re-entered from below the stretch zone")
alertcondition(exhShort, "Step Sonar: exhaustion SHORT", "Step Sonar: price re-entered from above the stretch zone")
alertcondition(confL, "Step Sonar: confluence LONG", "Step Sonar: fade-long confluence (2+/3)")
alertcondition(confS, "Step Sonar: confluence SHORT", "Step Sonar: fade-short confluence (2+/3)")
alertcondition(sweepLo, "Step Sonar: sweep of swing low", "Step Sonar: swing low swept, closed back above")
alertcondition(sweepHi, "Step Sonar: sweep of swing high", "Step Sonar: swing high swept, closed back below")
 
// ───────────────────────────── FORWARD MAP ─────────────────────────────
int tpN = tpSteps > 0 ? tpSteps : math.max(1, int(math.round(sigBar / step)))
int slN = slSteps > 0 ? slSteps : math.max(1, int(math.round(sigBar / step)))
 
float pUp  = slN / float(tpN + slN)           // gambler's ruin: P(upper barrier first)
float pDn  = 1.0 - pUp
float eSec = float(tpN) * slN / tps           // E[ticks to exit] = a·b → seconds
float pReq = (slN + spreadSt) / float(tpN + slN)
 
var array<polyline> pls    = array.new<polyline>()
var array<line>     dLines = array.new<line>()
var array<label>    dLbls  = array.new<label>()
 
if barstate.islast
    while pls.size() > 0
        polyline.delete(pls.pop())
    while dLines.size() > 0
        line.delete(dLines.pop())
    while dLbls.size() > 0
        label.delete(dLbls.pop())
 
    // Lattice grid — auto spacing follows what is actually on screen
    if showGrid
        float visRng = (na(rHi) or na(rLo)) ? 10.0 * sigBar : rHi - rLo
        float gsRaw  = gridSteps > 0 ? gridSteps * step : f_nice(math.max(visRng / 10.0, step))
        float gs     = math.max(step, math.round(gsRaw / step) * step)
        int iMid = int(math.round(close / gs))
        int i0 = gridSteps > 0 ? iMid - gridCnt : int(math.floor((na(rLo) ? close - visRng / 2 : rLo) / gs))
        int i1 = gridSteps > 0 ? iMid + gridCnt : int(math.ceil((na(rHi) ? close + visRng / 2 : rHi) / gs))
        if i1 - i0 <= 120
            for i = i0 to i1
                float lvl = i * gs
                dLines.push(line.new(bar_index - 1, lvl, bar_index, lvl, extend=extend.both, color=color.new(cMean, i == iMid ? 80 : 92), style=line.style_dotted, width=1))
 
    // Probability cone: ±1σ (68%) and ±2σ (95%) of where price can be after k bars
    if showCone
        pts2 = array.new<chart.point>()
        pts1 = array.new<chart.point>()
        for k = 0 to coneH
            float s = sigBar * math.sqrt(k)
            pts2.push(chart.point.from_index(bar_index + k, close + 2.0 * s))
            pts1.push(chart.point.from_index(bar_index + k, close + 1.0 * s))
        for k = coneH to 0
            float s = sigBar * math.sqrt(k)
            pts2.push(chart.point.from_index(bar_index + k, close - 2.0 * s))
            pts1.push(chart.point.from_index(bar_index + k, close - 1.0 * s))
        pls.push(polyline.new(pts2, closed=true, line_color=color.new(cBand, 55), fill_color=color.new(cBand, 92), line_width=1))
        pls.push(polyline.new(pts1, closed=true, line_color=color.new(cMean, 35), fill_color=color.new(cBand, 82), line_width=1))
        dLines.push(line.new(bar_index, close, bar_index + coneH, close, color=color.new(cMean, 40), style=line.style_dashed, width=1))
        float sH = sigBar * math.sqrt(coneH)
        dLbls.push(label.new(bar_index + coneH, close + 2.0 * sH, "+2σ  " + str.tostring(close + 2.0 * sH, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(cDn, 10), size=size.small))
        dLbls.push(label.new(bar_index + coneH, close + 1.0 * sH, "+1σ  " + str.tostring(close + 1.0 * sH, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(cMean, 10), size=size.small))
        dLbls.push(label.new(bar_index + coneH, close - 1.0 * sH, "−1σ  " + str.tostring(close - 1.0 * sH, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(cMean, 10), size=size.small))
        dLbls.push(label.new(bar_index + coneH, close - 2.0 * sH, "−2σ  " + str.tostring(close - 2.0 * sH, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(cUp, 10), size=size.small))
 
    // Fair-odds planner
    if showPlan
        float upPx = close + tpN * step
        float dnPx = close - slN * step
        dLines.push(line.new(bar_index, upPx, bar_index + coneH, upPx, color=color.new(cUp, 15), style=line.style_dashed, width=2))
        dLines.push(line.new(bar_index, dnPx, bar_index + coneH, dnPx, color=color.new(cDn, 15), style=line.style_dashed, width=2))
        dLbls.push(label.new(bar_index + coneH, upPx, "▲ +" + str.tostring(tpN) + " st  ·  " + str.tostring(pUp * 100, "0.0") + "% first", style=label.style_label_right, color=color.new(cPanel, 15), textcolor=cUp, size=size.small))
        dLbls.push(label.new(bar_index + coneH, dnPx, "▼ −" + str.tostring(slN) + " st  ·  " + str.tostring(pDn * 100, "0.0") + "% first", style=label.style_label_right, color=color.new(cPanel, 15), textcolor=cDn, size=size.small))
 
    // Small bias label next to the last candle
    if showBias and showBiasLbl
        string bl = "▲" + str.tostring(pBull * 100, "0") + "  ▼" + str.tostring(pBear * 100, "0") + (biasSig ? "" : "  ≈")
        dLbls.push(label.new(bar_index + 1, close, bl, style=label.style_label_left, color=color.new(cPanel, 25), textcolor=biasCol, size=size.tiny))
 
// ───────────────────────────── DASHBOARD (4 anchor tables, only one is filled) ─────────────────────────────
var table tTL = table.new(position.top_left, 2, 13, border_width=1, border_color=color.new(cBand, 82))
var table tTR = table.new(position.top_right, 2, 13, border_width=1, border_color=color.new(cBand, 82))
var table tBL = table.new(position.bottom_left, 2, 13, border_width=1, border_color=color.new(cBand, 82))
var table tBR = table.new(position.bottom_right, 2, 13, border_width=1, border_color=color.new(cBand, 82))
 
f_row(table t, int r, string k, string v, color vCol) =>
    table.cell(t, 0, r, k, text_color=color.new(cTxt, 30), text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cPanel, 14))
    table.cell(t, 1, r, v, text_color=vCol, text_size=txtSz, text_halign=text.align_right, bgcolor=color.new(cPanel, 14))
 
f_fill(table t) =>
    color zCol = absZ >= zTh ? (z > 0 ? cDn : cUp) : absZ >= 1.0 ? cAmb : cTxt
    table.cell(t, 0, 0, "◆ STEP SONAR  ·  " + syminfo.ticker, text_color=cMean, text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cBand, 55))
    table.merge_cells(t, 0, 0, 1, 0)
 
    f_row(t, 1, "σ per bar", str.tostring(sigBar / step, "0.0") + " st (" + str.tostring(sigBar, "0.###") + ") · " + str.tostring(nTicks, "0") + " ticks", cTxt)
    f_row(t, 2, "Stretch vs equilibrium", f_sg(z) + " σ", zCol)
    f_row(t, 3, "Drift (" + str.tostring(eqLen) + " bars)", f_sg(driftZ) + " σ", math.abs(driftZ) >= zTh ? cAmb : cTxt)
 
    string stTxt = streak == 0 ? "—" : str.tostring(math.abs(streak)) + (streak > 0 ? " ▲" : " ▼") + "  (p ≈ " + str.tostring(math.pow(0.5, math.abs(streak)) * 100, "0.00") + "%)"
    f_row(t, 4, "Bar streak", stTxt, math.abs(streak) >= streakTh ? cAmb : cTxt)
 
    string stateTxt = absZ >= zTh ? (z > 0 ? "STRETCHED ▲" : "STRETCHED ▼") : absZ >= 1.0 ? (z > 0 ? "Leaning up" : "Leaning down") : "Equilibrium"
    f_row(t, 5, "State", stateTxt, zCol)
 
    string dotsL = (scoreL >= 1 ? "●" : "○") + (scoreL >= 2 ? "●" : "○") + (scoreL >= 3 ? "●" : "○")
    string dotsS = (scoreS >= 1 ? "●" : "○") + (scoreS >= 2 ? "●" : "○") + (scoreS >= 3 ? "●" : "○")
    f_row(t, 6, "Fade ▲ long  |  ▼ short", dotsL + "   |   " + dotsS, scoreL >= 2 ? cUp : scoreS >= 2 ? cDn : cTxt)
 
    if showBias
        f_row(t, 7, "Bias · next " + str.tostring(biasH) + " bars", "▲" + str.tostring(pBull * 100, "0") + "% " + f_meter(pBull) + " " + str.tostring(pBear * 100, "0") + "%▼", biasCol)
        f_row(t, 8, "Bias evidence", "n≈" + str.tostring(nEff, "0") + "  ±" + str.tostring(ciHw * 100, "0") + "%  ·  " + biasVerdict, biasSig ? cAmb : color.new(cTxt, 35))
    else
        f_row(t, 7, "Bias", "off", color.new(cTxt, 50))
        f_row(t, 8, "", "", cTxt)
 
    f_row(t, 9, "Barriers  ·  fair odds ▲/▼", "+" + str.tostring(tpN) + "/−" + str.tostring(slN) + " st  ·  " + str.tostring(pUp * 100, "0") + "/" + str.tostring(pDn * 100, "0") + "%", cTxt)
    f_row(t, 10, "Exit in ≈  ·  break-even", f_dur(eSec) + "  ·  " + str.tostring(pReq * 100, "0.0") + "%", spreadSt > 0 ? cAmb : cTxt)
 
    float ratio = nz(sigEmp) / sigTheo
    bool sane = ratio > 0.85 and ratio < 1.18
    string chk = sane ? str.tostring(ratio, "0.00") + "×  ✓ calibrated" : str.tostring(ratio, "0.00") + "×  ⚠ tps≈" + str.tostring(tps * ratio * ratio, "0.00") + " or step≈" + str.tostring(step * ratio, "0.000")
    f_row(t, 11, "σ sanity check", chk, sane ? cUp : cAmb)
    f_row(t, 12, "Reality check", "martingale: edge = sizing & costs", color.new(cTxt, 55))
 
f_show(table t, bool on) =>
    if on
        f_fill(t)
    else
        table.clear(t, 0, 0, 1, 12)
 
if barstate.islast
    string chosen = dashPos
    if dashPos == "Auto"
        chosen := "Bottom left"
        int nV = array.size(vH)
        if nV >= 5 and not na(rHi) and not na(rLo) and rHi > rLo
            float rng    = rHi - rLo
            float topLim = rHi - rng * dashH / 100.0
            float botLim = rLo + rng * dashH / 100.0
            int wN = math.max(1, int(math.round(nV * dashW / 100.0)))
            int cTL = 0
            int cTR = 0
            int cBL = 0
            int cBR = 0
            for i = 0 to nV - 1
                float hh = vH.get(i)
                float ll = vL.get(i)
                bool inL = i < wN
                bool inR = i >= nV - wN
                if hh >= topLim
                    if inL
                        cTL += 1
                    if inR
                        cTR += 1
                if ll <= botLim
                    if inL
                        cBL += 1
                    if inR
                        cBR += 1
            // the cone / planner live in the empty space on the right → penalise right corners
            int pen = (showCone or showPlan) ? int(wN * 0.5) : 0
            cTR += pen
            cBR += pen
            int best = cBL
            if cTR < best
                best := cTR
                chosen := "Top right"
            if cBR < best
                best := cBR
                chosen := "Bottom right"
            if autoTL and cTL < best
                best := cTL
                chosen := "Top left"
    f_show(tTL, showDash and chosen == "Top left")
    f_show(tTR, showDash and chosen == "Top right")
    f_show(tBL, showDash and chosen == "Bottom left")
    f_show(tBR, showDash and chosen == "Bottom right")

← 返回列表