Perfected FlowScript
oi_z_robust2
OI Z-Score Robust v2 — Perfected Edition is indexed as 355_oi_z_robust2.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
17.7 KB
Lines
595
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Cross Up
line 476:9
Trigger
(showShapes) && (crossUp)
Value
signal
Deps
crossUp:var, showShapes:input
Cross Down
line 486:9
Trigger
(showShapes) && (crossDown)
Value
signal
Deps
crossDown:var, showShapes:input
Extreme Bull
line 496:9
Trigger
(showShapes) && (extremeBullEntry)
Value
oiZSmooth
Deps
extremeBullEntry:var, showShapes:input
Extreme Bear
line 506:9
Trigger
(showShapes) && (extremeBearEntry)
Value
oiZSmooth
Deps
extremeBearEntry:var, showShapes:input
Bull Div
line 516:9
Trigger
(showShapes) && (divBullEntry && !extremeBullEntry)
Value
oiZSmooth
Deps
divBullEntry:var, extremeBullEntry:var, showShapes:input
Bear Div
line 526:9
Trigger
(showShapes) && (divBearEntry && !extremeBearEntry)
Value
oiZSmooth
Deps
divBearEntry:var, extremeBearEntry:var, showShapes:input
Zero Cross +
line 536:9
Trigger
(showShapes) && (zeroCrossUp)
Value
0
Deps
showShapes:input, zeroCrossUp:var
Zero Cross -
line 546:9
Trigger
(showShapes) && (zeroCrossDown)
Value
0
Deps
showShapes:input, zeroCrossDown:var
355_oi_z_robust2.flowscript
source path: kscripts/perfected/355_oi_z_robust2.flowscript · sha256:afe13a6cb539197061f0498279e5c26799ea2acad96e1983eab26dcd78a711f2
//@version=2
// ============================================================================
// OI Z-Score Robust v2 — Perfected Edition
// Author: M (@Muhammad Dinaev) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #oi_z_robust2, #open_interest, #robust_statistics, #zscore
//
// Production-quality robust Open Interest z-score indicator using median and
// Median Absolute Deviation (MAD) with configurable consistency constant.
// Adds Wilder-smoothed overlay, dynamic volatility-adjusted thresholds,
// multi-regime color coding, fill areas, momentum histogram, and shape alerts.
//
// Research papers underpinning this design:
// 1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
// Basis and Open Interest in Futures Contracts": foundational OI-volatility
// link. OI levels proxy for information flow and price discovery.
// 2. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// z-score normalization framework z̄ₜ = (zₜ − μz) / σz; robust variant uses
// median / MAD to suppress outlier sensitivity.
// 3. 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.
// 4. Hampel (1974), "The Influence Curve and its Role in Robust Estimation":
// MAD scaled by 1.4826 yields a consistent estimator of σ for normal data.
// Underpins the robustConst × MAD → σ equivalence.
// ============================================================================
define(
title="OI Z-Score Robust v2 — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var symbol = input(
name="symbol",
type="string",
defaultValue="BTCUSDT",
label="Symbol",
group="Data Sources"
)
var exchange = input(
name="exchange",
type="string",
defaultValue="BINANCE_FUTURES",
label="Exchange",
group="Data Sources"
)
// -- Robust Statistics --
var lookback = input(
name="lookback",
type="number",
defaultValue=30,
label="Robust Lookback (bars)",
constraints={min: 10, max: 200, step: 5},
group="Robust Statistics"
)
var robustConst = input(
name="robustConst",
type="number",
defaultValue=1.4826,
label="MAD→σ Consistency Constant",
constraints={min: 1.0, max: 3.0, step: 0.1},
group="Robust Statistics"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=5,
label="Wilder Smoothing Length (RMA)",
constraints={min: 1, max: 20, step: 1},
group="Robust Statistics"
)
var emaSmoothLen = input(
name="emaSmoothLen",
type="number",
defaultValue=3,
label="EMA Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Robust Statistics"
)
// -- Thresholds --
var divThreshold = input(
name="divThreshold",
type="number",
defaultValue=2.0,
label="Divergence Threshold (±σ)",
constraints={min: 0.5, max: 4.0, step: 0.5},
group="Thresholds"
)
var extremeThreshold = input(
name="extremeThreshold",
type="number",
defaultValue=3.0,
label="Extreme Divergence Threshold (±σ)",
constraints={min: 2.0, max: 6.0, step: 0.5},
group="Thresholds"
)
var useDynamic = input(
name="useDynamic",
type="boolean",
defaultValue=false,
label="Dynamic Thresholds (volatility-adjusted)",
group="Thresholds"
)
var volLookback = input(
name="volLookback",
type="number",
defaultValue=20,
label="Volatility Lookback",
constraints={min: 5, max: 100, step: 1},
group="Thresholds"
)
var volMultiplier = input(
name="volMultiplier",
type="number",
defaultValue=1.0,
label="Volatility Multiplier",
constraints={min: 0.5, max: 3.0, step: 0.1},
group="Thresholds"
)
// -- Signal --
var signalLen = input(
name="signalLen",
type="number",
defaultValue=14,
label="Signal SMA Length",
constraints={min: 2, max: 50, step: 1},
group="Signal"
)
// -- Display --
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Robust Z-Score Line",
group="Display"
)
var showRma = input(
name="showRma",
type="boolean",
defaultValue=true,
label="Show Wilder RMA Line",
group="Display"
)
var showEma = input(
name="showEma",
type="boolean",
defaultValue=true,
label="Show EMA Line",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal SMA",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Z-Score vs Signal Fill",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
var showRawDev = input(
name="showRawDev",
type="boolean",
defaultValue=false,
label="Show Raw OI Deviation",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Alert Shapes",
group="Display"
)
// -- Colors --
var zColor = input(
name="zColor",
type="color",
defaultValue="#26c6da",
label="Z-Score Color",
group="Colors"
)
var rmaColor = input(
name="rmaColor",
type="color",
defaultValue="#ffeb3b",
label="RMA Color",
group="Colors"
)
var emaColor = input(
name="emaColor",
type="color",
defaultValue="#ffffff",
label="EMA Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bull Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bear Color",
group="Colors"
)
var signalColor = input(
name="signalColor",
type="color",
defaultValue="#9e9e9e",
label="Signal 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="#d50000",
label="Extreme Bear Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#78909c",
label="Neutral Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries oi = open_interest(symbol=symbol, exchange=exchange)
// Halt until OI feed has loaded to avoid NaN propagation
if (isnan(oi.close[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. ROBUST STATISTICS — Median + MAD z-score
// ---------------------------------------------------------------------------
// We approximate the rolling median with SMA (the engine's stable central
// tendency estimator) and compute MAD as SMA(|x − median|). The robustConst
// scales MAD to a consistent σ estimator per Hampel (1974).
timeseries oiMedian = sma(oi.close, lookback)
timeseries oiDev = math.abs(oi.close - oiMedian)
timeseries oiMad = sma(oiDev, lookback)
// Guard: if MAD is effectively zero, emit 0 to prevent division-by-zero
timeseries oiZ = (oiMad * robustConst > 0) ? (oi.close - oiMedian) / (oiMad * robustConst) : 0
// Smoothing variants
timeseries oiZRma = rma(oiZ, smoothLen)
timeseries oiZEma = ema(oiZ, emaSmoothLen)
// Primary smoothed series for regime logic (Wilder RMA as default)
timeseries oiZSmooth = oiZRma
// ---------------------------------------------------------------------------
// 4. SIGNAL & MOMENTUM
// ---------------------------------------------------------------------------
timeseries signal = sma(oiZSmooth, signalLen)
timeseries hist = oiZSmooth - signal
// ---------------------------------------------------------------------------
// 5. DYNAMIC THRESHOLDS
// ---------------------------------------------------------------------------
// Adjust divergence / extreme bands by rolling standard deviation of the
// smoothed z-score itself. This makes the indicator self-adaptive.
timeseries zVol = stddev(oiZSmooth, volLookback)
var dynDiv = useDynamic ? math.max(0.5, divThreshold + zVol * volMultiplier) : divThreshold
var dynExtreme = useDynamic ? math.max(1.5, extremeThreshold + zVol * volMultiplier * 1.5) : extremeThreshold
// Guard: ensure dynamic bands never invert or collapse
if (dynExtreme <= dynDiv) {
dynExtreme = divThreshold + 1.0
dynDiv = divThreshold
}
// ---------------------------------------------------------------------------
// 6. REGIME DETECTION
// ---------------------------------------------------------------------------
// Four-tier regime: extreme bull, bull, neutral, bear, extreme bear
// Based on smoothed z-score position relative to dynamic thresholds.
var extremeBull = oiZSmooth > dynExtreme
var bullRegime = oiZSmooth > dynDiv && !extremeBull
var extremeBear = oiZSmooth < -dynExtreme
var bearRegime = oiZSmooth < -dynDiv && !extremeBear
var neutralRegime = !extremeBull && !bullRegime && !extremeBear && !bearRegime
var regColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))
// ---------------------------------------------------------------------------
// 7. STATIC TRACKING — Consecutive regime bars for context-aware alerting
// ---------------------------------------------------------------------------
static lastRegime = 0
static divBullBars = 0
static divBearBars = 0
static extremeBullBars = 0
static extremeBearBars = 0
if (extremeBull) {
extremeBullBars = extremeBullBars + 1
extremeBearBars = 0
lastRegime = 2
} else if (bullRegime) {
divBullBars = divBullBars + 1
divBearBars = 0
extremeBearBars = 0
lastRegime = 1
} else if (extremeBear) {
extremeBearBars = extremeBearBars + 1
extremeBullBars = 0
lastRegime = -2
} else if (bearRegime) {
divBearBars = divBearBars + 1
divBullBars = 0
extremeBullBars = 0
lastRegime = -1
} else {
divBullBars = 0
divBearBars = 0
extremeBullBars = 0
extremeBearBars = 0
lastRegime = 0
}
// ---------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// ---------------------------------------------------------------------------
var crossUp = oiZSmooth > signal && oiZSmooth[1] <= signal[1]
var crossDown = oiZSmooth < signal && oiZSmooth[1] >= signal[1]
var extremeBullEntry = extremeBull && !extremeBull[1]
var extremeBearEntry = extremeBear && !extremeBear[1]
var divBullEntry = bullRegime && !bullRegime[1]
var divBearEntry = bearRegime && !bearRegime[1]
var zeroCrossUp = oiZSmooth > 0 && oiZSmooth[1] <= 0
var zeroCrossDown = oiZSmooth < 0 && oiZSmooth[1] >= 0
// ---------------------------------------------------------------------------
// 9. PLOTTING
// ---------------------------------------------------------------------------
// -- Midline & Thresholds --
hline(value=0, color="#ffffff20", width=1)
if (showZScore || showRma || showEma) {
hline(value=dynDiv, color=transparency(bullColor, 60), width=1)
hline(value=-dynDiv, color=transparency(bearColor, 60), width=1)
hline(value=dynExtreme, color=transparency(extremeBullColor, 50), width=1)
hline(value=-dynExtreme, color=transparency(extremeBearColor, 50), width=1)
}
// -- Robust Z-Score (regime-colored) --
if (showZScore) {
plotLine(
value=oiZSmooth,
width=2,
colors=[regColor],
label=["OI Z Robust v2"],
desc=["Robust OI z-score smoothed (median/MAD-based, adaptive regime-colored)"]
)
}
// -- Wilder RMA overlay --
if (showRma) {
plotLine(
value=oiZRma,
width=1,
colors=[rmaColor],
label=["OI Z (RMA)"],
desc=["Wilder-smoothed robust OI z-score (" + smoothLen + ")"]
)
}
// -- EMA overlay --
if (showEma) {
plotLine(
value=oiZEma,
width=1,
colors=[emaColor],
label=["OI Z (EMA)"],
desc=["EMA-smoothed robust OI z-score (" + emaSmoothLen + ")"]
)
}
// -- Signal SMA --
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=[signalColor],
label=["Signal SMA"],
desc=["SMA signal of robust OI z-score (" + signalLen + ")"]
)
}
// -- Fill between z-score and signal --
if (showFill) {
var fillBull = oiZSmooth > signal
plotLine(
value=[oiZSmooth, signal],
width=1,
colors=[transparency(bullColor, 25), transparency(bearColor, 25)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["OI Z", "Signal"],
desc=["Fill between robust z-score and signal SMA"]
)
}
// -- Momentum Histogram --
if (showHistogram) {
var histBull = hist >= 0
plotBar(
value=hist,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Z-Signal Momentum"],
desc=["Histogram of robust z-score minus signal SMA"]
)
}
// -- Raw OI Deviation (optional) --
if (showRawDev) {
plotBar(
value=oi.close - oiMedian,
colors=[transparency(zColor, 40)],
width=1,
label=["Raw Deviation"],
desc=["Raw OI deviation from rolling median (auxiliary)"]
)
}
// -- Shape Markers --
if (showShapes) {
if (crossUp) {
plotShape(
value=signal,
shape="circle",
colorIndex=bullColor,
width=2,
label=["Cross Up"],
desc=["Robust OI z-score crossed above signal SMA"]
)
}
if (crossDown) {
plotShape(
value=signal,
shape="circle",
colorIndex=bearColor,
width=2,
label=["Cross Down"],
desc=["Robust OI z-score crossed below signal SMA"]
)
}
if (extremeBullEntry) {
plotShape(
value=oiZSmooth,
shape="triangleup",
colorIndex=extremeBullColor,
width=3,
label=["Extreme Bull"],
desc=["Robust OI z-score entered extreme bullish regime (>" + dynExtreme + ") — potential euphoria / crowded longs"]
)
}
if (extremeBearEntry) {
plotShape(
value=oiZSmooth,
shape="triangledown",
colorIndex=extremeBearColor,
width=3,
label=["Extreme Bear"],
desc=["Robust OI z-score entered extreme bearish regime (<" + -dynExtreme + ") — potential capitulation / crowded shorts"]
)
}
if (divBullEntry && !extremeBullEntry) {
plotShape(
value=oiZSmooth,
shape="arrowup",
colorIndex=bullColor,
width=2,
label=["Bull Div"],
desc=["Robust OI z-score crossed above divergence threshold (" + dynDiv + ")"]
)
}
if (divBearEntry && !extremeBearEntry) {
plotShape(
value=oiZSmooth,
shape="arrowdown",
colorIndex=bearColor,
width=2,
label=["Bear Div"],
desc=["Robust OI z-score crossed below divergence threshold (" + -dynDiv + ")"]
)
}
if (zeroCrossUp) {
plotShape(
value=0,
shape="diamond",
colorIndex=bullColor,
width=2,
label=["Zero Cross +"],
desc=["Robust OI z-score crossed above zero — participation turning positive"]
)
}
if (zeroCrossDown) {
plotShape(
value=0,
shape="diamond",
colorIndex=bearColor,
width=2,
label=["Zero Cross -"],
desc=["Robust OI z-score crossed below zero — participation turning negative"]
)
}
}
// ---------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = extremeBull ? "EXTREME BULL" : (bullRegime ? "BULL" : (extremeBear ? "EXTREME BEAR" : (bearRegime ? "BEAR" : "NEUTRAL")))
var regimeTextColor = extremeBull ? extremeBullColor : (bullRegime ? bullColor : (extremeBear ? extremeBearColor : (bearRegime ? bearColor : neutralColor)))
var divLabel = useDynamic ? "Dyn Divergence: ±" + dynDiv : "Static Divergence: ±" + divThreshold
var extLabel = useDynamic ? "Dyn Extreme: ±" + dynExtreme : "Static Extreme: ±" + extremeThreshold
plotTable(
data=[
["OI Z Robust v2 — Perfected", regimeText],
["OI Z-Score", oiZSmooth[0]],
["RMA", oiZRma[0]],
["EMA", oiZEma[0]],
["Signal", signal[0]],
["Momentum", hist[0]],
["Robust σ (MAD×" + robustConst + ")", (oiMad[0] * robustConst)],
["Raw OI", oi.close[0]],
[divLabel, extLabel],
["Bull Bars", divBullBars],
["Bear Bars", divBearBars],
["Extreme Bull Bars", extremeBullBars],
["Extreme Bear Bars", extremeBearBars]
],
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
)
}