nautilus-model 0.55.0

Domain model for the Nautilus trading engine
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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Represents a discrete price level in an order book.

use std::cmp::Ordering;

use indexmap::IndexMap;
use nautilus_core::UnixNanos;
use rust_decimal::Decimal;

use crate::{
    data::order::{BookOrder, OrderId},
    enums::OrderSideSpecified,
    orderbook::{BookIntegrityError, BookPrice},
    types::{fixed::FIXED_SCALAR, quantity::QuantityRaw},
};

/// Represents a discrete price level in an order book.
///
/// Orders are stored in an [`IndexMap`] which preserves FIFO (insertion) order.
#[derive(Clone, Debug, Eq)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct BookLevel {
    pub price: BookPrice,
    pub(crate) orders: IndexMap<OrderId, BookOrder>,
}

impl BookLevel {
    /// Creates a new [`BookLevel`] instance.
    #[must_use]
    pub fn new(price: BookPrice) -> Self {
        Self {
            price,
            orders: IndexMap::new(),
        }
    }

    /// Creates a new [`BookLevel`] from an order, using the order's price and side.
    #[must_use]
    pub fn from_order(order: BookOrder) -> Self {
        let mut level = Self {
            price: order.to_book_price(),
            orders: IndexMap::new(),
        };
        level.add(order);
        level
    }

    pub fn side(&self) -> OrderSideSpecified {
        self.price.side
    }

    /// Returns the number of orders at this price level.
    #[must_use]
    pub fn len(&self) -> usize {
        self.orders.len()
    }

    /// Returns true if this price level has no orders.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.orders.is_empty()
    }

    /// Returns a reference to the first order at this price level in FIFO order.
    #[inline]
    #[must_use]
    pub fn first(&self) -> Option<&BookOrder> {
        self.orders.get_index(0).map(|(_key, order)| order)
    }

    /// Returns an iterator over the orders at this price level in FIFO order.
    pub fn iter(&self) -> impl Iterator<Item = &BookOrder> {
        self.orders.values()
    }

    /// Returns all orders at this price level in FIFO insertion order.
    #[must_use]
    pub fn get_orders(&self) -> Vec<BookOrder> {
        self.orders.values().copied().collect()
    }

    /// Returns the total size of all orders at this price level as a float.
    #[must_use]
    pub fn size(&self) -> f64 {
        self.orders.values().map(|o| o.size.as_f64()).sum()
    }

    /// Returns the total size of all orders at this price level as raw integer units.
    #[must_use]
    pub fn size_raw(&self) -> QuantityRaw {
        self.orders.values().map(|o| o.size.raw).sum()
    }

    /// Returns the total size of all orders at this price level as a decimal.
    #[must_use]
    pub fn size_decimal(&self) -> Decimal {
        self.orders.values().map(|o| o.size.as_decimal()).sum()
    }

    /// Returns the total exposure (price * size) of all orders at this price level as a float.
    #[must_use]
    pub fn exposure(&self) -> f64 {
        self.orders
            .values()
            .map(|o| o.price.as_f64() * o.size.as_f64())
            .sum()
    }

    /// Returns the total exposure (price * size) of all orders at this price level as raw integer units.
    ///
    /// Saturates at `QuantityRaw::MAX` if the total exposure would overflow.
    #[must_use]
    pub fn exposure_raw(&self) -> QuantityRaw {
        self.orders
            .values()
            .map(|o| {
                let exposure_f64 = o.price.as_f64() * o.size.as_f64();
                debug_assert!(
                    exposure_f64.is_finite(),
                    "Exposure calculation resulted in non-finite value for order {}: price={}, size={}",
                    o.order_id,
                    o.price,
                    o.size
                );

                let scaled = exposure_f64 * FIXED_SCALAR;
                if scaled >= QuantityRaw::MAX as f64 {
                    QuantityRaw::MAX
                } else if scaled < 0.0 {
                    0
                } else {
                    scaled as QuantityRaw
                }
            })
            .fold(0, |acc, val| acc.saturating_add(val))
    }

    /// Adds multiple orders to this price level in FIFO order. Orders must match the level's price.
    pub fn add_bulk(&mut self, orders: &[BookOrder]) {
        for order in orders {
            self.add(*order);
        }
    }

    /// Adds an order to this price level. Order must match the level's price.
    pub fn add(&mut self, order: BookOrder) {
        debug_assert_eq!(order.price, self.price.value);

        if !order.size.is_positive() {
            log::warn!(
                "Attempted to add order with non-positive size: order_id={order_id}, size={size}, ignoring",
                order_id = order.order_id,
                size = order.size
            );
            return;
        }

        self.orders.insert(order.order_id, order);
    }

    /// Updates an existing order at this price level. Updated order must match the level's price.
    /// Removes the order if size becomes zero.
    pub fn update(&mut self, order: BookOrder) {
        debug_assert_eq!(order.price, self.price.value);

        if order.size.raw == 0 {
            // Updating non-existent order to zero size is a no-op, which is valid
            self.orders.shift_remove(&order.order_id);
        } else {
            debug_assert!(
                order.size.is_positive(),
                "Order size must be positive: {}",
                order.size
            );
            self.orders.insert(order.order_id, order);
        }
    }

    /// Deletes an order from this price level.
    pub fn delete(&mut self, order: &BookOrder) {
        self.orders.shift_remove(&order.order_id);
    }

    /// Removes an order by its ID.
    ///
    /// # Panics
    ///
    /// Panics if no order with the given `order_id` exists at this level.
    pub fn remove_by_id(&mut self, order_id: OrderId, sequence: u64, ts_event: UnixNanos) {
        assert!(
            self.orders.shift_remove(&order_id).is_some(),
            "{}",
            &BookIntegrityError::OrderNotFound(order_id, sequence, ts_event)
        );
    }
}

impl PartialEq for BookLevel {
    fn eq(&self, other: &Self) -> bool {
        self.price == other.price
    }
}

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

impl Ord for BookLevel {
    fn cmp(&self, other: &Self) -> Ordering {
        self.price.cmp(&other.price)
    }
}

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

    use crate::{
        data::order::BookOrder,
        enums::{OrderSide, OrderSideSpecified},
        orderbook::{BookLevel, BookPrice},
        types::{Price, Quantity, fixed::FIXED_SCALAR, quantity::QuantityRaw},
    };

    #[rstest]
    fn test_empty_level() {
        let level = BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        assert!(level.first().is_none());
        assert_eq!(level.side(), OrderSideSpecified::Buy);
    }

    #[rstest]
    fn test_level_from_order() {
        let order = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        let level = BookLevel::from_order(order);

        assert_eq!(level.price.value, Price::from("1.00"));
        assert_eq!(level.price.side, OrderSideSpecified::Buy);
        assert_eq!(level.len(), 1);
        assert_eq!(level.first().unwrap(), &order);
        assert_eq!(level.size(), 10.0);
    }

    #[rstest]
    #[should_panic(expected = "assertion `left == right` failed")]
    fn test_add_order_incorrect_price_level() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let incorrect_price_order =
            BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 1);
        level.add(incorrect_price_order);
    }

    #[rstest]
    #[should_panic(expected = "assertion `left == right` failed")]
    fn test_add_bulk_orders_incorrect_price() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let orders = [
            BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1),
            BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 2), // Incorrect price
        ];
        level.add_bulk(&orders);
    }

    #[rstest]
    fn test_add_bulk_empty() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        level.add_bulk(&[]);
        assert!(level.is_empty());
    }

    #[rstest]
    fn test_comparisons_bid_side() {
        let level0 = BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let level1 = BookLevel::new(BookPrice::new(Price::from("1.01"), OrderSideSpecified::Buy));
        assert_eq!(level0, level0);
        assert!(level0 > level1);
    }

    #[rstest]
    fn test_comparisons_ask_side() {
        let level0 = BookLevel::new(BookPrice::new(
            Price::from("1.00"),
            OrderSideSpecified::Sell,
        ));
        let level1 = BookLevel::new(BookPrice::new(
            Price::from("1.01"),
            OrderSideSpecified::Sell,
        ));
        assert_eq!(level0, level0);
        assert!(level0 < level1);
    }

    #[rstest]
    fn test_book_level_sorting() {
        let mut levels = [
            BookLevel::new(BookPrice::new(
                Price::from("1.00"),
                OrderSideSpecified::Sell,
            )),
            BookLevel::new(BookPrice::new(
                Price::from("1.02"),
                OrderSideSpecified::Sell,
            )),
            BookLevel::new(BookPrice::new(
                Price::from("1.01"),
                OrderSideSpecified::Sell,
            )),
        ];
        levels.sort();
        assert_eq!(levels[0].price.value, Price::from("1.00"));
        assert_eq!(levels[1].price.value, Price::from("1.01"));
        assert_eq!(levels[2].price.value, Price::from("1.02"));
    }

    #[rstest]
    fn test_add_single_order() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 0);

        level.add(order);
        assert!(!level.is_empty());
        assert_eq!(level.len(), 1);
        assert_eq!(level.size(), 10.0);
        assert_eq!(level.first().unwrap(), &order);
    }

    #[rstest]
    fn test_add_multiple_orders() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(level.len(), 2);
        assert_eq!(level.size(), 30.0);
        assert_eq!(level.exposure(), 60.0);
        assert_eq!(level.first().unwrap(), &order1);
    }

    #[rstest]
    fn test_get_orders() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(20), 2);

        level.add(order1);
        level.add(order2);

        let orders = level.get_orders();
        assert_eq!(orders.len(), 2);
        assert_eq!(orders[0], order1); // Checks FIFO order maintained
        assert_eq!(orders[1], order2);
    }

    #[rstest]
    fn test_iter_returns_fifo() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(20), 2);
        level.add(order1);
        level.add(order2);

        let orders: Vec<_> = level.iter().copied().collect();
        assert_eq!(orders, vec![order1, order2]);
    }

    #[rstest]
    fn test_update_order() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(20), 0);

        level.add(order1);
        level.update(order2);
        assert_eq!(level.len(), 1);
        assert_eq!(level.size(), 20.0);
        assert_eq!(level.exposure(), 20.0);
    }

    #[rstest]
    fn test_update_inserts_if_missing() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        level.update(order);
        assert_eq!(level.len(), 1);
        assert_eq!(level.first().unwrap(), &order);
    }

    #[rstest]
    fn test_update_zero_size_nonexistent() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::zero(0), 1);
        level.update(order);
        assert_eq!(level.len(), 0);
    }

    #[rstest]
    fn test_fifo_order_after_updates() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));

        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(20), 2);

        level.add(order1);
        level.add(order2);

        // Update order1 size
        let updated_order1 =
            BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(15), 1);
        level.update(updated_order1);

        let orders = level.get_orders();
        assert_eq!(orders.len(), 2);
        assert_eq!(orders[0], updated_order1); // First order still first
        assert_eq!(orders[1], order2); // Second order still second
    }

    #[rstest]
    fn test_insertion_order_after_mixed_operations() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(20), 2);
        let order3 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(30), 3);

        level.add(order1);
        level.add(order2);
        level.add(order3);

        // Update order2 (should keep its position)
        let updated_order2 =
            BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(25), 2);
        level.update(updated_order2);

        // Remove order1; order2 (updated) should now be first
        level.delete(&order1);

        let orders = level.get_orders();
        assert_eq!(orders, vec![updated_order2, order3]);
    }

    #[rstest]
    #[should_panic(expected = "assertion `left == right` failed")]
    fn test_update_order_incorrect_price() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));

        // Add initial order at correct price level
        let initial_order =
            BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        level.add(initial_order);

        // Attempt to update with order at incorrect price level
        let updated_order =
            BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);
        level.update(updated_order);
    }

    #[rstest]
    fn test_update_order_with_zero_size() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::zero(0), 0);

        level.add(order1);
        level.update(order2);
        assert_eq!(level.len(), 0);
        assert_eq!(level.size(), 0.0);
        assert_eq!(level.exposure(), 0.0);
    }

    #[rstest]
    fn test_delete_nonexistent_order() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 1);
        level.delete(&order);
        assert_eq!(level.len(), 0);
    }

    #[rstest]
    fn test_delete_order() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1_id = 0;
        let order1 = BookOrder::new(
            OrderSide::Buy,
            Price::from("1.00"),
            Quantity::from(10),
            order1_id,
        );
        let order2_id = 1;
        let order2 = BookOrder::new(
            OrderSide::Buy,
            Price::from("1.00"),
            Quantity::from(20),
            order2_id,
        );

        level.add(order1);
        level.add(order2);
        level.delete(&order1);
        assert_eq!(level.len(), 1);
        assert_eq!(level.size(), 20.0);
        assert!(level.orders.contains_key(&order2_id));
        assert_eq!(level.exposure(), 20.0);
    }

    #[rstest]
    fn test_remove_order_by_id() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1_id = 0;
        let order1 = BookOrder::new(
            OrderSide::Buy,
            Price::from("1.00"),
            Quantity::from(10),
            order1_id,
        );
        let order2_id = 1;
        let order2 = BookOrder::new(
            OrderSide::Buy,
            Price::from("1.00"),
            Quantity::from(20),
            order2_id,
        );

        level.add(order1);
        level.add(order2);
        level.remove_by_id(order2_id, 0, 0.into());
        assert_eq!(level.len(), 1);
        assert!(level.orders.contains_key(&order1_id));
        assert_eq!(level.size(), 10.0);
        assert_eq!(level.exposure(), 10.0);
    }

    #[rstest]
    fn test_add_bulk_orders() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1_id = 0;
        let order1 = BookOrder::new(
            OrderSide::Buy,
            Price::from("2.00"),
            Quantity::from(10),
            order1_id,
        );
        let order2_id = 1;
        let order2 = BookOrder::new(
            OrderSide::Buy,
            Price::from("2.00"),
            Quantity::from(20),
            order2_id,
        );

        let orders = [order1, order2];
        level.add_bulk(&orders);
        assert_eq!(level.len(), 2);
        assert_eq!(level.size(), 30.0);
        assert_eq!(level.exposure(), 60.0);
    }

    #[rstest]
    fn test_maximum_order_id() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));

        let order = BookOrder::new(
            OrderSide::Buy,
            Price::from("1.00"),
            Quantity::from(10),
            u64::MAX,
        );
        level.add(order);

        assert_eq!(level.len(), 1);
        assert_eq!(level.first().unwrap(), &order);
    }

    #[rstest]
    #[should_panic(
        expected = "Integrity error: order not found: order_id=1, sequence=2, ts_event=3"
    )]
    fn test_remove_nonexistent_order() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        level.remove_by_id(1, 2, 3.into());
    }

    #[rstest]
    fn test_size() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("1.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("1.00"), Quantity::from(15), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(level.size(), 25.0);
    }

    #[rstest]
    fn test_size_raw() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(
            level.size_raw(),
            (30.0 * FIXED_SCALAR).round() as QuantityRaw
        );
    }

    #[rstest]
    fn test_size_decimal() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(level.size_decimal(), dec!(30.0));
    }

    #[rstest]
    fn test_exposure() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(level.exposure(), 60.0);
    }

    #[rstest]
    fn test_exposure_raw() {
        let mut level =
            BookLevel::new(BookPrice::new(Price::from("2.00"), OrderSideSpecified::Buy));
        let order1 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(10), 0);
        let order2 = BookOrder::new(OrderSide::Buy, Price::from("2.00"), Quantity::from(20), 1);

        level.add(order1);
        level.add(order2);
        assert_eq!(
            level.exposure_raw(),
            (60.0 * FIXED_SCALAR).round() as QuantityRaw
        );
    }

    #[rstest]
    fn test_exposure_raw_saturates_on_overflow() {
        // Test that exposure_raw saturates at QuantityRaw::MAX instead of wrapping
        // Use values whose product * FIXED_SCALAR overflows QuantityRaw
        #[cfg(feature = "high-precision")]
        let (price_str, qty_str) = ("1000000000000.00", "1000000000000.00");
        #[cfg(not(feature = "high-precision"))]
        let (price_str, qty_str) = ("100000000.00", "1000000000.00");

        let mut level = BookLevel::new(BookPrice::new(
            Price::from(price_str),
            OrderSideSpecified::Buy,
        ));

        // Create an order with large price and quantity that would overflow QuantityRaw
        let order = BookOrder::new(
            OrderSide::Buy,
            Price::from(price_str),
            Quantity::from(qty_str),
            0,
        );

        level.add(order);

        // Should saturate at max value instead of wrapping around
        let result = level.exposure_raw();
        assert_eq!(result, QuantityRaw::MAX);
    }

    #[rstest]
    fn test_exposure_raw_sum_saturates_on_overflow() {
        // Test that summing exposures saturates instead of wrapping
        #[cfg(feature = "high-precision")]
        let (price_str, qty_str, count) = ("10000000000000.00", "10000000000000.00", 100);
        #[cfg(not(feature = "high-precision"))]
        let (price_str, qty_str, count) = ("1000000000.00", "1000000000.00", 100);

        let mut level = BookLevel::new(BookPrice::new(
            Price::from(price_str),
            OrderSideSpecified::Buy,
        ));

        // Add multiple large orders that together would overflow when summed
        for i in 0..count {
            let order = BookOrder::new(
                OrderSide::Buy,
                Price::from(price_str),
                Quantity::from(qty_str),
                i,
            );
            level.add(order);
        }

        // Should saturate at max value instead of wrapping around
        let result = level.exposure_raw();
        assert_eq!(result, QuantityRaw::MAX);
    }
}