Perfected FlowScript
OI Delta / Price Delta
OI Delta vs Price Delta — Perfected Edition is indexed as 186_oi_delta_price_delta.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.1 KB
Lines
329
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull Pressure
line 243:5
Trigger
(showShapes && extremeBull)
Value
extremeThreshold
Deps
extremeBull:var, showShapes:input
Extreme Bear Pressure
line 253:5
Trigger
(showShapes && extremeBear)
Value
-extremeThreshold
Deps
extremeBear:var, showShapes:input
Bull Div
line 265:5
Trigger
(showShapes && bullishDiv)
Value
ratioZ
Deps
bullishDiv:var, showShapes:input
Bear Div
line 276:5
Trigger
(showShapes && bearishDiv)
Value
ratioZ
Deps
bearishDiv:var, showShapes:input
186_oi_delta_price_delta.flowscript
source path: kscripts/perfected/186_oi_delta_price_delta.flowscript · sha256:f7e12529cd1549a66e1648086b5cf2d759fc5475c9aabff2c81a468c0ec7e237
//@version=2
// ============================================================================
// OI Delta vs Price Delta — Perfected Edition
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #oi, #delta, #positioning, #regime, #divergence
//
// This indicator measures how aggressively open interest expands or contracts
// relative to actual price movement, answering the question: "For every unit of
// price movement, how much new positioning is being added or removed?" It goes
// beyond a simple ratio by adding z-score standardisation, divergence detection
// (OI and price disagreeing), regime classification, and visual alerts for
// extreme positioning pressure.
//
// Academic foundation (exact papers & formulas):
// 1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts", Journal of Financial Economics,
// 38(2), 187–213. Higher OI predicts future volatility and signals greater
// information flow; OI change is a direct proxy for positioning pressure.
// DOI: https://doi.org/10.1016/0304-405X(94)00808-W
//
// 2. Christensen, Krogstrup, Kwan & Lustig (2017), "Financialization in Commodity
// Markets". Citing Hong & Yogo (2012), regressing futures returns on
// aggregate OI yields a significantly positive coefficient — open interest
// predicts returns at the commodity level. Validates OI/price ratio as a
// predictive positioning metric.
//
// 3. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies, 22(6), 2201–2238. Liquidity and funding are
// mutually reinforcing; when OI expands faster than price it signals fresh
// leverage and trend participation, while OI contraction can flag forced
// deleveraging. The paper's "liquidity spiral" framework directly maps
// to the indicator's regime detection.
// DOI: https://doi.org/10.1093/rfs/hhp061
//
// 4. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
// 53(6), 1315–1335. p_t = p_{t−1} + λ·OFI_t + noise. Kyle's λ links
// order-flow intensity to price impact; analogous λ_OI links OI change to
// price change magnitude.
// DOI: https://doi.org/10.2307/1913210
//
// 5. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// Journal of Financial Econometrics, 12(1), 47–88. OFI linearly predicts
// short-term price changes; slope inversely proportional to depth. When OI
// delta exceeds price delta (high ratio), the market is shallow — small
// flows move price disproportionately.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
// ============================================================================
define(
title="OI Delta vs Price Delta — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var oiSymbol = input(name="oiSymbol", type="string", defaultValue="BTCUSDT", label="OI Symbol", group="Data Sources")
var oiExchange = input(name="oiExchange", type="string", defaultValue="BINANCE_FUTURES", label="OI Exchange", group="Data Sources")
// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=10, label="Ratio Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="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 corrLen = input(name="corrLen", type="number", defaultValue=20, label="Correlation Lookback", constraints={min: 5, max: 100, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Regime Threshold", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Computation")
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=3.0, label="Extreme Z-Score Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")
// -- Display --
var showRatioZ = input(name="showRatioZ", type="boolean", defaultValue=true, label="Show Ratio Z-Score", group="Display")
var showCorrelation = input(name="showCorrelation", type="boolean", defaultValue=true, label="Show OI-Price Correlation", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Histogram", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Momentum Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Alert Shapes", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Summary Table", group="Display")
// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish / Positive Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish / Negative Color", group="Colors")
var divBullColor = input(name="divBullColor", type="color", defaultValue="#00e676", label="Bullish Divergence Color", group="Colors")
var divBearColor = input(name="divBearColor", type="color", defaultValue="#ff5252", label="Bearish Divergence Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var corrColor = input(name="corrColor", type="color", defaultValue="#ffca28", label="Correlation Line Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=oiSymbol, exchange=oiExchange)
timeseries priceTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(oiTS.close[0]) || isnan(priceTS.close[0]) || isnan(priceTS.close[1])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Raw deltas --
timeseries dOI = oiTS.close - oiTS.close[1]
timeseries dPx = priceTS.close - priceTS.close[1]
// -- 3.2 Raw ratio (OI delta per unit price delta) — guard against zero price change --
// Positive ratio: OI expanding faster than price moving up (fresh longs building)
// Negative ratio: OI contracting while price rises (shorts covering, deleveraging)
timeseries ratioRaw = (math.abs(dPx) > 0) ? (dOI / math.abs(dPx)) : 0
// -- 3.3 Smooth the ratio with SMA --
timeseries ratioSmooth = sma(source=ratioRaw, period=smoothLen)
// -- 3.4 Z-score standardisation (rolling window, mean-reverting) --
// Z_t = (ratio_t − μ_t) / σ_t; denominator guarded against zero
timeseries ratioMean = sma(source=ratioSmooth, period=zWindow)
timeseries ratioStd = stdev(source=ratioSmooth, period=zWindow)
timeseries ratioZ = (ratioStd > 0) ? (ratioSmooth - ratioMean) / ratioStd : 0
// -- 3.5 Rolling correlation between OI delta and price delta --
// Positive correlation: OI and price moving together (healthy trend participation)
// Negative correlation: OI and price moving opposite (potential reversal / divergence)
timeseries corrOI_Px = correlation(sourceX=dOI, sourceY=dPx, period=corrLen)
// -- 3.6 Divergence detection: OI and price disagree --
// Bullish divergence: price falling but OI rising (accumulation under the surface)
// Bearish divergence: price rising but OI falling (distribution, weak participation)
timeseries pxDown = priceTS.close < priceTS.close[1]
timeseries pxUp = priceTS.close > priceTS.close[1]
timeseries oiUp = dOI > 0
timeseries oiDown = dOI < 0
var bullishDiv = pxDown && oiUp && (ratioZ > divThreshold)
var bearishDiv = pxUp && oiDown && (ratioZ < -divThreshold)
// -- 3.7 Extreme readings (statistical outliers) --
var extremeBull = ratioZ > extremeThreshold
var extremeBear = ratioZ < -extremeThreshold
// -- 3.8 Regime classification --
// High positive Z: aggressive positioning building (fresh leverage)
// High negative Z: positioning unwinding (deleveraging, stops)
// Neutral: normal positioning pressure
var regimeBull = ratioZ > divThreshold
var regimeBear = ratioZ < -divThreshold
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)
// -- 3.9 Momentum (rate of change of z-score) --
timeseries zMom = ratioZ - ratioZ[1]
// -- 3.10 Zero-line helper --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. STATIC STATE TRACKING — regime persistence, peak detection
// ---------------------------------------------------------------------------
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static maxBullZ = 0.0
static maxBearZ = 0.0
static lastDivBar = 0
if (regimeBull) {
bullBars = bullBars + 1
bearBars = 0
lastRegime = 1
if (ratioZ > maxBullZ) {
maxBullZ = ratioZ
}
} else if (regimeBear) {
bearBars = bearBars + 1
bullBars = 0
lastRegime = -1
if (ratioZ < maxBearZ) {
maxBearZ = ratioZ
}
} else {
bullBars = 0
bearBars = 0
maxBullZ = 0.0
maxBearZ = 0.0
}
// ---------------------------------------------------------------------------
// 5. VISUALIZATION
// ---------------------------------------------------------------------------
// 5.1 Ratio Z-Score (regime-colored line)
if (showRatioZ) {
plotLine(
value=ratioZ,
width=2,
colors=[regimeColor],
label=["OI/Price Z-Score"],
desc=["Standardised OI-delta/price-delta ratio; positive = fresh positioning, negative = unwinding"]
)
}
// 5.2 Correlation line (secondary visual)
if (showCorrelation) {
plotLine(
value=corrOI_Px,
width=1,
colors=[corrColor],
label=["OI-Price Correlation"],
desc=["Rolling correlation between OI change and price change; +1 = aligned, -1 = divergent"]
)
}
// 5.3 Divergence histogram (color-coded by regime)
if (showDivergence) {
timeseries divColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
plotLine(
value=[ratioZ, zeroLine],
width=2,
colors=[upColor, dnColor, neutralColor],
colorIndex=divColorIdx,
fill=true,
label=["Divergence"],
desc=["OI/Price Z-score filled histogram; colour-coded by regime threshold"]
)
}
// 5.4 Momentum histogram (change in z-score)
if (showHistogram) {
var histBull = zMom >= 0
plotBar(
value=zMom,
colors=[transparency(upColor, 60), transparency(dnColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Z Momentum"],
desc=["Rate of change of OI/Price Z-score; positive = pressure building, negative = easing"]
)
}
// 5.5 Extreme divergence shapes (statistical outliers)
if (showShapes && extremeBull) {
plotShape(
value=extremeThreshold,
shape="triangleup",
colorIndex=divBullColor,
width=3,
label=["Extreme Bull Pressure"],
desc=["OI expanding aggressively relative to price; potential short squeeze / fresh leverage"]
)
}
if (showShapes && extremeBear) {
plotShape(
value=-extremeThreshold,
shape="triangledown",
colorIndex=divBearColor,
width=3,
label=["Extreme Bear Pressure"],
desc=["OI contracting sharply relative to price; potential long squeeze / forced deleveraging"]
)
}
// 5.6 Divergence shapes (price/OI disagreement)
if (showShapes && bullishDiv) {
plotShape(
value=ratioZ,
shape="arrowup",
colorIndex=divBullColor,
width=2,
label=["Bull Div"],
desc=["Price falling but OI rising: accumulation under the surface (bullish divergence)"]
)
lastDivBar = 1
}
if (showShapes && bearishDiv) {
plotShape(
value=ratioZ,
shape="arrowdown",
colorIndex=divBearColor,
width=2,
label=["Bear Div"],
desc=["Price rising but OI falling: distribution, weak participation (bearish divergence)"]
)
lastDivBar = -1
}
// 5.7 Reference thresholds
hline(value=0, color="#ffffff30", width=1)
hline(value=divThreshold, color=transparency(upColor, 70), width=1)
hline(value=-divThreshold, color=transparency(dnColor, 70), width=1)
hline(value=extremeThreshold, color=transparency(upColor, 50), width=1)
hline(value=-extremeThreshold, color=transparency(dnColor, 50), width=1)
// 5.8 Correlation reference lines
hline(value=0.5, color=transparency(corrColor, 80), width=1)
hline(value=-0.5, color=transparency(corrColor, 80), width=1)
// ---------------------------------------------------------------------------
// 6. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regimeBull ? "BULLISH PRESSURE" : (regimeBear ? "BEARISH PRESSURE" : "NEUTRAL")
var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : neutralColor)
plotTable(
data=[
["OI Delta / Price Delta", regimeText],
["Z-Score", ratioZ[0]],
["Correlation", corrOI_Px[0]],
["Momentum", zMom[0]],
["Bull Bars", bullBars],
["Bear Bars", bearBars],
["Max Bull Z", maxBullZ],
["Max Bear Z", maxBearZ]
],
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
)
}