3.7 KiB
3.7 KiB
Module: orderbook_manager
Purpose
The orderbook_manager module provides in-memory orderbook state management with partial update capabilities. It maintains separate bid and ask sides and supports efficient top-level extraction for visualization.
Public Interface
Classes
OrderbookManager(depth_levels_per_side: int = 50): Main orderbook state manager
Methods
apply_updates(bids_updates: List[Tuple[float, float]], asks_updates: List[Tuple[float, float]]) -> None: Apply partial updates to both sidesget_total_volume() -> Tuple[float, float]: Get total bid and ask volumesget_top_levels() -> Tuple[List[List[float]], List[List[float]]]: Get sorted top levels for both sides
Private Methods
_apply_partial_updates(side_map: Dict[float, float], updates: List[Tuple[float, float]]) -> None: Apply updates to one side_build_top_levels(side_map: Dict[float, float], limit: int, reverse: bool) -> List[List[float]]: Extract sorted top levels
Usage Examples
from orderbook_manager import OrderbookManager
# Initialize manager
manager = OrderbookManager(depth_levels_per_side=25)
# Apply orderbook updates
bids = [(50000.0, 1.5), (49999.0, 2.0)]
asks = [(50001.0, 1.2), (50002.0, 0.8)]
manager.apply_updates(bids, asks)
# Get volume totals for OBI calculation
total_bids, total_asks = manager.get_total_volume()
obi = total_bids - total_asks
# Get top levels for depth visualization
bids_sorted, asks_sorted = manager.get_top_levels()
# Handle deletions (size = 0)
deletions = [(50000.0, 0.0)] # Remove price level
manager.apply_updates(deletions, [])
Dependencies
External
typing: Type annotations for Dict, List, Tuple
State Management
Internal State
_book_bids: Dict[float, float]: Price → size mapping for bid side_book_asks: Dict[float, float]: Price → size mapping for ask sidedepth_levels_per_side: int: Configuration for top-N extraction
Update Semantics
- Size = 0: Remove price level (deletion)
- Size > 0: Upsert price level with new size
- Size < 0: Ignored (invalid update)
Sorting Behavior
- Bids: Descending by price (highest price first)
- Asks: Ascending by price (lowest price first)
- Top-N: Limited by
depth_levels_per_sideparameter
Performance Characteristics
- Memory Efficient: Only stores non-zero price levels
- Fast Updates: O(1) upsert/delete operations using dict
- Efficient Sorting: Only sorts when extracting top levels
- Bounded Output: Limits result size for visualization performance
Use Cases
OBI Calculation
total_bids, total_asks = manager.get_total_volume()
order_book_imbalance = total_bids - total_asks
Depth Visualization
bids, asks = manager.get_top_levels()
depth_payload = {"bids": bids, "asks": asks}
Incremental Updates
# Typical orderbook update cycle
updates = parse_orderbook_changes(raw_data)
manager.apply_updates(updates['bids'], updates['asks'])
Testing
uv run pytest test_orderbook_manager.py -v
Test coverage includes:
- Partial update application correctness
- Deletion handling (size = 0)
- Volume calculation accuracy
- Top-level sorting and limiting
- Edge cases (empty books, single levels)
- Performance with large orderbooks
Configuration
depth_levels_per_side: Controls output size for visualization (default: 50)- Affects memory usage and sorting performance
- Higher values provide more market depth detail
- Lower values improve processing speed
Known Limitations
- No built-in validation of price/size values
- Memory usage scales with number of unique price levels
- No historical state tracking (current snapshot only)
- No support for spread calculation or market data statistics