tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
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
//! Microstructure — ported from the reference implementation.
//!
//! One spread model, one book, shared by display and execution. The
//! reference-implementation header explains why that matters and is not repeated here; what
//! follows is what the PORT has to be careful about.
//!
//! # Tier
//!
//! **Tier 2: no transcendentals, but RNG-bearing.** Everything up to and
//! including [`build_live_book`] is a pure function of its inputs and is held
//! to bit-identical parity. [`settle_price_through_book`] additionally draws
//! from the seeded generator, so its parity is conditional on the draw
//! schedule matching exactly — see below.
//!
//! # The draw schedule is load-bearing
//!
//! `settle_price_through_book` consumes **exactly four uniform draws, or
//! exactly zero. Never any other number.** Four when it reaches the flow
//! loop, zero when any guard returns early — and every guard sits *before*
//! the loop except the final "nothing traded" check, which runs after all
//! four draws are already spent.
//!
//! This is not an implementation detail that happens to be true. The
//! generator is a single shared stream: every company settling on every tick
//! draws from it in sequence, so a port that skipped a draw on some early
//! return, or took "up to four" draws by breaking out when a slice fills
//! nothing, would leave the stream at a different position. Every subsequent
//! company on that tick then gets different numbers, and the whole simulation
//! diverges from a difference that has nothing to do with this function's
//! own output. The loop is therefore written to run its full four iterations
//! unconditionally, and the module's tests assert the draw count rather than trusting
//! the shape of the code.
//!
//! Since the 2026-08 stream split, the four-or-zero consumption is the
//! REPLAY schedule: it is what a recorded reference stream actually holds,
//! and `market::SettleDrawPolicy::FourOrZero` preserves it. The engine's
//! own generated schedule pre-draws the four uniforms unconditionally
//! (`FourAlways`) and serves this function from the buffer, so the market
//! stream's position cannot depend on which guard fired — an early return
//! leaves drawn values unused rather than draws untaken. This function's
//! own contract is unchanged either way.
//!
//! # The depth bound, and the counterfactual it allows
//!
//! `settle_price_through_book` quotes only the levels this tick's flow can
//! reach: `levels_needed = min(BOOK_LEVELS, max(2, ceil(tick_volume /
//! level_size) + 1))`, computed before any draw.
//! [`SettleOptions::depth_multiplier`] is read at that one site and at no
//! other. The four settlement uniforms, `fair_value` and `buy_fraction` are
//! all decided without it, so the SAME tick settled twice at two multipliers
//! is a controlled comparison rather than two markets: only which resting
//! levels a slice can walk differs.
//!
//! The shipped multiplier is `1.0` and the shipped bound is returned
//! untouched at that value (`scaled_depth`). `f64::INFINITY` lifts the
//! bound to [`BOOK_LEVELS`], which is the unbounded-depth arm the engine's
//! depth counterfactual runs.
//!
//! # Faithfulness notes
//!
//! - **`||` is not `??`.** `baseQuoteSize` falls through a chain of `||`, so
//!   a volume of exactly zero — or a NaN — moves to the next candidate. A
//!   port using "if present" semantics would stop at a real zero and quote a
//!   one-share book. `makerInventory` and `shortInterest`, by contrast, use
//!   `??`, where a real zero must be kept. The distinction is preserved per
//!   field; see `truthy`.
//! - **`!(x > 0)` and not `x <= 0`.** The negated form also rejects NaN, and
//!   the guards are copied in that form deliberately.

use crate::market_maker::{
    quote_ladder_into, LadderParams, MakerInventory, QuoteParams, MARKET_MAKER_ID,
};
use crate::mathx;
use crate::order_book::{Fill, OrderBook, Side, SubmitOptions};
use crate::rng::Rng;
use crate::types::Difficulty;

/// Levels quoted per side. Matches the depth the UI has always rendered.
pub const BOOK_LEVELS: f64 = 10.0;

/// How much inventory a maker will carry before its skew saturates, as a
/// multiple of one level's quote size.
///
/// Sets how long impact persists: a trade of N levels leaves the maker skewed
/// for roughly N/`INVENTORY_LIMIT_LEVELS` of its capacity, unwinding as
/// opposing flow arrives.
pub const INVENTORY_LIMIT_LEVELS: f64 = 12.0;

/// Order flow is split into this many child orders per tick.
const FLOW_SLICES: usize = 4;

/// How hard noise-trader flow leans toward closing a gap to fair value.
///
/// Makers quote *around* fair value, but quoting alone does not move the
/// print — someone has to lift the offer. This is what makes a stock trading
/// below fair value attract buyers.
const GAP_PRESSURE: f64 = 40.0;

/// Converts a crowd flow lean (a daily-equivalent log-price shock, bounded at
/// ±0.02 in the mispricing module) into a buy-fraction tilt.
const FLOW_LEAN_TILT: f64 = 10.0;

/// The company fields this module reads, and only those.
///
/// Following `fair_value`'s convention: a narrow input struct rather than a
/// port of the whole `Company` type, and sector table values passed in rather
/// than duplicated into this crate.
///
/// `Option` mirrors JavaScript's `undefined`. Which fallback applies to each
/// one is NOT uniform — see the module note on `||` versus `??`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CompanyMicrostructure {
    pub id: String,
    /// `SECTOR_CONFIGS[company.sector]?.volatility`, already looked up.
    pub sector_volatility: Option<f64>,
    /// `company.stock.price`. Treated here as fair value — the book sets the
    /// price an order FILLS at, not the price itself.
    pub price: f64,
    pub market_cap: f64,
    pub beta: Option<f64>,
    pub float: Option<f64>,
    pub short_interest: Option<f64>,
    pub avg_volume: Option<f64>,
    pub volume: Option<f64>,
    pub shares_outstanding: Option<f64>,
    pub maker_inventory: Option<f64>,
}

impl CompanyMicrostructure {
    /// A name with only its price and market cap; every optional figure is
    /// absent. Set the others on the value.
    pub fn new(id: impl Into<String>, price: f64, market_cap: f64) -> Self {
        CompanyMicrostructure {
            id: id.into(),
            sector_volatility: None,
            price,
            market_cap,
            beta: None,
            float: None,
            short_interest: None,
            avg_volume: None,
            volume: None,
            shares_outstanding: None,
            maker_inventory: None,
        }
    }
}

/// JavaScript truthiness for a possibly-absent number.
///
/// `a || b` in JavaScript falls through on `0`, `-0`, `NaN` and `undefined`
/// alike. `Option::or` does not — it keeps a `Some(0.0)`. This is the
/// difference, made explicit so each call site has to choose.
fn truthy(value: Option<f64>) -> Option<f64> {
    match value {
        // `x != 0.0` is false for BOTH +0 and -0, which is what JavaScript
        // does; and NaN is falsy, which `!=` alone would not catch.
        Some(x) if x != 0.0 && !x.is_nan() => Some(x),
        _ => None,
    }
}

/// Full spread in basis points for a company.
///
/// Market-cap tier, sector volatility × beta, VIX stress, difficulty-gated
/// liquidity crisis, and short-interest widening.
/// Capitalisation, in billions, where the continuous spread curve equals
/// the step function's third tier exactly.
pub const SPREAD_SIZE_REFERENCE_B: f64 = 25.0;

/// Spread in basis points at the reference capitalisation.
pub const SPREAD_SIZE_REFERENCE_BPS: f64 = 5.0;

/// Exponent of the continuous spread curve, least-squares fitted to the
/// step function's own four tiers: 0.5B reads 29.65 bps against a step of
/// 30, 5B reads 10.40 against 10, 25B reads 5.00 against 5, and 100B reads
/// 2.66 against 3.
pub const SPREAD_SIZE_EXPONENT: f64 = 0.455;

/// Bounds on the continuous spread, in basis points. The curve is unbounded
/// as capitalisation goes to zero, and a spread of ten thousand basis points
/// is not a market.
pub const SPREAD_SIZE_BOUNDS: (f64, f64) = (1.0, 100.0);

pub fn compute_spread_bps(
    company: &CompanyMicrostructure,
    vix: f64,
    difficulty: Option<Difficulty>,
) -> f64 {
    compute_spread_bps_with(company, vix, difficulty, 0.0, SPREAD_SIZE_EXPONENT)
}

/// Full spread in basis points, with the size curve selectable.
///
/// # The tiers are a cliff, and this is how it gets removed
///
/// The step function charges 10 bps at $1B and 30 bps at $0.9B -- a THREE
/// TIMES jump in transaction cost from a rounding error in market
/// capitalisation. Every execution study run across that boundary is
/// measuring an artifact of the tier edge rather than a property of size,
/// and a strategy that happens to trade names near $1B pays a cost that
/// does not exist.
///
/// Real spreads scale continuously with size. The power law fitted here
/// reproduces all four tiers closely (see [`SPREAD_SIZE_EXPONENT`]) while
/// removing the cliffs between them.
///
/// At smoothness 0.0 this returns the stepped value by branch, so every
/// preset before pt-v4 is bit-identical.
pub fn compute_spread_bps_with(
    company: &CompanyMicrostructure,
    vix: f64,
    difficulty: Option<Difficulty>,
    size_smoothness: f64,
    size_exponent: f64,
) -> f64 {
    let mcap_billions = company.market_cap / 1e9;
    let stepped = if mcap_billions > 50.0 {
        3.0
    } else if mcap_billions > 10.0 {
        5.0
    } else if mcap_billions > 1.0 {
        10.0
    } else {
        30.0
    };
    let base_bps = if size_smoothness == 0.0 || mcap_billions <= 0.0 {
        stepped
    } else {
        let ratio = mcap_billions / SPREAD_SIZE_REFERENCE_B;
        let (lo, hi) = SPREAD_SIZE_BOUNDS;
        let smooth = mathx::clamp(
            SPREAD_SIZE_REFERENCE_BPS * mathx::pow(ratio, -size_exponent), lo, hi);
        (1.0 - size_smoothness) * stepped + size_smoothness * smooth
    };

    // `?? 1.0`, so a genuine zero volatility or beta is kept as zero.
    let sector_vol = company.sector_volatility.unwrap_or(1.0);
    let beta = company.beta.unwrap_or(1.0);
    let vol_multiplier = 0.7 + 0.3 * sector_vol * beta;

    let mut vix_multiplier = vix_spread_multiplier(vix);
    // The reference implementation is `if (difficulty === 'hard' && vix > 25) … else if
    // (difficulty === 'expert' && vix > 25)`. A hard run below VIX 25 falls
    // through BOTH arms, which the guards reproduce.
    //
    // The `vix > 25` guards are in fact REDUNDANT with the `max(0, …)` inside
    // each arm — below the threshold the bracket is negative, clamps to zero,
    // and multiplies by 1. Mutation-tested: deleting a guard changes no
    // output. They are kept because the original has them and because the
    // redundancy is not obvious, but nothing downstream depends on it, so
    // this is the one place in the module where the two spellings are
    // genuinely interchangeable.
    match difficulty {
        Some(Difficulty::Hard) if vix > 25.0 => {
            vix_multiplier *= 1.0 + mathx::max(0.0, (vix - 25.0) * 0.05);
        }
        Some(Difficulty::Expert) if vix > 25.0 => {
            vix_multiplier *= 1.0 + mathx::max(0.0, (vix - 25.0) * 0.1);
        }
        _ => {}
    }

    // Heavily-shorted names are harder to make a market in: borrow is scarce,
    // so makers demand more edge.
    //
    // `float || 1` is TRUTHY-or (a zero float becomes 1), then `Math.max(1, …)`
    // on top. The two are not redundant: the `||` catches zero and NaN, the
    // `max` catches a negative.
    let float = mathx::max(1.0, truthy(company.float).unwrap_or(1.0));
    let short_interest_ratio = company.short_interest.unwrap_or(0.0) / float;
    let short_spread_mult = if short_interest_ratio > 0.15 {
        1.0 + (short_interest_ratio - 0.15) * 2.0
    } else {
        1.0
    };

    base_bps * vol_multiplier * vix_multiplier * short_spread_mult
}

/// How much a quoted spread widens with the VIX: `1 + max(0, (vix - 15) / 30)`.
///
/// One at VIX 15 and below, two at VIX 45. A function of its own so the
/// equity spread above and the rate indices' spread (`crate::rates`) widen
/// by the same rule rather than by two copies of it. The arithmetic is the
/// expression that stood inline in `compute_spread_bps_with`, so every
/// equity spread is bit-identical.
pub fn vix_spread_multiplier(vix: f64) -> f64 {
    1.0 + mathx::max(0.0, (vix - 15.0) / 30.0)
}

/// Baseline quote size per level — the legacy display-book size, minus the RNG.
pub fn base_quote_size(company: &CompanyMicrostructure) -> f64 {
    // A `||` chain: zero and NaN fall through to the next candidate. Note the
    // third rung is an EXPRESSION — an absent `sharesOutstanding` makes
    // `undefined * 0.005` NaN, which is falsy, so it lands on 100.
    let avg_vol = truthy(company.avg_volume)
        .or_else(|| truthy(company.volume))
        .or_else(|| truthy(company.shares_outstanding.map(|s| s * 0.005)))
        .unwrap_or(100.0);
    mathx::max(1.0, (avg_vol / 100.0).floor())
}

/// A resting player/AI limit order seeded into the book alongside maker
/// liquidity, giving genuine queue position.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RestingOrder {
    pub id: String,
    pub side: Side,
    pub price: f64,
    pub quantity: f64,
    pub owner_id: String,
}

impl RestingOrder {
    pub fn new(
        id: impl Into<String>,
        side: Side,
        price: f64,
        quantity: f64,
        owner_id: impl Into<String>,
    ) -> Self {
        RestingOrder { id: id.into(), side, price, quantity, owner_id: owner_id.into() }
    }
}

/// Options for [`build_live_book`]. `Default` carries the reference implementation
/// destructuring defaults (`vix = 15`, `levels = BOOK_LEVELS`).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LiveBookOptions {
    pub vix: f64,
    pub difficulty: Option<Difficulty>,
    /// Blend from the four-tier spread step toward a continuous power law,
    /// in [0, 1]. 0.0 is the step and is bit-identical.
    pub spread_size_smoothness: f64,
    /// Exponent of the continuous spread curve. Only read when the
    /// smoothness is non-zero.
    pub spread_size_exponent: f64,
    /// A JS `number`, not an integer — see `market_maker::LadderParams::levels`.
    pub levels: f64,
    pub resting_orders: Vec<RestingOrder>,
}

impl Default for LiveBookOptions {
    fn default() -> Self {
        Self {
            vix: 15.0,
            difficulty: None,
            spread_size_smoothness: 0.0,
            spread_size_exponent: SPREAD_SIZE_EXPONENT,
            levels: BOOK_LEVELS,
            resting_orders: Vec::new(),
        }
    }
}

/// Build the executable book for a company at this instant.
///
/// Rebuilt per call rather than persisted: a maker re-quotes every tick
/// anyway, so the book is a pure function of (fair value, spread, resting
/// orders). That keeps the tick pure and replay deterministic for free.
pub fn build_live_book(company: &CompanyMicrostructure, options: &LiveBookOptions) -> OrderBook {
    let mut book = OrderBook::new(company.id.clone(), Some(company.price));
    fill_live_book(company, options, &mut book);
    book
}

/// [`build_live_book`] into a book that is as [`OrderBook::new`] (or
/// [`OrderBook::reset`]) left it for this company, so a settlement can reuse
/// one book's allocations. The book that comes out is the same.
fn fill_live_book(company: &CompanyMicrostructure, options: &LiveBookOptions, book: &mut OrderBook) {
    let fair_value = company.price;

    // Negated comparison, so a NaN price returns an empty book rather than
    // falling through to quote against it.
    if !(fair_value > 0.0) {
        return;
    }

    let spread_bps = compute_spread_bps_with(
        company, options.vix, options.difficulty,
        options.spread_size_smoothness, options.spread_size_exponent);
    let base_size = base_quote_size(company);
    LADDER.with(|cell| {
        // The ladder, quoted into this thread's two reused buffers.
        let (bids, asks) = &mut *cell.borrow_mut();
        quote_ladder_into(&LadderParams {
            quote: QuoteParams {
                fair_value,
                // `computeSpreadBps` returns the FULL spread; the maker takes a half.
                half_spread_bps: spread_bps / 2.0,
                base_size,
                inventory: MakerInventory {
                    // `?? 0` — a real zero inventory is a zero, not "absent".
                    position: company.maker_inventory.unwrap_or(0.0),
                    limit: mathx::max(1.0, base_size * INVENTORY_LIMIT_LEVELS),
                },
                // The reference implementation passes neither `volatilityMultiplier` nor
                // `maxSkew`, so both take their destructuring default of 1.
                ..QuoteParams::default()
            },
            levels: options.levels,
            // `levelStep` is likewise omitted upstream, defaulting to 0.5.
            level_step: 0.5,
        }, bids, asks);

        // `quote_ladder_into` emits both sides best-first, so append straight on
        // rather than paying the insertion scan per level. The sides are sized
        // first, the resting orders included: allocation only.
        let resting = options.resting_orders.len();
        book.bids.reserve(bids.len() + resting);
        book.asks.reserve(asks.len() + resting);
        for level in bids.iter() {
            book.push_maker_level(Side::Buy, level.price, level.size, MARKET_MAKER_ID);
        }
        for level in asks.iter() {
            book.push_maker_level(Side::Sell, level.price, level.size, MARKET_MAKER_ID);
        }
    });

    // Player/AI orders join the same queue as maker liquidity and are ranked
    // purely on price-time priority, exactly like a real venue.
    for o in &options.resting_orders {
        book.post_limit(o.side, o.price, o.quantity, &o.owner_id, Some(o.id.clone()));
    }
}

std::thread_local! {
    /// The two sides of the ladder [`fill_live_book`] quotes, kept for their
    /// allocations. Cleared before every quote.
    static LADDER: std::cell::RefCell<(Vec<crate::market_maker::LadderLevel>, Vec<crate::market_maker::LadderLevel>)> =
        const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
    /// The book the last settlement on this thread built, kept for its
    /// allocations (see [`settle_inner`]). Reset before every use.
    static SETTLE_BOOK: std::cell::RefCell<Option<OrderBook>> =
        const { std::cell::RefCell::new(None) };
    /// The flow slices' fills buffer, kept for its allocation as the book
    /// is: one a settlement was 14 per cent of a pt-v21 session's
    /// allocations over 20 names. Cleared before every slice.
    static SETTLE_FILLS: std::cell::RefCell<Vec<crate::order_book::Fill>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// A settlement's book, handed back to [`SETTLE_BOOK`] when the settlement
/// returns, on every path.
struct SettleBook(Option<OrderBook>);

impl SettleBook {
    fn take(company: &CompanyMicrostructure) -> Self {
        let book = SETTLE_BOOK
            .with(|cell| cell.borrow_mut().take())
            .map(|mut book| {
                book.reset(&company.id, Some(company.price));
                book
            })
            .unwrap_or_else(|| OrderBook::new(company.id.clone(), Some(company.price)));
        SettleBook(Some(book))
    }
}

impl Drop for SettleBook {
    fn drop(&mut self) {
        if let Some(book) = self.0.take() {
            SETTLE_BOOK.with(|cell| *cell.borrow_mut() = Some(book));
        }
    }
}

// ── Price discovery through the book ───────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct SettlementResult {
    /// Printed price — the last trade, or fair value if nothing traded.
    pub price: f64,
    /// Shares actually matched.
    pub traded_volume: f64,
    /// True when at least one trade printed.
    pub traded: bool,
    /// Change in maker inventory from this tick's fills. Returned rather than
    /// applied, so this stays a pure function of its inputs and the generator.
    pub maker_inventory_delta: f64,
    /// The shock that arrived, in log units: `log(fair_value / last_price)`.
    ///
    /// The distance the price model asked the book to cover this tick, before
    /// the book covered any of it. See [`decompose`].
    pub shock: f64,
    /// The depth that absorbed it, in log units: `log(price / fair_value)`.
    ///
    /// Negative of the part of the shock the book did NOT print. `shock +
    /// absorbed` is the print's own log move away from the last print. See
    /// [`decompose`].
    pub absorbed: f64,
}

/// Split a print's log move into the shock that arrived and the depth that
/// absorbed it.
///
/// `shock` is `log(model_price / last_price)`: the distance the price model
/// put between the last print and this tick's anchor. `absorbed` is
/// `log(print / model_price)`: what the book did with that distance. They
/// sum to `log(print / last_price)`, to within the rounding of two logs
/// against one.
///
/// One definition, called twice. [`settle_price_through_book`] reports the
/// settlement's own view, where the print is the last trade the book made;
/// the engine reports the same pair against the printed tape, where the
/// print has also been through the circuit breaker. A second spelling of
/// this arithmetic beside the second call site is how the two would drift
/// apart while both looking right.
pub fn decompose(last_price: f64, model_price: f64, print: f64) -> (f64, f64) {
    (
        mathx::log(model_price / last_price),
        mathx::log(print / model_price),
    )
}

/// Options for [`settle_price_through_book`].
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct SettleOptions {
    pub vix: f64,
    pub difficulty: Option<Difficulty>,
    /// Crowd flow lean: the bounded daily-equivalent log shock from
    /// the mispricing module's `crowdLean`. `None` means no crowd, matching
    /// legacy
    /// callers where behaviour is unchanged.
    pub flow_lean: Option<f64>,
    /// The size-curve settings, carried so a settlement quotes against the
    /// same spread the caller asked for rather than a defaulted one.
    pub spread_size_smoothness: f64,
    pub spread_size_exponent: f64,
    /// How far to widen the depth bound this settlement quotes against.
    ///
    /// Read at exactly one site, where `levels_needed` is computed, and
    /// nowhere else: no draw, no factor, no `fair_value` and no
    /// `buy_fraction` reads it. Widening the bound changes which resting
    /// levels a slice can walk and nothing else, which is what makes a
    /// settlement at a different multiplier a counterfactual under the SAME
    /// draws rather than a different market.
    ///
    /// `1.0` is what ships, and at `1.0` the bound is returned untouched
    /// rather than multiplied, so no trajectory can move. `f64::INFINITY`
    /// lifts it to every level the maker quotes ([`BOOK_LEVELS`]), which is
    /// the unbounded-depth arm. Values between the two are arithmetic that
    /// works and nothing measures.
    pub depth_multiplier: f64,
}

impl Default for SettleOptions {
    fn default() -> Self {
        Self {
            vix: 15.0,
            difficulty: None,
            flow_lean: None,
            spread_size_smoothness: 0.0,
            spread_size_exponent: SPREAD_SIZE_EXPONENT,
            depth_multiplier: 1.0,
        }
    }
}

/// Apply [`SettleOptions::depth_multiplier`] to the depth a tick's flow
/// reaches.
///
/// The shipped multiplier returns `reach` itself rather than `reach * 1.0`.
/// Multiplying by one is exact for every finite and infinite f64, so the two
/// spellings agree on every value a market produces -- and the identity of
/// the bits is the contract here, not an argument about IEEE 754. The branch
/// is what makes "the counterfactual cannot move a trajectory" something a
/// reader can check by looking rather than by running the digest.
fn scaled_depth(reach: f64, multiplier: f64) -> f64 {
    if multiplier == 1.0 {
        reach
    } else {
        reach * multiplier
    }
}

/// Net inventory change for the market maker across a set of fills.
///
/// The maker sits opposite the taker: a taker BUY means the maker sold, so
/// its position falls. Fills against other participants do not touch it.
pub fn maker_delta_from_fills(fills: &[Fill]) -> f64 {
    // Folded explicitly from `0.0`, not `.sum()`, for the same reason
    // `order_book::depth` is: `Sum for f64` starts from `-0.0`, so an empty
    // or fully-skipped set would return a negative zero the reference implementation never
    // produces.
    let mut delta = 0.0;
    for f in fills {
        if f.maker_id != MARKET_MAKER_ID {
            continue;
        }
        delta += if f.taker_side == Side::Buy {
            -f.quantity
        } else {
            f.quantity
        };
    }
    delta
}

/// Settle a tick's price through the order book.
///
/// The price model supplies `fair_value`; this decides what actually
/// PRINTED. Price can now sit a half-spread either side of fair value and
/// bounce between bid and offer — real bid-ask bounce rather than a smooth
/// analytic path.
///
/// Consumes exactly four uniform draws from `rng`, or exactly zero. See the
/// module documentation for why that is a hard contract and not an incidental
/// property.
pub fn settle_price_through_book(
    company: &CompanyMicrostructure,
    fair_value: f64,
    tick_volume: f64,
    options: &SettleOptions,
    rng: &mut impl Rng,
) -> SettlementResult {
    // `Vec::new` does not allocate, so the shipped path pays nothing for the
    // agents' variant sharing its body.
    let mut unused = Vec::new();
    settle_inner(company, fair_value, tick_volume, options, &[], rng, &mut unused)
}

/// One fill of an agent's order inside a settlement.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SettledAgentFill {
    /// The agent's order that filled.
    pub order_id: String,
    pub agent: String,
    /// The AGENT's side.
    pub side: Side,
    pub quantity: f64,
    pub price: f64,
    /// True when the agent's order took liquidity: a resting order the
    /// maker's re-quote left crossed, matched before the flow.
    pub taker: bool,
    /// Who was on the other side: the maker, the flow, or another agent.
    pub counterparty: String,
}

/// [`settle_price_through_book`] with agents' resting orders in the book.
///
/// The orders join the maker's ladder in the order given (their arrival
/// order), each through `submit` with its limit and `post_remainder`, so an
/// order the maker's re-quote has left crossed trades against the ladder at
/// the ladder's prices before the flow, and the rest queues by price and
/// time behind the maker's size. The flow's four slices then walk the book
/// as they always have, and fill an agent's order when they reach it.
///
/// The draw contract is unchanged: four uniforms or none, and none of the
/// guards reads the orders. With no orders this IS
/// [`settle_price_through_book`], which calls the same body.
pub fn settle_price_through_book_with_orders(
    company: &CompanyMicrostructure,
    fair_value: f64,
    tick_volume: f64,
    options: &SettleOptions,
    resting: &[RestingOrder],
    rng: &mut impl Rng,
) -> (SettlementResult, Vec<SettledAgentFill>) {
    let mut fills = Vec::new();
    let result = settle_inner(company, fair_value, tick_volume, options, resting, rng, &mut fills);
    (result, fills)
}

/// True for an owner id that belongs to an agent rather than the house.
fn is_agent(owner: &str) -> bool {
    owner != MARKET_MAKER_ID
        && owner != "flow"
        && owner != crate::agent_book::DEPTH_OWNER
}

fn opposite(side: Side) -> Side {
    match side {
        Side::Buy => Side::Sell,
        Side::Sell => Side::Buy,
    }
}

fn settle_inner(
    company: &CompanyMicrostructure,
    fair_value: f64,
    tick_volume: f64,
    options: &SettleOptions,
    resting: &[RestingOrder],
    rng: &mut impl Rng,
    agent_fills: &mut Vec<SettledAgentFill>,
) -> SettlementResult {
    let last_price = company.price;

    // Nothing traded, so the print IS the model price and the book absorbed
    // exactly none of the shock. `decompose` gives `absorbed` of zero here
    // for free, because `log(fair_value / fair_value)` is zero.
    //
    // A closure rather than a value: it costs two logarithms, and building it
    // eagerly would spend them on every settlement that goes on to trade and
    // never looks at it. Called at each of the three returns below.
    let no_trade = || {
        let (shock, absorbed) = decompose(last_price, fair_value, fair_value);
        SettlementResult {
            price: fair_value,
            traded_volume: 0.0,
            traded: false,
            maker_inventory_delta: 0.0,
            shock,
            absorbed,
        }
    };

    // Guard 1 — before any draw.
    if !(fair_value > 0.0) || !(last_price > 0.0) || !(tick_volume > 0.0) {
        return no_trade();
    }

    // Build only the depth this tick's flow can actually reach. A tick prints
    // roughly avgVolume/390 while one level quotes avgVolume/100, so ordinary
    // flow never leaves the top level or two — quoting all ten was ~4x the
    // settlement cost for depth nothing touches.
    let level_size = mathx::max(1.0, base_quote_size(company));
    // Stays f64 all the way into the ladder. Narrowing here would be wrong:
    // an infinite `tick_volume` AND an infinite `level_size` make this NaN,
    // which must yield an EMPTY book and an early return costing zero draws.
    // Any integer cast turns that NaN into one quoted level and four draws.
    //
    // The `min` is also what keeps the unbounded-depth arm finite. At
    // `depth_multiplier = f64::INFINITY` the inner term is infinite, and
    // `quote_ladder`'s `while (i as f64) < n` pushes one level per iteration
    // for as long as the comparison holds. Without this cap the arm asks for
    // 34 GB and the process aborts rather than failing a test, so the bound
    // is asserted rather than left to be read.
    let levels_needed = mathx::min(
        BOOK_LEVELS,
        scaled_depth(
            mathx::max(2.0, (tick_volume / level_size).ceil() + 1.0),
            options.depth_multiplier,
        ),
    );
    // NaN is a legitimate value here and means an empty book; an infinity is
    // not, and would mean the cap above stopped capping.
    debug_assert!(
        !levels_needed.is_infinite(),
        "levels_needed must stay bounded by BOOK_LEVELS, got {levels_needed}"
    );
    // One book per thread, reset rather than rebuilt: the settlement runs
    // on every tick of every name, and allocating its book each time was
    // most of the allocator's share of a session. Same book, same draws.
    let mut slot = SettleBook::take(company);
    let book = slot.0.as_mut().expect("SettleBook::take always holds a book");
    fill_live_book(
        company,
        &LiveBookOptions {
            vix: options.vix,
            difficulty: options.difficulty,
            // Propagated, not defaulted: this inner book must price with the
            // same size curve as the outer call, or a settlement would quote
            // against a spread the caller did not ask for.
            spread_size_smoothness: options.spread_size_smoothness,
            spread_size_exponent: options.spread_size_exponent,
            levels: levels_needed,
            resting_orders: Vec::new(),
        },
        book,
    );

    // Guard 2 — still before any draw.
    if book.asks.is_empty() || book.bids.is_empty() {
        return no_trade();
    }

    // How far the flow can walk: the deepest price the maker quotes on each
    // side of this settlement's ladder. Without agents' orders the book IS
    // that ladder and a slice that empties it stops there, so the bound is
    // what the flow always met and moves nothing. With them, it stops a
    // slice that empties the ladder from walking on into an agent's order
    // resting past it: the market never traded at that price, and before
    // this bound a bid at 4% of the market filled at its own price whenever
    // a slice ran the ladder dry. Taken before the orders go in, so an
    // order's own price can never widen it.
    let flow_bound = if resting.is_empty() {
        None
    } else {
        Some((
            book.bids.last().map(|o| o.price),
            book.asks.last().map(|o| o.price),
        ))
    };

    // Agents' resting orders, after the guard so no guard reads them. A
    // crossed order trades here, at the ladder's prices, before any flow.
    // It passes over its own agent's orders (`skip_own`): an agent's buy and
    // sell resting at one price stay in the book, each for someone else to
    // fill, and never trade with each other.
    let mut pre_traded = 0.0;
    let mut pre_inventory = 0.0;
    for o in resting {
        let r = book.submit(
            o.side,
            o.quantity,
            &o.owner_id,
            SubmitOptions {
                limit_price: Some(o.price),
                post_remainder: true,
                order_id: Some(o.id.clone()),
                skip_own: true,
                house_ids: false,
            },
        );
        for f in &r.fills {
            pre_traded += f.quantity;
            agent_fills.push(SettledAgentFill {
                order_id: o.id.clone(),
                agent: o.owner_id.clone(),
                side: o.side,
                quantity: f.quantity,
                price: f.price,
                taker: true,
                counterparty: f.maker_id.to_string(),
            });
            if is_agent(&f.maker_id) {
                agent_fills.push(SettledAgentFill {
                    order_id: f.maker_order_id.clone(),
                    agent: f.maker_id.to_string(),
                    side: opposite(o.side),
                    quantity: f.quantity,
                    price: f.price,
                    taker: false,
                    counterparty: o.owner_id.clone(),
                });
            }
        }
        pre_inventory += maker_delta_from_fills(&r.fills);
    }

    // Lean the flow toward whichever side closes the gap to fair value, plus
    // whichever side the crowd is leaning.
    let gap = (fair_value - last_price) / last_price;
    let buy_fraction = mathx::max(
        0.05,
        mathx::min(
            0.95,
            0.5 + gap * GAP_PRESSURE + options.flow_lean.unwrap_or(0.0) * FLOW_LEAN_TILT,
        ),
    );

    let slice = mathx::max(1.0, (tick_volume / FLOW_SLICES as f64).floor());
    let mut traded = 0.0;
    let mut maker_inventory_delta = 0.0;

    // One fills buffer for the slices, cleared before each, and the one the
    // last settlement on this thread used: allocation only. Handed back
    // below, after the slices.
    let mut fills = SETTLE_FILLS.with(|cell| std::mem::take(&mut *cell.borrow_mut()));
    // Exactly FLOW_SLICES iterations, unconditionally. There is deliberately
    // no early break: a slice that fills nothing must still cost its draw.
    for _ in 0..FLOW_SLICES {
        let side = if rng.next_f64() < buy_fraction {
            Side::Buy
        } else {
            Side::Sell
        };
        // A sell slice walks the bids down to the deepest maker bid, a buy
        // the asks up to the deepest maker ask. `None` with no orders, which
        // is the shipped call.
        let limit_price = flow_bound.and_then(|(deepest_bid, deepest_ask)| match side {
            Side::Buy => deepest_ask,
            Side::Sell => deepest_bid,
        });
        fills.clear();
        book.match_into(
            side,
            slice,
            "flow",
            SubmitOptions {
                limit_price,
                post_remainder: false,
                order_id: None,
                skip_own: false,
                house_ids: false,
            },
            &mut fills,
        );
        for f in &fills {
            traded += f.quantity;
        }
        maker_inventory_delta += maker_delta_from_fills(&fills);
        if !resting.is_empty() {
            for f in &fills {
                if is_agent(&f.maker_id) {
                    agent_fills.push(SettledAgentFill {
                        order_id: f.maker_order_id.clone(),
                        agent: f.maker_id.to_string(),
                        side: opposite(side),
                        quantity: f.quantity,
                        price: f.price,
                        taker: false,
                        counterparty: f.taker_id.to_string(),
                    });
                }
            }
        }
    }
    fills.clear();
    SETTLE_FILLS.with(|cell| *cell.borrow_mut() = fills);
    // Added after the flow, and only when there were orders, so the
    // shipped path's two sums are the ones it always computed.
    if !resting.is_empty() {
        traded += pre_traded;
        maker_inventory_delta += pre_inventory;
    }

    // Guard 3 — the only one AFTER the draws, so it still costs four.
    match book.last_price {
        Some(price) if traded != 0.0 => {
            let (shock, absorbed) = decompose(last_price, fair_value, price);
            SettlementResult {
                price,
                traded_volume: traded,
                traded: true,
                maker_inventory_delta,
                shock,
                absorbed,
            }
        }
        _ => no_trade(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rng::GameRng;

    fn company() -> CompanyMicrostructure {
        CompanyMicrostructure {
            id: "ACME".to_string(),
            sector_volatility: Some(1.0),
            price: 100.0,
            market_cap: 20e9,
            beta: Some(1.0),
            float: Some(1e8),
            short_interest: Some(0.0),
            avg_volume: Some(1e6),
            volume: Some(1e6),
            shares_outstanding: Some(1e8),
            maker_inventory: Some(0.0),
        }
    }

    // ── The `||` versus `??` distinction ──────────────────────────────────

    #[test]
    fn a_zero_average_volume_falls_through_rather_than_quoting_one_share() {
        let mut c = company();
        c.avg_volume = Some(0.0);
        c.volume = Some(500_000.0);
        // `||` semantics: the zero is skipped and `volume` is used.
        assert_eq!(base_quote_size(&c), 5000.0);
    }

    #[test]
    fn a_nan_volume_also_falls_through() {
        let mut c = company();
        c.avg_volume = Some(f64::NAN);
        c.volume = Some(500_000.0);
        assert_eq!(base_quote_size(&c), 5000.0);
    }

    #[test]
    fn an_absent_shares_outstanding_lands_on_the_hundred_default() {
        let mut c = company();
        c.avg_volume = None;
        c.volume = None;
        c.shares_outstanding = None;
        // undefined * 0.005 is NaN, which is falsy, so the chain reaches 100.
        // Then max(1, floor(100/100)) = 1.
        assert_eq!(base_quote_size(&c), 1.0);
    }

    #[test]
    fn a_zero_maker_inventory_is_kept_as_zero_not_treated_as_absent() {
        let mut c = company();
        c.maker_inventory = Some(0.0);
        let flat = build_live_book(&c, &LiveBookOptions::default());
        c.maker_inventory = None;
        let absent = build_live_book(&c, &LiveBookOptions::default());
        // `??` semantics: both mean zero here, so the books must agree.
        assert_eq!(flat.bids[0].price, absent.bids[0].price);
    }

    // ── Spread model ──────────────────────────────────────────────────────

    #[test]
    fn spread_tightens_with_market_cap() {
        let mut c = company();
        let mut last = f64::INFINITY;
        for mcap in [0.5e9, 5e9, 20e9, 100e9] {
            c.market_cap = mcap;
            let bps = compute_spread_bps(&c, 15.0, None);
            assert!(
                bps < last,
                "spread should tighten as cap rises, got {bps} after {last}"
            );
            last = bps;
        }
    }

    #[test]
    fn vix_stress_widens_the_spread() {
        let c = company();
        assert!(compute_spread_bps(&c, 40.0, None) > compute_spread_bps(&c, 15.0, None));
    }

    #[test]
    fn expert_punishes_a_vix_spike_harder_than_hard() {
        let c = company();
        let normal = compute_spread_bps(&c, 40.0, Some(Difficulty::Normal));
        let hard = compute_spread_bps(&c, 40.0, Some(Difficulty::Hard));
        let expert = compute_spread_bps(&c, 40.0, Some(Difficulty::Expert));
        assert!(expert > hard && hard > normal);
    }

    #[test]
    fn a_hard_run_below_the_vix_threshold_falls_through_both_arms() {
        let c = company();
        // vix <= 25 fails the `hard` guard, and `expert` cannot match a hard
        // difficulty, so the result must equal the no-difficulty case.
        assert_eq!(
            compute_spread_bps(&c, 20.0, Some(Difficulty::Hard)),
            compute_spread_bps(&c, 20.0, None)
        );
    }

    #[test]
    fn heavy_short_interest_widens_the_spread_past_the_threshold() {
        let mut c = company();
        c.float = Some(100.0);
        c.short_interest = Some(10.0); // 10% — below the 15% threshold
        let light = compute_spread_bps(&c, 15.0, None);
        c.short_interest = Some(50.0); // 50%
        assert!(compute_spread_bps(&c, 15.0, None) > light);
    }

    #[test]
    fn a_zero_float_does_not_divide_by_zero() {
        let mut c = company();
        c.float = Some(0.0);
        c.short_interest = Some(1000.0);
        assert!(compute_spread_bps(&c, 15.0, None).is_finite());
    }

    // ── Book construction ─────────────────────────────────────────────────

    #[test]
    fn a_non_positive_price_yields_an_empty_book() {
        for price in [0.0, -10.0, f64::NAN] {
            let mut c = company();
            c.price = price;
            let book = build_live_book(&c, &LiveBookOptions::default());
            assert!(
                book.bids.is_empty() && book.asks.is_empty(),
                "price {price}"
            );
        }
    }

    #[test]
    fn the_book_is_two_sided_and_uncrossed() {
        let book = build_live_book(&company(), &LiveBookOptions::default());
        assert_eq!(book.bids.len(), BOOK_LEVELS as usize);
        assert_eq!(book.asks.len(), BOOK_LEVELS as usize);
        assert!(book.best_bid().unwrap() < book.best_ask().unwrap());
    }

    #[test]
    fn a_resting_order_inside_the_spread_takes_queue_priority() {
        let c = company();
        let maker_only = build_live_book(&c, &LiveBookOptions::default());
        let best_maker_bid = maker_only.best_bid().unwrap();

        let book = build_live_book(
            &c,
            &LiveBookOptions {
                resting_orders: vec![RestingOrder {
                    id: "player-1".to_string(),
                    side: Side::Buy,
                    price: best_maker_bid + 0.05,
                    quantity: 100.0,
                    owner_id: "player".to_string(),
                }],
                ..Default::default()
            },
        );
        assert_eq!(book.bids[0].owner_id, "player");
    }

    // ── Settlement, and the draw schedule ─────────────────────────────────

    /// Counts draws by advancing a reference generator to the same point.
    fn draws_consumed(before: &GameRng, after: &GameRng) -> usize {
        let mut probe = before.clone();
        for n in 0..64 {
            if probe == *after {
                return n;
            }
            probe.next_f64();
        }
        panic!("generator advanced more than 64 draws");
    }

    #[test]
    fn settlement_consumes_exactly_four_draws() {
        let mut rng = GameRng::from_seed(42);
        let before = rng.clone();
        let out = settle_price_through_book(
            &company(),
            100.0,
            10_000.0,
            &SettleOptions::default(),
            &mut rng,
        );
        assert!(out.traded);
        assert_eq!(draws_consumed(&before, &rng), 4);
    }

    #[test]
    fn every_early_return_consumes_exactly_zero_draws() {
        // Each of these must bail BEFORE the flow loop. If a future edit
        // moves a guard below the draws, this catches it — and a drifted
        // stream position is otherwise invisible until the whole simulation
        // has diverged.
        let cases: Vec<(&str, CompanyMicrostructure, f64, f64)> = vec![
            ("fair value zero", company(), 0.0, 10_000.0),
            ("fair value NaN", company(), f64::NAN, 10_000.0),
            ("tick volume zero", company(), 100.0, 0.0),
            ("tick volume NaN", company(), 100.0, f64::NAN),
            (
                "last price zero",
                CompanyMicrostructure {
                    price: 0.0,
                    ..company()
                },
                100.0,
                10_000.0,
            ),
        ];

        for (note, c, fair_value, tick_volume) in cases {
            let mut rng = GameRng::from_seed(42);
            let before = rng.clone();
            let out = settle_price_through_book(
                &c,
                fair_value,
                tick_volume,
                &SettleOptions::default(),
                &mut rng,
            );
            assert!(!out.traded, "{note}: should not trade");
            assert_eq!(draws_consumed(&before, &rng), 0, "{note}: should not draw");
        }
    }

    #[test]
    fn the_flow_loop_never_breaks_early_even_when_slices_fill_nothing() {
        // A book so thin relative to the slice that later slices find an
        // empty side. All four draws must still be spent.
        let mut c = company();
        c.avg_volume = Some(200.0); // one level quotes 2 shares
        let mut rng = GameRng::from_seed(7);
        let before = rng.clone();
        settle_price_through_book(&c, 100.0, 100_000.0, &SettleOptions::default(), &mut rng);
        assert_eq!(draws_consumed(&before, &rng), 4);
    }

    // ── The depth bound, and the counterfactual ───────────────────────────

    /// Four fixed uniforms, so a settlement's flow direction is decided by
    /// the test rather than by a search for a convenient seed.
    struct Fixed([f64; 4], usize);

    impl Rng for Fixed {
        fn next_f64(&mut self) -> f64 {
            let v = self.0[self.1];
            self.1 += 1;
            v
        }
        fn next_normal(&mut self) -> f64 {
            unreachable!("settlement draws uniforms only")
        }
    }

    /// The shipped multiplier is the shipped market. This is the whole
    /// argument that the option cannot move a trajectory, and it is asserted
    /// on the BITS rather than on a comparison that a NaN would pass.
    #[test]
    fn the_shipped_depth_multiplier_settles_exactly_as_before() {
        for volume in [0.0, 1.0, 10_000.0, 100_000.0, f64::NAN] {
            let mut a = GameRng::from_seed(11);
            let mut b = GameRng::from_seed(11);
            let default = settle_price_through_book(
                &company(),
                100.0,
                volume,
                &SettleOptions::default(),
                &mut a,
            );
            let explicit = settle_price_through_book(
                &company(),
                100.0,
                volume,
                &SettleOptions {
                    depth_multiplier: 1.0,
                    ..SettleOptions::default()
                },
                &mut b,
            );
            assert_eq!(
                default.price.to_bits(),
                explicit.price.to_bits(),
                "volume {volume}: the shipped multiplier must be a no-op"
            );
            assert_eq!(a, b, "volume {volume}: and must take the same draws");
        }
    }

    /// The counterfactual costs the same four uniforms the real settlement
    /// costs, which is what lets the engine serve it from a rewound buffer.
    #[test]
    fn unbounded_depth_consumes_exactly_four_draws() {
        let mut rng = GameRng::from_seed(42);
        let before = rng.clone();
        let out = settle_price_through_book(
            &company(),
            100.0,
            10_000.0,
            &SettleOptions {
                depth_multiplier: f64::INFINITY,
                ..SettleOptions::default()
            },
            &mut rng,
        );
        assert!(out.traded);
        assert_eq!(draws_consumed(&before, &rng), 4);
    }

    /// Every guard that costs zero draws costs zero at unbounded depth too.
    ///
    /// The guards are the reason the two arms can share a buffer: if a
    /// multiplier could change which one fired, the second settlement would
    /// sometimes need draws the first one never took.
    #[test]
    fn unbounded_depth_takes_the_same_early_returns() {
        let cases: Vec<(&str, CompanyMicrostructure, f64, f64)> = vec![
            ("fair value zero", company(), 0.0, 10_000.0),
            ("fair value NaN", company(), f64::NAN, 10_000.0),
            ("tick volume zero", company(), 100.0, 0.0),
            ("tick volume NaN", company(), 100.0, f64::NAN),
            (
                "last price zero",
                CompanyMicrostructure {
                    price: 0.0,
                    ..company()
                },
                100.0,
                10_000.0,
            ),
        ];
        for (note, c, fair_value, tick_volume) in cases {
            let mut rng = GameRng::from_seed(42);
            let before = rng.clone();
            let out = settle_price_through_book(
                &c,
                fair_value,
                tick_volume,
                &SettleOptions {
                    depth_multiplier: f64::INFINITY,
                    ..SettleOptions::default()
                },
                &mut rng,
            );
            assert!(!out.traded, "{note}: should not trade");
            assert_eq!(draws_consumed(&before, &rng), 0, "{note}: should not draw");
        }
    }

    /// A tick whose flow already reaches every level settles identically at
    /// unbounded depth, so liquidity's share of that print is zero.
    ///
    /// `company()` quotes 10,000 a level, so 100,000 of flow puts
    /// `levels_needed` at its `BOOK_LEVELS` ceiling before the multiplier is
    /// consulted. The two arms are then the same call.
    #[test]
    fn a_book_already_at_full_depth_prints_the_same_unbounded() {
        let deep = settle_price_through_book(
            &company(),
            101.0,
            100_000.0,
            &SettleOptions::default(),
            &mut Fixed([0.1, 0.2, 0.3, 0.4], 0),
        );
        let unbounded = settle_price_through_book(
            &company(),
            101.0,
            100_000.0,
            &SettleOptions {
                depth_multiplier: f64::INFINITY,
                ..SettleOptions::default()
            },
            &mut Fixed([0.1, 0.2, 0.3, 0.4], 0),
        );
        assert_eq!(deep, unbounded);
    }

    /// Flow that exhausts the bounded book fills more of itself against
    /// unbounded depth, and prints nearer fair value for doing so.
    ///
    /// Four uniforms below the buy fraction send every slice to the ask side,
    /// so the test does not depend on a draw happening to lean one way.
    #[test]
    fn one_sided_flow_walks_further_when_the_bound_is_lifted() {
        // 30,000 against a 10,000 level puts the bound at four levels, which
        // quote 2.92 levels of size a side against four slices of 7,500.
        let bounded = settle_price_through_book(
            &company(),
            101.0,
            30_000.0,
            &SettleOptions::default(),
            &mut Fixed([0.1, 0.1, 0.1, 0.1], 0),
        );
        let unbounded = settle_price_through_book(
            &company(),
            101.0,
            30_000.0,
            &SettleOptions {
                depth_multiplier: f64::INFINITY,
                ..SettleOptions::default()
            },
            &mut Fixed([0.1, 0.1, 0.1, 0.1], 0),
        );
        assert!(
            unbounded.traded_volume > bounded.traded_volume,
            "unbounded depth must fill more of the same flow: {} against {}",
            unbounded.traded_volume,
            bounded.traded_volume
        );
        assert!(
            unbounded.price > bounded.price,
            "and the extra fills print higher: {} against {}",
            unbounded.price,
            bounded.price
        );
    }

    /// The two halves of a print add up to the print's own move.
    #[test]
    fn the_shock_and_the_absorption_sum_to_the_print_move() {
        let out = settle_price_through_book(
            &company(),
            101.0,
            30_000.0,
            &SettleOptions::default(),
            &mut Fixed([0.1, 0.6, 0.1, 0.6], 0),
        );
        assert!(out.traded);
        let moved = mathx::log(out.price / company().price);
        assert!(
            (out.shock + out.absorbed - moved).abs() < 1e-12,
            "shock {} + absorbed {} should be the move {moved}",
            out.shock,
            out.absorbed
        );
    }

    /// Nothing traded means the book absorbed nothing, and the print IS the
    /// model price.
    #[test]
    fn a_tick_that_does_not_settle_absorbs_exactly_zero() {
        let out = settle_price_through_book(
            &company(),
            101.0,
            0.0,
            &SettleOptions::default(),
            &mut GameRng::from_seed(3),
        );
        assert!(!out.traded);
        assert_eq!(out.absorbed, 0.0);
        assert_eq!(out.shock, mathx::log(101.0 / company().price));
    }

    #[test]
    fn settlement_is_reproducible_from_the_same_seed() {
        let run = || {
            let mut rng = GameRng::from_seed(99);
            settle_price_through_book(
                &company(),
                101.0,
                10_000.0,
                &SettleOptions::default(),
                &mut rng,
            )
        };
        assert_eq!(run(), run());
    }

    #[test]
    fn a_gap_to_fair_value_biases_flow_toward_closing_it() {
        // Fair value well above the last price should draw buyers, so the
        // print lands above where a symmetric flow would leave it.
        let c = company();
        let mut up = GameRng::from_seed(5);
        let above =
            settle_price_through_book(&c, 110.0, 50_000.0, &SettleOptions::default(), &mut up);
        let mut down = GameRng::from_seed(5);
        let below =
            settle_price_through_book(&c, 90.0, 50_000.0, &SettleOptions::default(), &mut down);
        assert!(
            above.price > below.price,
            "gap pressure should separate the prints: {} vs {}",
            above.price,
            below.price
        );
    }

    #[test]
    fn a_taker_buy_reduces_maker_inventory() {
        // The directional claim, tested where it is exact rather than
        // through four coin flips.
        let fill = |taker_side| Fill {
            price: 100.0,
            quantity: 50.0,
            maker_order_id: "x".to_string(),
            maker_id: MARKET_MAKER_ID.into(),
            taker_id: "flow".into(),
            taker_side,
        };
        assert_eq!(maker_delta_from_fills(&[fill(Side::Buy)]), -50.0);
        assert_eq!(maker_delta_from_fills(&[fill(Side::Sell)]), 50.0);
    }

    #[test]
    fn buy_leaning_flow_drains_maker_inventory_and_sell_leaning_builds_it() {
        // Deliberately NOT a single seed. `buy_fraction` saturates at 0.95,
        // so any individual four-draw run can still come out the other way
        // — an assertion on one seed would be asserting a coin flip, and
        // would pass or fail on which seed happened to be typed.
        let mean_delta = |fair_value: f64, flow_lean: f64| {
            let mut total = 0.0;
            for seed in 0..300u64 {
                let mut rng = GameRng::from_seed(seed);
                total += settle_price_through_book(
                    &company(),
                    fair_value,
                    50_000.0,
                    &SettleOptions {
                        spread_size_smoothness: 0.0,
                        spread_size_exponent: SPREAD_SIZE_EXPONENT,
                        flow_lean: Some(flow_lean),
                        ..SettleOptions::default()
                    },
                    &mut rng,
                )
                .maker_inventory_delta;
            }
            total / 300.0
        };

        // Undervalued plus a bullish crowd pins buy_fraction at its 0.95 cap.
        let buying = mean_delta(101.0, 0.02);
        // Overvalued plus a bearish crowd pins it at the 0.05 floor.
        let selling = mean_delta(99.0, -0.02);

        assert!(
            buying < 0.0,
            "maker sells into buying flow, mean delta {buying}"
        );
        assert!(
            selling > 0.0,
            "maker buys from selling flow, mean delta {selling}"
        );
    }

    #[test]
    fn fills_against_other_participants_do_not_touch_maker_inventory() {
        let fills = vec![Fill {
            price: 100.0,
            quantity: 50.0,
            maker_order_id: "x".to_string(),
            maker_id: "player".into(),
            taker_id: "flow".into(),
            taker_side: Side::Buy,
        }];
        assert_eq!(maker_delta_from_fills(&fills), 0.0);
    }

    // ── Agents' resting orders in the settlement ──────────────────────────

    fn resting(id: &str, side: Side, price: f64, quantity: f64) -> RestingOrder {
        RestingOrder {
            id: id.to_string(),
            side,
            price,
            quantity,
            owner_id: id.split('-').next().unwrap().to_string(),
        }
    }

    /// With no orders the variant IS the shipped settlement, to the bit and
    /// to the draw.
    #[test]
    fn with_no_orders_the_variant_is_the_shipped_settlement() {
        for volume in [0.0, 10_000.0, 100_000.0] {
            let mut a = GameRng::from_seed(3);
            let mut b = GameRng::from_seed(3);
            let x = settle_price_through_book(
                &company(), 101.0, volume, &SettleOptions::default(), &mut a);
            let (y, fills) = settle_price_through_book_with_orders(
                &company(), 101.0, volume, &SettleOptions::default(), &[], &mut b);
            assert_eq!(x, y);
            assert_eq!(a, b);
            assert!(fills.is_empty());
        }
    }

    /// The flow reaches a bid a cent inside the spread before the maker's,
    /// fills it at its own price, and takes the same four draws.
    #[test]
    fn the_flow_fills_a_resting_bid_inside_the_spread_first() {
        let bid = build_live_book(&company(), &LiveBookOptions::default())
            .best_bid()
            .unwrap();
        let price = bid + 0.01;
        let orders = vec![resting("a-0", Side::Buy, price, 3_000.0)];
        // Fair value under the last print, and four uniforms above the buy
        // fraction: every slice sells.
        let (out, fills) = settle_price_through_book_with_orders(
            &company(), 99.0, 20_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
        assert!(out.traded);
        assert_eq!(fills.len(), 1, "one slice of 5,000 took all 3,000: {fills:?}");
        let f = &fills[0];
        assert_eq!((f.agent.as_str(), f.side, f.price, f.quantity, f.taker),
                   ("a", Side::Buy, price, 3_000.0, false));
        assert_eq!(f.counterparty, "flow");
        let mut rng = GameRng::from_seed(42);
        let before = rng.clone();
        settle_price_through_book_with_orders(
            &company(), 99.0, 20_000.0, &SettleOptions::default(), &orders, &mut rng);
        assert_eq!(draws_consumed(&before, &rng), 4);
    }

    /// A slice smaller than the order fills it in part; the next slice
    /// continues where it stopped.
    #[test]
    fn a_slice_smaller_than_the_order_fills_it_in_part() {
        let bid = build_live_book(&company(), &LiveBookOptions::default())
            .best_bid()
            .unwrap();
        let orders = vec![resting("a-0", Side::Buy, bid + 0.01, 7_000.0)];
        let (_, fills) = settle_price_through_book_with_orders(
            &company(), 99.0, 20_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
        let q: Vec<f64> = fills.iter().map(|f| f.quantity).collect();
        assert_eq!(q, vec![5_000.0, 2_000.0]);
    }

    /// A resting order the re-quote leaves crossed trades against the
    /// ladder at the ladder's price, before the flow, as a taker.
    #[test]
    fn a_crossed_resting_order_takes_the_ladder_before_the_flow() {
        let ask = build_live_book(&company(), &LiveBookOptions::default())
            .best_ask()
            .unwrap();
        let orders = vec![resting("a-0", Side::Buy, ask + 0.05, 1_000.0)];
        let (_, fills) = settle_price_through_book_with_orders(
            &company(), 100.0, 20_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
        let f = &fills[0];
        assert!(f.taker);
        assert_eq!((f.price, f.quantity, f.counterparty.as_str()), (ask, 1_000.0, MARKET_MAKER_ID));
    }

    /// An agent's buy and sell resting at one price never trade with each
    /// other. A persona's quoter on AAC (book 23.65/23.67) rested both at
    /// 23.66 and the next settlement matched the later sell against the
    /// earlier buy: a wash trade on the tape. The sell now passes over its
    /// own bid, both rest, and the flow fills each from its own side.
    #[test]
    fn an_agents_buy_and_sell_at_one_price_do_not_trade_together() {
        let ladder = build_live_book(&company(), &LiveBookOptions::default());
        let (bid, ask) = (ladder.best_bid().unwrap(), ladder.best_ask().unwrap());
        let p = ((bid + 0.01) * 100.0).round() / 100.0;
        assert!(p < ask, "the test needs a spread of two cents: {bid} {ask}");
        let orders = vec![
            resting("a-0", Side::Buy, p, 1_000.0),
            resting("a-1", Side::Sell, p, 1_000.0),
        ];
        // One buy slice and one sell slice, so the flow meets both orders.
        let (_, fills) = settle_price_through_book_with_orders(
            &company(), 100.0, 4_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.0, 0.99, 0.99, 0.99], 0));
        assert!(fills.iter().all(|f| f.counterparty != "a"), "self-trade: {fills:?}");
        assert!(fills.iter().all(|f| !f.taker), "neither order crossed anyone else: {fills:?}");
        let sold: f64 = fills.iter().filter(|f| f.order_id == "a-1").map(|f| f.quantity).sum();
        let bought: f64 = fills.iter().filter(|f| f.order_id == "a-0").map(|f| f.quantity).sum();
        assert_eq!((bought, sold), (1_000.0, 1_000.0), "the flow fills both: {fills:?}");
    }

    /// Passing over its own order, a crossing order still trades with the
    /// next agent in the queue at that price.
    #[test]
    fn a_crossing_order_skips_its_own_and_meets_the_next_agent() {
        let ladder = build_live_book(&company(), &LiveBookOptions::default());
        let (bid, ask) = (ladder.best_bid().unwrap(), ladder.best_ask().unwrap());
        let p = ((bid + 0.01) * 100.0).round() / 100.0;
        assert!(p < ask);
        let orders = vec![
            resting("a-0", Side::Buy, p, 1_000.0),
            resting("b-0", Side::Buy, p, 600.0),
            resting("a-1", Side::Sell, p, 1_000.0),
        ];
        let (_, fills) = settle_price_through_book_with_orders(
            &company(), 100.0, 4.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.99, 0.99, 0.99, 0.99], 0));
        let crossed: Vec<_> = fills.iter().filter(|f| f.taker).collect();
        assert_eq!(crossed.len(), 1, "{fills:?}");
        assert_eq!(
            (crossed[0].order_id.as_str(), crossed[0].counterparty.as_str(), crossed[0].quantity),
            ("a-1", "b", 600.0)
        );
        assert!(fills.iter().all(|f| f.order_id != "a-0" || f.counterparty != "a"));
    }

    /// Flow that empties the ladder stops at the ladder's last price. A bid
    /// resting far below it is not filled, and the print is a price the
    /// maker quoted. Before the bound, the fourth slice filled 4% of the
    /// market at the order's own price and printed it.
    #[test]
    fn flow_that_empties_the_ladder_does_not_reach_a_bid_past_it() {
        // 200,000 shares against ten levels of about 10,000: every slice
        // sells, and the second empties the ladder.
        let ladder = build_live_book(&company(), &LiveBookOptions::default());
        let deepest = ladder.bids.last().unwrap().price;
        let held: f64 = ladder.bids.iter().map(|o| o.remaining).sum();
        assert!(held < 200_000.0, "the ladder must run dry: {held}");
        for price in [4.0, deepest * 0.9, deepest - 0.01] {
            let orders = vec![resting("a-0", Side::Buy, price, 5_000.0)];
            let (out, fills) = settle_price_through_book_with_orders(
                &company(), 99.0, 200_000.0, &SettleOptions::default(), &orders,
                &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
            assert!(fills.is_empty(), "a bid at {price} below the ladder filled: {fills:?}");
            assert_eq!(out.price, deepest, "the print is the ladder's last price");
            // The same settlement without the order prints the same.
            let (bare, _) = settle_price_through_book_with_orders(
                &company(), 99.0, 200_000.0, &SettleOptions::default(), &[],
                &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
            assert_eq!(out, bare);
        }
    }

    /// The mirror: an offer far above the ladder, against flow that buys
    /// it dry.
    #[test]
    fn flow_that_empties_the_ladder_does_not_reach_an_offer_past_it() {
        let ladder = build_live_book(&company(), &LiveBookOptions::default());
        let deepest = ladder.asks.last().unwrap().price;
        let orders = vec![resting("a-0", Side::Sell, 1_000.0, 5_000.0)];
        let (out, fills) = settle_price_through_book_with_orders(
            &company(), 101.0, 200_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.0, 0.0, 0.0, 0.0], 0));
        assert!(fills.is_empty(), "an offer at 10x filled: {fills:?}");
        assert_eq!(out.price, deepest);
    }

    /// An order AT the ladder's last price still fills once the maker's
    /// size there is gone, at that price: the bound stops the flow past the
    /// ladder, not at it.
    #[test]
    fn a_bid_at_the_ladders_last_price_still_fills_behind_the_maker() {
        let ladder = build_live_book(&company(), &LiveBookOptions::default());
        let deepest = ladder.bids.last().unwrap().price;
        let orders = vec![resting("a-0", Side::Buy, deepest, 5_000.0)];
        let (_, fills) = settle_price_through_book_with_orders(
            &company(), 99.0, 200_000.0, &SettleOptions::default(), &orders,
            &mut Fixed([0.9, 0.9, 0.9, 0.9], 0));
        let q: f64 = fills.iter().map(|f| f.quantity).sum();
        assert_eq!(q, 5_000.0, "{fills:?}");
        assert!(fills.iter().all(|f| f.price == deepest && !f.taker));
    }

    #[test]
    fn an_empty_fill_set_yields_positive_zero() {
        // `.sum()` would give -0.0 here; the reference implementation gives +0.
        assert_eq!(maker_delta_from_fills(&[]).to_bits(), 0.0f64.to_bits());
    }
}