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
//! Central limit order book — price-time priority matching.
//!
//! Ported from the reference implementation's order book, which is
//! **zero imports and zero transcendentals**: the most self-contained module
//! in the whole port, and therefore held to strict bit-identical parity like
//! `fair_value`.
//!
//! # What this module is for
//!
//! Execution used to run through a deterministic spread model with the
//! rendered book being display-only. That conflicts with the realism mandate:
//! real exchanges do not compute a fill price from a formula, they match two
//! orders. This is the matching core, and the consequence that matters is that
//! **slippage on size becomes emergent rather than modelled** — a large order
//! pays more because it eats real levels, not because a coefficient says so.
//!
//! # Faithfulness notes
//!
//! Several behaviours here look like they could be tidied and must not be:
//!
//! - **Trades print at the RESTING order's price**, never the incoming one.
//!   That is what gives a taker genuine price improvement when it crosses a
//!   better quote.
//! - **Depth is trimmed from the far end** at [`MAX_DEPTH_PER_SIDE`]. Dropping
//!   the worst-priced orders cannot change a fill that would have happened,
//!   which is why the cap is safe.
//! - **`!(quantity > 0)` rather than `quantity <= 0`.** The negation is
//!   load-bearing: it also rejects NaN, which `<=` would let through.
//! - **A posted remainder counts as filled, not unfilled.** `submitOrder` sets
//!   `remaining = 0` once the rest is parked in the book, because it was
//!   accepted rather than rejected.

/// Maximum resting orders per side. Bounded so insertion stays a short scan.
use crate::mathx;

pub const MAX_DEPTH_PER_SIDE: usize = 32;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Buy,
    Sell,
}

/// Who owns a resting order. The house owners are static strings, so a book
/// of house levels allocates nothing to name them.
pub type OwnerId = std::borrow::Cow<'static, str>;

/// An owner as an [`OwnerId`], borrowed when it is one of the house's own.
pub fn owner_id(owner: &str) -> OwnerId {
    match owner {
        "mm" => OwnerId::Borrowed("mm"),
        "depth" => OwnerId::Borrowed("depth"),
        "flow" => OwnerId::Borrowed("flow"),
        "range" => OwnerId::Borrowed("range"),
        other => OwnerId::Owned(other.to_string()),
    }
}

/// A resting order's id as it is stored: a caller's own, or the book's,
/// which reads `{company_id}-{sequence}` and is written out only when asked
/// for ([`BookOrder::id_in`]).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum OrderId {
    Given(String),
    Sequenced,
}

/// A resting order.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct BookOrder {
    pub id: OrderId,
    /// A piece of an order split in place: 0 for a whole order, `k` for the
    /// piece whose id is the order's with `.k` after it.
    pub piece: u32,
    pub side: Side,
    pub price: f64,
    /// Original size, in shares.
    pub quantity: f64,
    /// Unfilled remainder, in shares.
    pub remaining: f64,
    /// Monotonic arrival counter — the "time" half of price-time priority.
    pub sequence: u64,
    pub owner_id: OwnerId,
}

impl BookOrder {
    /// The order's id, written out, in the book of `company_id`.
    pub fn id_in(&self, company_id: &str) -> String {
        let base = match &self.id {
            OrderId::Given(id) => id.clone(),
            OrderId::Sequenced => sequenced_id(company_id, self.sequence),
        };
        if self.piece == 0 {
            base
        } else {
            format!("{base}.{}", self.piece)
        }
    }

    /// Piece `k` of this order, at a price and size: its id is this order's
    /// with `.k` after it (`k` at least 1), and it keeps the arrival counter.
    pub fn piece(&self, k: u32, price: f64, shares: f64, company_id: &str) -> BookOrder {
        let id = if self.piece == 0 {
            self.id.clone()
        } else {
            OrderId::Given(self.id_in(company_id))
        };
        BookOrder {
            id,
            piece: k,
            side: self.side,
            price,
            quantity: shares,
            remaining: shares,
            sequence: self.sequence,
            owner_id: self.owner_id.clone(),
        }
    }
}

/// One executed trade.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Fill {
    /// Always the resting (maker) order's price.
    pub price: f64,
    pub quantity: f64,
    /// The resting order's id. Against one of the house's own levels it is
    /// written out only when [`SubmitOptions::house_ids`] asks for it, and
    /// is empty otherwise: the engine never reads it there.
    pub maker_order_id: String,
    pub maker_id: OwnerId,
    pub taker_id: OwnerId,
    pub taker_side: Side,
}

/// Whether an owner is one of the house's own (the maker, latent depth,
/// flow, range).
pub fn is_house_owner(owner: &str) -> bool {
    matches!(owner, "mm" | "depth" | "flow" | "range")
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct MatchResult {
    pub fills: Vec<Fill>,
    /// Shares that could not be filled. Zero when a remainder was posted.
    pub unfilled: f64,
    /// Volume-weighted average across `fills`, or `None` if nothing filled.
    pub average_price: Option<f64>,
    /// The remainder as a resting order, when one was posted.
    pub resting: Option<BookOrder>,
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PriceLevel {
    pub price: f64,
    pub quantity: f64,
    pub orders: u32,
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SweepCost {
    pub average_price: f64,
    pub worst_price: f64,
    pub filled: f64,
}

/// Options for [`OrderBook::submit`].
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct SubmitOptions {
    /// `None` is a market order.
    pub limit_price: Option<f64>,
    /// Rest any unfilled remainder. Ignored for market orders, which never
    /// rest — an unfilled market remainder is simply unfilled.
    pub post_remainder: bool,
    /// Stable id for the incoming order. Only used when it rests.
    pub order_id: Option<String>,
    /// Self-trade prevention: pass over resting orders whose owner is the
    /// taker, leaving them in place, and match the next order behind them.
    /// Off, the book matches whoever is first in the queue, as the
    /// reference implementation does.
    pub skip_own: bool,
    /// Write out the ids of house levels a fill takes. Off, a fill against
    /// the house carries an empty `maker_order_id`.
    pub house_ids: bool,
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct OrderBook {
    pub company_id: String,
    /// Descending by price, then ascending by sequence.
    pub bids: Vec<BookOrder>,
    /// Ascending by price, then ascending by sequence.
    pub asks: Vec<BookOrder>,
    /// Last traded price. `None` until the book has printed a trade.
    pub last_price: Option<f64>,
    pub sequence: u64,
    /// Resting orders kept per side. [`MAX_DEPTH_PER_SIDE`] for every book
    /// the reference built, which is every book the market settles through.
    ///
    /// Larger only for the book an agent executes against when the depth
    /// tail is on (`ModelParams::book_depth_coefficient`): that book carries
    /// the maker's ladder, the latent levels behind it and every agent's
    /// resting orders, and trimming it at 32 would drop the far levels a
    /// large order is priced against, which is the silent cut-off the tail
    /// exists to remove. Trimming still drops the worst-priced orders first.
    pub cap: usize,
}

impl OrderBook {
    pub fn new(company_id: impl Into<String>, last_price: Option<f64>) -> Self {
        Self {
            company_id: company_id.into(),
            bids: Vec::new(),
            asks: Vec::new(),
            last_price,
            sequence: 0,
            cap: MAX_DEPTH_PER_SIDE,
        }
    }

    /// Empty this book back to what [`OrderBook::new`] builds, keeping the
    /// allocations its vectors and id hold, so a caller that builds a book
    /// per settlement can reuse one. Every field is named, so a field added
    /// to the struct is a compile error here until it is reset too.
    pub fn reset(&mut self, company_id: &str, last_price: Option<f64>) {
        let OrderBook {
            company_id: id,
            bids,
            asks,
            last_price: last,
            sequence,
            cap,
        } = self;
        id.clear();
        id.push_str(company_id);
        bids.clear();
        asks.clear();
        *last = last_price;
        *sequence = 0;
        *cap = MAX_DEPTH_PER_SIDE;
    }

    /// The same book with a different per-side cap. See [`OrderBook::cap`].
    pub fn with_cap(mut self, cap: usize) -> Self {
        self.cap = cap;
        self
    }

    pub fn best_bid(&self) -> Option<f64> {
        self.bids.first().map(|o| o.price)
    }

    pub fn best_ask(&self) -> Option<f64> {
        self.asks.first().map(|o| o.price)
    }

    /// `None` unless BOTH sides are populated.
    pub fn mid_price(&self) -> Option<f64> {
        match (self.best_bid(), self.best_ask()) {
            (Some(b), Some(a)) => Some((b + a) / 2.0),
            _ => None,
        }
    }

    /// `None` unless both sides are populated.
    pub fn spread(&self) -> Option<f64> {
        match (self.best_bid(), self.best_ask()) {
            (Some(b), Some(a)) => Some(a - b),
            _ => None,
        }
    }

    /// Total shares resting on a side.
    ///
    /// Folded explicitly from `0.0` rather than using `Iterator::sum`, and the
    /// difference is observable. Rust's `Sum for f64` uses **`-0.0`** as its
    /// identity — a deliberate choice, since `-0.0 + x == x` preserves sign
    /// where `0.0 + (-0.0)` would not. The reference implementation starts from `let total =
    /// 0`, which is `+0.0`.
    ///
    /// So on an empty side `sum()` returns `-0.0` and the original returns
    /// `+0.0`. They compare equal under `==` and print the same at most
    /// precisions, but the bit patterns differ, and `1.0 / -0.0` is negative
    /// infinity where `1.0 / 0.0` is positive. Caught by the parity gate on
    /// step 0 of the replay — a good advertisement for comparing bits rather
    /// than values.
    pub fn depth(&self, side: Side) -> f64 {
        let mut total = 0.0;
        for o in self.side(side) {
            total += o.remaining;
        }
        total
    }

    fn side(&self, side: Side) -> &Vec<BookOrder> {
        match side {
            Side::Buy => &self.bids,
            Side::Sell => &self.asks,
        }
    }

    fn side_mut(&mut self, side: Side) -> &mut Vec<BookOrder> {
        match side {
            Side::Buy => &mut self.bids,
            Side::Sell => &mut self.asks,
        }
    }

    /// Aggregate a side into price levels, best-first.
    ///
    /// Note the loop shape: the level cap is checked only when opening a NEW
    /// level, so an order at the same price as the last level is always merged
    /// even once `max_levels` is reached. Faithful to the original, where the
    /// `break` sits inside the else-branch.
    pub fn price_levels(&self, side: Side, max_levels: usize) -> Vec<PriceLevel> {
        let mut levels: Vec<PriceLevel> = Vec::new();
        for o in self.side(side) {
            if let Some(last) = levels.last_mut() {
                if last.price == o.price {
                    last.quantity += o.remaining;
                    last.orders += 1;
                    continue;
                }
            }
            if levels.len() >= max_levels {
                break;
            }
            levels.push(PriceLevel {
                price: o.price,
                quantity: o.remaining,
                orders: 1,
            });
        }
        levels
    }

    /// Insert preserving price-time priority.
    ///
    /// Advances past everything that ranks better than OR EQUAL TO the
    /// newcomer, so an order at an existing price lands behind the queue at
    /// that price. That is time priority, and it falls out of the comparison
    /// being strict — using `>=` here would silently give newcomers queue
    /// precedence over orders that arrived first.
    fn insert_resting(&mut self, order: BookOrder) {
        let is_buy = order.side == Side::Buy;
        let price = order.price;
        let cap = self.cap;
        let side = self.side_mut(order.side);

        let mut i = 0;
        while i < side.len() {
            let better = if is_buy {
                price > side[i].price
            } else {
                price < side[i].price
            };
            if better {
                break;
            }
            i += 1;
        }
        side.insert(i, order);

        // Trim the far end. The worst-priced orders are the ones that would
        // never trade, so dropping them cannot change any fill.
        if side.len() > cap {
            side.truncate(cap);
        }
    }

    /// Does `taker_price` cross `resting_price`? A market order crosses all.
    fn crosses(side: Side, taker_price: Option<f64>, resting_price: f64) -> bool {
        match taker_price {
            None => true,
            Some(p) => match side {
                Side::Buy => p >= resting_price,
                Side::Sell => p <= resting_price,
            },
        }
    }

    /// Submit an order and match it against the book, mutating in place.
    pub fn submit(
        &mut self,
        side: Side,
        quantity: f64,
        taker_id: &str,
        options: SubmitOptions,
    ) -> MatchResult {
        let mut fills: Vec<Fill> = Vec::new();
        let (unfilled, resting) = self.match_into(side, quantity, taker_id, options, &mut fills);
        let average_price = if fills.is_empty() {
            None
        } else {
            let mut notional = 0.0;
            let mut shares = 0.0;
            for f in &fills {
                notional += f.price * f.quantity;
                shares += f.quantity;
            }
            Some(notional / shares)
        };

        MatchResult {
            fills,
            unfilled,
            average_price,
            resting,
        }
    }

    /// [`OrderBook::submit`]'s matching, appending its fills to `fills`, so a
    /// caller that submits many orders can reuse one buffer. Returns the
    /// unfilled shares and the remainder posted, as `submit` reports them.
    pub(crate) fn match_into(
        &mut self,
        side: Side,
        quantity: f64,
        taker_id: &str,
        options: SubmitOptions,
        fills: &mut Vec<Fill>,
    ) -> (f64, Option<BookOrder>) {
        let limit_price = options.limit_price;

        // `!(q > 0)` and not `q <= 0` — the negation also rejects NaN.
        if !(quantity > 0.0) {
            return (0.0, None);
        }

        let mut remaining = quantity;
        let opposite_side = match side {
            Side::Buy => Side::Sell,
            Side::Sell => Side::Buy,
        };

        // `at` is the queue position being matched. It stays 0 unless
        // `skip_own` passes over the taker's own orders, so the reference
        // path is unchanged.
        let mut at = 0;
        while remaining > 0.0 && at < self.side(opposite_side).len() {
            let maker_price = self.side(opposite_side)[at].price;
            if !Self::crosses(side, limit_price, maker_price) {
                break;
            }
            if options.skip_own && self.side(opposite_side)[at].owner_id == taker_id {
                at += 1;
                continue;
            }

            let (traded, exhausted, maker_order_id, maker_id) = {
                let company = &self.company_id;
                let maker = match opposite_side {
                    Side::Buy => &mut self.bids[at],
                    Side::Sell => &mut self.asks[at],
                };
                let traded = mathx::min(remaining, maker.remaining);
                maker.remaining -= traded;
                let id = if options.house_ids || !is_house_owner(&maker.owner_id) {
                    maker.id_in(company)
                } else {
                    String::new()
                };
                (traded, maker.remaining <= 0.0, id, maker.owner_id.clone())
            };

            remaining -= traded;
            fills.push(Fill {
                price: maker_price,
                quantity: traded,
                maker_order_id,
                maker_id,
                taker_id: owner_id(taker_id),
                taker_side: side,
            });

            self.last_price = Some(maker_price);
            if exhausted {
                self.side_mut(opposite_side).remove(at);
            }
        }

        let mut resting: Option<BookOrder> = None;
        if remaining > 0.0 {
            if let (true, Some(limit)) = (options.post_remainder, limit_price) {
                let order = BookOrder {
                    id: options.order_id.map_or(OrderId::Sequenced, OrderId::Given),
                    piece: 0,
                    side,
                    price: limit,
                    quantity,
                    remaining,
                    sequence: self.sequence,
                    owner_id: owner_id(taker_id),
                };
                self.sequence += 1;
                self.insert_resting(order.clone());
                resting = Some(order);
                // Parked in the book rather than rejected, so it is not
                // "unfilled" from the caller's point of view.
                remaining = 0.0;
            }
        }

        (remaining, resting)
    }

    /// Rest a passive order without attempting to cross. Used by makers.
    pub fn post_limit(
        &mut self,
        side: Side,
        price: f64,
        quantity: f64,
        owner_id: &str,
        order_id: Option<String>,
    ) -> Option<BookOrder> {
        if !(quantity > 0.0) || !(price > 0.0) {
            return None;
        }
        let order = self.resting_order(side, price, quantity, owner_id, order_id);
        self.insert_resting(order.clone());
        Some(order)
    }

    /// [`OrderBook::post_limit`] for a caller that does not need the order
    /// back: the same book, without the copy.
    pub fn rest_limit(&mut self, side: Side, price: f64, quantity: f64, owner_id: &str) {
        if !(quantity > 0.0) || !(price > 0.0) {
            return;
        }
        let order = self.resting_order(side, price, quantity, owner_id, None);
        self.insert_resting(order);
    }

    /// A new resting order, taking the book's next sequence number.
    fn resting_order(
        &mut self,
        side: Side,
        price: f64,
        quantity: f64,
        owner_id: &str,
        order_id: Option<String>,
    ) -> BookOrder {
        let order = BookOrder {
            id: order_id.map_or(OrderId::Sequenced, OrderId::Given),
            piece: 0,
            side,
            price,
            quantity,
            remaining: quantity,
            sequence: self.sequence,
            owner_id: self::owner_id(owner_id),
        };
        self.sequence += 1;
        order
    }

    /// Remove a resting order by id.
    pub fn cancel_order(&mut self, order_id: &str) -> bool {
        for side in [Side::Buy, Side::Sell] {
            let company = &self.company_id;
            let orders = match side {
                Side::Buy => &mut self.bids,
                Side::Sell => &mut self.asks,
            };
            if let Some(idx) = orders.iter().position(|o| o.id_in(company) == order_id) {
                orders.remove(idx);
                return true;
            }
        }
        false
    }

    /// Remove every resting order owned by `owner_id` — a maker re-quote.
    pub fn cancel_all_for(&mut self, owner_id: &str) -> u32 {
        let mut removed = 0;
        for side in [Side::Buy, Side::Sell] {
            let orders = self.side_mut(side);
            let before = orders.len();
            orders.retain(|o| o.owner_id != owner_id);
            removed += (before - orders.len()) as u32;
        }
        removed
    }

    /// Cost to sweep `quantity` shares, walking real depth.
    ///
    /// This replaces the modelled market-impact coefficient: impact stops
    /// being a parameter and becomes a consequence of resting liquidity.
    /// `None` when nothing at all could be filled.
    pub fn sweep_cost(&self, side: Side, quantity: f64) -> Option<SweepCost> {
        let opposite = match side {
            Side::Buy => Side::Sell,
            Side::Sell => Side::Buy,
        };
        let mut remaining = quantity;
        let mut notional = 0.0;
        let mut worst_price = 0.0;

        for o in self.side(opposite) {
            if remaining <= 0.0 {
                break;
            }
            let traded = mathx::min(remaining, o.remaining);
            notional += o.price * traded;
            remaining -= traded;
            worst_price = o.price;
        }

        let filled = quantity - remaining;
        if filled <= 0.0 {
            return None;
        }
        Some(SweepCost {
            average_price: notional / filled,
            worst_price,
            filled,
        })
    }

    /// Append a maker level that is ALREADY in priority order.
    ///
    /// `post_limit` runs an insertion scan per order, which is quadratic when
    /// building a ladder — and the ladder is generated best-first, so the scan
    /// always walks to the end and finds nothing. Across 108 companies every
    /// game-minute that dominated the tick cost (measured in the original:
    /// 0.59 of 0.83 ms/tick).
    ///
    /// Callers MUST append in priority order. Anything out of order goes
    /// through `post_limit` instead.
    pub fn append_maker_level(
        &mut self,
        side: Side,
        price: f64,
        quantity: f64,
        owner_id: &str,
    ) -> Option<BookOrder> {
        if self.push_maker_level(side, price, quantity, owner_id) {
            self.side(side).last().cloned()
        } else {
            None
        }
    }

    /// [`OrderBook::append_maker_level`] without handing back a copy of
    /// the order: `true` when the level was appended.
    ///
    /// The engine rebuilds every name's maker ladder on every tick and
    /// never reads the returned order, so the copy was two string
    /// allocations per level thrown away. The id is written straight into
    /// a string sized for it rather than through `format!`, whose capacity
    /// estimate starts small and grows; the text is the same
    /// `"{company_id}-{sequence}"`. Together these were most of the
    /// ladder's cost in a `sample` of `run_days` on pt-v20.
    pub fn push_maker_level(
        &mut self,
        side: Side,
        price: f64,
        quantity: f64,
        owner_id: &str,
    ) -> bool {
        if !(quantity > 0.0) || !(price > 0.0) {
            return false;
        }
        if self.side(side).len() >= self.cap {
            return false;
        }
        let order = BookOrder {
            id: OrderId::Sequenced,
            piece: 0,
            side,
            price,
            quantity,
            remaining: quantity,
            sequence: self.sequence,
            owner_id: self::owner_id(owner_id),
        };
        self.sequence += 1;
        self.side_mut(side).push(order);
        true
    }
}

/// `format!("{company_id}-{sequence}")`, into a string allocated once at
/// its final length.
fn sequenced_id(company_id: &str, sequence: u64) -> String {
    let mut digits = [0u8; 20];
    let mut i = digits.len();
    let mut n = sequence;
    loop {
        i -= 1;
        digits[i] = b'0' + (n % 10) as u8;
        n /= 10;
        if n == 0 {
            break;
        }
    }
    let mut id = String::with_capacity(company_id.len() + 1 + (digits.len() - i));
    id.push_str(company_id);
    id.push('-');
    // ASCII digits only, so this is valid UTF-8.
    id.push_str(std::str::from_utf8(&digits[i..]).unwrap_or("0"));
    id
}

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

    fn book() -> OrderBook {
        OrderBook::new("TEST", None)
    }

    #[test]
    fn bids_rank_by_descending_price_then_arrival() {
        let mut b = book();
        b.post_limit(Side::Buy, 100.0, 10.0, "a", None);
        b.post_limit(Side::Buy, 101.0, 10.0, "b", None);
        b.post_limit(Side::Buy, 100.0, 10.0, "c", None); // ties with `a`
        let owners: Vec<&str> = b.bids.iter().map(|o| &*o.owner_id).collect();
        assert_eq!(
            owners,
            vec!["b", "a", "c"],
            "equal prices must keep arrival order"
        );
    }

    #[test]
    fn asks_rank_by_ascending_price_then_arrival() {
        let mut b = book();
        b.post_limit(Side::Sell, 101.0, 10.0, "a", None);
        b.post_limit(Side::Sell, 100.0, 10.0, "b", None);
        b.post_limit(Side::Sell, 101.0, 10.0, "c", None);
        let owners: Vec<&str> = b.asks.iter().map(|o| &*o.owner_id).collect();
        assert_eq!(owners, vec!["b", "a", "c"]);
    }

    /// The taker gets the maker's price, not its own — this is where price
    /// improvement comes from.
    #[test]
    fn trades_print_at_the_makers_price() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 10.0, "maker", None);
        let r = b.submit(
            Side::Buy,
            10.0,
            "taker",
            SubmitOptions {
                limit_price: Some(105.0),
                ..Default::default()
            },
        );
        assert_eq!(r.fills.len(), 1);
        assert_eq!(
            r.fills[0].price, 100.0,
            "should fill at 100, not the 105 bid"
        );
        assert_eq!(b.last_price, Some(100.0));
    }

    /// With `skip_own`, a taker passes over its own resting orders, leaves
    /// them whole, and matches the next order in the queue. Without it the
    /// book matches whoever is first, as the reference does.
    #[test]
    fn skip_own_passes_over_the_takers_own_orders() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 10.0, "me", Some("me-0".into()));
        b.post_limit(Side::Sell, 100.0, 4.0, "other", None);
        b.post_limit(Side::Sell, 101.0, 10.0, "me", Some("me-1".into()));
        b.post_limit(Side::Sell, 102.0, 10.0, "other", None);
        let r = b.submit(
            Side::Buy,
            20.0,
            "me",
            SubmitOptions { limit_price: Some(101.5), skip_own: true, ..Default::default() },
        );
        let got: Vec<_> = r.fills.iter().map(|f| (f.price, f.quantity, &*f.maker_id)).collect();
        assert_eq!(got, vec![(100.0, 4.0, "other")]);
        assert_eq!(r.unfilled, 16.0);
        let left: Vec<_> = b.asks.iter().map(|o| (o.id_in(&b.company_id), o.remaining)).collect();
        assert_eq!(left[..2], [("me-0".to_string(), 10.0), ("me-1".to_string(), 10.0)]);

        let mut plain = book();
        plain.post_limit(Side::Sell, 100.0, 10.0, "me", None);
        let r = plain.submit(Side::Buy, 5.0, "me", SubmitOptions::default());
        assert_eq!(r.fills[0].maker_id, "me", "off, the reference matches the queue as it stands");
    }

    /// Slippage as a consequence of depth rather than a coefficient.
    #[test]
    fn sweeping_multiple_levels_pays_a_worse_average() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 10.0, "m1", None);
        b.post_limit(Side::Sell, 101.0, 10.0, "m2", None);
        b.post_limit(Side::Sell, 102.0, 10.0, "m3", None);
        let r = b.submit(Side::Buy, 25.0, "taker", SubmitOptions::default());
        assert_eq!(r.fills.len(), 3);
        assert_eq!(r.unfilled, 0.0);
        // (100*10 + 101*10 + 102*5) / 25
        assert_eq!(r.average_price, Some((1000.0 + 1010.0 + 510.0) / 25.0));
    }

    #[test]
    fn a_market_order_never_rests() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 5.0, "m", None);
        let r = b.submit(
            Side::Buy,
            20.0,
            "taker",
            SubmitOptions {
                post_remainder: true,
                ..Default::default()
            },
        );
        assert_eq!(r.unfilled, 15.0);
        assert!(r.resting.is_none());
        assert!(b.bids.is_empty());
    }

    /// A posted remainder is accepted, not rejected, so it is not "unfilled".
    #[test]
    fn a_posted_remainder_counts_as_filled() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 5.0, "m", None);
        let r = b.submit(
            Side::Buy,
            20.0,
            "taker",
            SubmitOptions {
                limit_price: Some(100.0),
                post_remainder: true,
                order_id: None,
                skip_own: false,
                house_ids: false,
            },
        );
        assert_eq!(r.unfilled, 0.0);
        assert_eq!(r.resting.as_ref().unwrap().remaining, 15.0);
        assert_eq!(b.bids.len(), 1);
    }

    #[test]
    fn a_non_crossing_limit_does_not_trade() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 10.0, "m", None);
        let r = b.submit(
            Side::Buy,
            10.0,
            "taker",
            SubmitOptions {
                limit_price: Some(99.0),
                ..Default::default()
            },
        );
        assert!(r.fills.is_empty());
        assert_eq!(r.unfilled, 10.0);
    }

    /// NaN must be rejected by `!(q > 0)`, which `q <= 0` would let through.
    #[test]
    fn nan_and_nonpositive_sizes_are_rejected() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 10.0, "m", None);
        for q in [0.0, -5.0, f64::NAN] {
            let r = b.submit(Side::Buy, q, "taker", SubmitOptions::default());
            assert!(r.fills.is_empty(), "quantity {q} should not trade");
            assert_eq!(r.unfilled, 0.0);
        }
        assert!(b
            .post_limit(Side::Buy, 100.0, f64::NAN, "x", None)
            .is_none());
        assert!(b.post_limit(Side::Buy, f64::NAN, 10.0, "x", None).is_none());
    }

    #[test]
    fn depth_is_capped_and_trimmed_from_the_worst_end() {
        let mut b = book();
        // Ascending bids: each new one is the best, pushing the worst out.
        for i in 0..(MAX_DEPTH_PER_SIDE + 10) {
            b.post_limit(Side::Buy, 100.0 + i as f64, 1.0, "m", None);
        }
        assert_eq!(b.bids.len(), MAX_DEPTH_PER_SIDE);
        assert_eq!(b.bids[0].price, 100.0 + (MAX_DEPTH_PER_SIDE + 9) as f64);
    }

    #[test]
    fn sequenced_id_matches_format() {
        for &n in &[0u64, 1, 9, 10, 99, 100, 12345, u64::MAX] {
            assert_eq!(sequenced_id("ACME", n), format!("{}-{}", "ACME", n));
        }
        assert_eq!(sequenced_id("", 7), "-7");
    }

    #[test]
    fn append_maker_level_refuses_past_the_cap() {
        let mut b = book();
        for i in 0..MAX_DEPTH_PER_SIDE {
            assert!(b
                .append_maker_level(Side::Buy, 100.0 - i as f64, 1.0, "mm")
                .is_some());
        }
        assert!(b.append_maker_level(Side::Buy, 1.0, 1.0, "mm").is_none());
    }

    #[test]
    fn cancel_all_for_removes_both_sides() {
        let mut b = book();
        b.post_limit(Side::Buy, 99.0, 1.0, "mm", None);
        b.post_limit(Side::Sell, 101.0, 1.0, "mm", None);
        b.post_limit(Side::Buy, 98.0, 1.0, "other", None);
        assert_eq!(b.cancel_all_for("mm"), 2);
        assert_eq!(b.bids.len(), 1);
        assert!(b.asks.is_empty());
    }

    #[test]
    fn sweep_cost_reports_none_when_the_book_is_empty() {
        let b = book();
        assert!(b.sweep_cost(Side::Buy, 10.0).is_none());
    }

    #[test]
    fn sweep_cost_reports_a_partial_fill() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 5.0, "m", None);
        let s = b.sweep_cost(Side::Buy, 20.0).unwrap();
        assert_eq!(s.filled, 5.0);
        assert_eq!(s.average_price, 100.0);
        assert_eq!(s.worst_price, 100.0);
    }

    /// Shares in equals shares out: nothing is created or destroyed by a match.
    #[test]
    fn matching_conserves_shares() {
        let mut b = book();
        b.post_limit(Side::Sell, 100.0, 7.0, "m1", None);
        b.post_limit(Side::Sell, 101.0, 9.0, "m2", None);
        let before = b.depth(Side::Sell);
        let r = b.submit(Side::Buy, 12.0, "taker", SubmitOptions::default());
        let traded: f64 = r.fills.iter().map(|f| f.quantity).sum();
        assert_eq!(traded + b.depth(Side::Sell), before);
        assert_eq!(traded, 12.0);
    }
}