Perfected FlowScript
Open Interest Delta (Fork)a
Open Interest Delta (Fork A) — Perfected Edition is indexed as 266_open_interest_delta_fork_a.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.6 KB
Lines
358
Native Signal Candidates
5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme +OI
line 267:9
Trigger
(showShapes) && (extremeUpEvent)
Value
deltaSmooth
Deps
extremeUpEvent:var, showShapes:input
Extreme -OI
line 277:9
Trigger
(showShapes) && (extremeDnEvent)
Value
deltaSmooth
Deps
extremeDnEvent:var, showShapes:input
High +OI
line 287:9
Trigger
(showShapes) && (highUpEvent)
Value
deltaSmooth
Deps
highUpEvent:var, showShapes:input
High -OI
line 297:9
Trigger
(showShapes) && (highDnEvent)
Value
deltaSmooth
Deps
highDnEvent:var, showShapes:input
Unlabeled shape
line 310:5
Trigger
(showRegime && isLastBar)
Value
deltaSmooth
Deps
isLastBar:builtin, showRegime:input
266_open_interest_delta_fork_a.flowscript
source path: kscripts/perfected/266_open_interest_delta_fork_a.flowscript · sha256:9962d573cb0b4b62992cb47ef291b4832c2dc2f28805189fb1dd428eaa675161
//@version=2
// ============================================================================
// Open Interest Delta (Fork A) — Perfected Edition
// Author: Tzen Yang (@Tzen Yang) — Perfected by kScript_Perfection Engineer
// Tags: CORE, #openinterest, #delta, #zscore, #regime, #accumulation, #distribution
//
// Production-grade Open Interest delta analyzer with z-score normalization,
// volatility regime detection, color-coded histograms, and statistical
// extreme-event markers. Tracks bar-to-bar OI change, computes rolling
// z-score for significance testing, and classifies market regimes as
// accumulation (rising OI + rising price), distribution (rising OI + falling
// price), short-covering (falling OI + rising price), or long-liquidation
// (falling OI + falling price). Full static state machine for event tracking.
//
// Academic foundations:
// - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts" (J. Finance 50(1):281-300).
// Key finding: unexpected OI changes amplify volatility.
// Formula: σ_t² = α + β₁·|ΔOI_t| + β₂·|ΔBasis_t| + ε_t.
// - Yang Xu et al. (2021), "ARIMA-GJR-GARCH" (Complexity). Unexpected OI
// shocks amplify volatility; GARCH terms significant at 1% level.
// - Bessembinder & Seguin (1993), "Price Volatility, Trading Volume, and
// Market Depth" (Rev. Financial Studies). OI as proxy for speculative
// participation; OI increases → deeper markets, lower volatility.
// - Working (1960), "Note on the Correlation of First Differences of Averages
// in a Random Chain". OI change as predictor of market participation shifts.
// - Kyle (1985), "Continuous Auctions and Insider Trading" (Econometrica).
// λ = price impact coefficient; OI delta maps to informed vs. uninformed flow.
// Informed traders increase OI when accumulating; uninformed liquidation
// decreases OI without price recovery.
// ============================================================================
define(title="Open Interest Delta (Fork A) — Perfected Edition", position="offchart", axis=true)
// === USER INPUTS ===
// --- Data Sources ---
var exchange = input(name="exchange", type="select", defaultValue="BINANCE_FUTURES",
label="Exchange", options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP", "DERIBIT", "HYPERLIQUID_FUTURES"], group="Data Sources")
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Sources")
// --- Computation ---
var usePct = input(name="usePct", type="boolean", defaultValue=false, label="Use Percent Change", group="Computation")
var maLen = input(name="maLen", type="number", defaultValue=14, label="MA Length", constraints={min: 2, max: 100, step: 1}, group="Computation")
var maType = input(name="maType", type="select", defaultValue="SMA", label="MA Type", options=["SMA", "EMA"], group="Computation")
var zLookback = input(name="zLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 5, max: 200, step: 5}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=1, label="Delta Smoothing (1=none)", constraints={min: 1, max: 20, step: 1}, group="Computation")
// --- Thresholds ---
var zExtreme = input(name="zExtreme", type="number", defaultValue=3.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 5.0, step: 0.5}, group="Thresholds")
var zHigh = input(name="zHigh", type="number", defaultValue=2.0, label="High Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Thresholds")
var zModerate = input(name="zModerate", type="number", defaultValue=1.0, label="Moderate Z-Score Threshold", constraints={min: 0.5, max: 3.0, step: 0.5}, group="Thresholds")
// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Delta Histogram", group="Display")
var showMA = input(name="showMA", type="boolean", defaultValue=true, label="Show MA Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showRegime = input(name="showRegime", type="boolean", defaultValue=true, label="Show Regime Detection", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Info Table", group="Display")
// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive / Accumulation Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative / Liquidation Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var maColor = input(name="maColor", type="color", defaultValue="#ffeb3b", label="MA Line Color", group="Colors")
var zColor = input(name="zColor", type="color", defaultValue="#00e5ff", label="Z-Score Line Color", group="Colors")
var extremeUpColor = input(name="extremeUpColor", type="color", defaultValue="#00e676", label="Extreme Positive Color", group="Colors")
var extremeDnColor = input(name="extremeDnColor", type="color", defaultValue="#ff1744", label="Extreme Negative Color", group="Colors")
// === DATA SOURCES ===
timeseries oi = open_interest(symbol=symbol, exchange=exchange)
timeseries bars = ohlcv(symbol=symbol, exchange=exchange)
timeseries oiClose = oi.close
timeseries pxClose = bars.close
// isnan guard: prevent execution before data is loaded
if (isnan(oiClose[0]) || isnan(pxClose[0])) {
return
}
// === COMPUTATION ===
// Bar-to-bar OI change (absolute or percent)
timeseries oiPrev = oiClose[1]
timeseries rawDelta = oiClose - oiPrev
timeseries deltaPct = oiPrev != 0 ? (rawDelta / oiPrev) * 100 : 0
timeseries delta = usePct ? deltaPct : rawDelta
// Smoothing (optional)
timeseries deltaSmooth = smoothLen > 1 ? ema(delta, smoothLen) : delta
// Moving average of delta
timeseries deltaMA = maType == "EMA" ? ema(deltaSmooth, maLen) : sma(deltaSmooth, maLen)
// Z-score normalization: z_t = (Δ_t − μ_t) / σ_t
// μ_t = SMA(Δ, W), σ_t = StDev(Δ, W)
timeseries deltaMean = sma(deltaSmooth, zLookback)
timeseries deltaStd = stddev(deltaSmooth, zLookback)
timeseries deltaZ = deltaStd > 0 ? (deltaSmooth - deltaMean) / deltaStd : 0
// Price change for regime classification
timeseries pxChange = pxClose - pxClose[1]
// === REGIME DETECTION (4 regimes) ===
// 1. ACCUMULATION: rising OI + rising price → new longs entering
// 2. DISTRIBUTION: rising OI + falling price → new shorts entering
// 3. SHORT-COVERING: falling OI + rising price → shorts closing
// 4. LONG-LIQUIDATION: falling OI + falling price → longs closing
var regimeAccum = deltaSmooth > 0 && pxChange > 0
var regimeDistr = deltaSmooth > 0 && pxChange < 0
var regimeShortCover = deltaSmooth < 0 && pxChange > 0
var regimeLongLiq = deltaSmooth < 0 && pxChange < 0
var regimeColor = regimeAccum ? upColor : (regimeDistr ? dnColor : (regimeShortCover ? "#ffeb3b" : (regimeLongLiq ? "#ff5252" : neutralColor)))
var regimeLabel = regimeAccum ? "ACCUMULATION" : (regimeDistr ? "DISTRIBUTION" : (regimeShortCover ? "SHORT COVERING" : (regimeLongLiq ? "LONG LIQUIDATION" : "NEUTRAL")))
// === SIGNIFICANCE LEVELS ===
var absZ = math.abs(deltaZ)
var isPositive = deltaSmooth > 0
// Color index for histogram based on sign and z-score significance
// 0=neutral, 1=moderate up, 2=high up, 3=extreme up,
// 4=moderate dn, 5=high dn, 6=extreme dn
var colorIdx = 0
if (isPositive) {
if (absZ >= zExtreme) {
colorIdx = 3
} else if (absZ >= zHigh) {
colorIdx = 2
} else if (absZ >= zModerate) {
colorIdx = 1
} else {
colorIdx = 0
}
} else {
if (absZ >= zExtreme) {
colorIdx = 6
} else if (absZ >= zHigh) {
colorIdx = 5
} else if (absZ >= zModerate) {
colorIdx = 4
} else {
colorIdx = 0
}
}
// === STATIC STATE TRACKING ===
static barCount = 0
static lastBarIndex = 0
static sessionHighDelta = -999999999999.0
static sessionLowDelta = 999999999999.0
static extremeUpCount = 0
static extremeDnCount = 0
static highUpCount = 0
static highDnCount = 0
static lastExtremeUpBar = 0
static lastExtremeDnBar = 0
static lastHighUpBar = 0
static lastHighDnBar = 0
static regimeCountAccum = 0
static regimeCountDistr = 0
static regimeCountShortCover = 0
static regimeCountLongLiq = 0
if (!isLiveUpdate) {
barCount = barCount + 1
if (deltaSmooth > sessionHighDelta) {
sessionHighDelta = deltaSmooth
}
if (deltaSmooth < sessionLowDelta) {
sessionLowDelta = deltaSmooth
}
if (absZ >= zExtreme && isPositive) {
extremeUpCount = extremeUpCount + 1
lastExtremeUpBar = barCount
} else if (absZ >= zExtreme && !isPositive) {
extremeDnCount = extremeDnCount + 1
lastExtremeDnBar = barCount
}
if (absZ >= zHigh && absZ < zExtreme && isPositive) {
highUpCount = highUpCount + 1
lastHighUpBar = barCount
} else if (absZ >= zHigh && absZ < zExtreme && !isPositive) {
highDnCount = highDnCount + 1
lastHighDnBar = barCount
}
if (regimeAccum) {
regimeCountAccum = regimeCountAccum + 1
} else if (regimeDistr) {
regimeCountDistr = regimeCountDistr + 1
} else if (regimeShortCover) {
regimeCountShortCover = regimeCountShortCover + 1
} else if (regimeLongLiq) {
regimeCountLongLiq = regimeCountLongLiq + 1
}
}
var extremeUpEvent = lastExtremeUpBar == barCount
var extremeDnEvent = lastExtremeDnBar == barCount
var highUpEvent = lastHighUpBar == barCount
var highDnEvent = lastHighDnBar == barCount
// === PLOTS ===
// Zero line
hline(value=0, color="#ffffff30", width=1)
// --- Delta Histogram (color-coded by significance) ---
if (showHistogram) {
plotBar(
value=deltaSmooth,
colors=[neutralColor, upColor, extremeUpColor, extremeUpColor, dnColor, extremeDnColor, extremeDnColor],
colorIndex=colorIdx,
width=1,
label=["OI Delta"],
desc=["Open Interest delta: bar-to-bar change. Color-coded by sign and z-score significance (Chen, Cuny & Haugen 1995)."]
)
}
// --- MA Line ---
if (showMA) {
plotLine(
value=deltaMA,
width=2,
colors=[maColor],
label=["OI Delta " + maType],
desc=["Smoothed OI delta moving average (" + maType + " " + maLen + "). Trend filter for delta direction."]
)
}
// --- Z-Score Line (secondary visualization) ---
if (showZScore) {
plotLine(
value=deltaZ,
width=2,
colors=[zColor],
label=["Z-Score"],
desc=["Z-score normalized OI delta: (Δ − μ) / σ over " + zLookback + " bars. Statistical significance filter."]
)
// Z-score reference lines
hline(value=zExtreme, color=opacity(extremeUpColor, 50), width=1)
hline(value=zHigh, color=opacity(upColor, 50), width=1)
hline(value=-zHigh, color=opacity(dnColor, 50), width=1)
hline(value=-zExtreme, color=opacity(extremeDnColor, 50), width=1)
}
// --- Regime Fill (MA vs Delta) ---
if (showRegime) {
var regimeBull = deltaSmooth > deltaMA
plotLine(
value=[deltaSmooth, deltaMA],
width=1,
colors=[opacity(upColor, 20), opacity(dnColor, 20)],
colorIndex=regimeBull ? 0 : 1,
fill=true,
label=["OI Delta", "Delta MA"],
desc=["Fill between OI delta and MA. Green = delta above MA (bullish); Red = delta below MA (bearish)."]
)
}
// --- Extreme Event Shapes ---
if (showShapes) {
if (extremeUpEvent) {
plotShape(
value=deltaSmooth,
shape="triangleup",
colorIndex=extremeUpColor,
width=3,
label=["Extreme +OI"],
desc=["Extreme positive OI delta: z-score > +" + zExtreme + ". Significant new position buildup (Chen, Cuny & Haugen 1995)."]
)
}
if (extremeDnEvent) {
plotShape(
value=deltaSmooth,
shape="triangledown",
colorIndex=extremeDnColor,
width=3,
label=["Extreme -OI"],
desc=["Extreme negative OI delta: z-score < -" + zExtreme + ". Significant position liquidation (Chen, Cuny & Haugen 1995)."]
)
}
if (highUpEvent) {
plotShape(
value=deltaSmooth,
shape="diamond",
colorIndex=upColor,
width=2,
label=["High +OI"],
desc=["High positive OI delta: z-score > +" + zHigh + ". Above-average position increase."]
)
}
if (highDnEvent) {
plotShape(
value=deltaSmooth,
shape="diamond",
colorIndex=dnColor,
width=2,
label=["High -OI"],
desc=["High negative OI delta: z-score < -" + zHigh + ". Above-average position decrease."]
)
}
}
// === REGIME LABEL (plotPriceLabel) ===
if (showRegime && isLastBar) {
plotPriceLabel(
price=deltaSmooth,
text=regimeLabel,
type="callout",
color="#ffffff",
backgroundColor=regimeColor,
size=10,
fontWeight=700
)
}
// === INFO TABLE (last bar only) ===
if (showTable && isLastBar) {
var totalBars = regimeCountAccum + regimeCountDistr + regimeCountShortCover + regimeCountLongLiq
var totalBarsSafe = totalBars > 0 ? totalBars : 1
var pctAccum = math.round((regimeCountAccum / totalBarsSafe) * 100, 2)
var pctDistr = math.round((regimeCountDistr / totalBarsSafe) * 100, 2)
var pctShortCover = math.round((regimeCountShortCover / totalBarsSafe) * 100, 2)
var pctLongLiq = math.round((regimeCountLongLiq / totalBarsSafe) * 100, 2)
plotTable(
data=[
["OI Delta (Fork A) — Perfected", regimeLabel],
["Current Delta", deltaSmooth[0]],
["Delta MA", deltaMA[0]],
["Z-Score", deltaZ[0]],
["Session High Δ", sessionHighDelta],
["Session Low Δ", sessionLowDelta],
["Extreme +Events", extremeUpCount],
["Extreme -Events", extremeDnCount],
["Accumulation %", pctAccum + "%"],
["Distribution %", pctDistr + "%"],
["Short Cover %", pctShortCover + "%"],
["Long Liq %", pctLongLiq + "%"]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=opacity("#0f172a", 40),
headerBackgroundColor=opacity("#1e293b", 40),
borderColor=opacity("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}