lob-orderbook 0.1.1

High-performance limit order book with real-time market depth updates, NATS integration, and SQLite metrics
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
// Comprehensive benchmark for LIMIT_ORDER_BOOK pipeline
// Tests: OrderBook update, best bid/ask retrieval, stale data checks,
//        depth calculation, market impact, and JSON deserialization
//
// ┌─────────────────────────────────────────────────────────────────────────────┐
// │ BENCHMARK TABLE (5-run average, warmup excluded)                            │
// ├─────────────────────┬──────────┬─────────┬──────────┬──────────┬────────────┤
// │ [1] OrderBook Upd   │  Updates │ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.19  │    0.18  │     0.21   │
// │   Medium volume     │   10,000 │     200 │    3.14  │    3.09  │     3.33   │
// │   High volume       │  100,000 │     500 │   70.24  │   70.11  │    71.09   │
// │   Max volume        │1,000,000 │   1,000 │ 1823.00  │ 1820.82  │  1831.73   │
// ├─────────────────────┼──────────┼─────────┼──────────┼──────────┼────────────┤
// │ [2] Best Bid/Ask    │  Lookups │ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.00  │    0.00  │     0.00   │
// │   Medium volume     │   10,000 │     200 │    0.02  │    0.02  │     0.02   │
// │   High volume       │  100,000 │     500 │    0.37  │    0.38  │     0.39   │
// │   Max volume        │1,000,000 │   1,000 │    4.53  │    4.71  │     4.74   │
// ├─────────────────────┼──────────┼─────────┼──────────┼──────────┼────────────┤
// │ [3] Mid Price       │  Lookups │ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.00  │    0.00  │     0.00   │
// │   Medium volume     │   10,000 │     200 │    0.03  │    0.03  │     0.03   │
// │   High volume       │  100,000 │     500 │    0.44  │    0.42  │     0.54   │
// │   Max volume        │1,000,000 │   1,000 │    4.99  │    4.94  │     5.23   │
// ├─────────────────────┼──────────┼─────────┼──────────┼──────────┼────────────┤
// │ [4] Depth Calc      │  Lookups │ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.01  │    0.01  │     0.01   │
// │   Medium volume     │   10,000 │     200 │    0.09  │    0.09  │     0.11   │
// │   High volume       │  100,000 │     500 │    0.96  │    0.92  │     1.08   │
// │   Max volume        │1,000,000 │   1,000 │   10.74  │   10.75  │    10.84   │
// ├─────────────────────┼──────────┼─────────┼──────────┼──────────┼────────────┤
// │ [5] Market Impact   │  Lookups │ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.01  │    0.01  │     0.01   │
// │   Medium volume     │   10,000 │     200 │    0.07  │    0.07  │     0.08   │
// │   High volume       │  100,000 │     500 │    0.78  │    0.77  │     0.82   │
// │   Max volume        │1,000,000 │   1,000 │    8.19  │    8.10  │     8.64   │
// ├─────────────────────┼──────────┼─────────┼──────────┼──────────┼────────────┤
// │ [6] Deserialization │ Deserials│ Symbols │  Avg ms  │  P50 ms  │  Max ms    │
// │   Low volume        │    1,000 │      50 │    0.73  │    0.72  │     0.75   │
// │   Medium volume     │   10,000 │     200 │   10.74  │   10.73  │    11.08   │
// │   High volume       │  100,000 │     500 │  172.38  │  173.04  │   174.59   │
// │   Max volume        │1,000,000 │   1,000 │ 3861.20  │ 3860.38  │  3874.41   │
// └─────────────────────┴──────────┴─────────┴──────────┴──────────┴────────────┘
// Throughput (Max volume): [1] 548.5K/s  [2] 441.5M/s  [3] 200.6M/s  [4] 93.1M/s  [5] 122.2M/s  [6] 259.0K/s
// Throughput (High volume): [1] 1.4M/s  [2] 539.9M/s  [3] 228.7M/s  [4] 104.0M/s  [5] 128.3M/s  [6] 580.1K/s
// Warmup: 1 iteration skipped (CPU cache warmup)
// Measured: 5 runs, P50/Max reported
// SYSTEM: Ubuntu 24.04.4 LTS | AMD Ryzen 7 5800H (16 cores, 13Gi RAM) | Rust 1.94.0
// TESTED: 2026-05-28 UTC
//
// USAGE: Run in release mode for accurate performance measurements:
//   cargo run --release --bin a0_benchmark
//
// NOTE: All benchmarks are CPU-only (no NATS, DB, or I/O operations).
//       For end-to-end pipeline metrics (including NATS), see run_limit_order_book_full().
//       Benchmark 6 uses simd-json to match production hot path.
//
// NOTE ON [1] OrderBook Update: Reuses one OrderBook across all iterations to
//       measure clear() + insert overhead, matching production where update()
//       calls self.bid_order_book.clear() then rebuilds the maps.
// NOTE ON [5] Market Impact: Uses concrete if/else branches (no Box<dyn Iterator>)
//       to match production code exactly — eliminates ~2-5ns vtable dispatch per iteration.

use std::collections::BTreeMap;
use std::time::Instant;

// ── Simulated data structures matching a0_limit_order_book.rs ──────────────
// NOTE: Field order differs from the library's MarketDepthData (exch_timestamp first).
//       Serde matches by field name, not position, so serialization is correct.
//       If a field is renamed in one place, this struct will silently diverge —
//       keep both definitions in sync to ensure benchmark accuracy.

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[allow(dead_code)]
struct MarketDepthData {
    unified_symbol: String,
    bids: Vec<(f64, i32)>,
    asks: Vec<(f64, i32)>,
    exch_timestamp: u64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct OrderedF64(f64);

impl Eq for OrderedF64 {}

impl PartialOrd for OrderedF64 {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for OrderedF64 {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.total_cmp(&other.0)
    }
}

#[derive(Debug)]
struct OrderBook {
    bid_order_book: BTreeMap<OrderedF64, i32>,
    ask_order_book: BTreeMap<OrderedF64, i32>,
    exch_timestamp: u64,
}

impl OrderBook {
    fn new() -> Self {
        Self {
            bid_order_book: BTreeMap::new(),
            ask_order_book: BTreeMap::new(),
            exch_timestamp: 0,
        }
    }

    fn update(&mut self, data: &MarketDepthData) -> bool {
        if self.exch_timestamp > data.exch_timestamp {
            return false;
        }
        self.bid_order_book.clear();
        self.ask_order_book.clear();
        for (price, size) in &data.bids {
            if price.is_finite() && *price > 0.0 && *size > 0 {
                self.bid_order_book.insert(OrderedF64(*price), *size);
            }
        }
        for (price, size) in &data.asks {
            if price.is_finite() && *price > 0.0 && *size > 0 {
                self.ask_order_book.insert(OrderedF64(*price), *size);
            }
        }
        self.exch_timestamp = data.exch_timestamp;
        true
    }

    fn get_best_bid(&self) -> Option<f64> {
        self.bid_order_book
            .iter()
            .next_back()
            .map(|(OrderedF64(p), _)| *p)
    }

    fn get_best_ask(&self) -> Option<f64> {
        self.ask_order_book
            .iter()
            .next()
            .map(|(OrderedF64(p), _)| *p)
    }

    fn calculate_mid_price(&self) -> Option<f64> {
        let bid = self.get_best_bid()?;
        let ask = self.get_best_ask()?;
        Some((bid + ask) / 2.0)
    }

    fn calculate_depth_at_price(&self, price: f64, is_bid: bool) -> usize {
        if is_bid {
            self.bid_order_book
                .iter()
                .rev()
                .take_while(|(OrderedF64(p), _)| *p >= price)
                .map(|(_, s)| *s as usize)
                .sum()
        } else {
            self.ask_order_book
                .iter()
                .take_while(|(OrderedF64(p), _)| *p <= price)
                .map(|(_, s)| *s as usize)
                .sum()
        }
    }

    fn calculate_market_impact(
        &self,
        quantity: usize,
        is_buy: bool,
    ) -> Option<(f64, f64, usize, bool)> {
        let mut remaining = quantity;
        let mut total_cost = 0.0;
        let mut impact_price = 0.0;
        let mut executed = 0;

        if is_buy {
            // Walk asks from lowest to highest price — concrete iterator, no vtable
            for (OrderedF64(price), size) in self.ask_order_book.iter() {
                let fill = remaining.min(*size as usize);
                total_cost += fill as f64 * *price;
                remaining -= fill;
                executed += fill;
                impact_price = *price;
                if remaining == 0 {
                    break;
                }
            }
        } else {
            // Walk bids from highest to lowest price — concrete iterator, no vtable
            for (OrderedF64(price), size) in self.bid_order_book.iter().rev() {
                let fill = remaining.min(*size as usize);
                total_cost += fill as f64 * *price;
                remaining -= fill;
                executed += fill;
                impact_price = *price;
                if remaining == 0 {
                    break;
                }
            }
        }

        if executed > 0 {
            let avg_price = total_cost / executed as f64;
            Some((avg_price, impact_price, executed, executed >= quantity))
        } else {
            None
        }
    }
}

fn create_test_market_depth(symbol: &str, timestamp: u64, levels: usize) -> MarketDepthData {
    let bids: Vec<(f64, i32)> = (0..levels)
        .map(|i| (100.0 - i as f64, 10 + i as i32 * 5))
        .collect();
    let asks: Vec<(f64, i32)> = (0..levels)
        .map(|i| (101.0 + i as f64, 5 + i as i32 * 5))
        .collect();
    MarketDepthData {
        unified_symbol: symbol.to_string(),
        bids,
        asks,
        exch_timestamp: timestamp,
    }
}

#[allow(dead_code)]
fn format_duration(ms: f64) -> String {
    if ms < 1.0 {
        format!("{:.2}μs", ms * 1000.0)
    } else {
        format!("{:.2}ms", ms)
    }
}

fn format_throughput(count: u64, ms: f64) -> String {
    let per_sec = count as f64 / (ms / 1000.0);
    if per_sec >= 1_000_000.0 {
        format!("{:.1}M/s", per_sec / 1_000_000.0)
    } else if per_sec >= 1_000.0 {
        format!("{:.1}K/s", per_sec / 1_000.0)
    } else {
        format!("{:.0}/s", per_sec)
    }
}

// ── BENCHMARK 1: OrderBook Update ──────────────────────────────────────────
fn run_update_bench(total_updates: u64, num_symbols: usize, levels: usize) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        let start = Instant::now();

        // Reuse one book across all updates to measure clear() + insert overhead
        // (matches production where update() calls self.bid_order_book.clear() then inserts)
        let mut book = OrderBook::new();

        for i in 0..total_updates {
            let sym_idx = (i as usize) % num_symbols;
            let symbol = format!("SYM_{:04}", sym_idx);
            let data = create_test_market_depth(&symbol, 1_000_000 + i, levels);
            let _ = book.update(&data);
        }

        if run == 0 {
            continue; // Skip warmup
        }

        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── BENCHMARK 2: Best Bid/Ask Retrieval ────────────────────────────────────
fn run_best_bid_ask_bench(
    total_updates: u64,
    num_symbols: usize,
    levels: usize,
) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        // Setup: create books
        let mut books = Vec::with_capacity(num_symbols);
        for s in 0..num_symbols {
            let symbol = format!("SYM_{:04}", s);
            let data = create_test_market_depth(&symbol, 1_000_000, levels);
            let mut book = OrderBook::new();
            book.update(&data);
            books.push(book);
        }

        let start = Instant::now();
        let mut _bid_sum = 0.0;
        let mut _ask_sum = 0.0;

        for i in 0..total_updates {
            let book = &books[(i as usize) % num_symbols];
            if let Some(b) = book.get_best_bid() {
                _bid_sum += b;
            }
            if let Some(a) = book.get_best_ask() {
                _ask_sum += a;
            }
        }

        if run == 0 {
            continue;
        }
        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── BENCHMARK 3: Mid Price Calculation ─────────────────────────────────────
fn run_mid_price_bench(total_updates: u64, num_symbols: usize, levels: usize) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        let mut books = Vec::with_capacity(num_symbols);
        for s in 0..num_symbols {
            let symbol = format!("SYM_{:04}", s);
            let data = create_test_market_depth(&symbol, 1_000_000, levels);
            let mut book = OrderBook::new();
            book.update(&data);
            books.push(book);
        }

        let start = Instant::now();
        let mut _mid_sum = 0.0;

        for i in 0..total_updates {
            let book = &books[(i as usize) % num_symbols];
            if let Some(m) = book.calculate_mid_price() {
                _mid_sum += m;
            }
        }

        if run == 0 {
            continue;
        }
        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── BENCHMARK 4: Depth Calculation ─────────────────────────────────────────
fn run_depth_bench(total_updates: u64, num_symbols: usize, levels: usize) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        let mut books = Vec::with_capacity(num_symbols);
        for s in 0..num_symbols {
            let symbol = format!("SYM_{:04}", s);
            let data = create_test_market_depth(&symbol, 1_000_000, levels);
            let mut book = OrderBook::new();
            book.update(&data);
            books.push(book);
        }

        let start = Instant::now();
        let mut _depth_sum = 0usize;

        for i in 0..total_updates {
            let book = &books[(i as usize) % num_symbols];
            _depth_sum += book.calculate_depth_at_price(95.0, true);
        }

        if run == 0 {
            continue;
        }
        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── BENCHMARK 5: Market Impact ─────────────────────────────────────────────
fn run_market_impact_bench(
    total_updates: u64,
    num_symbols: usize,
    levels: usize,
) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        let mut books = Vec::with_capacity(num_symbols);
        for s in 0..num_symbols {
            let symbol = format!("SYM_{:04}", s);
            let data = create_test_market_depth(&symbol, 1_000_000, levels);
            let mut book = OrderBook::new();
            book.update(&data);
            books.push(book);
        }

        let start = Instant::now();
        let mut _impact_sum = 0.0;

        for i in 0..total_updates {
            let book = &books[(i as usize) % num_symbols];
            if let Some((avg, _, _, _)) = book.calculate_market_impact(50, true) {
                _impact_sum += avg;
            }
        }

        if run == 0 {
            continue;
        }
        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── BENCHMARK 6: JSON Deserialization Overhead ───────────────────────────────
// NOTE: Uses simd-json to match production hot path (process_message_batch)
//       serde_json::to_vec is only used for setup (not measured)
// NOTE: simd_json mutates the buffer in-place (replaces structural chars with
//       sentinel values), so each iteration needs a fresh copy. In production,
//       NATS delivers a fresh Vec<u8> per message — clone simulates that.
//       Clone cost for ~1KB messages is ~100-200ns vs ~1-5μs deserialize (<5% noise).
fn run_deserialization_bench(
    total_updates: u64,
    num_symbols: usize,
    levels: usize,
) -> (f64, f64, f64) {
    let mut times = Vec::with_capacity(5);

    for run in 0..6 {
        // Pre-serialize messages (setup cost, NOT measured)
        let serialized: Vec<Vec<u8>> = {
            let mut v = Vec::with_capacity(num_symbols);
            for s in 0..num_symbols {
                let symbol = format!("SYM_{:04}", s);
                let data = create_test_market_depth(&symbol, 1_000_000, levels);
                match serde_json::to_vec(&data) {
                    Ok(bytes) => v.push(bytes),
                    Err(_) => continue,
                }
            }
            v
        };

        let start = Instant::now();

        for i in 0..total_updates {
            let sym_idx = (i as usize) % serialized.len();
            // WHY clone: simd_json consumes buffer in-place; production gets fresh
            // Vec<u8> from NATS so there's no clone cost on the real hot path.
            // Clone noise: ~100-200ns for ~1KB vs ~1-5μs deserialize (<5%).
            let mut msg = serialized[sym_idx].clone();
            let _ = simd_json::serde::from_slice::<MarketDepthData>(&mut msg);
        }

        if run == 0 {
            continue;
        }
        times.push(start.elapsed().as_secs_f64() * 1000.0);
    }

    times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let avg = times.iter().sum::<f64>() / times.len() as f64;
    let p50 = times[2];
    let max = *times.last().unwrap();
    (avg, p50, max)
}

// ── MAIN ───────────────────────────────────────────────────────────────────
fn main() {
    println!("\n╔══════════════════════════════════════════════════════════════════════╗");
    println!("║  LIMIT_ORDER_BOOK BENCHMARK SUITE                                   ║");
    println!("╚══════════════════════════════════════════════════════════════════════╝\n");

    let configs = [
        ("Low volume", 1_000u64, 50, 5),
        ("Medium volume", 10_000u64, 200, 10),
        ("High volume", 100_000u64, 500, 20),
        ("Max volume", 1_000_000u64, 1000, 50),
    ];

    // Benchmark 1: OrderBook Update
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [1] OrderBook Update (clear + rebuild BTreeMap)                     │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Updates  │ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_update_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    // Benchmark 2: Best Bid/Ask
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [2] Best Bid/Ask Retrieval (BTreeMap iter/rev)                      │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Lookups  │ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_best_bid_ask_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates * 2, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    // Benchmark 3: Mid Price
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [3] Mid Price Calculation ((bid + ask) / 2)                         │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Lookups  │ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_mid_price_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    // Benchmark 4: Depth Calculation
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [4] Depth Calculation (take_while + sum)                            │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Lookups  │ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_depth_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    // Benchmark 5: Market Impact
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [5] Market Impact (book walk for avg execution price)               │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Lookups  │ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_market_impact_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    // Benchmark 6: JSON Deserialization
    println!("┌──────────────────────────────────────────────────────────────────────┐");
    println!("│ [6] JSON Deserialization (bytes → MarketDepthData, simd-json)        │");
    println!("├─────────────────────┬──────────┬─────────┬─────────┬─────────┬────────┤");
    println!("│ Test                │ Deserials│ Symbols │  Avg ms │   P50 ms│  Max ms│");
    println!("├─────────────────────┼──────────┼─────────┼─────────┼─────────┼────────┤");

    for (name, updates, syms, levels) in configs {
        let (avg, p50, max) = run_deserialization_bench(updates, syms, levels);
        println!(
            "│ {:<19} │ {:>8}{:>7}{:>7.2}{:>7.2}{:>7.2}",
            name, updates, syms, avg, p50, max
        );
        println!(
            "│   → Throughput: {:>14}                                       │",
            format_throughput(updates, avg)
        );
    }
    println!("└──────────────────────────────────────────────────────────────────────┘\n");

    println!("System: Ubuntu 24.04.4 LTS | AMD Ryzen 7 5800H (16 cores, 13Gi RAM) | Rust 1.94.0");
    println!("Tested: 2026-04-10 UTC");
    println!("\nNote: All benchmarks are CPU-only (no NATS, DB, or I/O operations).");
    println!("Run with --release flag for accurate performance measurements.\n");
}