Skip to main content

nautilus_model/python/orderbook/
book.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::str::FromStr;
17
18use ahash::AHashSet;
19use indexmap::IndexMap;
20use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
21use pyo3::{IntoPyObjectExt, prelude::*};
22use rust_decimal::Decimal;
23
24use crate::{
25    data::{BookOrder, OrderBookDelta, OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick},
26    enums::{BookType, OrderSide, OrderStatus},
27    identifiers::InstrumentId,
28    orderbook::{
29        BookLevel, OrderBook,
30        analysis::book_check_integrity,
31        own::{OwnOrderBook, validate_accepted_buffer},
32    },
33    python::{orderbook::level::check_sizes_float_precision, types::fixed::FloatArithmetic},
34    types::{Price, Quantity},
35};
36
37#[pymethods]
38#[pyo3_stub_gen::derive::gen_stub_pymethods]
39impl OrderBook {
40    /// Provides a high-performance, versatile order book.
41    ///
42    /// Maintains buy (bid) and sell (ask) orders in price-time priority, supporting multiple
43    /// market data formats:
44    /// - L3 (MBO): Market By Order - tracks individual orders with unique IDs.
45    /// - L2 (MBP): Market By Price - aggregates orders at each price level.
46    /// - L1 (MBP): Top-of-Book - maintains only the best bid and ask prices.
47    #[new]
48    fn py_new(instrument_id: InstrumentId, book_type: BookType) -> Self {
49        Self::new(instrument_id, book_type)
50    }
51
52    fn __repr__(&self) -> String {
53        format!("{self:?}")
54    }
55
56    fn __str__(&self) -> String {
57        self.to_string()
58    }
59
60    fn __getstate__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
61        let orders = self
62            .bids(None)
63            .chain(self.asks(None))
64            .flat_map(|level| level.iter().copied())
65            .collect::<Vec<_>>();
66        (
67            self.instrument_id,
68            self.book_type.to_string(),
69            self.sequence,
70            self.ts_last.as_u64(),
71            self.update_count,
72            orders,
73            self.bids.batch_state_code(),
74            self.asks.batch_state_code(),
75        )
76            .into_py_any(py)
77    }
78
79    fn __setstate__(&mut self, state: &Bound<'_, PyAny>) -> PyResult<()> {
80        let (
81            instrument_id,
82            book_type,
83            sequence,
84            ts_last,
85            update_count,
86            orders,
87            bid_batch_state,
88            ask_batch_state,
89        ): (InstrumentId, String, u64, u64, u64, Vec<BookOrder>, u8, u8) = state.extract()?;
90        let book_type = BookType::from_str(&book_type).map_err(to_pyvalue_err)?;
91
92        if instrument_id != self.instrument_id {
93            return Err(to_pyvalue_err(format!(
94                "OrderBook state instrument ID {instrument_id} does not match instance instrument ID {}",
95                self.instrument_id
96            )));
97        }
98
99        if book_type != self.book_type {
100            return Err(to_pyvalue_err(format!(
101                "OrderBook state book type {book_type:?} does not match instance book type {:?}",
102                self.book_type
103            )));
104        }
105
106        if orders.iter().any(|order| order.side.is_none()) {
107            return Err(to_pyvalue_err(
108                "OrderBook state contains an order with no side",
109            ));
110        }
111
112        let mut restored = Self::new(instrument_id, book_type);
113        for order in orders {
114            restored.add(order, 0, 0, 0.into());
115        }
116        restored
117            .bids
118            .set_batch_state_code(bid_batch_state)
119            .map_err(to_pyvalue_err)?;
120        restored
121            .asks
122            .set_batch_state_code(ask_batch_state)
123            .map_err(to_pyvalue_err)?;
124        restored.sequence = sequence;
125        restored.ts_last = ts_last.into();
126        restored.update_count = update_count;
127        *self = restored;
128        Ok(())
129    }
130
131    fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
132        let constructor = py.get_type::<Self>().getattr("_safe_constructor")?;
133        let args = (self.instrument_id, self.book_type.to_string());
134        let state = self.__getstate__(py)?;
135        (constructor, args, state).into_py_any(py)
136    }
137
138    #[staticmethod]
139    #[pyo3(name = "_safe_constructor")]
140    fn py_safe_constructor(instrument_id: InstrumentId, book_type: &str) -> PyResult<Self> {
141        let book_type = BookType::from_str(book_type).map_err(to_pyvalue_err)?;
142        Ok(Self::new(instrument_id, book_type))
143    }
144
145    fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self {
146        self.clone()
147    }
148
149    #[getter]
150    #[pyo3(name = "instrument_id")]
151    fn py_instrument_id(&self) -> InstrumentId {
152        self.instrument_id
153    }
154
155    #[getter]
156    #[pyo3(name = "book_type")]
157    fn py_book_type(&self) -> BookType {
158        self.book_type
159    }
160
161    #[getter]
162    #[pyo3(name = "sequence")]
163    fn py_sequence(&self) -> u64 {
164        self.sequence
165    }
166
167    #[getter]
168    #[pyo3(name = "ts_event")]
169    fn py_ts_event(&self) -> u64 {
170        self.ts_last.as_u64()
171    }
172
173    #[getter]
174    #[pyo3(name = "ts_init")]
175    fn py_ts_init(&self) -> u64 {
176        self.ts_last.as_u64()
177    }
178
179    #[getter]
180    #[pyo3(name = "ts_last")]
181    fn py_ts_last(&self) -> u64 {
182        self.ts_last.as_u64()
183    }
184
185    #[getter]
186    #[pyo3(name = "update_count")]
187    fn py_update_count(&self) -> u64 {
188        self.update_count
189    }
190
191    /// Resets the order book to its initial empty state.
192    #[pyo3(name = "reset")]
193    fn py_reset(&mut self) {
194        self.reset();
195    }
196
197    /// Adds an order to the book after preprocessing based on book type.
198    #[pyo3(name = "add")]
199    #[pyo3(signature = (order, flags, sequence, ts_event))]
200    fn py_add(&mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: u64) {
201        self.add(order, flags, sequence, ts_event.into());
202    }
203
204    /// Updates an existing order in the book after preprocessing based on book type.
205    #[pyo3(name = "update")]
206    #[pyo3(signature = (order, flags, sequence, ts_event))]
207    fn py_update(&mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: u64) {
208        self.update(order, flags, sequence, ts_event.into());
209    }
210
211    /// Deletes an order from the book after preprocessing based on book type.
212    #[pyo3(name = "delete")]
213    #[pyo3(signature = (order, flags, sequence, ts_event))]
214    fn py_delete(&mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: u64) {
215        self.delete(order, flags, sequence, ts_event.into());
216    }
217
218    /// Clears all orders from both sides of the book.
219    ///
220    /// A full clear uses its `sequence` as the new sequence high-water.
221    /// `clear_bids` and `clear_asks` preserve the current high-water.
222    #[pyo3(name = "clear")]
223    #[pyo3(signature = (sequence, ts_event))]
224    fn py_clear(&mut self, sequence: u64, ts_event: u64) {
225        self.clear(sequence, ts_event.into());
226    }
227
228    /// Clears all bid orders from the book.
229    #[pyo3(name = "clear_bids")]
230    #[pyo3(signature = (sequence, ts_event))]
231    fn py_clear_bids(&mut self, sequence: u64, ts_event: u64) {
232        self.clear_bids(sequence, ts_event.into());
233    }
234
235    /// Clears all ask orders from the book.
236    #[pyo3(name = "clear_asks")]
237    #[pyo3(signature = (sequence, ts_event))]
238    fn py_clear_asks(&mut self, sequence: u64, ts_event: u64) {
239        self.clear_asks(sequence, ts_event.into());
240    }
241
242    /// Removes overlapped bid/ask levels when the book is strictly crossed (best bid > best ask)
243    ///
244    /// - Acts only when both sides exist and the book is crossed.
245    /// - Deletes by removing whole price levels via the ladder API to preserve invariants.
246    /// - `side=None` clears both overlapped ranges (conservative, may widen spread).
247    /// - `side=Buy` clears crossed bids only; side=Sell clears crossed asks only.
248    /// - Returns removed price levels (crossed bids first, then crossed asks), or None if nothing removed.
249    #[pyo3(name = "clear_stale_levels")]
250    #[pyo3(signature = (side=None))]
251    fn py_clear_stale_levels(&mut self, side: Option<OrderSide>) -> Option<Vec<BookLevel>> {
252        self.clear_stale_levels(side)
253    }
254
255    /// Applies a single order book delta operation.
256    ///
257    /// # Errors
258    ///
259    /// Returns an error if:
260    /// - The delta's instrument ID does not match this book's instrument ID.
261    /// - An `Add` is given with no side, either explicitly or because the cache lookup failed.
262    /// - An `Add` with no side matches an order ID on both sides of the book.
263    /// - After resolution the delta still has no side but its action is not `Clear`.
264    ///
265    /// # Notes
266    ///
267    /// An ambiguous no-side `Update` or `Delete` is skipped with a warning.
268    #[pyo3(name = "apply_delta")]
269    fn py_apply_delta(&mut self, delta: &OrderBookDelta) -> PyResult<()> {
270        self.apply_delta_unchecked(delta).map_err(to_pyruntime_err)
271    }
272
273    /// Applies multiple order book delta operations.
274    ///
275    /// # Errors
276    ///
277    /// Returns an error if:
278    /// - The deltas' instrument ID does not match this book's instrument ID.
279    /// - Any individual delta application fails (see `Self.apply_delta`).
280    #[pyo3(name = "apply_deltas")]
281    fn py_apply_deltas(&mut self, deltas: &OrderBookDeltas) -> PyResult<()> {
282        self.apply_deltas_unchecked(deltas)
283            .map_err(to_pyruntime_err)
284    }
285
286    /// Replaces current book state with a depth snapshot.
287    ///
288    /// # Errors
289    ///
290    /// Returns an error if the depth's instrument ID does not match this book's instrument ID.
291    #[pyo3(name = "apply_depth")]
292    fn py_apply_depth(&mut self, depth: &OrderBookDepth) -> PyResult<()> {
293        self.apply_depth_unchecked(depth).map_err(to_pyruntime_err)
294    }
295
296    #[pyo3(name = "check_integrity")]
297    fn py_check_integrity(&mut self) -> PyResult<()> {
298        book_check_integrity(self).map_err(to_pyruntime_err)
299    }
300
301    /// Returns an iterator over bid price levels.
302    #[pyo3(name = "bids")]
303    #[pyo3(signature = (depth=None))]
304    fn py_bids(&self, depth: Option<usize>) -> Vec<BookLevel> {
305        self.bids(depth)
306            .map(|level_ref| (*level_ref).clone())
307            .collect()
308    }
309
310    /// Returns an iterator over ask price levels.
311    #[pyo3(name = "asks")]
312    #[pyo3(signature = (depth=None))]
313    fn py_asks(&self, depth: Option<usize>) -> Vec<BookLevel> {
314        self.asks(depth)
315            .map(|level_ref| (*level_ref).clone())
316            .collect()
317    }
318
319    #[pyo3(name = "bids_to_dict")]
320    #[pyo3(signature = (depth=None))]
321    fn py_bids_to_dict(&self, depth: Option<usize>) -> IndexMap<Decimal, Decimal> {
322        self.bids_as_map(depth)
323    }
324
325    #[pyo3(name = "asks_to_dict")]
326    #[pyo3(signature = (depth=None))]
327    fn py_asks_to_dict(&self, depth: Option<usize>) -> IndexMap<Decimal, Decimal> {
328        self.asks_as_map(depth)
329    }
330
331    /// Groups bid quantities by price into buckets, limited by depth.
332    #[pyo3(name = "group_bids")]
333    #[pyo3(signature = (group_size, depth=None))]
334    #[must_use]
335    pub fn py_group_bids(
336        &self,
337        group_size: Decimal,
338        depth: Option<usize>,
339    ) -> IndexMap<Decimal, Decimal> {
340        self.group_bids(group_size, depth)
341    }
342
343    /// Groups ask quantities by price into buckets, limited by depth.
344    #[pyo3(name = "group_asks")]
345    #[pyo3(signature = (group_size, depth=None))]
346    #[must_use]
347    pub fn py_group_asks(
348        &self,
349        group_size: Decimal,
350        depth: Option<usize>,
351    ) -> IndexMap<Decimal, Decimal> {
352        self.group_asks(group_size, depth)
353    }
354
355    #[pyo3(name = "bids_filtered_to_dict")]
356    #[pyo3(signature = (depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None))]
357    fn py_bids_filtered_to_dict(
358        &self,
359        depth: Option<usize>,
360        own_book: Option<&OwnOrderBook>,
361        status: Option<std::collections::HashSet<OrderStatus>>,
362        accepted_buffer_ns: Option<u64>,
363        ts_now: Option<u64>,
364    ) -> PyResult<IndexMap<Decimal, Decimal>> {
365        validate_accepted_buffer(accepted_buffer_ns, ts_now).map_err(to_pyvalue_err)?;
366        let status_set: Option<AHashSet<OrderStatus>> = status.map(|s| s.into_iter().collect());
367        Ok(self.bids_filtered_as_map(
368            depth,
369            own_book,
370            status_set.as_ref(),
371            accepted_buffer_ns,
372            ts_now,
373        ))
374    }
375
376    #[pyo3(name = "asks_filtered_to_dict")]
377    #[pyo3(signature = (depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None))]
378    fn py_asks_filtered_to_dict(
379        &self,
380        depth: Option<usize>,
381        own_book: Option<&OwnOrderBook>,
382        status: Option<std::collections::HashSet<OrderStatus>>,
383        accepted_buffer_ns: Option<u64>,
384        ts_now: Option<u64>,
385    ) -> PyResult<IndexMap<Decimal, Decimal>> {
386        validate_accepted_buffer(accepted_buffer_ns, ts_now).map_err(to_pyvalue_err)?;
387        let status_set: Option<AHashSet<OrderStatus>> = status.map(|s| s.into_iter().collect());
388        Ok(self.asks_filtered_as_map(
389            depth,
390            own_book,
391            status_set.as_ref(),
392            accepted_buffer_ns,
393            ts_now,
394        ))
395    }
396
397    #[pyo3(name = "group_bids_filtered")]
398    #[pyo3(signature = (group_size, depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None))]
399    fn py_group_bids_filered(
400        &self,
401        group_size: Decimal,
402        depth: Option<usize>,
403        own_book: Option<&OwnOrderBook>,
404        status: Option<std::collections::HashSet<OrderStatus>>,
405        accepted_buffer_ns: Option<u64>,
406        ts_now: Option<u64>,
407    ) -> PyResult<IndexMap<Decimal, Decimal>> {
408        validate_accepted_buffer(accepted_buffer_ns, ts_now).map_err(to_pyvalue_err)?;
409        let status_set: Option<AHashSet<OrderStatus>> = status.map(|s| s.into_iter().collect());
410        Ok(self.group_bids_filtered(
411            group_size,
412            depth,
413            own_book,
414            status_set.as_ref(),
415            accepted_buffer_ns,
416            ts_now,
417        ))
418    }
419
420    /// Groups ask quantities into price buckets, truncating to a maximum depth, excluding own orders.
421    ///
422    /// With `own_book`, subtracts own order sizes, filtered by `status` if provided.
423    /// When `now` is provided, only subtracts orders whose acceptance time plus
424    /// `accepted_buffer_ns` is at or before `now`. When `now` is `None`, acceptance-time
425    /// filtering is disabled.
426    #[pyo3(name = "group_asks_filtered")]
427    #[pyo3(signature = (group_size, depth=None, own_book=None, status=None, accepted_buffer_ns=None, ts_now=None))]
428    fn py_group_asks_filtered(
429        &self,
430        group_size: Decimal,
431        depth: Option<usize>,
432        own_book: Option<&OwnOrderBook>,
433        status: Option<std::collections::HashSet<OrderStatus>>,
434        accepted_buffer_ns: Option<u64>,
435        ts_now: Option<u64>,
436    ) -> PyResult<IndexMap<Decimal, Decimal>> {
437        validate_accepted_buffer(accepted_buffer_ns, ts_now).map_err(to_pyvalue_err)?;
438        let status_set: Option<AHashSet<OrderStatus>> = status.map(|s| s.into_iter().collect());
439        Ok(self.group_asks_filtered(
440            group_size,
441            depth,
442            own_book,
443            status_set.as_ref(),
444            accepted_buffer_ns,
445            ts_now,
446        ))
447    }
448
449    /// Returns a filtered `OrderBook` view with own sizes subtracted from public levels.
450    #[pyo3(name = "filtered_view")]
451    #[pyo3(signature = (own_book=None, depth=None, status=None, accepted_buffer_ns=None, ts_now=None))]
452    fn py_filtered_view(
453        &self,
454        own_book: Option<&OwnOrderBook>,
455        depth: Option<usize>,
456        status: Option<std::collections::HashSet<OrderStatus>>,
457        accepted_buffer_ns: Option<u64>,
458        ts_now: Option<u64>,
459    ) -> PyResult<Self> {
460        validate_accepted_buffer(accepted_buffer_ns, ts_now).map_err(to_pyvalue_err)?;
461        let status_set: Option<AHashSet<OrderStatus>> = status.map(|s| s.into_iter().collect());
462        self.filtered_view_checked(
463            own_book,
464            depth,
465            status_set.as_ref(),
466            accepted_buffer_ns,
467            ts_now,
468        )
469        .map_err(to_pyvalue_err)
470    }
471
472    /// Returns the best bid price if available.
473    #[pyo3(name = "best_bid_price")]
474    fn py_best_bid_price(&self) -> Option<Price> {
475        self.best_bid_price()
476    }
477
478    /// Returns the best ask price if available.
479    #[pyo3(name = "best_ask_price")]
480    fn py_best_ask_price(&self) -> Option<Price> {
481        self.best_ask_price()
482    }
483
484    /// Returns the size at the best bid price if available.
485    #[pyo3(name = "best_bid_size")]
486    fn py_best_bid_size(&self) -> Option<Quantity> {
487        self.best_bid_size()
488    }
489
490    /// Returns the size at the best ask price if available.
491    #[pyo3(name = "best_ask_size")]
492    fn py_best_ask_size(&self) -> Option<Quantity> {
493        self.best_ask_size()
494    }
495
496    /// Returns the spread between best ask and bid prices if both exist.
497    #[pyo3(name = "spread")]
498    fn py_spread(&self) -> PyResult<Option<f64>> {
499        check_top_float_precision(self)?;
500        Ok(self.spread())
501    }
502
503    /// Returns the midpoint between best ask and bid prices if both exist.
504    #[pyo3(name = "midpoint")]
505    fn py_midpoint(&self) -> PyResult<Option<f64>> {
506        check_top_float_precision(self)?;
507        Ok(self.midpoint())
508    }
509
510    /// Calculates the average price to fill the specified quantity.
511    #[pyo3(name = "get_avg_px_for_quantity")]
512    fn py_get_avg_px_for_quantity(&self, qty: Quantity, order_side: OrderSide) -> f64 {
513        self.get_avg_px_for_quantity(qty, order_side)
514    }
515
516    /// Calculates the worst (last-touched) price to fill the specified quantity.
517    #[pyo3(name = "get_worst_px_for_quantity")]
518    fn py_get_worst_px_for_quantity(&self, qty: Quantity, order_side: OrderSide) -> Option<Price> {
519        self.get_worst_px_for_quantity(qty, order_side)
520    }
521
522    /// Calculates average price and quantity for target exposure.
523    ///
524    /// Returns (average price, quantity, last-touched price).
525    #[pyo3(name = "get_avg_px_qty_for_exposure")]
526    fn py_get_avg_px_qty_for_exposure(
527        &self,
528        qty: Quantity,
529        order_side: OrderSide,
530    ) -> PyResult<(f64, f64, f64)> {
531        qty.check_float_precision()?;
532
533        for level in side_levels(self, order_side) {
534            level.price.value.check_float_precision()?;
535            check_sizes_float_precision(level)?;
536        }
537
538        Ok(self.get_avg_px_qty_for_exposure(qty, order_side))
539    }
540
541    /// Returns the cumulative quantity available at or better than the specified price.
542    ///
543    /// For a BUY order, sums ask levels at or below the price.
544    /// For a SELL order, sums bid levels at or above the price.
545    #[pyo3(name = "get_quantity_for_price")]
546    fn py_get_quantity_for_price(&self, price: Price, order_side: OrderSide) -> PyResult<f64> {
547        for level in side_levels(self, order_side) {
548            check_sizes_float_precision(level)?;
549        }
550
551        Ok(self.get_quantity_for_price(price, order_side))
552    }
553
554    /// Returns the quantity at a specific price level only, or 0 if no level exists.
555    ///
556    /// Unlike `get_quantity_for_price` which returns cumulative quantity across
557    /// multiple levels, this returns only the quantity at the exact price level.
558    ///
559    /// The Python binding raises `ValueError` for an unsupported `size_precision` or an
560    /// aggregated level size that cannot be represented as a `Quantity`.
561    #[pyo3(name = "get_quantity_at_level")]
562    fn py_get_quantity_at_level(
563        &self,
564        price: Price,
565        order_side: OrderSide,
566        size_precision: u8,
567    ) -> PyResult<Quantity> {
568        self.get_quantity_at_level_checked(price, order_side, size_precision)
569            .map_err(to_pyvalue_err)
570    }
571
572    /// Returns all price levels crossed by an order at the given price and side.
573    ///
574    /// Unlike `simulate_fills`, this returns ALL crossed levels regardless of
575    /// order quantity. Used when liquidity consumption tracking needs visibility
576    /// into all available levels.
577    ///
578    /// The Python binding raises `ValueError` for an unsupported `size_precision` or an
579    /// aggregated level size that cannot be represented as a `Quantity`.
580    #[pyo3(name = "get_all_crossed_levels")]
581    fn py_get_all_crossed_levels(
582        &self,
583        order_side: OrderSide,
584        price: Price,
585        size_precision: u8,
586    ) -> PyResult<Vec<(Price, Quantity)>> {
587        self.get_all_crossed_levels_checked(order_side, price, size_precision)
588            .map_err(to_pyvalue_err)
589    }
590
591    /// Simulates fills for an order, returning list of (price, quantity) tuples.
592    #[pyo3(name = "simulate_fills")]
593    fn py_simulate_fills(&self, order: &BookOrder) -> Vec<(Price, Quantity)> {
594        self.simulate_fills(order)
595    }
596
597    /// Creates an `OrderBookDeltas` snapshot from the current order book state.
598    ///
599    /// This is the reverse operation of `apply_deltas`: it converts the current book state
600    /// back into a snapshot format with a `Clear` delta followed by `Add` deltas for all orders.
601    ///
602    /// # Parameters
603    ///
604    /// * `ts_event` - UNIX timestamp (nanoseconds) when the book event occurred.
605    /// * `ts_init` - UNIX timestamp (nanoseconds) when the instance was created.
606    ///
607    /// # Returns
608    ///
609    /// An `OrderBookDeltas` containing a snapshot of the current order book state.
610    #[pyo3(name = "to_deltas")]
611    fn py_to_deltas(&self, ts_event: u64, ts_init: u64) -> OrderBookDeltas {
612        self.to_deltas(ts_event.into(), ts_init.into())
613    }
614
615    /// Return a formatted string representation of the order book.
616    #[pyo3(name = "pprint")]
617    #[pyo3(signature = (num_levels=3, group_size=None))]
618    fn py_pprint(&self, num_levels: usize, group_size: Option<Decimal>) -> String {
619        self.pprint(num_levels, group_size)
620    }
621}
622
623/// Updates the `OrderBook` with a [`QuoteTick`].
624///
625/// # Errors
626///
627/// Returns an error if the update operation fails.
628#[pyfunction()]
629#[pyo3(name = "update_book_with_quote_tick")]
630pub fn py_update_book_with_quote_tick(book: &mut OrderBook, quote: &QuoteTick) -> PyResult<()> {
631    book.update_quote_tick(quote).map_err(to_pyvalue_err)
632}
633
634/// Updates the `OrderBook` with a [`TradeTick`].
635///
636/// # Errors
637///
638/// Returns an error if the update operation fails.
639#[pyfunction()]
640#[pyo3(name = "update_book_with_trade_tick")]
641pub fn py_update_book_with_trade_tick(book: &mut OrderBook, trade: &TradeTick) -> PyResult<()> {
642    book.update_trade_tick(trade).map_err(to_pyvalue_err)
643}
644
645fn check_top_float_precision(book: &OrderBook) -> PyResult<()> {
646    if let (Some(bid), Some(ask)) = (book.best_bid_price(), book.best_ask_price()) {
647        bid.check_float_precision()?;
648        ask.check_float_precision()?;
649    }
650
651    Ok(())
652}
653
654fn side_levels(book: &OrderBook, order_side: OrderSide) -> impl Iterator<Item = &BookLevel> {
655    match order_side {
656        OrderSide::Buy => book.asks.levels.values(),
657        OrderSide::Sell => book.bids.levels.values(),
658    }
659}