Perfected FlowScript
OI–Funding Crowding Score
OI–Funding Crowding Score [Perfected] is indexed as 061_oi_funding_crowding_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
14.3 KB
Lines
318
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Crowded Long
line 278:9
Trigger
(showShapes) && (crossUp)
Value
score
Deps
crossUp:var, showShapes:input
Crowded Short
line 288:9
Trigger
(showShapes) && (crossDn)
Value
score
Deps
crossDn:var, showShapes:input
Extreme Long
line 298:9
Trigger
(showShapes) && (extremeUp)
Value
score
Deps
extremeUp:var, showShapes:input
Extreme Short
line 308:9
Trigger
(showShapes) && (extremeDn)
Value
score
Deps
extremeDn:var, showShapes:input
061_oi_funding_crowding_score.flowscript
source path: kscripts/perfected/061_oi_funding_crowding_score.flowscript · sha256:1864105745e46d9540f965ce1499a00e498b080f4c52327a810e7da30a0c85c8
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// OI–Funding Crowding Score [BackQuant Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, CORE, #oi, #funding, #crowding, #sentiment, #zscore
//
// Composite crowding score combining Open Interest and funding rate into
// rolling z-scores, merged via a weighted composite with regime detection,
// session tracking, and extreme-event shape markers.
//
// FORMULA FOUNDATION:
// 1. Z-Score Normalization: z = (x − μ) / σ over rolling window (Zhao & Palomar 2018)
// 2. Weighted Composite: Score = w_OI × |OIz| + w_FR × FRz (sign-aware)
// 3. Regime Segmentation: Crowded Long (>+2), Neutral (−2 to +2), Crowded Short (<−2)
// per Baker & Wurgler (2006) sentiment extremes and Brunnermeier & Pedersen (2005)
// predatory-trading crowding dynamics.
// 4. Funding Rate Proxy: Signed price drift as funding-rate proxy (He & Manela 2022
// perpetual-futures framework).
//
// RESEARCH BASIS:
// • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
// Returns", J. Finance 61(4), 1645–1680. Composite sentiment index construction
// via multiple proxies; sentiment extremes predict reversals.
// • 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 (R² > 50%). Funding rate as
// positioning sentiment gauge.
// • Brunnermeier & Pedersen (2005), "Predatory Trading", J. Finance 60(4), 1825–1863.
// Crowded positioning creates vulnerability to predatory price action; squeeze
// dynamics when one side is overextended.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// Z-score event triggers at ±1σ, ±2σ; standardized distance to equilibrium.
// • CoinxSight (2026), "Funding Rate: The Cost of Being Crowded". Thresholds:
// >+0.05% funding = overcrowded long; <−0.05% = overcrowded short.
// • Amberdata Research (2026), "Leverage & Liquidations: The $31B Deleveraging".
// Liquidation intensity >5% of OI triggers cascade; funding >15% APR precedes
// corrections.
// ============================================================================
define(
title="OI–Funding Crowding Score [Perfected]",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ---------------------------------------------------------------------------
// --- OI Z-Score Group ---
var oiZLen = input(name="oiZLen", type="number", defaultValue=60, label="OI Z-Score Lookback", constraints={min: 10, max: 500, step: 1}, group="OI Z-Score")
var oiZSmooth = input(name="oiZSmooth", type="boolean", defaultValue=true, label="Smooth OI Z-Score (EMA)", group="OI Z-Score")
var oiZSmoothLen = input(name="oiZSmoothLen", type="number", defaultValue=5, label="OI Z EMA Length", constraints={min: 1, max: 50, step: 1}, group="OI Z-Score")
// --- Funding Z-Score Group ---
var frZLen = input(name="frZLen", type="number", defaultValue=60, label="Funding Z-Score Lookback", constraints={min: 10, max: 500, step: 1}, group="Funding Z-Score")
var frZSmooth = input(name="frZSmooth", type="boolean", defaultValue=true, label="Smooth Funding Z (EMA)", group="Funding Z-Score")
var frZSmoothLen = input(name="frZSmoothLen", type="number", defaultValue=5, label="Funding Z EMA Length", constraints={min: 1, max: 50, step: 1}, group="Funding Z-Score")
// --- Composite Group ---
var wOI = input(name="wOI", type="number", defaultValue=0.5, label="OI Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Composite")
var wFR = input(name="wFR", type="number", defaultValue=0.5, label="Funding Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Composite")
var compositeSmooth = input(name="compositeSmooth", type="boolean", defaultValue=true, label="Smooth Composite (EMA)", group="Composite")
var compositeSmoothLen = input(name="compositeSmoothLen", type="number", defaultValue=3, label="Composite EMA Length", constraints={min: 1, max: 50, step: 1}, group="Composite")
// --- Thresholds Group ---
var bandHi = input(name="bandHi", type="number", defaultValue=2.0, label="Crowded Long Threshold", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var bandLo = input(name="bandLo", type="number", defaultValue=-2.0, label="Crowded Short Threshold", constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeHi = input(name="extremeHi", type="number", defaultValue=3.0, label="Extreme Long Threshold", constraints={min: 2.0, max: 6.0, step: 0.1}, group="Thresholds")
var extremeLo = input(name="extremeLo", type="number", defaultValue=-3.0, label="Extreme Short Threshold", constraints={min: -6.0, max: -2.0, step: 0.1}, group="Thresholds")
// --- Display Group ---
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show Composite Histogram", group="Display")
var showComponents = input(name="showComponents", type="boolean", defaultValue=false, label="Show Individual Z-Scores", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")
// --- Colors Group ---
var longColor = input(name="longColor", type="color", defaultValue="#ef5350", label="Crowded Long Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#26a69a", label="Crowded Short Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeLongColor = input(name="extremeLongColor", type="color", defaultValue="#ff1744", label="Extreme Long Color", group="Colors")
var extremeShortColor = input(name="extremeShortColor", type="color", defaultValue="#00e676", label="Extreme Short Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = oiTS.close
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
// isnan guard: prevent execution before data is loaded
if (isnan(oi[0]) || isnan(c[0]) || isnan(h[0]) || isnan(l[0])) {
return
}
// ---------------------------------------------------------------------------
// Funding Rate Proxy (signed price drift per He & Manela 2022)
// ---------------------------------------------------------------------------
// Perpetual futures funding rate is theoretically linked to the futures-spot
// premium. In the absence of direct funding-rate data, we use signed price drift
// as a proxy: positive drift = longs pay shorts (long crowding); negative drift
// = shorts pay longs (short crowding).
timeseries drift = c[1] > 0 ? (c - c[1]) / c[1] * 100.0 : 0.0
// ---------------------------------------------------------------------------
// Z-Score Normalization per Component (Zhao & Palomar 2018)
// ---------------------------------------------------------------------------
// z = (x − μ) / σ over rolling window; zero-division guarded.
timeseries oiM = sma(oi, oiZLen)
timeseries oiSD = stddev(oi, oiZLen)
timeseries oiZ_raw = oiSD > 0 ? (oi - oiM) / oiSD : 0.0
timeseries frM = sma(drift, frZLen)
timeseries frSD = stddev(drift, frZLen)
timeseries frZ_raw = frSD > 0 ? (drift - frM) / frSD : 0.0
// Optional EMA smoothing per component
timeseries oiZ = oiZSmooth ? ema(oiZ_raw, oiZSmoothLen) : oiZ_raw
timeseries frZ = frZSmooth ? ema(frZ_raw, frZSmoothLen) : frZ_raw
// ---------------------------------------------------------------------------
// Weighted Composite Score
// ---------------------------------------------------------------------------
// Weighted sum preserving sign directionality: OI z-score indicates positioning
// magnitude; funding z-score indicates directional sentiment. The composite
// blends both into a single crowding gauge.
//
// Normalization: weights are renormalized so w_OI + w_FR = 1.0 always.
var wSum = wOI + wFR
var wOI_norm = wSum > 0 ? wOI / wSum : 0.5
var wFR_norm = wSum > 0 ? wFR / wSum : 0.5
// Signed composite: positive = long crowding, negative = short crowding
timeseries composite_raw = wOI_norm * oiZ + wFR_norm * frZ
timeseries score = compositeSmooth ? ema(composite_raw, compositeSmoothLen) : composite_raw
// ---------------------------------------------------------------------------
// Regime Detection (Baker & Wurgler 2006 sentiment extremes + Brunnermeier 2005)
// ---------------------------------------------------------------------------
// Three-regime segmentation:
// Crowded Long: score ≥ bandHi
// Neutral: bandLo < score < bandHi
// Crowded Short: score ≤ bandLo
//
// Extreme regime overlays:
// Extreme Long: score ≥ extremeHi
// Extreme Short: score ≤ extremeLo
var regime = 0 // 0 = neutral, 1 = crowded long, -1 = crowded short
var extremeRegime = 0 // 0 = normal, 1 = extreme long, -1 = extreme short
if (score >= bandHi) {
regime = 1
} else if (score <= bandLo) {
regime = -1
}
if (score >= extremeHi) {
extremeRegime = 1
} else if (score <= extremeLo) {
extremeRegime = -1
}
// Regime color index: 0 = long, 1 = short, 2 = neutral
var regimeColorIdx = regime == 1 ? 0 : (regime == -1 ? 1 : 2)
// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts for
// anchoring and diagnostics.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static extremeLongCount = 0
static extremeShortCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (score > sessionHighScore) {
sessionHighScore = score
}
if (score < sessionLowScore) {
sessionLowScore = score
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeLongCount = extremeLongCount + 1
} else if (extremeRegime == -1) {
extremeShortCount = extremeShortCount + 1
}
}
// ---------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Histogram, Line, Fill, Shape, HLine)
// ---------------------------------------------------------------------------
// Horizontal guide lines — zero line and configurable threshold zones
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=bandHi, color=opacity(longColor, 30), width=1)
hline(value=bandLo, color=opacity(shortColor, 30), width=1)
hline(value=extremeHi, color=opacity(extremeLongColor, 20), width=1)
hline(value=extremeLo, color=opacity(extremeShortColor, 20), width=1)
}
// Raw composite score as histogram bars (regime-colored)
if (showRawBars) {
plotBar(
value=score,
colors=[longColor, shortColor, neutralColor],
width=1,
colorIndex=regimeColorIdx,
label=["Crowding Score"],
desc=["Weighted composite z-score of OI + funding; positive=long crowding, negative=short crowding"]
)
}
// Smoothed composite line with regime-coded fill
plotLine(
value=score,
width=2,
colors=[longColor, shortColor, neutralColor],
colorIndex=regimeColorIdx,
label=["Crowding Score (Line)"],
desc=["EMA-smoothed weighted composite z-score. Regime: long/short/neutral."],
fill=showFill
)
// Individual z-score components (optional, for granular analysis)
if (showComponents) {
plotLine(
value=oiZ,
width=1,
colors=[opacity(longColor, 50)],
label=["OI Z-Score"],
desc=["Rolling z-score of open interest (positioning magnitude)"]
)
plotLine(
value=frZ,
width=1,
colors=[opacity(shortColor, 50)],
label=["Funding Z-Score"],
desc=["Rolling z-score of funding proxy (signed price drift)"]
)
}
// Extreme-event shape markers (Amberdata 2026 thresholds)
if (showShapes) {
var crossUp = score >= bandHi && !isnan(score[1]) && score[1] < bandHi
var crossDn = score <= bandLo && !isnan(score[1]) && score[1] > bandLo
var extremeUp = score >= extremeHi && !isnan(score[1]) && score[1] < extremeHi
var extremeDn = score <= extremeLo && !isnan(score[1]) && score[1] > extremeLo
if (crossUp) {
plotShape(
value=score,
shape="triangleup",
color=longColor,
width=3,
label=["Crowded Long"],
desc=["Composite score crossed into crowded long regime (>+2σ) — potential reversal zone"]
)
}
if (crossDn) {
plotShape(
value=score,
shape="triangledown",
color=shortColor,
width=3,
label=["Crowded Short"],
desc=["Composite score crossed into crowded short regime (<−2σ) — potential squeeze zone"]
)
}
if (extremeUp) {
plotShape(
value=score,
shape="diamond",
color=extremeLongColor,
width=4,
label=["Extreme Long"],
desc=["Extreme long crowding detected — elevated squeeze risk per Brunnermeier & Pedersen (2005)"]
)
}
if (extremeDn) {
plotShape(
value=score,
shape="diamond",
color=extremeShortColor,
width=4,
label=["Extreme Short"],
desc=["Extreme short crowding detected — elevated correction risk per Baker & Wurgler (2006)"]
)
}
}