MM Flow
FlowScripts

Perfected FlowScript

Open Interest Bubbles • [Leviathan]

Open Interest Bubbles [Leviathan] Perfected is indexed as 016_open_interest_bubbles_leviathan.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

onchart

Axis

false

Size

11.8 KB

Lines

275

Native Signal Candidates

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

5/5 guarded

OI Bubble

line 184:5

Trigger

(showBubbles && isSignificant)

Value

plotY

Deps

isSignificant:var, showBubbles:input

Extreme OI +

line 200:9

Trigger

(showShapes) && (extremeUpEvent)

Value

hi

Deps

extremeUpEvent:var, showShapes:input

Extreme OI -

line 212:9

Trigger

(showShapes) && (extremeDnEvent)

Value

lo

Deps

extremeDnEvent:var, showShapes:input

Significant OI +

line 224:9

Trigger

(showShapes) && (sigUpEvent && !extremeUpEvent)

Value

hi

Deps

extremeUpEvent:var, showShapes:input, sigUpEvent:var

Significant OI -

line 236:9

Trigger

(showShapes) && (sigDnEvent && !extremeDnEvent)

Value

lo

Deps

extremeDnEvent:var, showShapes:input, sigDnEvent:var

016_open_interest_bubbles_leviathan.flowscript

source path: kscripts/perfected/016_open_interest_bubbles_leviathan.flowscript · sha256:eac2941cc0d38c9b3f6fbca2f0790c27bc8af988639183468cfccd10d349eb62

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Open Interest Bubbles — OI Delta & Z-Score Positioning Visualization
// Author: Leviathan (@Leviathan) — Perfected by kScript_Perfection_Engineer
// Tags: FLOW, ADVANCED, #openinterest, #bubbles, #openinterestbubbles,
//       #leviathan, #oi, #oidelta, #zscore
//
// On-chart bubble visualization of open interest bar-to-bar changes. Computes
// OI delta (change per bar), z-score normalizes over a rolling window, and
// renders bubbles sized by magnitude and colored by direction (green = OI
// increase, red = OI decrease). Shape markers flag statistically significant
// OI changes, making positioning shifts visible at each price level.
//
// Research papers underpinning this design:
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//    Basis and Open Interest in Futures Contracts" (J. Finance, 50(1)):
//    establishes foundational relationship between OI levels and volatility.
//    Higher OI is associated with greater information flow and price discovery.
//  - LeviathanCapital (2024), "Open Interest Delta - By Leviathan": OI delta
//    maps net change in open interest per candle. Positive delta clusters
//    act as defense zones where traders will defend entries on revisit.
//  - Christensen et al. (2017), "Financialization in Commodity Markets"
//    (NBER 23766): Hong and Yogo found aggregate OI is significantly
//    positive for futures returns. OI predicts returns at commodity level.
//  - Yang Xu et al. (2021), "Price Volatility Characteristics of China's
//    Soybean Futures": unexpected OI changes have larger impact on volatility
//    than expected changes, confirming the "information flow" hypothesis.
//  - Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//    z-score normalization framework; entry thresholds at ±1σ, ±2σ.
// ============================================================================

define(
    title="Open Interest Bubbles [Leviathan] Perfected",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------

// --- Display Group ---
var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show OI Bubbles", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Significant Change Shapes", group="Display")
var showOIChange = input(name="showOIChange", type="boolean", defaultValue=true, label="Show OI Change Bar", group="Display")
var showDeltaProfile = input(name="showDeltaProfile", type="boolean", defaultValue=true, label="Show Delta Profile", group="Display")
var sizeMult = input(name="sizeMult", type="number", defaultValue=2.0, label="Bubble Size Multiplier", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=1, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Z-Score Group ---
var lookback = input(name="lookback", type="number", defaultValue=30, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Z-Score")
var threshold = input(name="threshold", type="number", defaultValue=1.5, label="Display Threshold (z)", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Z-Score")
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=2.5, label="Extreme Threshold (z)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Z-Score")

// --- Colors Group ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="OI Increase Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="OI Decrease Color", group="Colors")
var extremeUpColor = input(name="extremeUpColor", type="color", defaultValue="#00e676", label="Extreme Increase Color", group="Colors")
var extremeDnColor = input(name="extremeDnColor", type="color", defaultValue="#ff1744", label="Extreme Decrease Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries hi = bars.high
timeseries lo = bars.low
timeseries cl = bars.close

// isnan guard: prevent computation on incomplete data
if (isnan(cl[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(oi[0])) {
    return
}

// ---------------------------------------------------------------------------
// OI Delta Computation
// ---------------------------------------------------------------------------
// Bar-to-bar change in open interest. Positive = new positions opened;
// negative = positions closed / liquidated.

timeseries oiClose = oi.close
timeseries oiPrev = isnan(oiClose[1]) ? oiClose : oiClose[1]
timeseries oiChange = oiClose - oiPrev

// Guard against missing data on first bar
timeseries oiChangeSafe = isnan(oiChange) ? 0 : oiChange

// ---------------------------------------------------------------------------
// Z-Score Normalization
// ---------------------------------------------------------------------------
timeseries oiMean = sma(oiChangeSafe, lookback)
timeseries oiStd = stdev(oiChangeSafe, lookback)
timeseries oiZ = oiStd > 0 ? (oiChangeSafe - oiMean) / oiStd : 0

// ---------------------------------------------------------------------------
// Bubble Size by Magnitude and Significance
// ---------------------------------------------------------------------------
function calcBubbleSize(z) {
    var absZ = math.abs(z)
    var clampedZ = math.min(20, math.max(2, absZ))
    return sizeMult * clampedZ
}

// ---------------------------------------------------------------------------
// Event Detection
// ---------------------------------------------------------------------------
var absZ = math.abs(oiZ)
var isSignificant = absZ >= threshold
var isExtreme = absZ >= extremeThreshold
var isIncrease = oiChangeSafe > 0

// --- STATIC STATE: Event Tracking ---
static lastExtremeUpBar = 0
static lastExtremeDnBar = 0
static lastSigUpBar = 0
static lastSigDnBar = 0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1
    if (isExtreme && isIncrease) {
        lastExtremeUpBar = barCount
    }
    if (isExtreme && !isIncrease) {
        lastExtremeDnBar = barCount
    }
    if (isSignificant && isIncrease) {
        lastSigUpBar = barCount
    }
    if (isSignificant && !isIncrease) {
        lastSigDnBar = barCount
    }
}

var extremeUpEvent = lastExtremeUpBar == barCount
var extremeDnEvent = lastExtremeDnBar == barCount
var sigUpEvent = lastSigUpBar == barCount
var sigDnEvent = lastSigDnBar == barCount

// ---------------------------------------------------------------------------
// Plotting: OI Delta (plotBar — raw change)
// ---------------------------------------------------------------------------
if (showOIChange) {
    var oiChangeColor = oiChangeSafe > 0 ? upColor : (oiChangeSafe < 0 ? dnColor : neutralColor)
    plotBar(
        value=oiChangeSafe,
        colors=[oiChangeColor],
        label=["OI Change"],
        desc=["Open interest bar-to-bar change. Positive = new positions opened; negative = positions closed."]
    )
}

// ---------------------------------------------------------------------------
// Plotting: OI Delta Profile (plotLine — cumulative for context)
// ---------------------------------------------------------------------------
if (showDeltaProfile) {
    // Simple cumulative OI delta for trend context
    static cumOIDelta = 0.0
    if (!isLiveUpdate) {
        cumOIDelta = cumOIDelta + oiChangeSafe
    }

    plotLine(
        value=cumOIDelta,
        width=lineWidth,
        colors=[cumOIDelta >= 0 ? upColor : dnColor],
        label=["Cum OI Delta"],
        desc=["Cumulative open interest delta since script start. Rising = net positioning increase."]
    )
}

// ---------------------------------------------------------------------------
// Plotting: Bubbles (Sized by Z-Score, Colored by Direction)
// ---------------------------------------------------------------------------
if (showBubbles && isSignificant) {
    var bubbleColor = isExtreme ? (isIncrease ? extremeUpColor : extremeDnColor) : (isIncrease ? upColor : dnColor)
    var bubbleSize = calcBubbleSize(oiZ)
    var plotY = isIncrease ? hi : lo

    plotShape(
        value=plotY,
        shape="circle",
        colorIndex=bubbleColor,
        width=bubbleSize,
        label=["OI Bubble"],
        desc=["OI change: " + oiChangeSafe + ", z=" + oiZ + ", mean=" + oiMean + ", std=" + oiStd]
    )
}

// ---------------------------------------------------------------------------
// Plotting: Shape Markers for Significant OI Changes
// ---------------------------------------------------------------------------
if (showShapes) {
    // Extreme increase — triangle up at high
    if (extremeUpEvent) {
        plotShape(
            value=hi,
            shape="triangleup",
            colorIndex=extremeUpColor,
            width=shapeSize + 2,
            label=["Extreme OI +"],
            desc=["Extreme OI increase: z=" + oiZ + ", change=" + oiChangeSafe + ". New aggressive positioning."]
        )
    }

    // Extreme decrease — triangle down at low
    if (extremeDnEvent) {
        plotShape(
            value=lo,
            shape="triangledown",
            colorIndex=extremeDnColor,
            width=shapeSize + 2,
            label=["Extreme OI -"],
            desc=["Extreme OI decrease: z=" + oiZ + ", change=" + oiChangeSafe + ". Position liquidation or closing."]
        )
    }

    // Significant increase (but not extreme) — circle at high
    if (sigUpEvent && !extremeUpEvent) {
        plotShape(
            value=hi,
            shape="circle",
            colorIndex=upColor,
            width=shapeSize,
            label=["Significant OI +"],
            desc=["Significant OI increase: z=" + oiZ + ", change=" + oiChangeSafe + ". New positions entering."]
        )
    }

    // Significant decrease (but not extreme) — circle at low
    if (sigDnEvent && !extremeDnEvent) {
        plotShape(
            value=lo,
            shape="circle",
            colorIndex=dnColor,
            width=shapeSize,
            label=["Significant OI -"],
            desc=["Significant OI decrease: z=" + oiZ + ", change=" + oiChangeSafe + ". Positions closing."]
        )
    }
}

// ---------------------------------------------------------------------------
// Plotting: Z-Score Line (plotLine — for statistical context)
// ---------------------------------------------------------------------------
plotLine(
    value=oiZ,
    width=lineWidth,
    colors=[oiZ > 0 ? upColor : dnColor],
    label=["OI Z-Score"],
    desc=["Z-score of open interest change over " + lookback + " bars. |z| > " + threshold + " = significant. |z| > " + extremeThreshold + " = extreme."]
)

// ---------------------------------------------------------------------------
// Plotting: Threshold Reference Lines
// ---------------------------------------------------------------------------
plotLine(
    value=threshold,
    width=1,
    colors=[neutralColor],
    label=["+z Threshold"],
    desc=["Upper significance threshold at z=" + threshold]
)
plotLine(
    value=-threshold,
    width=1,
    colors=[neutralColor],
    label=["-z Threshold"],
    desc=["Lower significance threshold at z=" + threshold]
)