MM Flow
FlowScripts

Perfected FlowScript

Net Longs

Net Longs — OI Positioning Decomposition is indexed as 126_net_longs.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.4 KB

Lines

521

Native Signal Candidates

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

5/5 guarded

Long Regime

line 468:9

Trigger

(showShapes) && (crossUp)

Value

zScore

Deps

crossUp:var, showShapes:input

Short Regime

line 478:9

Trigger

(showShapes) && (crossDn)

Value

zScore

Deps

crossDn:var, showShapes:input

Extreme Long

line 488:9

Trigger

(showShapes) && (extremeUp)

Value

zScore

Deps

extremeUp:var, showShapes:input

Extreme Short

line 498:9

Trigger

(showShapes) && (extremeDn)

Value

zScore

Deps

extremeDn:var, showShapes:input

Unlabeled shape

line 511:5

Trigger

(showRegimeLabel && isLastBar)

Value

h

Deps

isLastBar:builtin, showRegimeLabel:input

126_net_longs.flowscript

source path: kscripts/perfected/126_net_longs.flowscript · sha256:16159edd5c84fd4263e484f76e58833c47b1b6aa4a610e2bb2bca829af61cc61

hash verified
//@version=2
// ============================================================================
// Net Longs — Open Interest Positioning Decomposition with Regime Detection
// Author: BackQuant (@BackQuant) — Perfected Edition
// Tags: ADVANCED, #netlongs, #oi, #positioning, #cvd, #regime, #zscore
//
// Production-grade open-interest decomposition model that estimates net long
// futures positioning by distributing OI changes into long/short contributions
// using price-based weighting, volume delta, and rolling z-score normalization.
// Features regime detection, color-coded histograms, transition markers, and
// session-level static tracking.
//
// Academic foundations:
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
//    and Open Interest in Futures Contracts" (J. Business 68(2)). OI levels
//    contain information about future volatility and market expectations.
//    Formula: OI_t → predictive for σ_{t+1}; ΔOI_t × ΔP_t correlation > 0.3
//    for major futures. The script's decomposition extends this by extracting
//    directional components from aggregate OI changes.
//  - Brunnermeier & Pedersen (2005), "Predatory Trading" (J. Finance 60(4)).
//    Models traders selling to push prices against crowded positions.
//    Key formula: π_i = Σ_t [x_{i,t} · (v_t − v_{t−1})] where v_t = distressed
//    trader's position value. Validates net long positioning as squeeze risk
//    indicator — when net longs are crowded, predatory selling intensifies.
//  - Adrian & Shin (2010), "Liquidity and Leverage" (J. Financial Intermediation).
//    Leverage is procyclical: L_t = α + β·A_t + ε_t with β > 0. Intermediaries
//    expand balance sheets during booms and contract during busts. The script's
//    net long estimates capture this procyclical positioning dynamic.
//  - Bessembinder & Seguin (1993), "Price Volatility, Trading Volume, and Market
//    Depth" (Rev. Financial Studies 6(1)). Volume and OI jointly predict volatility:
//    σ_t² = f(Volume_{t−1}, ΔOI_{t−1}). Validates using volume delta alongside
//    OI changes for directional inference.
//  - Wang (2003), "The Behavior of Cumulative Volume-Determined (CVD) Measures
//    and Their Relationship to Price Changes". CVD = Σ_t (ΔV_buy − ΔV_sell) and
//    CVD/Volume ratio correlates with price direction. Used here to augment
//    price-based weighting with volume-flow confirmation.
// ============================================================================

define(
    title="Net Longs — OI Positioning Decomposition",
    position="offchart",
    axis=true
)

// === USER INPUTS ===
// --- Anchor & Aggregation ---
var anchor = input(
    name="anchor",
    type="select",
    defaultValue="Daily",
    label="Anchor Period",
    options=["Hourly", "Daily", "Weekly", "Monthly", "Rolling", "Full"],
    group="Anchor & Aggregation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="Smoothing Length (EMA)",
    constraints={min: 1, max: 50, step: 1},
    group="Anchor & Aggregation"
)
var oiLookback = input(
    name="oiLookback",
    type="number",
    defaultValue=14,
    label="OI Change Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Anchor & Aggregation"
)

// --- Positioning Model ---
var priceWeight = input(
    name="priceWeight",
    type="number",
    defaultValue=0.6,
    label="Price Weight (0 = neutral, 1 = full directional)",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Positioning Model"
)
var volWeight = input(
    name="volWeight",
    type="number",
    defaultValue=0.3,
    label="Volume-Delta Weight (0 = off, 1 = full)",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Positioning Model"
)
var useVolConfirm = input(
    name="useVolConfirm",
    type="boolean",
    defaultValue=true,
    label="Use Volume Delta for Confirmation",
    group="Positioning Model"
)

// --- Z-Score & Normalization ---
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 10, max: 100, step: 1},
    group="Z-Score & Normalization"
)
var zSmooth = input(
    name="zSmooth",
    type="boolean",
    defaultValue=true,
    label="Smooth Z-Score",
    group="Z-Score & Normalization"
)
var zSmoothLen = input(
    name="zSmoothLen",
    type="number",
    defaultValue=3,
    label="Z-Score Smooth Length",
    constraints={min: 1, max: 20, step: 1},
    group="Z-Score & Normalization"
)

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

// --- Display ---
var showRawLine = input(
    name="showRawLine",
    type="boolean",
    defaultValue=true,
    label="Show Raw Net Longs Line",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Color-Coded Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Transition Shapes",
    group="Display"
)
var showZero = input(
    name="showZero",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Guide Lines",
    group="Display"
)
var showRegimeLabel = input(
    name="showRegimeLabel",
    type="boolean",
    defaultValue=true,
    label="Show Regime State Label",
    group="Display"
)

// --- Colors ---
var longColor = input(
    name="longColor",
    type="color",
    defaultValue="#26a69a",
    label="Net Longs (Bullish) Color",
    group="Colors"
)
var shortColor = input(
    name="shortColor",
    type="color",
    defaultValue="#ef5350",
    label="Net Shorts (Bearish) Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var extremeLongColor = input(
    name="extremeLongColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Long Color",
    group="Colors"
)
var extremeShortColor = input(
    name="extremeShortColor",
    type="color",
    defaultValue="#ff1744",
    label="Extreme Short Color",
    group="Colors"
)

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries o = bars.open
timeseries v = bars.volume
timeseries t = bars.time

// Open interest from multiple exchanges for robustness
timeseries oiBybit = open_interest(symbol="BTCUSDT", exchange="BYBIT")
timeseries oiOkex  = open_interest(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")

// Aggregate OI (averaged across major venues)
timeseries aggOI = (oiBybit.close + oiOkex.close) / 2.0

// isnan guard on first use of external data — prevents NaN propagation on startup
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0]) || isnan(aggOI[0])) {
    return
}

// === COMPUTATION ===
// OI delta: change in aggregate open interest from prior bar
// Formula: ΔOI_t = OI_t − OI_{t−1}
// Chen et al. (1995): OI changes contain directional information about positioning
timeseries oiDelta = aggOI - nz(aggOI[1])
timeseries oiAvg = rma(oiDelta, oiLookback)

// Price-based long allocation weight
// If close > typical range midpoint (HL/2), weight toward longs; else toward shorts.
// Formula: midPx = (h + l) / 2; aboveMid = 1 if c > midPx else 0
// longWeight = aboveMid × priceWeight + (1 − priceWeight) × 0.5
// This gives a directional bias: 0.5 = neutral, >0.5 = long-biased, <0.5 = short-biased.
timeseries midPx = (h + l) / 2.0
timeseries aboveMid = (c > midPx) ? 1.0 : 0.0
timeseries longWeight = aboveMid * priceWeight + (1.0 - priceWeight) * 0.5

// Volume delta confirmation (Bessembinder & Seguin 1993)
// If close > open, volume treated as buying; else selling.
// This is a simplified CVD approach (Wang 2003).
timeseries volDelta = (c > o) ? v : (-v)
timeseries volDeltaNorm = v > 0 ? volDelta / v : 0.0
timeseries volConfirm = volDeltaNorm * volWeight

// Combined positioning weight: price direction + volume confirmation
timeseries combinedWeight = longWeight + (useVolConfirm ? volConfirm : 0.0)
// Clamp to [0, 1] to avoid overshoot
timeseries clampedWeight = math.max(0.0, math.min(1.0, combinedWeight))

// Net long estimate: distribute OI delta into long/short contributions
// Formula: netLong = ΔOI × (2 × weight − 1)
// where (2 × weight − 1) maps [0, 1] → [−1, +1]
// Positive = long-dominated OI growth; Negative = short-dominated OI growth.
timeseries netLong = oiDelta * (2.0 * clampedWeight - 1.0)
timeseries netSmooth = ema(netLong, smoothLen)

// === ANCHOR AGGREGATION ===
// Anchor period in milliseconds for time-based aggregation
var anchorMs = 86400000
if (anchor == "Hourly") {
    anchorMs = 3600000
} else if (anchor == "Weekly") {
    anchorMs = 604800000
} else if (anchor == "Monthly") {
    anchorMs = 2592000000
}

// Time-based anchor ID for discrete aggregation (Hourly/Daily/Weekly/Monthly)
var anchorId = math.floor(t / anchorMs)

// --- STATIC STATE: Anchor Aggregation ---
static aggLong = 0.0
static lastAnchor = -1
static rollingSum = 0.0
static rollingCount = 0

// Rolling window for "Rolling" anchor mode (last 20 bars)
static rollingWindow = 0.0
static rollingWindowCount = 0

if (!isLiveUpdate) {
    if (anchor == "Full") {
        // Cumulative sum over entire session
        aggLong = nz(aggLong) + netSmooth
    } else if (anchor == "Rolling") {
        // Rolling 20-bar sum
        rollingSum = rollingSum + netSmooth
        rollingCount = rollingCount + 1
        if (rollingCount > 20) {
            rollingSum = 0.0
            rollingCount = 0
        }
        aggLong = rollingSum
    } else {
        // Discrete anchor-based aggregation
        if (lastAnchor == -1 || anchorId != lastAnchor) {
            // New anchor period — reset
            aggLong = netSmooth
            lastAnchor = anchorId
        } else {
            // Same anchor period — accumulate
            aggLong = aggLong + netSmooth
        }
    }
}

// === Z-SCORE NORMALIZATION ===
// Standardize the aggregated net long series to have mean 0 and std 1.
// Formula: z = (x − μ) / σ where μ = SMA(x, zLen), σ = stdev(x, zLen)
// This makes regime thresholds comparable across assets and time periods.
timeseries zMean = sma(aggLong, zLen)
timeseries zStd = stdev(aggLong, zLen)
timeseries zScoreRaw = zStd > 0 ? (aggLong - zMean) / zStd : 0.0
timeseries zScore = zSmooth ? ema(zScoreRaw, zSmoothLen) : zScoreRaw

// === REGIME DETECTION ===
// Three-regime model: Bullish (z > bullThresh), Bearish (z < bearThresh), Neutral.
// Extreme regime flags for event detection.
var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

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

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

// Regime color and label for display
var regimeColor = regime == 1 ? longColor : (regime == -1 ? shortColor : neutralColor)
var regimeLabel = regime == 1 ? "LONG DOMINANT" : (regime == -1 ? "SHORT DOMINANT" : "NEUTRAL")

// === STATIC STATE: Session Tracking ===
// Tracks regime transitions, session extremes, and cumulative statistics.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeLongCount = 0
static extremeShortCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    // Track session extremes
    if (zScore > sessionHighZ) {
        sessionHighZ = zScore
    }
    if (zScore < sessionLowZ) {
        sessionLowZ = zScore
    }

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

    // Count extreme events
    if (extremeRegime == 1) {
        extremeLongCount = extremeLongCount + 1
    } else if (extremeRegime == -1) {
        extremeShortCount = extremeShortCount + 1
    }
}

// === EVENT FLAGS FOR PLOTTING ===
// Detect crossing events for shape markers
var crossUp = zScore >= bullThresh && !isnan(zScore[1]) && zScore[1] < bullThresh
var crossDn = zScore <= bearThresh && !isnan(zScore[1]) && zScore[1] > bearThresh
var extremeUp = zScore >= extremeThresh && !isnan(zScore[1]) && zScore[1] < extremeThresh
var extremeDn = zScore <= -extremeThresh && !isnan(zScore[1]) && zScore[1] > -extremeThresh

// === PLOTS: GUIDE LINES (hline) ===
if (showZero) {
    hline(value=0, color="#ffffff30", width=1)
}
if (showGuides) {
    hline(value=bullThresh, color=opacity(longColor, 30), width=1)
    hline(value=bearThresh, color=opacity(shortColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeLongColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeShortColor, 20), width=1)
}

// === PLOTS: RAW NET LONGS LINE (plotLine) ===
if (showRawLine) {
    plotLine(
        value=aggLong,
        width=1,
        colors=[opacity(longColor, 40)],
        label=["Raw Net Longs"],
        desc=["Aggregated net long estimate (OI delta × directional weight). Positive = long-dominated OI growth."]
    )
}

// === PLOTS: Z-SCORE LINE (plotLine with fill) ===
if (showZScore) {
    plotLine(
        value=zScore,
        width=2,
        colors=[longColor, shortColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Net Longs Z-Score"],
        desc=["Z-score normalized net long positioning. Regime-coded: green=bullish, red=bearish, gray=neutral."],
        fill=true
    )
}

// === PLOTS: COLOR-CODED HISTOGRAM (plotBar) ===
if (showHistogram) {
    // Histogram color by regime: extreme long, long, neutral, short, extreme short
    var histColor = extremeRegime == 1 ? extremeLongColor : (extremeRegime == -1 ? extremeShortColor : regimeColor)
    plotBar(
        value=zScore,
        colors=[histColor],
        width=1,
        label=["Net Longs Z Histogram"],
        desc=["Z-score histogram of net long positioning. Height = magnitude; color = regime."]
    )
}

// === PLOTS: REGIME TRANSITION SHAPES (plotShape) ===
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=zScore,
            shape="triangleup",
            colorIndex=extremeLongColor,
            width=3,
            label=["Long Regime"],
            desc=["Net long positioning crossed into bullish regime (z-score > threshold)."]
        )
    }
    if (crossDn) {
        plotShape(
            value=zScore,
            shape="triangledown",
            colorIndex=extremeShortColor,
            width=3,
            label=["Short Regime"],
            desc=["Net short positioning crossed into bearish regime (z-score < threshold)."]
        )
    }
    if (extremeUp) {
        plotShape(
            value=zScore,
            shape="diamond",
            colorIndex=extremeLongColor,
            width=4,
            label=["Extreme Long"],
            desc=["Extreme net long positioning detected — crowded longs, squeeze risk elevated."]
        )
    }
    if (extremeDn) {
        plotShape(
            value=zScore,
            shape="diamond",
            colorIndex=extremeShortColor,
            width=4,
            label=["Extreme Short"],
            desc=["Extreme net short positioning detected — crowded shorts, short-covering risk."]
        )
    }
}

// === REGIME LABEL (plotPriceLabel) ===
if (showRegimeLabel && isLastBar) {
    plotPriceLabel(
        price=h,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}