Perfected FlowScript
orderflow
Order Flow V2 is indexed as 200_orderflow.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
17.8 KB
Lines
388
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 315:9
Trigger
(showShapes) && (crossUp)
Value
composite
Deps
crossUp:var, showShapes:input
Bear Regime
line 325:9
Trigger
(showShapes) && (crossDn)
Value
composite
Deps
crossDn:var, showShapes:input
Extreme Bull
line 335:9
Trigger
(showShapes) && (extremeUp)
Value
composite
Deps
extremeUp:var, showShapes:input
Extreme Bear
line 345:9
Trigger
(showShapes) && (extremeDn)
Value
composite
Deps
extremeDn:var, showShapes:input
200_orderflow.flowscript
source path: kscripts/perfected/200_orderflow.flowscript · sha256:59f895b843f8ba1225033407cd74d223ed552f204734e0b2acccd07ddc3d044b
//@version=2
// ============================================================================
// Order Flow V2 — Production-Quality Multi-Factor Composite Indicator
// Author: E | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderflow, #delta, #obi, #cvd, #composite, #regime
//
// Multi-factor orderflow analysis combining delta, OBI proxy, and CVD into a
// z-score-normalized composite score with regime detection, color coding,
// shape markers, and static session tracking.
//
// FORMULA FOUNDATION:
// 1. Volume Delta (VD): VD = BuyVol − SellVol classified per Lee & Ready (1991)
// tick-test adaptation. Captures aggressive order flow imbalance per bar.
// 2. Cumulative Volume Delta (CVD): Σ VD over lookback per Cont, Kukanov &
// Stoikov (2014). The linear price-impact model: ΔP ≈ OFI / Depth.
// 3. Order Book Imbalance (OBI) Proxy: (Bid − Ask) / (Bid + Ask) at top of
// book per Cartea, Donnelly & Jaimungal (2018) regime segmentation.
// 4. Z-Score Normalization: z_t = (x_t − μ) / σ per Zhao & Palomar (2018).
// Converts multi-factor inputs into commensurable units for composite scoring.
// 5. Multi-Factor Composite: Weighted combination of z-scored delta, CVD, and
// OBI aligned by sign (Fama & French 1993 multi-factor framework).
// 6. Regime Detection: Three-segment model (Sell-heavy, Neutral, Buy-heavy) per
// Cartea et al. (2018). Positive price changes preceded by buy-heavy books.
// 7. Efficiency Ratio (ER): |change| / Σ|changes| per Kaufman (1995) KAMA.
// Filters noise: low ER = choppy market = suppress composite confidence.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI explains 65% of mid-price
// variance; slope ∝ 1/depth.
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// J. Finance 46(2), 733–746. Tick-test classification accuracy ~85%.
// • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
// segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
// • Kyle, A.S. (1985), "Continuous Auctions and Insider Trading", Econometrica
// 53(6), 1315–1335. Linear price impact λ = price change per unit order flow.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE TSP. Z-score normalization for signal standardization.
// • Fama & French (1993), "Common Risk Factors in the Returns on Stocks and
// Bonds", JFE 33(1), 3–56. Multi-factor model construction methodology.
// • Kaufman, P.J. (1995), *Smarter Trading*. Efficiency Ratio for noise
// filtering and adaptive moving averages.
// • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", JFE 65(1). Extreme imbalances predict return reversals.
// • Lillo & Farmer (2004), "The Long Memory of the Efficient Market", SNDE 8(3).
// Order flow persistence justifies cumulative measures.
// ============================================================================
define(
title="Order Flow V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Order Flow Components ---
var deltaLookback = input(name="deltaLookback", type="number", defaultValue=14, label="Delta Lookback", constraints={min: 5, max: 100, step: 1}, group="Order Flow")
var cvdLookback = input(name="cvdLookback", type="number", defaultValue=50, label="CVD Lookback", constraints={min: 10, max: 200, step: 1}, group="Order Flow")
var obiLookback = input(name="obiLookback", type="number", defaultValue=5, label="OBI Proxy Lookback", constraints={min: 3, max: 50, step: 1}, group="Order Flow")
var erLen = input(name="erLen", type="number", defaultValue=20, label="Efficiency Ratio Length", constraints={min: 5, max: 100, step: 1}, group="Order Flow")
// --- Composite & Z-Score ---
var zScoreLookback = input(name="zScoreLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Composite & Z-Score")
var deltaWeight = input(name="deltaWeight", type="number", defaultValue=40.0, label="Delta Weight (%)", constraints={min: 0.0, max: 100.0, step: 5.0}, group="Composite & Z-Score")
var cvdWeight = input(name="cvdWeight", type="number", defaultValue=40.0, label="CVD Weight (%)", constraints={min: 0.0, max: 100.0, step: 5.0}, group="Composite & Z-Score")
var obiWeight = input(name="obiWeight", type="number", defaultValue=20.0, label="OBI Weight (%)", constraints={min: 0.0, max: 100.0, step: 5.0}, group="Composite & Z-Score")
// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=50.0, label="Bullish Threshold", constraints={min: 10.0, max: 90.0, step: 5.0}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-50.0, label="Bearish Threshold", constraints={min: -90.0, max: -10.0, step: 5.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=80.0, label="Extreme Threshold", constraints={min: 50.0, max: 95.0, step: 5.0}, group="Thresholds")
var erMin = input(name="erMin", type="number", defaultValue=0.15, label="Min Efficiency Ratio (noise filter)", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Thresholds")
// --- Display ---
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Score", group="Display")
var showComponents = input(name="showComponents", type="boolean", defaultValue=true, label="Show Individual Components", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showTable = input(name="showTable", type="boolean", defaultValue=true, label="Show Summary Table", group="Display")
// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
var compositeColor = input(name="compositeColor", type="color", defaultValue="#42a5f5", label="Composite Line Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries vol = bars.volume
if (isnan(px[0]) || isnan(vol[0])) {
return
}
// ------------------------------------------------------------------------------
// Component 1: Volume Delta (Lee & Ready 1991; Cont et al. 2014)
// ------------------------------------------------------------------------------
// Bar-level trade classification: close >= open = buy-initiated
timeseries upBar = bars.close >= bars.open
timeseries buyVol = upBar ? vol : 0
timeseries sellVol = upBar ? 0 : vol
timeseries delta = buyVol - sellVol
// Delta z-score over lookback
timeseries deltaMean = sma(source=delta, period=zScoreLookback)
timeseries deltaStd = stddev(source=delta, period=zScoreLookback)
timeseries deltaZ = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0.0
// ------------------------------------------------------------------------------
// Component 2: CVD — Cumulative Volume Delta (Lillo & Farmer 2004)
// ------------------------------------------------------------------------------
timeseries cvd = 0.0
for (var cvdIndex = 0; cvdIndex < cvdLookback; cvdIndex = cvdIndex + 1) {
cvd = cvd + delta[cvdIndex]
}
// CVD z-score
timeseries cvdMean = sma(source=cvd, period=zScoreLookback)
timeseries cvdStd = stddev(source=cvd, period=zScoreLookback)
timeseries cvdZ = cvdStd > 0 ? (cvd - cvdMean) / cvdStd : 0.0
// ------------------------------------------------------------------------------
// Component 3: OBI Proxy (Cartea et al. 2018 regime segmentation)
// ------------------------------------------------------------------------------
// OBI proxy = normalized directional pressure per bar over lookback
// Uses (close - open) / (high - low) as a bar-level imbalance proxy
// when true orderbook data is unavailable; bounded to [-1, +1]
timeseries obi = 0.0
for (var obiIndex = 0; obiIndex < obiLookback; obiIndex = obiIndex + 1) {
var barRange = bars.high[obiIndex] - bars.low[obiIndex]
var barDir = barRange > 0 ? (bars.close[obiIndex] - bars.open[obiIndex]) / barRange : 0.0
obi = obi + barDir
}
obi = obi / obiLookback
// OBI z-score
timeseries obiMean = sma(source=obi, period=zScoreLookback)
timeseries obiStd = stddev(source=obi, period=zScoreLookback)
timeseries obiZ = obiStd > 0 ? (obi - obiMean) / obiStd : 0.0
// ------------------------------------------------------------------------------
// Noise Filter: Efficiency Ratio (Kaufman 1995)
// ------------------------------------------------------------------------------
// ER = |change| / Σ|changes|. Low ER = noisy/choppy market.
// Composite confidence is suppressed when ER < erMin.
timeseries erChange = math.abs(px[0] - px[erLen])
timeseries erVol = 0.0
for (var erIndex = 0; erIndex < erLen; erIndex = erIndex + 1) {
erVol = erVol + math.abs(px[erIndex] - px[erIndex + 1])
}
timeseries er = erVol > 0 ? erChange / erVol : 0.0
// ------------------------------------------------------------------------------
// Multi-Factor Composite Score (Fama & French 1993 factor weighting)
// ------------------------------------------------------------------------------
// Normalize weights
var totalWeight = deltaWeight + cvdWeight + obiWeight
var wDelta = totalWeight > 0 ? deltaWeight / totalWeight : 0.0
var wCVD = totalWeight > 0 ? cvdWeight / totalWeight : 0.0
var wOBI = totalWeight > 0 ? obiWeight / totalWeight : 0.0
// Raw composite: weighted sum of z-scored components, scaled to [-100, 100]
timeseries rawComposite = (deltaZ * wDelta + cvdZ * wCVD + obiZ * wOBI) * 100.0
// Noise-filtered composite: suppress when ER is too low (choppy market)
timeseries composite = er >= erMin ? rawComposite : rawComposite * (er / erMin)
// Clamp composite to [-100, 100]
composite = math.max(-100.0, math.min(100.0, composite))
// Composite z-score for statistical analysis
timeseries compMean = sma(source=composite, period=zScoreLookback)
timeseries compStd = stddev(source=composite, period=zScoreLookback)
timeseries compZ = compStd > 0 ? (composite - compMean) / compStd : 0.0
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (composite >= bullThresh) {
regime = 1
} else if (composite <= bearThresh) {
regime = -1
}
if (composite >= extremeThresh) {
extremeRegime = 1
} else if (composite <= -extremeThresh) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastBarIndex = 0
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighComp = -999999.0
static sessionLowComp = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static goldenOBI = 0
static deathOBI = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (composite > sessionHighComp) {
sessionHighComp = composite
}
if (composite < sessionLowComp) {
sessionLowComp = composite
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBullCount = extremeBullCount + 1
} else if (extremeRegime == -1) {
extremeBearCount = extremeBearCount + 1
}
if (regime == 1 && lastRegime == 0) {
goldenOBI = goldenOBI + 1
}
if (regime == -1 && lastRegime == 0) {
deathOBI = deathOBI + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multi-Factor Composite with Z-Score, Components, and Shapes
// ------------------------------------------------------------------------------
// Reference lines
hline(value=0, color="#ffffff20", width=1)
hline(value=bullThresh, color=opacity(bullColor, 30), width=1)
hline(value=bearThresh, color=opacity(bearColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(extremeBearColor, 20), width=1)
// --- Composite Score (regime-colored line with fill) ---
if (showComposite) {
var compColor = extremeRegime == 1 ? extremeBullColor : (extremeRegime == -1 ? extremeBearColor : (regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)))
plotLine(
value=composite,
width=2,
colors=[compColor],
label=["Order Flow Composite"],
desc=["Multi-factor composite (delta " + deltaWeight + "%, CVD " + cvdWeight + "%, OBI " + obiWeight + "%). Per Fama & French (1993) weighting."]
)
}
// --- Z-Score Line ---
if (showZScore) {
var zColor = compZ > 2.0 ? extremeBullColor : (compZ < -2.0 ? extremeBearColor : (compZ > 0 ? bullColor : bearColor))
plotLine(
value=compZ,
width=1,
colors=[zColor],
label=["Composite Z-Score"],
desc=["Z-score of composite score. ±2 = statistical extreme; ±3 = 3-sigma event."]
)
}
// --- Individual Components (faint lines) ---
if (showComponents) {
plotLine(
value=deltaZ * 50.0,
width=1,
colors=[opacity(bullColor, 40)],
label=["Delta Z"],
desc=["Delta z-score (scaled ±50) per Lee & Ready (1991) classification"]
)
plotLine(
value=cvdZ * 50.0,
width=1,
colors=[opacity(bearColor, 40)],
label=["CVD Z"],
desc=["CVD z-score (scaled ±50) per Cont et al. (2014) OFI framework"]
)
plotLine(
value=obiZ * 50.0,
width=1,
colors=[opacity(neutralColor, 40)],
label=["OBI Z"],
desc=["OBI proxy z-score (scaled ±50) per Cartea et al. (2018) regime model"]
)
}
// --- Regime Transition Shapes ---
if (showShapes) {
var crossUp = composite >= bullThresh && !isnan(composite[1]) && composite[1] < bullThresh
var crossDn = composite <= bearThresh && !isnan(composite[1]) && composite[1] > bearThresh
var extremeUp = composite >= extremeThresh && !isnan(composite[1]) && composite[1] < extremeThresh
var extremeDn = composite <= -extremeThresh && !isnan(composite[1]) && composite[1] > -extremeThresh
if (crossUp) {
plotShape(
value=composite,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["Bull Regime"],
desc=["Composite crossed into bullish regime (buy-heavy order flow) per Cartea et al. (2018)"]
)
}
if (crossDn) {
plotShape(
value=composite,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["Bear Regime"],
desc=["Composite crossed into bearish regime (sell-heavy order flow)"]
)
}
if (extremeUp) {
plotShape(
value=composite,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Bull"],
desc=["Extreme bullish order flow — composite exceeds " + extremeThresh + " (Kyle 1985 λ spike)"]
)
}
if (extremeDn) {
plotShape(
value=composite,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Bear"],
desc=["Extreme bearish order flow — composite below -" + extremeThresh]
)
}
}
// ------------------------------------------------------------------------------
// Summary Table (last bar only)
// ------------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regime == 1 ? "BUY-HEAVY" : (regime == -1 ? "SELL-HEAVY" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotTable(
data=[
["Order Flow V2", regimeText],
["Composite", composite[0]],
["Delta Z", deltaZ[0]],
["CVD Z", cvdZ[0]],
["OBI Z", obiZ[0]],
["ER", er[0]],
["Regime Changes", regimeChangeCount],
["Extreme Bull", extremeBullCount],
["Extreme Bear", extremeBearCount]
],
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
)
}