Perfected FlowScript
Liquidation Bubbles [BackQuant]
Liquidation Bubbles [BackQuant] Perfected is indexed as 014_liquidation_bubbles_backquant.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
onchart
Axis
false
Size
15.1 KB
Lines
334
Native Signal Candidates
9 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Total Liq
line 189:5
Trigger
(mode == "Total Liquidations" && totalDisplay)
Value
plotY
Deps
mode:input, totalDisplay:var
Liq Delta
line 208:5
Trigger
(mode == "Liquidation Delta" && deltaDisplay)
Value
plotY
Deps
deltaDisplay:var, mode:input
Long Liq
line 228:9
Trigger
(mode == "Buy & Sell Liquidations") && (longDisplay)
Value
bars.low
Deps
longDisplay:var, mode:input
Short Liq
line 244:9
Trigger
(mode == "Buy & Sell Liquidations") && (shortDisplay)
Value
bars.high
Deps
mode:input, shortDisplay:var
Liq Cluster
line 263:9
Trigger
(showClusters) && (mode == "Total Liquidations" && totalDisplay && math.abs(totalZ[1]) >= threshold)
Value
bars.high
Deps
math:builtin, mode:input, showClusters:input, threshold:input, totalDisplay:var, totalZ:timeseries
Delta Cluster
line 275:13
Trigger
(showClusters) && (mode == "Liquidation Delta" && deltaDisplay && math.abs(deltaZ[1]) >= threshold) && (sameDir)
Value
bars.high
Deps
deltaDisplay:var, deltaZ:timeseries, math:builtin, mode:input, sameDir:var, showClusters:input, threshold:input
Long Cluster
line 287:13
Trigger
(showClusters) && (mode == "Buy & Sell Liquidations") && (longDisplay && math.abs(longZ[1]) >= threshold)
Value
bars.low
Deps
longDisplay:var, longZ:timeseries, math:builtin, mode:input, showClusters:input, threshold:input
Short Cluster
line 297:13
Trigger
(showClusters) && (mode == "Buy & Sell Liquidations") && (shortDisplay && math.abs(shortZ[1]) >= threshold)
Value
bars.high
Deps
math:builtin, mode:input, shortDisplay:var, shortZ:timeseries, showClusters:input, threshold:input
CASCADE
line 313:5
Trigger
(showCascade && cascadeEvent)
Value
bars.high
Deps
cascadeEvent:var, showCascade:input
014_liquidation_bubbles_backquant.flowscript
source path: kscripts/perfected/014_liquidation_bubbles_backquant.flowscript · sha256:5eb859322b59d81df7358bd28c1f80e7e496e41273c8e9e8925c8136db6e2657
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Liquidation Bubbles — Z-Score Scaled Liquidation Event Visualization
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: SPECIALIZED, FLOW, ADVANCED, #liquidations, #bubbles, #zscore, #cascade
//
// On-chart bubbles surfacing liquidation activity in real time. Bubble size and
// opacity scale by z-score over a rolling window, with three display modes
// (total liquidations, liquidation delta, buy/sell split). Includes configurable
// thresholds for extreme event filtering, shape markers for liquidation clusters,
// and cascade detection based on 5% of OI intensity (Amberdata 2026).
//
// Research papers underpinning this design:
// - Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
// (Rev. Financial Studies, 22(6)): liquidity spiral model explains why
// liquidation events cluster and cascade. Margin threshold breaches trigger
// non-linear price moves as forced selling begets more forced selling.
// - Bian et al. (2023), "Deleveraging Commonality" (J. Financial Economics):
// fire sales from deleveraging create liquidity commonality that propagates
// across assets. Systematic deleveraging validated on margin trading data.
// - Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// z-score normalization framework; extreme events flagged at ±1σ/±2σ.
// Bubble size scales with absolute z for statistical significance.
// - Amberdata Research (2026), "Leverage & Liquidations: The $31B
// Deleveraging": liquidation intensity > 5% of OI = cascade trigger.
// $31.4B total BTC liquidations YTD; 60% from longs.
// - Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
// in a High-Frequency World" (VPIN): volume-bucket approach and toxicity
// measurement inform liquidation clustering detection.
// ============================================================================
define(
title="Liquidation Bubbles [BackQuant] Perfected",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------
// --- Display Group ---
var mode = input(name="mode", type="select", defaultValue="Total Liquidations", label="Display Mode", options=["Total Liquidations", "Liquidation Delta", "Buy & Sell Liquidations"], group="Display")
var showClusters = input(name="showClusters", type="boolean", defaultValue=true, label="Show Cluster Shapes", group="Display")
var showCascade = input(name="showCascade", type="boolean", defaultValue=true, label="Show Cascade Markers", group="Display")
var sizeMult = input(name="sizeMult", type="number", defaultValue=2.0, label="Bubble Size Multiplier", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Cluster Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")
// --- Z-Score Group ---
var lookback = input(name="lookback", type="number", defaultValue=30, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Z-Score")
var threshold = input(name="threshold", type="number", defaultValue=1.5, label="Display Threshold (z)", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Z-Score")
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=2.5, label="Extreme Event Threshold (z)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Z-Score")
var opacityBase = input(name="opacityBase", type="number", defaultValue=0.5, label="Base Opacity", constraints={min: 0.1, max: 1.0, step: 0.1}, group="Z-Score")
var opacityMult = input(name="opacityMult", type="number", defaultValue=0.5, label="Opacity Multiplier", constraints={min: 0.1, max: 1.0, step: 0.1}, group="Z-Score")
// --- Cascade Detection Group ---
var cascadeThreshold = input(name="cascadeThreshold", type="number", defaultValue=5.0, label="Cascade Threshold (% of OI)", constraints={min: 1.0, max: 20.0, step: 0.5}, group="Cascade Detection")
var cascadeLookback = input(name="cascadeLookback", type="number", defaultValue=24, label="Cascade Lookback (bars)", constraints={min: 4, max: 100, step: 1}, group="Cascade Detection")
// --- Colors Group ---
var longColor = input(name="longColor", type="color", defaultValue="#ef5350", label="Long Liquidation Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#26a69a", label="Short Liquidation 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="#e91e63", label="Extreme Event Color", group="Colors")
var clusterColor = input(name="clusterColor", type="color", defaultValue="#ffab00", label="Cluster Shape Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries liqs = source("liquidations", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
// isnan guard: prevent computation on incomplete data
if (isnan(bars.close[0]) || isnan(oi[0])) {
return
}
// ---------------------------------------------------------------------------
// Liquidation Data Extraction
// ---------------------------------------------------------------------------
timeseries longLiq = isnum(liqs.long) ? liqs.long : 0
timeseries shortLiq = isnum(liqs.short) ? liqs.short : 0
timeseries totalLiq = longLiq + shortLiq
timeseries deltaLiq = longLiq - shortLiq
// ---------------------------------------------------------------------------
// Z-Score Computation — Total Liquidations
// ---------------------------------------------------------------------------
timeseries totalMean = sma(totalLiq, lookback)
timeseries totalStd = stdev(totalLiq, lookback)
timeseries totalZ = totalStd > 0 ? (totalLiq - totalMean) / totalStd : 0
// ---------------------------------------------------------------------------
// Z-Score Computation — Liquidation Delta
// ---------------------------------------------------------------------------
timeseries deltaMean = sma(deltaLiq, lookback)
timeseries deltaStd = stdev(deltaLiq, lookback)
timeseries deltaZ = deltaStd > 0 ? (deltaLiq - deltaMean) / deltaStd : 0
// ---------------------------------------------------------------------------
// Z-Score Computation — Individual Long/Short (for Buy/Sell mode)
// ---------------------------------------------------------------------------
timeseries longMean = sma(longLiq, lookback)
timeseries longStd = stdev(longLiq, lookback)
timeseries longZ = longStd > 0 ? (longLiq - longMean) / longStd : 0
timeseries shortMean = sma(shortLiq, lookback)
timeseries shortStd = stdev(shortLiq, lookback)
timeseries shortZ = shortStd > 0 ? (shortLiq - shortMean) / shortStd : 0
// ---------------------------------------------------------------------------
// Opacity Scaling — Dynamic by Statistical Significance
// ---------------------------------------------------------------------------
// Opacity increases with z-score magnitude. Base + multiplier * normalized z.
function calcOpacity(z) {
var absZ = math.abs(z)
var normZ = math.min(1.0, absZ / extremeThreshold)
return opacityBase + opacityMult * normZ
}
// ---------------------------------------------------------------------------
// Bubble Size — Dynamic by Z-Score
// ---------------------------------------------------------------------------
function calcSize(z) {
var absZ = math.abs(z)
var clampedZ = math.min(20, math.max(2, absZ))
return sizeMult * clampedZ
}
// ---------------------------------------------------------------------------
// Cascade Detection — Liquidation Intensity vs. Open Interest
// ---------------------------------------------------------------------------
timeseries totalLiqVal = longLiq + shortLiq
timeseries liqSum = sum(totalLiqVal, cascadeLookback)
timeseries oiVal = oi.close > 0 ? oi.close : 1
timeseries liqIntensity = (liqSum / oiVal) * 100
var cascadeTrigger = liqIntensity >= cascadeThreshold
// --- STATIC STATE: Event Tracking ---
static lastCascadeBar = 0
static lastTotalExtremeBar = 0
static lastDeltaExtremeBar = 0
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
if (cascadeTrigger) {
lastCascadeBar = barCount
}
}
var cascadeEvent = lastCascadeBar == barCount
// ---------------------------------------------------------------------------
// Event Flags
// ---------------------------------------------------------------------------
var totalExtreme = math.abs(totalZ) >= extremeThreshold
var deltaExtreme = math.abs(deltaZ) >= extremeThreshold
var totalDisplay = math.abs(totalZ) >= threshold
var deltaDisplay = math.abs(deltaZ) >= threshold
var longDisplay = math.abs(longZ) >= threshold
var shortDisplay = math.abs(shortZ) >= threshold
if (!isLiveUpdate) {
if (totalExtreme) {
lastTotalExtremeBar = barCount
}
if (deltaExtreme) {
lastDeltaExtremeBar = barCount
}
}
var totalExtremeEvent = lastTotalExtremeBar == barCount
var deltaExtremeEvent = lastDeltaExtremeBar == barCount
// ---------------------------------------------------------------------------
// Plotting: Total Liquidations Mode
// ---------------------------------------------------------------------------
if (mode == "Total Liquidations" && totalDisplay) {
var totalCol = totalExtreme ? extremeColor : (totalZ > 0 ? longColor : shortColor)
var totalOp = calcOpacity(totalZ)
var totalSz = calcSize(totalZ)
var plotY = bars.close
plotShape(
value=plotY,
shape="circle",
colorIndex=totalCol,
width=totalSz,
label=["Total Liq"],
desc=["Total liquidations: z=" + totalZ + ", mean=" + totalMean + ", std=" + totalStd]
)
}
// ---------------------------------------------------------------------------
// Plotting: Liquidation Delta Mode
// ---------------------------------------------------------------------------
if (mode == "Liquidation Delta" && deltaDisplay) {
var deltaCol = deltaExtreme ? extremeColor : (deltaZ > 0 ? longColor : shortColor)
var deltaOp = calcOpacity(deltaZ)
var deltaSz = calcSize(deltaZ)
var plotY = bars.close
plotShape(
value=plotY,
shape="circle",
colorIndex=deltaCol,
width=deltaSz,
label=["Liq Delta"],
desc=["Liquidation delta (long − short): z=" + deltaZ + ", mean=" + deltaMean + ", std=" + deltaStd]
)
}
// ---------------------------------------------------------------------------
// Plotting: Buy & Sell Liquidations Mode
// ---------------------------------------------------------------------------
if (mode == "Buy & Sell Liquidations") {
// Long liquidations (forced selling of longs) at bar low
if (longDisplay) {
var longCol = math.abs(longZ) >= extremeThreshold ? extremeColor : longColor
var longSz = calcSize(longZ)
var longOp = calcOpacity(longZ)
plotShape(
value=bars.low,
shape="circle",
colorIndex=longCol,
width=longSz,
label=["Long Liq"],
desc=["Long liquidations at bar low: z=" + longZ + ", value=" + longLiq]
)
}
// Short liquidations (forced buying of shorts) at bar high
if (shortDisplay) {
var shortCol = math.abs(shortZ) >= extremeThreshold ? extremeColor : shortColor
var shortSz = calcSize(shortZ)
var shortOp = calcOpacity(shortZ)
plotShape(
value=bars.high,
shape="circle",
colorIndex=shortCol,
width=shortSz,
label=["Short Liq"],
desc=["Short liquidations at bar high: z=" + shortZ + ", value=" + shortLiq]
)
}
}
// ---------------------------------------------------------------------------
// Plotting: Cluster Shape Markers
// ---------------------------------------------------------------------------
// A "cluster" is defined as two consecutive bars with significant liquidation
// activity (|z| >= threshold) in the same direction.
if (showClusters) {
if (mode == "Total Liquidations" && totalDisplay && math.abs(totalZ[1]) >= threshold) {
plotShape(
value=bars.high,
shape="triangleup",
colorIndex=clusterColor,
width=shapeSize,
label=["Liq Cluster"],
desc=["Consecutive liquidation cluster detected. Total z=" + totalZ + " / " + totalZ[1]]
)
}
if (mode == "Liquidation Delta" && deltaDisplay && math.abs(deltaZ[1]) >= threshold) {
var sameDir = (deltaZ > 0 && deltaZ[1] > 0) || (deltaZ < 0 && deltaZ[1] < 0)
if (sameDir) {
plotShape(
value=bars.high,
shape="triangleup",
colorIndex=clusterColor,
width=shapeSize,
label=["Delta Cluster"],
desc=["Consecutive liquidation delta cluster: z=" + deltaZ + " / " + deltaZ[1]]
)
}
}
if (mode == "Buy & Sell Liquidations") {
if (longDisplay && math.abs(longZ[1]) >= threshold) {
plotShape(
value=bars.low,
shape="triangleup",
colorIndex=clusterColor,
width=shapeSize,
label=["Long Cluster"],
desc=["Consecutive long liquidation cluster: z=" + longZ + " / " + longZ[1]]
)
}
if (shortDisplay && math.abs(shortZ[1]) >= threshold) {
plotShape(
value=bars.high,
shape="triangleup",
colorIndex=clusterColor,
width=shapeSize,
label=["Short Cluster"],
desc=["Consecutive short liquidation cluster: z=" + shortZ + " / " + shortZ[1]]
)
}
}
}
// ---------------------------------------------------------------------------
// Plotting: Cascade Markers
// ---------------------------------------------------------------------------
if (showCascade && cascadeEvent) {
plotShape(
value=bars.high,
shape="rectangle",
colorIndex=extremeColor,
width=6,
label=["CASCADE"],
desc=["Liquidation cascade detected: intensity=" + liqIntensity + "% of OI (threshold=" + cascadeThreshold + "%)"]
)
}
// ---------------------------------------------------------------------------
// Plotting: Liquidation Intensity (plotBar on secondary axis)
// ---------------------------------------------------------------------------
if (showCascade) {
plotBar(
value=liqIntensity,
colors=[liqIntensity >= cascadeThreshold ? extremeColor : opacity(neutralColor, 40)],
label=["Liq Intensity (% OI)"],
desc=["Rolling liquidation sum as % of open interest over " + cascadeLookback + " bars"]
)
}