Perfected FlowScript
SCF Delta Perps
SCF Delta Perps V2 is indexed as 104_scf_delta_perps.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.8 KB
Lines
337
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Pressure
line 277:9
Trigger
(showShapes) && (crossUp)
Value
pressure
Deps
crossUp:var, showShapes:input
Bear Pressure
line 287:9
Trigger
(showShapes) && (crossDn)
Value
pressure
Deps
crossDn:var, showShapes:input
Extreme Bull
line 297:9
Trigger
(showShapes) && (extremeUp)
Value
pressure
Deps
extremeUp:var, showShapes:input
Extreme Bear
line 307:9
Trigger
(showShapes) && (extremeDn)
Value
pressure
Deps
extremeDn:var, showShapes:input
Cascade Up
line 317:9
Trigger
(showShapes) && (cascadeUp)
Value
pressure
Deps
cascadeUp:var, showShapes:input
Cascade Down
line 327:9
Trigger
(showShapes) && (cascadeDn)
Value
pressure
Deps
cascadeDn:var, showShapes:input
104_scf_delta_perps.flowscript
source path: kscripts/perfected/104_scf_delta_perps.flowscript · sha256:20a8af9933805e28ec2dad605a0a686d80604a6091b49e5c1a96f4f4aa796df6
//@version=2
// ============================================================================
// SCF Delta Perps V2 — Production-Quality Perpetual Futures Delta & Pressure Gauge
// Author: SoulzBTC (@SoulzBTC) | Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, #perps, #funding, #liquidation, #oi, #delta, #zscore, #regime
//
// Multi-component perpetual futures pressure gauge combining funding rate
// z-score, liquidation imbalance z-score, and OI delta z-score into a composite
// regime indicator with color-coded visualization and shape alerts.
//
// FORMULA FOUNDATION:
// 1. Funding Pressure Z: Z_funding = (funding − μ_funding) / σ_funding [He & Manela 2022]
// 2. Liquidation Imbalance Z: Z_liq = (liqBuy − liqSell − μ_liq) / σ_liq [Brunnermeier & Pedersen 2009]
// 3. OI Delta Z: Z_oi = (ΔOI − μ_ΔOI) / σ_ΔOI [Chen, Cuny & Haugen 1995]
// 4. Composite Pressure: P = w_f·Z_funding + w_liq·Z_liq + w_oi·Z_oi
// 5. Regime Detection: Extreme (|P| > extreme), Elevated (|P| > threshold), Normal
// per Brunnermeier & Pedersen (2009) liquidity spiral thresholds.
// 6. Cascade Risk: |P| > cascadeThreshold flags liquidation cascade probability
// per Amberdata Research (2026) >5% OI intensity trigger.
//
// RESEARCH BASIS:
// • He & Manela (2022), "Fundamentals of Perpetual Futures", J. Financial
// Economics (forthcoming), arXiv:2212.06888. No-arbitrage perpetual futures
// pricing; past return momentum explains futures-spot gap with R² > 50%.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies 22(6), 2201–2238. Liquidity spiral: market
// liquidity ↔ funding liquidity reinforcement; small shocks amplify into
// systemic crises.
// • Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts", J. Finance 50(1), 281–300.
// OI levels contain information about future volatility and expectations.
// • Amberdata Research (2026), "Leverage & Liquidations: The $31B Deleveraging".
// Liquidation intensity > 5% of OI = cascade trigger; funding rates above
// 15% APR historically precede corrections.
// • BitMEX Quantitative Analysis (2020), "Perpetual Inverse Futures XBTUSD".
// Liquidation as stopping time problem; expected liquidation probability
// based on leverage and volatility.
// • Kim & Park (2025), "Designing Funding Rates for Perpetual Futures in
// Cryptocurrency Markets", arXiv:2506.08573. Path-dependent funding rate
// design using BSDEs and arbitrage pricing theory.
// ============================================================================
define(
title="SCF Delta Perps V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Data Sources ---
var perpSymbol = input(name="perpSymbol", type="string", defaultValue="BTCUSDT", label="Perp Symbol", group="Data Sources")
var perpExch = input(name="perpExch", type="string", defaultValue="BYBIT", label="Perp Exchange", group="Data Sources")
// --- Component Weights ---
var fundingWeight = input(name="fundingWeight", type="number", defaultValue=0.40, label="Weight: Funding Pressure", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var liqWeight = input(name="liqWeight", type="number", defaultValue=0.35, label="Weight: Liquidation Imbalance", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
var oiWeight = input(name="oiWeight", type="number", defaultValue=0.25, label="Weight: OI Delta", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Weights")
// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Composite EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Z-Score")
// --- Thresholds & Regime ---
var divThreshold = input(name="divThreshold", type="number", defaultValue=1.5, label="Elevated Pressure Threshold (σ)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.5, label="Extreme Pressure Threshold (σ)", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Thresholds")
var cascadeThreshold = input(name="cascadeThreshold", type="number", defaultValue=3.0, label="Cascade Risk Threshold (σ)", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Thresholds")
// --- Display ---
var showComponents = input(name="showComponents", type="boolean", defaultValue=true, label="Show Component Z-Scores", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Pressure", group="Display")
var showZBars = input(name="showZBars", type="boolean", defaultValue=true, label="Show Pressure Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Sigma Bands", group="Display")
// --- Colors ---
var fundingColor = input(name="fundingColor", type="color", defaultValue="#2962ff", label="Funding Z Color", group="Colors")
var liqColor = input(name="liqColor", type="color", defaultValue="#9c27b0", label="Liquidation Z Color", group="Colors")
var oiColor = input(name="oiColor", type="color", defaultValue="#00bcd4", label="OI Delta Z Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Pressure Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Pressure Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
var cascadeColor = input(name="cascadeColor", type="color", defaultValue="#ff1744", label="Cascade Risk Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources — with isnan() guard on first external access
// ------------------------------------------------------------------------------
timeseries funding = source("funding_rate", perpSymbol, perpExch)
timeseries liquidations = source("liquidations", perpSymbol, perpExch)
timeseries oiData = open_interest(symbol=perpSymbol, exchange=perpExch)
timeseries ohlcvData = ohlcv(symbol=perpSymbol, exchange=perpExch)
timeseries close = ohlcvData.close
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(close[0]) || !isnum(funding) || !isnum(liquidations.buy)) {
return
}
// ------------------------------------------------------------------------------
// Component Z-Score Computation
// ------------------------------------------------------------------------------
// All denominators guarded against zero per production spec
// 1. Funding pressure: positive funding = longs paying shorts (bullish positioning)
// Negative funding = shorts paying longs (bearish positioning)
// He & Manela (2022): funding rate deviation from fair value signals sentiment.
var fundingMean = sma(funding, zWindow)
var fundingStd = stdev(funding, zWindow)
var fundingZ = fundingStd > 0 ? (funding - fundingMean) / fundingStd : 0
// 2. Liquidation imbalance (buy liqs - sell liqs)
// Brunnermeier & Pedersen (2009): liquidation cascades amplify when one side
// is forced to cover, creating feedback loops.
var liqImb = liquidations.buy - liquidations.sell
var liqMean = sma(liqImb, zWindow)
var liqStd = stdev(liqImb, zWindow)
var liqZ = liqStd > 0 ? (liqImb - liqMean) / liqStd : 0
// 3. OI delta — change in open interest
// Chen, Cuny & Haugen (1995): unexpected OI changes carry more information
// than expected changes; information flow hypothesis.
var dOI = oiData.close - oiData.close[1]
var oiMean = sma(dOI, zWindow)
var oiStd = stdev(dOI, zWindow)
var oiZ = oiStd > 0 ? (dOI - oiMean) / oiStd : 0
// ------------------------------------------------------------------------------
// Composite Pressure & Smoothing
// ------------------------------------------------------------------------------
// Weighted composite per Brunnermeier & Pedersen (2009) multi-factor framework
var pressureRaw = fundingWeight * fundingZ + liqWeight * liqZ + oiWeight * oiZ
var pressure = ema(pressureRaw, smoothLen)
// ------------------------------------------------------------------------------
// Regime Detection (Brunnermeier & Pedersen 2009 liquidity spiral thresholds)
// ------------------------------------------------------------------------------
// Regime segmentation:
// Extreme bull: P ≥ extremeThresh
// Elevated bull: divThreshold ≤ P < extremeThresh
// Neutral: −divThreshold < P < divThreshold
// Elevated bear: −extremeThresh < P ≤ −divThreshold
// Extreme bear: P ≤ −extremeThresh
// Cascade risk: |P| ≥ cascadeThreshold (Amberdata 2026 >5% OI intensity)
var regime = 0 // 0 = neutral, 1 = elevated bull, 2 = extreme bull, -1 = elevated bear, -2 = extreme bear
var cascadeRisk = false
if (pressure >= extremeThresh) {
regime = 2
} else if (pressure >= divThreshold) {
regime = 1
} else if (pressure <= -extremeThresh) {
regime = -2
} else if (pressure <= -divThreshold) {
regime = -1
}
cascadeRisk = abs(pressure) >= cascadeThreshold
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and cascade-event counts
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighPressure = -999999.0
static sessionLowPressure = 999999.0
static cascadeCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (pressure > sessionHighPressure) {
sessionHighPressure = pressure
}
if (pressure < sessionLowPressure) {
sessionLowPressure = pressure
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (cascadeRisk) {
cascadeCount = cascadeCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Zero line and threshold guides
hline(value=0, color="#ffffff30", width=1)
if (showBands) {
hline(value=divThreshold, color=opacity(bullColor, 30), width=1)
hline(value=-divThreshold, color=opacity(bearColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(extremeBearColor, 20), width=1)
hline(value=cascadeThreshold, color=opacity(cascadeColor, 15), width=1)
hline(value=-cascadeThreshold, color=opacity(cascadeColor, 15), width=1)
}
// Component z-scores (optional, for granular analysis)
if (showComponents) {
plotLine(
value=fundingZ,
width=1,
colors=[fundingColor],
label=["Funding Z"],
desc=["Funding rate z-score; positive = longs paying shorts (bullish positioning)"]
)
plotLine(
value=liqZ,
width=1,
colors=[liqColor],
label=["Liquidation Z"],
desc=["Liquidation imbalance z-score; positive = more buy liquidations (shorts blown out)"]
)
plotLine(
value=oiZ,
width=1,
colors=[oiColor],
label=["OI Delta Z"],
desc=["Open interest delta z-score; positive = OI rising faster than average (new positions)"]
)
}
// Composite pressure line with regime-coded fill area
if (showComposite) {
var colorIdx = regime > 0 ? (regime == 2 ? 3 : 0) : (regime < 0 ? (regime == -2 ? 4 : 1) : 2)
plotLine(
value=pressure,
width=2,
colors=[bullColor, bearColor, neutralColor, extremeBullColor, extremeBearColor],
colorIndex=colorIdx,
label=["Perp Pressure"],
desc=["Composite perp pressure (funding + liquidation + OI). Regime: extreme bull / elevated bull / neutral / elevated bear / extreme bear."],
fill=true
)
}
// Pressure bars (color-coded histogram)
if (showZBars) {
var barColorIdx = regime > 0 ? (regime == 2 ? 3 : 0) : (regime < 0 ? (regime == -2 ? 4 : 1) : 2)
plotBar(
value=pressure,
colors=[bullColor, bearColor, neutralColor, extremeBullColor, extremeBearColor],
colorIndex=barColorIdx,
width=1,
label=["Pressure Bars"],
desc=["Composite pressure as color-coded bars (positive = upward pressure, negative = downward pressure)"]
)
}
// Regime transition shapes — directional signal extraction
if (showShapes) {
var crossUp = pressure >= divThreshold && !isnan(pressure[1]) && pressure[1] < divThreshold
var crossDn = pressure <= -divThreshold && !isnan(pressure[1]) && pressure[1] > -divThreshold
var extremeUp = pressure >= extremeThresh && !isnan(pressure[1]) && pressure[1] < extremeThresh
var extremeDn = pressure <= -extremeThresh && !isnan(pressure[1]) && pressure[1] > -extremeThresh
var cascadeUp = pressure >= cascadeThreshold && !isnan(pressure[1]) && pressure[1] < cascadeThreshold
var cascadeDn = pressure <= -cascadeThreshold && !isnan(pressure[1]) && pressure[1] > -cascadeThreshold
if (crossUp) {
plotShape(
value=pressure,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["Bull Pressure"],
desc=["Perp pressure crossed into elevated bullish regime — long positioning building"]
)
}
if (crossDn) {
plotShape(
value=pressure,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["Bear Pressure"],
desc=["Perp pressure crossed into elevated bearish regime — short positioning building"]
)
}
if (extremeUp) {
plotShape(
value=pressure,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Bull"],
desc=["Extreme bullish perp pressure — potential squeeze zone per Brunnermeier & Pedersen 2009"]
)
}
if (extremeDn) {
plotShape(
value=pressure,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Bear"],
desc=["Extreme bearish perp pressure — potential cascade zone per Brunnermeier & Pedersen 2009"]
)
}
if (cascadeUp) {
plotShape(
value=pressure,
shape="flag",
color=cascadeColor,
width=5,
label=["Cascade Up"],
desc=["LIQUIDATION CASCADE RISK: Short squeeze probability elevated per Amberdata 2026 threshold"]
)
}
if (cascadeDn) {
plotShape(
value=pressure,
shape="flag",
color=cascadeColor,
width=5,
label=["Cascade Down"],
desc=["LIQUIDATION CASCADE RISK: Long liquidation probability elevated per Amberdata 2026 threshold"]
)
}
}