nautilus_model/orderbook/
analysis.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
16//! Functions related to order book analysis.
17
18use std::collections::BTreeMap;
19
20use super::{BookLevel, BookPrice, OrderBook};
21use crate::{
22    enums::{BookType, OrderSide, OrderSideSpecified},
23    orderbook::BookIntegrityError,
24    types::{Price, Quantity, fixed::FIXED_SCALAR, quantity::QuantityRaw},
25};
26
27/// Calculates the estimated fill quantity for a specified price from a set of
28/// order book levels and order side.
29#[must_use]
30pub fn get_quantity_for_price(
31    price: Price,
32    order_side: OrderSideSpecified,
33    levels: &BTreeMap<BookPrice, BookLevel>,
34) -> f64 {
35    let mut matched_size: f64 = 0.0;
36
37    for (book_price, level) in levels {
38        match order_side {
39            OrderSideSpecified::Buy => {
40                if book_price.value > price {
41                    break;
42                }
43            }
44            OrderSideSpecified::Sell => {
45                if book_price.value < price {
46                    break;
47                }
48            }
49        }
50        matched_size += level.size();
51    }
52
53    matched_size
54}
55
56/// Returns all price levels that would be crossed by an order at the given price.
57///
58/// Unlike `get_quantity_for_price` which returns just the total, this returns
59/// each individual level as (price, size). Used when liquidity consumption
60/// tracking needs visibility into all available levels.
61#[must_use]
62pub fn get_levels_for_price(
63    price: Price,
64    order_side: OrderSideSpecified,
65    levels: &BTreeMap<BookPrice, BookLevel>,
66    size_precision: u8,
67) -> Vec<(Price, Quantity)> {
68    let mut result = Vec::new();
69
70    for (book_price, level) in levels {
71        match order_side {
72            OrderSideSpecified::Buy => {
73                if book_price.value > price {
74                    break;
75                }
76            }
77            OrderSideSpecified::Sell => {
78                if book_price.value < price {
79                    break;
80                }
81            }
82        }
83        let level_size = Quantity::new(level.size(), size_precision);
84        result.push((level.price.value, level_size));
85    }
86
87    result
88}
89
90/// Calculates the estimated average price for a specified quantity from a set of
91/// order book levels.
92#[must_use]
93pub fn get_avg_px_for_quantity(qty: Quantity, levels: &BTreeMap<BookPrice, BookLevel>) -> f64 {
94    let mut cumulative_size_raw: QuantityRaw = 0;
95    let mut cumulative_value = 0.0;
96
97    for (book_price, level) in levels {
98        let size_this_level = level.size_raw().min(qty.raw - cumulative_size_raw);
99        cumulative_size_raw += size_this_level;
100        cumulative_value += book_price.value.as_f64() * size_this_level as f64;
101
102        if cumulative_size_raw >= qty.raw {
103            break;
104        }
105    }
106
107    if cumulative_size_raw == 0 {
108        0.0
109    } else {
110        cumulative_value / cumulative_size_raw as f64
111    }
112}
113
114/// Calculates the estimated average price for a specified exposure from a set of
115/// order book levels.
116#[must_use]
117pub fn get_avg_px_qty_for_exposure(
118    target_exposure: Quantity,
119    levels: &BTreeMap<BookPrice, BookLevel>,
120) -> (f64, f64, f64) {
121    let mut cumulative_exposure = 0.0;
122    let mut cumulative_size_raw: QuantityRaw = 0;
123    let mut final_price = levels
124        .first_key_value()
125        .map_or(0.0, |(price, _)| price.value.as_f64());
126
127    for (book_price, level) in levels {
128        let price = book_price.value.as_f64();
129        final_price = price;
130
131        let level_exposure = price * level.size_raw() as f64;
132        let exposure_this_level =
133            level_exposure.min(target_exposure.raw as f64 - cumulative_exposure);
134        let size_this_level = (exposure_this_level / price).floor() as QuantityRaw;
135
136        cumulative_exposure += price * size_this_level as f64;
137        cumulative_size_raw += size_this_level;
138
139        if cumulative_exposure >= target_exposure.as_f64() {
140            break;
141        }
142    }
143
144    if cumulative_size_raw == 0 {
145        (0.0, 0.0, final_price)
146    } else {
147        let avg_price = cumulative_exposure / cumulative_size_raw as f64;
148        (
149            avg_price,
150            cumulative_size_raw as f64 / FIXED_SCALAR,
151            final_price,
152        )
153    }
154}
155
156/// Checks the integrity of the given order `book`.
157///
158/// # Errors
159///
160/// Returns an error if a book integrity check fails.
161pub fn book_check_integrity(book: &OrderBook) -> Result<(), BookIntegrityError> {
162    match book.book_type {
163        BookType::L1_MBP => {
164            if book.bids.len() > 1 {
165                return Err(BookIntegrityError::TooManyLevels(
166                    OrderSide::Buy,
167                    book.bids.len(),
168                ));
169            }
170            if book.asks.len() > 1 {
171                return Err(BookIntegrityError::TooManyLevels(
172                    OrderSide::Sell,
173                    book.asks.len(),
174                ));
175            }
176        }
177        BookType::L2_MBP => {
178            for bid_level in book.bids.levels.values() {
179                let num_orders = bid_level.orders.len();
180                if num_orders > 1 {
181                    return Err(BookIntegrityError::TooManyOrders(
182                        OrderSide::Buy,
183                        num_orders,
184                    ));
185                }
186            }
187
188            for ask_level in book.asks.levels.values() {
189                let num_orders = ask_level.orders.len();
190                if num_orders > 1 {
191                    return Err(BookIntegrityError::TooManyOrders(
192                        OrderSide::Sell,
193                        num_orders,
194                    ));
195                }
196            }
197        }
198        BookType::L3_MBO => {}
199    };
200
201    if let (Some(top_bid_level), Some(top_ask_level)) = (book.bids.top(), book.asks.top()) {
202        let best_bid = top_bid_level.price;
203        let best_ask = top_ask_level.price;
204
205        // Only strictly crossed books (bid > ask) are invalid; locked markets (bid == ask) are valid
206        if best_bid.value > best_ask.value {
207            return Err(BookIntegrityError::OrdersCrossed(best_bid, best_ask));
208        }
209    }
210
211    Ok(())
212}