Vol Sonar | Deriv Volatility Index Statistical Analysis Terminal

Deriv · study · 490 行 · 点赞 49 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  VOL SONAR — built for Deriv Volatility Indices (constant-σ, driftless GBM-style)
//
//   • The index number = ANNUALISED volatility. One bar's log-return σ is therefore
//     known exactly: σ_bar = V · √(bar seconds / seconds per year). No ATR guessing.
//   • Volatility is CONSTANT → volatility clustering/expansion signals are meaningless.
//     Instead the dashboard calibrates measured vs theoretical σ (and detects which
//     index you are actually looking at).
//   • 24/7, no gaps, no news, no volume, no sessions → none of that is used here.
//   • Direction = a measured, honest estimate: variance-ratio regime test + multi-
//     horizon drift stack + historical hit-rates with confidence margins.
//     If there is no edge, it says so.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Vol Sonar [Deriv Volatility Index]", shorttitle="VOL SONAR", overlay=true, max_lines_count=500, max_labels_count=500, max_polylines_count=100, max_bars_back=1000)
 
// ───────────────────────────── INPUTS ─────────────────────────────
gI = "① Instrument"
idxMode   = input.string("Auto (from symbol name)", "Volatility index", options=["Auto (from symbol name)", "10", "25", "50", "75", "100", "150", "200", "250", "Custom"], group=gI, tooltip="The number is the annualised volatility in %. Auto tries to read it from the symbol (R_100, 1HZ100V, 'Volatility 100 Index'...).")
customVol = input.float(100.0, "Custom / fallback annualised volatility (%)", minval=1.0, step=5.0, group=gI)
tickMode  = input.string("Auto", "Tick interval (display only)", options=["Auto", "2 s", "1 s"], group=gI, tooltip="Standard indices tick every 2 s, the (1s) indices every second. Only affects the 'ticks per bar' readout.")
yearDays  = input.float(365.0, "Days per year used for annualisation", minval=200.0, maxval=400.0, group=gI)
sigMode   = input.string("Theoretical", "σ source", options=["Theoretical", "Measured"], group=gI, tooltip="Theoretical = from the index number (exact). Measured = from the bars (use if the calibration row shows a mismatch).")
empLen    = input.int(300, "Measured σ 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)
sweepK     = input.float(0.3, "Min sweep depth (σ of one bar)", minval=0.05, step=0.05, group=gS, tooltip="A wick must poke at least this far past a swing level (and close back) to count as a sweep.")
showShock  = input.bool(true, "Shock-bar markers", group=gS)
shockK     = input.float(3.0, "Shock bar threshold (σ of one bar)", minval=2.0, step=0.5, group=gS, tooltip="A single bar moving more than this many σ. Under constant volatility these are pure tail events, not regime changes.")
showConf   = input.bool(true, "Confluence labels (score ≥ 2/3)", group=gS)
reqStretch = input.bool(true, "Confluence requires a σ-stretch", group=gS)
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)
 
gD = "④ Direction engine (measured, not predicted)"
hS        = input.int(15, "Drift horizon – short (bars)", minval=3, group=gD)
hM        = input.int(60, "Drift horizon – medium (bars)", minval=5, group=gD)
hL        = input.int(240, "Drift horizon – long (bars)", minval=10, maxval=400, group=gD)
zv        = input.float(1.0, "Drift significance per horizon (σ)", minval=0.25, step=0.25, group=gD)
vrQ       = input.int(5, "Variance-ratio aggregation (bars)", minval=2, maxval=30, group=gD)
vrN       = input.int(300, "Variance-ratio sample (bars)", minval=100, maxval=900, group=gD)
vrTh      = input.float(2.0, "Regime significance (z)", minval=1.0, step=0.25, group=gD, tooltip="|z| above this = the recent price action is statistically NOT a pure random walk.")
biasH     = input.int(10, "Bias horizon (bars)", minval=1, maxval=100, group=gD, tooltip="Measures how often price was higher this many bars later, whenever the engine showed the same lean, across the loaded history.")
showBias    = input.bool(true, "Bias rows in dashboard", group=gD)
showBiasLbl = input.bool(true, "Bias label next to last candle", group=gD)
 
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.")
showPlan  = input.bool(true, "Fair-odds planner (barriers)", group=gC)
tpK       = input.float(1.0, "Upper barrier (σ of one bar)", minval=0.1, step=0.25, group=gC)
slK       = input.float(1.0, "Lower barrier (σ of one bar)", minval=0.1, step=0.25, group=gC)
costPct   = input.float(0.0, "Round-trip cost (% of price)", minval=0.0, step=0.01, group=gC, tooltip="Spread/commission as % of price. Used for the break-even win rate.")
showGrid  = input.bool(true, "Auto grid", group=gC)
 
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 colour", 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 = 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 top-left 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(38, "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" : sec < 172800 ? str.tostring(sec / 3600.0, "0.0") + " h" : str.tostring(sec / 86400.0, "0.0") + " d"
 
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_meter(float p) =>
    int n = int(math.round(p * 10))
    string s = ""
    for i = 0 to 9
        s := s + (i < n ? "█" : "░")
    s
 
// ───────────────────────────── INSTRUMENT DETECTION ─────────────────────────────
string nameU = str.upper(syminfo.ticker + " " + syminfo.description)
float volDet = str.contains(nameU, "250") ? 250.0 : str.contains(nameU, "200") ? 200.0 : str.contains(nameU, "150") ? 150.0 : str.contains(nameU, "100") ? 100.0 : str.contains(nameU, "75") ? 75.0 : str.contains(nameU, "50") ? 50.0 : str.contains(nameU, "25") ? 25.0 : str.contains(nameU, "10") ? 10.0 : na
bool tick1sDet = str.contains(nameU, "1HZ") or str.contains(nameU, "(1S)")
 
float volIn = idxMode == "Auto (from symbol name)" ? nz(volDet, customVol) : idxMode == "Custom" ? customVol : str.tonumber(idxMode)
bool autoOK = idxMode == "Auto (from symbol name)" and not na(volDet)
 
// ───────────────────────────── ENGINE ─────────────────────────────
tfSec   = timeframe.in_seconds()
barSec  = (na(tfSec) or tfSec <= 0) ? 1.0 : float(tfSec)
yearSec = yearDays * 86400.0
tickSec = tickMode == "1 s" ? 1.0 : tickMode == "2 s" ? 2.0 : (tick1sDet ? 1.0 : 2.0)
nTicks  = barSec / tickSec
 
sigTheo = (volIn / 100.0) * math.sqrt(barSec / yearSec)     // σ of one bar's LOG return
r       = math.log(close / close[1])
sigEmp  = ta.stdev(r, empLen)
sigBar  = sigMode == "Theoretical" ? sigTheo : nz(sigEmp, sigTheo)
volEst  = nz(sigEmp) / math.sqrt(barSec / yearSec) * 100.0  // measured annualised vol %
 
lc        = math.log(close)
mLog      = ta.sma(lc, eqLen)
devFactor = math.sqrt((eqLen - 1) * (2.0 * eqLen - 1) / (6.0 * eqLen))   // σ of (price − SMA) for a random walk
sigDev    = sigBar * devFactor
z         = nz((lc - mLog) / sigDev)
absZ      = math.abs(z)
 
bool isUp = close >= open
 
var int streak = 0
streak := close > open ? (streak > 0 ? streak + 1 : 1) : close < open ? (streak < 0 ? streak - 1 : -1) : streak
 
// ───────────────────────────── DIRECTION ENGINE ─────────────────────────────
// 1) multi-horizon drift, each tested against the KNOWN σ of a driftless walk
dz1 = nz((lc - lc[hS]) / (sigBar * math.sqrt(hS)))
dz2 = nz((lc - lc[hM]) / (sigBar * math.sqrt(hM)))
dz3 = nz((lc - lc[hL]) / (sigBar * math.sqrt(hL)))
int v1 = dz1 >= zv ? 1 : dz1 <= -zv ? -1 : 0
int v2 = dz2 >= zv ? 1 : dz2 <= -zv ? -1 : 0
int v3 = dz3 >= zv ? 1 : dz3 <= -zv ? -1 : 0
int trendVote = v1 + v2 + v3
 
// 2) variance-ratio regime test (Lo–MacKinlay): VR = 1 for a pure random walk
float var1 = ta.sma(r * r, vrN)
float rq   = lc - lc[vrQ]
float varq = ta.sma(rq * rq, vrN)
float vr   = var1 > 0 ? varq / (vrQ * var1) : 1.0
float vrSE = math.sqrt(2.0 * (2.0 * vrQ - 1) * (vrQ - 1) / (3.0 * vrQ * vrN))
float vrZ  = nz((vr - 1.0) / vrSE)
int regime = vrZ >= vrTh ? 1 : vrZ <= -vrTh ? -1 : 0       // 1 trending · -1 mean-reverting · 0 random
 
// 3) lean: momentum in a trending regime, reversion in a mean-reverting one, weak tilt otherwise
int soft       = trendVote >= 2 ? 1 : trendVote <= -2 ? -1 : 0
int stretchDir = z >= zTh ? 1 : z <= -zTh ? -1 : 0
int leanState  = regime == 1 ? (soft != 0 ? 2 * soft : 0) : regime == -1 ? (stretchDir != 0 ? -2 * stretchDir : 0) : soft
 
// 4) MEASURED hit-rates: how often was price higher biasH bars later, for each lean state
var array<float> bUp  = array.new<float>(5, 0.0)
var array<float> bTot = array.new<float>(5, 0.0)
var float sumR = 0.0
var int   nR   = 0
 
if barstate.isconfirmed and not na(r)
    sumR += r
    nR += 1
if barstate.isconfirmed and bar_index > biasH + math.max(hL, vrN) + 2
    int bk = leanState[biasH] + 2
    float dlt = lc - lc[biasH]
    if not na(dlt)
        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  = leanState + 2
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 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 (verify!)" : "no significant edge"
color biasCol = biasSig ? (pBull > 0.5 ? cUp : cDn) : (leanState > 0 ? color.new(cUp, 35) : leanState < 0 ? color.new(cDn, 35) : cTxt)
 
float histDrift = nR > 10 ? sumR / (sigBar * math.sqrt(nR)) : 0.0   // is there ANY drift in the loaded history?
 
// ───────────────────────────── 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(mLog)) ? math.max(high, math.exp(mLog + k3 * sigDev)) : high
    float bLo = (showBands and not na(mLog)) ? math.min(low, math.exp(mLog - k3 * sigDev)) : low
    rHi := na(rHi) ? bHi : math.max(rHi, bHi)
    rLo := na(rLo) ? bLo : math.min(rLo, bLo)
 
// ───────────────────────────── BANDS (lognormal) ─────────────────────────────
pMean = plot(showBands ? math.exp(mLog) : na, "Equilibrium", color=color.new(cMean, 5), linewidth=2)
pU1   = plot(showBands ? math.exp(mLog + k1 * sigDev) : na, "Upper inner", color=color.new(cBand, 50), linewidth=1)
pL1   = plot(showBands ? math.exp(mLog - k1 * sigDev) : na, "Lower inner", color=color.new(cBand, 50), linewidth=1)
pU2   = plot(showBands ? math.exp(mLog + k2 * sigDev) : na, "Upper outer", color=color.new(cDn, 45), linewidth=1)
pL2   = plot(showBands ? math.exp(mLog - k2 * sigDev) : na, "Lower outer", color=color.new(cUp, 45), linewidth=1)
plot(showBands ? math.exp(mLog + k3 * sigDev) : na, "Upper extreme", color=color.new(cDn, 75), linewidth=1, style=plot.style_circles)
plot(showBands ? math.exp(mLog - 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")
 
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 math.log(high / px) >= sweepK * sigBar
                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 math.log(px / low) >= sweepK * sigBar
                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)
 
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
 
float zr = nz(r / sigBar)
bool shockUp = showShock and zr >= shockK
bool shockDn = showShock and zr <= -shockK
 
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)
plotshape(shockUp, "Shock up", shape.diamond, location.abovebar, color=color.new(cAmb, 10), size=size.tiny)
plotshape(shockDn, "Shock down", shape.diamond, location.belowbar, color=color.new(cAmb, 10), size=size.tiny)
 
alertcondition(exhLong, "Vol Sonar: exhaustion LONG", "Vol Sonar: price re-entered from below the stretch zone")
alertcondition(exhShort, "Vol Sonar: exhaustion SHORT", "Vol Sonar: price re-entered from above the stretch zone")
alertcondition(confL, "Vol Sonar: confluence LONG", "Vol Sonar: fade-long confluence (2+/3)")
alertcondition(confS, "Vol Sonar: confluence SHORT", "Vol Sonar: fade-short confluence (2+/3)")
alertcondition(leanState == 2 and leanState[1] != 2, "Vol Sonar: strong BULL lean", "Vol Sonar: strong bullish lean (statistically significant regime)")
alertcondition(leanState == -2 and leanState[1] != -2, "Vol Sonar: strong BEAR lean", "Vol Sonar: strong bearish lean (statistically significant regime)")
 
// ───────────────────────────── FORWARD MAP ─────────────────────────────
float aL   = tpK * sigBar                         // log distance to upper barrier
float bL   = slK * sigBar                         // log distance to lower barrier
float pUp  = bL / (aL + bL)                       // driftless diffusion: P(upper barrier first)
float pDn  = 1.0 - pUp
float eSec = tpK * slK * barSec                   // E[time to exit] = a·b / σ²_per_second = tpK·slK bars
float pReq = (bL + costPct / 100.0) / (aL + bL)
 
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())
 
    // Auto grid — spacing follows what is on screen
    if showGrid and not na(rHi) and not na(rLo) and rHi > rLo
        float gs = f_nice((rHi - rLo) / 10.0)
        int i0 = int(math.floor(rLo / gs))
        int i1 = int(math.ceil(rHi / gs))
        int iMid = int(math.round(close / 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))
 
    // Lognormal probability cone: ±1σ (68%) and ±2σ (95%)
    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 * math.exp(2.0 * s)))
            pts1.push(chart.point.from_index(bar_index + k, close * math.exp(1.0 * s)))
        for k = coneH to 0
            float s = sigBar * math.sqrt(k)
            pts2.push(chart.point.from_index(bar_index + k, close * math.exp(-2.0 * s)))
            pts1.push(chart.point.from_index(bar_index + k, close * math.exp(-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 * math.exp(2.0 * sH), "+2σ  " + str.tostring(close * math.exp(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 * math.exp(1.0 * sH), "+1σ  " + str.tostring(close * math.exp(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 * math.exp(-1.0 * sH), "−1σ  " + str.tostring(close * math.exp(-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 * math.exp(-2.0 * sH), "−2σ  " + str.tostring(close * math.exp(-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 * math.exp(aL)
        float dnPx = close * math.exp(-bL)
        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(tpK, "0.0") + "σ  ·  " + 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(slK, "0.0") + "σ  ·  " + str.tostring(pDn * 100, "0.0") + "% first", style=label.style_label_right, color=color.new(cPanel, 15), textcolor=cDn, size=size.small))
 
    // Bias label next to the last candle
    if showBias and showBiasLbl
        string arrow = leanState > 0 ? "▲ " : leanState < 0 ? "▼ " : "◆ "
        string bl = arrow + "▲" + 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.small))
 
// ───────────────────────────── CALIBRATION ─────────────────────────────
var lvls = array.from(10.0, 25.0, 50.0, 75.0, 100.0, 150.0, 250.0)
float nearLvl = na
float bestD = 1e10
for i = 0 to array.size(lvls) - 1
    float lv2 = array.get(lvls, i)
    float dd = math.abs(math.log(math.max(volEst, 0.001) / lv2))
    if dd < bestD
        bestD := dd
        nearLvl := lv2
 
// ───────────────────────────── 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 r0, string k, string v, color vCol) =>
    table.cell(t, 0, r0, k, text_color=color.new(cTxt, 30), text_size=txtSz, text_halign=text.align_left, bgcolor=color.new(cPanel, 14))
    table.cell(t, 1, r0, 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, "◆ VOL SONAR  ·  " + syminfo.ticker + "  ·  V" + str.tostring(volIn, "0") + (autoOK ? " (auto)" : ""), 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 * 100, "0.000") + "%  ·  " + str.tostring(nTicks, "0") + " ticks", cTxt)
    f_row(t, 2, "Stretch vs equilibrium", f_sg(z) + " σ", zCol)
    f_row(t, 3, "Drift " + str.tostring(hS) + "/" + str.tostring(hM) + "/" + str.tostring(hL), f_sg(dz1) + " / " + f_sg(dz2) + " / " + f_sg(dz3) + " σ", trendVote >= 2 ? cUp : trendVote <= -2 ? cDn : cTxt)
 
    string regTxt = regime == 1 ? "Trending" : regime == -1 ? "Mean-reverting" : "Random walk"
    f_row(t, 4, "Regime (variance ratio)", regTxt + "  VR " + str.tostring(vr, "0.00") + " (z " + f_sg(vrZ) + ")", regime != 0 ? cAmb : cTxt)
 
    string why = leanState == 0 ? "" : math.abs(leanState) == 2 ? (regime == 1 ? " · momentum" : " · reversion") : " · weak tilt"
    string leanTxt = (leanState > 0 ? "▲ BULL" : leanState < 0 ? "▼ BEAR" : "◆ NEUTRAL") + why
    f_row(t, 5, "Lean", leanTxt, leanState > 0 ? cUp : leanState < 0 ? cDn : cTxt)
 
    if showBias
        f_row(t, 6, "Measured P · next " + str.tostring(biasH) + " bars", "▲" + str.tostring(pBull * 100, "0") + "% " + f_meter(pBull) + " " + str.tostring(pBear * 100, "0") + "%▼", biasCol)
        f_row(t, 7, "Evidence", "n≈" + str.tostring(nEff, "0") + "  ±" + str.tostring(ciHw * 100, "0") + "%  ·  " + biasVerdict, biasSig ? cAmb : color.new(cTxt, 35))
    else
        f_row(t, 6, "Measured P", "off", color.new(cTxt, 50))
        f_row(t, 7, "Evidence", "off", color.new(cTxt, 50))
 
    f_row(t, 8, "History drift test", f_sg(histDrift) + " σ  ·  " + (math.abs(histDrift) >= 2.0 ? "⚠ drift?" : "driftless ✓"), math.abs(histDrift) >= 2.0 ? cAmb : cTxt)
    f_row(t, 9, "Barriers", "+" + str.tostring(tpK, "0.0") + "σ / −" + str.tostring(slK, "0.0") + "σ  (" + str.tostring((math.exp(aL) - 1) * 100, "0.00") + "% / " + str.tostring((1 - math.exp(-bL)) * 100, "0.00") + "%)", cTxt)
    f_row(t, 10, "Fair odds · exit ≈ · b/e", str.tostring(pUp * 100, "0") + "/" + str.tostring(pDn * 100, "0") + "%  ·  " + f_dur(eSec) + "  ·  " + str.tostring(pReq * 100, "0.0") + "%", costPct > 0 ? cAmb : cTxt)
 
    float ratio = volIn > 0 ? volEst / volIn : 1.0
    bool sane = ratio > 0.85 and ratio < 1.18
    string chk = sane ? "✓ measured " + str.tostring(volEst, "0") + "% ≈ V" + str.tostring(volIn, "0") : "⚠ measured " + str.tostring(volEst, "0") + "% → looks like V" + str.tostring(nearLvl, "0")
    f_row(t, 11, "Calibration", chk, sane ? cUp : cAmb)
    f_row(t, 12, "Reality check", "constant σ, no memory: 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
            // 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")

← 返回列表