Perfected FlowScript
Funding–Liquidation Pressure Gauge
Funding-Liquidation Pressure Gauge — Perfected Edition is indexed as 092_funding_liquidation_pressure_gauge.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
14.7 KB
Lines
349
Native Signal Candidates
5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull
line 266:9
Trigger
(showShapeMarkers) && (bullCrossUp)
Value
aggregate
Deps
bullCrossUp:var, showShapeMarkers:input
Extreme Bear
line 276:9
Trigger
(showShapeMarkers) && (bearCrossDown)
Value
aggregate
Deps
bearCrossDown:var, showShapeMarkers:input
Zero Cross Up
line 286:9
Trigger
(showShapeMarkers) && (zeroCrossUp)
Value
0
Deps
showShapeMarkers:input, zeroCrossUp:var
Zero Cross Down
line 296:9
Trigger
(showShapeMarkers) && (zeroCrossDown)
Value
0
Deps
showShapeMarkers:input, zeroCrossDown:var
Unlabeled shape
line 309:5
Trigger
(showRegimeLabel && isLastBar)
Value
aggregate
Deps
isLastBar:builtin, showRegimeLabel:input
092_funding_liquidation_pressure_gauge.flowscript
source path: kscripts/perfected/092_funding_liquidation_pressure_gauge.flowscript · sha256:aa2509fb3320d12f2b0dc7ea384d126e9bfb2fd5e4cd323c250aef1b1774e6af
//@version=2
// ============================================================================
// Funding-Liquidation Pressure Gauge — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #funding, #liquidation, #pressure, #gauge, #zscore, #regime
//
// Production-grade composite indicator blending funding rate × long/short ratio,
// liquidation imbalance, and open interest change into a single z-normalized
// pressure gauge with regime detection, color coding, and fill visualization.
//
// Academic foundations:
// 1. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
// (Rev. Financial Studies, 22(6), 2201–2238). Liquidity spiral: market
// liquidity ↔ funding liquidity mutual reinforcement. Key formula:
// small shocks amplify into systemic crises through margin calls.
// 2. He & Manela (2022), "Fundamentals of Perpetual Futures" (J. Financial
// Economics, forthcoming). No-arbitrage perpetual futures pricing;
// past return momentum explains futures-spot gap with R² > 50%.
// 3. Bian et al. (2023), "Deleveraging Commonality" (J. Financial Economics).
// Margin trading decreases spread; deleveraging commonality where fire
// sales from liquidations exacerbate market liquidity.
// 4. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint"
// (IEEE Trans. Signal Processing). Z-score event triggers for mean
// reversion: z_t = (x_t − μ) / σ; entry at ±1σ or ±2σ.
// 5. Poterba & Summers (1988), "Mean Reversion in Stock Prices" (J. Financial
// Economics, 22(1), 27–59). Negative autocorrelation at medium horizons
// supports dynamic threshold calibration.
// 6. Amberdata Research (2026), "Leverage & Liquidations: The $31B Deleveraging."
// Liquidation intensity threshold = 5% of OI triggers systemic cascade.
// ============================================================================
define(
title="Funding-Liquidation Pressure Gauge — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=30, label="Z-score window", constraints={min: 10, max: 100, step: 1}, group="Z-Score")
// --- Weights ---
var wFundingLSR = input(name="wFundingLSR", type="number", defaultValue=0.4, label="Weight: Funding × LSR", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wLiq = input(name="wLiq", type="number", defaultValue=0.35, label="Weight: Liquidation imbalance", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var wOI = input(name="wOI", type="number", defaultValue=0.25, label="Weight: OI change", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
// --- Smoothing ---
var smooth = input(name="smooth", type="boolean", defaultValue=true, label="Smooth aggregate with EMA", group="Smoothing")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing length", constraints={min: 1, max: 20, step: 1}, group="Smoothing")
// --- Thresholds ---
var extremeUpper = input(name="extremeUpper", type="number", defaultValue=2.0, label="Extreme upper threshold", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var extremeLower = input(name="extremeLower", type="number", defaultValue=-2.0, label="Extreme lower threshold", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
// --- Display ---
var showComponents = input(name="showComponents", type="boolean", defaultValue=false, label="Show component z-scores", group="Display")
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show raw aggregate", group="Display")
var showShapeMarkers = input(name="showShapeMarkers", type="boolean", defaultValue=true, label="Show extreme markers", group="Display")
var showRegimeLabel = input(name="showRegimeLabel", type="boolean", defaultValue=true, label="Show regime label", group="Display")
// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive pressure color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative pressure color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral color", group="Colors")
var gaugeColor = input(name="gaugeColor", type="color", defaultValue="#ffd700", label="Gauge line color", group="Colors")
var compFundingColor = input(name="compFundingColor", type="color", defaultValue="#2962ff", label="Funding component color", group="Colors")
var compLiqColor = input(name="compLiqColor", type="color", defaultValue="#ff9800", label="Liquidation component color", group="Colors")
var compOIColor = input(name="compOIColor", type="color", defaultValue="#9c27b0", label="OI component color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries funding = source("funding_rate", currentSymbol, currentExchange)
timeseries lsr = source("long_short_ratio", currentSymbol, currentExchange)
timeseries liquidations = source("liquidations", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
// isnan guard — prevents NaN propagation on startup when external data
// sources are not yet available or the symbol lacks the required feed.
if (isnan(funding[0]) || isnan(lsr[0]) || isnan(liquidations[0]) || isnan(oi.close[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. BAR COUNTER
// ---------------------------------------------------------------------------
static barCount = 0
if (!isLiveUpdate) {
barCount = barCount + 1
}
// ---------------------------------------------------------------------------
// 4. COMPONENT Z-SCORES
// ---------------------------------------------------------------------------
// Per Zhao & Palomar (2018): z_t = (x_t − μ_t) / σ_t over a rolling window.
// Each component is independently normalized to ensure comparable scales.
// 4.1 Funding × Long/Short Ratio
// lsr - 1.0 = skew; positive = longs dominant, negative = shorts dominant.
// Funding rate amplifies the skew: when longs are crowded AND funding is
// positive, upward pressure is extreme. When shorts are crowded AND funding
// is negative, downward pressure is extreme.
var fundingLSR = funding * (lsr - 1.0)
var fLSRMean = sma(source=fundingLSR, period=zWindow)
var fLSRStd = stdev(source=fundingLSR, period=zWindow)
var fLSRZ = fLSRStd > 0 ? (fundingLSR - fLSRMean) / fLSRStd : 0
// 4.2 Liquidation imbalance (buy liquidations − sell liquidations)
// Positive = more long liquidations (downward pressure).
// Negative = more short liquidations (upward pressure).
var liqImb = liquidations.buy - liquidations.sell
var liqMean = sma(source=liqImb, period=zWindow)
var liqStd = stdev(source=liqImb, period=zWindow)
var liqZ = liqStd > 0 ? (liqImb - liqMean) / liqStd : 0
// 4.3 Open interest change
// Positive dOI = new positions opening (trend continuation).
// Negative dOI = positions closing (trend exhaustion / de-risking).
var dOI = oi.close - oi.close[1]
var oiMean = sma(source=dOI, period=zWindow)
var oiStd = stdev(source=dOI, period=zWindow)
var oiZ = oiStd > 0 ? (dOI - oiMean) / oiStd : 0
// ---------------------------------------------------------------------------
// 5. WEIGHTED COMPOSITE
// ---------------------------------------------------------------------------
// Aggregate: weighted sum of three z-scores. Default weights reflect the
// relative importance of funding skew (sentiment), liquidation pressure
// (forced flow), and OI change (positioning trend) in price dynamics.
var aggregateRaw = wFundingLSR * fLSRZ + wLiq * liqZ + wOI * oiZ
var aggregate = smooth ? ema(source=aggregateRaw, period=smoothLen) : aggregateRaw
// ---------------------------------------------------------------------------
// 6. REGIME DETECTION
// ---------------------------------------------------------------------------
// Bullish pressure: gauge > 0.5 (net positive composite z-score).
// Bearish pressure: gauge < -0.5 (net negative composite z-score).
// Neutral: everything in between (no dominant directional pressure).
var regimeBull = aggregate > 0.5
var regimeBear = aggregate < -0.5
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)
var regimeLabel = regimeBull ? "UPWARD PRESSURE" : (regimeBear ? "DOWNWARD PRESSURE" : "NEUTRAL")
// ---------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
static lastRegime = 0
static regimeDuration = 0
static maxGauge = 0.0
static minGauge = 0.0
if (!isLiveUpdate) {
var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
if (currentRegime == lastRegime) {
regimeDuration = regimeDuration + 1
} else {
regimeDuration = 1
}
lastRegime = currentRegime
if (aggregate > maxGauge) {
maxGauge = aggregate
}
if (aggregate < minGauge) {
minGauge = aggregate
}
}
// ---------------------------------------------------------------------------
// 8. EXTREME FLAGS & CROSS DETECTION
// ---------------------------------------------------------------------------
// Extreme readings beyond ±2σ are statistically rare (~95% of values fall
// within ±2σ in a normal distribution). Per Zhao & Palomar (2018), these
// levels mark mean-reversion triggers and contrarian positioning extremes.
var extremeBull = aggregate > extremeUpper
var extremeBear = aggregate < extremeLower
var bullCrossUp = aggregate > extremeUpper && aggregate[1] <= extremeUpper
var bearCrossDown = aggregate < extremeLower && aggregate[1] >= extremeLower
var zeroCrossUp = aggregate > 0 && aggregate[1] <= 0
var zeroCrossDown = aggregate < 0 && aggregate[1] >= 0
// ---------------------------------------------------------------------------
// 9. PLOTTING
// ---------------------------------------------------------------------------
// --- Reference lines ---
hline(value=0, color="#ffffff", width=1)
hline(value=extremeUpper, color=transparency(upColor, 50), width=1)
hline(value=extremeLower, color=transparency(dnColor, 50), width=1)
hline(value=1, color=transparency(upColor, 70), width=1)
hline(value=-1, color=transparency(dnColor, 70), width=1)
// --- Component z-scores (optional) ---
if (showComponents) {
plotLine(
value=fLSRZ,
width=1,
colors=[compFundingColor],
label=["Funding × LSR z"],
desc=["Funding rate weighted by long/short ratio skew, z-scored"]
)
plotLine(
value=liqZ,
width=1,
colors=[compLiqColor],
label=["Liq imbalance z"],
desc=["Liquidation imbalance (buy − sell), z-scored"]
)
plotLine(
value=oiZ,
width=1,
colors=[compOIColor],
label=["dOI z"],
desc=["Open interest change, z-scored"]
)
}
// --- Raw aggregate (optional) ---
if (showRaw) {
plotLine(
value=aggregateRaw,
width=1,
colors=[transparency(neutralColor, 50)],
label=["Raw aggregate"],
desc=["Unsmoothed weighted composite of all three z-scores"]
)
}
// --- Gauge line with fill to zero ---
var gaugeBull = aggregate >= 0
plotLine(
value=[aggregate, 0],
width=1,
colors=[transparency(upColor, 20), transparency(dnColor, 20)],
colorIndex=gaugeBull ? 0 : 1,
fill=true,
label=["Pressure Gauge", "Zero"],
desc=["Funding-liquidation pressure gauge (z-normalized)", "Zero reference"]
)
plotLine(
value=aggregate,
width=2,
colors=[gaugeColor],
label=["Pressure Gauge"],
desc=["Smoothed weighted composite: " + wFundingLSR + "×Funding + " + wLiq + "×Liq + " + wOI + "×OI"]
)
// --- Gauge histogram ---
plotBar(
value=aggregate,
colors=[transparency(upColor, 60), transparency(dnColor, 60)],
colorIndex=gaugeBull ? 0 : 1,
width=1,
label=["Pressure Bar"],
desc=["Pressure gauge as histogram: above zero = net upward pressure"]
)
// --- Extreme markers ---
if (showShapeMarkers) {
if (bullCrossUp) {
plotShape(
value=aggregate,
shape="triangleup",
colorIndex=upColor,
width=4,
label=["Extreme Bull"],
desc=["Extreme upward pressure: gauge crossed above " + extremeUpper]
)
}
if (bearCrossDown) {
plotShape(
value=aggregate,
shape="triangledown",
colorIndex=dnColor,
width=4,
label=["Extreme Bear"],
desc=["Extreme downward pressure: gauge crossed below " + extremeLower]
)
}
if (zeroCrossUp) {
plotShape(
value=0,
shape="circle",
colorIndex=upColor,
width=2,
label=["Zero Cross Up"],
desc=["Pressure gauge crossed above zero: bullish regime shift"]
)
}
if (zeroCrossDown) {
plotShape(
value=0,
shape="circle",
colorIndex=dnColor,
width=2,
label=["Zero Cross Down"],
desc=["Pressure gauge crossed below zero: bearish regime shift"]
)
}
}
// --- Regime label on last bar ---
if (showRegimeLabel && isLastBar) {
plotPriceLabel(
price=aggregate,
text=regimeLabel,
type="callout",
color="#ffffff",
backgroundColor=regimeColor,
size=10,
fontWeight=700
)
}
// ---------------------------------------------------------------------------
// 10. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
plotTable(
data=[
["Pressure Gauge", regimeLabel],
["Funding × LSR z", fLSRZ],
["Liq imbalance z", liqZ],
["dOI z", oiZ],
["Raw aggregate", aggregateRaw],
["Gauge (smoothed)", aggregate],
["Regime duration", regimeDuration],
["Max gauge", maxGauge],
["Min gauge", minGauge]
],
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
)
}