Order Flow Microstructure Engine# Order Flow Microstructure Engine
**Order Flow Microstructure Engine** condenses a full stack of order-flow and market-microstructure measures into a single decision: one confidence %, one tier, and one action with entry/stop levels — shown in an adaptive on-chart dashboard. It is built to answer one question on every bar: *are aggressive buyers or aggressive sellers in control, and how convinced should you be?*
This is not a bundle of unrelated indicators placed on one chart. Every component measures a **different facet of the same process** — the buy/sell auction happening inside each bar — and they are combined inside **one probabilistic model**. The reason for the mashup, and how the parts interact, is described below as the guidelines require.
**Why these components are combined (mashup justification)**
No single order-flow measure is reliable alone: raw delta misleads during absorption, CVD drifts, footprint imbalances appear in chop, and toxicity rises at both reversals and breakouts. Because these weaknesses are *partially independent*, fusing the measures correctly cancels noise that any one of them carries. The original element is **how** the fusion is done — not what is plotted.
**How it works (the pipeline)**
1. *Reconstruction.* Lower-timeframe sub-bars are pulled and each is classified buy/sell with a tick-rule cascade (after Lee & Ready). Where the data plan exposes native volume footprint, real bid/ask is used and aggregated into the same price bins. The dashboard always shows whether it is running on reconstructed (`RECON`) or native (`NATIVE`) data.
2. *Factors.* From that base it derives Aggressor Imbalance Ratio, Cumulative Volume Delta, footprint imbalances/POC, auction Value-Area efficiency (acceptance vs rejection), integrated multi-level Order-Flow Imbalance (depth-weighted), VPIN-style flow toxicity, Kyle's lambda price-impact/liquidity, a directional self-exciting (Hawkes) intensity, and a square-root-law absorption measure.
3. *Fusion (the original part).* Each factor is mapped to a probability and combined in Bayesian log-odds. Crucially, the flow-derived factors are **decorrelated before fusion** using an effective-sample-size (design-effect) shrinkage, so factors that are really the *same evidence* (AIR, delta, CVD, footprint, OFI) cannot inflate confidence just by agreeing. Structurally independent factors (auction efficiency, MOC, Hawkes, absorption, cross-instrument) enter at full weight. The posterior is then gated by multi-timeframe and multi-horizon consensus and damped by a regime-thrash (chop) penalty, producing one confidence → a 5-tier ladder → an action.
Without this combination you would get several conflicting opinions; the value is the **correlation-aware fusion** that turns them into one calibrated read.
**How to use it**
- Apply to a liquid instrument on an intraday timeframe (1m–1h). Defaults are tuned for index futures on 5-minute charts with 5-second sub-bars.
- Read the Compact dashboard top-down: ACTION + confidence %, Tier (position-size guidance), Entry/Stop, then CO-FIRE confluence, multi-timeframe and regime/stability. Switch "Table view mode" to Full for a complete factor-by-factor breakdown.
- On-chart triangles mark Tier-1/Tier-2 long/short signals across history; footprint boxes show the intrabar buy/sell distribution.
- For other markets: change the **Market preset** (group 01). Choose **CUSTOM** to set your own session, MOC window, footprint bin sizing and CVD reset — making it usable on any instrument in any market.
- The dashboard theme auto-adapts to a light or dark chart background.
**What makes it original**
Correlation-aware decorrelated Bayesian fusion of order-flow factors; a native-footprint seam that uses real bid/ask when available and transparently falls back to reconstruction; layered multi-horizon + multi-timeframe + cross-instrument confirmation on a microstructure base; and a regime-stability filter that penalizes only genuine directional reversals, not same-direction intensity changes.
**Honesty / limitations**
On most retail feeds, order flow here is reconstructed from lower-timeframe data via the tick rule (~75–80% trade-sign accuracy), not true exchange bid/ask, unless your plan provides native footprint data. The data source is shown in the dashboard. This is an analytic and educational tool, not financial advice and not a guarantee of results.
**Concept credits**
Lee & Ready (trade sign); Kyle (price impact / lambda); Easley, López de Prado & O'Hara (VPIN); Cont, Kukanov & Stoikov and Xu, Gould & Howison (OFI / multi-level OFI); Hawkes and Bacry–Muzy (self-exciting intensity); Almgren and Tóth–Bouchaud (square-root impact law); Kaufman (Efficiency-Ratio adaptation); Steidlmayer (Market Profile / Value Area); Kish (design effect). All Pine implementations are original re-derivations; no external script code is used.
**Disclaimer**
For research and educational purposes only. Nothing here is financial advice. Markets carry risk and past behaviour does not guarantee future results. Always do your own research and manage risk.
Indicator

Order Flow Imbalance Regime Engine# Order Flow Imbalance Regime Engine
## OVERVIEW
The Order Flow Imbalance Regime Engine reconstructs a proxy for **order-flow imbalance** (net aggressive buying vs selling) directly from price and volume, scales it into an **expected price move**, and turns it into a connected set of read-outs: directional pressure, price impact, multi-horizon conviction, self-excitation (cascade) intensity, a three-lens liquidity-stress score, optional cross-asset confirmation, and a probability distribution over five market regimes. It runs on **any symbol and any market** — equities, futures, forex, crypto, indices — including instruments without reliable volume.
A charting platform exposes no Level-2 order book, so true exchange-grade OFI is not computable. This engine is an honest **approximation** that rebuilds buy/sell pressure from intrabar tick direction, probabilistic bulk classification, or candle geometry — not from limit-order placements and cancellations.
## WHY THE COMPONENTS BELONG IN ONE SCRIPT (not a mashup of unrelated tools)
Every stage is derived from **one underlying quantity** — reconstructed buy-vs-sell pressure — and each stage consumes the previous stage's output, all feeding a single end product (the regime probabilities). They are dependencies in a chain, not independent indicators placed side by side:
1. **Classification** reconstructs buy/sell pressure (tick rule, bulk volume, or geometry).
2. **Stationarization** standardizes that exact series so values compare across assets.
3. **Price impact (Kyle λ)** scales the standardized flow into an expected price move — large imbalance against thin depth implies a bigger move.
4. **Multi-horizon consensus** measures the same series across timescales for conviction.
5. **Self-excitation (Hawkes)** tests whether the imbalance is clustering — flow that triggers more flow.
6. **Liquidity stress** estimates fragility (the *context* that makes impact larger or smaller).
7. **Cross-asset confirmation** checks whether a correlated instrument agrees.
8. **Regime classifier** is a softmax that takes features 1–7 as inputs and outputs probabilities. Remove any earlier stage and the classifier loses an input — that dependency is the justification for combining them.
## HOW EACH STAGE WORKS
- **Classification (choose one):**
- *Intrabar Tick Rule* — pulls lower-timeframe bars inside each candle and tags each buy or sell by its own open/close.
- *Bulk Volume Classification (BVC)* — splits each bar's volume probabilistically using the normal CDF of its standardized return; designed for bar-aggregated data and consistent with the VPIN liquidity layer.
- *Candle Geometry* — splits volume by where the close sits within the bar's range.
- On volume-less instruments it falls back to a tick count, so the imbalance stays meaningful.
- **Stationarized OFI (z-score):** standardizes raw imbalance over a lookback so +2 means "two standard deviations of buying" on any asset.
- **Price impact (Kyle λ):** estimates λ by regressing bar return on signed flow; market depth ≈ 1/λ. The dashboard's **Expected Move** is λ · OFI, expressed in ATR units — this reproduces the founding result that price impact scales inversely with depth.
- **Multi-horizon consensus:** three EMAs of the z-score; agreement of their signs (shown as n/3) gauges conviction.
- **Self-excitation (Hawkes):** an intensity that jumps on strong imbalance events and decays exponentially — λ(t) = λ(t-1)·e^(-β) + α·event. Reported as a 0–100 percentile (Cascade Strength) plus direction.
- **Liquidity stress:** the mean percentile of three orthogonal lenses — VPIN-style flow toxicity, a thin-book "vacuum" term (price travelling far on thin relative volume), and Amihud illiquidity (|return|/volume). Using three independent estimators avoids resting the read on any single one.
- **Cross-asset confirmation:** a lagged imbalance proxy on a user-chosen correlated symbol; used only to confirm, never as a stand-alone signal.
- **Round-level magnet (optional, heuristic):** distance to the nearest auto-scaled round level as a crude pinning gauge. **This is explicitly not options dealer gamma**, which needs options open-interest data unavailable on a price chart.
- **Regime classifier:** a softmax over the above producing probabilities for Trend Continuation, Squeeze, Cascade Blast, Mean Reversion, and Liquidity Shock; the dominant one is highlighted.
## HOW TO USE IT
- Works best on intraday timeframes where intrabar data exists (1m–1h); it also runs higher via the geometry/BVC paths.
- **Dashboard:** read Buy/Sell pressure for direction, OFI z-score and consensus for strength/conviction, **Expected Move** for the impact-scaled magnitude, Cascade for clustering, Liquidity Stress for fragility, and the highlighted Regime for context.
- **Signals:** a triangle prints on the first bar of a buy or sell cascade (strong, directionally-aligned self-excitation, optionally confirmed by the cross-asset). Treat these as context/timing aids, not stand-alone entries.
- **Tuning:** switch Classification method to compare tick-rule vs BVC; lower Squeeze sensitivity on compression-prone instruments; set the Volume source and cross-asset reference to suit your instrument.
## WHAT MAKES IT ORIGINAL
Most published "order flow" tools stop at a single buy-minus-sell histogram. This engine (a) offers **three interchangeable classification methods** including probabilistic bulk classification, (b) **stationarizes** the imbalance for cross-asset comparability, (c) scales it into a **Kyle-λ expected move** rather than leaving it as a raw count, (d) adds an explicit **self-exciting (Hawkes) cascade** layer, (e) fuses **three orthogonal liquidity lenses** into one stress score, and (f) routes everything through a **softmax regime classifier** that outputs a probability distribution rather than a binary signal. The volume-agnostic fallback and theme-adaptive dashboard make it genuinely universal. The code is an independent implementation and reuses no third-party scripts.
## DATA, UNIVERSALITY & SETTINGS
The Volume source input, three classification methods, and automatic tick/geometry fallbacks let the engine run on any market, including volume-less instruments. The cross-asset reference defaults to a NIFTY-family symbol (BANKNIFTY) but is freely editable to any correlated instrument, and the round-level spacing auto-scales or accepts manual values, so the engine adapts to any exchange or instrument.
## REPAINTING DISCLOSURE
Intrabar and cross-asset requests update on the live (forming) bar, so live read-outs can change until the bar closes. The "Confirm signals on bar close" option (ON by default) makes all plotted signals and alerts evaluate only on closed bars, so historical signals are fixed and non-repainting.
## ACADEMIC CREDIT
This script is an original implementation of concepts from public research, with thanks to their authors: Cont, Kukanov & Stoikov (order-flow imbalance and linear price impact, 2014); Kyle (the λ price-impact coefficient and market depth, 1985); Xu, Gould & Howison (multi-level order flow, 2018); Cont, Cucuringu & Zhang (integrated and cross-asset OFI, 2023); the Generalized/Stationarized OFI literature; Lee & Ready (tick-rule trade classification, 1991); Easley, López de Prado & O'Hara (Bulk Volume Classification and VPIN flow toxicity, 2012); Amihud (the illiquidity measure, 2002); the Hawkes self-exciting process literature (Bacry, Muzy, and others); and Kolm, Turiel & Westray (multi-horizon order-flow alpha, 2023).
## DISCLAIMER
This indicator is provided for research and educational purposes only. It is not financial, investment, or trading advice and makes no promise of profitability. Order-flow imbalance here is an approximation, not exchange-grade Level-2 data. Trading involves substantial risk of loss; past behaviour does not guarantee future results. You are solely responsible for your own decisions.
Indicator
