MM Flow
FlowScripts

Perfected FlowScript

SCF Onboard Volume

SCF Onboard Volume [Perfected] is indexed as 112_scf_onboard_volume.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.7 KB

Lines

328

Native Signal Candidates

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

6/6 guarded

Flow Cross Up

line 269:5

Trigger

(showShapes && flowCrossUp)

Value

flow

Deps

flowCrossUp:var, showShapes:input

Flow Cross Down

line 279:5

Trigger

(showShapes && flowCrossDown)

Value

flow

Deps

flowCrossDown:var, showShapes:input

Zero Cross Up

line 289:5

Trigger

(showShapes && zeroCrossUp)

Value

0

Deps

showShapes:input, zeroCrossUp:var

Zero Cross Down

line 299:5

Trigger

(showShapes && zeroCrossDown)

Value

0

Deps

showShapes:input, zeroCrossDown:var

Z+3 Extreme

line 309:5

Trigger

(showShapes && zRarePos)

Value

flow

Deps

showShapes:input, zRarePos:var

Z-3 Extreme

line 319:5

Trigger

(showShapes && zRareNeg)

Value

flow

Deps

showShapes:input, zRareNeg:var

112_scf_onboard_volume.flowscript

source path: kscripts/perfected/112_scf_onboard_volume.flowscript · sha256:6ccfad89b2237f6124ee5b4235ca9e32aa33cb9e55240d0c620ef407df4ec649

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

// ============================================================================
// SCF Onboard Volume [Perfected Edition]
// Author: SoulzBTC (@SoulzBTC) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #volume, #onboard, #delta, #zscore, #orderflow, #soulzbtc
//
// Production-grade onboard volume analysis combining Lee-Ready trade
// classification, Cont-Kukanov-Stoikov order flow imbalance (OFI), volume
// profile concepts, z-score normalization, and Bulk Volume Classification
// (BVC) for robust volume-based scalping signals.
//
// Research papers underpinning this design:
//  - Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//    foundational quote-rule classification (~85% accuracy); trade at ask
//    = buyer-initiated (+), at bid = seller-initiated (−).
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//    OFI explains ~65% of contemporaneous mid-price changes; ΔP ≈ λ·OFI.
//  - Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
//    Activity": probabilistic BVC classification superior to tick-rule in HFT.
//  - Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns": extreme order imbalances predict return reversals.
//  - Lillo & Farmer (2004), "The Long Memory of the Efficient Market":
//    order flow has long-memory properties; cumulative measures capture
//    sustained pressure that drives trends.
//  - Steidlmayer & Hawkins (2003), "Steidlmayer on Markets": volume profile
//    concepts (POC, Value Area) as auction-market equilibrium framework.
// ============================================================================

define(
    title="SCF Onboard Volume [Perfected]",
    position="offchart",
    axis=true
)

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

// --- Flow Group ---
var flowLen = input(name="flowLen", type="number", defaultValue=14, label="Flow Lookback", constraints={min: 5, max: 100, step: 1}, group="Flow")
var smoothLen = input(name="smoothLen", type="number", defaultValue=7, label="Smoothing Length", constraints={min: 2, max: 50, step: 1}, group="Flow")
var useEma = input(name="useEma", type="boolean", defaultValue=true, label="Use EMA (off = SMA)", group="Flow")
var zScoreLen = input(name="zScoreLen", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Flow")
var showVolumeProfile = input(name="showVolumeProfile", type="boolean", defaultValue=true, label="Show Volume Profile Estimates", group="Flow")

// --- Display Group ---
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal Line", group="Display")
var showZeroLine = input(name="showZeroLine", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Band", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Signal Shapes", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors Group ---
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 bullWeakColor = input(name="bullWeakColor", type="color", defaultValue="#4db6ac", label="Bullish Weak Color", group="Colors")
var bearWeakColor = input(name="bearWeakColor", type="color", defaultValue="#ef9a9a", label="Bearish Weak Color", group="Colors")
var signalColor = input(name="signalColor", type="color", defaultValue="#ffffff", label="Signal Line Color", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#ffd700", label="Z-Score Extreme Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries closePx = bars.close
timeseries openPx = bars.open
timeseries highPx = bars.high
timeseries lowPx = bars.low
timeseries vol = bars.volume
timeseries t = bars.time

// isnan guard on first use of external data
if (isnan(closePx[0]) || isnan(openPx[0]) || isnan(highPx[0]) || isnan(lowPx[0]) || isnan(vol[0]) || isnan(t[0])) {
    return
}

// ---------------------------------------------------------------------------
// Classification (Lee-Ready style quote-rule proxy + BVC enhancement)
// ---------------------------------------------------------------------------
timeseries mid = (highPx + lowPx) / 2.0

// Quote-rule proxy: close >= midpoint = buyer-initiated, else seller-initiated
timeseries buyVol = (closePx >= mid) ? vol : 0.0
timeseries sellVol = (closePx < mid) ? vol : 0.0
timeseries delta = buyVol - sellVol

// BVC-style enhancement: weight delta by bar range position
// Close near high = more buy pressure; close near low = more sell pressure
timeseries barRange = highPx - lowPx
var barRangeSafe = barRange > 0 ? barRange : 1.0
timeseries barPos = (closePx - lowPx) / barRangeSafe
timeseries bvcDelta = vol * (barPos - 0.5) * 2.0  // Scale to [-vol, +vol]

// Combine quote-rule and BVC (average for robustness)
timeseries blendedDelta = (delta + bvcDelta) / 2.0

// ---------------------------------------------------------------------------
// Rolling OFI proxy: sum of blended delta over flowLen
// ---------------------------------------------------------------------------
timeseries ofiRaw = sum(blendedDelta, flowLen)

// --- Volume Profile Estimates (Steidlmayer-inspired) ---
// Approximate POC as the price with highest volume in the lookback window
static volAtPriceHigh = 0.0
static volAtPriceLow = 0.0
static volAtPrice = 0.0

// Volume-weighted typical price as proxy for Value Area High / Low
timeseries vwTyp = (highPx + lowPx + closePx) / 3.0
timeseries volProfile = sum(vol, flowLen)
timeseries volWtdHi = sum(highPx * vol, flowLen) / (sum(vol, flowLen) > 0 ? sum(vol, flowLen) : 1.0)
timeseries volWtdLo = sum(lowPx * vol, flowLen) / (sum(vol, flowLen) > 0 ? sum(vol, flowLen) : 1.0)

// Value Area approximation: ~70% of volume within this range
timeseries valueArea = volWtdHi - volWtdLo

// ---------------------------------------------------------------------------
// Smoothing
// ---------------------------------------------------------------------------
timeseries flowEma = ema(ofiRaw, smoothLen)
timeseries flowSma = sma(ofiRaw, smoothLen)
timeseries flow = useEma ? flowEma : flowSma

// Signal line: slower smoothing of the flow
timeseries sig = ema(flow, max(smoothLen * 2, 3))

// ---------------------------------------------------------------------------
// Z-Score Normalization of Flow
// ---------------------------------------------------------------------------
timeseries flowMean = sma(flow, zScoreLen)
timeseries flowDev = stdev(flow, zScoreLen)
timeseries flowZ = (flowDev > 0) ? (flow - flowMean) / flowDev : 0.0

// Z-score extremes: |z| > 2 = statistical extreme, |z| > 3 = rare event
var zExtremePos = flowZ > 2.0
var zExtremeNeg = flowZ < -2.0
var zRarePos = flowZ > 3.0
var zRareNeg = flowZ < -3.0

// ---------------------------------------------------------------------------
// Regime & Strength Detection
// ---------------------------------------------------------------------------
var isBull = flow > 0
var isStrong = flow > sig && flow > 0
var isWeak = flow < sig && flow > 0
var isStrongBear = flow < sig && flow < 0
var isWeakBear = flow > sig && flow < 0

// Confluence strength: 0=neutral, 1=weak bull, 2=strong bull, -1=weak bear, -2=strong bear
var strength = 0
if (flow > 0) {
    if (flow > sig) {
        strength = 2
    } else {
        strength = 1
    }
} else if (flow < 0) {
    if (flow < sig) {
        strength = -2
    } else {
        strength = -1
    }
}

// Color mapping by strength and z-score
timeseries flowColor = isBull ? (isStrong ? bullColor : bullWeakColor) : (isStrongBear ? bearColor : bearWeakColor)

// ---------------------------------------------------------------------------
// Cross Detection (shape markers)
// ---------------------------------------------------------------------------
static prevFlow = 0.0
static prevSig = 0.0
var flowCrossUp = prevFlow <= prevSig && flow > sig
var flowCrossDown = prevFlow >= prevSig && flow < sig
var zeroCrossUp = prevFlow <= 0 && flow > 0
var zeroCrossDown = prevFlow >= 0 && flow < 0
var sigCrossUp = cross(flow, sig) && flow > sig
var sigCrossDown = cross(flow, sig) && flow < sig

prevFlow = flow
prevSig = sig

// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------

// --- Histogram of raw blended delta (background) ---
timeseries normDelta = ofiRaw / max(rma(vol, flowLen) * 0.5, 1.0)
plotBar(
    value=normDelta,
    colors=[flowColor],
    label=["OFI Norm"],
    desc=["Normalized order flow imbalance — blended Lee-Ready + BVC classification"]
)

// --- Main flow line (strength-colored) ---
plotLine(
    value=flow,
    width=lineWidth,
    colors=[bullColor, bearColor, bullWeakColor, bearWeakColor],
    colorIndex=strength == 2 ? 0 : (strength == -2 ? 1 : (strength == 1 ? 2 : 3)),
    label=["Onboard Flow"],
    desc=["Smoothed order flow imbalance. Positive = buy-side dominance; negative = sell-side dominance."]
)

// --- Signal line ---
if (showSignal) {
    plotLine(
        value=sig,
        width=1,
        colors=[signalColor],
        label=["Signal"],
        desc=["Slower signal line for cross confirmation"]
    )
}

// --- Zero line ---
if (showZeroLine) {
    plotLine(
        value=0,
        width=1,
        colors=["#ffffff40"],
        label=["Zero"],
        desc=["Zero line — no net flow bias"]
    )
}

// --- Z-Score bands (+2 / -2) ---
if (showZScore) {
    plotLine(
        value=2,
        width=1,
        colors=["#ffffff20"],
        label=["Z+2"],
        desc=["Z-score +2 threshold — statistical extreme"]
    )
    plotLine(
        value=-2,
        width=1,
        colors=["#ffffff20"],
        label=["Z-2"],
        desc=["Z-score -2 threshold — statistical extreme"]
    )
}

// --- Volume Profile Estimates (POC / Value Area boundaries) ---
if (showVolumeProfile) {
    plotLine(
        value=volWtdHi,
        width=1,
        colors=["#ffffff30"],
        label=["Vol Wtd High"],
        desc=["Volume-weighted high — proxy for Value Area High (Steidlmayer)"]
    )
    plotLine(
        value=volWtdLo,
        width=1,
        colors=["#ffffff30"],
        label=["Vol Wtd Low"],
        desc=["Volume-weighted low — proxy for Value Area Low (Steidlmayer)"]
    )
}

// --- Shape Markers ---
if (showShapes && flowCrossUp) {
    plotShape(
        value=flow,
        shape="triangleup",
        colorIndex=bullColor,
        width=shapeSize,
        label=["Flow Cross Up"],
        desc=["Onboard flow crossed above signal line — bullish momentum confirmed"]
    )
}
if (showShapes && flowCrossDown) {
    plotShape(
        value=flow,
        shape="triangledown",
        colorIndex=bearColor,
        width=shapeSize,
        label=["Flow Cross Down"],
        desc=["Onboard flow crossed below signal line — bearish momentum confirmed"]
    )
}
if (showShapes && zeroCrossUp) {
    plotShape(
        value=0,
        shape="triangleup",
        colorIndex=bullWeakColor,
        width=shapeSize,
        label=["Zero Cross Up"],
        desc=["Flow crossed above zero — buy-side dominance emerging"]
    )
}
if (showShapes && zeroCrossDown) {
    plotShape(
        value=0,
        shape="triangledown",
        colorIndex=bearWeakColor,
        width=shapeSize,
        label=["Zero Cross Down"],
        desc=["Flow crossed below zero — sell-side dominance emerging"]
    )
}
if (showShapes && zRarePos) {
    plotShape(
        value=flow,
        shape="diamond",
        colorIndex=zScoreColor,
        width=shapeSize,
        label=["Z+3 Extreme"],
        desc=["Flow z-score > +3 — rare buy-side extreme (mean reversion watch)"]
    )
}
if (showShapes && zRareNeg) {
    plotShape(
        value=flow,
        shape="diamond",
        colorIndex=zScoreColor,
        width=shapeSize,
        label=["Z-3 Extreme"],
        desc=["Flow z-score < -3 — rare sell-side extreme (mean reversion watch)"]
    )
}