Strong Implied Volatility | ProjectSyndicate

ProjectSyndicate · study · 499 行 · 点赞 1,080 · TradingView 原页

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

Pine Script

//@version=6
indicator("Strong Implied Volatility", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
gV = "═══ Volatility Engine ═══"
volMode   = input.string("Realized (auto)", "IV Source", options = ["Realized (auto)", "Manual IV %", "IV Symbol"], group = gV, tooltip = "Realized = annualised close-to-close daily vol (HV) read non-repainting from the daily feed. Manual = type the ATM IV from your options chain. IV Symbol = read a vol index (VIX / VXN / GVZ / OVX …) daily close as the IV.")
manIV     = input.float(40.0, "Manual ATM IV (%)", minval = 0.1, maxval = 500.0, step = 0.5, group = gV)
ivSym     = input.symbol("CBOE:VIX", "IV Symbol", group = gV, tooltip = "Used only when IV Source = IV Symbol. Read as a % level (VIX 18.4 → 18.4 %).")
hvLen     = input.int(20, "Realized Vol Lookback (days)", minval = 5, maxval = 252, group = gV)
ivMult    = input.float(1.0, "Vol Multiplier", minval = 0.25, maxval = 3.0, step = 0.05, group = gV, tooltip = "Scales whichever vol you feed in. Weekly realised moves are often fatter than HV implies — 1.1–1.2 widens the cone.")
 
gP = "═══ Period & History ═══"
anchorTf  = input.string("W", "Anchor Period", options = ["D", "W", "2W", "M"], group = gP, tooltip = "W = weekly cone (open Monday → expiry Friday / Sunday on crypto). Each period freezes its own σ-cone at the open.")
histN     = input.int(6, "Historic Periods Drawn", minval = 0, maxval = 30, group = gP, tooltip = "Completed periods kept on the chart with their HIT / HELD outcomes. The live period is always drawn on top of these.")
statsN    = input.int(52, "Stats Window (completed periods)", minval = 4, maxval = 260, group = gP, tooltip = "Completed periods feeding the hit-rate ledger, even when they are no longer drawn.")
tdInput   = input.int(0, "Trading Days per Period (0 = auto)", minval = 0, maxval = 60, group = gP, tooltip = "Time-to-expiry in trading days. Auto: D=1, W=5 (crypto 7), 2W=10 (14), M=21 (30).")
 
gT = "═══ Sigma Tiers ═══"
use1       = input.bool(true, "±1σ  (expected move)", group = gT)
use2       = input.bool(true, "±2σ", group = gT)
use3       = input.bool(true, "±3σ", group = gT)
showAnchor = input.bool(true, "Anchor Line (period open)", group = gT)
showCone   = input.bool(true, "Live Cone from Current Price", group = gT, tooltip = "Dashed ±σ lines from the latest close to the period expiry using the REMAINING time — the original IV-range cone, re-struck every bar.")
coneLabels = input.bool(false, "Label Live Cone", group = gT)
 
gR = "═══ Beam Render (GEX palette) ═══"
colorBy    = input.string("Sigma Tier", "Color By", options = ["Sigma Tier", "Strength Score"], group = gR, tooltip = "Sigma Tier: 1σ = low colour, 2σ = mid, 3σ = high. Strength Score: colour follows the 0–10 hold-strength of each level.")
lineW      = input.int(2, "Core Line Width", minval = 1, maxval = 4, group = gR)
gradLayers = input.int(2, "Glow Layers", minval = 1, maxval = 4, group = gR, tooltip = "Extra wider, fainter lines drawn under the core line for a soft glow.")
maxOpac    = input.int(92, "% Core Opacity", minval = 20, maxval = 100, step = 2, group = gR)
minOpac    = input.int(40, "% Weak Opacity", minval = 5, maxval = 90, step = 2, group = gR)
contrast   = input.float(0.7, "Power Contrast", minval = 0.1, maxval = 3.0, step = 0.05, group = gR)
fillTr     = input.int(94, "Cone Fill Transparency", minval = 60, maxval = 100, group = gR)
fadeHit    = input.bool(true, "Dim Hit Levels", group = gR, tooltip = "Levels price has already tagged are dimmed — their liquidity was taken.")
showSep    = input.bool(true, "Period Separators", group = gR)
lowCol     = input.color(#cc24e2, "Low Power / 1σ",  group = gR)
midCol     = input.color(#2f6de0, "Mid Power / 2σ",  group = gR)
highCol    = input.color(#21c997, "High Power / 3σ", group = gR)
 
gLab = "═══ Strength Labels ═══"
showLabels  = input.bool(true, "Show Level Labels", group = gLab)
labelDetail = input.string("Full", "Label Detail", options = ["Full", "Compact"], group = gLab)
showHistLab = input.bool(true, "Label Historic Periods", group = gLab)
showHeader  = input.bool(true, "Period Header (left anchor)", group = gLab)
labelSize   = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal", "Large"], group = gLab)
 
gD = "═══ Dashboard ═══"
showDash = input.bool(true, "Show Dashboard", group = gD)
dashPos  = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = gD)
dashSize = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = gD)
 
gAl = "═══ Alerts ═══"
alertProx = input.float(0.15, "Level Proximity (% of price)", minval = 0.0, step = 0.01, group = gAl)
 
// ───────────────────────────── helpers ─────────────────────────────
clamp01(float x) => math.min(math.max(x, 0.0), 1.0)
f_stars(float sc) => sc >= 8.5 ? "★★★★★" : sc >= 7 ? "★★★★" : sc >= 5.5 ? "★★★" : sc >= 4 ? "★★" : "★"
f_tier(float sc)  => sc >= 8.5 ? "FORTRESS" : sc >= 7 ? "HEAVY" : sc >= 5.5 ? "STRONG" : sc >= 4 ? "MEDIUM" : "LIGHT"
f_lsz(string s)   => s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : s == "Large" ? size.large : size.small
f_dsz(string s)   => s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
f_pos(string s)   => s == "Top Left" ? position.top_left : s == "Bottom Right" ? position.bottom_right : s == "Bottom Left" ? position.bottom_left : position.top_right
 
f_grad(float p) =>
    float v = clamp01(p)
    v < 0.5 ? color.from_gradient(v, 0.0, 0.5, lowCol, midCol) : color.from_gradient(v, 0.5, 1.0, midCol, highCol)
 
f_tr(float p) =>
    float adj = math.pow(clamp01(p), contrast)
    int(math.round((100 - minOpac) + adj * (minOpac - maxOpac)))
 
f_ncdf(float x) =>
    float a = math.abs(x)
    float t = 1.0 / (1.0 + 0.2316419 * a)
    float poly = t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))))
    float tail = 0.3989422804014327 * math.exp(-0.5 * a * a) * poly
    x >= 0 ? 1.0 - tail : tail
 
// Wilson lower bound (z = 1.0, pessimistic) of a hit/hold proportion
f_wilson(float x, float n) =>
    float z = 1.0
    float p = n > 0 ? x / n : 0.0
    float z2n = z * z / n
    n > 0 ? (p + z2n / 2.0 - z * math.sqrt(p * (1.0 - p) / n + z2n * z2n / 4.0)) / (1.0 + z2n) : 0.0
 
f_pct(float x)     => str.tostring(x * 100.0, "#.#") + "%"
f_pct2(float x)    => str.tostring(x * 100.0, "#.##") + "%"
f_px(float px)     => str.tostring(px, format.mintick)
f_sgn(float z, string fmt) => (z >= 0 ? "+" : "") + str.tostring(z, fmt)
f_useK(int k)      => k == 1 ? use1 : k == 2 ? use2 : use3
f_theoTouch(int k) => 2.0 * f_ncdf(-float(k))       // reflection principle, driftless
f_theoEnd(int k)   => f_ncdf(-float(k))             // close beyond ±kσ at expiry
 
// ───────────────────────────── vol feed (non-repaint) ─────────────────────────────
bool  isCrypto = syminfo.type == "crypto"
float tdYear   = isCrypto ? 365.0 : 252.0
float dlr      = close > 0 and close[1] > 0 ? math.log(close / close[1]) : 0.0
float hvRaw    = ta.stdev(dlr, hvLen) * math.sqrt(tdYear)
float hvD      = request.security(syminfo.tickerid, "D", hvRaw[1], lookahead = barmerge.lookahead_on)
float ivSymD   = request.security(ivSym, "D", close[1], lookahead = barmerge.lookahead_on)
 
float ivRaw = volMode == "Manual IV %" ? manIV / 100.0 : volMode == "IV Symbol" ? nz(ivSymD, 0.0) / 100.0 : nz(hvD, 0.0)
float ivUse = ivRaw * ivMult
string ivTag = volMode == "Manual IV %" ? "MANUAL" : volMode == "IV Symbol" ? ivSym : "HV" + str.tostring(hvLen)
 
float autoTd = anchorTf == "D" ? 1.0 : anchorTf == "W" ? (isCrypto ? 7.0 : 5.0) : anchorTf == "2W" ? (isCrypto ? 14.0 : 10.0) : (isCrypto ? 30.0 : 21.0)
float tdPer  = tdInput > 0 ? float(tdInput) : autoTd
float Tyrs   = tdPer / tdYear
 
// ───────────────────────────── period record ─────────────────────────────
type Wk
    int   startT
    int   endT
    int   startBar
    float p0
    float iv
    float sig
    float T
    float hi
    float lo
    float cl
    float sumSq
    int   bars
    bool  done
    array<float>    up
    array<float>    dn
    array<bool>     upHit
    array<bool>     dnHit
    array<int>      upBar
    array<int>      dnBar
    array<line>     upLn
    array<line>     dnLn
    array<label>    upLb
    array<label>    dnLb
    array<linefill> fills
    line  anchor
    line  sep
    label head
 
var array<Wk>    wks     = array.new<Wk>()
var array<float> stUpHit = array.new<float>(3, 0.0)
var array<float> stDnHit = array.new<float>(3, 0.0)
var array<float> stUpEnd = array.new<float>(3, 0.0)
var array<float> stDnEnd = array.new<float>(3, 0.0)
var array<float> stMisc  = array.new<float>(4, 0.0)   // 0 = n completed, 1 = Σ VRP, 2 = Σ |z|, 3 = Σ RV
var array<line>  coneLn  = array.new<line>()
var array<label> coneLb  = array.new<label>()
 
f_delWk(Wk w) =>
    for ln in w.upLn
        if not na(ln)
            line.delete(ln)
    for ln in w.dnLn
        if not na(ln)
            line.delete(ln)
    for lb in w.upLb
        if not na(lb)
            label.delete(lb)
    for lb in w.dnLb
        if not na(lb)
            label.delete(lb)
    for fl in w.fills
        if not na(fl)
            linefill.delete(fl)
    if not na(w.anchor)
        line.delete(w.anchor)
    if not na(w.sep)
        line.delete(w.sep)
    if not na(w.head)
        label.delete(w.head)
    array.clear(w.upLn)
    array.clear(w.dnLn)
    array.clear(w.upLb)
    array.clear(w.dnLb)
    array.clear(w.fills)
 
// honest ledger: every completed period in the window counts, hits and holds alike
f_recalc() =>
    for k = 0 to 2
        array.set(stUpHit, k, 0.0)
        array.set(stDnHit, k, 0.0)
        array.set(stUpEnd, k, 0.0)
        array.set(stDnEnd, k, 0.0)
    float n = 0.0
    float sVrp = 0.0
    float sAbsZ = 0.0
    float sRv = 0.0
    if array.size(wks) > 0
        for i = 0 to array.size(wks) - 1
            Wk w = array.get(wks, i)
            if w.done and w.sig > 0
                n += 1.0
                float zc = math.log(w.cl / w.p0) / w.sig
                float rv = w.T > 0 ? math.sqrt(w.sumSq / w.T) : na
                sAbsZ += math.abs(zc)
                if not na(rv)
                    sRv  += rv
                    sVrp += w.iv - rv
                for k = 0 to 2
                    if array.get(w.upHit, k)
                        array.set(stUpHit, k, array.get(stUpHit, k) + 1.0)
                    if array.get(w.dnHit, k)
                        array.set(stDnHit, k, array.get(stDnHit, k) + 1.0)
                    if w.cl > array.get(w.up, k)
                        array.set(stUpEnd, k, array.get(stUpEnd, k) + 1.0)
                    if w.cl < array.get(w.dn, k)
                        array.set(stDnEnd, k, array.get(stDnEnd, k) + 1.0)
    array.set(stMisc, 0, n)
    array.set(stMisc, 1, sVrp)
    array.set(stMisc, 2, sAbsZ)
    array.set(stMisc, 3, sRv)
 
// 0–10 hold strength of a ±kσ level: Wilson-LB empirical hold rate shrunk toward the lognormal prior
f_score(int k, bool upper) =>
    float n    = array.get(stMisc, 0)
    float hits = upper ? array.get(stUpHit, k - 1) : array.get(stDnHit, k - 1)
    float theo = 1.0 - f_theoTouch(k)
    float lb   = n > 0 ? f_wilson(n - hits, n) : theo
    float w    = n / (n + 6.0)
    10.0 * clamp01(w * lb + (1.0 - w) * theo)
 
f_power(int k, bool upper) => colorBy == "Sigma Tier" ? float(k - 1) / 2.0 : f_score(k, upper) / 10.0
 
f_beam(int x1, float y1, int x2, float y2, color base, int baseTr, array<line> dst) =>
    for g = gradLayers - 1 to 0
        float frac = gradLayers > 1 ? float(g) / (gradLayers - 1) : 0.0
        int   wdt  = lineW + 2 * g
        int   tr   = math.min(96, baseTr + int(frac * (94 - baseTr)))
        line  ln   = line.new(x1, y1, x2, y2, xloc = xloc.bar_time, color = color.new(base, tr), width = wdt)
        array.push(dst, ln)
 
f_dimTier(Wk w, int k, bool upper) =>
    array<line> src = upper ? w.upLn : w.dnLn
    color base = f_grad(f_power(k, upper))
    for g = 0 to gradLayers - 1
        int idx = (k - 1) * gradLayers + g
        if idx < array.size(src)
            line ln = array.get(src, idx)
            if not na(ln)
                line.set_color(ln, color.new(base, 86))
 
f_remFrac(Wk w) =>
    float span = float(w.endT - w.startT)
    span > 0 ? clamp01(float(w.endT - time) / span) : 0.0
 
// ───────────────────────────── label text ─────────────────────────────
f_lvlText(Wk w, int k, bool upper, bool live) =>
    float lvl = upper ? array.get(w.up, k - 1) : array.get(w.dn, k - 1)
    bool  hit = upper ? array.get(w.upHit, k - 1) : array.get(w.dnHit, k - 1)
    int   hb  = upper ? array.get(w.upBar, k - 1) : array.get(w.dnBar, k - 1)
    float sc  = f_score(k, upper)
    float n   = array.get(stMisc, 0)
    float hits = upper ? array.get(stUpHit, k - 1) : array.get(stDnHit, k - 1)
    float ends = upper ? array.get(stUpEnd, k - 1) : array.get(stDnEnd, k - 1)
    string histT = n > 0 ? str.tostring(int(hits)) + "/" + str.tostring(int(n)) + " touch (" + f_pct(hits / n) + ") · " + str.tostring(int(ends)) + " expired beyond (" + f_pct(ends / n) + ")" : "n/a"
    string hdr = (upper ? "▲ +" : "▼ −") + str.tostring(k) + "σ  " + f_px(lvl) + " (" + f_sgn((lvl / w.p0 - 1.0) * 100.0, "#.#") + "%)"
    string outT = hit ? "  ✔ HIT b" + str.tostring(hb) : (live ? "" : "  ✘ HELD")
    string txt = hdr + outT
    if live
        float rf   = f_remFrac(w)
        float sr   = w.sig * math.sqrt(rf)
        float dist = close > 0 ? math.log(lvl / close) : 0.0
        float pT   = hit ? 1.0 : sr > 0 ? math.min(1.0, 2.0 * f_ncdf(-math.abs(dist) / sr)) : 0.0
        float pE   = sr > 0 ? (upper ? f_ncdf((-dist - 0.5 * sr * sr) / sr) : f_ncdf((dist + 0.5 * sr * sr) / sr)) : (upper ? (close > lvl ? 1.0 : 0.0) : (close < lvl ? 1.0 : 0.0))
        float away = (lvl / close - 1.0) * 100.0
        if labelDetail == "Full"
            txt := txt + "  " + f_stars(sc) + " " + str.tostring(sc, "#.0") + "/10 " + f_tier(sc) + " · " + f_sgn(away, "#.#") + "% away · P(touch) " + f_pct(f_theoTouch(k)) + " · LIVE " + f_pct(pT) + " · P(expire beyond) " + f_pct(pE) + " · HIST " + histT
        else
            txt := txt + "  " + f_stars(sc) + " " + str.tostring(sc, "#.0") + " · live " + f_pct(pT) + " · hist " + (n > 0 ? f_pct(hits / n) : "n/a")
    else
        if labelDetail == "Full"
            txt := txt + " · " + f_stars(sc) + " " + str.tostring(sc, "#.0") + "/10 · impl " + f_pct(f_theoTouch(k)) + " · hist " + histT
    txt
 
f_headText(Wk w, bool live) =>
    float z    = w.sig > 0 ? math.log(close / w.p0) / w.sig : 0.0
    float zh   = w.sig > 0 ? math.log(w.hi / w.p0) / w.sig : 0.0
    float zl   = w.sig > 0 ? math.log(w.lo / w.p0) / w.sig : 0.0
    float ef   = 1.0 - f_remFrac(w)
    float rv   = w.T > 0 and ef > 0.05 and w.sumSq > 0 ? math.sqrt(w.sumSq / (w.T * (live ? ef : 1.0))) : na
    string base = "◆ " + anchorTf + " " + str.format_time(w.startT, "dd MMM", syminfo.timezone) + " · open " + f_px(w.p0) + " · IV " + f_pct(w.iv) + " · σ " + f_pct(w.sig) + " (±" + f_px(w.p0 * w.sig) + ")"
    string rvT = na(rv) ? "" : " · RV " + f_pct(rv) + " · VRP " + f_sgn((w.iv - rv) * 100.0, "#.#") + "pt"
    live ? base + " · LIVE z " + f_sgn(z, "#.00") + "σ · " + str.tostring(ef * 100.0, "#") + "% elapsed" + rvT : base + " · close z " + f_sgn(z, "#.00") + "σ · hi " + f_sgn(zh, "#.0") + "σ / lo " + f_sgn(zl, "#.0") + "σ" + rvT
 
f_refreshLabels(Wk w, bool live) =>
    for k = 1 to 3
        if f_useK(k) and array.size(w.upLb) >= k and array.size(w.dnLb) >= k
            label lu = array.get(w.upLb, k - 1)
            label ld = array.get(w.dnLb, k - 1)
            if not na(lu)
                label.set_text(lu, f_lvlText(w, k, true, live))
            if not na(ld)
                label.set_text(ld, f_lvlText(w, k, false, live))
    if not na(w.head)
        label.set_text(w.head, f_headText(w, live))
 
// ───────────────────────────── draw a period ─────────────────────────────
f_draw(Wk w) =>
    bool drawLab = showLabels
    for k = 1 to 3
        float pu = f_power(k, true)
        float pd = f_power(k, false)
        color cu = f_grad(pu)
        color cd = f_grad(pd)
        if f_useK(k)
            f_beam(w.startT, w.p0, w.endT, array.get(w.up, k - 1), cu, f_tr(pu), w.upLn)
            f_beam(w.startT, w.p0, w.endT, array.get(w.dn, k - 1), cd, f_tr(pd), w.dnLn)
            line coreU = array.get(w.upLn, array.size(w.upLn) - 1)
            line coreD = array.get(w.dnLn, array.size(w.dnLn) - 1)
            linefill fl = linefill.new(coreU, coreD, color.new(cu, fillTr))
            array.push(w.fills, fl)
            label lu = drawLab ? label.new(w.endT, array.get(w.up, k - 1), "", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(cu, 15), textcolor = color.white, size = f_lsz(labelSize)) : na
            label ld = drawLab ? label.new(w.endT, array.get(w.dn, k - 1), "", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(cd, 15), textcolor = color.white, size = f_lsz(labelSize)) : na
            array.push(w.upLb, lu)
            array.push(w.dnLb, ld)
        else
            for g = 0 to gradLayers - 1
                array.push(w.upLn, na)
                array.push(w.dnLn, na)
            array.push(w.fills, na)
            array.push(w.upLb, na)
            array.push(w.dnLb, na)
    if showAnchor
        w.anchor := line.new(w.startT, w.p0, w.endT, w.p0, xloc = xloc.bar_time, color = color.new(color.gray, 55), width = 1, style = line.style_dotted)
    if showSep
        w.sep := line.new(w.startT, w.p0, w.startT, w.p0 * 1.001, xloc = xloc.bar_time, extend = extend.both, color = color.new(#5C6470, 35), width = 1, style = line.style_dashed)
    if showHeader and showLabels
        w.head := label.new(w.startT, w.p0, "", xloc = xloc.bar_time, style = label.style_label_right, color = color.new(midCol, 25), textcolor = color.white, size = f_lsz(labelSize))
 
// ───────────────────────────── period engine ─────────────────────────────
var Wk act = na
bool newP  = ta.change(time(anchorTf)) != 0
bool tfTooBig = timeframe.in_seconds() >= timeframe.in_seconds(anchorTf)
 
if newP and not tfTooBig
    // close the previous period — outcomes are frozen, drawings become history
    if not na(act)
        act.done := true
        array.push(wks, act)
        f_recalc()
        if showLabels and showHistLab
            f_refreshLabels(act, false)
        else
            for lb in act.upLb
                if not na(lb)
                    label.delete(lb)
            for lb in act.dnLb
                if not na(lb)
                    label.delete(lb)
            array.clear(act.upLb)
            array.clear(act.dnLb)
            if not na(act.head)
                label.delete(act.head)
                act.head := na
        // cull drawings beyond histN (the live period is extra)
        int nW = array.size(wks)
        if nW > histN
            Wk old = array.get(wks, nW - histN - 1)
            f_delWk(old)
        // cull records beyond the stats window
        while array.size(wks) > statsN
            Wk gone = array.shift(wks)
            f_delWk(gone)
 
    int   t0 = time(anchorTf)
    int   t1 = time_close(anchorTf)
    if na(t1) or t1 <= t0
        t1 := t0 + int(math.round(autoTd * 86400000.0 * (isCrypto ? 1.0 : 7.0 / 5.0)))
    float p0 = open
    float sg = ivUse * math.sqrt(Tyrs)
    Wk w = Wk.new(startT = t0, endT = t1, startBar = bar_index, p0 = p0, iv = ivUse, sig = sg, T = Tyrs, hi = high, lo = low, cl = close, sumSq = 0.0, bars = 0, done = false)
    w.up    := array.new<float>(3, na)
    w.dn    := array.new<float>(3, na)
    w.upHit := array.new<bool>(3, false)
    w.dnHit := array.new<bool>(3, false)
    w.upBar := array.new<int>(3, 0)
    w.dnBar := array.new<int>(3, 0)
    w.upLn  := array.new<line>()
    w.dnLn  := array.new<line>()
    w.upLb  := array.new<label>()
    w.dnLb  := array.new<label>()
    w.fills := array.new<linefill>()
    float drift = -0.5 * sg * sg
    for k = 1 to 3
        array.set(w.up, k - 1, p0 * math.exp(drift + k * sg))
        array.set(w.dn, k - 1, p0 * math.exp(drift - k * sg))
    if sg > 0
        f_draw(w)
    act := w
 
// per-bar lifecycle of the live period: running extremes, realised variance, level hits
if not na(act) and not act.done
    act.hi    := math.max(act.hi, high)
    act.lo    := math.min(act.lo, low)
    act.cl    := close
    act.sumSq := act.sumSq + dlr * dlr
    act.bars  := act.bars + 1
    for k = 1 to 3
        if not array.get(act.upHit, k - 1) and high >= array.get(act.up, k - 1)
            array.set(act.upHit, k - 1, true)
            array.set(act.upBar, k - 1, act.bars)
            if fadeHit
                f_dimTier(act, k, true)
        if not array.get(act.dnHit, k - 1) and low <= array.get(act.dn, k - 1)
            array.set(act.dnHit, k - 1, true)
            array.set(act.dnBar, k - 1, act.bars)
            if fadeHit
                f_dimTier(act, k, false)
 
// ───────────────────────────── live refresh (last bar) ─────────────────────────────
float liveRf = not na(act) ? f_remFrac(act) : 0.0
float liveSr = not na(act) ? ivUse * math.sqrt(act.T * liveRf) : 0.0
 
if barstate.islast and not na(act)
    f_recalc()
    if showLabels
        f_refreshLabels(act, true)
    // re-strike the live cone from the current close with the remaining time
    for ln in coneLn
        line.delete(ln)
    for lb in coneLb
        label.delete(lb)
    array.clear(coneLn)
    array.clear(coneLb)
    if showCone and liveSr > 0 and act.endT > time
        float dr = -0.5 * liveSr * liveSr
        for k = 1 to 3
            if f_useK(k)
                float cu = close * math.exp(dr + k * liveSr)
                float cd = close * math.exp(dr - k * liveSr)
                color cc = f_grad(f_power(k, true))
                array.push(coneLn, line.new(time, close, act.endT, cu, xloc = xloc.bar_time, color = color.new(cc, 45), width = 1, style = line.style_dashed))
                array.push(coneLn, line.new(time, close, act.endT, cd, xloc = xloc.bar_time, color = color.new(cc, 45), width = 1, style = line.style_dashed))
                if coneLabels
                    array.push(coneLb, label.new(act.endT, cu, "live +" + str.tostring(k) + "σ " + f_px(cu), xloc = xloc.bar_time, style = label.style_label_right, color = color.new(cc, 60), textcolor = color.white, size = size.tiny))
                    array.push(coneLb, label.new(act.endT, cd, "live −" + str.tostring(k) + "σ " + f_px(cd), xloc = xloc.bar_time, style = label.style_label_right, color = color.new(cc, 60), textcolor = color.white, size = size.tiny))
 
// ───────────────────────────── dashboard ─────────────────────────────
var table dash = table.new(f_pos(dashPos), 2, 12, bgcolor = color.new(#0b0e14, 15), border_color = color.new(#2a2f3a, 40), border_width = 1)
f_cell(int r, string a, string b, color bc) =>
    table.cell(dash, 0, r, a, text_color = color.new(#c9ced6, 0), text_halign = text.align_left, text_size = f_dsz(dashSize))
    table.cell(dash, 1, r, b, text_color = bc, text_halign = text.align_right, text_size = f_dsz(dashSize))
 
if barstate.islast and showDash
    table.clear(dash, 0, 0, 1, 11)
    table.cell(dash, 0, 0, "STRONG IV", text_color = highCol, text_halign = text.align_left, text_size = f_dsz(dashSize))
    table.cell(dash, 1, 0, anchorTf + " · " + ivTag, text_color = highCol, text_halign = text.align_right, text_size = f_dsz(dashSize))
    float n = array.get(stMisc, 0)
    if na(act)
        f_cell(1, "status", tfTooBig ? "chart TF ≥ anchor" : "waiting for period open", color.new(#ffb454, 0))
    else
        float z   = act.sig > 0 ? math.log(close / act.p0) / act.sig : 0.0
        float ef  = 1.0 - liveRf
        float rv  = act.T > 0 and ef > 0.05 and act.sumSq > 0 ? math.sqrt(act.sumSq / (act.T * ef)) : na
        f_cell(1, "IV used", f_pct(act.iv) + (ivMult != 1.0 ? " (×" + str.tostring(ivMult, "#.##") + ")" : ""), color.white)
        f_cell(2, "period σ", f_pct(act.sig) + " · " + str.tostring(tdPer, "#") + " td", color.white)
        f_cell(3, "anchor open", f_px(act.p0) + " · " + str.format_time(act.startT, "dd MMM", syminfo.timezone), color.white)
        f_cell(4, "expected move", "±" + f_px(act.p0 * act.sig) + "  (" + f_px(array.get(act.dn, 0)) + " – " + f_px(array.get(act.up, 0)) + ")", f_grad(0.0))
        f_cell(5, "live z / elapsed", f_sgn(z, "#.00") + "σ · " + str.tostring(ef * 100.0, "#") + "%", math.abs(z) >= 2 ? f_grad(1.0) : math.abs(z) >= 1 ? f_grad(0.5) : color.white)
        f_cell(6, "live cone ±1σ", liveSr > 0 ? f_px(close * math.exp(-0.5 * liveSr * liveSr - liveSr)) + " – " + f_px(close * math.exp(-0.5 * liveSr * liveSr + liveSr)) : "expired", color.white)
        f_cell(7, "period RV / VRP", na(rv) ? "n/a" : f_pct(rv) + " · " + f_sgn((act.iv - rv) * 100.0, "#.#") + "pt", na(rv) ? color.gray : (act.iv - rv >= 0 ? highCol : lowCol))
        for k = 1 to 3
            float hu = array.get(stUpHit, k - 1)
            float hd = array.get(stDnHit, k - 1)
            float emp = n > 0 ? (hu + hd) / (2.0 * n) : na
            string hitT = n > 0 ? "↑" + str.tostring(int(hu)) + " ↓" + str.tostring(int(hd)) + " /" + str.tostring(int(n)) + " · " + f_pct(emp) + " vs " + f_pct(f_theoTouch(k)) : "n/a"
            color hc = na(emp) ? color.gray : emp > f_theoTouch(k) * 1.15 ? lowCol : emp < f_theoTouch(k) * 0.85 ? highCol : color.white
            f_cell(7 + k, "hist ±" + str.tostring(k) + "σ hit", hitT, hc)
        float avgVrp = n > 0 ? array.get(stMisc, 1) / n : na
        float avgZ   = n > 0 ? array.get(stMisc, 2) / n : na
        f_cell(11, "avg VRP · avg |z|", na(avgVrp) ? "n/a" : f_sgn(avgVrp * 100.0, "#.#") + "pt (" + (avgVrp >= 0 ? "IV RICH" : "IV CHEAP") + ") · " + str.tostring(avgZ, "#.00") + "σ", na(avgVrp) ? color.gray : avgVrp >= 0 ? highCol : lowCol)
 
var label warnLb = na
if barstate.islast
    if not na(warnLb)
        label.delete(warnLb)
        warnLb := na
    if tfTooBig
        warnLb := label.new(bar_index, high, "Chart timeframe is not lower than the " + anchorTf + " anchor —\nswitch to an intra-period timeframe for the σ-cone to resolve.", xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#7A2B2B, 15), textcolor = #F0F0F0, style = label.style_label_down, size = size.small, textalign = text.align_left)
 
// ───────────────────────────── alerts ─────────────────────────────
float aU1 = not na(act) ? array.get(act.up, 0) : na
float aD1 = not na(act) ? array.get(act.dn, 0) : na
float aU2 = not na(act) ? array.get(act.up, 1) : na
float aD2 = not na(act) ? array.get(act.dn, 1) : na
float aU3 = not na(act) ? array.get(act.up, 2) : na
float aD3 = not na(act) ? array.get(act.dn, 2) : na
float prox = close * alertProx / 100.0
 
alertcondition(not na(aU1) and math.abs(close - aU1) <= prox, "Approaching +1σ", "Price approaching the +1σ expected-move level.")
alertcondition(not na(aD1) and math.abs(close - aD1) <= prox, "Approaching −1σ", "Price approaching the −1σ expected-move level.")
alertcondition(not na(aU2) and math.abs(close - aU2) <= prox, "Approaching +2σ", "Price approaching the +2σ wall.")
alertcondition(not na(aD2) and math.abs(close - aD2) <= prox, "Approaching −2σ", "Price approaching the −2σ wall.")
alertcondition(not na(aU1) and ta.crossover(high, aU1),  "+1σ Tagged", "Price tagged the +1σ expected-move level.")
alertcondition(not na(aD1) and ta.crossunder(low, aD1),  "−1σ Tagged", "Price tagged the −1σ expected-move level.")
alertcondition(not na(aU2) and ta.crossover(high, aU2),  "+2σ Tagged", "Price tagged the +2σ wall — 2σ tail event.")
alertcondition(not na(aD2) and ta.crossunder(low, aD2),  "−2σ Tagged", "Price tagged the −2σ wall — 2σ tail event.")
alertcondition(not na(aU3) and ta.crossover(high, aU3),  "+3σ Tagged", "Price tagged the +3σ wall — extreme tail event.")
alertcondition(not na(aD3) and ta.crossunder(low, aD3),  "−3σ Tagged", "Price tagged the −3σ wall — extreme tail event.")
alertcondition(not na(aU2) and close > aU2, "Close beyond +2σ", "Close is beyond the +2σ wall — IV under-priced the upside.")
alertcondition(not na(aD2) and close < aD2, "Close beyond −2σ", "Close is beyond the −2σ wall — IV under-priced the downside.")

← 返回列表