MM Flow
FlowScripts

Perfected FlowScript

oi z score star

OI Z-Score Star — Perfected Edition is indexed as 324_oi_z_score_star.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

16.1 KB

Lines

505

Native Signal Candidates

5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

5/5 guarded

Extreme High

line 418:9

Trigger

(showShapes) && (thrPenetrateUp)

Value

zScore

Deps

showShapes:input, thrPenetrateUp:var

Extreme Low

line 428:9

Trigger

(showShapes) && (thrPenetrateDn)

Value

zScore

Deps

showShapes:input, thrPenetrateDn:var

Zero Cross Up

line 438:9

Trigger

(showShapes) && (zeroCrossUp)

Value

0

Deps

showShapes:input, zeroCrossUp:var

Zero Cross Down

line 448:9

Trigger

(showShapes) && (zeroCrossDn)

Value

0

Deps

showShapes:input, zeroCrossDn:var

Star Rating

line 462:9

Trigger

(showStars && isLastBar) && (starRating >= 3)

Value

zScore

Deps

isLastBar:builtin, showStars:input, starRating:var

324_oi_z_score_star.flowscript

source path: kscripts/perfected/324_oi_z_score_star.flowscript · sha256:c92db26fa8e427d2df85df6ac68652d0de1ecb9db90a87fbd382ffda846b43d7

hash verified
//@version=2
// ============================================================================
// OI Z-Score Star — Perfected Edition
// Author: B (@buyanyjeansnecessary) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #openinterest, #zscore, #meanreversion, #regime, #positioning
//
// Production-quality Open Interest Z-Score indicator with star rating,
// multi-sigma bands, color-coded histogram, regime detection, and stateful
// extreme-tracking via static variables.
//
// Normalizes OI changes into standard deviation units to identify statistically
// significant positioning extremes. Implements ±1/2/3σ bands with fill,
// dynamic regime coloring, and a 5-star extremity rating system.
//
// Research papers underpinning this design:
//  1. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     formalizes z-score event triggers; z̄ₜ = (zₜ − μz) / σz with entry
//     thresholds at Δ = d × σz.
//  2. QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI": |Z| > 2
//     indicates statistical rarity (~95% of values within ±2σ); multi-indicator
//     confirmation recommended before mean-reversion entry.
//  3. Yang Xu et al. (2021), "ARIMA-GJR-GARCH Model for China's Soybean Futures":
//     unexpected OI changes have larger impact on price volatility than expected
//     changes; z-score directly measures "unexpectedness".
//  4. LeviathanCapital (2024), "Open Interest Delta": OI Delta maps net change
//     in OI at each price level; z-score normalization extends this by making
//     deltas comparable across instruments and time periods.
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons supports volatility-adjusted band
//     calibration for mean-reversion timing.
// ============================================================================

define(
    title="OI Z-Score Star — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Data Source ---
var symbol = input(
    name="symbol",
    type="select",
    defaultValue="BTCUSDT",
    label="OI Symbol",
    options=["BTCUSDT", "ETHUSDT", "SOLUSDT"],
    group="Data Source"
)
var exchange = input(
    name="exchange",
    type="select",
    defaultValue="BINANCE_FUTURES",
    label="Exchange",
    options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP", "DERIBIT"],
    group="Data Source"
)

// --- Z-Score Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=30,
    label="Z-Score Lookback",
    constraints={min: 5, max: 200, step: 1},
    group="Z-Score Settings"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Z-Score EMA Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score Settings"
)
var useSmooth = input(
    name="useSmooth",
    type="boolean",
    defaultValue=true,
    label="Smooth Z-Score with EMA",
    group="Z-Score Settings"
)

// --- Sigma Bands ---
var showBand1 = input(
    name="showBand1",
    type="boolean",
    defaultValue=true,
    label="Show ±1σ Band",
    group="Sigma Bands"
)
var showBand2 = input(
    name="showBand2",
    type="boolean",
    defaultValue=true,
    label="Show ±2σ Band",
    group="Sigma Bands"
)
var showBand3 = input(
    name="showBand3",
    type="boolean",
    defaultValue=true,
    label="Show ±3σ Band",
    group="Sigma Bands"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fills",
    group="Sigma Bands"
)

// --- Thresholds ---
var upperThr = input(
    name="upperThr",
    type="number",
    defaultValue=2.0,
    label="Upper Signal Threshold (z)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)
var lowerThr = input(
    name="lowerThr",
    type="number",
    defaultValue=-2.0,
    label="Lower Signal Threshold (z)",
    constraints={min: -5.0, max: -0.5, step: 0.1},
    group="Thresholds"
)
var useDynamicThr = input(
    name="useDynamicThr",
    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"
)

// --- Display ---
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Shape Markers",
    group="Display"
)
var showStars = input(
    name="showStars",
    type="boolean",
    defaultValue=true,
    label="Show Star Rating on Last Bar",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Info Table",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull / Low Extreme Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear / High Extreme Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#2962ff",
    label="Z-Score Line Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries oi = open_interest(symbol=symbol, exchange=exchange)

if (isnan(oi.close[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. Z-SCORE CALCULATION
// -----------------------------------------------------------------------------
// Canonical z-score: z = (X − μ) / σ
timeseries oiClose = oi.close
timeseries oiMean = sma(source=oiClose, period=lookback)
timeseries oiStd = stddev(source=oiClose, period=lookback)
timeseries zRaw = oiStd > 0 ? (oiClose - oiMean) / oiStd : 0.0
timeseries zScore = useSmooth ? ema(source=zRaw, period=smoothLen) : zRaw

// -----------------------------------------------------------------------------
// 4. DYNAMIC THRESHOLDS (volatility-adjusted)
// -----------------------------------------------------------------------------
// Per Poterba & Summers (1988), mean-reversion intensity varies with volatility.
// Adjust signal bands by rolling z-score standard deviation.
timeseries zVol = stddev(source=zScore, period=volLookback)
var dynUpper = useDynamicThr ? math.min(4.0, upperThr + zVol * 0.5) : upperThr
var dynLower = useDynamicThr ? math.max(-4.0, lowerThr - zVol * 0.5) : lowerThr

// Guard: ensure bands never cross
if (dynUpper <= dynLower) {
    dynUpper = 2.0
    dynLower = -2.0
}

// -----------------------------------------------------------------------------
// 5. SIGMA BANDS
// -----------------------------------------------------------------------------
// ±1/2/3σ reference bands for visual context
timeseries band1p = 1.0
timeseries band1n = -1.0
timeseries band2p = 2.0
timeseries band2n = -2.0
timeseries band3p = 3.0
timeseries band3n = -3.0

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification based on z-score position relative to bands and zero:
//   Extreme Bull: zScore < -2σ (oversold positioning, mean-reversion bullish)
//   Extreme Bear: zScore > +2σ (overbought positioning, mean-reversion bearish)
//   Bullish:      zScore < 0 and zScore < -1σ
//   Bearish:      zScore > 0 and zScore > +1σ
//   Neutral:      -1σ <= zScore <= +1σ

var regimeExtremeBull = zScore <= dynLower
var regimeExtremeBear = zScore >= dynUpper
var regimeBull = zScore < 0 && zScore < band1n
var regimeBear = zScore > 0 && zScore > band1p
var regimeNeutral = !regimeBull && !regimeBear && !regimeExtremeBull && !regimeExtremeBear

var regimeColor = regimeExtremeBull ? bullColor : (regimeExtremeBear ? bearColor : (regimeBull ? transparency(bullColor, 60) : (regimeBear ? transparency(bearColor, 60) : neutralColor)))

// -----------------------------------------------------------------------------
// 7. STAR RATING (5-star extremity system)
// -----------------------------------------------------------------------------
// Stars reflect how many σ the z-score has exceeded:
//   ★★★★★ = |z| >= 3.0  (extremely rare, < 0.3% probability)
//   ★★★★☆ = |z| >= 2.5
//   ★★★☆☆ = |z| >= 2.0
//   ★★☆☆☆ = |z| >= 1.5
//   ★☆☆☆☆ = |z| >= 1.0
//   ☆☆☆☆☆ = |z| < 1.0

var absZ = math.abs(zScore[0])
var starRating = 0
if (absZ >= 3.0) {
    starRating = 5
} else if (absZ >= 2.5) {
    starRating = 4
} else if (absZ >= 2.0) {
    starRating = 3
} else if (absZ >= 1.5) {
    starRating = 2
} else if (absZ >= 1.0) {
    starRating = 1
}

var starString = starRating == 5 ? "★★★★★" : (starRating == 4 ? "★★★★☆" : (starRating == 3 ? "★★★☆☆" : (starRating == 2 ? "★★☆☆☆" : (starRating == 1 ? "★☆☆☆☆" : "☆☆☆☆☆"))))

// -----------------------------------------------------------------------------
// 8. HISTOGRAM (color-coded by regime)
// -----------------------------------------------------------------------------
timeseries hist = zScore

// -----------------------------------------------------------------------------
// 9. STATIC STATE TRACKING — extreme event history
// -----------------------------------------------------------------------------
// Track consecutive extreme readings and max absolute z-score for context.
static maxAbsZ = 0.0
static maxZBar = 0
static minZBar = 0
static extremeCount = 0
static barCount = 0

barCount = barCount + 1

var currentAbsZ = absZ
if (currentAbsZ > maxAbsZ) {
    maxAbsZ = currentAbsZ
}
if (zScore[0] > maxZBar) {
    maxZBar = zScore[0]
}
if (zScore[0] < minZBar) {
    minZBar = zScore[0]
}
if (regimeExtremeBull || regimeExtremeBear) {
    extremeCount = extremeCount + 1
}

// -----------------------------------------------------------------------------
// 10. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Threshold penetrations and returns to neutral
var thrPenetrateUp = zScore >= dynUpper && zScore[1] < dynUpper
var thrPenetrateDn = zScore <= dynLower && zScore[1] > dynLower
var thrExitUp = zScore < dynUpper && zScore[1] >= dynUpper
var thrExitDn = zScore > dynLower && zScore[1] <= dynLower
var zeroCrossUp = zScore > 0 && zScore[1] <= 0
var zeroCrossDn = zScore < 0 && zScore[1] >= 0

// -----------------------------------------------------------------------------
// 11. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero Line ---
hline(value=0, color="#ffffff20", width=1)

// --- ±1σ Band Fill & Lines ---
if (showBand1) {
    if (showBandFill) {
        plotLine(
            value=[band1n, band1p],
            width=1,
            colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
            colorIndex=0,
            fill=true,
            label=["±1σ Fill"],
            desc=["Fill between -1σ and +1σ bands"]
        )
    }
    hline(value=band1p, color=transparency(neutralColor, 40), width=1)
    hline(value=band1n, color=transparency(neutralColor, 40), width=1)
}

// --- ±2σ Band Fill & Lines ---
if (showBand2) {
    if (showBandFill) {
        plotLine(
            value=[band2n, band2p],
            width=1,
            colors=[transparency(bullColor, 10), transparency(bearColor, 10)],
            colorIndex=0,
            fill=true,
            label=["±2σ Fill"],
            desc=["Fill between -2σ and +2σ bands"]
        )
    }
    hline(value=band2p, color=transparency(neutralColor, 30), width=1)
    hline(value=band2n, color=transparency(neutralColor, 30), width=1)
}

// --- ±3σ Band Lines ---
if (showBand3) {
    hline(value=band3p, color=transparency(neutralColor, 20), width=1)
    hline(value=band3n, color=transparency(neutralColor, 20), width=1)
}

// --- Dynamic Threshold Lines ---
hline(value=dynUpper, color=transparency(bearColor, 50), width=1)
hline(value=dynLower, color=transparency(bullColor, 50), width=1)

// --- Z-Score Line (regime-colored) ---
plotLine(
    value=zScore,
    width=2,
    colors=[regimeColor],
    label=["OI Z-Score"],
    desc=["Z-score of open interest vs " + lookback + " bar baseline (regime-colored)"]
)

// --- Color-Coded Histogram ---
if (showHistogram) {
    var histBull = zScore >= 0
    var histExtreme = regimeExtremeBull || regimeExtremeBear
    plotBar(
        value=hist,
        colors=[transparency(bearColor, 60), transparency(bullColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Z-Score Histogram"],
        desc=["Open Interest Z-Score histogram (color-coded by regime)"]
    )
}

// --- Shape Markers (extreme penetrations) ---
if (showShapes) {
    if (thrPenetrateUp) {
        plotShape(
            value=zScore,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Extreme High"],
            desc=["Z-Score penetrated upper threshold (" + dynUpper + "σ) — overbought positioning"]
        )
    }
    if (thrPenetrateDn) {
        plotShape(
            value=zScore,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Extreme Low"],
            desc=["Z-Score penetrated lower threshold (" + dynLower + "σ) — oversold positioning"]
        )
    }
    if (zeroCrossUp) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=neutralColor,
            width=1,
            label=["Zero Cross Up"],
            desc=["Z-Score crossed above zero — neutral positioning shift"]
        )
    }
    if (zeroCrossDn) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=neutralColor,
            width=1,
            label=["Zero Cross Down"],
            desc=["Z-Score crossed below zero — neutral positioning shift"]
        )
    }
}

// --- Star Rating Shape (last bar only) ---
if (showStars && isLastBar) {
    if (starRating >= 3) {
        plotShape(
            value=zScore,
            shape="star",
            colorIndex=regimeExtremeBull ? bullColor : bearColor,
            width=3,
            label=["Star Rating"],
            desc=["Extremity star rating: " + starString + " (|z| = " + absZ + ")"]
        )
    }
}

// -----------------------------------------------------------------------------
// 12. INFO TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeExtremeBull ? "EXTREME BULL" : (regimeExtremeBear ? "EXTREME BEAR" : (regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")))
    var regimeTextColor = regimeExtremeBull ? bullColor : (regimeExtremeBear ? bearColor : (regimeBull ? transparency(bullColor, 80) : (regimeBear ? transparency(bearColor, 80) : neutralColor)))

    plotTable(
        data=[
            ["OI Z-Score Star", starString],
            ["Regime", regimeText],
            ["Z-Score", zScore[0]],
            ["|Z| Max (hist)", maxAbsZ],
            ["Z Max (hist)", maxZBar],
            ["Z Min (hist)", minZBar],
            ["Extreme Count", extremeCount],
            ["Dynamic Upper", dynUpper],
            ["Dynamic Lower", dynLower]
        ],
        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
    )
}