MM Flow
FlowScripts

Perfected FlowScript

Liquidations Z-score

Liquidations Z-Score V2 is indexed as 023_liquidations_z_score.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

10.9 KB

Lines

237

Native Signal Candidates

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

2/2 guarded

Extreme Long Liq

line 212:5

Trigger

(showShapes && bullExtreme)

Value

zSmoothed

Deps

bullExtreme:var, showShapes:input

Extreme Short Liq

line 222:5

Trigger

(showShapes && bearExtreme)

Value

zSmoothed

Deps

bearExtreme:var, showShapes:input

023_liquidations_z_score.flowscript

source path: kscripts/perfected/023_liquidations_z_score.flowscript · sha256:edbbfb46f7add7912b176482553aea9c2e3034345962a746eba6a75f979e3d3d

hash verified
//@version=2

// ============================================================================
// Liquidations Z-Score V2 — Production-Quality Liquidation Cascade Detector
// Author: abetrade (@abetrade) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #liquidations, #zscore, #cascade, #futures
//
// Z-score normalization of liquidation levels over a rolling window,
// with long/short decomposition, ±1/2/3σ bands, regime-coded fill,
// and extreme-event shape markers.  Extreme positive values flag cascade-risk
// conditions in long liquidations; extreme negative flags short-side cascades.
//
// Academic foundation (exact papers & formulas):
//  1. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//     Review of Financial Studies, 22(6), 2201–2238.
//     [Formula] Liquidity spiral: market liquidity ↔ funding liquidity
//     reinforcement.  Small shocks amplify into systemic crises when margin
//     thresholds are breached.  DOI: https://doi.org/10.1093/rfs/hhn098
//
//  2. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     [Formula] z̄_t = (z_t − μ_z) / σ_z; entry/exit thresholds at Δ = d × σ_z.
//     Directly underpins the rolling z-score and band-based signal design.
//
//  3. Amberdata Research (2026), "Leverage & Liquidations: The $31B
//     Deleveraging".  Empirical cascade threshold: liquidation intensity > 5%
//     of open interest triggers forced-selling feedback loops.  October 2025
//     reached 4.82% intensity, liquidating $2.3B in a single day.
//     https://blog.amberdata.io/leverage-liquidations-the-31b-deleveraging
//
//  4. Bian et al. (2023), "Deleveraging Commonality", Journal of Financial
//     Economics.  Systematic deleveraging creates liquidity commonality;
//     fire-sale effects propagate across assets, amplifying cascade severity.
//
//  5. Adrian & Shin (2010), "Liquidity and Leverage", Journal of Financial
//     Intermediation, 19(3), 418–437.  Leverage is procyclical—expands in
//     booms, collapses in busts, amplifying cycle amplitude.
//     DOI: https://doi.org/10.1016/j.jfi.2008.12.002
// ============================================================================

define(title="Liquidations Z-Score V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Sources")
var exchange = input(name="exchange", type="string", defaultValue="BINANCE_FUTURES", label="Exchange", group="Data Sources")

// -- Computation --
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Extreme Regime Threshold (σ)", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")
var useLongShort = input(name="useLongShort", type="boolean", defaultValue=true, label="Decompose Long vs. Short", group="Computation")

// -- Display --
var showZ = input(name="showZ", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show ±1/2/3σ Bands", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showSessionStats = input(name="showSessionStats", type="boolean", defaultValue=true, label="Show Session Stats", group="Display")

// -- Colors --
var longColor = input(name="longColor", type="color", defaultValue="#00c853", label="Long Liquidation Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#d50000", label="Short Liquidation Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Below Average Z", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Above Average Z", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff9100", label="Extreme Event Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries liqs = source("liquidations", symbol, exchange)

// Guard: halt until liquidation data has loaded to avoid NaN propagation
if (!isnum(liqs.long) || !isnum(liqs.short)) {
    return
}

timeseries longLiq = isnum(liqs.long) ? liqs.long : 0
timeseries shortLiq = isnum(liqs.short) ? liqs.short : 0
timeseries totalLiq = longLiq + shortLiq
timeseries netLiq = longLiq - shortLiq

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Total liquidation z-score (primary signal) --
// Z_t = (Liq_t − μ_t) / σ_t, where μ_t = SMA(Liq, W), σ_t = StDev(Liq, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
timeseries meanLiq = sma(totalLiq, zWindow)
timeseries stdLiq = stdev(totalLiq, zWindow)
timeseries zTotal = (stdLiq > 0) ? (totalLiq - meanLiq) / stdLiq : 0

// -- 3.2 Long/short z-scores (decomposed view) --
timeseries meanLong = sma(longLiq, zWindow)
timeseries stdLong = stdev(longLiq, zWindow)
timeseries zLong = (stdLong > 0) ? (longLiq - meanLong) / stdLong : 0

timeseries meanShort = sma(shortLiq, zWindow)
timeseries stdShort = stdev(shortLiq, zWindow)
timeseries zShort = (stdShort > 0) ? (shortLiq - meanShort) / stdShort : 0

// -- 3.3 Net liquidation z-score (directional bias) --
timeseries meanNet = sma(netLiq, zWindow)
timeseries stdNet = stdev(netLiq, zWindow)
timeseries zNet = (stdNet > 0) ? (netLiq - meanNet) / stdNet : 0

// -- 3.4 Smoothing (noise reduction per Cont et al. 2014) --
timeseries zSmoothed = ema(zTotal, smoothLen)
timeseries zLongSm = ema(zLong, smoothLen)
timeseries zShortSm = ema(zShort, smoothLen)

// -- 3.5 Regime detection (configurable thresholds, no magic numbers) --
var bullExtreme = zSmoothed > divThreshold
var bearExtreme = zSmoothed < -divThreshold
var extremeEvent = bullExtreme || bearExtreme

// -- 3.6 Session tracking via static variables --
// Tracks session extremes, event counts, and consecutive extreme bars.
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeCount = 0
static lastBarIdx = 0
static maxConsecutiveExtreme = 0
static currentConsecutiveExtreme = 0

var currentBarIdx = bar_index[0]

if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
    // New bar — update session tracking
    lastBarIdx = currentBarIdx

    if (zSmoothed > sessionHighZ) {
        sessionHighZ = zSmoothed
    }
    if (zSmoothed < sessionLowZ) {
        sessionLowZ = zSmoothed
    }

    if (extremeEvent) {
        extremeCount = extremeCount + 1
        currentConsecutiveExtreme = currentConsecutiveExtreme + 1
        if (currentConsecutiveExtreme > maxConsecutiveExtreme) {
            maxConsecutiveExtreme = currentConsecutiveExtreme
        }
    } else {
        currentConsecutiveExtreme = 0
    }
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// Zero-line helper for fill areas
timeseries zeroLine = 0

// 4.1 ±1/2/3σ horizontal reference lines
hline(value=0, color="#ffffff30", width=1)
if (showBands) {
    hline(value=3, color="#ffffff15", width=1)
    hline(value=-3, color="#ffffff15", width=1)
    hline(value=2, color="#ffffff20", width=1)
    hline(value=-2, color="#ffffff20", width=1)
    hline(value=1, color="#ffffff10", width=1)
    hline(value=-1, color="#ffffff10", width=1)
}

// 4.2 Z-score line with regime-coded fill (plotLine + fill)
// colorIndex maps: 0 = below average (bull/bullColor), 1 = above average (bear/bearColor)
// When extreme, override to extreme color.
var zColorIdx = zSmoothed >= 0 ? 1 : 0
var zLineColors = [bullColor, bearColor]
if (showZ) {
    plotLine(
        value=([zSmoothed, zeroLine]),
        width=2,
        colors=zLineColors,
        colorIndex=zColorIdx,
        label=["Liq Z-Score"],
        desc=["Total liquidations z-score; extreme values flag cascade conditions"],
        fill=showFill
    )
}

// 4.3 Z-score histogram (plotBar) — color-coded by direction and extreme
if (showHistogram) {
    var histColors = extremeEvent ? [extremeColor, extremeColor] : [bullColor, bearColor]
    plotBar(
        value=zSmoothed,
        colors=histColors,
        width=1,
        label=["Liq Z Histogram"],
        desc=["Liquidation z-score as histogram bars; orange = extreme regime"]
    )
}

// 4.4 Long/Short decomposed z-scores (optional plotLine)
if (useLongShort && showZ) {
    plotLine(value=zLongSm, width=1, colors=[longColor], label=["Long Liq Z"], desc=["Long liquidation z-score; positive = elevated long liquidations"])
    plotLine(value=zShortSm, width=1, colors=[shortColor], label=["Short Liq Z"], desc=["Short liquidation z-score; positive = elevated short liquidations"])
}

// 4.5 Extreme event shapes — >+2σ or <-2σ (plotShape)
// Shape markers fire when z-score crosses into extreme regime.
if (showShapes && bullExtreme) {
    plotShape(
        value=zSmoothed,
        shape="triangleup",
        color=extremeColor,
        width=3,
        label=["Extreme Long Liq"],
        desc=["Total liquidations z-score > +2σ: potential long cascade / perp squeeze risk"]
    )
}
if (showShapes && bearExtreme) {
    plotShape(
        value=zSmoothed,
        shape="triangledown",
        color=extremeColor,
        width=3,
        label=["Extreme Short Liq"],
        desc=["Total liquidations z-score < -2σ: potential short cascade / spot dump risk"]
    )
}

// 4.6 Band fill areas (fill between z-score and threshold lines)
if (showFill && showBands) {
    // Fill between z-score and ±1σ when inside normal range
    plotLine(value=([zSmoothed, zeroLine]), width=1, colors=[opacity(bullColor, 20)], label=["Z Fill"], desc=["Z-score fill area"], fill=true)
}