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
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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! An `OwnBookOrder` for use with tracking own/user orders in L3 order books.
//! It organizes orders into bid and ask ladders, maintains timestamps for state changes,
//! and provides various methods for adding, updating, deleting, and querying orders.

use std::{
    cmp::Ordering,
    collections::BTreeMap,
    fmt::{Debug, Display},
    hash::{Hash, Hasher},
};

use ahash::{AHashMap, AHashSet};
use indexmap::IndexMap;
use nautilus_core::{UnixNanos, time::nanos_since_unix_epoch};
use rust_decimal::Decimal;

use super::{BookViewError, display::pprint_own_book};
use crate::{
    enums::{OrderSideSpecified, OrderStatus, OrderType, TimeInForce},
    identifiers::{ClientOrderId, InstrumentId, TraderId, VenueOrderId},
    orderbook::BookPrice,
    orders::{Order, OrderAny},
    types::{Price, Quantity},
};

/// Represents an own/user order for a book.
///
/// This struct models an order that may be in-flight to the trading venue or actively working,
/// depending on the value of the `status` field.
#[repr(C)]
#[derive(Clone, Copy, 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 OwnBookOrder {
    /// The trader ID.
    pub trader_id: TraderId,
    /// The client order ID.
    pub client_order_id: ClientOrderId,
    /// The venue order ID (if assigned by the venue).
    pub venue_order_id: Option<VenueOrderId>,
    /// The specified order side (BUY or SELL).
    pub side: OrderSideSpecified,
    /// The order price.
    pub price: Price,
    /// The order size.
    pub size: Quantity,
    /// The order type.
    pub order_type: OrderType,
    /// The order time in force.
    pub time_in_force: TimeInForce,
    /// The current order status (SUBMITTED/ACCEPTED/PENDING_CANCEL/PENDING_UPDATE/PARTIALLY_FILLED).
    pub status: OrderStatus,
    /// UNIX timestamp (nanoseconds) when the last order event occurred for this order.
    pub ts_last: UnixNanos,
    /// UNIX timestamp (nanoseconds) when the order was accepted (zero unless accepted).
    pub ts_accepted: UnixNanos,
    /// UNIX timestamp (nanoseconds) when the order was submitted (zero unless submitted).
    pub ts_submitted: UnixNanos,
    /// UNIX timestamp (nanoseconds) when the order was initialized.
    pub ts_init: UnixNanos,
}

impl OwnBookOrder {
    /// Creates a new [`OwnBookOrder`] instance.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        trader_id: TraderId,
        client_order_id: ClientOrderId,
        venue_order_id: Option<VenueOrderId>,
        side: OrderSideSpecified,
        price: Price,
        size: Quantity,
        order_type: OrderType,
        time_in_force: TimeInForce,
        status: OrderStatus,
        ts_last: UnixNanos,
        ts_accepted: UnixNanos,
        ts_submitted: UnixNanos,
        ts_init: UnixNanos,
    ) -> Self {
        Self {
            trader_id,
            client_order_id,
            venue_order_id,
            side,
            price,
            size,
            order_type,
            time_in_force,
            status,
            ts_last,
            ts_accepted,
            ts_submitted,
            ts_init,
        }
    }

    /// Returns a [`BookPrice`] from this order.
    #[must_use]
    pub fn to_book_price(&self) -> BookPrice {
        BookPrice::new(self.price, self.side)
    }

    /// Returns the order exposure as an `f64`.
    #[must_use]
    pub fn exposure(&self) -> f64 {
        self.price.as_f64() * self.size.as_f64()
    }

    /// Returns the signed order exposure as an `f64`.
    #[must_use]
    pub fn signed_size(&self) -> f64 {
        match self.side {
            OrderSideSpecified::Buy => self.size.as_f64(),
            OrderSideSpecified::Sell => -(self.size.as_f64()),
        }
    }
}

impl Ord for OwnBookOrder {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.ts_init
            .cmp(&other.ts_init)
            .then_with(|| self.client_order_id.cmp(&other.client_order_id))
    }
}

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

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

impl Hash for OwnBookOrder {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.client_order_id.hash(state);
    }
}

impl Debug for OwnBookOrder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}(trader_id={}, client_order_id={}, venue_order_id={:?}, side={}, price={}, size={}, order_type={}, time_in_force={}, status={}, ts_last={}, ts_accepted={}, ts_submitted={}, ts_init={})",
            stringify!(OwnBookOrder),
            self.trader_id,
            self.client_order_id,
            self.venue_order_id,
            self.side,
            self.price,
            self.size,
            self.order_type,
            self.time_in_force,
            self.status,
            self.ts_last,
            self.ts_accepted,
            self.ts_submitted,
            self.ts_init,
        )
    }
}

impl Display for OwnBookOrder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{},{},{:?},{},{},{},{},{},{},{},{},{},{}",
            self.trader_id,
            self.client_order_id,
            self.venue_order_id,
            self.side,
            self.price,
            self.size,
            self.order_type,
            self.time_in_force,
            self.status,
            self.ts_last,
            self.ts_accepted,
            self.ts_submitted,
            self.ts_init,
        )
    }
}

#[derive(Clone, Debug)]
#[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 OwnOrderBook {
    /// The instrument ID for the order book.
    pub instrument_id: InstrumentId,
    /// The timestamp of the last event applied to the order book.
    pub ts_last: UnixNanos,
    /// The current count of updates applied to the order book.
    pub update_count: u64,
    pub(crate) bids: OwnBookLadder,
    pub(crate) asks: OwnBookLadder,
}

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

impl Display for OwnOrderBook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}(instrument_id={}, orders={}, update_count={})",
            stringify!(OwnOrderBook),
            self.instrument_id,
            self.bids.cache.len() + self.asks.cache.len(),
            self.update_count,
        )
    }
}

impl OwnOrderBook {
    /// Creates a new [`OwnOrderBook`] instance.
    #[must_use]
    pub fn new(instrument_id: InstrumentId) -> Self {
        Self {
            instrument_id,
            ts_last: UnixNanos::default(),
            update_count: 0,
            bids: OwnBookLadder::new(OrderSideSpecified::Buy),
            asks: OwnBookLadder::new(OrderSideSpecified::Sell),
        }
    }

    fn increment(&mut self, order: &OwnBookOrder) {
        self.ts_last = order.ts_last;
        self.update_count += 1;
    }

    /// Resets the order book to its initial empty state.
    pub fn reset(&mut self) {
        self.bids.clear();
        self.asks.clear();
        self.ts_last = UnixNanos::default();
        self.update_count = 0;
    }

    /// Adds an own order to the book.
    pub fn add(&mut self, order: OwnBookOrder) {
        self.increment(&order);
        match order.side {
            OrderSideSpecified::Buy => self.bids.add(order),
            OrderSideSpecified::Sell => self.asks.add(order),
        }
    }

    /// Updates an existing own order in the book.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn update(&mut self, order: OwnBookOrder) -> anyhow::Result<()> {
        let result = match order.side {
            OrderSideSpecified::Buy => self.bids.update(order),
            OrderSideSpecified::Sell => self.asks.update(order),
        };

        if result.is_ok() {
            self.increment(&order);
        }

        result
    }

    /// Deletes an own order from the book.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn delete(&mut self, order: OwnBookOrder) -> anyhow::Result<()> {
        let result = match order.side {
            OrderSideSpecified::Buy => self.bids.delete(order),
            OrderSideSpecified::Sell => self.asks.delete(order),
        };

        if result.is_ok() {
            self.increment(&order);
        }

        result
    }

    /// Clears all orders from both sides of the book.
    pub fn clear(&mut self) {
        self.bids.clear();
        self.asks.clear();
    }

    /// Returns an iterator over bid price levels.
    pub fn bids(&self) -> impl Iterator<Item = &OwnBookLevel> {
        self.bids.levels.values()
    }

    /// Returns an iterator over ask price levels.
    pub fn asks(&self) -> impl Iterator<Item = &OwnBookLevel> {
        self.asks.levels.values()
    }

    /// Returns the client order IDs currently on the bid side.
    pub fn bid_client_order_ids(&self) -> Vec<ClientOrderId> {
        self.bids.cache.keys().copied().collect()
    }

    /// Returns the client order IDs currently on the ask side.
    pub fn ask_client_order_ids(&self) -> Vec<ClientOrderId> {
        self.asks.cache.keys().copied().collect()
    }

    /// Return whether the given client order ID is in the own book.
    pub fn is_order_in_book(&self, client_order_id: &ClientOrderId) -> bool {
        self.asks.cache.contains_key(client_order_id)
            || self.bids.cache.contains_key(client_order_id)
    }

    /// Maps bid price levels to their own orders, excluding empty levels after filtering.
    ///
    /// Filters by `status` if provided. With `accepted_buffer_ns`, only includes orders accepted
    /// at least that many nanoseconds before `ts_now` (defaults to now).
    pub fn bids_as_map(
        &self,
        status: Option<&AHashSet<OrderStatus>>,
        accepted_buffer_ns: Option<u64>,
        ts_now: Option<u64>,
    ) -> IndexMap<Decimal, Vec<OwnBookOrder>> {
        filter_orders(self.bids(), status, accepted_buffer_ns, ts_now)
    }

    /// Maps ask price levels to their own orders, excluding empty levels after filtering.
    ///
    /// Filters by `status` if provided. With `accepted_buffer_ns`, only includes orders accepted
    /// at least that many nanoseconds before `ts_now` (defaults to now).
    pub fn asks_as_map(
        &self,
        status: Option<&AHashSet<OrderStatus>>,
        accepted_buffer_ns: Option<u64>,
        ts_now: Option<u64>,
    ) -> IndexMap<Decimal, Vec<OwnBookOrder>> {
        filter_orders(self.asks(), status, accepted_buffer_ns, ts_now)
    }

    /// Aggregates own bid quantities per price level, omitting zero-quantity levels.
    ///
    /// Filters by `status` if provided, including only matching orders. With `accepted_buffer_ns`,
    /// only includes orders accepted at least that many nanoseconds before `ts_now` (defaults to now).
    ///
    /// If `group_size` is provided, groups quantities into price buckets.
    /// If `depth` is provided, limits the number of price levels returned.
    pub fn bid_quantity(
        &self,
        status: Option<&AHashSet<OrderStatus>>,
        depth: Option<usize>,
        group_size: Option<Decimal>,
        accepted_buffer_ns: Option<u64>,
        ts_now: Option<u64>,
    ) -> IndexMap<Decimal, Decimal> {
        let quantities = self
            .bids_as_map(status, accepted_buffer_ns, ts_now)
            .into_iter()
            .map(|(price, orders)| (price, sum_order_sizes(orders.iter())))
            .filter(|(_, quantity)| *quantity > Decimal::ZERO)
            .collect::<IndexMap<Decimal, Decimal>>();

        if let Some(group_size) = group_size {
            group_quantities(quantities, group_size, depth, true)
        } else if let Some(depth) = depth {
            quantities.into_iter().take(depth).collect()
        } else {
            quantities
        }
    }

    /// Aggregates own ask quantities per price level, omitting zero-quantity levels.
    ///
    /// Filters by `status` if provided, including only matching orders. With `accepted_buffer_ns`,
    /// only includes orders accepted at least that many nanoseconds before `ts_now` (defaults to now).
    ///
    /// If `group_size` is provided, groups quantities into price buckets.
    /// If `depth` is provided, limits the number of price levels returned.
    pub fn ask_quantity(
        &self,
        status: Option<&AHashSet<OrderStatus>>,
        depth: Option<usize>,
        group_size: Option<Decimal>,
        accepted_buffer_ns: Option<u64>,
        ts_now: Option<u64>,
    ) -> IndexMap<Decimal, Decimal> {
        let quantities = self
            .asks_as_map(status, accepted_buffer_ns, ts_now)
            .into_iter()
            .map(|(price, orders)| {
                let quantity = sum_order_sizes(orders.iter());
                (price, quantity)
            })
            .filter(|(_, quantity)| *quantity > Decimal::ZERO)
            .collect::<IndexMap<Decimal, Decimal>>();

        if let Some(group_size) = group_size {
            group_quantities(quantities, group_size, depth, false)
        } else if let Some(depth) = depth {
            quantities.into_iter().take(depth).collect()
        } else {
            quantities
        }
    }

    /// Returns a new own book containing this books orders plus parity-transformed opposite orders.
    ///
    /// Opposite asks are transformed into bids with price `1 - price`.
    /// Opposite bids are transformed into asks with price `1 - price`.
    ///
    /// # Errors
    ///
    /// Returns [`BookViewError::OppositeInstrumentMatch`] if `self` and `opposite` have the
    /// same instrument ID.
    pub fn combined_with_opposite(&self, opposite: &Self) -> Result<Self, BookViewError> {
        if self.instrument_id == opposite.instrument_id {
            return Err(BookViewError::OppositeInstrumentMatch(
                self.instrument_id,
                opposite.instrument_id,
            ));
        }

        let mut combined = self.clone();

        for level in opposite.asks() {
            for order in level.iter() {
                combined.add(transform_opposite_order(*order, OrderSideSpecified::Buy));
            }
        }

        for level in opposite.bids() {
            for order in level.iter() {
                combined.add(transform_opposite_order(*order, OrderSideSpecified::Sell));
            }
        }

        Ok(combined)
    }

    /// Return a formatted string representation of the order book.
    #[must_use]
    pub fn pprint(&self, num_levels: usize, group_size: Option<Decimal>) -> String {
        pprint_own_book(self, num_levels, group_size)
    }

    pub fn audit_open_orders(&mut self, open_order_ids: &AHashSet<ClientOrderId>) {
        log::debug!("Auditing {self}");

        // Audit bids
        let bids_to_remove: Vec<ClientOrderId> = self
            .bids
            .cache
            .keys()
            .filter(|&key| !open_order_ids.contains(key))
            .copied()
            .collect();

        // Audit asks
        let asks_to_remove: Vec<ClientOrderId> = self
            .asks
            .cache
            .keys()
            .filter(|&key| !open_order_ids.contains(key))
            .copied()
            .collect();

        for client_order_id in bids_to_remove {
            log_audit_error(&client_order_id);
            if let Err(e) = self.bids.remove(&client_order_id) {
                log::error!("{e}");
            }
        }

        for client_order_id in asks_to_remove {
            log_audit_error(&client_order_id);
            if let Err(e) = self.asks.remove(&client_order_id) {
                log::error!("{e}");
            }
        }
    }
}

fn log_audit_error(client_order_id: &ClientOrderId) {
    log::error!(
        "Audit error - {client_order_id} cached order already closed, deleting from own book"
    );
}

fn transform_opposite_order(order: OwnBookOrder, side: OrderSideSpecified) -> OwnBookOrder {
    let parity_price = Price::from_decimal(Decimal::ONE - order.price.as_decimal())
        .expect("Invalid parity transformed price for OwnOrderBook::combined_with_opposite");

    OwnBookOrder::new(
        order.trader_id,
        order.client_order_id,
        order.venue_order_id,
        side,
        parity_price,
        order.size,
        order.order_type,
        order.time_in_force,
        order.status,
        order.ts_last,
        order.ts_accepted,
        order.ts_submitted,
        order.ts_init,
    )
}

/// Filters orders by status and accepted timestamp.
///
/// `accepted_buffer_ns` acts as a grace period after `ts_accepted`. Orders whose
/// `ts_accepted` is still zero (e.g. SUBMITTED/PENDING state before an ACCEPTED
/// event) will pass the buffer check once `ts_now` exceeds the buffer, even though
/// they have not been venue-acknowledged yet. Callers that want to hide inflight
/// orders must additionally filter by `OrderStatus` (for example, include only
/// `ACCEPTED` / `PARTIALLY_FILLED`).
fn filter_orders<'a>(
    levels: impl Iterator<Item = &'a OwnBookLevel>,
    status: Option<&AHashSet<OrderStatus>>,
    accepted_buffer_ns: Option<u64>,
    ts_now: Option<u64>,
) -> IndexMap<Decimal, Vec<OwnBookOrder>> {
    let accepted_buffer_ns = accepted_buffer_ns.unwrap_or(0);
    let ts_now = ts_now.unwrap_or_else(nanos_since_unix_epoch);
    levels
        .map(|level| {
            let orders = level
                .orders
                .values()
                .filter(|order| status.is_none_or(|f| f.contains(&order.status)))
                .filter(|order| order.ts_accepted + accepted_buffer_ns <= ts_now)
                .copied()
                .collect::<Vec<OwnBookOrder>>();

            (level.price.value.as_decimal(), orders)
        })
        .filter(|(_, orders)| !orders.is_empty())
        .collect::<IndexMap<Decimal, Vec<OwnBookOrder>>>()
}

fn group_quantities(
    quantities: IndexMap<Decimal, Decimal>,
    group_size: Decimal,
    depth: Option<usize>,
    is_bid: bool,
) -> IndexMap<Decimal, Decimal> {
    if group_size <= Decimal::ZERO {
        log::error!("Invalid group_size: {group_size}, must be positive; returning empty map");
        return IndexMap::new();
    }

    let mut grouped = IndexMap::new();
    let depth = depth.unwrap_or(usize::MAX);

    for (price, size) in quantities {
        let grouped_price = if is_bid {
            (price / group_size).floor() * group_size
        } else {
            (price / group_size).ceil() * group_size
        };

        grouped
            .entry(grouped_price)
            .and_modify(|total| *total += size)
            .or_insert(size);

        if grouped.len() > depth {
            if is_bid {
                // For bids, remove the lowest price level
                if let Some((lowest_price, _)) = grouped.iter().min_by_key(|(price, _)| *price) {
                    let lowest_price = *lowest_price;
                    grouped.shift_remove(&lowest_price);
                }
            } else {
                // For asks, remove the highest price level
                if let Some((highest_price, _)) = grouped.iter().max_by_key(|(price, _)| *price) {
                    let highest_price = *highest_price;
                    grouped.shift_remove(&highest_price);
                }
            }
        }
    }

    grouped
}

fn sum_order_sizes<'a, I>(orders: I) -> Decimal
where
    I: Iterator<Item = &'a OwnBookOrder>,
{
    orders.fold(Decimal::ZERO, |total, order| {
        total + order.size.as_decimal()
    })
}

/// Represents a ladder of price levels for one side of an order book.
#[derive(Clone)]
pub(crate) struct OwnBookLadder {
    pub side: OrderSideSpecified,
    pub levels: BTreeMap<BookPrice, OwnBookLevel>,
    pub cache: AHashMap<ClientOrderId, BookPrice>,
}

impl OwnBookLadder {
    /// Creates a new [`OwnBookLadder`] instance.
    #[must_use]
    pub fn new(side: OrderSideSpecified) -> Self {
        Self {
            side,
            levels: BTreeMap::new(),
            cache: AHashMap::new(),
        }
    }

    /// Returns the number of price levels in the ladder.
    #[must_use]
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.levels.len()
    }

    /// Returns true if the ladder has no price levels.
    #[must_use]
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.levels.is_empty()
    }

    /// Removes all orders and price levels from the ladder.
    pub fn clear(&mut self) {
        self.levels.clear();
        self.cache.clear();
    }

    /// Adds an order to the ladder at its price level.
    pub fn add(&mut self, order: OwnBookOrder) {
        let book_price = order.to_book_price();
        self.cache.insert(order.client_order_id, book_price);

        match self.levels.get_mut(&book_price) {
            Some(level) => {
                level.add(order);
            }
            None => {
                let level = OwnBookLevel::from_order(order);
                self.levels.insert(book_price, level);
            }
        }
    }

    /// Updates an existing order in the ladder, moving it to a new price level if needed.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn update(&mut self, order: OwnBookOrder) -> anyhow::Result<()> {
        let Some(price) = self.cache.get(&order.client_order_id).copied() else {
            log::error!(
                "Own book update failed - order {client_order_id} not in cache",
                client_order_id = order.client_order_id
            );
            anyhow::bail!(
                "Order {} not found in own book (cache)",
                order.client_order_id
            );
        };

        let Some(level) = self.levels.get_mut(&price) else {
            log::error!(
                "Own book update failed - order {client_order_id} cached level {price:?} missing",
                client_order_id = order.client_order_id
            );
            anyhow::bail!(
                "Order {} not found in own book (level)",
                order.client_order_id
            );
        };

        if order.price == level.price.value {
            level.update(order);
            if order.size.is_zero() {
                self.cache.remove(&order.client_order_id);

                if level.is_empty() {
                    self.levels.remove(&price);
                }
            }
            return Ok(());
        }

        level.delete(&order.client_order_id)?;
        self.cache.remove(&order.client_order_id);

        if level.is_empty() {
            self.levels.remove(&price);
        }

        self.add(order);
        Ok(())
    }

    /// Deletes an order from the ladder.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn delete(&mut self, order: OwnBookOrder) -> anyhow::Result<()> {
        self.remove(&order.client_order_id)
    }

    /// Removes an order by its ID from the ladder.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn remove(&mut self, client_order_id: &ClientOrderId) -> anyhow::Result<()> {
        let Some(price) = self.cache.get(client_order_id).copied() else {
            log::error!("Own book remove failed - order {client_order_id} not in cache");
            anyhow::bail!("Order {client_order_id} not found in own book (cache)");
        };

        let Some(level) = self.levels.get_mut(&price) else {
            log::error!(
                "Own book remove failed - order {client_order_id} cached level {price:?} missing"
            );
            anyhow::bail!("Order {client_order_id} not found in own book (level)");
        };

        level.delete(client_order_id)?;

        if level.is_empty() {
            self.levels.remove(&price);
        }
        self.cache.remove(client_order_id);

        Ok(())
    }

    /// Returns the total size of all orders in the ladder.
    #[must_use]
    #[allow(dead_code)]
    pub fn sizes(&self) -> f64 {
        self.levels.values().map(OwnBookLevel::size).sum()
    }

    /// Returns the total value exposure (price * size) of all orders in the ladder.
    #[must_use]
    #[allow(dead_code)]
    pub fn exposures(&self) -> f64 {
        self.levels.values().map(OwnBookLevel::exposure).sum()
    }

    /// Returns the best price level in the ladder.
    #[must_use]
    #[allow(dead_code)]
    pub fn top(&self) -> Option<&OwnBookLevel> {
        match self.levels.iter().next() {
            Some((_, l)) => Option::Some(l),
            None => Option::None,
        }
    }
}

impl Debug for OwnBookLadder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(OwnBookLadder))
            .field("side", &self.side)
            .field("levels", &self.levels)
            .finish()
    }
}

impl Display for OwnBookLadder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{}(side={})", stringify!(OwnBookLadder), self.side)?;
        for (price, level) in &self.levels {
            writeln!(f, "  {} -> {} orders", price, level.len())?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct OwnBookLevel {
    pub price: BookPrice,
    pub orders: IndexMap<ClientOrderId, OwnBookOrder>,
}

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

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

    /// 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.
    #[must_use]
    pub fn first(&self) -> Option<&OwnBookOrder> {
        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 = &OwnBookOrder> {
        self.orders.values()
    }

    /// Returns all orders at this price level in FIFO insertion order.
    #[must_use]
    pub fn get_orders(&self) -> Vec<OwnBookOrder> {
        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.iter().map(|(_, o)| o.size.as_f64()).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.iter().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
            .iter()
            .map(|(_, o)| o.price.as_f64() * o.size.as_f64())
            .sum()
    }

    /// Adds multiple orders to this price level in FIFO order. Orders must match the level's price.
    pub fn add_bulk(&mut self, orders: &[OwnBookOrder]) {
        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: OwnBookOrder) {
        debug_assert_eq!(order.price, self.price.value);

        self.orders.insert(order.client_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: OwnBookOrder) {
        debug_assert_eq!(order.price, self.price.value);

        if order.size.is_zero() {
            self.orders.shift_remove(&order.client_order_id);
        } else {
            self.orders[&order.client_order_id] = order;
        }
    }

    /// Deletes an order from this price level.
    ///
    /// # Errors
    ///
    /// Returns an error if the order is not found.
    pub fn delete(&mut self, client_order_id: &ClientOrderId) -> anyhow::Result<()> {
        if self.orders.shift_remove(client_order_id).is_none() {
            // TODO: Use a generic anyhow result for now pending specific error types
            anyhow::bail!("Order {client_order_id} not found for delete");
        }
        Ok(())
    }
}

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

impl Eq for OwnBookLevel {}

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

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

pub fn should_handle_own_book_order(order: &OrderAny) -> bool {
    order.has_price()
        && order.time_in_force() != TimeInForce::Ioc
        && order.time_in_force() != TimeInForce::Fok
}