MM Flow
FlowScripts

Perfected FlowScript

Z-Score Heatmap • [Leviathan]

Z-Score Heatmap [Leviathan] — Perfected is indexed as 024_z_score_heatmap_leviathan.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.0 KB

Lines

686

Native Signal Candidates

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

16/16 guarded

Price Extreme High

line 606:17

Trigger

(showShapes) && ((showPrice) && !isnan((retZ)) && !isnan((retZ[1]))) && ((retZ) >= highThresh && (retZ[1]) < highThresh)

Value

(retZ)

Deps

highThresh:input, retZ:var, showPrice:input, showShapes:input

Volume Extreme High

line 606:17

Trigger

(showShapes) && ((showVolume) && !isnan((volZ)) && !isnan((volZ[1]))) && ((volZ) >= highThresh && (volZ[1]) < highThresh)

Value

(volZ)

Deps

highThresh:input, showShapes:input, showVolume:input, volZ:var

Delta Extreme High

line 606:17

Trigger

(showShapes) && ((showDelta) && !isnan((deltaZ)) && !isnan((deltaZ[1]))) && ((deltaZ) >= highThresh && (deltaZ[1]) < highThresh)

Value

(deltaZ)

Deps

deltaZ:var, highThresh:input, showDelta:input, showShapes:input

CVD Extreme High

line 606:17

Trigger

(showShapes) && ((showCvd) && !isnan((cvdZ)) && !isnan((cvdZ[1]))) && ((cvdZ) >= highThresh && (cvdZ[1]) < highThresh)

Value

(cvdZ)

Deps

cvdZ:var, highThresh:input, showCvd:input, showShapes:input

OI Extreme High

line 606:17

Trigger

(showShapes) && ((showOi) && !isnan((oiZ)) && !isnan((oiZ[1]))) && ((oiZ) >= highThresh && (oiZ[1]) < highThresh)

Value

(oiZ)

Deps

highThresh:input, oiZ:var, showOi:input, showShapes:input

OI Δ Extreme High

line 606:17

Trigger

(showShapes) && ((showOiDelta) && !isnan((oidZ)) && !isnan((oidZ[1]))) && ((oidZ) >= highThresh && (oidZ[1]) < highThresh)

Value

(oidZ)

Deps

highThresh:input, oidZ:var, showOiDelta:input, showShapes:input

Funding Extreme High

line 606:17

Trigger

(showShapes) && ((showFunding) && !isnan((fundingZ)) && !isnan((fundingZ[1]))) && ((fundingZ) >= highThresh && (fundingZ[1]) < highThresh)

Value

(fundingZ)

Deps

fundingZ:var, highThresh:input, showFunding:input, showShapes:input

Price Extreme Low

line 617:17

Trigger

(showShapes) && ((showPrice) && !isnan((retZ)) && !isnan((retZ[1]))) && ((retZ) <= lowThresh && (retZ[1]) > lowThresh)

Value

(retZ)

Deps

lowThresh:input, retZ:var, showPrice:input, showShapes:input

Volume Extreme Low

line 617:17

Trigger

(showShapes) && ((showVolume) && !isnan((volZ)) && !isnan((volZ[1]))) && ((volZ) <= lowThresh && (volZ[1]) > lowThresh)

Value

(volZ)

Deps

lowThresh:input, showShapes:input, showVolume:input, volZ:var

Delta Extreme Low

line 617:17

Trigger

(showShapes) && ((showDelta) && !isnan((deltaZ)) && !isnan((deltaZ[1]))) && ((deltaZ) <= lowThresh && (deltaZ[1]) > lowThresh)

Value

(deltaZ)

Deps

deltaZ:var, lowThresh:input, showDelta:input, showShapes:input

CVD Extreme Low

line 617:17

Trigger

(showShapes) && ((showCvd) && !isnan((cvdZ)) && !isnan((cvdZ[1]))) && ((cvdZ) <= lowThresh && (cvdZ[1]) > lowThresh)

Value

(cvdZ)

Deps

cvdZ:var, lowThresh:input, showCvd:input, showShapes:input

OI Extreme Low

line 617:17

Trigger

(showShapes) && ((showOi) && !isnan((oiZ)) && !isnan((oiZ[1]))) && ((oiZ) <= lowThresh && (oiZ[1]) > lowThresh)

Value

(oiZ)

Deps

lowThresh:input, oiZ:var, showOi:input, showShapes:input

OI Δ Extreme Low

line 617:17

Trigger

(showShapes) && ((showOiDelta) && !isnan((oidZ)) && !isnan((oidZ[1]))) && ((oidZ) <= lowThresh && (oidZ[1]) > lowThresh)

Value

(oidZ)

Deps

lowThresh:input, oidZ:var, showOiDelta:input, showShapes:input

Funding Extreme Low

line 617:17

Trigger

(showShapes) && ((showFunding) && !isnan((fundingZ)) && !isnan((fundingZ[1]))) && ((fundingZ) <= lowThresh && (fundingZ[1]) > lowThresh)

Value

(fundingZ)

Deps

fundingZ:var, lowThresh:input, showFunding:input, showShapes:input

Composite Extreme High

line 632:13

Trigger

(showShapes) && (!isnan(compositeZsmooth) && !isnan(compositeZsmooth[1])) && (compositeZsmooth >= highThresh && compositeZsmooth[1] < highThresh)

Value

compositeZsmooth

Deps

compositeZsmooth:var, highThresh:input, showShapes:input

Composite Extreme Low

line 642:13

Trigger

(showShapes) && (!isnan(compositeZsmooth) && !isnan(compositeZsmooth[1])) && (compositeZsmooth <= lowThresh && compositeZsmooth[1] > lowThresh)

Value

compositeZsmooth

Deps

compositeZsmooth:var, lowThresh:input, showShapes:input

024_z_score_heatmap_leviathan.flowscript

source path: kscripts/perfected/024_z_score_heatmap_leviathan.flowscript · sha256:de5a3239bb416a441951ede33f87944bcff97df0dcb9548d7c3879dc0b69d3bb

hash verified
//@version=2
// ============================================================================
// Z-Score Heatmap [Leviathan] — Perfected Edition
// Author: Leviathan (@Leviathan) | Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, SPECIALIZED, #zscore, #volume, #openinterest, #cvd, #leviathan
//
// Multi-metric z-score heatmap displaying standardized deviations for Price,
// Volume, Volume Delta, CVD, Open Interest, OI Delta, and Funding Rate.
// Each metric is normalized over a rolling window and color-coded by statistical
// significance so the user can see at a glance which dimensions are stretched
// vs. typical. Includes a composite alignment score, regime detection, session
// tracking, and extreme-event shape alerts.
//
// FORMULA FOUNDATION:
// 1. Z-Score: z_t = (x_t − μ) / σ  over rolling lookback window
//    per Zhao & Palomar (2018), mean-reversion signal triggers.
// 2. Composite Alignment Score: Σ(z_i) / N  where N = number of active metrics.
//    Per Baker & Wurgler (2006), composite indices outperform single indicators.
// 3. Multi-Indicator Confirmation Stack: agreement across ≥ 3 metrics at ±2σ
//    flags high-probability regime extremes per QuantOracle (2026).
// 4. Heatmap Regime Detection: Bullish (≥ 3 metrics above +1σ), Bearish
//    (≥ 3 metrics below −1σ), Neutral (mixed) per Rakovská (2021).
//
// RESEARCH BASIS:
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE TSP. z̄_t = (z_t − μ_z) / σ_z; entry thresholds at ±1σ or ±2σ.
//  • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//    Stock Returns", JF 61(4), 1645–1680. Composite sentiment index from
//    multiple proxies via PCA; each heatmap row is a distinct market-state proxy.
//  • QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI: Which Mean
//    Reversion Indicator Should You Use?" Multi-indicator confirmation stacks
//    (price touching band AND RSI < 30 AND Z-score < −2) improve signal quality.
//  • Rakovská (2021), "Composite Survey Sentiment as a Predictor of Future
//    Market Returns", IREF 72, 127–142. Composite indicators outperform single
//    indicators; macro-orthogonalized multi-proxy construction methodology.
//  • Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1), 47–88.
//    OFI = Σ(E_i × ΔP_i); linear price-impact model validates multi-metric
//    orderflow approach underpinning CVD and Delta z-scores.
//  • Lillo & Farmer (2004), SNDE 8(3), 1–35. Order flow long-memory properties
//    justify cumulative measures (CVD) as more informative than per-bar readings.
// ============================================================================

define(
    title="Z-Score Heatmap [Leviathan] — Perfected",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// 1. USER INPUTS — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Z-Score Configuration ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score"
)
var useAbsZ = input(
    name="useAbsZ",
    type="boolean",
    defaultValue=false,
    label="Use Absolute Z-Score (flip negative to positive)",
    group="Z-Score"
)

// --- Thresholds ---
var highThresh = input(
    name="highThresh",
    type="number",
    defaultValue=2.0,
    label="High Z-Score Threshold (σ)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)
var lowThresh = input(
    name="lowThresh",
    type="number",
    defaultValue=-2.0,
    label="Low Z-Score Threshold (σ)",
    constraints={min: -5.0, max: -0.5, step: 0.1},
    group="Thresholds"
)
var neutralBand = input(
    name="neutralBand",
    type="number",
    defaultValue=0.5,
    label="Neutral Band (±σ)",
    constraints={min: 0.0, max: 2.0, step: 0.1},
    group="Thresholds"
)

// --- Display Toggles ---
var showPrice = input(
    name="showPrice",
    type="boolean",
    defaultValue=true,
    label="Show Price Z-Score",
    group="Display"
)
var showVolume = input(
    name="showVolume",
    type="boolean",
    defaultValue=true,
    label="Show Volume Z-Score",
    group="Display"
)
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Volume Delta Z-Score",
    group="Display"
)
var showCvd = input(
    name="showCvd",
    type="boolean",
    defaultValue=true,
    label="Show CVD Z-Score",
    group="Display"
)
var showOi = input(
    name="showOi",
    type="boolean",
    defaultValue=true,
    label="Show Open Interest Z-Score",
    group="Display"
)
var showOiDelta = input(
    name="showOiDelta",
    type="boolean",
    defaultValue=true,
    label="Show OI Delta Z-Score",
    group="Display"
)
var showFunding = input(
    name="showFunding",
    type="boolean",
    defaultValue=true,
    label="Show Funding Rate Z-Score",
    group="Display"
)
var showComposite = input(
    name="showComposite",
    type="boolean",
    defaultValue=true,
    label="Show Composite Alignment Score",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme-Event Shapes",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Guide Lines",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish (High Z) Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish (Low Z) Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#ffca28",
    label="Extreme Event Color",
    group="Colors"
)
var compositeColor = input(
    name="compositeColor",
    type="color",
    defaultValue="#42a5f5",
    label="Composite Line Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries funding = source("funding_rate", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded (Zhao & Palomar 2018 data-integrity)
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// 3. BASE METRIC COMPUTATION
// ------------------------------------------------------------------------------
// Price return
var ret = px - px[1]

// Volume delta (buy − sell) with Lee-Ready (1991) fallback tick test
var buyVol = isnum(taker.buy) ? taker.buy : (px > bars.open ? bars.volume : 0)
var sellVol = isnum(taker.sell) ? taker.sell : (px <= bars.open ? bars.volume : 0)
var delta = buyVol - sellVol
var cvd = sum(delta, lookback)

// OI and OI delta
var oiVal = oi.close
var oiChange = oiVal - oiVal[1]

// Funding rate
var fundingVal = isnum(funding.value) ? funding.value : 0

// ------------------------------------------------------------------------------
// 4. Z-SCORE COMPUTATION WITH ZERO-DIVISION GUARDS
// ------------------------------------------------------------------------------
// Helper: compute smoothed z-score of a series over lookback bars.
// z = (x − μ) / σ; then EMA-smoothed for noise reduction.

var retMean = sma(ret, lookback)
var retStd = stdev(ret, lookback)
var retZ = retStd > 0 ? ema((ret - retMean) / retStd, smoothLen) : 0
retZ = useAbsZ ? math.abs(retZ) : retZ

var volMean = sma(bars.volume, lookback)
var volStd = stdev(bars.volume, lookback)
var volZ = volStd > 0 ? ema((bars.volume - volMean) / volStd, smoothLen) : 0
volZ = useAbsZ ? math.abs(volZ) : volZ

var deltaMean = sma(delta, lookback)
var deltaStd = stdev(delta, lookback)
var deltaZ = deltaStd > 0 ? ema((delta - deltaMean) / deltaStd, smoothLen) : 0
deltaZ = useAbsZ ? math.abs(deltaZ) : deltaZ

var cvdMean = sma(cvd, lookback)
var cvdStd = stdev(cvd, lookback)
var cvdZ = cvdStd > 0 ? ema((cvd - cvdMean) / cvdStd, smoothLen) : 0
cvdZ = useAbsZ ? math.abs(cvdZ) : cvdZ

var oiMean = sma(oiVal, lookback)
var oiStd = stdev(oiVal, lookback)
var oiZ = oiStd > 0 ? ema((oiVal - oiMean) / oiStd, smoothLen) : 0
oiZ = useAbsZ ? math.abs(oiZ) : oiZ

var oidMean = sma(oiChange, lookback)
var oidStd = stdev(oiChange, lookback)
var oidZ = oidStd > 0 ? ema((oiChange - oidMean) / oidStd, smoothLen) : 0
oidZ = useAbsZ ? math.abs(oidZ) : oidZ

var fundingMean = sma(fundingVal, lookback)
var fundingStd = stdev(fundingVal, lookback)
var fundingZ = fundingStd > 0 ? ema((fundingVal - fundingMean) / fundingStd, smoothLen) : 0
fundingZ = useAbsZ ? math.abs(fundingZ) : fundingZ

// ------------------------------------------------------------------------------
// 5. COMPOSITE ALIGNMENT SCORE
// ------------------------------------------------------------------------------
// Per Baker & Wurgler (2006), composite indices outperform single indicators.
// We compute the average of all active z-scores, giving equal weight to each
// metric (proxy) in the composite sentiment index.

var activeCount = 0
var compositeSum = 0.0

if (showPrice) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + retZ
}
if (showVolume) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + volZ
}
if (showDelta) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + deltaZ
}
if (showCvd) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + cvdZ
}
if (showOi) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + oiZ
}
if (showOiDelta) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + oidZ
}
if (showFunding) {
    activeCount = activeCount + 1
    compositeSum = compositeSum + fundingZ
}

var compositeZ = activeCount > 0 ? compositeSum / activeCount : 0.0
var compositeZsmooth = ema(compositeZ, smoothLen)

// ------------------------------------------------------------------------------
// 6. REGIME DETECTION (per Rakovská 2021 composite methodology)
// ------------------------------------------------------------------------------
// Bullish regime: ≥ 3 metrics above +neutralBand (positive alignment)
// Bearish regime: ≥ 3 metrics below −neutralBand (negative alignment)
// Neutral regime: mixed signals (chop zone)

var bullCount = 0
var bearCount = 0
var neutralCount = 0

var checkMetrics = [retZ, volZ, deltaZ, cvdZ, oiZ, oidZ, fundingZ]
var checkFlags = [showPrice, showVolume, showDelta, showCvd, showOi, showOiDelta, showFunding]

for (i = 0; i < 7; i = i + 1) {
    if (checkFlags[i]) {
        if (checkMetrics[i] >= neutralBand) {
            bullCount = bullCount + 1
        } else if (checkMetrics[i] <= -neutralBand) {
            bearCount = bearCount + 1
        } else {
            neutralCount = neutralCount + 1
        }
    }
}

var regimeBull = bullCount >= 3
var regimeBear = bearCount >= 3
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// ------------------------------------------------------------------------------
// 7. STATIC SESSION TRACKING
// ------------------------------------------------------------------------------
// Stateful computation for anchoring, session tracking, and extreme-event counts.
// Tracks session extremes, composite highs/lows, and extreme-event counts per
// Zhao & Palomar (2018) statistical significance framework.

static sessionHighComposite = -999999.0
static sessionLowComposite = 999999.0
static extremeHighCount = 0
static extremeLowCount = 0
static extremeEventCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (compositeZ > sessionHighComposite) {
        sessionHighComposite = compositeZ
    }
    if (compositeZ < sessionLowComposite) {
        sessionLowComposite = compositeZ
    }

    // Count extreme events across all metrics (z > 2 or z < -2)
    for (i = 0; i < 7; i = i + 1) {
        if (checkFlags[i] && !isnan(checkMetrics[i])) {
            if (checkMetrics[i] >= highThresh) {
                extremeHighCount = extremeHighCount + 1
            } else if (checkMetrics[i] <= lowThresh) {
                extremeLowCount = extremeLowCount + 1
            }
        }
    }

    // Count composite extreme events
    if (!isnan(compositeZ)) {
        if (compositeZ >= highThresh || compositeZ <= lowThresh) {
            extremeEventCount = extremeEventCount + 1
        }
    }
}

// ------------------------------------------------------------------------------
// 8. PLOTTING — Multi-Metric Dashboard with Heatmap Color Coding
// ------------------------------------------------------------------------------

// --- Guide lines ---
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
    hline(value=highThresh, color=transparency(bullColor, 40), width=1)
    hline(value=lowThresh, color=transparency(bearColor, 40), width=1)
    hline(value=neutralBand, color=transparency(neutralColor, 30), width=1)
    hline(value=-neutralBand, color=transparency(neutralColor, 30), width=1)
}

// --- Color index helper: 0 = bull (high), 1 = bear (low), 2 = neutral ---
// Price Z-Score
if (showPrice) {
    var retColorIdx = retZ >= neutralBand ? 0 : (retZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=retZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=retColorIdx,
        width=1,
        label=["Price Z"],
        desc=["Bar return z-score: price momentum in σ units (green=high, red=low)"]
    )
    plotLine(
        value=retZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=retColorIdx,
        label=["Price Z Line"],
        desc=["Smoothed price return z-score line"]
    )
}

// Volume Z-Score
if (showVolume) {
    var volColorIdx = volZ >= neutralBand ? 0 : (volZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=volZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=volColorIdx,
        width=1,
        label=["Volume Z"],
        desc=["Volume z-score: statistical significance of current volume vs. lookback (green=high, red=low)"]
    )
    plotLine(
        value=volZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=volColorIdx,
        label=["Volume Z Line"],
        desc=["Smoothed volume z-score line"]
    )
}

// Volume Delta Z-Score
if (showDelta) {
    var deltaColorIdx = deltaZ >= neutralBand ? 0 : (deltaZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=deltaZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=deltaColorIdx,
        width=1,
        label=["Delta Z"],
        desc=["Volume delta z-score: buy/sell imbalance in σ units (green=buy-heavy, red=sell-heavy)"]
    )
    plotLine(
        value=deltaZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=deltaColorIdx,
        label=["Delta Z Line"],
        desc=["Smoothed volume delta z-score line"]
    )
}

// CVD Z-Score
if (showCvd) {
    var cvdColorIdx = cvdZ >= neutralBand ? 0 : (cvdZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=cvdZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=cvdColorIdx,
        width=1,
        label=["CVD Z"],
        desc=["Cumulative volume delta z-score: sustained orderflow pressure in σ units"]
    )
    plotLine(
        value=cvdZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=cvdColorIdx,
        label=["CVD Z Line"],
        desc=["Smoothed CVD z-score line"]
    )
}

// OI Z-Score
if (showOi) {
    var oiColorIdx = oiZ >= neutralBand ? 0 : (oiZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=oiZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=oiColorIdx,
        width=1,
        label=["OI Z"],
        desc=["Open interest level z-score: OI positioning in σ units (green=high OI, red=low OI)"]
    )
    plotLine(
        value=oiZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=oiColorIdx,
        label=["OI Z Line"],
        desc=["Smoothed open interest z-score line"]
    )
}

// OI Delta Z-Score
if (showOiDelta) {
    var oidColorIdx = oidZ >= neutralBand ? 0 : (oidZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=oidZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=oidColorIdx,
        width=1,
        label=["OID Z"],
        desc=["Open interest delta z-score: rate of OI change in σ units (green=OI building, red=OI unwinding)"]
    )
    plotLine(
        value=oidZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=oidColorIdx,
        label=["OID Z Line"],
        desc=["Smoothed OI delta z-score line"]
    )
}

// Funding Z-Score
if (showFunding) {
    var fundingColorIdx = fundingZ >= neutralBand ? 0 : (fundingZ <= -neutralBand ? 1 : 2)
    plotBar(
        value=fundingZ,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=fundingColorIdx,
        width=1,
        label=["Funding Z"],
        desc=["Funding rate z-score: cost of carry in σ units (green=expensive longs, red=expensive shorts)"]
    )
    plotLine(
        value=fundingZ,
        width=1,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
        colorIndex=fundingColorIdx,
        label=["Funding Z Line"],
        desc=["Smoothed funding rate z-score line"]
    )
}

// --- Composite Alignment Score (regime-colored with fill) ---
if (showComposite) {
    plotLine(
        value=compositeZsmooth,
        width=2,
        colors=[regimeColor],
        label=["Composite Z"],
        desc=["Composite alignment score: average of all active z-scores (bull/bear/neutral regime-colored)"],
        fill=true
    )

    // Zero-line fill area for composite
    plotLine(
        value=[compositeZsmooth, 0],
        width=1,
        colors=[transparency(compositeColor, 15), transparency(compositeColor, 15)],
        colorIndex=0,
        fill=true,
        label=["Composite Z", "Zero"],
        desc=["Fill between composite alignment score and zero line"]
    )
}

// ------------------------------------------------------------------------------
// 9. EXTREME EVENT SHAPES
// ------------------------------------------------------------------------------
// Per QuantOracle (2026), multi-indicator confirmation at ±2σ flags
// high-probability regime extremes. We plot shapes when any metric crosses
// the high/low threshold.

if (showShapes) {
    var metrics = [retZ, volZ, deltaZ, cvdZ, oiZ, oidZ, fundingZ]
    var flags = [showPrice, showVolume, showDelta, showCvd, showOi, showOiDelta, showFunding]
    var labels = ["Price", "Volume", "Delta", "CVD", "OI", "OI Δ", "Funding"]

    for (i = 0; i < 7; i = i + 1) {
        if (flags[i] && !isnan(metrics[i]) && !isnan(metrics[i][1])) {
            // Extreme high cross
            if (metrics[i] >= highThresh && metrics[i][1] < highThresh) {
                plotShape(
                    value=metrics[i],
                    shape="triangleup",
                    color=extremeColor,
                    width=2,
                    label=[labels[i] + " Extreme High"],
                    desc=[labels[i] + " z-score crossed above +" + highThresh + "σ — extreme positive deviation"]
                )
            }
            // Extreme low cross
            if (metrics[i] <= lowThresh && metrics[i][1] > lowThresh) {
                plotShape(
                    value=metrics[i],
                    shape="triangledown",
                    color=extremeColor,
                    width=2,
                    label=[labels[i] + " Extreme Low"],
                    desc=[labels[i] + " z-score crossed below " + lowThresh + "σ — extreme negative deviation"]
                )
            }
        }
    }

    // Composite extreme shapes
    if (!isnan(compositeZsmooth) && !isnan(compositeZsmooth[1])) {
        if (compositeZsmooth >= highThresh && compositeZsmooth[1] < highThresh) {
            plotShape(
                value=compositeZsmooth,
                shape="diamond",
                color=extremeColor,
                width=3,
                label=["Composite Extreme High"],
                desc=["Composite alignment score crossed above +" + highThresh + "σ — broad market extreme"]
            )
        }
        if (compositeZsmooth <= lowThresh && compositeZsmooth[1] > lowThresh) {
            plotShape(
                value=compositeZsmooth,
                shape="diamond",
                color=extremeColor,
                width=3,
                label=["Composite Extreme Low"],
                desc=["Composite alignment score crossed below " + lowThresh + "σ — broad market extreme"]
            )
        }
    }
}

// ------------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH ALIGNMENT" : (regimeBear ? "BEARISH ALIGNMENT" : "NEUTRAL / MIXED")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Z-Score Heatmap — Perfected", regimeText],
            ["Composite Z", compositeZsmooth[0]],
            ["Active Metrics", activeCount],
            ["Bullish Metrics", bullCount],
            ["Bearish Metrics", bearCount],
            ["Session High Z", sessionHighComposite],
            ["Session Low Z", sessionLowComposite],
            ["Extreme High Events", extremeHighCount],
            ["Extreme Low Events", 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=10,
        cellPadding=4
    )
}