MM Flow
FlowScripts

Perfected FlowScript

open interest

Open Interest Pro is indexed as 307_open_interest.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.8 KB

Lines

309

Native Signal Candidates

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

4/4 guarded

Accumulation

line 238:9

Trigger

(showShapes) && (crossUp)

Value

smoothedZ

Deps

crossUp:var, showShapes:input

Distribution

line 248:9

Trigger

(showShapes) && (crossDn)

Value

smoothedZ

Deps

crossDn:var, showShapes:input

Extreme Accum

line 258:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedZ

Deps

extremeUp:var, showShapes:input

Extreme Dist

line 268:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedZ

Deps

extremeDn:var, showShapes:input

307_open_interest.flowscript

source path: kscripts/perfected/307_open_interest.flowscript · sha256:4dcbbf183ef7b2e7c3c8cbc750b1e27d593b3b0cc2bcc19f495336c22ff854f9

hash verified
//@version=2
// ============================================================================
// Open Interest Pro — Production-Quality Open Interest Microstructure Indicator
// Author: S (@Sabri Tonyali (DesignBase)) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #oi, #open_interest, #positioning, #futures, #regime
//
// Comprehensive open interest analysis with OI change, z-score normalization,
// regime detection, and color-coded visualization. OI measures total outstanding
// derivative contracts — a proxy for market participation and capital commitment.
//
// FORMULA FOUNDATION:
// 1. OI Change (Delta): ΔOI = OI[t] − OI[t−δ]  (net new positions)
// 2. OI Rate of Change: ROC = (OI[t] − OI[t−δ]) / OI[t−δ] × 100
// 3. Z-Score: z = (OI − μ_OI) / σ_OI  over rolling window
// 4. Regime Detection: z > bullThresh = high OI accumulation (bullish/ bearish
//    depending on price context); z < bearThresh = low OI / distribution
//
// RESEARCH BASIS:
//  • Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
//    and Open Interest in Futures Contracts". OI predicts future volatility;
//    higher OI = greater information flow.
//  • Yang Xu et al. (2021), "An Empirical Analysis of the Price Volatility
//    Characteristics of China's Soybean Futures Market". Unexpected OI
//    changes have larger impact on volatility than expected changes.
//  • Christensen, Krogstrup, Kwan & Lustig (2017), "Financialization in
//    Commodity Markets". OI predicts returns at the commodity level; positive
//    coefficient on aggregate OI in return regressions.
//  • Hong & Yogo (2012), "What Does Future Market Interest Tell Us about the
//    Macro Economy and Asset Prices?" (cited in Christensen et al.). Aggregate
//    OI is a strong predictor of futures risk premia.
// ============================================================================

define(
    title="Open Interest Pro",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained
// ------------------------------------------------------------------------------

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

// --- Smoothing ---
var maLen = input(name="maLen", type="number", defaultValue=14, label="OI MA Length", constraints={min: 2, max: 100, step: 1}, group="Smoothing")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smooth Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")

// --- Delta & Z-Score ---
var deltaLen = input(name="deltaLen", type="number", defaultValue=5, label="OI Delta Lookback", constraints={min: 1, max: 50, step: 1}, group="Delta & Z-Score")
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 1}, group="Delta & Z-Score")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=0.5, label="Bullish Z-Score Threshold", constraints={min: 0.0, max: 3.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-0.5, label="Bearish Z-Score Threshold", constraints={min: -3.0, max: 0.0, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 4.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showOI = input(name="showOI", type="boolean", defaultValue=true, label="Show OI Line", group="Display")
var showMA = input(name="showMA", type="boolean", defaultValue=true, label="Show MA Line", group="Display")
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show OI Delta Histogram", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="OI Increasing Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="OI Decreasing Color", group="Colors")
var maColor = input(name="maColor", type="color", defaultValue="#ff9800", label="MA Line Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeUpColor = input(name="extremeUpColor", type="color", defaultValue="#00e676", label="Extreme Up Color", group="Colors")
var extremeDnColor = input(name="extremeDnColor", type="color", defaultValue="#ff1744", label="Extreme Down Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries oi = open_interest(symbol=symbol, exchange=exchange)
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close

// NaN guard — prevent execution before data is loaded
if (isnan(px[0]) || isnan(oi.close[0])) {
    return
}

// ------------------------------------------------------------------------------
// OI Core Calculations
// ------------------------------------------------------------------------------
timeseries oiClose = oi.close
timeseries oiMA = sma(oiClose, maLen)
timeseries oiDelta = oiClose - oiClose[deltaLen]
timeseries oiROC = oiClose[deltaLen] > 0 ? (oiClose - oiClose[deltaLen]) / oiClose[deltaLen] * 100.0 : 0.0

// ------------------------------------------------------------------------------
// Z-Score Normalization
// ------------------------------------------------------------------------------
// Z = (OI − μ) / σ  over zLookback window
// Extreme z-scores flag statistically significant positioning extremes
// per Yang Xu et al. (2021) — unexpected OI changes carry more predictive power.

timeseries oiMean = sma(oiClose, zLookback)
timeseries oiStd = stddev(oiClose, zLookback)
timeseries oiZ = oiStd > 0 ? (oiClose - oiMean) / oiStd : 0.0

// EMA smoothing of the z-score for cleaner signal
timeseries smoothedZ = ema(oiZ, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection
// ------------------------------------------------------------------------------
// Z-score regime interpretation:
//  z > bullThresh  = high OI accumulation (participation expanding)
//  z < bearThresh  = low OI / distribution (participation contracting)
//  z > extremeThresh = statistically extreme accumulation
//  z < −extremeThresh = statistically extreme distribution

var regime = 0      // 0 = neutral, 1 = bull (high accumulation), -1 = bear (low/distribution)
var extremeRegime = 0

if (smoothedZ >= bullThresh) {
    regime = 1
} else if (smoothedZ <= bearThresh) {
    regime = -1
}

if (smoothedZ >= extremeThresh) {
    extremeRegime = 1
} else if (smoothedZ <= -extremeThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeHighCount = 0
static extremeLowCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (smoothedZ > sessionHighZ) {
        sessionHighZ = smoothedZ
    }
    if (smoothedZ < sessionLowZ) {
        sessionLowZ = smoothedZ
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeHighCount = extremeHighCount + 1
    } else if (extremeRegime == -1) {
        extremeLowCount = extremeLowCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    hline(value=bullThresh, color=opacity(upColor, 30), width=1)
    hline(value=bearThresh, color=opacity(dnColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeUpColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeDnColor, 20), width=1)
}

// OI level line (color-coded by direction)
if (showOI) {
    plotLine(
        value=oiClose,
        colors=[oiClose >= oiClose[1] ? upColor : dnColor],
        width=2,
        label=["Open Interest"],
        desc=["Open interest from configured exchange"]
    )
}

// OI moving average
if (showMA) {
    plotLine(
        value=oiMA,
        colors=[maColor],
        width=1,
        label=["OI MA"],
        desc=["SMA of open interest"]
    )
}

// OI delta histogram (color-coded by direction)
if (showDelta) {
    var deltaUp = oiDelta >= 0
    plotBar(
        value=oiDelta,
        colors=[upColor, dnColor],
        colorIndex=deltaUp ? 0 : 1,
        width=1,
        label=["OI Delta"],
        desc=["Change in OI over deltaLen bars — net new positions"]
    )
}

// Z-score line with regime-coded fill
if (showZScore) {
    plotLine(
        value=smoothedZ,
        width=2,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["OI Z-Score"],
        desc=["Z-score of open interest (smoothed). Regime: accumulation / distribution / neutral."],
        fill=true
    )
}

// Regime transition shapes
if (showShapes) {
    var crossUp = smoothedZ >= bullThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < bullThresh
    var crossDn = smoothedZ <= bearThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > bearThresh
    var extremeUp = smoothedZ >= extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < extremeThresh
    var extremeDn = smoothedZ <= -extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=smoothedZ,
            shape="triangleup",
            color=extremeUpColor,
            width=3,
            label=["Accumulation"],
            desc=["OI Z-Score crossed into accumulation regime (high participation)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedZ,
            shape="triangledown",
            color=extremeDnColor,
            width=3,
            label=["Distribution"],
            desc=["OI Z-Score crossed into distribution regime (low participation)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeUpColor,
            width=4,
            label=["Extreme Accum"],
            desc=["Extreme OI accumulation detected — statistically significant positioning"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeDnColor,
            width=4,
            label=["Extreme Dist"],
            desc=["Extreme OI distribution detected — statistically significant unwind"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "ACCUMULATION" : (regime == -1 ? "DISTRIBUTION" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? upColor : (regime == -1 ? dnColor : neutralColor)

    plotTable(
        data=[
            ["OI Pro", regimeText],
            ["OI Level", oiClose[0]],
            ["OI MA", oiMA[0]],
            ["OI Delta", oiDelta[0]],
            ["OI ROC", oiROC[0]],
            ["Z-Score", smoothedZ[0]],
            ["Regime Changes", regimeChangeCount]
        ],
        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
    )
}