1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//! Core OrderBook implementation for managing price levels and orders
use super::error::OrderBookError;
use super::snapshot::OrderBookSnapshot;
use crate::utils::current_time_millis;
use dashmap::DashMap;
use pricelevel::{MatchResult, OrderId, OrderType, PriceLevel, Side, UuidGenerator};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tracing::trace;
use uuid::Uuid;
/// The OrderBook manages a collection of price levels for both bid and ask sides.
/// It supports adding, cancelling, and matching orders with lock-free operations where possible.
pub struct OrderBook {
/// The symbol or identifier for this order book
pub(super) symbol: String,
/// Bid side price levels (buy orders), stored in a concurrent map for lock-free access
/// The map is keyed by price levels and stores Arc references to PriceLevel instances
pub(super) bids: DashMap<u64, Arc<PriceLevel>>,
/// Ask side price levels (sell orders), stored in a concurrent map for lock-free access
/// The map is keyed by price levels and stores Arc references to PriceLevel instances
pub(super) asks: DashMap<u64, Arc<PriceLevel>>,
/// A concurrent map from order ID to (price, side) for fast lookups
/// This avoids having to search through all price levels to find an order
pub(super) order_locations: DashMap<OrderId, (u64, Side)>,
/// Generator for unique transaction IDs
transaction_id_generator: UuidGenerator,
/// The last price at which a trade occurred
pub(super) last_trade_price: AtomicU64,
/// Flag indicating if there was a trade
pub(super) has_traded: AtomicBool,
/// The timestamp of market close, if applicable (for DAY orders)
pub(super) market_close_timestamp: AtomicU64,
/// Flag indicating if market close is set
pub(super) has_market_close: AtomicBool,
}
impl OrderBook {
/// Create a new order book for the given symbol
pub fn new(symbol: &str) -> Self {
// Create a unique namespace for this order book's transaction IDs
let namespace = Uuid::new_v4();
Self {
symbol: symbol.to_string(),
bids: DashMap::new(),
asks: DashMap::new(),
order_locations: DashMap::new(),
transaction_id_generator: UuidGenerator::new(namespace),
last_trade_price: AtomicU64::new(0),
has_traded: AtomicBool::new(false),
market_close_timestamp: AtomicU64::new(0),
has_market_close: AtomicBool::new(false),
}
}
/// Get the symbol of this order book
pub fn symbol(&self) -> &str {
&self.symbol
}
/// Set the market close timestamp for DAY orders
pub fn set_market_close_timestamp(&self, timestamp: u64) {
self.market_close_timestamp
.store(timestamp, Ordering::SeqCst);
self.has_market_close.store(true, Ordering::SeqCst);
trace!(
"Order book {}: Set market close timestamp to {}",
self.symbol, timestamp
);
}
/// Clear the market close timestamp
pub fn clear_market_close_timestamp(&self) {
self.has_market_close.store(false, Ordering::SeqCst);
}
/// Get the best bid price, if any
pub fn best_bid(&self) -> Option<u64> {
let mut best_price = None;
// Find the highest price in bids
for item in self.bids.iter() {
let price = *item.key();
if best_price.is_none() || price > best_price.unwrap() {
best_price = Some(price);
}
}
best_price
}
/// Get the best ask price, if any
pub fn best_ask(&self) -> Option<u64> {
let mut best_price = None;
// Find the lowest price in asks
for item in self.asks.iter() {
let price = *item.key();
if best_price.is_none() || price < best_price.unwrap() {
best_price = Some(price);
}
}
best_price
}
/// Get the mid price (average of best bid and best ask)
pub fn mid_price(&self) -> Option<f64> {
match (self.best_bid(), self.best_ask()) {
(Some(bid), Some(ask)) => Some((bid as f64 + ask as f64) / 2.0),
_ => None,
}
}
/// Get the last trade price, if any
pub fn last_trade_price(&self) -> Option<u64> {
if self.has_traded.load(Ordering::Relaxed) {
Some(self.last_trade_price.load(Ordering::Relaxed))
} else {
None
}
}
/// Get the spread (best ask - best bid)
pub fn spread(&self) -> Option<u64> {
match (self.best_bid(), self.best_ask()) {
(Some(bid), Some(ask)) => Some(ask.saturating_sub(bid)),
_ => None,
}
}
/// Get all orders at a specific price level
pub fn get_orders_at_price(&self, price: u64, side: Side) -> Vec<Arc<OrderType>> {
trace!(
"Order book {}: Getting orders at price {} for side {:?}",
self.symbol, price, side
);
let price_levels = match side {
Side::Buy => &self.bids,
Side::Sell => &self.asks,
};
if let Some(price_level) = price_levels.get(&price) {
price_level.iter_orders()
} else {
Vec::new()
}
}
/// Get all orders in the book
pub fn get_all_orders(&self) -> Vec<Arc<OrderType>> {
trace!("Order book {}: Getting all orders", self.symbol);
let mut result = Vec::new();
// Get all bid orders
for item in self.bids.iter() {
let price_level = item.value();
result.extend(price_level.iter_orders());
}
// Get all ask orders
for item in self.asks.iter() {
let price_level = item.value();
result.extend(price_level.iter_orders());
}
result
}
/// Get an order by ID
pub fn get_order(&self, order_id: OrderId) -> Option<Arc<OrderType>> {
// Check if we know where this order is
if let Some(location) = self.order_locations.get(&order_id) {
let (price, side) = *location;
// Get appropriate price level
let price_levels = match side {
Side::Buy => &self.bids,
Side::Sell => &self.asks,
};
if let Some(price_level) = price_levels.get(&price) {
// Look through orders at this price level
for order in price_level.iter_orders() {
if order.id() == order_id {
return Some(order);
}
}
}
}
None
}
/// Match a market order against the book
pub fn match_market_order(
&self,
order_id: OrderId,
quantity: u64,
side: Side,
) -> Result<MatchResult, OrderBookError> {
trace!(
"Order book {}: Matching market order {} for {} at side {:?}",
self.symbol, order_id, quantity, side
);
// Determine which side of the book to match against
let opposite_side = side.opposite();
let match_side = match opposite_side {
Side::Buy => &self.bids, // Market sell matches against bids
Side::Sell => &self.asks, // Market buy matches against asks
};
let mut remaining_quantity = quantity;
let mut match_result = MatchResult::new(order_id, quantity);
let mut filled_orders = Vec::new();
// Keep matching until we've filled the order or run out of liquidity
while remaining_quantity > 0 {
// Get the best price to match against
let best_price = match opposite_side {
Side::Buy => self.best_bid(), // For sell orders, match against highest bid
Side::Sell => self.best_ask(), // For buy orders, match against lowest ask
};
if let Some(price) = best_price {
// Match against this price level
if let Some(entry) = match_side.get_mut(&price) {
let price_level = entry.value();
let price_level_match = price_level.match_order(
remaining_quantity,
order_id,
&self.transaction_id_generator,
);
// Update last trade price if we had matches
if !price_level_match.transactions.is_empty() {
self.last_trade_price.store(price, Ordering::SeqCst);
self.has_traded.store(true, Ordering::SeqCst);
}
// Update the match result with transactions
for transaction in price_level_match.transactions.as_vec() {
match_result.add_transaction(*transaction);
}
// Track filled orders to remove from tracking later
for filled_order_id in &price_level_match.filled_order_ids {
match_result.add_filled_order_id(*filled_order_id);
filled_orders.push(*filled_order_id);
}
// Update remaining quantity
remaining_quantity = price_level_match.remaining_quantity;
// If the price level is now empty, remove it
if price_level.order_count() == 0 {
// We must drop the mutable reference before removing
drop(entry);
match_side.remove(&price);
}
if remaining_quantity == 0 {
break; // Order fully matched
}
} else {
// This shouldn't happen since we just got the price from the map
break;
}
} else {
// No more price levels to match against
break;
}
}
// Remove all filled orders from tracking
for order_id in filled_orders {
self.order_locations.remove(&order_id);
}
// Update final match result
match_result.remaining_quantity = remaining_quantity;
match_result.is_complete = remaining_quantity == 0;
if match_result.transactions.as_vec().is_empty() {
// Order couldn't be matched at all
Err(OrderBookError::InsufficientLiquidity {
side,
requested: quantity,
available: 0,
})
} else if !match_result.is_complete && remaining_quantity > 0 {
// If the order was partially executed, you should still return Ok with the match_result
// but make sure the tests reflect this expected behavior
Ok(match_result)
} else {
Ok(match_result)
}
}
/// Create a snapshot of the current order book state
pub fn create_snapshot(&self, depth: usize) -> OrderBookSnapshot {
// Get all bid prices and sort them in descending order
let mut bid_prices: Vec<u64> = self.bids.iter().map(|item| *item.key()).collect();
bid_prices.sort_by(|a, b| b.cmp(a)); // Descending order
bid_prices.truncate(depth);
// Get all ask prices and sort them in ascending order
let mut ask_prices: Vec<u64> = self.asks.iter().map(|item| *item.key()).collect();
ask_prices.sort(); // Ascending order
ask_prices.truncate(depth);
let mut bid_levels = Vec::with_capacity(bid_prices.len());
let mut ask_levels = Vec::with_capacity(ask_prices.len());
// Create snapshots for each bid level
for price in bid_prices {
if let Some(price_level) = self.bids.get(&price) {
bid_levels.push(price_level.snapshot());
}
}
// Create snapshots for each ask level
for price in ask_prices {
if let Some(price_level) = self.asks.get(&price) {
ask_levels.push(price_level.snapshot());
}
}
OrderBookSnapshot {
symbol: self.symbol.clone(),
timestamp: current_time_millis(),
bids: bid_levels,
asks: ask_levels,
}
}
/// Get the total volume at each price level
pub fn get_volume_by_price(&self) -> (HashMap<u64, u64>, HashMap<u64, u64>) {
let mut bid_volumes = HashMap::new();
let mut ask_volumes = HashMap::new();
// Calculate bid volumes
for item in self.bids.iter() {
let price = *item.key();
let price_level = item.value();
bid_volumes.insert(price, price_level.total_quantity());
}
// Calculate ask volumes
for item in self.asks.iter() {
let price = *item.key();
let price_level = item.value();
ask_volumes.insert(price, price_level.total_quantity());
}
(bid_volumes, ask_volumes)
}
}