1. Introduction: The Streaming Market Data Firehose
In quantitative trading, the Limit Order Book (LOB) serves as the source of truth for immediate price discovery and order book imbalance metrics. However, financial exchanges do not broadcast fully formed order book snapshots at millisecond frequencies due to network bandwidth constraints. Instead, they broadcast a raw firehose of incremental level updates (e.g., Nasdaq TotalView-ITCH, or Binance WebSocket feeds).
A typical feed event specifies: *\"Add 50 lots resting at bid price 100.25\"*, *\"Modify level at ask price 100.30 to size 0\"*, or *\"Execute 10 lots at 100.25\"*. Reconstructing these raw, fragmented streams into a queryable in-memory order book represents the foundational infrastructure that every quantitative desk is forced to rebuild.
2. Rebuilding Depth and Sorting Logic
Maintaining a clean order book requires managing two segregated, sorted lists of price levels: **bids** (sorted in descending order) and **asks** (sorted in ascending order). An incremental level update consists of three parameters: $Side$ (Bid/Ask), $Price$, and $Size$ (Quantity). The LOB state update logic follows three core rules:
- Insert/Update: If the price level exists, update its resting volume to $Size$. If it does not exist and $Size > 0$, insert it at the correct sorted position.
- Cancellation/Depletion: If $Size = 0$, completely remove the price level from the queue.
By keeping both lists sorted, we can extract the top $N$ depth levels at any instant to compute real-time signals. Let $P_{bid}$ and $P_{ask}$ be the best bid and ask prices, and let $V_{bid}$ and $V_{ask}$ be the resting volumes at those levels. We calculate the **micro-price** and **L1 book imbalance** as follows:
$Imbalance_{L1} = \frac{V_{bid} - V_{ask}}{V_{bid} + V_{ask}}$
$Price_{micro} = \frac{V_{bid} \cdot P_{ask} + V_{ask} \cdot P_{bid}}{V_{bid} + V_{ask}}$
Unlike the simple mid-price, the micro-price incorporates volume weights, making it a far more predictive short-term indicator of price drift.
3. TypeScript Implementation: Pure Order Book Rebuilder
The following pure TypeScript code (zero dependencies) illustrates how incoming incremental updates are processed to maintain sorted bid/ask sides and calculate micro-price:
interface LevelUpdate {
side: 'buy' | 'sell';
price: number;
size: number;
}
class LimitOrderBook {
private bids: Map = new Map(); // Price -> Size
private asks: Map = new Map();
public update(update: LevelUpdate): void {
const targetMap = update.side === 'buy' ? this.bids : this.asks;
if (update.size === 0) {
targetMap.delete(update.price);
} else {
targetMap.set(update.price, update.size);
}
}
public getSortedSnapshot(depth: number = 5) {
const sortedBids = Array.from(this.bids.entries())
.sort((a, b) => b[0] - a[0]) // Bids descending
.slice(0, depth);
const sortedAsks = Array.from(this.asks.entries())
.sort((a, b) => a[0] - b[0]) // Asks ascending
.slice(0, depth);
return { bids: sortedBids, asks: sortedAsks };
}
public calculateMicroPrice(): number | null {
const snap = this.getSortedSnapshot(1);
if (snap.bids.length === 0 || snap.asks.length === 0) return null;
const [bestBidPrice, bestBidSize] = snap.bids[0];
const [bestAskPrice, bestAskSize] = snap.asks[0];
const totalSize = bestBidSize + bestAskSize;
if (totalSize === 0) return null;
return (bestBidSize * bestAskPrice + bestAskSize * bestBidPrice) / totalSize;
}
}
// Usage:
// const lob = new LimitOrderBook();
// lob.update({ side: 'buy', price: 100.25, size: 50 });
// lob.update({ side: 'sell', price: 100.30, size: 40 });
// console.log("Micro Price:", lob.calculateMicroPrice());
4. Integrating Microstructure Signals for Alpha and Regime Identification
Having an in-memory reconstructed order book is the prerequisite for calculating advanced microstructure signals. For example, by analyzing the rolling autocorrelation of returns generated from the reconstructed micro-price, quants can execute the Lo-MacKinlay Variance Ratio Test. This allows algorithms to dynamically classify the market regime into mean-reverting (anti-persistent) or trending (persistent) structures, preventing the strategy from overfitting to local noise.
5. Conclusion: Releasing OrderFlow Metrics
To help independent algorithmic traders skip the redundant step of order book reconstruction, we have open-sourced a clean, zero-dependency order book rebuilder: **orderflow-metrics**. Built in pure TypeScript, it handles incremental LOB updates and exposes clean interfaces for OFI, VPIN, spreads, and micro-prices.