MM Flow
FlowScripts

Perfected FlowScript

Net Position Flow

Net Position Flow — OI & Flow Toxicity is indexed as 047_net_position_flow.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

9.9 KB

Lines

227

Native Signal Candidates

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

3/3 guarded

Extreme Long Flow

line 178:9

Trigger

(showExtremeShapes) && (extremeLongEvent)

Value

zScore

Deps

extremeLongEvent:var, showExtremeShapes:input

Extreme Short Flow

line 188:9

Trigger

(showExtremeShapes) && (extremeShortEvent)

Value

zScore

Deps

extremeShortEvent:var, showExtremeShapes:input

Unlabeled shape

line 217:5

Trigger

(showTrendLabel && isLastBar)

Value

zScore

Deps

isLastBar:builtin, showTrendLabel:input

047_net_position_flow.flowscript

source path: kscripts/perfected/047_net_position_flow.flowscript · sha256:4bba6c91ec3edd2cc7a93f21781081b9bc359aa459f651ba3e11aa96269ae33d

hash verified
//@version=2
// ============================================================================
// Net Position Flow — Open Interest, Positioning & Flow Toxicity
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #netposition, #flow, #openinterest, #positioning, #zscore, #vpin
//
// Production-grade net position flow indicator combining OI delta magnitude
// with tick-direction proxy (OFI sign), z-score normalization, regime
// detection, and extreme positioning alerts. Implements the OI-Price-Volume
// framework with flow toxicity scoring.
//
// Academic foundations:
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//    (J. Financial Econometrics). Price impact model: ΔP = λ·OFI + ε,
//    where OFI = Σ sign(ΔBid)·ΔVolBid + sign(ΔAsk)·ΔVolAsk. Validates
//    that order flow imbalance (OFI) is a strong predictor of short-term
//    price movements.
//  - Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity"
//    (VPIN, JFM). Volume-synchronized probability of informed trading:
//    VPIN = Σ|α_j - β_j| / (2μ·V), where α_j = buy volume, β_j = sell volume
//    in volume bucket j. VPIN predicts liquidity stress and price volatility.
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and Open Interest"
//    (J. Finance, 50(1), 281-300). Higher open interest is associated with
//    greater information flow and price discovery activity. OI levels contain
//    predictive information about future volatility.
//  - Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
//    (RFS, 22(6)). Liquidity spirals: when funding liquidity is tight, traders
//    reduce positions, lowering market liquidity, which amplifies volatility.
//    Extreme positioning is a precursor to forced deleveraging.
//  - Harris (1986), "A Transaction Data Study of Weekly and Intradaily Patterns
//    in Stock Returns" (JFE, 16(1)). Intraday seasonality in volume and
//    volatility; opening period shows distinct price discovery dynamics.
//    Supports session-based flow normalization.
//  - He & Manela (2022), "Fundamentals of Perpetual Futures" (JFE, arXiv:2212.06888).
//    No-arbitrage perpetual futures pricing; past return momentum explains
//    futures-spot gap with R² > 50%. Supports flow momentum as a fair-value
//    deviation signal.
// ============================================================================

define(title="Net Position Flow — OI & Flow Toxicity", position="offchart", axis=true)

// === USER INPUTS ===
// --- Flow Calculation ---
var rollLen = input(name="rollLen", type="number", defaultValue=14, label="Rolling Aggregation Length", constraints={min: 5, max: 100, step: 1}, group="Flow Calculation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Flow Calculation")
var zScoreLen = input(name="zScoreLen", type="number", defaultValue=20, label="Z-Score Lookback Length", constraints={min: 10, max: 100, step: 1}, group="Flow Calculation")
var src = input(name="src", type="select", defaultValue="hlc3", label="Source Price", options=["close", "hlc3"], group="Flow Calculation")
var useVolWeight = input(name="useVolWeight", type="boolean", defaultValue=true, label="Volume-Weight Flow", group="Flow Calculation")

// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Flow Histogram", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showTrendLabel = input(name="showTrendLabel", type="boolean", defaultValue=true, label="Show Flow Regime Label", group="Display")
var showExtremeShapes = input(name="showExtremeShapes", type="boolean", defaultValue=true, label="Show Extreme Positioning Shapes", group="Display")
var showZeroLine = input(name="showZeroLine", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")

// --- Thresholds ---
var extremeThreshold = input(name="extremeThreshold", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold (σ)", constraints={min: 1.0, max: 4.0, step: 0.1}, group="Thresholds")
var regimeLookback = input(name="regimeLookback", type="number", defaultValue=50, label="Regime Detection Lookback", constraints={min: 20, max: 200, step: 1}, group="Thresholds")

// --- Colors ---
var netLongColor = input(name="netLongColor", type="color", defaultValue="#26a69a", label="Net Long Color (Flow > 0)", group="Colors")
var netShortColor = input(name="netShortColor", type="color", defaultValue="#ef5350", label="Net Short Color (Flow < 0)", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#ffd700", label="Z-Score Line Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff00ff", label="Extreme Shape Color", group="Colors")
var zeroLineColor = input(name="zeroLineColor", type="color", defaultValue="#88888860", label="Zero Line Color", group="Colors")

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

// Open interest data
timeseries oiRaw = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = oiRaw.close

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

// === COMPUTATION ===
timeseries source = src == "close" ? c : (h + l + c) / 3.0

// OFI Sign Proxy (tick direction): +1 for up-tick, -1 for down-tick
// This is the standard Cont-Kukanov-Stoikov (2014) tick-direction proxy when
// full order-book data is unavailable.
timeseries tickDir = c >= o ? 1.0 : -1.0

// |ΔOI| × sign(OFI) — the core net position flow metric
// Positive = net long creation (or short covering); Negative = net short creation
timeseries dOI = oi - oi[1]
timeseries flowRaw = math.abs(dOI) * tickDir

// Volume-weighted flow for instruments where volume is meaningful
timeseries volWeight = useVolWeight ? (v / math.max(sma(v, 20), 1.0)) : 1.0
timeseries flowWeighted = flowRaw * volWeight

// Rolling aggregation and smoothing
timeseries flowAgg = sma(flowWeighted, rollLen)
timeseries flowSm = smoothLen > 1 ? ema(flowAgg, smoothLen) : flowAgg

// Z-Score normalization: z = (flow - μ) / σ
// Where μ = SMA(flow, zScoreLen) and σ = standard deviation over same window
timeseries flowMean = sma(flowSm, zScoreLen)
timeseries flowDev = stdev(flowSm, zScoreLen)
timeseries zScore = flowDev > 0 ? (flowSm - flowMean) / flowDev : 0.0

// Regime detection: trend of the smoothed flow over regimeLookback
timeseries flowTrend = flowSm - flowSm[regimeLookback]
var isNetLong = flowSm >= 0
var isNetLongTrend = flowTrend >= 0

// === EXTREME POSITIONING DETECTION ===
// Extreme positioning when z-score exceeds ±extremeThreshold
var extremeLong = zScore >= extremeThreshold
var extremeShort = zScore <= -extremeThreshold
var extremeEvent = extremeLong || extremeShort

// === SESSION TRACKING (static) ===
static lastExtremeLongBar = 0
static lastExtremeShortBar = 0
static barCount = 0

if (!isLiveUpdate) {
    barCount = barCount + 1
    if (extremeLong) {
        lastExtremeLongBar = barCount
    }
    if (extremeShort) {
        lastExtremeShortBar = barCount
    }
}

var extremeLongEvent = lastExtremeLongBar == barCount
var extremeShortEvent = lastExtremeShortBar == barCount

// === PLOTS: FLOW HISTOGRAM (plotBar) ===
if (showHistogram) {
    var barColor = flowSm >= 0 ? netLongColor : netShortColor
    plotBar(
        value=flowSm,
        colors=[barColor],
        width=2,
        label=["Net Position Flow"],
        desc=["|ΔOI| × sign(OFI) volume-weighted: >0 net long creation, <0 net short creation / long close"]
    )
}

// === PLOTS: Z-SCORE LINE (plotLine) ===
if (showZScore) {
    plotLine(
        value=zScore,
        width=2,
        colors=[zScoreColor],
        label=["Flow Z-Score"],
        desc=["Z-score of net position flow: (flow - μ) / σ over " + zScoreLen + " bars. ±2σ = extreme."]
    )
}

// === PLOTS: ZERO LINE ===
if (showZeroLine) {
    plotLine(
        value=0,
        width=1,
        colors=[zeroLineColor],
        label=["Zero Line"],
        desc=["Equilibrium: net longs = net shorts"]
    )
}

// === PLOTS: EXTREME POSITIONING SHAPES ===
if (showExtremeShapes) {
    if (extremeLongEvent) {
        plotShape(
            value=zScore,
            shape="triangleup",
            colorIndex=extremeColor,
            width=5,
            label=["Extreme Long Flow"],
            desc=["Z-Score >= +" + extremeThreshold + "σ: extreme net long positioning. Crowded long = contrarian reversal risk."]
        )
    }
    if (extremeShortEvent) {
        plotShape(
            value=zScore,
            shape="triangledown",
            colorIndex=extremeColor,
            width=5,
            label=["Extreme Short Flow"],
            desc=["Z-Score <= -" + extremeThreshold + "σ: extreme net short positioning. Crowded short = squeeze risk."]
        )
    }
}

// === REGIME LABEL (plotPriceLabel) ===
if (showTrendLabel && isLastBar) {
    var regimeLabel = ""
    var regimeColor = "#ffffff"
    if (isNetLong && isNetLongTrend) {
        regimeLabel = "NET LONG — TRENDING LONG"
        regimeColor = netLongColor
    } else if (isNetLong && !isNetLongTrend) {
        regimeLabel = "NET LONG — WEAKENING"
        regimeColor = "#4db6ac"
    } else if (!isNetLong && !isNetLongTrend) {
        regimeLabel = "NET SHORT — TRENDING SHORT"
        regimeColor = netShortColor
    } else {
        regimeLabel = "NET SHORT — WEAKENING"
        regimeColor = "#ef9a9a"
    }

    plotPriceLabel(
        price=zScore,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}