OPEN-SOURCE SCRIPT
업데이트됨 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.
## 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.
릴리즈 노트
RELEASE NOTES Added a Price source input so the return/impact/regime engine runs on any instrument in any market (candle-geometry and round-level features stay on native OHLC by design).
New plain-language ACTION banner at the top of the dashboard (with-trend / await-break / fade / momentum / reduce), regime lifted to the top, and a flow-bias arrow — readable at a glance without knowing the internals.
Dashboard theme is now fully adaptive to light/dark chart backgrounds (solid panel + zebra rows) for guaranteed legibility.
Expanded academic credits (PIN model; Sirignano & Cont 2019) and added an explicit honesty note (BVC vs true tick rule; VPIN and trading intensity).
Performance/clean-up: removed a redundant moving-average in the squeeze test, de-duplicated a running sum in the VPIN lens, and simplified the flow accumulators — same output, lighter per-bar load.
릴리즈 노트
v2.0 — Sweep-proof calibration, named VSA events, and a 4-way absorption check. The engine, the regime classifier and every dashboard read-out are unchanged; these three layers sit on top of the same imbalance spine.This update makes the existing read more robust and adds two optional event layers, without touching how the engine reconstructs order flow or how it classifies the regime.
1. Robust standardization (default ON) Reconstructed order-flow imbalance spikes violently on sweeps, and a plain mean/standard-deviation z-score lets those few outliers distort the whole pressure read. The imbalance is now standardized with median / median-absolute-deviation (×1.4826) — the robust equivalent of a z-score, which is nearly immune to a handful of extreme bars. The result: the buy/sell pressure and the multi-horizon consensus stay calibrated through violent bars instead of being dragged around by them. If you want the previous behaviour exactly, set Stationarization mode → "Classic (mean/stdev)" — the original output is reproduced bit-for-bit.
2. VSA bar events (optional, alerts only) The engine now recognises the classic Wyckoff / Volume-Spread-Analysis effort-vs-result bars on the flow it reconstructs — Upthrust (new high rejected on volume), Shakeout (new low reclaimed on volume), Stopping Volume (a wide down-bar closing off its low), and Buying / Selling Climax (peak-volume wide bars). An optional time-of-day volume baseline judges each bar's volume against the same clock slot on prior sessions, so a 09:20 spike is compared to other 09:20s rather than to a quiet mid-session bar. These are exposed as alertconditions only — the oscillator and dashboard are unchanged — because this pane is already information-dense.
3. Absorption consensus (optional, alerts only) Absorption — a large order-flow imbalance that fails to move price — is one of the most reliable signs that a level is being defended. It's now measured four independent ways on the same imbalance spine, and only flags when at least N of 4 agree: (1) the OLS residual of the price change regressed on flow (price moved far less than the flow predicted), (2) cost-per-tick in a high percentile (a lot of imbalance bought very little movement), (3) flow dominance minus candle result (one side dominated but the bar didn't finish there), and (4) a high-effort / narrow-result bar. Requiring consensus across four orthogonal lenses filters the false positives any single measure throws. Exposed as one "Absorption consensus" alert; no new plots.
What is unchanged. The synthetic-OFI reconstruction (tick-rule / bulk-volume-classification / candle-geometry), the Kyle-λ price-impact estimate, the multi-horizon consensus, the Hawkes self-excitation cascade, the three-lens liquidity-stress score, cross-asset confirmation, the round-level magnet, and the softmax regime classifier (Trend / Squeeze / Cascade Blast / Mean Reversion / Liquidity Shock) all behave exactly as before. The new layers only read the existing spine; they never feed back into it.
This remains a CONTEXT engine, not a buy/sell system: use the regime + action line to decide which of your own tools to trust. No Level-2 order book is exposed to charting scripts, so all order flow here is a disciplined proxy from intrabar volume and candle geometry — an approximation, not exchange-grade flow. Signals evaluate on closed bars when "Confirm signals on bar close" is on (default). Concept credits (unchanged): Cont-Kukanov-Stoikov and Kyle on order-flow impact; Easley-López de Prado-O'Hara on bulk-volume classification and VPIN; Lee-Ready tick rule; Amihud illiquidity; Hawkes self-exciting processes; Kolm-Turiel-Westray multi-horizon flow. Independent, original implementation; no third-party code reused. Research/education only, not financial advice.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.