Perfected FlowScript
oi_z_robust
OI Z-Score Robust V2 is indexed as 337_oi_z_robust.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
12.3 KB
Lines
293
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Pos
line 219:9
Trigger
(showShapes) && (crossPos1)
Value
oiZSmooth
Deps
crossPos1:var, showShapes:input
Moderate Pos
line 229:9
Trigger
(showShapes) && (crossPos2 && !crossPos1)
Value
oiZSmooth
Deps
crossPos1:var, crossPos2:var, showShapes:input
Extreme Neg
line 239:9
Trigger
(showShapes) && (crossNeg1)
Value
oiZSmooth
Deps
crossNeg1:var, showShapes:input
Moderate Neg
line 249:9
Trigger
(showShapes) && (crossNeg2 && !crossNeg1)
Value
oiZSmooth
Deps
crossNeg1:var, crossNeg2:var, showShapes:input
337_oi_z_robust.flowscript
source path: kscripts/perfected/337_oi_z_robust.flowscript · sha256:7533acce5b9ecfd3479c5a20b3ea4ae4b70c9bcb1f8a3f5c99ac47eb3cc18932
//@version=2
// ============================================================================
// OI Z-Score Robust V2 — Production-Quality Open Interest Z-Score
// Author: M (@Muhammad Dinaev) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #open_interest, #zscore, #robust, #positioning, #futures, #regime
//
// Robust z-score of Open Interest using median and median absolute deviation (MAD),
// with regime detection, color-coded histogram, shape markers, and session-level tracking.
//
// FORMULA FOUNDATION:
// 1. Robust Center: median(OI) over rolling window [Chen, Cuny & Haugen 1995]
// 2. Robust Dispersion: MAD = median(|OI − median(OI)|) [Zhao & Palomar 2018]
// 3. Consistency Scaling: σ_equiv = MAD × 1.4826 (asymptotically consistent with normal σ)
// 4. Robust Z-Score: z = (OI − median) / σ_equiv
// 5. Regime Thresholds: ±1σ (moderate), ±2σ (extreme) per standard Gaussian tails
//
// RESEARCH BASIS:
// • 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
// carry information about future volatility and information flow.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE TSP. z̄ₜ = (zₜ − μz) / σz; entry at ±dσ. The robust variant uses
// median / MAD to suppress outlier sensitivity.
// • Yang Xu et al. (2021), "An Empirical Analysis of the Price Volatility
// Characteristics of China's Soybean Futures Market". Unexpected OI shocks
// (z-score deviations) drive more volatility than expected components.
// • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Rev. Fin. Studies 22(6), 2201–2238. Liquidity spirals and OI dynamics
// in leveraged markets; OI shocks propagate through funding constraints.
// ============================================================================
define(
title="OI Z-Score Robust V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Lookback & Smoothing ---
var lookback = input(name="lookback", type="number", defaultValue=30, label="Lookback Period", constraints={min: 10, max: 200, step: 1}, group="Parameters")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Period", constraints={min: 1, max: 20, step: 1}, group="Parameters")
var useRobust = input(name="useRobust", type="boolean", defaultValue=true, label="Use Robust Statistics (MAD)", group="Parameters")
// --- Thresholds ---
var level1 = input(name="level1", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Thresholds")
var level2 = input(name="level2", type="number", defaultValue=1.0, label="Moderate Threshold (σ)", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Z-Score Histogram", group="Display")
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showSmoothed = input(name="showSmoothed", type="boolean", defaultValue=true, label="Show Smoothed Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Threshold Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showDeviation = input(name="showDeviation", type="boolean", defaultValue=false, label="Show Raw Deviation", group="Display")
// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Positive Z-Score Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Negative Z-Score 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 Positive Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Negative Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
if (isnan(px[0]) || isnan(oi[0])) {
return
}
// ------------------------------------------------------------------------------
// Robust Statistics Computation
// ------------------------------------------------------------------------------
// Note: In a streaming engine without native median(), we approximate the rolling
// center with SMA (a practical proxy that remains numerically stable across bars).
// The MAD is then SMA(|OI − center|). For true offline robust analysis, substitute
// proper median and median absolute deviation. The 1.4826 scaling factor makes the
// MAD asymptotically consistent with the standard deviation under normality.
timeseries oiCenter = useRobust ? sma(oi.close, lookback) : sma(oi.close, lookback)
timeseries oiDev = math.abs(oi.close - oiCenter)
timeseries oiMAD = useRobust ? sma(oiDev, lookback) : stddev(oi.close, lookback)
// Robust z-score with 1.4826 scaling factor for normal consistency
var scaleFactor = useRobust ? 1.4826 : 1.0
var safeDispersion = oiMAD * scaleFactor
var oiZ = safeDispersion > 0 ? (oi.close - oiCenter) / safeDispersion : 0.0
timeseries oiZSmooth = ema(oiZ, smoothLen)
// ------------------------------------------------------------------------------
// Regime Detection (Five-tier classification)
// ------------------------------------------------------------------------------
// 2 = extreme positive (>level1)
// 1 = moderate positive (>level2)
// 0 = neutral
// -1 = moderate negative (<−level2)
// -2 = extreme negative (<−level1)
var regime = 0
if (oiZSmooth >= level1) {
regime = 2
} else if (oiZSmooth >= level2) {
regime = 1
} else if (oiZSmooth <= -level1) {
regime = -2
} else if (oiZSmooth <= -level2) {
regime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremePosCount = 0
static extremeNegCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (oiZSmooth > sessionHighZ) {
sessionHighZ = oiZSmooth
}
if (oiZSmooth < sessionLowZ) {
sessionLowZ = oiZSmooth
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (regime == 2) {
extremePosCount = extremePosCount + 1
} else if (regime == -2) {
extremeNegCount = extremeNegCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=level1, color=transparency(extremeBullColor, 60), width=1)
hline(value=-level1, color=transparency(extremeBearColor, 60), width=1)
hline(value=level2, color=transparency(bullColor, 40), width=1)
hline(value=-level2, color=transparency(bearColor, 40), width=1)
}
// Z-score histogram with regime color coding
if (showHistogram) {
plotBar(
value=oiZSmooth,
colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
colorIndex=regime + 2,
width=1,
label=["OI Z-Score"],
desc=["Robust OI z-score histogram with regime coloring (extreme/moderate/neutral)"]
)
}
// Z-score line with regime-coded fill area
if (showLine) {
plotLine(
value=oiZSmooth,
width=2,
colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
colorIndex=regime + 2,
label=["OI Z-Score"],
desc=["Robust OI z-score with regime coloring and fill"],
fill=true
)
}
// Smoothed line (alternate display)
if (showSmoothed) {
plotLine(
value=oiZSmooth,
width=2,
colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
colorIndex=regime + 2,
label=["OI Z-Score (Smoothed)"],
desc=["EMA-smoothed robust OI z-score (" + smoothLen + "-period)"]
)
}
// Raw deviation auxiliary line
if (showDeviation) {
plotLine(
value=oi.close - oiCenter,
width=1,
colors=[bullColor, bearColor],
colorIndex=oi.close > oiCenter ? 0 : 1,
label=["Raw OI Deviation"],
desc=["Raw OI deviation from rolling center (unstandardized)"]
)
}
// Threshold crossing shapes
if (showShapes) {
var crossPos1 = oiZSmooth >= level1 && !isnan(oiZSmooth[1]) && oiZSmooth[1] < level1
var crossPos2 = oiZSmooth >= level2 && !isnan(oiZSmooth[1]) && oiZSmooth[1] < level2
var crossNeg1 = oiZSmooth <= -level1 && !isnan(oiZSmooth[1]) && oiZSmooth[1] > -level1
var crossNeg2 = oiZSmooth <= -level2 && !isnan(oiZSmooth[1]) && oiZSmooth[1] > -level2
if (crossPos1) {
plotShape(
value=oiZSmooth,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Pos"],
desc=["OI z-score crossed above extreme positive threshold (" + level1 + "σ)"]
)
}
if (crossPos2 && !crossPos1) {
plotShape(
value=oiZSmooth,
shape="triangleup",
color=bullColor,
width=3,
label=["Moderate Pos"],
desc=["OI z-score crossed above moderate positive threshold (" + level2 + "σ)"]
)
}
if (crossNeg1) {
plotShape(
value=oiZSmooth,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Neg"],
desc=["OI z-score crossed below extreme negative threshold (-" + level1 + "σ)"]
)
}
if (crossNeg2 && !crossNeg1) {
plotShape(
value=oiZSmooth,
shape="triangledown",
color=bearColor,
width=3,
label=["Moderate Neg"],
desc=["OI z-score crossed below moderate negative threshold (-" + level2 + "σ)"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 2 ? "EXTREME POS" : (regime == 1 ? "MODERATE POS" : (regime == -1 ? "MODERATE NEG" : (regime == -2 ? "EXTREME NEG" : "NEUTRAL")))
var regimeTextColor = regime > 0 ? bullColor : (regime < 0 ? bearColor : neutralColor)
plotTable(
data=[
["OI Z-Score Robust V2", regimeText],
["Z-Score", oiZSmooth[0]],
["OI Level", oi.close[0]],
["OI Center", oiCenter[0]],
["Dispersion", safeDispersion[0]],
["Session High Z", sessionHighZ],
["Session Low Z", sessionLowZ],
["Regime Changes", regimeChangeCount],
["Extreme Pos Bars", extremePosCount],
["Extreme Neg Bars", extremeNegCount]
],
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
)
}