MM Flow
FlowScripts

Perfected FlowScript

Open Interest Oscillator

Open Interest Oscillator — Perfected Edition is indexed as 316_open_interest_oscillator.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

15.0 KB

Lines

482

Native Signal Candidates

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

8/8 guarded

OI OB

line 369:9

Trigger

(showShapes) && (rsiOb)

Value

oiRsi

Deps

rsiOb:var, showShapes:input

OI OS

line 379:9

Trigger

(showShapes) && (rsiOs)

Value

oiRsi

Deps

rsiOs:var, showShapes:input

Z+ Extreme

line 389:9

Trigger

(showShapes) && (zExtremePos)

Value

oiZClip

Deps

showShapes:input, zExtremePos:var

Z- Extreme

line 399:9

Trigger

(showShapes) && (zExtremeNeg)

Value

oiZClip

Deps

showShapes:input, zExtremeNeg:var

OI Δ+

line 409:9

Trigger

(showShapes) && (changeCrossUp)

Value

oiChangeSmooth

Deps

changeCrossUp:var, showShapes:input

OI Δ-

line 419:9

Trigger

(showShapes) && (changeCrossDown)

Value

oiChangeSmooth

Deps

changeCrossDown:var, showShapes:input

Bull Regime

line 429:9

Trigger

(showShapes) && (regimeToBull)

Value

composite * 100

Deps

regimeToBull:var, showShapes:input

Bear Regime

line 439:9

Trigger

(showShapes) && (regimeToBear)

Value

composite * 100

Deps

regimeToBear:var, showShapes:input

316_open_interest_oscillator.flowscript

source path: kscripts/perfected/316_open_interest_oscillator.flowscript · sha256:7288a8b79bb96f6bbed8545d294399b52d75a52331b8183162d3c7628809aba8

hash verified
//@version=2
// ============================================================================
// Open Interest Oscillator — Perfected Edition
// Author: E (@eCnEuLfNi) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #oi, #openinterest, #oscillator, #zscore, #regime, #positioning
//
// Production-quality futures positioning oscillator built on open interest
// dynamics. Implements three parallel signals: (1) OI RSI — canonical Wilder
// RSI applied to open interest levels for momentum extremes; (2) OI Change
// Oscillator — rate-of-change in OI normalized to detect acceleration/
// deceleration in position building; (3) OI Z-Score — statistical
// standardization for extreme positioning detection. Full regime detection,
// color-coded histogram, shape markers, and static state tracking.
//
// Research papers underpinning this design:
//  1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts", Journal of Finance, 50(1).
//     Foundational relationship between OI levels and future volatility.
//     Higher OI = greater information flow and price discovery.
//     DOI: https://doi.org/10.1111/j.1540-6261.1995.tb05178.x
//
//  2. Yang Xu et al. (2021), "ARIMA-GJR-GARCH Model" on soybean futures.
//     Decomposes OI into expected and unexpected components. Unexpected OI
//     changes have LARGER impact on volatility than expected changes.
//     Validates OI delta and z-score as predictive signals.
//
//  3. LeviathanCapital (2024), "Open Interest Delta": OI Delta maps net
//     change in OI per candle. Positive = new positions opened; negative =
//     positions closed. High-density OI areas act as support/resistance.
//
//  4. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI formula. RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain)/SMA(loss).
//     Applying RSI to OI instead of price creates a positioning momentum measure.
//
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score event triggers for mean reversion. z_t = (x_t − μ) / σ with
//     entry thresholds at ±1σ or ±2σ. Directly applicable to OI z-score.
//
//  6. Hong & Yogo (2012), via Christensen et al. (2017) NBER WP 23766:
//     aggregate OI predicts futures returns with significantly positive coefficient.
//     Supports OI-based trend confirmation and return prediction.
// ============================================================================

define(
    title="Open Interest Oscillator — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Data Sources ---
var symbol = input(
    name="symbol",
    type="string",
    defaultValue="BTCUSDT",
    label="OI Symbol",
    group="Data Sources"
)
var exchange = input(
    name="exchange",
    type="string",
    defaultValue="BINANCE_FUTURES",
    label="OI Exchange",
    group="Data Sources"
)

// --- OI RSI ---
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="OI RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="OI RSI"
)
var rsiSmooth = input(
    name="rsiSmooth",
    type="number",
    defaultValue=3,
    label="OI RSI Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="OI RSI"
)
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=70,
    label="Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="OI RSI"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=30,
    label="Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="OI RSI"
)

// --- OI Change Oscillator ---
var changeLen = input(
    name="changeLen",
    type="number",
    defaultValue=14,
    label="OI Change Lookback",
    constraints={min: 5, max: 50, step: 1},
    group="OI Change Oscillator"
)
var changeSmooth = input(
    name="changeSmooth",
    type="number",
    defaultValue=3,
    label="OI Change Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="OI Change Oscillator"
)

// --- OI Z-Score ---
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 20, max: 200, step: 5},
    group="OI Z-Score"
)
var zThreshold = input(
    name="zThreshold",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.5},
    group="OI Z-Score"
)

// --- Display ---
var showOiRsi = input(
    name="showOiRsi",
    type="boolean",
    defaultValue=true,
    label="Show OI RSI",
    group="Display"
)
var showOiChange = input(
    name="showOiChange",
    type="boolean",
    defaultValue=true,
    label="Show OI Change Oscillator",
    group="Display"
)
var showOiZ = input(
    name="showOiZ",
    type="boolean",
    defaultValue=true,
    label="Show OI Z-Score",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Regime Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish 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)
timeseries oiClose = oi.close

if (isnan(oiClose[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. COMPUTATION
// -----------------------------------------------------------------------------

// -- 3.1 OI RSI (Wilder RSI applied to OI) --
// RSI = 100 − [100 / (1 + RS)] where RS = avgGain / avgLoss
timeseries oiChange = oiClose - oiClose[1]
timeseries oiGain = oiChange > 0 ? oiChange : 0
timeseries oiLoss = oiChange < 0 ? -oiChange : 0

timeseries avgGain = sma(oiGain, rsiLen)
timeseries avgLoss = sma(oiLoss, rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries oiRsiRaw = 100 - (100 / (1 + rs))
timeseries oiRsi = sma(oiRsiRaw, rsiSmooth)

// -- 3.2 OI Change Oscillator (rate of change, normalized) --
// Measures acceleration/deceleration in position building
timeseries oiDelta = oiClose - oiClose[changeLen]
// Normalize by rolling mean absolute change for cross-asset comparability
timeseries oiDeltaAbs = math.abs(oiDelta)
timeseries oiDeltaMean = sma(oiDeltaAbs, changeLen)
timeseries oiChangeOsc = (oiDeltaMean > 0) ? (oiDelta / oiDeltaMean) * 50 : 0
timeseries oiChangeSmooth = sma(oiChangeOsc, changeSmooth)

// -- 3.3 OI Z-Score (statistical standardization) --
// z_t = (OI_t − μ_t) / σ_t where μ = SMA(OI, W), σ = StDev(OI, W)
timeseries oiMean = sma(oiClose, zWindow)
timeseries oiStd = stddev(oiClose, zWindow)
timeseries oiZ = (oiStd > 0) ? (oiClose - oiMean) / oiStd : 0
// Clip to ±4 for display stability
timeseries oiZClip = oiZ > 4 ? 4 : (oiZ < -4 ? -4 : oiZ)

// -- 3.4 Combined Regime Signal --
// Composite score: average of normalized RSI, Change, and Z-Score readings
// Each normalized to [-1, +1] roughly, then averaged
timeseries rsiNorm = (oiRsi - 50) / 50  // -1 to +1
timeseries changeNorm = oiChangeSmooth / 100  // approx -1 to +1
timeseries zNorm = oiZClip / 4  // -1 to +1
timeseries composite = (rsiNorm + changeNorm + zNorm) / 3

// -- 3.5 Regime Detection --
// Bullish: OI RSI > 50 AND OI increasing AND Z-Score positive
// Bearish: OI RSI < 50 AND OI decreasing AND Z-Score negative
// Neutral: everything else

var regimeBull = oiRsi > 50 && oiChangeSmooth > 0 && oiZ > 0
var regimeBear = oiRsi < 50 && oiChangeSmooth < 0 && oiZ < 0
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// -----------------------------------------------------------------------------
// 4. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static prevRsi = 50.0
static prevZ = 0.0
static prevChange = 0.0
static bullBars = 0
static bearBars = 0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
} else {
    bullBars = 0
    bearBars = 0
}

prevRsi = oiRsi[0]
prevZ = oiZ[0]
prevChange = oiChangeSmooth[0]

// -----------------------------------------------------------------------------
// 5. ALERT CONDITIONS
// -----------------------------------------------------------------------------

// OI RSI extremes
var rsiOb = oiRsi > obLevel && oiRsi[1] <= obLevel
var rsiOs = oiRsi < osLevel && oiRsi[1] >= osLevel
var rsiObExit = oiRsi < obLevel && oiRsi[1] >= obLevel
var rsiOsExit = oiRsi > osLevel && oiRsi[1] <= osLevel

// Z-Score extremes
var zExtremePos = oiZ > zThreshold && oiZ[1] <= zThreshold
var zExtremeNeg = oiZ < -zThreshold && oiZ[1] >= -zThreshold

// Change oscillator zero-line crosses
var changeCrossUp = oiChangeSmooth > 0 && oiChangeSmooth[1] <= 0
var changeCrossDown = oiChangeSmooth < 0 && oiChangeSmooth[1] >= 0

// Regime transitions
var regimeToBull = regimeBull && !regimeBull[1]
var regimeToBear = regimeBear && !regimeBear[1]

// -----------------------------------------------------------------------------
// 6. PLOTTING
// -----------------------------------------------------------------------------

// --- Reference Lines ---
hline(value=50, color="#ffffff30", width=1)
hline(value=obLevel, color=transparency(bearColor, 60), width=1)
hline(value=osLevel, color=transparency(bullColor, 60), width=1)

// --- OI RSI Line ---
if (showOiRsi) {
    plotLine(
        value=oiRsi,
        width=2,
        colors=[oiRsi > 50 ? bullColor : bearColor],
        label=["OI RSI"],
        desc=["Wilder RSI applied to Open Interest (" + rsiLen + ") — positioning momentum"]
    )
}

// --- OI Change Oscillator ---
if (showOiChange) {
    plotLine(
        value=oiChangeSmooth,
        width=2,
        colors=[oiChangeSmooth > 0 ? bullColor : bearColor],
        label=["OI Change"],
        desc=["OI rate-of-change oscillator (" + changeLen + ") — position building acceleration"]
    )
}

// --- OI Z-Score ---
if (showOiZ) {
    plotLine(
        value=oiZClip,
        width=2,
        colors=[oiZClip > 0 ? bullColor : bearColor],
        label=["OI Z-Score"],
        desc=["OI standardization (" + zWindow + ") — statistical positioning extremes"]
    )
    // Reference thresholds for z-score
    hline(value=zThreshold, color="#ffffff15", width=1)
    hline(value=-zThreshold, color="#ffffff15", width=1)
}

// --- Regime Histogram (composite) ---
if (showHistogram) {
    var histBull = composite > 0
    plotBar(
        value=composite * 100,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["OI Regime"],
        desc=["Composite regime histogram: average of RSI/Change/Z normalized signals"]
    )
}

// --- Shape Markers ---
if (showShapes) {
    if (rsiOb) {
        plotShape(
            value=oiRsi,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["OI OB"],
            desc=["OI RSI entered overbought (>" + obLevel + ") — potential positioning exhaustion"]
        )
    }
    if (rsiOs) {
        plotShape(
            value=oiRsi,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["OI OS"],
            desc=["OI RSI entered oversold (<" + osLevel + ") — potential capitulation / low leverage"]
        )
    }
    if (zExtremePos) {
        plotShape(
            value=oiZClip,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["Z+ Extreme"],
            desc=["OI Z-Score exceeded +" + zThreshold + " — statistically extreme positioning buildup"]
        )
    }
    if (zExtremeNeg) {
        plotShape(
            value=oiZClip,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["Z- Extreme"],
            desc=["OI Z-Score below -" + zThreshold + " — statistically extreme deleveraging"]
        )
    }
    if (changeCrossUp) {
        plotShape(
            value=oiChangeSmooth,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["OI Δ+"],
            desc=["OI Change crossed above zero — position building accelerating"]
        )
    }
    if (changeCrossDown) {
        plotShape(
            value=oiChangeSmooth,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["OI Δ-"],
            desc=["OI Change crossed below zero — position unwinding accelerating"]
        )
    }
    if (regimeToBull) {
        plotShape(
            value=composite * 100,
            shape="arrowup",
            colorIndex=bullColor,
            width=2,
            label=["Bull Regime"],
            desc=["Composite regime flipped bullish — OI momentum + position building + positive z-score"]
        )
    }
    if (regimeToBear) {
        plotShape(
            value=composite * 100,
            shape="arrowdown",
            colorIndex=bearColor,
            width=2,
            label=["Bear Regime"],
            desc=["Composite regime flipped bearish — OI momentum + position unwinding + negative z-score"]
        )
    }
}

// -----------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH POSITIONING" :
        (regimeBear ? "BEARISH POSITIONING" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["OI Oscillator", regimeText],
            ["OI RSI", oiRsi[0]],
            ["OI Change", oiChangeSmooth[0]],
            ["OI Z-Score", oiZClip[0]],
            ["OI Level", oiClose[0]],
            ["Composite", composite[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars]
        ],
        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
    )
}