VPIN Flow Regime [OutOfSampleLab]VPIN Flow Regime visualises order-flow toxicity and buy/sell pressure directly on your chart, with non-repainting flow-price divergence. It describes the current state of the tape. It does not give buy or sell signals.
How it works
- Each bar's volume is split into buy and sell parts using Bulk Volume Classification: the buy fraction is the CDF of the standardised close-to-close change. Two paper-faithful variants are selectable: the standard-normal CDF (Easley, Lopez de Prado & O'Hara, 2012) or the fat-tailed Student-t CDF with 0.25 degrees of freedom (their 2016 paper). To our knowledge no other public script offers both.
- VPIN toxicity = sum |buy - sell| / sum volume over N bars. An unsigned measure of how one-sided flow has been. It is coloured by its own rolling percentile into a regime light: Quiet, Normal, Elevated, Burst.
- Buy pressure = net flow rescaled to 0-100 (50 = balanced).
- Divergence: when price makes a higher high (or lower low) that net flow does not confirm. Confirmed on pivots a few bars later, so it never repaints. By default the divergence lines and labels are drawn directly on the price chart.
Alerts
- Toxicity crossing into Elevated / Burst / back to calm.
- Bullish / bearish flow-price divergence.
All alerts are state-change events, not trade instructions.
Honest limitations (please read)
- This is a bar-based approximation of VPIN, not tick-level VPIN on a true volume clock. Read relative levels and percentiles, not absolute values.
- PulseWire volume is feed-dependent; on many FX/index/CFD symbols it is tick count, not traded volume, and the reading is weak there. Prefer symbols with real volume.
- Aggressor classification is imperfect and depends on the window settings.
This is an impersonal educational tool that runs the same for everyone. Not financial advice, no performance claims.
References: Easley, Lopez de Prado & O'Hara (2012), Review of Financial Studies 25(5); (2016), Journal of Financial Economics 120(2); Lee & Ready (1991), Journal of Finance 46(2). Indicator

Adaptive Structural Trail Order Flow, Imbalance & RegimeAdaptive Structural Trail — Order Flow, Imbalance & Regime
What it is
Adaptive Structural Trail is a single, self-contained market-structure framework that re-clocks the chart by participation instead of time, marks the imbalances that real activity leaves behind, lets order flow decide which of those levels still matter, asks a regime filter whether trending behaviour can be trusted right now, and trails the strongest surviving level as an adaptive stop — all summarised in a plain-language dashboard that tells you, at a glance, whether the picture says ride, wait, or stand aside.
It is designed to be market-agnostic: every raw input (price, volume, and the volatility-index reference) is user-selectable, so the same logic runs on index futures, equities, FX, crypto or commodities without touching the code. Defaults are set for NIFTY index futures; change the volatility symbol and (if needed) the volume source for other instruments.
Why the components are combined (this is one tool, not a bundle)
Each layer measures a different facet of one process — activity creating structure, structure decaying or being defended, and a regime deciding whether to act. They are not independent indicators stacked for visual effect; remove any one and the others lose their meaning:
Delta clock (the substrate). A virtual bar closes only when cumulative signed volume becomes statistically significant (σ × a multiplier). Every downstream reading is therefore spaced by participation, not by the clock — a quiet 10 minutes and a violent 10 seconds are treated differently, which is the whole point.
Imbalance / fair-value-gap detection runs on those virtual bars, so a level is recorded only where genuine activity gapped price, not on arbitrary time bars.
Order-flow lifecycle (charge → decay → breaker/dead). When price returns to a level, delta adjudicates the outcome: absorbed-and-defended levels are reborn as breakers; levels that are surged through are killed. Flow decides what structure survives.
Regime gate (efficiency ratio + volatility burst). This routes everything. The trail is shown and signals arm only where trend behaviour is statistically credible; in range/transition/high-volatility states the tool deliberately stands aside.
Confidence fusion. Structure strength, cumulative-delta slope and flow toxicity (VPIN) are blended into one confidence number, which the dashboard converts into a plain instruction.
That coupling — a volume-significance clock feeding imbalance detection whose survival is adjudicated by order flow and gated by regime, fused into a single trailing level and a decision read-out — is the original contribution here.
How to use it
Add it to any liquid instrument. It is built for intraday timeframes (1–15 min is the sweet spot on index futures).
Read the dashboard top-down: the ACTION banner is the headline (e.g. LONG · ride the trail, RANGE · stand aside). Below it: bias + confidence, market state, the actual trail-stop price, order flow, flow toxicity, volatility context, and a plain "what to do" line.
Treat the coloured trail as a structure-based stop while the market state is a trend; when the state leaves trend, the trail disappears by design.
The imbalance zones show where unfilled activity sits; fresh, tapped and breaker levels are colour-coded (see the on-chart legend).
Edge-calibration panel (bottom-right): for transparency it scores past signals against a regime-matched base rate and reports EDGE = Hit − Base with a 95% confidence interval. Read the Edge column, not the raw hit-rate. This is descriptive of the past on your symbol — not a backtest and not a forward guarantee.
Key-info panel (top-left): instrument, timeframe, the live data source (see honesty note), threshold, ATR and level counts.
Honest note on data (please read)
PulseWire exposes no true tick-by-tick aggressor delta and cannot build custom bars, so delta here is a proxy: signed intrabar volume taken from the finest lower timeframe your data plan returns — 1-second where available, otherwise 1-minute — falling back to bar-shape when no lower-timeframe data exists. The live source is shown as "Delta source" in the Key-info panel, so you always know which mode is active. Non-repaint: the delta clock advances and structure/regime/signals resolve only on confirmed bars; the trail line itself updates within the forming bar as a current estimate.
Originality
The novelty is the synthesis and coupling, not any single classical block. A participation clock is used to gate imbalance detection; order flow is used to adjudicate level survival; regime is used to route the entire read; and the whole thing collapses into one trailing level plus a decision dashboard and a self-calibration panel. Every raw input is user-selectable so the framework generalises across markets.
Concept credits
This tool synthesises well-established, publicly documented ideas; credit to their originators:
Information / volume-driven bars & VPIN flow toxicity — Marcos López de Prado; Easley, López de Prado & O'Hara.
Efficiency Ratio (trend vs. noise) — Perry J. Kaufman.
Trade-side classification (tick rule) — Lee & Ready.
Market impact & absorption (square-root law) — Almgren; Tóth & Bouchaud.
Wilson score interval (small-sample proportion CI) — E. B. Wilson.
Imbalance / fair-value-gap and trailing-stop concepts are long-standing, widely used market-structure ideas. The synthesis and the Pine implementation are the author's own.
Exported outputs (for use in other scripts)
Available via input.source() in any other indicator, with clean generic names: Bias Score (signed conviction, ±10), Trail Stop, Trail Direction, Regime State, Confidence, Leading Strength, CVD Slope, Flow Toxicity, Cumulative Delta, Volatility ROC, Volatility Bias.
Disclaimer
For research and education only. This is an analytical tool — not financial advice, not a signal service, and not a guarantee of future results. No indicator has an inherent edge; validate with your own testing, apply realistic costs, and manage risk. You are solely responsible for your trading decisions. Indicator

Multi Timeframe Order-Flow CockpitMulti-Timeframe Order-Flow Cockpit
A single overlay that turns raw volume into a multi-timeframe order-flow read. It draws a compact row of higher-timeframe (HTF) candles beside price — each split into buy vs sell volume — and condenses several timeframes' order flow into one plain-language verdict. Unusually, it ships with a built-in calibration layer that forward-tests its own verdict and tells you, in plain words, whether that verdict actually beats a base rate — instead of asserting an edge it cannot show.
WHAT IT DOES
For each timeframe you enable, the script reconstructs the buy/sell volume that built every bar, scores how one-sided that flow is, reads market structure, and fuses everything into a single bias with a stated conviction. It then projects key price levels and marks where current price sits inside each timeframe's range — so you can see, at one glance, what order flow is doing across the whole timeframe stack.
WHY THESE COMPONENTS ARE COMBINED
This is not a pile of unrelated overlays. It is a pipeline where each stage feeds the next, and a final stage audits the whole:
Higher-timeframe candles are the canvas — see several timeframes' auctions at once without flipping charts.
Intrabar delta classifies sub-bar volume into buy vs sell (close-vs-open, or range-weighted). Where your plan and symbol allow, the chart-timeframe strip uses native footprint (real aggressor bid/ask volume), tagged REAL; otherwise it reconstructs the delta and is tagged EST — so data fidelity is never hidden.
Order-flow toxicity (VPIN-family) measures how aggressive/one-sided each timeframe's flow is. It is a conviction input, not a direction.
Market structure (swing breaks, BOS/CHoCH) supplies directional context that can override delta when price structure genuinely shifts.
Probabilistic synthesis fuses the above in log-odds space, averaging correlated inputs so that redundant agreement cannot inflate confidence, plus an optional exogenous volatility-index vote (rising volatility pressures the asset).
Forward calibration resolves every committed verdict N bars later against an ATR-sized move and reports Hit% versus an unconditional Base%, gated by a Wilson score interval so a result is only flagged (star) when it is statistically distinguishable from chance — split by trending versus ranging regime.
The components belong together because the deliverable is the synthesis and its honest scoring, which no single overlay can provide: toxicity needs the delta, structure contextualizes the delta, the verdict needs all of them, and the calibration is meaningless without a verdict to test.
HOW TO USE IT
Read the Compact table (default). Bias = which way flow leans; Conviction = how strongly; Flow = calm vs one-sided; Setup = exhaustion flags; Edge = whether the verdict has measured, significant edge; Use = the bottom line — "Context only" until edge is proven, "Tradeable — still verify" only when the calibration confirms it.
Switch the table to Pro for per-timeframe metrics (delta %, toxicity, structure, calibrated bias) plus the combined verdict and calibration rows. Turn on the Key Info table while learning — it is a plain-language legend.
On-chart aids: each panel tags its true High/Low and shows a position triangle at its edge — green when price is above that timeframe's range, red when below, yellow when inside, with brightness scaling to how far price has stretched. Key levels (POC, value-area high/low, recent swing high/low) are projected at true price as reference zones.
Any market: set your symbol, price source and intrabar resolution in Data Source, and your market's volatility index in Volatility Vote. Defaults are set for NSE NIFTY — change them for other assets.
Alerts are attention cues (verdict shift, toxicity spike, divergence, structure shift) — they tell you where to look, never what to do. Create one alert with the condition "Any alert() function call."
WHAT IS ORIGINAL HERE
Most order-flow and "smart-money" tools assert an edge by drawing confident signals. This one is built around the opposite discipline: a transparent calibration layer that measures and reports its own edge against a base rate, refuses to certify a signal that has not earned statistical significance, and reports it separately by market regime. The multi-timeframe order-flow synthesis with decorrelated log-odds fusion, and the REAL/EST fidelity tagging of delta, are also original to this implementation. The honesty layer is the headline feature — it is designed to tell you when there is no proven edge.
CONCEPT CREDITS (methods, not code)
Bulk Volume Classification / VPIN — Easley, Lopez de Prado and O'Hara. Market/Volume Profile (value area, POC) — J. Peter Steidlmayer. Wilson score interval — E. B. Wilson (1927). Efficiency-ratio regime — Perry Kaufman. Market-structure concepts — classical price action. All original code, architecture, fusion and calibration by the author.
DISCLAIMER
This is an awareness/context tool — not a signal generator and not financial advice. No indicator predicts the future. Past behavior and any displayed statistics do not guarantee future results; the calibration is explicitly designed to report when the tool has no measurable edge — heed it. Trade your own plan and manage your risk. Indicator

VPIN Flow-Toxicity OscillatorVPIN Flow-Toxicity Oscillator
What it does
The VPIN Flow-Toxicity Oscillator is a single-pane order-flow toxicity gauge, scaled 0–100. It rises when estimated buy/sell volume becomes one-sided and "informed" — a condition that historically tends to precede volatility expansion and liquidity events, regardless of direction.
Why this is different (and original)
This is not a directional momentum or volume oscillator. It is an early-warning for volatility. Where most volume tools sum or net volume, VPIN measures the imbalance between estimated buy and sell volume and ranks how toxic (one-sided) flow currently is. The key property — documented in the microstructure literature — is that toxic flow tends to lead range expansion, so the oscillator can light up while price is still quiet. Delivering VPIN as a clean, self-calibrating 0–100 line with an honest volatility-expansion edge test (not a directional one) is what makes it original.
How it works
Bulk-Volume Classification splits each bar's volume into buy and sell using the normal CDF of the standardized price change (Φ of the price move divided by its rolling standard deviation).
Toxicity = rolling mean of |buy − sell| ÷ rolling mean of volume over the window (a 0–1 figure).
That figure is percentile-ranked over the percentile window into a 0–100 line, so the toxic and extreme thresholds self-calibrate to each instrument.
How to use it
Low (green) = calm, balanced flow. High (red) = toxic, one-sided flow — tighten risk and expect a range expansion, not a particular direction.
A cross above the Toxic threshold (triangle) is the warning event; the Extreme zone is a stronger version.
Read the EDGE row. Because VPIN signals volatility (not direction), the harness measures whether high toxicity actually preceded a range expansion — the high−low range over the horizon reaching ≥ k×ATR — versus the unconditional Base %. EDGE = Hit − Base. This is the honest test of the metric's stated claim.
Important honesty note
This is the bar-based bulk-volume approximation of VPIN. Charts do not provide exchange-classified aggressor (true buy/sell) data, so buy/sell split is estimated from price and volume. It is a faithful, widely-used approximation — but it is an approximation, and the indicator says so.
Settings guide
01 · VPIN Engine — return-sigma length, toxicity window, percentile window, universal price source.
02 · Calibration — horizon, expansion threshold (×ATR range), base-rate window.
03 · Bands — calm, toxic and extreme percentile thresholds.
04 · Display & Theme — visual style, regime tint, dashboard, colors.
Non-repaint
Classification uses closed bars only — no future leak.
Concept credit
Volume-synchronized Probability of Informed Trading (VPIN) and bulk-volume classification — Easley, López de Prado & O'Hara, Flow Toxicity and Liquidity in a High-Frequency World (2012).
Disclaimer
For research and education only. Not financial advice, not a recommendation, and not a guarantee of future results. VPIN signals toxicity and potential volatility, not direction. All statistics are in-sample and exclude costs. Do your own research and manage your own risk. Indicator

Order-Flow Profile Microstructure & Calibrated SweepsOrder-Flow Profile — Footprint, Microstructure & Calibrated Sweeps
A single-pane volume profile that reconstructs intrabar buy/sell activity, renders it as a footprint / delta heatmap with Point of Control and a 70% Value Area, layers a stack of market-microstructure factors over the same price bins, and then forward-tests every reversal signal it emits against realized outcomes. The dashboard reports measured edge with confidence intervals — not asserted edge.
It runs on any liquid symbol and any intraday timeframe. Defaults are tuned for index futures (e.g. NIFTY / BANKNIFTY); a few inputs adapt it to other instruments.
What it plots
Order-flow profile drawn to the right of price: each price bin colored by who controlled it (delta) with brightness scaled to volume, or a classic split footprint. The peak-volume row is the POC; a 70% Value Area is built outward from the POC.
Low-volume nodes / voids and four quadrant deltas that localize where buying and selling concentrated within the range.
A VPIN heat-glow background whose brightness rises with flow toxicity.
Sweep tags (ABS / EXH / DIV / REJ) at liquidity extremes, and a ⚡ reclaim-confirmed liquidity-sweep marker for the high-conviction stop-run-and-reclaim subset.
A calibration / key-reads dashboard (Compact by default, Pro on demand) that adapts its colors to your chart's background luminance.
Why these components belong in one script (component rationale)
This is not a bundle of unrelated indicators stacked together. Every component describes one object — the order-flow auction taking place inside the price profile — and each measures a different facet of it. They share one substrate (the price bins) and one validation spine (the calibration engine):
The profile says WHERE volume traded. POC, Value Area and voids are the structural skeleton — the price levels that matter.
Trade classification splits that volume into buy vs sell, giving every bin a delta. Bulk Volume Classification (a Student-t CDF on the standardized intrabar move) is used by default; on Premium plans, native bid/ask footprint can replace it, feeding the same bins. A tick rule classifies the same intrabars in parallel and the agreement % is reported, so you know when the trade-side read is fragile.
The microstructure factors qualify HOW that flow behaves at those levels. VPIN (informed vs balanced), multi-level OFI (depth-weighted imbalance across the bins), Kyle's λ and Amihud (price impact / illiquidity), and √-law absorption (flow soaked up vs fragile) each answer a question the raw profile cannot. They are computed over the very bins the profile draws.
The sweep layers detect reversals AT those levels — an order-flow taxonomy (absorption / exhaustion / divergence / rejection) plus a structural stop-run-and-reclaim. A Hawkes self-exciting intensity flags when sweeps are clustering (cascade risk).
A correlation-aware fusion (Kish design-effect shrinkage) combines the firing sweep's realized edge with the concurrent absorption and toxicity tells into a single reversal probability — shrinking redundant, correlated evidence so agreement among related signals cannot masquerade as independent confirmation.
The calibration spine forward-resolves every sweep and reports its hit rate versus base rate with a Wilson confidence interval. This is what ties the stack together: a factor only earns trust if the resolved outcomes say it does.
Remove any one layer and the others lose context: the profile without classification is just a volume histogram; the microstructure factors without the profile have no levels to attach to; the sweeps without calibration are unverified claims. Together they are a single, self-checking read of the auction.
How it works (mechanics)
Intrabar data. Lower-timeframe OHLCV is pulled with request.security_lower_tf (no lookahead). The lower timeframe is auto-derived from the chart timeframe or set manually.
Trade side. Bulk Volume Classification assigns each intrabar a buy fraction from a Student-t CDF of its standardized price change; delta = buy − sell. Where a Premium/Ultimate plan allows it, native request.footprint() real bid/ask volume per price replaces the reconstruction and feeds the identical bins.
Profile build. On the last bar, the chosen lookback of confirmed bars is accumulated into price bins; POC and the 70% Value Area are derived, voids and quadrant deltas computed.
VPIN. Volume is partitioned into equal-volume buckets; the average order imbalance across the last N buckets is the 0–1 toxicity read (with a percentile and background glow).
Impact factors. Stationarized (log-compressed, z-scored) OFI; depth-weighted multi-level OFI across the bins; Kyle's λ as the regression slope of return on signed flow; Amihud illiquidity as |return| per traded value.
Absorption. A displacement-normalized form and a √-law form (realized impact vs Y·ATR·√(|Δ|/V)): below the prediction = passive absorption / reversal candidate; above = fragile expansion.
Sweeps & fusion. At a swept extreme the bar is classified ABS / EXH / DIV / REJ; a Hawkes intensity tracks clustering; a Kish-decorrelated log-odds fusion outputs one reversal probability. Separately, a reclaim-confirmed liquidity sweep fires when price runs a confirmed swing pivot, closes back inside recovering a minimum fraction of the run, on a volume spike.
Calibration. Each sweep is queued and resolved a fixed horizon later against a moveATR·ATR threshold, recorded in R-multiples (MFE / MAE). The dashboard shows, per class: sample count, Hit% ± Wilson interval, Base% (the unconditional reversal rate over the same horizon), Edge (Hit − Base, starred at 95% significance), and average MFE / MAE.
Non-repaint: all detection is on confirmed bars, lower-timeframe arrays are confirmed intrabars, no dynamic-length built-ins are used, and the profile is drawn on the last bar from confirmed history. Pivots used by the liquidity sweep are confirmed before they can be swept.
What makes it original
It is built around calibration, not assertion. Most order-flow tools print a delta, a "confidence," or a footprint and leave it there. Here every reversal signal is forward-resolved against realized price and reported with a base rate and a Wilson interval, so the dashboard distinguishes a real edge from a small-sample illusion.
The agreement between Bulk Volume Classification and a tick rule is surfaced openly — a known weakness of reconstructed order flow is shown rather than hidden.
The microstructure factors are computed over the profile's own bins and decorrelated before fusion, so correlated flow signals don't inflate confidence.
It degrades gracefully from native exchange footprint (Premium) to reconstruction (every plan) with no change to the visual or the workflow.
All factor implementations are original Pine re-derivations of published methods; no code from other scripts is used.
How to use it
Apply to a liquid symbol on an intraday timeframe. Read the profile to see where volume concentrated (POC, Value Area, voids).
Watch the sweep tags and ⚡ liquidity-sweep markers at the edges of the range — these are reversal hypotheses, not guarantees.
Before trusting a sweep class, check its row in the calibration panel (switch the dashboard to Pro): is its Hit% above Base%, is the edge starred (significant), and is the Wilson interval tight enough to mean something?
Use the VPIN glow and fused reversal probability as context: bright background = one-sided / informed flow, which leans toward continuation and makes fades riskier.
The Compact dashboard summarizes the key reads (POC, VPIN, best calibrated edge, fused probability, liquidity-sweep status, auction efficiency); Pro expands the full per-class calibration table and every microstructure row.
Hidden EXP_* data-window series are provided for chaining into other scripts via input.source().
Data & markets
Works on whatever symbol the chart shows — nothing is hard-coded to an exchange or instrument. Defaults suit index futures on an intraday chart. For other instruments, adjust the Profile & Data Source group (lower-timeframe division, profile lookback) and, on a supporting plan, the native footprint settings. Reconstructed order flow is most reliable on liquid instruments with continuous volume.
Concept credits
This script operationalizes published methods; all implementations are original re-derivations.
Tick rule / trade sign — Lee & Ready (1991)
Bulk Volume Classification & flow toxicity (VPIN) — Easley, López de Prado & O'Hara (2012)
Order-Flow Imbalance — Cont, Kukanov & Stoikov (2014)
Multi-level / integrated OFI — Xu, Gould & Howison (2018)
Price impact (λ) — Kyle (1985)
Illiquidity ratio — Amihud (2002)
Self-exciting intensity — Hawkes (1971); Bacry, Muzy et al.
Square-root impact law — Almgren et al.; Tóth, Bouchaud et al.
Effective-sample decorrelation — Kish design effect
Market / auction profile (POC, Value Area) — Steidlmayer
Confidence interval — Wilson score interval (1927)
Disclaimer
For educational and informational purposes only. This is an analytical tool, not financial advice and not a solicitation to trade, and it is not a guarantee of future results. Order-flow classification from OHLCV is an estimate, not the true tape — without a Level-2 order book every delta here is a proxy (native footprint excepted). Always do your own research and manage risk; paper-trade before committing real capital. Indicator

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
