MM Flow
FlowScripts

Perfected FlowScript

Volatility and Skew Suite

Volatility and Skew Suite — Perfected Edition is indexed as 150_volatility_and_skew_suite.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.

This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.

Dialect

flowscript-v2

Compatibility

flowscript-v2-needs-transpile

Position

offchart

Axis

true

Size

23.7 KB

Lines

707

Native Signal Candidates

6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

6/6 guarded

Extreme High

line 596:9

Trigger

(showShapes) && (zCrossUp)

Value

primaryVal

Deps

showShapes:input, zCrossUp:var

Extreme Low

line 606:9

Trigger

(showShapes) && (zCrossDn)

Value

primaryVal

Deps

showShapes:input, zCrossDn:var

Elevated High

line 616:9

Trigger

(showShapes) && (zMildUp && !zCrossUp)

Value

primaryVal

Deps

showShapes:input, zCrossUp:var, zMildUp:var

Elevated Low

line 626:9

Trigger

(showShapes) && (zMildDn && !zCrossDn)

Value

primaryVal

Deps

showShapes:input, zCrossDn:var, zMildDn:var

Zero Cross Up

line 636:9

Trigger

(showShapes) && (zeroCrossUp && (mode == "IV - RV Spread" || mode == "Variance Risk Premium" || mode == "Volatility Momentum" || mode == "Skew Momentum" || mode == "Volatility Term Structure"))

Value

0

Deps

mode:input, showShapes:input, zeroCrossUp:var

Zero Cross Down

line 646:9

Trigger

(showShapes) && (zeroCrossDn && (mode == "IV - RV Spread" || mode == "Variance Risk Premium" || mode == "Volatility Momentum" || mode == "Skew Momentum" || mode == "Volatility Term Structure"))

Value

0

Deps

mode:input, showShapes:input, zeroCrossDn:var

150_volatility_and_skew_suite.flowscript

source path: kscripts/perfected/150_volatility_and_skew_suite.flowscript · sha256:00efd859565e50f62d11b2cd20b947f792c0f0b5b618e4d3a7536c72b02f79bd

hash verified
//@version=2
// ============================================================================
// Volatility and Skew Suite — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, ADVANCED, #options, #volatility, #skew, #zscore, #momentum, #regime
//
// Production-quality multi-dimensional options analytics panel combining
// realized volatility, implied volatility (proxy), variance risk premium,
// skew, term structure, and put/call ratio into a unified sentiment/flow
// dashboard with z-score normalization, dynamic regime detection, and
// comprehensive fill / shape / histogram visualization.
//
// Research papers underpinning this design:
//  1. Black & Scholes (1973), "The Pricing of Options and Corporate
//     Liabilities": canonical option pricing. IV is the σ that equates
//     model price to market price; underpins all vol extraction.
//  2. Carr & Wu (2009), "Variance Risk Premia": VRP = IV² − RV²;
//     documented strongly negative VRP across equity indexes, establishing
//     the convexity-aware premium concept.
//  3. Zhang & Xiang (2008), "The Implied Volatility Smirk": 25-delta put/call
//     skew as polynomial expansion around ATM-forward; quantifies skew shape
//     and links to risk-neutral moments.
//  4. Zhu (2025), "Put-Call Ratio as a Sentiment Indicator": validates PCR
//     as a robust cross-asset contrarian signal; extreme readings flag
//     crowded positioning.
//  5. Xu & Taylor (1994), "The Term Structure of Volatility Implied by
//     Foreign Exchange Options": factor-decomposition (level, slope,
//     curvature) for term structure; >0 slope pushes risk outward.
//  6. Parkinson (1980), "The Extreme Value Method for Estimating the Variance
//     of the Rate of Return": Parkinson estimator σₚ = √[1/(4·ln2) · Σ(ln(H/L))²]
//     is ~5.2× more efficient than close-close; underpins the IV proxy.
//  7. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons; supports dynamic z-score thresholds
//     calibrated to rolling volatility regimes.
// ============================================================================

define(
    title="Volatility and Skew Suite — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Mode ---
var mode = input(
    name="mode",
    type="select",
    defaultValue="IV - RV Spread",
    label="Primary Display Mode",
    options=["Realised Volatility","Implied Volatility","IV - RV Spread",
             "Variance Risk Premium","Volatility Z-Score","Volatility Momentum",
             "Volatility of Volatility","Skew","Skew Momentum",
             "Volatility Term Structure","Put to Call Ratio","Put & Call Volume"],
    group="Mode"
)

// --- Volatility ---
var rvLen = input(
    name="rvLen",
    type="number",
    defaultValue=14,
    label="RV Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volatility"
)
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=60,
    label="Z-Score Window",
    constraints={min: 20, max: 252, step: 1},
    group="Volatility"
)
var annualize = input(
    name="annualize",
    type="boolean",
    defaultValue=true,
    label="Annualize (365-day basis)",
    group="Volatility"
)
var useParkinson = input(
    name="useParkinson",
    type="boolean",
    defaultValue=true,
    label="Use Parkinson IV Proxy (high-low)",
    group="Volatility"
)

// --- Skew ---
var skewLen = input(
    name="skewLen",
    type="number",
    defaultValue=14,
    label="Skew Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Skew"
)

// --- Term Structure ---
var shortTerm = input(
    name="shortTerm",
    type="number",
    defaultValue=5,
    label="Short-Term RV Length",
    constraints={min: 2, max: 20, step: 1},
    group="Term Structure"
)
var longTerm = input(
    name="longTerm",
    type="number",
    defaultValue=30,
    label="Long-Term RV Length",
    constraints={min: 10, max: 100, step: 1},
    group="Term Structure"
)

// --- Thresholds & Regime ---
var zExtreme = input(
    name="zExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)
var zMild = input(
    name="zMild",
    type="number",
    defaultValue=1.0,
    label="Mild Z-Score Threshold",
    constraints={min: 0.5, max: 2.0, step: 0.1},
    group="Thresholds"
)
var useDynamicRegime = input(
    name="useDynamicRegime",
    type="boolean",
    defaultValue=true,
    label="Dynamic Regime Bands (vol-adjusted)",
    group="Thresholds"
)

// --- Display ---
var showPrimary = input(
    name="showPrimary",
    type="boolean",
    defaultValue=true,
    label="Show Primary Line",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Overlay",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showRegimeFill = input(
    name="showRegimeFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Guide Lines",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table",
    group="Display"
)

// --- Colors ---
var lowVolColor = input(
    name="lowVolColor",
    type="color",
    defaultValue="#26a69a",
    label="Low Vol / Normal Color",
    group="Colors"
)
var highVolColor = input(
    name="highVolColor",
    type="color",
    defaultValue="#ef5350",
    label="High Vol / Extreme Color",
    group="Colors"
)
var midVolColor = input(
    name="midVolColor",
    type="color",
    defaultValue="#ffa726",
    label="Mild Vol / Elevated Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var fillUpColor = input(
    name="fillUpColor",
    type="color",
    defaultValue="#26a69a",
    label="Positive Fill",
    group="Colors"
)
var fillDnColor = input(
    name="fillDnColor",
    type="color",
    defaultValue="#ef5350",
    label="Negative Fill",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries open = price.open
timeseries volume = price.volume

if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(volume[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. REALIZED VOLATILITY (Parkinson-enhanced close-close)
// -----------------------------------------------------------------------------
// Log returns
timeseries logRet = math.log(close / math.max(close[1], 0.0001))
// Rolling stdev of log returns
timeseries rvPeriod = stdev(logRet, rvLen)
// Annualize (365 periods per year crypto style)
timeseries annualFactor = annualize ? math.sqrt(365) : 1.0
timeseries rvPct = rvPeriod * annualFactor * 100.0
timeseries rvSq = rvPct * rvPct

// -----------------------------------------------------------------------------
// 4. IMPLIED VOLATILITY PROXY
// -----------------------------------------------------------------------------
// Parkinson estimator: σₚ = √[1/(4·ln2) · (ln(H/L))²] — ~5.2× more efficient
// than close-close (Parkinson 1980). Used as a high-quality IV proxy when
// options chain data is unavailable.

var parkinsonFactor = 1.0 / math.sqrt(4.0 * math.log(2.0))
timeseries hlLog = math.log(high / math.max(low, 0.0001))
timeseries parkinson = stdev(hlLog, rvLen) * parkinsonFactor * annualFactor * 100.0

// Rolling high-low range as a secondary IV proxy (smoothed)
timeseries hlRange = (high - low) / math.max(close, 0.0001)
timeseries ivRaw = ema(hlRange, rvLen) * math.sqrt(365) * 100.0

// Composite IV (weighted blend of Parkinson and raw range)
timeseries ivComposite = useParkinson ? 0.7 * parkinson + 0.3 * ivRaw : ivRaw
timeseries ivSq = ivComposite * ivComposite

// -----------------------------------------------------------------------------
// 5. DERIVED VOLATILITY METRICS
// -----------------------------------------------------------------------------
// IV-RV spread (carry / risk premium)
timeseries spread = ivComposite - rvPct
// Variance Risk Premium (Carr & Wu 2009)
timeseries vrp = ivSq - rvSq

// Volatility momentum (rate of change)
timeseries rvMom = rvPct - rvPct[rvLen]

// Volatility of volatility
timeseries rvStd = stdev(rvPct, rvLen)
timeseries rvMean = sma(rvPct, zLen)
timeseries volOfVol = rvStd / math.max(rvMean, 0.0001)

// -----------------------------------------------------------------------------
// 6. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Standardized measure: z = (X − μ) / σ over a rolling window.
// Per Zhao & Palomar (2018), thresholds at ±1σ and ±2σ flag statistical rarity.

timeseries rvMeanZ = sma(rvPct, zLen)
timeseries rvStdZ = stdev(rvPct, zLen)
timeseries rvZ = (rvPct - rvMeanZ) / math.max(rvStdZ, 0.0001)

timeseries spreadMean = sma(spread, zLen)
timeseries spreadStd = stdev(spread, zLen)
timeseries spreadZ = (spread - spreadMean) / math.max(spreadStd, 0.0001)

timeseries vrpMean = sma(vrp, zLen)
timeseries vrpStd = stdev(vrp, zLen)
timeseries vrpZ = (vrp - vrpMean) / math.max(vrpStd, 0.0001)

timeseries skewMean = sma(skewProxy, zLen)
timeseries skewStd = stdev(skewProxy, zLen)
timeseries skewZ = (skewProxy - skewMean) / math.max(skewStd, 0.0001)

timeseries termMean = sma(termStruct, zLen)
timeseries termStd = stdev(termStruct, zLen)
timeseries termZ = (termStruct - termMean) / math.max(termStd, 0.0001)

timeseries pcrMean = sma(pcr, zLen)
timeseries pcrStd = stdev(pcr, zLen)
timeseries pcrZ = (pcr - pcrMean) / math.max(pcrStd, 0.0001)

// -----------------------------------------------------------------------------
// 7. SKEW PROXY
// -----------------------------------------------------------------------------
// Upper- and lower-wick ratios as a bar-level skew proxy. When lower wicks
// dominate, sellers are being absorbed (bullish skew); when upper wicks dominate,
// buyers are being absorbed (bearish skew).

timeseries upperWick = high - math.max(open, close)
timeseries lowerWick = math.min(open, close) - low
timeseries skewProxy = ema(lowerWick - upperWick, skewLen) / math.max(close * 0.001, 0.0001)
timeseries skewMom = skewProxy - skewProxy[skewLen]

// -----------------------------------------------------------------------------
// 8. TERM STRUCTURE
// -----------------------------------------------------------------------------
// Short- vs long-term realized volatility slope. Positive slope = risk pushed
// outward (backdated); negative slope = near-term risk elevated (contango).

timeseries logRetS = math.log(close / math.max(close[1], 0.0001))
timeseries shortRV = stdev(logRetS, shortTerm) * annualFactor * 100.0
timeseries longRV  = stdev(logRetS, longTerm) * annualFactor * 100.0
timeseries termStruct = longRV - shortRV

// -----------------------------------------------------------------------------
// 9. PUT/CALL RATIO PROXY
// -----------------------------------------------------------------------------
// Down-volume vs up-volume as a sentiment proxy (Zhu 2025 contrarian framework).
// Extreme readings (>1.5 or <0.5) flag crowded positioning.

timeseries isDown = close < open
timeseries isUp = close >= open
timeseries downVol = isDown ? volume : 0.0
timeseries upVol   = isUp ? volume : 0.0
timeseries pcr = sma(downVol, 14) / math.max(sma(upVol, 14), 1.0)

// -----------------------------------------------------------------------------
// 10. MODE SELECTOR & PRIMARY VALUE
// -----------------------------------------------------------------------------
timeseries primaryVal = (mode == "Realised Volatility") ? rvPct
    : (mode == "Implied Volatility")       ? ivComposite
    : (mode == "IV - RV Spread")           ? spread
    : (mode == "Variance Risk Premium")    ? vrp
    : (mode == "Volatility Z-Score")       ? rvZ
    : (mode == "Volatility Momentum")      ? rvMom
    : (mode == "Volatility of Volatility") ? volOfVol
    : (mode == "Skew")                     ? skewProxy
    : (mode == "Skew Momentum")            ? skewMom
    : (mode == "Volatility Term Structure")? termStruct
    : (mode == "Put to Call Ratio")        ? pcr
    : sma(downVol + upVol, 14)

timeseries primaryZ = (mode == "Realised Volatility") ? rvZ
    : (mode == "Implied Volatility")       ? rvZ
    : (mode == "IV - RV Spread")           ? spreadZ
    : (mode == "Variance Risk Premium")    ? vrpZ
    : (mode == "Volatility Z-Score")       ? rvZ
    : (mode == "Volatility Momentum")      ? ((rvMom - sma(rvMom, zLen)) / math.max(stdev(rvMom, zLen), 0.0001))
    : (mode == "Volatility of Volatility") ? ((volOfVol - sma(volOfVol, zLen)) / math.max(stdev(volOfVol, zLen), 0.0001))
    : (mode == "Skew")                     ? skewZ
    : (mode == "Skew Momentum")            ? ((skewMom - sma(skewMom, zLen)) / math.max(stdev(skewMom, zLen), 0.0001))
    : (mode == "Volatility Term Structure")? termZ
    : (mode == "Put to Call Ratio")        ? pcrZ
    : 0.0

// Momentum histogram for the primary metric
timeseries primaryMom = primaryVal - primaryVal[rvLen]

// -----------------------------------------------------------------------------
// 11. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on the primary metric's z-score or on the raw
// metric itself when z-score is unavailable. Three regimes: calm, elevated, extreme.

var regime = 0      // 0 = calm, 1 = elevated, 2 = extreme high, -1 = elevated low, -2 = extreme low
var regimeColor = neutralColor

var dynHigh = zMild
var dynLow = -zMild
var dynExtHigh = zExtreme
var dynExtLow = -zExtreme

if (useDynamicRegime) {
    // Dynamic bands based on rolling z-score volatility
    var zVol = stddev(primaryZ, zLen)
    dynHigh = zMild + zVol * 0.5
    dynLow = -(zMild + zVol * 0.5)
    dynExtHigh = zExtreme + zVol
    dynExtLow = -(zExtreme + zVol)
    // Clamp
    dynHigh = math.min(dynHigh, 3.0)
    dynLow = math.max(dynLow, -3.0)
    dynExtHigh = math.min(dynExtHigh, 4.0)
    dynExtLow = math.max(dynExtLow, -4.0)
}

if (!isnan(primaryZ[0])) {
    if (primaryZ >= dynExtHigh) {
        regime = 2
        regimeColor = highVolColor
    } else if (primaryZ >= dynHigh) {
        regime = 1
        regimeColor = midVolColor
    } else if (primaryZ <= dynExtLow) {
        regime = -2
        regimeColor = highVolColor
    } else if (primaryZ <= dynLow) {
        regime = -1
        regimeColor = midVolColor
    } else {
        regime = 0
        regimeColor = lowVolColor
    }
} else {
    // Fallback using raw primary value if z-score is NaN
    var primMean = sma(primaryVal, zLen)
    var primStd = stdev(primaryVal, zLen)
    var rawZ = primStd > 0 ? (primaryVal - primMean) / primStd : 0
    if (rawZ >= zExtreme) {
        regime = 2
        regimeColor = highVolColor
    } else if (rawZ >= zMild) {
        regime = 1
        regimeColor = midVolColor
    } else if (rawZ <= -zExtreme) {
        regime = -2
        regimeColor = highVolColor
    } else if (rawZ <= -zMild) {
        regime = -1
        regimeColor = midVolColor
    } else {
        regime = 0
        regimeColor = lowVolColor
    }
}

// -----------------------------------------------------------------------------
// 12. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static sessionHighVal = -999999.0
static sessionLowVal = 999999.0
static lastRegime = 0
static regimeChangeCount = 0
static extremeHighCount = 0
static extremeLowCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex && !isLiveUpdate) {
    lastBarIndex = currentBarIndex

    // Session extremes for the primary metric
    if (primaryVal > sessionHighVal) {
        sessionHighVal = primaryVal
    }
    if (primaryVal < sessionLowVal) {
        sessionLowVal = primaryVal
    }

    // Regime transition counting
    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    // Extreme event counting
    if (regime == 2 || regime == -2) {
        if (regime == 2) {
            extremeHighCount = extremeHighCount + 1
        } else {
            extremeLowCount = extremeLowCount + 1
        }
    }
}

// Initialize on first bar
if (sessionHighVal < -900000) {
    sessionHighVal = primaryVal
    sessionLowVal = primaryVal
    lastRegime = regime
}

// -----------------------------------------------------------------------------
// 13. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Z-score extreme penetrations and exits
var zCrossUp = primaryZ > dynExtHigh && !isnan(primaryZ[1]) && primaryZ[1] <= dynExtHigh
var zCrossDn = primaryZ < dynExtLow && !isnan(primaryZ[1]) && primaryZ[1] >= dynExtLow
var zMildUp = primaryZ > dynHigh && !isnan(primaryZ[1]) && primaryZ[1] <= dynHigh
var zMildDn = primaryZ < dynLow && !isnan(primaryZ[1]) && primaryZ[1] >= dynLow
var zExitHigh = primaryZ < dynHigh && !isnan(primaryZ[1]) && primaryZ[1] >= dynHigh
var zExitLow = primaryZ > dynLow && !isnan(primaryZ[1]) && primaryZ[1] <= dynLow

// Zero-line cross for momentum-like metrics
var zeroCrossUp = primaryVal > 0 && !isnan(primaryVal[1]) && primaryVal[1] <= 0
var zeroCrossDn = primaryVal < 0 && !isnan(primaryVal[1]) && primaryVal[1] >= 0

// -----------------------------------------------------------------------------
// 14. PLOTTING
// -----------------------------------------------------------------------------

// --- Midline ---
hline(value=0, color="#ffffff20", width=1)

// --- Guide lines (z-score thresholds) ---
if (showGuides) {
    hline(value=dynHigh, color=transparency(midVolColor, 60), width=1)
    hline(value=dynLow, color=transparency(midVolColor, 60), width=1)
    hline(value=dynExtHigh, color=transparency(highVolColor, 40), width=1)
    hline(value=dynExtLow, color=transparency(highVolColor, 40), width=1)
}

// --- Primary Line (regime-colored) ---
if (showPrimary) {
    plotLine(
        value=primaryVal,
        width=2,
        colors=[regimeColor],
        label=[mode],
        desc=["Primary metric: " + mode]
    )
}

// --- Z-Score Overlay (secondary line) ---
if (showZScore && !isnan(primaryZ[0])) {
    var zColor = primaryZ > 0 ? fillUpColor : fillDnColor
    plotLine(
        value=primaryZ,
        width=1,
        colors=[transparency(zColor, 50)],
        label=["Z-Score"],
        desc=["Rolling z-score of primary metric (" + zLen + "-period window)"]
    )
}

// --- Regime Fill (primary vs zero) ---
if (showRegimeFill) {
    var fillBull = primaryVal > 0
    plotLine(
        value=[primaryVal, 0],
        width=1,
        colors=[transparency(fillUpColor, 15), transparency(fillDnColor, 15)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=[mode, "Zero"],
        desc=["Regime fill between primary metric and zero line"]
    )
}

// --- Momentum Histogram ---
if (showHistogram) {
    var histBull = primaryMom >= 0
    plotBar(
        value=primaryMom,
        colors=[transparency(fillUpColor, 50), transparency(fillDnColor, 50)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Momentum"],
        desc=["Primary metric momentum (" + rvLen + "-period difference)"]
    )
}

// --- Extreme Shapes ---
if (showShapes) {
    if (zCrossUp) {
        plotShape(
            value=primaryVal,
            shape="triangleup",
            color=highVolColor,
            width=3,
            label=["Extreme High"],
            desc=["Z-score crossed above +" + dynExtHigh + " — extreme regime entry"]
        )
    }
    if (zCrossDn) {
        plotShape(
            value=primaryVal,
            shape="triangledown",
            color=highVolColor,
            width=3,
            label=["Extreme Low"],
            desc=["Z-score crossed below " + dynExtLow + " — extreme regime entry"]
        )
    }
    if (zMildUp && !zCrossUp) {
        plotShape(
            value=primaryVal,
            shape="diamond",
            color=midVolColor,
            width=2,
            label=["Elevated High"],
            desc=["Z-score crossed above +" + dynHigh + " — elevated regime entry"]
        )
    }
    if (zMildDn && !zCrossDn) {
        plotShape(
            value=primaryVal,
            shape="diamond",
            color=midVolColor,
            width=2,
            label=["Elevated Low"],
            desc=["Z-score crossed below " + dynLow + " — elevated regime entry"]
        )
    }
    if (zeroCrossUp && (mode == "IV - RV Spread" || mode == "Variance Risk Premium" || mode == "Volatility Momentum" || mode == "Skew Momentum" || mode == "Volatility Term Structure")) {
        plotShape(
            value=0,
            shape="circle",
            color=fillUpColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["Primary metric crossed above zero"]
        )
    }
    if (zeroCrossDn && (mode == "IV - RV Spread" || mode == "Variance Risk Premium" || mode == "Volatility Momentum" || mode == "Skew Momentum" || mode == "Volatility Term Structure")) {
        plotShape(
            value=0,
            shape="circle",
            color=fillDnColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["Primary metric crossed below zero"]
        )
    }
}

// -----------------------------------------------------------------------------
// 15. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar && showTable) {
    var regimeText = (regime == 2) ? "EXTREME HIGH"
        : (regime == 1) ? "ELEVATED HIGH"
        : (regime == -1) ? "ELEVATED LOW"
        : (regime == -2) ? "EXTREME LOW"
        : "CALM"
    var regimeTextColor = (regime == 2 || regime == -2) ? highVolColor
        : (regime == 1 || regime == -1) ? midVolColor
        : lowVolColor

    var dynHighStr = dynHigh
    var dynLowStr = dynLow
    var dynExtHighStr = dynExtHigh
    var dynExtLowStr = dynExtLow

    plotTable(
        data=[
            ["Vol & Skew Suite — Perfected", regimeText],
            ["Mode", mode],
            ["Primary", primaryVal],
            ["Z-Score", primaryZ],
            ["Session High", sessionHighVal],
            ["Session Low", sessionLowVal],
            ["RV", rvPct],
            ["IV Proxy", ivComposite],
            ["Spread", spread],
            ["Skew", skewProxy],
            ["Term Structure", termStruct],
            ["PCR", pcr],
            ["Dyn Mild", "±" + dynHighStr],
            ["Dyn Extreme", "±" + dynExtHighStr],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Events", extremeHighCount + extremeLowCount]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=9,
        cellPadding=3
    )
}