fin-stream 2.4.2

Real-time market data streaming primitives — 100K+ ticks/second ingestion pipeline
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
//! Order book — delta streaming with full reconstruction.
//!
//! ## Responsibility
//! Maintain a live order book per symbol by applying incremental deltas
//! received from exchange WebSocket feeds. Supports full snapshot reset
//! and crossed-book detection.
//!
//! ## Guarantees
//! - Deterministic: applying the same delta sequence always yields the same book
//! - Non-panicking: all mutations return Result
//! - Single-owner mutable access: all mutation methods take `&mut self`; wrap
//!   in `Arc<Mutex<OrderBook>>` or `Arc<RwLock<OrderBook>>` for shared
//!   concurrent access across threads

use crate::error::StreamError;
use rust_decimal::Decimal;
use std::collections::BTreeMap;

/// Side of the order book.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum BookSide {
    /// Bid (buy) side.
    Bid,
    /// Ask (sell) side.
    Ask,
}

/// A single price level in the order book.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PriceLevel {
    /// Price of this level.
    pub price: Decimal,
    /// Resting quantity at this price.
    pub quantity: Decimal,
}

impl PriceLevel {
    /// Construct a price level from a price and resting quantity.
    pub fn new(price: Decimal, quantity: Decimal) -> Self {
        Self { price, quantity }
    }

    /// Notional value of this level: `price × quantity`.
    pub fn notional(&self) -> Decimal {
        self.price * self.quantity
    }
}

/// Incremental order book update.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BookDelta {
    /// Symbol this delta applies to.
    pub symbol: String,
    /// Side of the book (bid or ask).
    pub side: BookSide,
    /// Price level to update. `quantity == 0` means remove the level.
    pub price: Decimal,
    /// New resting quantity at this price. Zero removes the level.
    pub quantity: Decimal,
    /// Optional exchange-assigned sequence number for gap detection.
    pub sequence: Option<u64>,
}

impl BookDelta {
    /// Construct a delta without a sequence number.
    ///
    /// Use [`BookDelta::with_sequence`] to attach the exchange sequence number
    /// when available; sequenced deltas enable gap detection.
    pub fn new(
        symbol: impl Into<String>,
        side: BookSide,
        price: Decimal,
        quantity: Decimal,
    ) -> Self {
        Self {
            symbol: symbol.into(),
            side,
            price,
            quantity,
            sequence: None,
        }
    }

    /// Attach an exchange sequence number to this delta.
    pub fn with_sequence(mut self, seq: u64) -> Self {
        self.sequence = Some(seq);
        self
    }

    /// Returns `true` if this delta signals a level deletion (`quantity == 0`).
    ///
    /// Exchanges signal the removal of a price level by sending a delta with
    /// zero quantity. Checking `is_delete()` is clearer than comparing with
    /// `Decimal::ZERO` at every call site.
    pub fn is_delete(&self) -> bool {
        self.quantity.is_zero()
    }

    /// Returns `true` if this delta adds or updates a price level (`quantity > 0`).
    ///
    /// The logical complement of [`is_delete`](Self::is_delete).
    pub fn is_add(&self) -> bool {
        !self.is_delete()
    }
}

impl std::fmt::Display for BookDelta {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let side = match self.side {
            BookSide::Bid => "Bid",
            BookSide::Ask => "Ask",
        };
        match self.sequence {
            Some(seq) => write!(
                f,
                "{} {} {} x {} seq={}",
                self.symbol, side, self.price, self.quantity, seq
            ),
            None => write!(
                f,
                "{} {} {} x {}",
                self.symbol, side, self.price, self.quantity
            ),
        }
    }
}

/// Live order book for a single symbol.
pub struct OrderBook {
    symbol: String,
    bids: BTreeMap<Decimal, Decimal>, // price → quantity
    asks: BTreeMap<Decimal, Decimal>, // price → quantity
    last_sequence: Option<u64>,
}

impl OrderBook {
    /// Create an empty order book for the given symbol.
    pub fn new(symbol: impl Into<String>) -> Self {
        Self {
            symbol: symbol.into(),
            bids: BTreeMap::new(),
            asks: BTreeMap::new(),
            last_sequence: None,
        }
    }

    /// Apply an incremental delta. quantity == 0 removes the level.
    ///
    /// # Errors
    ///
    /// - [`StreamError::BookReconstructionFailed`] if the delta's symbol does
    ///   not match this book.
    /// - [`StreamError::SequenceGap`] if the delta carries a sequence number
    ///   that is not exactly one greater than the last applied sequence.
    /// - [`StreamError::BookCrossed`] if applying the delta would leave the
    ///   best bid >= best ask.
    #[must_use = "errors from apply() must be handled to avoid missed gaps or crossed-book state"]
    pub fn apply(&mut self, delta: BookDelta) -> Result<(), StreamError> {
        if delta.symbol != self.symbol {
            return Err(StreamError::BookReconstructionFailed {
                symbol: self.symbol.clone(),
                reason: format!(
                    "delta symbol '{}' does not match book '{}'",
                    delta.symbol, self.symbol
                ),
            });
        }

        // Sequence gap detection: if both the book and the delta carry a
        // sequence number, they must be consecutive.
        if let (Some(last), Some(incoming)) = (self.last_sequence, delta.sequence) {
            let expected = last + 1;
            if incoming != expected {
                return Err(StreamError::SequenceGap {
                    symbol: self.symbol.clone(),
                    expected,
                    got: incoming,
                });
            }
        }

        let map = match delta.side {
            BookSide::Bid => &mut self.bids,
            BookSide::Ask => &mut self.asks,
        };
        if delta.quantity.is_zero() {
            map.remove(&delta.price);
        } else {
            map.insert(delta.price, delta.quantity);
        }
        if let Some(seq) = delta.sequence {
            self.last_sequence = Some(seq);
        }
        self.check_crossed()
    }

    /// Reset the book from a full snapshot, also resetting the sequence counter.
    #[must_use = "errors from reset() indicate a crossed snapshot and must be handled"]
    pub fn reset(
        &mut self,
        bids: Vec<PriceLevel>,
        asks: Vec<PriceLevel>,
    ) -> Result<(), StreamError> {
        self.bids.clear();
        self.asks.clear();
        self.last_sequence = None;
        for lvl in bids {
            if !lvl.quantity.is_zero() {
                self.bids.insert(lvl.price, lvl.quantity);
            }
        }
        for lvl in asks {
            if !lvl.quantity.is_zero() {
                self.asks.insert(lvl.price, lvl.quantity);
            }
        }
        self.check_crossed()
    }

    /// Best bid (highest).
    pub fn best_bid(&self) -> Option<PriceLevel> {
        self.bids
            .iter()
            .next_back()
            .map(|(p, q)| PriceLevel::new(*p, *q))
    }

    /// Best ask (lowest).
    pub fn best_ask(&self) -> Option<PriceLevel> {
        self.asks
            .iter()
            .next()
            .map(|(p, q)| PriceLevel::new(*p, *q))
    }

    /// Resting quantity at the best bid level.
    ///
    /// Shorthand for `self.best_bid().map(|l| l.quantity)`.
    pub fn best_bid_qty(&self) -> Option<Decimal> {
        self.best_bid().map(|l| l.quantity)
    }

    /// Resting quantity at the best ask level.
    ///
    /// Shorthand for `self.best_ask().map(|l| l.quantity)`.
    pub fn best_ask_qty(&self) -> Option<Decimal> {
        self.best_ask().map(|l| l.quantity)
    }

    /// Mid price.
    pub fn mid_price(&self) -> Option<Decimal> {
        let bid = self.best_bid()?.price;
        let ask = self.best_ask()?.price;
        Some((bid + ask) / Decimal::from(2))
    }

    /// Quantity-weighted mid price.
    ///
    /// `(bid_price × ask_qty + ask_price × bid_qty) / (bid_qty + ask_qty)`.
    ///
    /// Gives a better estimate of fair value than the arithmetic mid when the
    /// best-bid and best-ask have very different resting quantities.
    /// Returns `None` if either side is empty or total quantity is zero.
    pub fn weighted_mid_price(&self) -> Option<Decimal> {
        let bid = self.best_bid()?;
        let ask = self.best_ask()?;
        let total_qty = bid.quantity + ask.quantity;
        if total_qty.is_zero() {
            return None;
        }
        Some((bid.price * ask.quantity + ask.price * bid.quantity) / total_qty)
    }

    /// Returns `(best_bid, best_ask)` in a single call, or `None` if either side is absent.
    pub fn top_of_book(&self) -> Option<(PriceLevel, PriceLevel)> {
        Some((self.best_bid()?, self.best_ask()?))
    }

    /// Full displayed price range: `best_ask - worst_displayed_bid`.
    ///
    /// Wider than `spread()` which only uses the top-of-book.
    /// Returns `None` if either side is empty.
    pub fn price_range(&self) -> Option<Decimal> {
        let worst_bid = *self.bids.iter().next()?.0; // lowest bid price
        let best_ask = self.best_ask_price()?;
        Some(best_ask - worst_bid)
    }

    /// Spread.
    pub fn spread(&self) -> Option<Decimal> {
        let bid = self.best_bid()?.price;
        let ask = self.best_ask()?.price;
        Some(ask - bid)
    }

    /// Returns `true` if both sides of the book have no resting orders.
    pub fn is_empty(&self) -> bool {
        self.bids.is_empty() && self.asks.is_empty()
    }

    /// Combined notional value (price × quantity) across both bid and ask sides.
    pub fn total_notional_both_sides(&self) -> Decimal {
        self.total_notional(BookSide::Bid) + self.total_notional(BookSide::Ask)
    }

    /// Returns `true` if a resting order exists at `price` on `side`.
    pub fn price_level_exists(&self, side: BookSide, price: Decimal) -> bool {
        match side {
            BookSide::Bid => self.bids.contains_key(&price),
            BookSide::Ask => self.asks.contains_key(&price),
        }
    }

    /// Remove all price levels from both sides of the book.
    ///
    /// Also clears the last seen sequence number. Useful when reconnecting to
    /// an exchange feed and waiting for a fresh snapshot before applying deltas.
    pub fn clear(&mut self) {
        self.bids.clear();
        self.asks.clear();
        self.last_sequence = None;
    }

    /// Number of bid levels.
    pub fn bid_depth(&self) -> usize {
        self.bids.len()
    }

    /// Number of ask levels.
    pub fn ask_depth(&self) -> usize {
        self.asks.len()
    }

    /// Total resting quantity across all bid levels.
    pub fn bid_volume_total(&self) -> Decimal {
        self.bids.values().copied().sum()
    }

    /// Total resting quantity across all ask levels.
    pub fn ask_volume_total(&self) -> Decimal {
        self.asks.values().copied().sum()
    }

    /// Total notional value (`Σ price × quantity`) across all levels on the
    /// given side.
    ///
    /// Useful for comparing the dollar value committed to each side of the
    /// book, rather than just the raw quantity.
    pub fn total_notional(&self, side: BookSide) -> Decimal {
        match side {
            BookSide::Bid => self.bids.iter().map(|(p, q)| *p * *q).sum(),
            BookSide::Ask => self.asks.iter().map(|(p, q)| *p * *q).sum(),
        }
    }

    /// Returns `true` if exactly one side (bids or asks) has levels and the
    /// other is empty. An empty book returns `false`.
    pub fn is_one_sided(&self) -> bool {
        (self.bid_depth() > 0) != (self.ask_depth() > 0)
    }

    /// Imbalance between number of bid and ask price levels.
    ///
    /// Returns `(bid_levels - ask_levels) / (bid_levels + ask_levels)` as `f64`
    /// in the range `[-1.0, 1.0]`. Returns `None` when the book is empty.
    pub fn level_count_imbalance(&self) -> Option<f64> {
        let total = self.bid_depth() + self.ask_depth();
        if total == 0 {
            return None;
        }
        let diff = self.bid_depth() as f64 - self.ask_depth() as f64;
        Some(diff / total as f64)
    }

    /// Bid-ask spread in basis points: `(ask − bid) / mid × 10_000`.
    ///
    /// Returns `None` if either side of the book is empty or the mid-price is zero.
    pub fn bid_ask_spread_bps(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let mid = self.mid_price()?;
        if mid.is_zero() {
            return None;
        }
        let spread_f = self.spread()?.to_f64()?;
        let mid_f = mid.to_f64()?;
        Some(spread_f / mid_f * 10_000.0)
    }

    /// Total resting quantity across all bid levels.
    ///
    /// Alias for [`bid_volume_total`](Self::bid_volume_total).
    #[deprecated(since = "2.2.0", note = "Use `bid_volume_total()` instead")]
    pub fn total_bid_volume(&self) -> Decimal {
        self.bid_volume_total()
    }

    /// Total resting quantity across all ask levels.
    ///
    /// Alias for [`ask_volume_total`](Self::ask_volume_total).
    #[deprecated(since = "2.2.0", note = "Use `ask_volume_total()` instead")]
    pub fn total_ask_volume(&self) -> Decimal {
        self.ask_volume_total()
    }

    /// Sum of the top `n` bid levels' quantities (best `n` bids).
    ///
    /// If fewer than `n` bid levels exist, sums all available levels. Returns
    /// `Decimal::ZERO` when the bid side is empty.
    pub fn cumulative_bid_volume(&self, n: usize) -> Decimal {
        self.bids.values().rev().take(n).copied().sum()
    }

    /// Sum of the top `n` ask levels' quantities (best `n` asks).
    ///
    /// If fewer than `n` ask levels exist, sums all available levels. Returns
    /// `Decimal::ZERO` when the ask side is empty.
    pub fn cumulative_ask_volume(&self, n: usize) -> Decimal {
        self.asks.values().take(n).copied().sum()
    }

    /// Best `n` bid levels as [`PriceLevel`]s, sorted best-first (highest price first).
    ///
    /// If fewer than `n` levels exist, all are returned.
    pub fn top_n_bids(&self, n: usize) -> Vec<PriceLevel> {
        self.bids
            .iter()
            .rev()
            .take(n)
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// Best `n` ask levels as [`PriceLevel`]s, sorted best-first (lowest price first).
    ///
    /// If fewer than `n` levels exist, all are returned.
    pub fn top_n_asks(&self, n: usize) -> Vec<PriceLevel> {
        self.asks
            .iter()
            .take(n)
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// Ratio of cumulative bid volume to cumulative ask volume across top `n` levels.
    ///
    /// Returns `None` when the ask side is empty (avoids division by zero).
    /// Values > 1.0 indicate buy-side pressure; values < 1.0 indicate sell-side pressure.
    pub fn depth_ratio(&self, n: usize) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let ask_vol = self.cumulative_ask_volume(n);
        if ask_vol.is_zero() {
            return None;
        }
        (self.cumulative_bid_volume(n) / ask_vol).to_f64()
    }

    /// The cheapest ask level with quantity ≥ `min_qty`, or `None` if no such level exists.
    ///
    /// Scans ask levels from the tightest (best) price outward. Useful for
    /// detecting large sell walls sitting near the top of the book.
    pub fn ask_wall(&self, min_qty: Decimal) -> Option<PriceLevel> {
        self.asks
            .iter()
            .find(|(_, qty)| **qty >= min_qty)
            .map(|(price, qty)| PriceLevel::new(*price, *qty))
    }

    /// The highest bid level with quantity ≥ `min_qty`, or `None` if no such level exists.
    ///
    /// Scans bid levels from the best (highest) price downward. Useful for
    /// detecting large buy walls sitting near the top of the book.
    pub fn bid_wall(&self, min_qty: Decimal) -> Option<PriceLevel> {
        self.bids
            .iter()
            .rev()
            .find(|(_, qty)| **qty >= min_qty)
            .map(|(price, qty)| PriceLevel::new(*price, *qty))
    }

    /// Number of bid levels with price strictly above `price`.
    ///
    /// Useful for measuring how much resting bid interest sits above a given
    /// reference price (e.g. the last trade price).
    pub fn bid_levels_above(&self, price: Decimal) -> usize {
        self.bids.range((std::ops::Bound::Excluded(&price), std::ops::Bound::Unbounded)).count()
    }

    /// Number of ask levels with price strictly below `price`.
    ///
    /// Useful for measuring how much resting ask interest sits below a given
    /// reference price (e.g. the last trade price).
    pub fn ask_levels_below(&self, price: Decimal) -> usize {
        self.asks.range(..price).count()
    }

    /// Ratio of total bid volume to total ask volume.
    ///
    /// Returns `None` when either side has zero volume (avoids division by
    /// zero and meaningless ratios on empty books).  A value > 1.0 means more
    /// buying interest; < 1.0 means more selling pressure.
    pub fn bid_ask_volume_ratio(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid = self.bid_volume_total();
        let ask = self.ask_volume_total();
        if bid.is_zero() || ask.is_zero() {
            return None;
        }
        let bid_f = bid.to_f64()?;
        let ask_f = ask.to_f64()?;
        Some(bid_f / ask_f)
    }

    /// Total volume across the top `n` bid price levels (best-to-worst order).
    ///
    /// If there are fewer than `n` levels, the volume of all existing levels is
    /// returned. Returns `Decimal::ZERO` for an empty bid side.
    pub fn top_n_bid_volume(&self, n: usize) -> Decimal {
        self.cumulative_bid_volume(n)
    }

    /// Normalised order-book imbalance: `(bid_vol − ask_vol) / (bid_vol + ask_vol)`.
    ///
    /// Returns a value in `[-1.0, 1.0]`.  `+1.0` means all volume is on the
    /// bid side (strong buying pressure); `-1.0` means all volume is on the
    /// ask side (strong selling pressure).  Returns `None` when both sides are
    /// empty (sum is zero).
    pub fn imbalance_ratio(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid = self.bid_volume_total();
        let ask = self.ask_volume_total();
        let total = bid + ask;
        if total.is_zero() {
            return None;
        }
        let bid_f = bid.to_f64()?;
        let ask_f = ask.to_f64()?;
        let total_f = bid_f + ask_f;
        Some((bid_f - ask_f) / total_f)
    }

    /// Total volume across the top `n` ask price levels (best-to-worst order,
    /// i.e. lowest asks first).
    ///
    /// If there are fewer than `n` levels, the volume of all existing levels is
    /// returned. Returns `Decimal::ZERO` for an empty ask side.
    pub fn top_n_ask_volume(&self, n: usize) -> Decimal {
        self.cumulative_ask_volume(n)
    }

    /// Returns `true` if there is a non-zero ask entry at exactly `price`.
    pub fn has_ask_at(&self, price: Decimal) -> bool {
        self.asks.get(&price).map_or(false, |q| !q.is_zero())
    }

    /// Returns `(bid_levels, ask_levels)` — the number of distinct price levels
    /// on each side of the book.
    pub fn bid_ask_depth(&self) -> (usize, usize) {
        (self.bid_depth(), self.ask_depth())
    }

    /// Total volume across all bid and ask levels combined.
    ///
    /// Alias for [`total_volume`](Self::total_volume).
    pub fn total_book_volume(&self) -> Decimal {
        self.total_volume()
    }

    /// Price distance from the best bid to the worst (lowest) bid.
    ///
    /// Returns `None` if there are fewer than 2 bid levels.
    pub fn price_range_bids(&self) -> Option<Decimal> {
        if self.bid_depth() < 2 {
            return None;
        }
        let best = self.best_bid_price()?;
        let worst = *self.bids.keys().next()?;
        Some(best - worst)
    }

    /// Spread as a percentage of the mid-price: `spread / mid × 100`.
    ///
    /// Returns `None` if either best bid or best ask is absent, or if the
    /// mid-price is zero.
    pub fn spread_pct(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let mid = self.mid_price()?;
        if mid.is_zero() {
            return None;
        }
        let spread = self.spread()?;
        (spread / mid * Decimal::from(100)).to_f64()
    }

    /// Returns `true` if the bid-ask spread is at or below `threshold`.
    ///
    /// Returns `false` when either side is empty (no spread to compare).
    pub fn is_tight_spread(&self, threshold: Decimal) -> bool {
        self.spread().map_or(false, |s| s <= threshold)
    }

    /// Total number of price levels across both sides of the book.
    ///
    /// Equivalent to `bid_depth() + ask_depth()`.
    pub fn total_depth(&self) -> usize {
        self.bid_depth() + self.ask_depth()
    }

    /// Total resting quantity across both sides of the book.
    ///
    /// Equivalent to `bid_volume_total() + ask_volume_total()`.
    pub fn total_volume(&self) -> Decimal {
        self.bid_volume_total() + self.ask_volume_total()
    }

    /// The symbol this order book tracks.
    pub fn symbol(&self) -> &str {
        &self.symbol
    }

    /// The sequence number of the most recently applied delta, if any.
    pub fn last_sequence(&self) -> Option<u64> {
        self.last_sequence
    }

    /// Best-bid quantity as a fraction of `(best_bid_qty + best_ask_qty)`.
    ///
    /// Values near `1.0` indicate the best bid has dominant size; near `0.0` the best ask
    /// dominates. Returns `None` when either side is empty or both quantities are zero.
    pub fn quote_imbalance(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid_qty = self.best_bid_qty()?;
        let ask_qty = self.best_ask_qty()?;
        let total = bid_qty + ask_qty;
        if total.is_zero() {
            return None;
        }
        (bid_qty / total).to_f64()
    }

    /// Returns `true` if a bid level exists at exactly `price`.
    pub fn contains_bid(&self, price: Decimal) -> bool {
        self.bids.contains_key(&price)
    }

    /// Returns `true` if an ask level exists at exactly `price`.
    pub fn contains_ask(&self, price: Decimal) -> bool {
        self.asks.contains_key(&price)
    }

    /// Returns the resting quantity at `price` on the bid side, or `None` if absent.
    pub fn volume_at_bid(&self, price: Decimal) -> Option<Decimal> {
        self.bids.get(&price).copied()
    }

    /// Returns the resting quantity at `price` on the ask side, or `None` if absent.
    pub fn volume_at_ask(&self, price: Decimal) -> Option<Decimal> {
        self.asks.get(&price).copied()
    }

    /// Number of resting price levels on the given side.
    ///
    /// Unified version of [`bid_depth`](Self::bid_depth) /
    /// [`ask_depth`](Self::ask_depth) for runtime dispatch by side.
    pub fn level_count(&self, side: BookSide) -> usize {
        match side {
            BookSide::Bid => self.bid_depth(),
            BookSide::Ask => self.ask_depth(),
        }
    }

    /// Total number of distinct price levels across both bid and ask sides.
    ///
    /// Alias for [`total_depth`](Self::total_depth).
    pub fn level_count_both_sides(&self) -> usize {
        self.total_depth()
    }

    /// The `n`th-best ask price (0 = best/lowest ask).
    ///
    /// Returns `None` if there are fewer than `n + 1` ask levels.
    pub fn ask_price_at_rank(&self, n: usize) -> Option<Decimal> {
        self.asks.keys().nth(n).copied()
    }

    /// The `n`th-best bid price (0 = best/highest bid).
    ///
    /// Returns `None` if there are fewer than `n + 1` bid levels.
    pub fn bid_price_at_rank(&self, n: usize) -> Option<Decimal> {
        self.bids.keys().nth_back(n).copied()
    }

    /// Number of distinct price levels per unit of price range on the given side.
    ///
    /// `quote_density = level_count / (max_price - min_price)`.
    /// Returns `None` if the side has fewer than 2 levels (range is zero).
    pub fn quote_density(&self, side: BookSide) -> Option<Decimal> {
        let map = match side {
            BookSide::Bid => &self.bids,
            BookSide::Ask => &self.asks,
        };
        if map.len() < 2 { return None; }
        let min_p = *map.keys().next()?;
        let max_p = *map.keys().next_back()?;
        let range = max_p - min_p;
        if range.is_zero() { return None; }
        Some(Decimal::from(map.len()) / range)
    }

    /// Ratio of total bid quantity to total ask quantity.
    ///
    /// Values > 1 indicate heavier buy-side resting volume; < 1 more sell-side.
    /// Returns `None` if the ask side has zero volume.
    /// Alias for [`bid_ask_ratio`](Self::bid_ask_ratio).
    pub fn bid_ask_qty_ratio(&self) -> Option<f64> {
        self.bid_ask_ratio()
    }

    /// Quantity resting at the best bid price.
    ///
    /// Returns `None` if the bid side is empty.
    /// Alias for [`best_bid_qty`](Self::best_bid_qty).
    pub fn top_bid_qty(&self) -> Option<Decimal> {
        self.best_bid_qty()
    }

    /// Quantity resting at the best ask price.
    ///
    /// Returns `None` if the ask side is empty.
    /// Alias for [`best_ask_qty`](Self::best_ask_qty).
    pub fn top_ask_qty(&self) -> Option<Decimal> {
        self.best_ask_qty()
    }

    /// Sum of quantity across the best `n` bid levels.
    ///
    /// Returns total bid quantity if `n >= bid_count`.
    /// Alias for [`cumulative_bid_volume`](Self::cumulative_bid_volume).
    pub fn cumulative_bid_qty(&self, n: usize) -> Decimal {
        self.cumulative_bid_volume(n)
    }

    /// Sum of quantity across the best `n` ask levels.
    ///
    /// Returns total ask quantity if `n >= ask_count`.
    /// Alias for [`cumulative_ask_volume`](Self::cumulative_ask_volume).
    pub fn cumulative_ask_qty(&self, n: usize) -> Decimal {
        self.cumulative_ask_volume(n)
    }

    /// Ratio of top-`n` bid quantity to top-`n` ask quantity.
    ///
    /// Values > 1 indicate more buy-side depth in the top `n` levels.
    /// Returns `None` if ask side has no volume in top `n` levels.
    pub fn ladder_balance(&self, n: usize) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let ask_qty = self.cumulative_ask_qty(n);
        if ask_qty.is_zero() { return None; }
        (self.cumulative_bid_qty(n) / ask_qty).to_f64()
    }

    /// Ratio of ask levels to bid levels: `ask_count / bid_count`.
    ///
    /// Values > 1 indicate more ask granularity; < 1 more bid granularity.
    /// Returns `None` if the bid side is empty.
    pub fn ask_bid_level_ratio(&self) -> Option<f64> {
        if self.bid_depth() == 0 { return None; }
        Some(self.ask_depth() as f64 / self.bid_depth() as f64)
    }

    /// Resting quantity at an exact price level on the given side.
    ///
    /// Returns `None` if there is no resting order at that price. This is a
    /// unified alternative to calling `volume_at_bid` / `volume_at_ask`
    /// separately when the side is determined at runtime.
    pub fn depth_at_price(&self, price: Decimal, side: BookSide) -> Option<Decimal> {
        match side {
            BookSide::Bid => self.bids.get(&price).copied(),
            BookSide::Ask => self.asks.get(&price).copied(),
        }
    }

    /// Ratio of total bid volume to total ask volume: `bid_volume_total / ask_volume_total`.
    ///
    /// Returns `None` if the ask side is empty (to avoid division by zero).
    /// Values > 1.0 indicate more buy-side depth; < 1.0 indicates more sell-side depth.
    pub fn bid_ask_ratio(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let ask = self.ask_volume_total();
        if ask.is_zero() {
            return None;
        }
        (self.bid_volume_total() / ask).to_f64()
    }

    /// All bid levels, sorted descending by price (highest first).
    ///
    /// Equivalent to `top_bids(usize::MAX)` but more expressive when you want
    /// the complete depth without specifying a level count.
    pub fn all_bids(&self) -> Vec<PriceLevel> {
        self.bids
            .iter()
            .rev()
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// All ask levels, sorted ascending by price (lowest first).
    ///
    /// Equivalent to `top_asks(usize::MAX)` but more expressive when you want
    /// the complete depth without specifying a level count.
    pub fn all_asks(&self) -> Vec<PriceLevel> {
        self.asks
            .iter()
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// Top N bids (descending by price).
    pub fn top_bids(&self, n: usize) -> Vec<PriceLevel> {
        self.bids
            .iter()
            .rev()
            .take(n)
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// Top N asks (ascending by price).
    pub fn top_asks(&self, n: usize) -> Vec<PriceLevel> {
        self.asks
            .iter()
            .take(n)
            .map(|(p, q)| PriceLevel::new(*p, *q))
            .collect()
    }

    /// Order-book imbalance at the best bid/ask: `(bid_qty - ask_qty) / (bid_qty + ask_qty)`.
    ///
    /// Returns a value in `[-1.0, 1.0]`:
    /// - `+1.0` means the entire resting quantity is on the bid side (maximum buy pressure).
    /// - `-1.0` means the entire resting quantity is on the ask side (maximum sell pressure).
    /// - `0.0` means perfectly balanced.
    ///
    /// Returns `None` if either side has no best level.
    pub fn imbalance(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid_qty = self.best_bid()?.quantity;
        let ask_qty = self.best_ask()?.quantity;
        let total = bid_qty + ask_qty;
        if total.is_zero() {
            return None;
        }
        let imb = (bid_qty - ask_qty) / total;
        imb.to_f64()
    }

    /// Order-book imbalance using the top `n` levels on each side.
    ///
    /// `(Σ bid_qty - Σ ask_qty) / (Σ bid_qty + Σ ask_qty)` in `[-1.0, 1.0]`.
    ///
    /// Returns `None` if either side has no levels or total volume is zero.
    pub fn bid_ask_imbalance(&self, n: usize) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid_vol = self.cumulative_bid_volume(n);
        let ask_vol = self.cumulative_ask_volume(n);
        if bid_vol.is_zero() || ask_vol.is_zero() {
            return None;
        }
        let total = bid_vol + ask_vol;
        ((bid_vol - ask_vol) / total).to_f64()
    }

    /// Volume-weighted average price (VWAP) of the top `n` resting levels on `side`.
    ///
    /// `Σ(price × qty) / Σ(qty)`. Returns `None` if the side has no levels or
    /// total volume is zero.
    pub fn vwap(&self, side: BookSide, n: usize) -> Option<Decimal> {
        let levels = match side {
            BookSide::Bid => self.top_bids(n),
            BookSide::Ask => self.top_asks(n),
        };
        let total_vol: Decimal = levels.iter().map(|l| l.quantity).sum();
        if total_vol.is_zero() {
            return None;
        }
        let price_vol_sum: Decimal = levels.iter().map(|l| l.price * l.quantity).sum();
        Some(price_vol_sum / total_vol)
    }

    /// Walk the book on `side` and return the average fill price to absorb `target_volume`.
    ///
    /// Sweeps levels from best to worst until `target_volume` is consumed, computing
    /// the VWAP of the executed portion. If the book has less total volume than
    /// `target_volume`, returns the VWAP of all available liquidity anyway.
    ///
    /// Returns `None` if the side is empty or `target_volume` is zero.
    pub fn price_at_volume(&self, side: BookSide, target_volume: Decimal) -> Option<Decimal> {
        if target_volume.is_zero() {
            return None;
        }
        let levels: Vec<(Decimal, Decimal)> = match side {
            BookSide::Bid => self.bids.iter().rev().map(|(p, q)| (*p, *q)).collect(),
            BookSide::Ask => self.asks.iter().map(|(p, q)| (*p, *q)).collect(),
        };
        if levels.is_empty() {
            return None;
        }
        let mut remaining = target_volume;
        let mut notional = Decimal::ZERO;
        let mut filled = Decimal::ZERO;
        for (price, qty) in &levels {
            if remaining.is_zero() {
                break;
            }
            let take = (*qty).min(remaining);
            notional += price * take;
            filled += take;
            remaining -= take;
        }
        if filled.is_zero() {
            return None;
        }
        Some(notional / filled)
    }

    /// Volume imbalance over the top-`n` price levels on each side: `(bid_vol - ask_vol) / (bid_vol + ask_vol)`.
    ///
    /// Returns a value in `[-1, 1]`: positive means more resting bid volume, negative means
    /// more resting ask volume. Returns `None` if both sides have zero volume or `n == 0`.
    ///
    /// Unlike [`imbalance`](Self::imbalance) which only uses the best bid/ask quantity,
    /// `depth_imbalance` aggregates across up to `n` levels providing a broader picture of
    /// order book pressure.
    pub fn depth_imbalance(&self, n: usize) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        if n == 0 {
            return None;
        }
        let bid_vol = self.cumulative_bid_volume(n);
        let ask_vol = self.cumulative_ask_volume(n);
        let total = bid_vol + ask_vol;
        if total.is_zero() {
            return None;
        }
        ((bid_vol - ask_vol) / total).to_f64()
    }

    /// Returns the top-`n` price levels for the given side, sorted best-first.
    ///
    /// For bids, levels are sorted descending (highest price first).
    /// For asks, levels are sorted ascending (lowest price first).
    /// If `n` exceeds the available levels, all levels are returned.
    pub fn levels(&self, side: BookSide, n: usize) -> Vec<PriceLevel> {
        match side {
            BookSide::Bid => self
                .bids
                .iter()
                .rev()
                .take(n)
                .map(|(p, q)| PriceLevel::new(*p, *q))
                .collect(),
            BookSide::Ask => self
                .asks
                .iter()
                .take(n)
                .map(|(p, q)| PriceLevel::new(*p, *q))
                .collect(),
        }
    }

    /// Returns the resting quantity at a specific bid price level, or `None` if absent.
    pub fn bid_volume_at_price(&self, price: Decimal) -> Option<Decimal> {
        self.bids.get(&price).copied()
    }

    /// Returns the resting quantity at a specific ask price level, or `None` if absent.
    pub fn ask_volume_at_price(&self, price: Decimal) -> Option<Decimal> {
        self.asks.get(&price).copied()
    }

    /// Return a full snapshot of all bid and ask levels.
    ///
    /// The returned tuple is `(bids, asks)`:
    /// - `bids` are sorted descending by price (highest first).
    /// - `asks` are sorted ascending by price (lowest first).
    ///
    /// Use this after receiving a [`StreamError::SequenceGap`] to rebuild the
    /// book from a fresh exchange snapshot: call [`reset`](Self::reset) with
    /// the snapshot levels, then resume applying deltas from the new sequence.
    pub fn snapshot(&self) -> (Vec<PriceLevel>, Vec<PriceLevel>) {
        (self.all_bids(), self.all_asks())
    }

    /// Returns the best bid price, or `None` if the bid side is empty.
    pub fn best_bid_price(&self) -> Option<Decimal> {
        self.best_bid().map(|l| l.price)
    }

    /// Returns the best ask price, or `None` if the ask side is empty.
    pub fn best_ask_price(&self) -> Option<Decimal> {
        self.best_ask().map(|l| l.price)
    }

    /// Returns `true` if the book is crossed: best bid ≥ best ask.
    ///
    /// A crossed book indicates an invalid state (stale snapshot or missed
    /// delta). Under normal operation this should always be `false`.
    pub fn is_crossed(&self) -> bool {
        self.best_bid_price().zip(self.best_ask_price()).map_or(false, |(b, a)| b >= a)
    }

    /// Returns `true` if there is at least one bid level in the book.
    pub fn has_bids(&self) -> bool {
        self.bid_depth() > 0
    }

    /// Returns `true` if there is at least one ask level in the book.
    pub fn has_asks(&self) -> bool {
        self.ask_depth() > 0
    }

    /// Price distance from best ask to worst ask (highest ask price - lowest ask price).
    ///
    /// Returns `None` if the ask side is empty.
    pub fn ask_price_range(&self) -> Option<Decimal> {
        let best = self.best_ask_price()?;
        let worst = *self.asks.keys().next_back()?;
        Some(worst - best)
    }

    /// Price distance from best bid to worst bid (highest bid price - lowest bid price).
    ///
    /// Returns `None` if the bid side is empty.
    pub fn bid_price_range(&self) -> Option<Decimal> {
        let best = self.best_bid_price()?;
        let worst = *self.bids.keys().next()?;
        Some(best - worst)
    }

    /// Spread as a fraction of the mid price: `spread / mid_price`.
    ///
    /// Returns `None` if the book has no bid or ask, or mid price is zero.
    pub fn mid_spread_ratio(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let spread = self.spread()?;
        let mid = self.mid_price()?;
        if mid.is_zero() {
            return None;
        }
        (spread / mid).to_f64()
    }

    /// Bid-ask volume imbalance: `(bid_vol - ask_vol) / (bid_vol + ask_vol)`.
    ///
    /// Returns a value in `[-1.0, 1.0]`. Positive = more bid volume; negative = more ask volume.
    /// Returns `None` if both sides are empty.
    pub fn volume_imbalance(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let bid = self.bid_volume_total();
        let ask = self.ask_volume_total();
        let total = bid + ask;
        if total.is_zero() {
            return None;
        }
        ((bid - ask) / total).to_f64()
    }

    fn check_crossed(&self) -> Result<(), StreamError> {
        if let (Some(bid), Some(ask)) = (self.best_bid(), self.best_ask()) {
            if bid.price >= ask.price {
                return Err(StreamError::BookCrossed {
                    symbol: self.symbol.clone(),
                    bid: bid.price,
                    ask: ask.price,
                });
            }
        }
        Ok(())
    }

    /// Estimated trading fee for a market order of `qty` on `side`, given a fee in basis points.
    ///
    /// `fee ≈ fill_price * qty * fee_bps / 10_000`. Returns fee in base currency.
    /// Returns `None` if the side is empty, qty ≤ 0, or not enough liquidity to fill.
    pub fn fee_estimate(&self, side: BookSide, qty: Decimal, fee_bps: Decimal) -> Option<Decimal> {
        if qty <= Decimal::ZERO { return None; }
        let best_price = match side {
            BookSide::Bid => self.best_bid_price()?,
            BookSide::Ask => self.best_ask_price()?,
        };
        let impact = self.price_impact(side, qty).unwrap_or(Decimal::ZERO);
        let fill_price = best_price + impact;
        Some(fill_price * qty * fee_bps / Decimal::from(10_000u32))
    }

    /// Spread expressed as number of ticks: `spread / tick_size`.
    ///
    /// Returns `None` if either side is empty or tick_size is zero.
    pub fn spread_ticks(&self, tick_size: Decimal) -> Option<Decimal> {
        if tick_size.is_zero() { return None; }
        let spread = self.spread()?;
        Some(spread / tick_size)
    }

    /// Spread expressed in basis points relative to mid-price: `(ask - bid) / mid × 10_000`.
    ///
    /// Returns `None` when either side is empty or mid-price is zero.
    pub fn spread_bps(&self) -> Option<f64> {
        use rust_decimal::prelude::ToPrimitive;
        let mid = self.mid_price()?;
        if mid.is_zero() {
            return None;
        }
        let spread = self.spread()?;
        (spread / mid * Decimal::from(10_000u32)).to_f64()
    }

    /// Cumulative volume within `pct` percent of the best price on a given side.
    ///
    /// For bids: sums quantity at all levels where `price >= best_bid * (1 - pct/100)`.
    /// For asks: sums quantity at all levels where `price <= best_ask * (1 + pct/100)`.
    ///
    /// Returns `None` if the side is empty or `pct` is negative.
    pub fn depth_at_pct(&self, side: BookSide, pct: f64) -> Option<Decimal> {
        use rust_decimal::prelude::FromPrimitive;
        if pct < 0.0 { return None; }
        let pct_dec = Decimal::from_f64(pct / 100.0)?;
        match side {
            BookSide::Bid => {
                let best = self.best_bid_price()?;
                let threshold = best * (Decimal::ONE - pct_dec);
                Some(self.bids.range(threshold..).map(|(_, q)| q).sum())
            }
            BookSide::Ask => {
                let best = self.best_ask_price()?;
                let threshold = best * (Decimal::ONE + pct_dec);
                Some(self.asks.range(..=threshold).map(|(_, q)| q).sum())
            }
        }
    }

    /// Microprice: volume-weighted mid using top-of-book quantities.
    ///
    /// `microprice = (ask_qty * best_bid + bid_qty * best_ask) / (bid_qty + ask_qty)`
    ///
    /// More accurate than simple mid when the order book is imbalanced.
    /// Returns `None` if either side is empty or total quantity is zero.
    pub fn microprice(&self) -> Option<Decimal> {
        let bid = self.best_bid()?;
        let ask = self.best_ask()?;
        let total_qty = bid.quantity + ask.quantity;
        if total_qty.is_zero() { return None; }
        Some((ask.quantity * bid.price + bid.quantity * ask.price) / total_qty)
    }

    /// Returns the top `n` price levels on a given side as `(price, quantity)` pairs.
    ///
    /// Bid levels are returned in descending price order (best bid first).
    /// Ask levels are returned in ascending price order (best ask first).
    /// Returns fewer than `n` entries if the side has fewer levels.
    pub fn best_n_levels(&self, side: BookSide, n: usize) -> Vec<(Decimal, Decimal)> {
        match side {
            BookSide::Bid => self.bids.iter().rev().take(n)
                .map(|(&p, &q)| (p, q)).collect(),
            BookSide::Ask => self.asks.iter().take(n)
                .map(|(&p, &q)| (p, q)).collect(),
        }
    }

    /// Estimated price impact of a market order of `qty` on the given side.
    ///
    /// Walks the book, consuming levels until `qty` is filled. Returns the
    /// weighted average fill price minus the best price (positive = adverse).
    /// Returns `None` if the side is empty or `qty` is zero/negative.
    pub fn price_impact(&self, side: BookSide, qty: Decimal) -> Option<Decimal> {
        if qty <= Decimal::ZERO { return None; }
        let best_price = match side {
            BookSide::Bid => self.best_bid_price()?,
            BookSide::Ask => self.best_ask_price()?,
        };
        let mut remaining = qty;
        let mut cost = Decimal::ZERO;
        let levels: Box<dyn Iterator<Item = (&Decimal, &Decimal)>> = match side {
            BookSide::Bid => Box::new(self.bids.iter().rev()),
            BookSide::Ask => Box::new(self.asks.iter()),
        };
        for (&price, &level_qty) in levels {
            if remaining <= Decimal::ZERO { break; }
            let filled = remaining.min(level_qty);
            cost += price * filled;
            remaining -= filled;
        }
        if remaining > Decimal::ZERO { return None; } // not enough liquidity
        let avg_fill = cost / qty;
        Some((avg_fill - best_price).abs())
    }

    /// Total notional value (price × quantity) at a specific price level on a given side.
    ///
    /// Returns `None` if no level exists at `price`.
    pub fn total_value_at_level(&self, side: BookSide, price: Decimal) -> Option<Decimal> {
        match side {
            BookSide::Bid => self.bids.get(&price).map(|&q| price * q),
            BookSide::Ask => self.asks.get(&price).map(|&q| price * q),
        }
    }

    /// Estimated volume-weighted average execution price for a market buy of `quantity`.
    ///
    /// Walks up the ask side. Returns `None` if insufficient liquidity.
    pub fn price_impact_buy(&self, quantity: Decimal) -> Option<Decimal> {
        if quantity <= Decimal::ZERO {
            return None;
        }
        let mut remaining = quantity;
        let mut cost = Decimal::ZERO;
        for (&price, &qty) in &self.asks {
            if remaining.is_zero() { break; }
            let fill = remaining.min(qty);
            cost += fill * price;
            remaining -= fill;
        }
        if !remaining.is_zero() { return None; }
        Some(cost / quantity)
    }

    /// Estimated volume-weighted average execution price for a market sell of `quantity`.
    ///
    /// Walks down the bid side. Returns `None` if insufficient liquidity.
    pub fn price_impact_sell(&self, quantity: Decimal) -> Option<Decimal> {
        if quantity <= Decimal::ZERO {
            return None;
        }
        let mut remaining = quantity;
        let mut proceeds = Decimal::ZERO;
        for (&price, &qty) in self.bids.iter().rev() {
            if remaining.is_zero() { break; }
            let fill = remaining.min(qty);
            proceeds += fill * price;
            remaining -= fill;
        }
        if !remaining.is_zero() { return None; }
        Some(proceeds / quantity)
    }

    /// Number of distinct price levels on the ask side.
    #[deprecated(note = "use ask_depth() instead")]
    pub fn ask_level_count(&self) -> usize {
        self.ask_depth()
    }

    /// Number of distinct price levels on the bid side.
    #[deprecated(note = "use bid_depth() instead")]
    pub fn bid_level_count(&self) -> usize {
        self.bid_depth()
    }

    /// Cumulative ask volume at levels within `price_range` of the best ask.
    ///
    /// Sums all ask quantities where `price <= best_ask + price_range`.
    /// Returns `Decimal::ZERO` if the ask side is empty.
    pub fn ask_volume_within(&self, price_range: Decimal) -> Decimal {
        self.best_ask().map_or(Decimal::ZERO, |best| {
            self.asks.range(..=(best.price + price_range)).map(|(_, &q)| q).sum()
        })
    }

    /// Cumulative bid volume at levels within `price_range` of the best bid.
    ///
    /// Sums all bid quantities where `price >= best_bid - price_range`.
    /// Returns `Decimal::ZERO` if the bid side is empty.
    pub fn bid_volume_within(&self, price_range: Decimal) -> Decimal {
        self.best_bid().map_or(Decimal::ZERO, |best| {
            self.bids.range((best.price - price_range)..).map(|(_, &q)| q).sum()
        })
    }

    /// Total ask quantity at price levels strictly above `price`.
    pub fn ask_volume_above(&self, price: Decimal) -> Decimal {
        use std::ops::Bound::Excluded;
        self.asks
            .range((Excluded(price), std::ops::Bound::Unbounded))
            .map(|(_, &q)| q)
            .sum()
    }

    /// Total bid quantity at price levels strictly below `price`.
    pub fn bid_volume_below(&self, price: Decimal) -> Decimal {
        use std::ops::Bound::Unbounded;
        use std::ops::Bound::Excluded;
        self.bids
            .range((Unbounded, Excluded(price)))
            .map(|(_, &q)| q)
            .sum()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    fn book(symbol: &str) -> OrderBook {
        OrderBook::new(symbol)
    }

    fn delta(symbol: &str, side: BookSide, price: Decimal, qty: Decimal) -> BookDelta {
        BookDelta::new(symbol, side, price, qty)
    }

    #[test]
    fn test_order_book_apply_bid_level() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        assert_eq!(b.best_bid().unwrap().price, dec!(50000));
    }

    #[test]
    fn test_order_book_apply_ask_level() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2)))
            .unwrap();
        assert_eq!(b.best_ask().unwrap().price, dec!(50100));
    }

    #[test]
    fn test_order_book_remove_level_with_zero_qty() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(0)))
            .unwrap();
        assert!(b.best_bid().is_none());
    }

    #[test]
    fn test_order_book_best_bid_is_highest() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(2)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(3)))
            .unwrap();
        assert_eq!(b.best_bid().unwrap().price, dec!(50000));
    }

    #[test]
    fn test_order_book_best_ask_is_lowest() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50300), dec!(3)))
            .unwrap();
        assert_eq!(b.best_ask().unwrap().price, dec!(50100));
    }

    #[test]
    fn test_order_book_mid_price() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)))
            .unwrap();
        assert_eq!(b.mid_price().unwrap(), dec!(50050));
    }

    #[test]
    fn test_order_book_spread() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)))
            .unwrap();
        assert_eq!(b.spread().unwrap(), dec!(100));
    }

    #[test]
    fn test_order_book_crossed_returns_error() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50000), dec!(1)))
            .unwrap();
        let result = b.apply(delta("BTC-USD", BookSide::Bid, dec!(50001), dec!(1)));
        assert!(matches!(result, Err(StreamError::BookCrossed { .. })));
    }

    #[test]
    fn test_order_book_wrong_symbol_delta_rejected() {
        let mut b = book("BTC-USD");
        let result = b.apply(delta("ETH-USD", BookSide::Bid, dec!(3000), dec!(1)));
        assert!(matches!(
            result,
            Err(StreamError::BookReconstructionFailed { .. })
        ));
    }

    #[test]
    fn test_order_book_reset_clears_and_reloads() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49000), dec!(5)))
            .unwrap();
        b.reset(
            vec![PriceLevel::new(dec!(50000), dec!(1))],
            vec![PriceLevel::new(dec!(50100), dec!(1))],
        )
        .unwrap();
        assert_eq!(b.bid_depth(), 1);
        assert_eq!(b.best_bid().unwrap().price, dec!(50000));
    }

    #[test]
    fn test_order_book_reset_ignores_zero_qty_levels() {
        let mut b = book("BTC-USD");
        b.reset(
            vec![
                PriceLevel::new(dec!(50000), dec!(1)),
                PriceLevel::new(dec!(49900), dec!(0)),
            ],
            vec![PriceLevel::new(dec!(50100), dec!(1))],
        )
        .unwrap();
        assert_eq!(b.bid_depth(), 1);
    }

    #[test]
    fn test_order_book_reset_clears_sequence() {
        let mut b = book("BTC-USD");
        b.apply(
            delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1)).with_sequence(5),
        )
        .unwrap();
        assert_eq!(b.last_sequence(), Some(5));
        b.reset(
            vec![PriceLevel::new(dec!(50000), dec!(1))],
            vec![PriceLevel::new(dec!(50100), dec!(1))],
        )
        .unwrap();
        assert_eq!(b.last_sequence(), None);
    }

    #[test]
    fn test_order_book_depth_counts() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)))
            .unwrap();
        assert_eq!(b.bid_depth(), 2);
        assert_eq!(b.ask_depth(), 1);
    }

    #[test]
    fn test_order_book_top_bids_descending() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(3)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(2)))
            .unwrap();
        let top = b.top_bids(2);
        assert_eq!(top[0].price, dec!(50000));
        assert_eq!(top[1].price, dec!(49900));
    }

    #[test]
    fn test_order_book_top_asks_ascending() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50300), dec!(3)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(2)))
            .unwrap();
        let top = b.top_asks(2);
        assert_eq!(top[0].price, dec!(50100));
        assert_eq!(top[1].price, dec!(50200));
    }

    #[test]
    fn test_book_delta_with_sequence() {
        let d = BookDelta::new("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)).with_sequence(42);
        assert_eq!(d.sequence, Some(42));
    }

    #[test]
    fn test_order_book_sequence_tracking() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)).with_sequence(7))
            .unwrap();
        assert_eq!(b.last_sequence(), Some(7));
    }

    #[test]
    fn test_order_book_sequence_gap_detected() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1)).with_sequence(1))
            .unwrap();
        // Skip sequence 2, send 3 → gap
        let result =
            b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)).with_sequence(3));
        assert!(matches!(
            result,
            Err(StreamError::SequenceGap { expected: 2, got: 3, .. })
        ));
    }

    #[test]
    fn test_order_book_sequential_deltas_accepted() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1)).with_sequence(1))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1)).with_sequence(2))
            .unwrap();
        assert_eq!(b.last_sequence(), Some(2));
    }

    #[test]
    fn test_order_book_mid_price_empty_returns_none() {
        let b = book("BTC-USD");
        assert!(b.mid_price().is_none());
    }

    #[test]
    fn test_price_level_new() {
        let lvl = PriceLevel::new(dec!(100), dec!(5));
        assert_eq!(lvl.price, dec!(100));
        assert_eq!(lvl.quantity, dec!(5));
    }

    #[test]
    fn test_contains_bid_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        assert!(b.contains_bid(dec!(50000)));
        assert!(!b.contains_bid(dec!(49999)));
    }

    #[test]
    fn test_contains_ask_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2)))
            .unwrap();
        assert!(b.contains_ask(dec!(50100)));
        assert!(!b.contains_ask(dec!(50200)));
    }

    #[test]
    fn test_contains_bid_removed_after_zero_qty() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(0)))
            .unwrap();
        assert!(!b.contains_bid(dec!(50000)));
    }

    #[test]
    fn test_book_delta_serde_roundtrip() {
        let d = BookDelta::new("BTC-USD", BookSide::Bid, dec!(50000), dec!(1))
            .with_sequence(42);
        let json = serde_json::to_string(&d).unwrap();
        let d2: BookDelta = serde_json::from_str(&json).unwrap();
        assert_eq!(d2.symbol, "BTC-USD");
        assert_eq!(d2.price, dec!(50000));
        assert_eq!(d2.sequence, Some(42));
    }

    #[test]
    fn test_volume_at_bid_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(3)))
            .unwrap();
        assert_eq!(b.volume_at_bid(dec!(50000)), Some(dec!(3)));
        assert_eq!(b.volume_at_bid(dec!(49999)), None);
    }

    #[test]
    fn test_volume_at_ask_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(5)))
            .unwrap();
        assert_eq!(b.volume_at_ask(dec!(50100)), Some(dec!(5)));
        assert_eq!(b.volume_at_ask(dec!(50200)), None);
    }

    #[test]
    fn test_book_delta_display_with_sequence() {
        let d = BookDelta::new("BTC-USD", BookSide::Bid, dec!(50000), dec!(1))
            .with_sequence(42);
        let s = d.to_string();
        assert!(s.contains("BTC-USD"));
        assert!(s.contains("Bid"));
        assert!(s.contains("seq=42"));
    }

    #[test]
    fn test_book_delta_display_without_sequence() {
        let d = BookDelta::new("ETH-USD", BookSide::Ask, dec!(3000), dec!(2));
        let s = d.to_string();
        assert!(s.contains("ETH-USD"));
        assert!(s.contains("Ask"));
        assert!(!s.contains("seq="));
    }

    #[test]
    fn test_book_delta_is_delete_zero_qty() {
        let d = BookDelta::new("BTC-USD", BookSide::Bid, dec!(50000), dec!(0));
        assert!(d.is_delete());
    }

    #[test]
    fn test_book_delta_is_delete_nonzero_qty() {
        let d = BookDelta::new("BTC-USD", BookSide::Bid, dec!(50000), dec!(1));
        assert!(!d.is_delete());
    }

    #[test]
    fn test_snapshot_bids_descending_asks_ascending() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(2)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(1)))
            .unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(3)))
            .unwrap();
        let (bids, asks) = b.snapshot();
        assert_eq!(bids[0].price, dec!(50000));
        assert_eq!(bids[1].price, dec!(49800));
        assert_eq!(asks[0].price, dec!(50100));
        assert_eq!(asks[1].price, dec!(50200));
    }

    // ── bid_ask_imbalance ─────────────────────────────────────────────────────

    #[test]
    fn test_bid_ask_imbalance_balanced() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1))).unwrap();
        let imb = b.bid_ask_imbalance(1).unwrap();
        assert!((imb).abs() < 1e-9, "equal qty → ~0");
    }

    #[test]
    fn test_bid_ask_imbalance_full_bid_pressure() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(10))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(0))).unwrap();
        // ask qty = 0 → None
        assert!(b.bid_ask_imbalance(1).is_none());
    }

    #[test]
    fn test_bid_ask_imbalance_two_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(2))).unwrap();
        // bid_vol = 4, ask_vol = 4 → imbalance = 0
        let imb = b.bid_ask_imbalance(2).unwrap();
        assert!((imb).abs() < 1e-9);
    }

    // ── vwap ──────────────────────────────────────────────────────────────────

    #[test]
    fn test_vwap_single_level_equals_price() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(5))).unwrap();
        assert_eq!(b.vwap(BookSide::Ask, 1), Some(dec!(50100)));
    }

    #[test]
    fn test_vwap_two_equal_qty_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(1))).unwrap();
        // vwap = (50000 + 49800) / 2 = 49900
        assert_eq!(b.vwap(BookSide::Bid, 2), Some(dec!(49900)));
    }

    #[test]
    fn test_vwap_empty_side_returns_none() {
        let b = book("BTC-USD");
        assert!(b.vwap(BookSide::Ask, 5).is_none());
    }

    // ── OrderBook::depth_at_price / bid_ask_ratio ─────────────────────────────

    #[test]
    fn test_depth_at_price_bid_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(3))).unwrap();
        assert_eq!(b.depth_at_price(dec!(50000), BookSide::Bid), Some(dec!(3)));
    }

    #[test]
    fn test_depth_at_price_ask_present() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2))).unwrap();
        assert_eq!(b.depth_at_price(dec!(50100), BookSide::Ask), Some(dec!(2)));
    }

    #[test]
    fn test_depth_at_price_absent_returns_none() {
        let b = book("BTC-USD");
        assert!(b.depth_at_price(dec!(99999), BookSide::Bid).is_none());
        assert!(b.depth_at_price(dec!(99999), BookSide::Ask).is_none());
    }

    #[test]
    fn test_bid_ask_ratio_equal_sides() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(5))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(5))).unwrap();
        let ratio = b.bid_ask_ratio().unwrap();
        assert!((ratio - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_bid_ask_ratio_more_bids() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(10))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(5))).unwrap();
        let ratio = b.bid_ask_ratio().unwrap();
        assert!((ratio - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_bid_ask_ratio_no_asks_returns_none() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(5))).unwrap();
        assert!(b.bid_ask_ratio().is_none());
    }

    // ── OrderBook::all_bids / all_asks ────────────────────────────────────────

    #[test]
    fn test_all_bids_sorted_descending() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(3))).unwrap();
        let bids = b.all_bids();
        assert_eq!(bids.len(), 3);
        assert_eq!(bids[0].price, dec!(50000));
        assert_eq!(bids[1].price, dec!(49900));
        assert_eq!(bids[2].price, dec!(49800));
    }

    #[test]
    fn test_all_asks_sorted_ascending() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50300), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(3))).unwrap();
        let asks = b.all_asks();
        assert_eq!(asks.len(), 3);
        assert_eq!(asks[0].price, dec!(50100));
        assert_eq!(asks[1].price, dec!(50200));
        assert_eq!(asks[2].price, dec!(50300));
    }

    #[test]
    fn test_all_bids_empty_returns_empty() {
        let b = book("BTC-USD");
        assert!(b.all_bids().is_empty());
    }

    // ── spread_pct / total_depth / total_volume ──────────────────────────────

    #[test]
    fn test_spread_pct_basic() {
        // bid=100, ask=101 → spread=1, mid=100.5 → pct ≈ 0.995%
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        let pct = b.spread_pct().unwrap();
        assert!((pct - 100.0 / 100.5).abs() < 1e-9, "got {pct}");
    }

    #[test]
    fn test_spread_pct_empty_book_returns_none() {
        let b = book("X");
        assert!(b.spread_pct().is_none());
    }

    #[test]
    fn test_total_depth_counts_both_sides() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert_eq!(b.total_depth(), 3);
    }

    #[test]
    fn test_total_depth_empty_is_zero() {
        let b = book("X");
        assert_eq!(b.total_depth(), 0);
    }

    #[test]
    fn test_total_volume_sums_both_sides() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(3))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        assert_eq!(b.total_volume(), dec!(8));
    }

    #[test]
    fn test_total_volume_empty_is_zero() {
        let b = book("X");
        assert_eq!(b.total_volume(), dec!(0));
    }

    // ── OrderBook::level_count ────────────────────────────────────────────────

    #[test]
    fn test_level_count_empty() {
        let b = book("BTC-USD");
        assert_eq!(b.level_count(BookSide::Bid), 0);
        assert_eq!(b.level_count(BookSide::Ask), 0);
    }

    #[test]
    fn test_level_count_matches_depth_methods() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        assert_eq!(b.level_count(BookSide::Bid), b.bid_depth());
        assert_eq!(b.level_count(BookSide::Ask), b.ask_depth());
    }

    // ── PriceLevel::notional ─────────────────────────────────────────────────

    #[test]
    fn test_price_level_notional() {
        let level = PriceLevel::new(dec!(50000), dec!(2));
        assert_eq!(level.notional(), dec!(100000));
    }

    #[test]
    fn test_price_level_notional_zero_qty() {
        let level = PriceLevel::new(dec!(100), dec!(0));
        assert_eq!(level.notional(), dec!(0));
    }

    // ── OrderBook::weighted_mid_price ────────────────────────────────────────

    #[test]
    fn test_weighted_mid_price_equal_qtys_is_arithmetic_mid() {
        // bid=100 qty=1, ask=102 qty=1 → wmid = (100*1 + 102*1) / 2 = 101
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        assert_eq!(b.weighted_mid_price().unwrap(), dec!(101));
    }

    #[test]
    fn test_weighted_mid_price_skews_toward_larger_qty() {
        // bid=100 qty=1, ask=102 qty=3 → wmid = (100*3 + 102*1) / 4 = 402/4 = 100.5
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(3))).unwrap();
        assert_eq!(b.weighted_mid_price().unwrap(), dec!(100.5));
    }

    #[test]
    fn test_weighted_mid_price_empty_returns_none() {
        let b = book("X");
        assert!(b.weighted_mid_price().is_none());
    }

    // ── OrderBook::is_empty ───────────────────────────────────────────────────

    #[test]
    fn test_is_empty_new_book() {
        let b = book("BTC-USD");
        assert!(b.is_empty());
    }

    #[test]
    fn test_is_empty_false_with_bid() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(!b.is_empty());
    }

    #[test]
    fn test_is_empty_false_with_ask() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(!b.is_empty());
    }

    #[test]
    fn test_is_empty_true_after_removing_all_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(0))).unwrap(); // remove
        assert!(b.is_empty());
    }

    // ── OrderBook::clear ──────────────────────────────────────────────────────

    #[test]
    fn test_clear_empty_book_is_noop() {
        let mut b = book("BTC-USD");
        b.clear();
        assert!(b.is_empty());
    }

    #[test]
    fn test_clear_removes_all_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        b.clear();
        assert!(b.is_empty());
    }

    #[test]
    fn test_clear_allows_fresh_apply_after() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.clear();
        // After clear, a new bid should work without sequence issues
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(5))).unwrap();
        assert_eq!(b.bid_depth(), 1);
    }

    // ── OrderBook::total_notional ─────────────────────────────────────────────

    #[test]
    fn test_total_notional_bid_side() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(50000), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(3))).unwrap();
        // 50000*2 + 49900*3 = 100000 + 149700 = 249700
        assert_eq!(b.total_notional(BookSide::Bid), dec!(249700));
    }

    #[test]
    fn test_total_notional_ask_side() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(2))).unwrap();
        // 50100*1 + 50200*2 = 50100 + 100400 = 150500
        assert_eq!(b.total_notional(BookSide::Ask), dec!(150500));
    }

    #[test]
    fn test_total_notional_empty_side_is_zero() {
        let b = book("BTC-USD");
        assert_eq!(b.total_notional(BookSide::Bid), dec!(0));
        assert_eq!(b.total_notional(BookSide::Ask), dec!(0));
    }

    #[test]
    fn test_cumulative_bid_volume_top_two() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(98), dec!(2))).unwrap();
        // best 2 bids: 100 (qty=5), 99 (qty=3)
        assert_eq!(b.cumulative_bid_volume(2), dec!(8));
    }

    #[test]
    fn test_cumulative_ask_volume_top_two() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(4))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(6))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(103), dec!(1))).unwrap();
        // best 2 asks: 101 (qty=4), 102 (qty=6)
        assert_eq!(b.cumulative_ask_volume(2), dec!(10));
    }

    #[test]
    fn test_cumulative_volume_empty_returns_zero() {
        let b = book("BTC-USD");
        assert_eq!(b.cumulative_bid_volume(5), dec!(0));
        assert_eq!(b.cumulative_ask_volume(5), dec!(0));
    }

    #[test]
    fn test_top_n_bids_best_first() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(98), dec!(3))).unwrap();
        let top2 = b.top_n_bids(2);
        assert_eq!(top2.len(), 2);
        assert_eq!(top2[0].price, dec!(100)); // best bid first
        assert_eq!(top2[1].price, dec!(99));
    }

    #[test]
    fn test_top_n_asks_best_first() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(103), dec!(3))).unwrap();
        let top2 = b.top_n_asks(2);
        assert_eq!(top2.len(), 2);
        assert_eq!(top2[0].price, dec!(101)); // best ask first
        assert_eq!(top2[1].price, dec!(102));
    }

    #[test]
    fn test_depth_ratio_balanced_book() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        let ratio = b.depth_ratio(1).unwrap();
        assert!((ratio - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_depth_ratio_empty_asks_returns_none() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        assert!(b.depth_ratio(1).is_none());
    }

    // ── OrderBook::is_one_sided ───────────────────────────────────────────────

    #[test]
    fn test_is_one_sided_bids_only() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(b.is_one_sided());
    }

    #[test]
    fn test_is_one_sided_asks_only() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(b.is_one_sided());
    }

    #[test]
    fn test_is_one_sided_false_with_both_sides() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(!b.is_one_sided());
    }

    #[test]
    fn test_is_one_sided_false_for_empty_book() {
        let b = book("BTC-USD");
        assert!(!b.is_one_sided());
    }

    // ── OrderBook::bid_ask_spread_bps ─────────────────────────────────────────

    #[test]
    fn test_bid_ask_spread_bps_known_value() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // spread=1, mid=100.5, bps = 1/100.5*10000 ≈ 99.5
        let bps = b.bid_ask_spread_bps().unwrap();
        assert!((bps - 1.0 / 100.5 * 10_000.0).abs() < 0.01);
    }

    #[test]
    fn test_bid_ask_spread_bps_none_when_one_sided() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(b.bid_ask_spread_bps().is_none());
    }

    #[test]
    fn test_bid_ask_spread_bps_none_for_empty_book() {
        let b = book("BTC-USD");
        assert!(b.bid_ask_spread_bps().is_none());
    }

    // --- ask_wall / bid_wall ---

    #[test]
    fn test_ask_wall_returns_cheapest_ask_above_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50200), dec!(10))).unwrap();
        // ask_wall(5) should find 50200 (qty=10 >= 5); 50100 has qty=2 < 5
        let wall = b.ask_wall(dec!(5)).unwrap();
        assert_eq!(wall.price, dec!(50200));
        assert_eq!(wall.quantity, dec!(10));
    }

    #[test]
    fn test_ask_wall_none_when_no_level_meets_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(50100), dec!(1))).unwrap();
        assert!(b.ask_wall(dec!(5)).is_none());
    }

    #[test]
    fn test_bid_wall_returns_highest_bid_above_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(10))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49800), dec!(2))).unwrap();
        // bid_wall(5) scans from best (49900) → qty=10 >= 5, so returns 49900
        let wall = b.bid_wall(dec!(5)).unwrap();
        assert_eq!(wall.price, dec!(49900));
        assert_eq!(wall.quantity, dec!(10));
    }

    #[test]
    fn test_bid_wall_none_when_no_level_meets_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(49900), dec!(1))).unwrap();
        assert!(b.bid_wall(dec!(5)).is_none());
    }

    // ── OrderBook::level_count_imbalance ──────────────────────────────────────

    #[test]
    fn test_level_count_imbalance_balanced_sides() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // 1 bid, 1 ask → (1-1)/(1+1) = 0.0
        assert_eq!(b.level_count_imbalance(), Some(0.0));
    }

    #[test]
    fn test_level_count_imbalance_bids_only() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(98), dec!(1))).unwrap();
        // 2 bids, 0 asks → (2-0)/(2+0) = 1.0
        assert_eq!(b.level_count_imbalance(), Some(1.0));
    }

    #[test]
    fn test_level_count_imbalance_none_for_empty_book() {
        let b = book("BTC-USD");
        assert!(b.level_count_imbalance().is_none());
    }

    // ── OrderBook::total_bid_volume / total_ask_volume ────────────────────────

    #[test]
    fn test_total_bid_volume_sums_all_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(98), dec!(2))).unwrap();
        assert_eq!(b.total_bid_volume(), dec!(5));
    }

    #[test]
    fn test_total_ask_volume_sums_all_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(4))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        assert_eq!(b.total_ask_volume(), dec!(5));
    }

    #[test]
    fn test_total_bid_volume_zero_for_empty_side() {
        let b = book("BTC-USD");
        assert_eq!(b.total_bid_volume(), dec!(0));
    }

    // --- bid_levels_above / ask_levels_below ---

    #[test]
    fn test_bid_levels_above_counts_strictly_above() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(101), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(102), dec!(1))).unwrap();
        // levels above 100: 101 and 102 → 2
        assert_eq!(b.bid_levels_above(dec!(100)), 2);
    }

    #[test]
    fn test_bid_levels_above_zero_when_none_above() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        assert_eq!(b.bid_levels_above(dec!(100)), 0);
    }

    #[test]
    fn test_ask_levels_below_counts_strictly_below() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        // levels below 102: 100 and 101 → 2
        assert_eq!(b.ask_levels_below(dec!(102)), 2);
    }

    #[test]
    fn test_ask_levels_below_zero_for_empty_book() {
        let b = book("BTC-USD");
        assert_eq!(b.ask_levels_below(dec!(100)), 0);
    }

    // --- bid_ask_volume_ratio / top_n_bid_volume ---

    #[test]
    fn test_bid_ask_volume_ratio_returns_correct_ratio() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // 3 / 1 = 3.0
        let ratio = b.bid_ask_volume_ratio().unwrap();
        assert!((ratio - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_bid_ask_volume_ratio_none_when_ask_empty() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(b.bid_ask_volume_ratio().is_none());
    }

    #[test]
    fn test_bid_ask_volume_ratio_none_when_bid_empty() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(b.bid_ask_volume_ratio().is_none());
    }

    #[test]
    fn test_top_n_bid_volume_sums_top_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap(); // worst
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(101), dec!(2))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(102), dec!(3))).unwrap(); // best
        // top 2: 102 (3) + 101 (2) = 5
        assert_eq!(b.top_n_bid_volume(2), dec!(5));
    }

    #[test]
    fn test_top_n_bid_volume_all_when_n_exceeds_levels() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(101), dec!(2))).unwrap();
        // n=5 but only 2 levels → total = 3
        assert_eq!(b.top_n_bid_volume(5), dec!(3));
    }

    #[test]
    fn test_top_n_bid_volume_zero_for_empty_book() {
        let b = book("BTC-USD");
        assert_eq!(b.top_n_bid_volume(3), dec!(0));
    }

    // --- imbalance_ratio / top_n_ask_volume ---

    #[test]
    fn test_imbalance_ratio_positive_when_more_bids() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // (3 - 1) / (3 + 1) = 0.5
        let ratio = b.imbalance_ratio().unwrap();
        assert!((ratio - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_imbalance_ratio_negative_when_more_asks() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(3))).unwrap();
        // (1 - 3) / (1 + 3) = -0.5
        let ratio = b.imbalance_ratio().unwrap();
        assert!((ratio - (-0.5)).abs() < 1e-10);
    }

    #[test]
    fn test_imbalance_ratio_none_when_both_empty() {
        let b = book("BTC-USD");
        assert!(b.imbalance_ratio().is_none());
    }

    #[test]
    fn test_top_n_ask_volume_sums_lowest_asks() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(100), dec!(2))).unwrap(); // best ask
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(5))).unwrap(); // worst
        // top 2: 100 (2) + 101 (3) = 5
        assert_eq!(b.top_n_ask_volume(2), dec!(5));
    }

    #[test]
    fn test_top_n_ask_volume_zero_for_empty_book() {
        let b = book("BTC-USD");
        assert_eq!(b.top_n_ask_volume(3), dec!(0));
    }

    // --- has_ask_at / bid_ask_depth ---

    #[test]
    fn test_has_ask_at_true_when_ask_exists() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        assert!(b.has_ask_at(dec!(101)));
    }

    #[test]
    fn test_has_ask_at_false_when_no_ask_at_price() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        assert!(!b.has_ask_at(dec!(101)));
    }

    #[test]
    fn test_bid_ask_depth_correct_counts() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert_eq!(b.bid_ask_depth(), (2, 1));
    }

    #[test]
    fn test_bid_ask_depth_zero_for_empty_book() {
        let b = book("BTC-USD");
        assert_eq!(b.bid_ask_depth(), (0, 0));
    }

    // --- OrderBook::best_bid_qty / best_ask_qty ---
    #[test]
    fn test_best_bid_qty_returns_top_bid_quantity() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(5))).unwrap();
        // best bid = 100 with qty=3
        assert_eq!(b.best_bid_qty(), Some(dec!(3)));
    }

    #[test]
    fn test_best_ask_qty_returns_top_ask_quantity() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(7))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(102), dec!(2))).unwrap();
        // best ask = 101 with qty=7
        assert_eq!(b.best_ask_qty(), Some(dec!(7)));
    }

    #[test]
    fn test_best_bid_qty_none_when_no_bids() {
        let b = book("BTC-USD");
        assert!(b.best_bid_qty().is_none());
    }

    #[test]
    fn test_best_ask_qty_none_when_no_asks() {
        let b = book("BTC-USD");
        assert!(b.best_ask_qty().is_none());
    }

    // --- OrderBook::total_book_volume ---
    #[test]
    fn test_total_book_volume_sum_of_bids_and_asks() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(3))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        assert_eq!(b.total_book_volume(), dec!(5));
    }

    #[test]
    fn test_total_book_volume_zero_on_empty_book() {
        let b = book("BTC-USD");
        assert_eq!(b.total_book_volume(), dec!(0));
    }

    // --- OrderBook::price_range_bids ---
    #[test]
    fn test_price_range_bids_correct_range() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(97), dec!(1))).unwrap();
        // best=100, worst=97 → range=3
        assert_eq!(b.price_range_bids(), Some(dec!(3)));
    }

    #[test]
    fn test_price_range_bids_none_with_single_bid() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(b.price_range_bids().is_none());
    }

    // ── OrderBook::is_tight_spread ────────────────────────────────────────────

    #[test]
    fn test_is_tight_spread_true_when_spread_at_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // spread = 1, threshold = 1 → tight
        assert!(b.is_tight_spread(dec!(1)));
    }

    #[test]
    fn test_is_tight_spread_false_when_spread_above_threshold() {
        let mut b = book("BTC-USD");
        b.apply(delta("BTC-USD", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        b.apply(delta("BTC-USD", BookSide::Ask, dec!(103), dec!(1))).unwrap();
        // spread = 3, threshold = 1 → not tight
        assert!(!b.is_tight_spread(dec!(1)));
    }

    #[test]
    fn test_is_tight_spread_false_when_empty() {
        let b = book("BTC-USD");
        assert!(!b.is_tight_spread(dec!(10)));
    }

    // ── OrderBook::best_bid_price / best_ask_price ────────────────────────────

    #[test]
    fn test_best_bid_price_returns_price() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(5))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(3))).unwrap();
        assert_eq!(b.best_bid_price(), Some(dec!(99)));
    }

    #[test]
    fn test_best_ask_price_returns_price() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(3))).unwrap();
        assert_eq!(b.best_ask_price(), Some(dec!(101)));
    }

    #[test]
    fn test_best_bid_price_none_when_empty() {
        assert_eq!(book("X").best_bid_price(), None);
    }

    #[test]
    fn test_best_ask_price_none_when_empty() {
        assert_eq!(book("X").best_ask_price(), None);
    }

    // ── OrderBook::is_crossed ─────────────────────────────────────────────────

    #[test]
    fn test_is_crossed_false_when_normal() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(!b.is_crossed());
    }

    #[test]
    fn test_is_crossed_false_when_empty() {
        assert!(!book("X").is_crossed());
    }

    // ── OrderBook::has_bids / has_asks ────────────────────────────────────────

    #[test]
    fn test_has_bids_true_when_bid_present() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        assert!(b.has_bids());
    }

    #[test]
    fn test_has_bids_false_when_empty() {
        assert!(!book("X").has_bids());
    }

    #[test]
    fn test_has_asks_true_when_ask_present() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert!(b.has_asks());
    }

    #[test]
    fn test_has_asks_false_when_empty() {
        assert!(!book("X").has_asks());
    }

    // ── OrderBook::ask_price_range / bid_price_range ──────────────────────────

    #[test]
    fn test_ask_price_range_none_when_empty() {
        assert_eq!(book("X").ask_price_range(), None);
    }

    #[test]
    fn test_ask_price_range_zero_when_single_level() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(1))).unwrap();
        assert_eq!(b.ask_price_range(), Some(dec!(0)));
    }

    #[test]
    fn test_ask_price_range_correct_with_multiple_levels() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(105), dec!(1))).unwrap();
        assert_eq!(b.ask_price_range(), Some(dec!(5)));
    }

    #[test]
    fn test_bid_price_range_none_when_empty() {
        assert_eq!(book("X").bid_price_range(), None);
    }

    #[test]
    fn test_bid_price_range_correct_with_multiple_levels() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(96), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(94), dec!(1))).unwrap();
        // best = 98, worst = 94, range = 4
        assert_eq!(b.bid_price_range(), Some(dec!(4)));
    }

    // ── OrderBook::mid_spread_ratio ───────────────────────────────────────────

    #[test]
    fn test_mid_spread_ratio_none_when_empty() {
        assert_eq!(book("X").mid_spread_ratio(), None);
    }

    #[test]
    fn test_mid_spread_ratio_correct() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // spread = 2, mid = 100, ratio = 2/100 = 0.02
        let ratio = b.mid_spread_ratio().unwrap();
        assert!((ratio - 0.02).abs() < 1e-9);
    }

    // ── OrderBook::volume_imbalance ────────────────────────────────────────────

    #[test]
    fn test_volume_imbalance_none_when_empty() {
        assert_eq!(book("X").volume_imbalance(), None);
    }

    #[test]
    fn test_volume_imbalance_positive_when_more_bids() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(3))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        // (3 - 1) / (3 + 1) = 0.5
        let imb = b.volume_imbalance().unwrap();
        assert!((imb - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_volume_imbalance_negative_when_more_asks() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(3))).unwrap();
        // (1 - 3) / (1 + 3) = -0.5
        let imb = b.volume_imbalance().unwrap();
        assert!((imb - (-0.5)).abs() < 1e-9);
    }

    #[test]
    fn test_volume_imbalance_zero_when_equal() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(2))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        let imb = b.volume_imbalance().unwrap();
        assert!(imb.abs() < 1e-9);
    }

    // ── OrderBook::ask_volume_within / bid_volume_within ─────────────────────

    #[test]
    fn test_ask_volume_within_sums_levels_in_range() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(2))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(3))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(105), dec!(10))).unwrap();
        // best ask = 100, range = 2 → include 100 and 101 (102 is limit, 105 outside)
        let vol = b.ask_volume_within(dec!(2));
        assert_eq!(vol, dec!(5)); // 2 + 3
    }

    #[test]
    fn test_ask_volume_within_zero_when_empty() {
        assert_eq!(book("X").ask_volume_within(dec!(10)), dec!(0));
    }

    #[test]
    fn test_bid_volume_within_sums_levels_in_range() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(3))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(95), dec!(10))).unwrap();
        // best bid = 100, range = 2 → include 100 and 99 (floor=98, 95 outside)
        let vol = b.bid_volume_within(dec!(2));
        assert_eq!(vol, dec!(8)); // 5 + 3
    }

    #[test]
    fn test_bid_volume_within_zero_when_empty() {
        assert_eq!(book("X").bid_volume_within(dec!(10)), dec!(0));
    }

    // ── OrderBook::ask_level_count / bid_level_count ─────────────────────────

    #[test]
    fn test_ask_level_count_zero_when_empty() {
        assert_eq!(book("X").ask_level_count(), 0);
    }

    #[test]
    fn test_ask_level_count_correct() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(2))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(3))).unwrap();
        assert_eq!(b.ask_level_count(), 3);
    }

    #[test]
    fn test_bid_level_count_correct() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(2))).unwrap();
        assert_eq!(b.bid_level_count(), 2);
    }

    // ── OrderBook::price_impact_buy / price_impact_sell ──────────────────────

    #[test]
    fn test_price_impact_buy_correct_single_level() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(10))).unwrap();
        // buy 5 units all at 100 → avg = 100
        assert_eq!(b.price_impact_buy(dec!(5)), Some(dec!(100)));
    }

    #[test]
    fn test_price_impact_buy_spans_levels() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(5))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        // buy 10: 5@100 + 5@101 → avg = 100.5
        assert_eq!(b.price_impact_buy(dec!(10)), Some(dec!(100.5)));
    }

    #[test]
    fn test_price_impact_buy_none_when_insufficient_liquidity() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(3))).unwrap();
        assert!(b.price_impact_buy(dec!(5)).is_none());
    }

    #[test]
    fn test_price_impact_sell_correct_single_level() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(10))).unwrap();
        assert_eq!(b.price_impact_sell(dec!(5)), Some(dec!(99)));
    }

    // ── total_value_at_level ──────────────────────────────────────────────────

    #[test]
    fn test_total_value_at_level_bid_returns_price_times_qty() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        assert_eq!(b.total_value_at_level(BookSide::Bid, dec!(100)), Some(dec!(500)));
    }

    #[test]
    fn test_total_value_at_level_ask_returns_price_times_qty() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(105), dec!(3))).unwrap();
        assert_eq!(b.total_value_at_level(BookSide::Ask, dec!(105)), Some(dec!(315)));
    }

    #[test]
    fn test_total_value_at_level_none_when_price_missing() {
        let b = book("X");
        assert!(b.total_value_at_level(BookSide::Bid, dec!(100)).is_none());
    }

    // ── ask_volume_above / bid_volume_below ───────────────────────────────────

    #[test]
    fn test_ask_volume_above_sums_asks_above_price() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(3))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(103), dec!(2))).unwrap();
        // volume above 101: 3+2=5
        assert_eq!(b.ask_volume_above(dec!(101)), dec!(5));
    }

    #[test]
    fn test_ask_volume_above_zero_when_no_asks_above() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(100), dec!(10))).unwrap();
        assert_eq!(b.ask_volume_above(dec!(100)), dec!(0));
    }

    #[test]
    fn test_bid_volume_below_sums_bids_below_price() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(4))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(6))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(2))).unwrap();
        // volume below 100: 4+6=10
        assert_eq!(b.bid_volume_below(dec!(100)), dec!(10));
    }

    #[test]
    fn test_bid_volume_below_zero_when_no_bids_below() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(5))).unwrap();
        assert_eq!(b.bid_volume_below(dec!(100)), dec!(0));
    }

    // ── total_notional_both_sides ─────────────────────────────────────────────

    #[test]
    fn test_total_notional_both_sides_sums_both() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(2))).unwrap(); // 200
        b.apply(delta("X", BookSide::Ask, dec!(105), dec!(3))).unwrap(); // 315
        assert_eq!(b.total_notional_both_sides(), dec!(515));
    }

    #[test]
    fn test_total_notional_both_sides_zero_when_empty() {
        let b = book("X");
        assert_eq!(b.total_notional_both_sides(), dec!(0));
    }

    // ── level_count_both_sides ────────────────────────────────────────────────

    #[test]
    fn test_level_count_both_sides_zero_when_empty() {
        let b = book("X");
        assert_eq!(b.level_count_both_sides(), 0);
    }

    #[test]
    fn test_level_count_both_sides_counts_all_levels() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        assert_eq!(b.level_count_both_sides(), 3);
    }

    // ── ask_price_at_rank / bid_price_at_rank ─────────────────────────────────

    #[test]
    fn test_ask_price_at_rank_best_ask_at_zero() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Ask, dec!(102), dec!(1))).unwrap();
        assert_eq!(b.ask_price_at_rank(0), Some(dec!(101)));
    }

    #[test]
    fn test_bid_price_at_rank_best_bid_at_zero() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(99), dec!(1))).unwrap();
        b.apply(delta("X", BookSide::Bid, dec!(98), dec!(1))).unwrap();
        assert_eq!(b.bid_price_at_rank(0), Some(dec!(99)));
    }

    #[test]
    fn test_ask_price_at_rank_none_out_of_bounds() {
        let b = book("X");
        assert!(b.ask_price_at_rank(0).is_none());
    }

    // ── price_level_exists ────────────────────────────────────────────────────

    #[test]
    fn test_price_level_exists_true_when_present() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Bid, dec!(100), dec!(1))).unwrap();
        assert!(b.price_level_exists(BookSide::Bid, dec!(100)));
    }

    #[test]
    fn test_price_level_exists_false_when_absent() {
        let b = book("X");
        assert!(!b.price_level_exists(BookSide::Bid, dec!(100)));
    }

    #[test]
    fn test_price_level_exists_ask_side() {
        let mut b = book("X");
        b.apply(delta("X", BookSide::Ask, dec!(101), dec!(5))).unwrap();
        assert!(b.price_level_exists(BookSide::Ask, dec!(101)));
        assert!(!b.price_level_exists(BookSide::Ask, dec!(102)));
    }
}