Article contents

Evidence and scope

Cont, Kukanov and Stoikov study OFI and price impact for 50 US stocks. The proposed predictive and execution layers below are separate experiments, not reported results from that paper.

Data and marketsA specified limit-order venue with bid/ask prices, sizes, timestamps and documented feed rules. Public depth is not necessarily all available liquidity.
Research timeframesEvent time or 100ms–5s windows are research examples. An executable horizon depends on the actual observation, computation and network delays.
OFI rises when displayed ask size falls and declines when bid size falls; the flow can reverse after a positive imbalance.Open full-size illustration
Synthetic event OFI. The line measures signed queue changes and the auxiliary bars show independently invented trade volume; OFI is not traded volume.

Practical workflow

Workflow for Order book imbalance and OFI: inventory, quote flow and genuine prediction
The full steps appear below. At each stage, missing data or failed conditions require a recorded rejection reason.
  1. Reconstruct the bookApply the venue’s snapshot and delta rules.
  2. Calculate OBI and eKeep displayed state separate from quote flow.
  3. Close the feature windowUse only observations received before the decision.
  4. Simulate order arrivalApply delay, spread and queue assumptions.
  5. Evaluate net future returnsSeparate prediction from same-window explanation.

A snapshot and a stream of changes

OBI=(B−A)/(B+A), where B and A are contemporaneous best-bid and best-ask sizes. A multi-level version can use a fixed number of levels or fixed price distance, but must state which. An OBI near+1 means relatively more displayed bid depth; it does not count buyers, reveal intent or guarantee that the bid will remain when an order arrives.

OFI measures changes in queue sizes and quote prices. The primary study examines short-interval price impact and the role of depth [1]. That explanatory relationship is different from a strategy that forecasts and captures a future move after receiving the observations.

Trade delta counts aggressive executions. OFI also reflects quote additions, cancellations and price changes. OFI can become positive when asks are canceled without any aggressive buy trade. A positive OBI snapshot can coexist with rapidly negative OFI as the previously large bid queue disappears.

Complete the feature window before defining its target

For an update from n−1 to n, let b and a denote best bid and ask prices, and qb and qa their sizes. The code uses the level-one OFI definition from the study [1]. With unchanged prices it reduces to change in bid size minus change in ask size. When quote prices change, contributions must use the appropriate old or new queues rather than subtracting sizes alone.

Sum e over a completed window W. Possible normalizations include preceding average depth or a z-score estimated using training data. Do not standardize with the complete future test period. End-window OBI, within-window OFI and spread remain separate features. If B+A=0 or either side is missing, mark the observation invalid.

One proposed candidate requires zOFI>1.5, OBI>0.3, spread≤2 ticks and fresh data. Its target begins at an executable quote after the observation and order delays and ends H=2 seconds later. Those thresholds and horizon are research proposals, not a profitable configuration established by the paper.

Maintain two timestamps: when the exchange event occurred and when the complete feature was received locally. A predictive simulation that starts its position at the earlier timestamp assumes knowledge the trading system did not yet have. The return inside the feature window belongs to an explanatory test, not future trading profit.

e = I(b>=b_prev)*qb - I(b<=b_prev)*qb_prev
    - I(a<=a_prev)*qa + I(a>=a_prev)*qa_prev
OFI_window = sum(e for quote events in completed_window)
OBI = (qb-qa)/(qb+qa)
features_known_at = local_receive_time_of_last_required_event
order_arrival = features_known_at + compute_delay + network_delay
label = executable_exit_price_after(order_arrival,H) - executable_entry_price
# A price move inside the feature window is not future trading profit.

Reconstructing the book is part of the method

Bybit documents replacement on a new snapshot and deletion on a zero-size delta [2]. Implement the schema actually being consumed: level-one can be snapshot-only, while deeper feeds use deltas. One generic parser that assumes every message is incremental can create a false book.

Validate update IDs, cross sequence and clocks according to venue guarantees. Do not assume every identifier increments by exactly one unless that is documented. After resynchronization, do not compare a new snapshot with a stale discontinuous book and call the difference enormous OFI. Restart the feature window.

Published quotes are the observable subset, not all resting interest. Sampling or batching can omit cancel/add sequences between messages. Label the result observed OFI at the feed’s frequency. When comparing it with trade delta, use the separate trade channel’s aggressor and timestamp semantics [3].

Also record depth truncation. A top-K book can lose levels when prices move, even without the strategy observing individual cancellations. Avoid interpreting changes beyond the known boundary as exact order events. Missing quotes are not zero queues.

Synthetic calculations and executable outcomes

Suppose best bid is 100.00 with size 80 and ask 100.01 with size 20. OBI=0.60. Ask size then falls from 20 to 5 while bid and prices remain unchanged, giving e=+15. If that was cancellation, trade delta is zero. Next, bid size falls from 80 to 70 with ask size unchanged: e=−10. Two-event OFI is+5, while final OBI=65/75, approximately 0.867.

A positive feature is not yet a profit. For a separate synthetic winning path, buy at the executable ask 100.01 and sell at bid 100.04 after the chosen horizon. Gross gain is 0.03 per unit. If round-trip fees and slippage total 0.01, net gain is 0.02. Midprice 100.005 is not automatically an available purchase price.

In a failure path, the large bid disappears before the order arrives and quotes move to 99.96/99.98. A buy fills 99.98, followed by an exit at bid 99.94, losing 0.04 gross. A passive limit at 100.00 might instead fill precisely as price begins falling. The model cannot label adverse touches no-fill while giving favorable touches guaranteed execution.

Latency and order choice determine the economics

Choose aggressive or passive execution before testing. Aggressive orders pay the spread and may consume several depth levels at larger sizes. Passive orders require queue, cancellation and adverse-selection assumptions. Aggregated L2 without order IDs usually does not reveal exact queue priority, so report conservative fill scenarios or bounds.

Tick stops, fixed-horizon exits and exits on feature reversal are different policies. Fast feature changes can generate excessive turnover. Cooldown or persistence requirements may reduce it but also introduce delay; measure both effects.

When the feed is stale, crossed outside expected market rules, or resynchronizing, stop opening new positions. Existing positions require a predetermined risk-process response. Missing data does not mean price has stopped moving.

Run a size sensitivity as well as a latency sensitivity. A feature may predict a small midprice move yet fail to support the intended trade quantity. The relevant result is the execution-weighted return for the size being studied, not an unlimited number of trades at the displayed best quote.

Do not turn contemporaneous regression into claimed alpha

Separate three tasks: explaining the midprice change during W, forecasting the change after W, and measuring P&L after realistic latency. Strong R-squared on the first task does not establish the third. Price may already have reacted before the data reaches the system.

Split by trading day and purge target horizons that overlap validation boundaries. Compare against models using lagged returns, spread and depth without OFI. This checks whether OFI adds information or mainly restates the price move that just occurred.

Report prediction quality alongside turnover, fill ratio, net P&L, tail losses and sensitivity to delay and size. Evaluate liquidity regimes and venues separately. The paper’s equity evidence cannot be transferred to crypto perpetuals with an unchanged threshold and an assumed identical cost structure.

Common pitfalls

Filling every order at midprice

This removes the spread and overstates available returns.

A displayed wall proves committed demand

Quotes can be withdrawn and participant intent is not observed.

Calling simultaneous fit a forecast

Targets must begin after the complete feature is available.

Checklist before using this method

Check each item after verifying it on your data. Progress is saved in this browser; it does not certify a profitable strategy.

0/7 items

Frequently asked questions

Can OBI be positive while price falls?

Yes. Displayed depth is temporary; new flow, cancellations and other venues can change the market immediately.

Can standard OHLCV reconstruct OFI?

No. At least a sequence of best bid/ask prices and sizes is required. Trade volume does not reveal quote events.

Research sources

Each source supports the definition or evidence described beside it. The pseudocode, synthetic examples and proposed parameters require separate validation.

  1. The price impact of order book eventsCont, Kukanov and Stoikov. Read the abstract and OFI definition;50 US stocks, not a backtest of this strategy. Checked: .
  2. OrderbookBybit. Read snapshot/delta, clocks and public-feed limitations. Checked: .
  3. Public TradeBybit. Read trade-channel fields to distinguish aggressive executions from quote changes. Checked: .

Related methods

Risk note

This content supports education and research design, not financial advice. Backtest is historical simulation, does not guarantee future performance and does not place real trades. Methods in this library are not automatically features available in the app. See methodology and learning center.

Validate rules before risking real capital

Check app support, data and individual simulated trades; advanced detectors may require a separate implementation.

Download Backtest on the App Store