Perfected FlowScript
FlowScore — Composite Orderflow Energy
FlowScore Composite Orderflow Energy V2 is indexed as 174_flowscore_composite_orderflow_energy.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
14.9 KB
Lines
314
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull Flow
line 259:5
Trigger
(showShapes && extremeBull)
Value
extremeDiv / 3.0
Deps
extremeBull:var, showShapes:input
Extreme Bear Flow
line 269:5
Trigger
(showShapes && extremeBear)
Value
-extremeDiv / 3.0
Deps
extremeBear:var, showShapes:input
174_flowscore_composite_orderflow_energy.flowscript
source path: kscripts/perfected/174_flowscore_composite_orderflow_energy.flowscript · sha256:dd876ed61f91dbcd235405cc9a0348e770110f0337b40f67ae2ece1b6f1d07a4
//@version=2
// ============================================================================
// FlowScore Composite Orderflow Energy V2 — Multi-Factor Microstructure Score
// Author: luis jimenez (@luis jimenez) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #orderflow, #delta, #obi, #volume, #cvd, #zscore, #regime
//
// This indicator computes a composite FlowScore by fusing four orthogonal
// orderflow components: (1) per-bar volume delta (Δ), (2) order book imbalance
// (OBI), (3) relative volume surge, and (4) cumulative volume delta (CVD).
// Each component is independently z-score normalised over a rolling window,
// weighted by user-configurable coefficients, and projected into a [-1,+1]
// energy metric. Regime detection, colour-coded histograms, filled divergence
// areas, and extreme shape alerts provide actionable microstructure context.
//
// Academic foundation (exact papers & formulas):
// 1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// Journal of Financial Econometrics, 12(1), 47–88.
// [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}.
// Cumulative OFI (CVD) linearly predicts short-term price changes.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
//
// 2. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746. Tick-test classification:
// close > open → buyer-initiated; else seller-initiated.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
// 3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", Journal of Financial Economics, 65(1), 111–130.
// [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
// return reversals. Underpins z-score threshold design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
// 4. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
// Stock Returns", Journal of Finance, 61(4), 1645–1680. Composite index
// construction: weighted sum of orthogonal proxies into a single score.
//
// 5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
// IEEE Trans. Signal Processing. z-score normalisation via MAD for robust
// deviation detection: z = (X − μ) / σ; entry thresholds at ±1σ, ±2σ.
//
// 6. Chande & Kroll (1994), "The New Technical Trader". CMO = (UpSum − DnSum)
// / (UpSum + DnSum); impulse via spread of fast and slow smoothed values.
// Motivates the impulse-momentum component.
// ============================================================================
define(title="FlowScore Composite Orderflow Energy V2", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Component Weights --
var wDelta = input(name="wDelta", type="number", defaultValue=0.35, label="Weight: Delta (Δ)", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Component Weights")
var wOBI = input(name="wOBI", type="number", defaultValue=0.25, label="Weight: OBI", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Component Weights")
var wVolume = input(name="wVolume", type="number", defaultValue=0.20, label="Weight: Relative Volume", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Component Weights")
var wCVD = input(name="wCVD", type="number", defaultValue=0.20, label="Weight: CVD", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Component Weights")
// -- Computation --
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var obiDepth = input(name="obiDepth", type="number", defaultValue=10, label="OBI Depth (levels)", constraints={min: 1, max: 50, step: 1}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Output Smoothing", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=1.5, label="Elevated Regime Threshold (σ)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=2.5, label="Extreme Regime Threshold (σ)", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")
// -- Display --
var showDelta = input(name="showDelta", type="boolean", defaultValue=true, label="Show Delta Component", group="Display")
var showOBI = input(name="showOBI", type="boolean", defaultValue=true, label="Show OBI Component", group="Display")
var showVolume = input(name="showVolume", type="boolean", defaultValue=true, label="Show Volume Component", group="Display")
var showCVDLine = input(name="showCVDLine", type="boolean", defaultValue=true, label="Show CVD Component", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite FlowScore", group="Display")
var showZBars = input(name="showZBars", type="boolean", defaultValue=true, label="Show Z-Score Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var compositeColor = input(name="compositeColor", type="color", defaultValue="#2962ff", label="Composite Color", group="Colors")
var deltaColor = input(name="deltaColor", type="color", defaultValue="#42a5f5", label="Delta Component Color", group="Colors")
var obiColor = input(name="obiColor", type="color", defaultValue="#ab47bc", label="OBI Component Color", group="Colors")
var volColor = input(name="volColor", type="color", defaultValue="#ff9800", label="Volume Component Color", group="Colors")
var cvdCompColor = input(name="cvdCompColor", type="color", defaultValue="#26a69a", label="CVD Component Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = bars.open
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries obi = source("orderbook_imbalance", currentSymbol, currentExchange)
// Guard: halt until price data and volume are loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Component 1: Volume Delta (Δ) — Lee-Ready tick test with taker fallback --
// Per Lee & Ready (1991): close > open → buyer-initiated; else seller-initiated.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (c > o ? v : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (c <= o ? v : 0)
timeseries delta = buyVol - sellVol
// Normalise delta to [-1, +1] via bar range (close position)
timeseries rng = math.max(h - l, 0.0001)
timeseries closePos = (c - l) / rng
timeseries deltaPct = (delta / math.max(v, 1.0)) * closePos
// Z-score normalise delta over rolling window
timeseries deltaMean = sma(deltaPct, zWindow)
timeseries deltaStd = stdev(deltaPct, zWindow)
timeseries deltaZ = (deltaStd > 0) ? (deltaPct - deltaMean) / deltaStd : 0
// -- 3.2 Component 2: Order Book Imbalance (OBI) --
// Per Cont et al. (2014): OBI = (BidQty − AskQty) / (BidQty + AskQty) at depth.
// Platform best-effort: use available orderbook imbalance or estimate from range.
timeseries obiRaw = isnum(obi) ? obi : ((c - l) - (h - c)) / rng
timeseries obiMean = sma(obiRaw, zWindow)
timeseries obiStd = stdev(obiRaw, zWindow)
timeseries obiZ = (obiStd > 0) ? (obiRaw - obiMean) / obiStd : 0
// -- 3.3 Component 3: Relative Volume Surge --
// Volume relative to its rolling average; z-score normalised.
timeseries volMean = sma(v, zWindow)
timeseries volStd = stdev(v, zWindow)
timeseries volZ = (volStd > 0) ? (v - volMean) / volStd : 0
// Sign by price direction: positive volume surge when price up, negative when down
timeseries priceDir = c > o ? 1 : (c < o ? -1 : 0)
timeseries volSigned = volZ * priceDir
// -- 3.4 Component 4: Cumulative Volume Delta (CVD) --
// Rolling-window CVD (stationary approximation) plus true cumulative via static.
timeseries cvdRolling = sum(delta, zWindow)
timeseries cvdMean = sma(cvdRolling, zWindow)
timeseries cvdStd = stdev(cvdRolling, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvdRolling - cvdMean) / cvdStd : 0
// True cumulative CVD via static state (tracked for raw display)
static cvdCum = 0.0
if (!isnan(delta[0])) {
cvdCum = cvdCum + delta[0]
}
// -- 3.5 Composite FlowScore — weighted projection into [-1, +1] --
// Normalise weights so they sum to 1.0
timeseries weightSum = wDelta + wOBI + wVolume + wCVD
timeseries wD = wDelta / weightSum
timeseries wO = wOBI / weightSum
timeseries wV = wVolume / weightSum
timeseries wC = wCVD / weightSum
timeseries rawFlow = wD * deltaZ + wO * obiZ + wV * volSigned + wC * cvdZ
timeseries flowScore = ema(math.max(math.min(rawFlow, 3.0), -3.0) / 3.0, smoothLen)
// -- 3.6 Z-score normalisation of the composite itself --
timeseries flowMean = sma(flowScore, zWindow)
timeseries flowStd = stdev(flowScore, zWindow)
timeseries flowZ = (flowStd > 0) ? (flowScore - flowMean) / flowStd : 0
// -- 3.7 Regime detection (configurable thresholds, no magic numbers) --
var bullRegime = flowScore > divThreshold / 3.0
var bearRegime = flowScore < -divThreshold / 3.0
var extremeBull = flowScore > extremeDiv / 3.0
var extremeBear = flowScore < -extremeDiv / 3.0
var neutralRegime = !bullRegime && !bearRegime
// -- 3.8 Static state tracking for consecutive regime bars --
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0
if (bullRegime) {
bullBars = bullBars + 1
bearBars = 0
neutralBars = 0
lastRegime = 1
} else if (bearRegime) {
bearBars = bearBars + 1
bullBars = 0
neutralBars = 0
lastRegime = -1
} else {
neutralBars = neutralBars + 1
bullBars = 0
bearBars = 0
lastRegime = 0
}
// -- 3.9 Zero-line helper for fill areas --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------
// 4.1 Component lines (plotLine) — optional, colour-coded
timeseries compBull = flowScore > 0
if (showDelta) {
plotLine(value=deltaZ, width=1, colors=[deltaColor], label=["Delta Z"], desc=["Z-score normalised per-bar volume delta (Lee-Ready classification)"])
}
if (showOBI) {
plotLine(value=obiZ, width=1, colors=[obiColor], label=["OBI Z"], desc=["Z-score normalised order book imbalance at depth " + obiDepth])
}
if (showVolume) {
plotLine(value=volSigned, width=1, colors=[volColor], label=["Volume Z"], desc=["Directionally-signed relative volume z-score"])
}
if (showCVDLine) {
plotLine(value=cvdZ, width=1, colors=[cvdCompColor], label=["CVD Z"], desc=["Z-score normalised rolling-window CVD"])
}
// 4.2 Composite FlowScore (plotLine with regime colour + fill)
if (showComposite) {
plotLine(
value=flowScore,
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=compBull ? 0 : (flowScore < 0 ? 1 : 2),
label=["FlowScore"],
desc=["Composite orderflow energy (Δ + OBI + Volume + CVD) in [-1, +1]"]
)
}
// 4.3 Fill area between composite and zero line (plotLine with fill=true)
if (showFill && showComposite) {
plotLine(
value=[flowScore, zeroLine],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=compBull ? 0 : 1,
fill=true,
label=["FlowScore Fill"],
desc=["Filled area between composite FlowScore and zero"]
)
}
// 4.4 Z-Score histogram (plotBar) — regime colour coding
if (showZBars) {
var zBull = flowZ > 0
plotBar(
value=flowZ,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=zBull ? 0 : 1,
width=1,
label=["FlowScore Z"],
desc=["Z-score of composite FlowScore; bars coloured by sign"]
)
}
// 4.5 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
plotShape(
value=extremeDiv / 3.0,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Extreme Bull Flow"],
desc=["Composite flow score exceeds extreme bullish threshold; potential buyer exhaustion or short squeeze"]
)
}
if (showShapes && extremeBear) {
plotShape(
value=-extremeDiv / 3.0,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Extreme Bear Flow"],
desc=["Composite flow score exceeds extreme bearish threshold; potential seller exhaustion or long trap"]
)
}
// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=divThreshold / 3.0, color=transparency(bullColor, 50), width=1)
hline(value=-divThreshold / 3.0, color=transparency(bearColor, 50), width=1)
hline(value=extremeDiv / 3.0, color=transparency(bullColor, 30), width=1)
hline(value=-extremeDiv / 3.0, color=transparency(bearColor, 30), width=1)
// 4.7 Regime table (last bar only)
if (isLastBar) {
var regimeText = bullRegime ? "BULLISH" : (bearRegime ? "BEARISH" : "NEUTRAL")
var regimeTextColor = bullRegime ? bullColor : (bearRegime ? bearColor : neutralColor)
plotTable(
data=[
["FlowScore V2", regimeText],
["Composite", flowScore[0]],
["Delta Z", deltaZ[0]],
["OBI Z", obiZ[0]],
["Volume Z", volSigned[0]],
["CVD Z", cvdZ[0]],
["Bull Bars", bullBars],
["Bear Bars", bearBars]
],
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
)
}