MM Flow
FlowScripts

Perfected FlowScript

Flow and Position Oscillator

Flow and Position Oscillator — Perfected Edition is indexed as 144_flow_and_position_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

19.6 KB

Lines

596

Native Signal Candidates

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

8/8 guarded

Bull Cross

line 484:9

Trigger

(showShapes) && (crossUp)

Value

oscFinal

Deps

crossUp:var, showShapes:input

Bear Cross

line 494:9

Trigger

(showShapes) && (crossDown)

Value

oscFinal

Deps

crossDown:var, showShapes:input

Extreme Bull

line 504:9

Trigger

(showShapes) && (extremeBull)

Value

oscFinal

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 514:9

Trigger

(showShapes) && (extremeBear)

Value

oscFinal

Deps

extremeBear:var, showShapes:input

Sig Cross Up

line 524:9

Trigger

(showShapes) && (sigCrossUp)

Value

oscFinal

Deps

showShapes:input, sigCrossUp:var

Sig Cross Down

line 534:9

Trigger

(showShapes) && (sigCrossDown)

Value

oscFinal

Deps

showShapes:input, sigCrossDown:var

Bull Div

line 544:9

Trigger

(showShapes) && (bullDiv)

Value

oscFinal

Deps

bullDiv:var, showShapes:input

Bear Div

line 554:9

Trigger

(showShapes) && (bearDiv)

Value

oscFinal

Deps

bearDiv:var, showShapes:input

144_flow_and_position_oscillator.flowscript

source path: kscripts/perfected/144_flow_and_position_oscillator.flowscript · sha256:f44344d6f3a2e3a3532e8dfd1eb588b92e3b5cf67399121f2d81f2d4c96cda61

hash verified
//@version=2
// ============================================================================
// Flow and Position Oscillator — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #flow, #position, #cvd, #oi, #oscillator, #zscore, #regime
//
// Production-grade composite oscillator blending taker imbalance (CVD proxy),
// open interest delta, volume z-score, and long/short ratio positioning into a
// unified flow-pressure gauge with z-score normalization, regime detection,
// color-coded histogram, and shape-marked event alerts.
//
// Academic foundations:
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//    (J. Financial Econometrics, 12(1), 47–88). Taker imbalance = (V_buy −
//    V_sell) / V_total is a direct implementation of OFI. Linear relationship
//    between OFI and short-term price changes; slope inversely proportional to
//    market depth. Key formula: OFI_t = Σ(E⁺_t − E⁻_t).
//  - Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns" (J. Financial Economics, 65(1), 111–130). Order imbalance
//    is distinct from volume; market returns strongly affected by contemporaneous
//    and lagged imbalances. Extreme imbalances predict return reversals.
//  - Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
//    Returns" (J. Finance, 61(4), 1645–1680). Composite sentiment = PCA of
//    multiple proxies. Supports combining taker imbalance, positioning, and
//    volume proxies into a single standardized index.
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
//    and Open Interest in Futures Contracts" (J. Finance, 50(1), 281–300).
//    Open interest levels contain information about future volatility and market
//    expectations. Unexpected OI changes have larger impact than expected.
//  - Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//    Activity" (SSRN 1989555). BVC method: probabilistic classification of
//    volume in aggregate buckets based on price-change distribution. More robust
//    in HFT environments than tick-rule methods. Underpins volume-z-score boost.
//  - Lillo & Farmer (2004), "The Long Memory of the Efficient Market" (Studies
//    in Nonlinear Dynamics & Econometrics, 8(3), 1–35). Order flow has long-
//    memory properties (autocorrelations decay as power law). Cumulative
//    measures capture sustained pressure that drives trends.
// ============================================================================

define(
    title="Flow and Position Oscillator — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Flow Components ---
var takerLookback = input(
    name="takerLookback",
    type="number",
    defaultValue=1,
    label="Taker Imbalance Lookback (bars)",
    constraints={min: 1, max: 10, step: 1},
    group="Flow Components"
)
var useCvd = input(
    name="useCvd",
    type="boolean",
    defaultValue=true,
    label="Include Cumulative Volume Delta (CVD)",
    group="Flow Components"
)
var cvdLen = input(
    name="cvdLen",
    type="number",
    defaultValue=20,
    label="CVD Smoothing Length",
    constraints={min: 5, max: 100, step: 1},
    group="Flow Components"
)
var useOi = input(
    name="useOi",
    type="boolean",
    defaultValue=true,
    label="Include Open Interest Delta",
    group="Flow Components"
)
var oiLen = input(
    name="oiLen",
    type="number",
    defaultValue=20,
    label="OI Delta Smoothing Length",
    constraints={min: 5, max: 100, step: 1},
    group="Flow Components"
)

// --- Volume Z-Score ---
var volZLen = input(
    name="volZLen",
    type="number",
    defaultValue=30,
    label="Volume Z-Score Lookback",
    constraints={min: 10, max: 100, step: 1},
    group="Volume Z-Score"
)
var volZWeight = input(
    name="volZWeight",
    type="number",
    defaultValue=0.5,
    label="Volume Z-Score Weight",
    constraints={min: 0.0, max: 2.0, step: 0.1},
    group="Volume Z-Score"
)

// --- L/S Ratio ---
var useLs = input(
    name="useLs",
    type="boolean",
    defaultValue=true,
    label="Include L/S Ratio Z-Score",
    group="L/S Ratio"
)
var lsZLen = input(
    name="lsZLen",
    type="number",
    defaultValue=30,
    label="L/S Ratio Z-Score Lookback",
    constraints={min: 10, max: 100, step: 1},
    group="L/S Ratio"
)
var lsWeight = input(
    name="lsWeight",
    type="number",
    defaultValue=0.5,
    label="L/S Ratio Weight (0–1)",
    constraints={min: 0.0, max: 2.0, step: 0.1},
    group="L/S Ratio"
)

// --- Z-Score Normalization ---
var zScoreNorm = input(
    name="zScoreNorm",
    type="boolean",
    defaultValue=true,
    label="Z-Score Normalize Composite",
    group="Z-Score Normalization"
)
var zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 20, max: 200, step: 1},
    group="Z-Score Normalization"
)
var clipLimit = input(
    name="clipLimit",
    type="number",
    defaultValue=3.0,
    label="Clip Limit (std devs)",
    constraints={min: 1.0, max: 6.0, step: 0.5},
    group="Z-Score Normalization"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Final Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)
var useEma = input(
    name="useEma",
    type="boolean",
    defaultValue=true,
    label="Use EMA (off = SMA)",
    group="Smoothing"
)

// --- Display ---
var showZero = input(
    name="showZero",
    type="boolean",
    defaultValue=true,
    label="Show Zero Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Flow Histogram",
    group="Display"
)
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Event Shapes",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show Oscillator / Signal Fill",
    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 strongBullColor = input(
    name="strongBullColor",
    type="color",
    defaultValue="#00e676",
    label="Strong Bullish Color",
    group="Colors"
)
var strongBearColor = input(
    name="strongBearColor",
    type="color",
    defaultValue="#ff1744",
    label="Strong Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Signal Line Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

if (isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0])) {
    return
}

// L/S ratio data (best-effort; falls back to neutral if unavailable)
timeseries lsrSrc = long_short_ratio(symbol=currentSymbol, exchange=currentExchange)
timeseries lsr = isnan(lsrSrc.total_account[0]) ? 1.0 : lsrSrc.total_account

// Open interest data (best-effort; falls back to volume proxy if unavailable)
timeseries oiSrc = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = isnan(oiSrc[0]) ? v : oiSrc

// ------------------------------------------------------------------------------
// 3. TAKER IMBALANCE (CVD proxy per Cont-Kukanov-Stoikov 2014)
// ------------------------------------------------------------------------------
// Per-bar taker imbalance using mid-price classification (BVC method).
// Mid = (high + low) / 2; close >= mid → buyer-initiated; else seller-initiated.
timeseries mid = (h + l) / 2.0
timeseries buyV = (c >= mid) ? v : 0.0
timeseries sellV = (c < mid) ? v : 0.0
timeseries takerImbal = (buyV - sellV) / math.max(v, 1e-9)

// Cumulative Volume Delta (CVD): long-memory accumulation of taker imbalance.
// Per Lillo & Farmer (2004), cumulative measures capture sustained order-flow
// pressure that drives trends. We track cumulative delta, then smooth it.
static cvd = 0.0
if (!isLiveUpdate) {
    cvd = cvd + takerImbal
}
timeseries cvdSmooth = useCvd ? (useEma ? ema(cvd, cvdLen) : sma(cvd, cvdLen)) : 0.0

// ------------------------------------------------------------------------------
// 4. OPEN INTEREST DELTA
// ------------------------------------------------------------------------------
// Per Chen, Cuny & Haugen (1995), unexpected OI changes carry more predictive
// power than absolute levels. We compute bar-to-bar OI delta and smooth it.
timeseries oiDelta = oi - nz(oi[1])
timeseries oiDeltaSmooth = useOi ? (useEma ? ema(oiDelta, oiLen) : sma(oiDelta, oiLen)) : 0.0

// ------------------------------------------------------------------------------
// 5. VOLUME Z-SCORE BOOST
// ------------------------------------------------------------------------------
// Per Easley, López de Prado & O'Hara (2012), BVC improves robustness in HFT
// by using volume-bucket probabilistic classification. We boost the signal when
// activity is above average (positive z-score only, to avoid suppression).
timeseries vMean = sma(v, volZLen)
timeseries vStd = stdev(v, volZLen)
timeseries vZ = (v - vMean) / math.max(vStd, 1e-9)
timeseries vBoost = math.max(vZ, 0.0) * volZWeight

// ------------------------------------------------------------------------------
// 6. L/S RATIO Z-SCORE
// ------------------------------------------------------------------------------
// Per Baker & Wurgler (2006), sentiment/positioning proxies are informative
// when combined into a composite. L/S ratio z-score amplifies signal when
// positioning shifts sharply (crowding / squeeze dynamics).
timeseries lsrMean = sma(lsr, lsZLen)
timeseries lsrStd = stdev(lsr, lsZLen)
timeseries lsrZ = (lsr - lsrMean) / math.max(lsrStd, 1e-9)

// ------------------------------------------------------------------------------
// 7. COMPOSITE OSCILLATOR
// ------------------------------------------------------------------------------
// Base = taker imbalance + CVD smooth + OI delta smooth, boosted by volume z.
timeseries base = takerImbal + (useCvd ? cvdSmooth * 0.5 : 0.0) + (useOi ? oiDeltaSmooth * 0.5 : 0.0)
timeseries baseBoosted = base * (1.0 + vBoost)

// L/S amplification (optional)
timeseries withLs = (useLs) ? baseBoosted * (1.0 + lsrZ * lsWeight) : baseBoosted

// Z-score normalization of the composite (standardize to mean 0, std 1)
timeseries compMean = sma(withLs, zScoreLen)
timeseries compStd = stdev(withLs, zScoreLen)
timeseries compZ = (withLs - compMean) / math.max(compStd, 1e-9)

// Clip to limit spikes, then smooth
timeseries rawOsc = zScoreNorm ? compZ : withLs
timeseries clipped = math.min(math.max(rawOsc, -clipLimit), clipLimit)

// Final smoothing
timeseries oscEma = ema(clipped, smoothLen)
timeseries oscSma = sma(clipped, smoothLen)
timeseries oscFinal = useEma ? oscEma : oscSma

// Signal line (SMA of oscillator)
timeseries signal = sma(oscFinal, smoothLen * 2)

// Histogram (oscillator minus signal)
timeseries hist = oscFinal - signal

// ------------------------------------------------------------------------------
// 8. REGIME DETECTION
// ------------------------------------------------------------------------------
// Regime classification based on oscillator value, signal cross, and slope:
//   Strong Bull: osc > signal AND osc > 0 AND osc > 1 (above +1 std)
//   Bull: osc > signal AND osc > 0
//   Strong Bear: osc < signal AND osc < 0 AND osc < -1 (below -1 std)
//   Bear: osc < signal AND osc < 0
//   Neutral: everything else (chop / transition zone)

var regimeStrongBull = oscFinal > signal && oscFinal > 0 && oscFinal > 1.0
var regimeBull = oscFinal > signal && oscFinal > 0 && !regimeStrongBull
var regimeStrongBear = oscFinal < signal && oscFinal < 0 && oscFinal < -1.0
var regimeBear = oscFinal < signal && oscFinal < 0 && !regimeStrongBear
var regimeNeutral = !regimeBull && !regimeBear && !regimeStrongBull && !regimeStrongBear

var regimeColor = regimeStrongBull ? strongBullColor : (regimeBull ? bullColor : (regimeStrongBear ? strongBearColor : (regimeBear ? bearColor : neutralColor)))

// ------------------------------------------------------------------------------
// 9. EVENT FLAGS & SHAPE MARKERS
// ------------------------------------------------------------------------------
// Zero cross events
var crossUp = oscFinal > 0 && oscFinal[1] <= 0
var crossDown = oscFinal < 0 && oscFinal[1] >= 0

// Extreme penetration events (beyond ±2 std)
var extremeBull = oscFinal > 2.0 && oscFinal[1] <= 2.0
var extremeBear = oscFinal < -2.0 && oscFinal[1] >= -2.0

// Signal cross events
var sigCrossUp = oscFinal > signal && oscFinal[1] <= signal[1]
var sigCrossDown = oscFinal < signal && oscFinal[1] >= signal[1]

// Divergence detection (stateful via static)
static prevOscHigh = -1.0
static prevOscLow = -1.0
static prevPxHigh = -1.0
static prevPxLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevOscHigh < 0) {
    prevOscHigh = oscFinal[0]
    prevOscLow = oscFinal[0]
    prevPxHigh = h[0]
    prevPxLow = l[0]
}

if (!isLiveUpdate) {
    // Regular bearish divergence: price higher high, oscillator lower high
    if (h[0] > prevPxHigh) {
        if (oscFinal[0] < prevOscHigh) {
            bearDiv = true
        }
        prevPxHigh = h[0]
        prevOscHigh = oscFinal[0]
    }
    // Regular bullish divergence: price lower low, oscillator higher low
    if (l[0] < prevPxLow) {
        if (oscFinal[0] > prevOscLow) {
            bullDiv = true
        }
        prevPxLow = l[0]
        prevOscLow = oscFinal[0]
    }
}

// ------------------------------------------------------------------------------
// 10. PLOTTING
// ------------------------------------------------------------------------------

// --- Zero line ---
if (showZero) {
    hline(value=0, color="#ffffff30", width=1)
    hline(value=1, color=transparency(bullColor, 80), width=1)
    hline(value=-1, color=transparency(bearColor, 80), width=1)
    hline(value=2, color=transparency(bullColor, 90), width=1)
    hline(value=-2, color=transparency(bearColor, 90), width=1)
}

// --- Oscillator line (regime-colored) ---
plotLine(
    value=oscFinal,
    width=2,
    colors=[regimeColor],
    label=["Flow & Position Osc"],
    desc=["Composite flow and positioning oscillator. Regime-colored: green = bull, red = bear, gray = neutral."]
)

// --- Signal line ---
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal"],
        desc=["SMA of oscillator — trend of flow pressure. Crosses mark regime shifts."]
    )
}

// --- Ribbon fill (oscillator vs signal) ---
if (showRibbon && showSignal) {
    var ribbonBull = oscFinal > signal
    plotLine(
        value=[oscFinal, signal],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Osc", "Signal"],
        desc=["Fill between oscillator and signal SMA", "Fill between oscillator and signal SMA"]
    )
}

// --- Histogram (color-coded by regime) ---
if (showHistogram) {
    var histColor = regimeStrongBull ? strongBullColor : (regimeBull ? bullColor : (regimeStrongBear ? strongBearColor : (regimeBear ? bearColor : neutralColor)))
    plotBar(
        value=hist,
        colors=[histColor],
        label=["Flow Histogram"],
        desc=["Momentum histogram: oscillator minus signal. Positive = pressure building, Negative = pressure fading."]
    )
}

// --- Shape markers ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=oscFinal,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Bull Cross"],
            desc=["Oscillator crossed above zero: buyers took control."]
        )
    }
    if (crossDown) {
        plotShape(
            value=oscFinal,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Bear Cross"],
            desc=["Oscillator crossed below zero: sellers took control."]
        )
    }
    if (extremeBull) {
        plotShape(
            value=oscFinal,
            shape="xcross",
            colorIndex=strongBullColor,
            width=2,
            label=["Extreme Bull"],
            desc=["Oscillator exceeded +2 std: possible overextension."]
        )
    }
    if (extremeBear) {
        plotShape(
            value=oscFinal,
            shape="xcross",
            colorIndex=strongBearColor,
            width=2,
            label=["Extreme Bear"],
            desc=["Oscillator exceeded -2 std: possible overextension."]
        )
    }
    if (sigCrossUp) {
        plotShape(
            value=oscFinal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Sig Cross Up"],
            desc=["Oscillator crossed above signal: momentum shift bullish."]
        )
    }
    if (sigCrossDown) {
        plotShape(
            value=oscFinal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Sig Cross Down"],
            desc=["Oscillator crossed below signal: momentum shift bearish."]
        )
    }
    if (bullDiv) {
        plotShape(
            value=oscFinal,
            shape="arrowup",
            colorIndex=strongBullColor,
            width=1,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, oscillator higher low."]
        )
    }
    if (bearDiv) {
        plotShape(
            value=oscFinal,
            shape="arrowdown",
            colorIndex=strongBearColor,
            width=1,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, oscillator lower high."]
        )
    }
}

// ------------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeStrongBull ? "STRONG BULL" : (regimeBull ? "BULL" : (regimeStrongBear ? "STRONG BEAR" : (regimeBear ? "BEAR" : "NEUTRAL")))
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["Flow & Position — Perfected", regimeText],
            ["Oscillator", oscFinal[0]],
            ["Signal", signal[0]],
            ["Histogram", hist[0]],
            ["CVD", cvdSmooth[0]],
            ["OI Delta", oiDeltaSmooth[0]],
            ["Vol Z", vZ[0]],
            ["L/S Z", lsrZ[0]]
        ],
        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
    )
}