Perfected FlowScript
Liquidations Scored
Liquidations Scored V2 — Perfected Edition is indexed as 256_liquidations_scored.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
15.5 KB
Lines
334
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Cascade Long Liq
line 285:5
Trigger
(showShapes && volConfirmedExtBull)
Value
sig3
Deps
showShapes:input, volConfirmedExtBull:var
Cascade Short Liq
line 295:5
Trigger
(showShapes && volConfirmedExtBear)
Value
-sig3
Deps
showShapes:input, volConfirmedExtBear:var
256_liquidations_scored.flowscript
source path: kscripts/perfected/256_liquidations_scored.flowscript · sha256:942059073cad58330a2cad7226d8881b77cca11c5b7ef39074d3c83913fbdd4e
//@version=2
// ============================================================================
// Liquidations Scored V2 — Perfected Edition
// Author: B (@buyanyjeansnecessary) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #liquidations, #zscore, #cascade, #futures, #impact
//
// Z-score normalization of liquidation levels with long/short decomposition,
// impact scoring, cascade detection, and volume-confirmed extreme-event
// markers. Regime-coded fills, shape alerts, and session statistics provide
// a complete liquidation analytics toolkit.
//
// 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. Bian et al. (2023), "Deleveraging Commonality", Journal of Financial
// Economics. Systematic deleveraging creates liquidity commonality;
// fire-sale effects propagate across assets, amplifying cascade severity.
//
// 3. Amberdata Research (2026), "Leverage & Liquidations: The $31B
// Deleveraging". Empirical cascade threshold: liquidation intensity > 5%
// of open interest triggers forced-selling feedback loops.
// https://blog.amberdata.io/leverage-liquidations-the-31b-deleveraging
//
// 4. 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.
//
// 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
//
// 6. Cont (2001), "Empirical Properties of Asset Returns: Stylized Facts
// and Statistical Issues", Quantitative Finance, 1(2), 223–236. Volatility
// clustering and heavy tails in liquidation data justify z-score
// standardisation over raw levels. DOI: https://doi.org/10.1080/713665550
// ============================================================================
define(title="Liquidations Scored V2 — Perfected Edition", 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 sig1 = input(name="sig1", type="number", defaultValue=1.0, label="±1σ Moderate Threshold", constraints={min: 0.5, max: 2.0, step: 0.5}, group="Computation")
var sig2 = input(name="sig2", type="number", defaultValue=2.0, label="±2σ Significant Threshold", constraints={min: 1.0, max: 3.0, step: 0.5}, group="Computation")
var sig3 = input(name="sig3", type="number", defaultValue=3.0, label="±3σ Extreme / Cascade Threshold", constraints={min: 2.0, max: 5.0, step: 0.5}, group="Computation")
var useImpactScore = input(name="useImpactScore", type="boolean", defaultValue=true, label="Use Impact Scoring", group="Computation")
var useVolConfirm = input(name="useVolConfirm", type="boolean", defaultValue=true, label="Use Volume Confirmation", group="Computation")
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume SMA Lookback", constraints={min: 5, max: 100, step: 5}, 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 showDecomp = input(name="showDecomp", type="boolean", defaultValue=true, label="Show Long/Short Decomposition", group="Display")
var showRegime = input(name="showRegime", type="boolean", defaultValue=true, label="Show Regime Table", 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 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 modBullColor = input(name="modBullColor", type="color", defaultValue="#4caf50", label="Moderate Bull Color", group="Colors")
var modBearColor = input(name="modBearColor", type="color", defaultValue="#e57373", label="Moderate Bear Color", group="Colors")
var sigBullColor = input(name="sigBullColor", type="color", defaultValue="#00e676", label="Significant Bull Color", group="Colors")
var sigBearColor = input(name="sigBearColor", type="color", defaultValue="#ff5252", label="Significant Bear Color", group="Colors")
var extBullColor = input(name="extBullColor", type="color", defaultValue="#00ff00", label="Extreme Bull Color", group="Colors")
var extBearColor = input(name="extBearColor", type="color", defaultValue="#ff0000", label="Extreme Bear Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries liqs = source("liquidations", symbol, exchange)
// Guard: halt until liquidation data has loaded to avoid NaN propagation
if (isnan(bars.close[0]) || !isnum(liqs.long) || !isnum(liqs.short)) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Long/short decomposition --
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.2 Impact scoring (ratio of long to short liquidations, normalised) --
// Impact score = |long - short| / (long + short); 0 = balanced, 1 = one-sided.
// One-sided liquidations are higher-impact because they indicate directional
// trapped positioning being forced out.
timeseries impactScore = (totalLiq > 0) ? math.abs(netLiq) / totalLiq : 0
timeseries impactZ = useImpactScore ? impactScore : 1
// -- 3.3 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.4 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.5 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.6 Smoothing (noise reduction per Cont et al. 2014) --
timeseries zSmoothed = ema(zTotal, smoothLen)
timeseries zLongSm = ema(zLong, smoothLen)
timeseries zShortSm = ema(zShort, smoothLen)
// -- 3.7 Volume confirmation --
timeseries volSMA = sma(bars.volume, volLookback)
timeseries volRatio = (volSMA > 0) ? bars.volume / volSMA : 1
var volConfirm = (volRatio > 1.2) ? true : false
// -- 3.8 Regime detection (±1σ / ±2σ / ±3σ bands) --
var regimeExtBull = zSmoothed > sig3
var regimeExtBear = zSmoothed < -sig3
var regimeSigBull = zSmoothed > sig2 && !regimeExtBull
var regimeSigBear = zSmoothed < -sig2 && !regimeExtBear
var regimeModBull = zSmoothed > sig1 && !regimeSigBull && !regimeExtBull
var regimeModBear = zSmoothed < -sig1 && !regimeSigBear && !regimeExtBear
var regimeNeutral = !regimeModBull && !regimeModBear && !regimeSigBull && !regimeSigBear && !regimeExtBull && !regimeExtBear
// -- 3.9 Volume-confirmed extreme signals --
var volConfirmedExtBull = regimeExtBull && volConfirm
var volConfirmedExtBear = regimeExtBear && volConfirm
// -- 3.10 Regime state tracking via static variables --
static lastRegime = 0
static regimeBullBars = 0
static regimeBearBars = 0
static regimeExtBullBars = 0
static regimeExtBearBars = 0
static totalExtBull = 0
static totalExtBear = 0
static totalCascade = 0
if (regimeExtBull) {
regimeExtBullBars = regimeExtBullBars + 1
regimeExtBearBars = 0
regimeBearBars = 0
regimeBullBars = regimeBullBars + 1
lastRegime = 3
totalExtBull = totalExtBull + 1
totalCascade = totalCascade + 1
} else if (regimeExtBear) {
regimeExtBearBars = regimeExtBearBars + 1
regimeExtBullBars = 0
regimeBullBars = 0
regimeBearBars = regimeBearBars + 1
lastRegime = -3
totalExtBear = totalExtBear + 1
totalCascade = totalCascade + 1
} else if (regimeSigBull) {
regimeExtBullBars = 0
regimeExtBearBars = 0
regimeBearBars = 0
regimeBullBars = regimeBullBars + 1
lastRegime = 2
} else if (regimeSigBear) {
regimeExtBullBars = 0
regimeExtBearBars = 0
regimeBullBars = 0
regimeBearBars = regimeBearBars + 1
lastRegime = -2
} else if (regimeModBull) {
regimeExtBullBars = 0
regimeExtBearBars = 0
regimeBearBars = 0
regimeBullBars = regimeBullBars + 1
lastRegime = 1
} else if (regimeModBear) {
regimeExtBullBars = 0
regimeExtBearBars = 0
regimeBullBars = 0
regimeBearBars = regimeBearBars + 1
lastRegime = -1
} else {
regimeExtBullBars = 0
regimeExtBearBars = 0
regimeBullBars = 0
regimeBearBars = 0
lastRegime = 0
}
// -- 3.11 Color index for multi-level regime coloring --
// 0=extBull, 1=sigBull, 2=modBull, 3=neutral, 4=modBear, 5=sigBear, 6=extBear
var colorIdx = regimeExtBull ? 0 : (regimeSigBull ? 1 : (regimeModBull ? 2 : (regimeModBear ? 4 : (regimeSigBear ? 5 : (regimeExtBear ? 6 : 3)))))
// -- 3.12 Zero-line helper --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------
// 4.1 Sigma band reference lines (hline)
if (showBands) {
hline(value=0, color="#ffffff30", width=1)
hline(value=sig1, color=transparency(modBullColor, 60), width=1)
hline(value=-sig1, color=transparency(modBearColor, 60), width=1)
hline(value=sig2, color=transparency(sigBullColor, 60), width=1)
hline(value=-sig2, color=transparency(sigBearColor, 60), width=1)
hline(value=sig3, color=transparency(extBullColor, 60), width=1)
hline(value=-sig3, color=transparency(extBearColor, 60), width=1)
}
// 4.2 Z-score line with regime-coded fill (plotLine + fill)
if (showZ) {
var zColorIdx = zSmoothed >= 0 ? 0 : 1
plotLine(
value=[zSmoothed, zeroLine],
width=2,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=zColorIdx,
fill=showFill,
label=["Liq Z-Score"],
desc=["Total liquidations z-score; extreme values flag cascade conditions"]
)
}
// 4.3 Z-score histogram (plotBar) — multi-level regime coloring
if (showHistogram) {
plotBar(
value=zSmoothed,
colors=[extBullColor, sigBullColor, modBullColor, neutralColor, modBearColor, sigBearColor, extBearColor],
colorIndex=colorIdx,
width=1,
label=["Liq Z Histogram"],
desc=["Liquidation z-score histogram; color-coded by sigma regime"]
)
}
// 4.4 Long/Short decomposed z-scores (optional plotLine)
if (showDecomp && 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 — volume-confirmed >±3σ (plotShape)
if (showShapes && volConfirmedExtBull) {
plotShape(
value=sig3,
shape="triangleup",
colorIndex=extBullColor,
width=3,
label=["Cascade Long Liq"],
desc=["Volume-confirmed total liquidations z-score > +3σ: potential long cascade / perp squeeze risk"]
)
}
if (showShapes && volConfirmedExtBear) {
plotShape(
value=-sig3,
shape="triangledown",
colorIndex=extBearColor,
width=3,
label=["Cascade Short Liq"],
desc=["Volume-confirmed total liquidations z-score < −3σ: potential short cascade / spot dump risk"]
)
}
// 4.6 Regime table (last bar only)
if (showRegime && isLastBar) {
var regimeText = regimeExtBull ? "EXTREME BULL" : (regimeExtBear ? "EXTREME BEAR" : (regimeSigBull ? "SIG BULL" : (regimeSigBear ? "SIG BEAR" : (regimeModBull ? "MOD BULL" : (regimeModBear ? "MOD BEAR" : "NEUTRAL")))))
var regimeTextColor = regimeExtBull ? extBullColor : (regimeExtBear ? extBearColor : (regimeSigBull ? sigBullColor : (regimeSigBear ? sigBearColor : (regimeModBull ? modBullColor : (regimeModBear ? modBearColor : neutralColor)))))
var volConfirmText = volConfirm ? "CONFIRMED" : "UNCONFIRMED"
var impactText = useImpactScore ? (impactScore[0] * 100) + "%" : "N/A"
plotTable(
data=[
["Liquidations Scored V2", regimeText],
["Z-Score", zSmoothed[0]],
["Impact Score", impactText],
["Volume Ratio", volRatio[0]],
["Volume", volConfirmText],
["Total Cascades", totalCascade]
],
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
)
}