Skip to main content

nautilus_common/python/
cache.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//! Python bindings for the [`Cache`] component.
17
18use std::{cell::RefCell, rc::Rc, sync::LazyLock};
19
20use bytes::Bytes;
21use nautilus_core::python::to_pyvalue_err;
22#[cfg(feature = "defi")]
23use nautilus_model::defi::{Pool, PoolProfiler};
24use nautilus_model::{
25    data::{
26        Bar, BarType, CustomData, DataType, FundingRateUpdate, InstrumentClose, InstrumentStatus,
27        QuoteTick, TradeTick, YieldCurve,
28        prices::{IndexPriceUpdate, MarkPriceUpdate},
29    },
30    enums::{AggregationSource, OmsType, OrderSide, PositionSide, PriceType},
31    identifiers::{
32        AccountId, ActorId, ClientId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId,
33        PositionId, StrategyId, Venue, VenueOrderId,
34    },
35    instruments::SyntheticInstrument,
36    orderbook::{OrderBook, own::OwnOrderBook},
37    orders::OrderList,
38    position::Position,
39    python::{
40        account::account_any_to_pyobject,
41        instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
42        orders::{order_any_to_pyobject, pyobject_to_order_any},
43    },
44    types::{Currency, Money, Price, Quantity},
45};
46use pyo3::prelude::*;
47use rust_decimal::prelude::ToPrimitive;
48
49use crate::{
50    cache::{Cache, CacheConfig, database::CacheDatabaseFactory},
51    enums::SerializationEncoding,
52    python::{config_error_to_pyvalue_err, factory::FactoryRegistry},
53};
54
55/// Registry for Python cache database factory extractors.
56pub type CacheDatabaseFactoryRegistry = FactoryRegistry<dyn CacheDatabaseFactory>;
57
58static GLOBAL_CACHE_DATABASE_FACTORY_REGISTRY: LazyLock<CacheDatabaseFactoryRegistry> =
59    LazyLock::new(|| CacheDatabaseFactoryRegistry::new("cache database factory"));
60
61/// Returns the global Python cache database factory registry.
62#[must_use]
63pub fn get_global_cache_database_factory_registry() -> &'static CacheDatabaseFactoryRegistry {
64    &GLOBAL_CACHE_DATABASE_FACTORY_REGISTRY
65}
66
67/// Wrapper providing shared access to [`Cache`] from Python.
68///
69/// This wrapper holds an `Rc<RefCell<Cache>>` allowing actors to share
70/// the same cache instance. All methods delegate to the underlying cache.
71#[allow(non_camel_case_types)]
72#[pyo3::pyclass(
73    module = "nautilus_trader.common",
74    name = "Cache",
75    unsendable,
76    from_py_object
77)]
78#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.common")]
79#[derive(Debug, Clone)]
80pub struct PyCache(Rc<RefCell<Cache>>);
81
82impl PyCache {
83    /// Creates a `PyCache` from an `Rc<RefCell<Cache>>`.
84    #[must_use]
85    pub fn from_rc(rc: Rc<RefCell<Cache>>) -> Self {
86        Self(rc)
87    }
88
89    /// Gets the inner `Rc<RefCell<Cache>>` for use in Rust code.
90    #[must_use]
91    pub fn cache_rc(&self) -> Rc<RefCell<Cache>> {
92        self.0.clone()
93    }
94}
95
96#[pymethods]
97#[pyo3_stub_gen::derive::gen_stub_pymethods]
98impl PyCache {
99    #[new]
100    #[pyo3(signature = (config=None))]
101    fn py_new(config: Option<CacheConfig>) -> PyResult<Self> {
102        let cache = Cache::try_new(config, None).map_err(config_error_to_pyvalue_err)?;
103        Ok(Self(Rc::new(RefCell::new(cache))))
104    }
105
106    #[pyo3(name = "reset")]
107    fn py_reset(&mut self) {
108        self.0.borrow_mut().reset();
109    }
110
111    #[pyo3(name = "dispose")]
112    fn py_dispose(&mut self) {
113        self.0.borrow_mut().dispose();
114    }
115
116    #[pyo3(name = "purge_closed_orders", signature = (ts_now, buffer_secs=0, purge_from_database=false))]
117    fn py_purge_closed_orders(
118        &mut self,
119        ts_now: u64,
120        buffer_secs: u64,
121        purge_from_database: bool,
122    ) -> PyResult<()> {
123        self.0
124            .borrow_mut()
125            .purge_closed_orders(ts_now.into(), buffer_secs, purge_from_database)
126            .map_err(to_pyvalue_err)
127    }
128
129    #[pyo3(name = "purge_closed_positions", signature = (ts_now, buffer_secs=0, purge_from_database=false))]
130    fn py_purge_closed_positions(
131        &mut self,
132        ts_now: u64,
133        buffer_secs: u64,
134        purge_from_database: bool,
135    ) -> PyResult<()> {
136        self.0
137            .borrow_mut()
138            .purge_closed_positions(ts_now.into(), buffer_secs, purge_from_database)
139            .map_err(to_pyvalue_err)
140    }
141
142    #[pyo3(name = "delete_actor")]
143    fn py_delete_actor(&self, actor_id: ActorId) -> PyResult<()> {
144        self.0
145            .borrow()
146            .delete_actor(&actor_id)
147            .map_err(to_pyvalue_err)
148    }
149
150    #[pyo3(name = "delete_strategy")]
151    fn py_delete_strategy(&self, strategy_id: StrategyId) -> PyResult<()> {
152        self.0
153            .borrow()
154            .delete_strategy(&strategy_id)
155            .map_err(to_pyvalue_err)
156    }
157
158    #[pyo3(name = "heartbeat")]
159    fn py_heartbeat(&self, timestamp: u64) -> PyResult<()> {
160        self.0
161            .borrow()
162            .heartbeat(timestamp.into())
163            .map_err(to_pyvalue_err)
164    }
165
166    #[pyo3(name = "load_instrument")]
167    fn py_load_instrument(
168        &mut self,
169        py: Python<'_>,
170        instrument_id: InstrumentId,
171    ) -> PyResult<Option<Py<PyAny>>> {
172        let instrument = self
173            .0
174            .borrow_mut()
175            .load_instrument(&instrument_id)
176            .map_err(to_pyvalue_err)?;
177        instrument
178            .map(|instrument| instrument_any_to_pyobject(py, instrument))
179            .transpose()
180    }
181
182    #[pyo3(name = "load_synthetic")]
183    fn py_load_synthetic(
184        &mut self,
185        instrument_id: InstrumentId,
186    ) -> PyResult<Option<SyntheticInstrument>> {
187        self.0
188            .borrow_mut()
189            .load_synthetic(&instrument_id)
190            .map_err(to_pyvalue_err)
191    }
192
193    #[pyo3(name = "purge_order", signature = (client_order_id, purge_from_database=false))]
194    fn py_purge_order(
195        &mut self,
196        client_order_id: ClientOrderId,
197        purge_from_database: bool,
198    ) -> PyResult<()> {
199        self.0
200            .borrow_mut()
201            .purge_order(client_order_id, purge_from_database)
202            .map_err(to_pyvalue_err)
203    }
204
205    #[pyo3(name = "purge_position", signature = (position_id, purge_from_database=false))]
206    fn py_purge_position(
207        &mut self,
208        position_id: PositionId,
209        purge_from_database: bool,
210    ) -> PyResult<()> {
211        self.0
212            .borrow_mut()
213            .purge_position(position_id, purge_from_database)
214            .map_err(to_pyvalue_err)
215    }
216
217    #[pyo3(name = "purge_instrument")]
218    fn py_purge_instrument(&mut self, instrument_id: InstrumentId) {
219        self.0.borrow_mut().purge_instrument(instrument_id);
220    }
221
222    #[pyo3(name = "purge_account_events", signature = (ts_now, lookback_secs=0, purge_from_database=false))]
223    fn py_purge_account_events(
224        &mut self,
225        ts_now: u64,
226        lookback_secs: u64,
227        purge_from_database: bool,
228    ) -> PyResult<()> {
229        self.0
230            .borrow_mut()
231            .purge_account_events(ts_now.into(), lookback_secs, purge_from_database)
232            .map_err(to_pyvalue_err)
233    }
234
235    #[pyo3(name = "get")]
236    fn py_get(&self, key: &str) -> PyResult<Option<Vec<u8>>> {
237        match self.0.borrow().get(key).map_err(to_pyvalue_err)? {
238            Some(bytes) => Ok(Some(bytes.to_vec())),
239            None => Ok(None),
240        }
241    }
242
243    #[pyo3(name = "add")]
244    fn py_add_general(&mut self, key: &str, value: Vec<u8>) -> PyResult<()> {
245        self.0
246            .borrow_mut()
247            .add(key, Bytes::from(value))
248            .map_err(to_pyvalue_err)
249    }
250
251    /// Adds an instrument close, replacing any close cached for the same instrument.
252    #[pyo3(name = "add_instrument_close")]
253    fn py_add_instrument_close(&mut self, close: InstrumentClose) -> PyResult<()> {
254        self.0
255            .borrow_mut()
256            .add_instrument_close(close)
257            .map_err(to_pyvalue_err)
258    }
259
260    /// Adds custom data as the newest entry in its bounded history.
261    ///
262    /// Each data type topic has its own history, limited by `CacheConfig::data_capacity`.
263    /// This operation updates memory only.
264    #[pyo3(name = "add_custom_data")]
265    fn py_add_custom_data(&mut self, data: CustomData) {
266        self.0.borrow_mut().add_custom_data(data);
267    }
268
269    #[pyo3(name = "add_yield_curve")]
270    fn py_add_yield_curve(&mut self, yield_curve: YieldCurve) -> PyResult<()> {
271        self.0
272            .borrow_mut()
273            .add_yield_curve(yield_curve)
274            .map_err(to_pyvalue_err)
275    }
276
277    /// Returns the quote at `index` for the `instrument_id`.
278    ///
279    /// Index 0 is the most recently added quote; index 1 is the previous insertion.
280    /// Entries are not sorted by timestamp. Returns `None` when no quote exists at the index.
281    #[pyo3(name = "quote", signature = (instrument_id, index=0))]
282    fn py_quote(&self, instrument_id: InstrumentId, index: usize) -> Option<QuoteTick> {
283        self.0
284            .borrow()
285            .quote_at_index(&instrument_id, index)
286            .copied()
287    }
288
289    /// Returns the trade at `index` for the `instrument_id`.
290    ///
291    /// Index 0 is the most recently added trade; index 1 is the previous insertion.
292    /// Entries are not sorted by timestamp. Returns `None` when no trade exists at the index.
293    #[pyo3(name = "trade", signature = (instrument_id, index=0))]
294    fn py_trade(&self, instrument_id: InstrumentId, index: usize) -> Option<TradeTick> {
295        self.0
296            .borrow()
297            .trade_at_index(&instrument_id, index)
298            .copied()
299    }
300
301    /// Returns the bar at `index` for the `bar_type`.
302    ///
303    /// Bars are ordered by `ts_event`, newest first. Index 0 is the most recent bar;
304    /// index 1 is the previous bar. Returns `None` when no bar exists at the index.
305    #[pyo3(name = "bar", signature = (bar_type, index=0))]
306    fn py_bar(&self, bar_type: BarType, index: usize) -> Option<Bar> {
307        self.0.borrow().bar_at_index(&bar_type, index).copied()
308    }
309
310    /// Returns cached quotes for the `instrument_id` in reverse insertion order.
311    ///
312    /// Index 0 is the most recently added quote. Entries are not sorted by timestamp.
313    /// Returns `None` when no quotes are cached for the instrument.
314    #[pyo3(name = "quotes")]
315    fn py_quotes(&self, instrument_id: InstrumentId) -> Option<Vec<QuoteTick>> {
316        self.0.borrow().quotes(&instrument_id)
317    }
318
319    /// Returns cached trades for the `instrument_id` in reverse insertion order.
320    ///
321    /// Index 0 is the most recently added trade. Entries are not sorted by timestamp.
322    /// Returns `None` when no trades are cached for the instrument.
323    #[pyo3(name = "trades")]
324    fn py_trades(&self, instrument_id: InstrumentId) -> Option<Vec<TradeTick>> {
325        self.0.borrow().trades(&instrument_id)
326    }
327
328    /// Returns cached bars for the `bar_type` in reverse chronological order by `ts_event`.
329    ///
330    /// Index 0 is the most recent bar. Returns `None` when no bars are cached for the bar type.
331    #[pyo3(name = "bars")]
332    fn py_bars(&self, bar_type: BarType) -> Option<Vec<Bar>> {
333        self.0.borrow().bars(&bar_type)
334    }
335
336    /// Returns the most recently added custom data for the `data_type`, or `None` if absent.
337    #[pyo3(name = "custom_data")]
338    fn py_custom_data(&self, data_type: &DataType) -> Option<CustomData> {
339        self.0.borrow().custom_data(data_type).cloned()
340    }
341
342    /// Returns custom data at `index` for the `data_type`.
343    ///
344    /// Index 0 is the most recently added item. Entries are not sorted by timestamp.
345    /// Returns `None` when no item exists at the index.
346    #[pyo3(name = "custom_data_at_index")]
347    fn py_custom_data_at_index(&self, data_type: &DataType, index: usize) -> Option<CustomData> {
348        self.0
349            .borrow()
350            .custom_data_at_index(data_type, index)
351            .cloned()
352    }
353
354    /// Returns custom data for the `data_type` in reverse insertion order.
355    ///
356    /// Entries are not sorted by timestamp. The history is empty when no data is cached.
357    #[pyo3(name = "custom_data_history")]
358    fn py_custom_data_history(&self, data_type: &DataType) -> Vec<CustomData> {
359        self.0.borrow().custom_data_history(data_type)
360    }
361
362    #[pyo3(name = "bar_types", signature = (aggregation_source, instrument_id=None, price_type=None))]
363    fn py_bar_types(
364        &self,
365        aggregation_source: AggregationSource,
366        instrument_id: Option<InstrumentId>,
367        price_type: Option<PriceType>,
368    ) -> Vec<BarType> {
369        self.0
370            .borrow()
371            .bar_types(
372                instrument_id.as_ref(),
373                price_type.as_ref(),
374                aggregation_source,
375            )
376            .into_iter()
377            .copied()
378            .collect()
379    }
380
381    /// Returns the mark price update at `index` for the `instrument_id`.
382    ///
383    /// Index 0 is the most recently added update; index 1 is the previous insertion.
384    /// Entries are not sorted by timestamp. Returns `None` when no update exists at the index.
385    #[pyo3(name = "mark_price", signature = (instrument_id, index=0))]
386    fn py_mark_price(&self, instrument_id: InstrumentId, index: usize) -> Option<MarkPriceUpdate> {
387        self.0
388            .borrow()
389            .mark_price_at_index(&instrument_id, index)
390            .copied()
391    }
392
393    /// Returns cached mark price updates for the `instrument_id` in reverse insertion order.
394    ///
395    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
396    /// Returns `None` when no mark price updates are cached for the instrument.
397    #[pyo3(name = "mark_prices")]
398    fn py_mark_prices(&self, instrument_id: InstrumentId) -> Option<Vec<MarkPriceUpdate>> {
399        self.0.borrow().mark_prices(&instrument_id)
400    }
401
402    /// Returns the index price update at `index` for the `instrument_id`.
403    ///
404    /// Index 0 is the most recently added update; index 1 is the previous insertion.
405    /// Entries are not sorted by timestamp. Returns `None` when no update exists at the index.
406    #[pyo3(name = "index_price", signature = (instrument_id, index=0))]
407    fn py_index_price(
408        &self,
409        instrument_id: InstrumentId,
410        index: usize,
411    ) -> Option<IndexPriceUpdate> {
412        self.0
413            .borrow()
414            .index_price_at_index(&instrument_id, index)
415            .copied()
416    }
417
418    /// Returns cached index price updates for the `instrument_id` in reverse insertion order.
419    ///
420    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
421    /// Returns `None` when no index price updates are cached for the instrument.
422    #[pyo3(name = "index_prices")]
423    fn py_index_prices(&self, instrument_id: InstrumentId) -> Option<Vec<IndexPriceUpdate>> {
424        self.0.borrow().index_prices(&instrument_id)
425    }
426
427    /// Returns the funding rate update at `index` for the `instrument_id`.
428    ///
429    /// Index 0 is the most recently added update; index 1 is the previous insertion.
430    /// Entries are not sorted by timestamp. Returns `None` when no update exists at the index.
431    #[pyo3(name = "funding_rate", signature = (instrument_id, index=0))]
432    fn py_funding_rate(
433        &self,
434        instrument_id: InstrumentId,
435        index: usize,
436    ) -> Option<FundingRateUpdate> {
437        self.0
438            .borrow()
439            .funding_rate_at_index(&instrument_id, index)
440            .copied()
441    }
442
443    /// Returns cached funding rate updates for the `instrument_id` in reverse insertion order.
444    ///
445    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
446    /// Returns `None` when no funding rate updates are cached for the instrument.
447    #[pyo3(name = "funding_rates")]
448    fn py_funding_rates(&self, instrument_id: InstrumentId) -> Option<Vec<FundingRateUpdate>> {
449        self.0.borrow().funding_rates(&instrument_id)
450    }
451
452    /// Returns the most recently added instrument status for the `instrument_id`, or `None` if absent.
453    #[pyo3(name = "instrument_status")]
454    fn py_instrument_status(&self, instrument_id: InstrumentId) -> Option<InstrumentStatus> {
455        self.0.borrow().instrument_status(&instrument_id).copied()
456    }
457
458    /// Returns cached instrument status updates for the `instrument_id` in reverse insertion order.
459    ///
460    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
461    /// Returns `None` when no instrument status updates are cached for the instrument.
462    #[pyo3(name = "instrument_statuses")]
463    fn py_instrument_statuses(&self, instrument_id: InstrumentId) -> Option<Vec<InstrumentStatus>> {
464        self.0.borrow().instrument_statuses(&instrument_id)
465    }
466
467    /// Returns the close cached for `instrument_id`, if present.
468    ///
469    /// A later insertion replaces the cached close for the instrument; no history is kept.
470    #[pyo3(name = "instrument_close")]
471    fn py_instrument_close(&self, instrument_id: InstrumentId) -> Option<InstrumentClose> {
472        self.0.borrow().instrument_close(&instrument_id).copied()
473    }
474
475    #[pyo3(name = "price")]
476    fn py_price(&self, instrument_id: InstrumentId, price_type: PriceType) -> Option<Price> {
477        self.0.borrow().price(&instrument_id, price_type)
478    }
479
480    /// Returns the current order book for the `instrument_id`, or `None` if absent.
481    ///
482    /// The cache holds the current book state, not a history of book updates.
483    #[pyo3(name = "order_book")]
484    fn py_order_book(&self, instrument_id: InstrumentId) -> Option<OrderBook> {
485        self.0.borrow().order_book(&instrument_id).cloned()
486    }
487
488    /// Returns the best bid/ask price and size for the `instrument_id`, without cloning the
489    /// resident order book.
490    ///
491    /// Returns `(bid_price, bid_size, ask_price, ask_size)`, or `None` if the book is
492    /// missing, empty, or one-sided.
493    ///
494    /// For L3 books, each size is the first order's size at the best level, not the
495    /// aggregate level size, consistent with the order book's best-size getters.
496    ///
497    /// Prefer this over `order_book()` in hot paths that only need top-of-book values, since
498    /// `order_book()` clones the full book and its cost scales with depth.
499    #[pyo3(name = "top_of_book")]
500    fn py_top_of_book(
501        &self,
502        instrument_id: InstrumentId,
503    ) -> Option<(Price, Quantity, Price, Quantity)> {
504        let cache = self.0.borrow();
505        let book = cache.order_book(&instrument_id)?;
506        Some((
507            book.best_bid_price()?,
508            book.best_bid_size()?,
509            book.best_ask_price()?,
510            book.best_ask_size()?,
511        ))
512    }
513
514    #[pyo3(name = "has_order_book")]
515    fn py_has_order_book(&self, instrument_id: InstrumentId) -> bool {
516        self.0.borrow().has_order_book(&instrument_id)
517    }
518
519    #[pyo3(name = "book_update_count")]
520    fn py_book_update_count(&self, instrument_id: InstrumentId) -> usize {
521        self.0.borrow().book_update_count(&instrument_id)
522    }
523
524    #[pyo3(name = "has_quote_ticks")]
525    fn py_has_quote_ticks(&self, instrument_id: InstrumentId) -> bool {
526        self.0.borrow().has_quote_ticks(&instrument_id)
527    }
528
529    #[pyo3(name = "has_trade_ticks")]
530    fn py_has_trade_ticks(&self, instrument_id: InstrumentId) -> bool {
531        self.0.borrow().has_trade_ticks(&instrument_id)
532    }
533
534    #[pyo3(name = "has_mark_prices")]
535    fn py_has_mark_prices(&self, instrument_id: InstrumentId) -> bool {
536        self.0.borrow().has_mark_prices(&instrument_id)
537    }
538
539    #[pyo3(name = "has_index_prices")]
540    fn py_has_index_prices(&self, instrument_id: InstrumentId) -> bool {
541        self.0.borrow().has_index_prices(&instrument_id)
542    }
543
544    #[pyo3(name = "has_funding_rates")]
545    fn py_has_funding_rates(&self, instrument_id: InstrumentId) -> bool {
546        self.0.borrow().has_funding_rates(&instrument_id)
547    }
548
549    #[pyo3(name = "has_instrument_statuses")]
550    fn py_has_instrument_statuses(&self, instrument_id: InstrumentId) -> bool {
551        self.0.borrow().has_instrument_statuses(&instrument_id)
552    }
553
554    #[pyo3(name = "has_instrument_close")]
555    fn py_has_instrument_close(&self, instrument_id: InstrumentId) -> bool {
556        self.0.borrow().has_instrument_close(&instrument_id)
557    }
558
559    #[pyo3(name = "has_bars")]
560    fn py_has_bars(&self, bar_type: BarType) -> bool {
561        self.0.borrow().has_bars(&bar_type)
562    }
563
564    #[pyo3(name = "quote_count")]
565    fn py_quote_count(&self, instrument_id: InstrumentId) -> usize {
566        self.0.borrow().quote_count(&instrument_id)
567    }
568
569    #[pyo3(name = "trade_count")]
570    fn py_trade_count(&self, instrument_id: InstrumentId) -> usize {
571        self.0.borrow().trade_count(&instrument_id)
572    }
573
574    #[pyo3(name = "mark_price_count")]
575    fn py_mark_price_count(&self, instrument_id: InstrumentId) -> usize {
576        self.0.borrow().mark_price_count(&instrument_id)
577    }
578
579    #[pyo3(name = "index_price_count")]
580    fn py_index_price_count(&self, instrument_id: InstrumentId) -> usize {
581        self.0.borrow().index_price_count(&instrument_id)
582    }
583
584    #[pyo3(name = "funding_rate_count")]
585    fn py_funding_rate_count(&self, instrument_id: InstrumentId) -> usize {
586        self.0.borrow().funding_rate_count(&instrument_id)
587    }
588
589    #[pyo3(name = "instrument_status_count")]
590    fn py_instrument_status_count(&self, instrument_id: InstrumentId) -> usize {
591        self.0.borrow().instrument_status_count(&instrument_id)
592    }
593
594    #[pyo3(name = "bar_count")]
595    fn py_bar_count(&self, bar_type: BarType) -> usize {
596        self.0.borrow().bar_count(&bar_type)
597    }
598
599    #[pyo3(name = "get_xrate")]
600    fn py_get_xrate(
601        &self,
602        venue: Venue,
603        from_currency: Currency,
604        to_currency: Currency,
605        price_type: PriceType,
606    ) -> Option<f64> {
607        self.0
608            .borrow()
609            .get_xrate(venue, from_currency, to_currency, price_type)
610            .and_then(|rate| rate.to_f64())
611    }
612
613    #[pyo3(name = "get_mark_xrate")]
614    fn py_get_mark_xrate(&self, from_currency: Currency, to_currency: Currency) -> Option<f64> {
615        self.0.borrow().get_mark_xrate(from_currency, to_currency)
616    }
617
618    #[pyo3(name = "own_order_book")]
619    fn py_own_order_book(&self, instrument_id: InstrumentId) -> Option<OwnOrderBook> {
620        self.0.borrow().own_order_book(&instrument_id).cloned()
621    }
622
623    #[pyo3(name = "instrument")]
624    fn py_instrument(
625        &self,
626        py: Python,
627        instrument_id: InstrumentId,
628    ) -> PyResult<Option<Py<PyAny>>> {
629        let cache = self.0.borrow();
630        match cache.instrument(&instrument_id) {
631            Some(instrument) => Ok(Some(instrument_any_to_pyobject(py, instrument.clone())?)),
632            None => Ok(None),
633        }
634    }
635
636    #[pyo3(name = "instrument_ids", signature = (venue=None))]
637    fn py_instrument_ids(&self, venue: Option<Venue>) -> Vec<InstrumentId> {
638        self.0
639            .borrow()
640            .instrument_ids(venue.as_ref())
641            .into_iter()
642            .copied()
643            .collect()
644    }
645
646    #[pyo3(name = "instruments", signature = (venue=None))]
647    fn py_instruments(&self, py: Python, venue: Option<Venue>) -> PyResult<Vec<Py<PyAny>>> {
648        let cache = self.0.borrow();
649        let mut py_instruments = Vec::new();
650
651        match venue {
652            Some(venue) => {
653                for instrument in cache.instruments(&venue, None) {
654                    py_instruments.push(instrument_any_to_pyobject(py, (*instrument).clone())?);
655                }
656            }
657            None => {
658                for instrument_id in cache.instrument_ids(None) {
659                    if let Some(instrument) = cache.instrument(instrument_id) {
660                        py_instruments.push(instrument_any_to_pyobject(py, instrument.clone())?);
661                    }
662                }
663            }
664        }
665        Ok(py_instruments)
666    }
667
668    #[pyo3(name = "synthetic")]
669    fn py_synthetic(&self, instrument_id: InstrumentId) -> Option<SyntheticInstrument> {
670        self.0.borrow().synthetic(&instrument_id).cloned()
671    }
672
673    #[pyo3(name = "synthetic_ids")]
674    fn py_synthetic_ids(&self) -> Vec<InstrumentId> {
675        self.0
676            .borrow()
677            .synthetic_ids()
678            .into_iter()
679            .copied()
680            .collect()
681    }
682
683    #[pyo3(name = "account")]
684    fn py_account(&self, py: Python, account_id: AccountId) -> PyResult<Option<Py<PyAny>>> {
685        let cache = self.0.borrow();
686        match cache.account(&account_id) {
687            Some(account) => Ok(Some(account_any_to_pyobject(py, account.clone())?)),
688            None => Ok(None),
689        }
690    }
691
692    #[pyo3(name = "account_for_venue")]
693    fn py_account_for_venue(&self, py: Python, venue: Venue) -> PyResult<Option<Py<PyAny>>> {
694        let cache = self.0.borrow();
695        match cache.account_for_venue(&venue) {
696            Some(account) => Ok(Some(account_any_to_pyobject(py, account.clone())?)),
697            None => Ok(None),
698        }
699    }
700
701    #[pyo3(name = "account_id")]
702    fn py_account_id(&self, venue: Venue) -> Option<AccountId> {
703        self.0.borrow().account_id(&venue).copied()
704    }
705
706    #[pyo3(name = "client_order_ids", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
707    fn py_client_order_ids(
708        &self,
709        venue: Option<Venue>,
710        instrument_id: Option<InstrumentId>,
711        strategy_id: Option<StrategyId>,
712        account_id: Option<AccountId>,
713    ) -> Vec<ClientOrderId> {
714        self.0
715            .borrow()
716            .client_order_ids(
717                venue.as_ref(),
718                instrument_id.as_ref(),
719                strategy_id.as_ref(),
720                account_id.as_ref(),
721            )
722            .into_iter()
723            .collect()
724    }
725
726    #[pyo3(name = "client_order_ids_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
727    fn py_client_order_ids_open(
728        &self,
729        venue: Option<Venue>,
730        instrument_id: Option<InstrumentId>,
731        strategy_id: Option<StrategyId>,
732        account_id: Option<AccountId>,
733    ) -> Vec<ClientOrderId> {
734        self.0
735            .borrow()
736            .client_order_ids_open(
737                venue.as_ref(),
738                instrument_id.as_ref(),
739                strategy_id.as_ref(),
740                account_id.as_ref(),
741            )
742            .into_iter()
743            .collect()
744    }
745
746    #[pyo3(name = "client_order_ids_closed", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
747    fn py_client_order_ids_closed(
748        &self,
749        venue: Option<Venue>,
750        instrument_id: Option<InstrumentId>,
751        strategy_id: Option<StrategyId>,
752        account_id: Option<AccountId>,
753    ) -> Vec<ClientOrderId> {
754        self.0
755            .borrow()
756            .client_order_ids_closed(
757                venue.as_ref(),
758                instrument_id.as_ref(),
759                strategy_id.as_ref(),
760                account_id.as_ref(),
761            )
762            .into_iter()
763            .collect()
764    }
765
766    #[pyo3(name = "client_order_ids_emulated", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
767    fn py_client_order_ids_emulated(
768        &self,
769        venue: Option<Venue>,
770        instrument_id: Option<InstrumentId>,
771        strategy_id: Option<StrategyId>,
772        account_id: Option<AccountId>,
773    ) -> Vec<ClientOrderId> {
774        self.0
775            .borrow()
776            .client_order_ids_emulated(
777                venue.as_ref(),
778                instrument_id.as_ref(),
779                strategy_id.as_ref(),
780                account_id.as_ref(),
781            )
782            .into_iter()
783            .collect()
784    }
785
786    #[pyo3(name = "client_order_ids_inflight", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
787    fn py_client_order_ids_inflight(
788        &self,
789        venue: Option<Venue>,
790        instrument_id: Option<InstrumentId>,
791        strategy_id: Option<StrategyId>,
792        account_id: Option<AccountId>,
793    ) -> Vec<ClientOrderId> {
794        self.0
795            .borrow()
796            .client_order_ids_inflight(
797                venue.as_ref(),
798                instrument_id.as_ref(),
799                strategy_id.as_ref(),
800                account_id.as_ref(),
801            )
802            .into_iter()
803            .collect()
804    }
805
806    #[pyo3(name = "position_ids", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
807    fn py_position_ids(
808        &self,
809        venue: Option<Venue>,
810        instrument_id: Option<InstrumentId>,
811        strategy_id: Option<StrategyId>,
812        account_id: Option<AccountId>,
813    ) -> Vec<PositionId> {
814        self.0
815            .borrow()
816            .position_ids(
817                venue.as_ref(),
818                instrument_id.as_ref(),
819                strategy_id.as_ref(),
820                account_id.as_ref(),
821            )
822            .into_iter()
823            .collect()
824    }
825
826    #[pyo3(name = "position_open_ids", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
827    fn py_position_open_ids(
828        &self,
829        venue: Option<Venue>,
830        instrument_id: Option<InstrumentId>,
831        strategy_id: Option<StrategyId>,
832        account_id: Option<AccountId>,
833    ) -> Vec<PositionId> {
834        self.0
835            .borrow()
836            .position_open_ids(
837                venue.as_ref(),
838                instrument_id.as_ref(),
839                strategy_id.as_ref(),
840                account_id.as_ref(),
841            )
842            .into_iter()
843            .collect()
844    }
845
846    #[pyo3(name = "position_closed_ids", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
847    fn py_position_closed_ids(
848        &self,
849        venue: Option<Venue>,
850        instrument_id: Option<InstrumentId>,
851        strategy_id: Option<StrategyId>,
852        account_id: Option<AccountId>,
853    ) -> Vec<PositionId> {
854        self.0
855            .borrow()
856            .position_closed_ids(
857                venue.as_ref(),
858                instrument_id.as_ref(),
859                strategy_id.as_ref(),
860                account_id.as_ref(),
861            )
862            .into_iter()
863            .collect()
864    }
865
866    #[pyo3(name = "strategy_ids")]
867    fn py_strategy_ids(&self) -> Vec<StrategyId> {
868        self.0.borrow().strategy_ids().into_iter().collect()
869    }
870
871    #[pyo3(name = "exec_algorithm_ids")]
872    fn py_exec_algorithm_ids(&self) -> Vec<ExecAlgorithmId> {
873        self.0.borrow().exec_algorithm_ids().into_iter().collect()
874    }
875
876    #[pyo3(name = "order")]
877    fn py_order(&self, py: Python, client_order_id: ClientOrderId) -> PyResult<Option<Py<PyAny>>> {
878        let cache = self.0.borrow();
879        match cache.order(&client_order_id) {
880            Some(order) => Ok(Some(order_any_to_pyobject(py, order.clone())?)),
881            None => Ok(None),
882        }
883    }
884
885    #[pyo3(name = "client_order_id")]
886    fn py_client_order_id(&self, venue_order_id: VenueOrderId) -> Option<ClientOrderId> {
887        self.0.borrow().client_order_id(&venue_order_id).copied()
888    }
889
890    #[pyo3(name = "venue_order_id")]
891    fn py_venue_order_id(&self, client_order_id: ClientOrderId) -> Option<VenueOrderId> {
892        self.0.borrow().venue_order_id(&client_order_id).copied()
893    }
894
895    #[pyo3(name = "client_id")]
896    fn py_client_id(&self, client_order_id: ClientOrderId) -> Option<ClientId> {
897        self.0.borrow().client_id(&client_order_id).copied()
898    }
899
900    #[pyo3(name = "orders", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
901    fn py_orders(
902        &self,
903        py: Python,
904        venue: Option<Venue>,
905        instrument_id: Option<InstrumentId>,
906        strategy_id: Option<StrategyId>,
907        account_id: Option<AccountId>,
908        side: Option<OrderSide>,
909    ) -> PyResult<Vec<Py<PyAny>>> {
910        let cache = self.0.borrow();
911        cache
912            .orders(
913                venue.as_ref(),
914                instrument_id.as_ref(),
915                strategy_id.as_ref(),
916                account_id.as_ref(),
917                side,
918            )
919            .into_iter()
920            .map(|o| order_any_to_pyobject(py, o.clone()))
921            .collect()
922    }
923
924    #[pyo3(name = "orders_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
925    fn py_orders_open(
926        &self,
927        py: Python,
928        venue: Option<Venue>,
929        instrument_id: Option<InstrumentId>,
930        strategy_id: Option<StrategyId>,
931        account_id: Option<AccountId>,
932        side: Option<OrderSide>,
933    ) -> PyResult<Vec<Py<PyAny>>> {
934        let cache = self.0.borrow();
935        cache
936            .orders_open(
937                venue.as_ref(),
938                instrument_id.as_ref(),
939                strategy_id.as_ref(),
940                account_id.as_ref(),
941                side,
942            )
943            .into_iter()
944            .map(|o| order_any_to_pyobject(py, o.clone()))
945            .collect()
946    }
947
948    #[pyo3(name = "orders_closed", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
949    fn py_orders_closed(
950        &self,
951        py: Python,
952        venue: Option<Venue>,
953        instrument_id: Option<InstrumentId>,
954        strategy_id: Option<StrategyId>,
955        account_id: Option<AccountId>,
956        side: Option<OrderSide>,
957    ) -> PyResult<Vec<Py<PyAny>>> {
958        let cache = self.0.borrow();
959        cache
960            .orders_closed(
961                venue.as_ref(),
962                instrument_id.as_ref(),
963                strategy_id.as_ref(),
964                account_id.as_ref(),
965                side,
966            )
967            .into_iter()
968            .map(|o| order_any_to_pyobject(py, o.clone()))
969            .collect()
970    }
971
972    #[pyo3(name = "orders_emulated", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
973    fn py_orders_emulated(
974        &self,
975        py: Python,
976        venue: Option<Venue>,
977        instrument_id: Option<InstrumentId>,
978        strategy_id: Option<StrategyId>,
979        account_id: Option<AccountId>,
980        side: Option<OrderSide>,
981    ) -> PyResult<Vec<Py<PyAny>>> {
982        let cache = self.0.borrow();
983        cache
984            .orders_emulated(
985                venue.as_ref(),
986                instrument_id.as_ref(),
987                strategy_id.as_ref(),
988                account_id.as_ref(),
989                side,
990            )
991            .into_iter()
992            .map(|o| order_any_to_pyobject(py, o.clone()))
993            .collect()
994    }
995
996    #[pyo3(name = "orders_inflight", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
997    fn py_orders_inflight(
998        &self,
999        py: Python,
1000        venue: Option<Venue>,
1001        instrument_id: Option<InstrumentId>,
1002        strategy_id: Option<StrategyId>,
1003        account_id: Option<AccountId>,
1004        side: Option<OrderSide>,
1005    ) -> PyResult<Vec<Py<PyAny>>> {
1006        let cache = self.0.borrow();
1007        cache
1008            .orders_inflight(
1009                venue.as_ref(),
1010                instrument_id.as_ref(),
1011                strategy_id.as_ref(),
1012                account_id.as_ref(),
1013                side,
1014            )
1015            .into_iter()
1016            .map(|o| order_any_to_pyobject(py, o.clone()))
1017            .collect()
1018    }
1019
1020    #[pyo3(name = "orders_for_position")]
1021    fn py_orders_for_position(
1022        &self,
1023        py: Python,
1024        position_id: PositionId,
1025    ) -> PyResult<Vec<Py<PyAny>>> {
1026        let cache = self.0.borrow();
1027        cache
1028            .orders_for_position(&position_id)
1029            .into_iter()
1030            .map(|o| order_any_to_pyobject(py, o.clone()))
1031            .collect()
1032    }
1033
1034    #[pyo3(name = "order_exists")]
1035    fn py_order_exists(&self, client_order_id: ClientOrderId) -> bool {
1036        self.0.borrow().order_exists(&client_order_id)
1037    }
1038
1039    #[pyo3(name = "is_order_open")]
1040    fn py_is_order_open(&self, client_order_id: ClientOrderId) -> bool {
1041        self.0.borrow().is_order_open(&client_order_id)
1042    }
1043
1044    #[pyo3(name = "is_order_closed")]
1045    fn py_is_order_closed(&self, client_order_id: ClientOrderId) -> bool {
1046        self.0.borrow().is_order_closed(&client_order_id)
1047    }
1048
1049    #[pyo3(name = "is_order_emulated")]
1050    fn py_is_order_emulated(&self, client_order_id: ClientOrderId) -> bool {
1051        self.0.borrow().is_order_emulated(&client_order_id)
1052    }
1053
1054    #[pyo3(name = "is_order_inflight")]
1055    fn py_is_order_inflight(&self, client_order_id: ClientOrderId) -> bool {
1056        self.0.borrow().is_order_inflight(&client_order_id)
1057    }
1058
1059    #[pyo3(name = "is_order_pending_cancel_local")]
1060    fn py_is_order_pending_cancel_local(&self, client_order_id: ClientOrderId) -> bool {
1061        self.0
1062            .borrow()
1063            .is_order_pending_cancel_local(&client_order_id)
1064    }
1065
1066    #[pyo3(name = "orders_open_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1067    fn py_orders_open_count(
1068        &self,
1069        venue: Option<Venue>,
1070        instrument_id: Option<InstrumentId>,
1071        strategy_id: Option<StrategyId>,
1072        account_id: Option<AccountId>,
1073        side: Option<OrderSide>,
1074    ) -> usize {
1075        self.0.borrow().orders_open_count(
1076            venue.as_ref(),
1077            instrument_id.as_ref(),
1078            strategy_id.as_ref(),
1079            account_id.as_ref(),
1080            side,
1081        )
1082    }
1083
1084    #[pyo3(name = "orders_closed_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1085    fn py_orders_closed_count(
1086        &self,
1087        venue: Option<Venue>,
1088        instrument_id: Option<InstrumentId>,
1089        strategy_id: Option<StrategyId>,
1090        account_id: Option<AccountId>,
1091        side: Option<OrderSide>,
1092    ) -> usize {
1093        self.0.borrow().orders_closed_count(
1094            venue.as_ref(),
1095            instrument_id.as_ref(),
1096            strategy_id.as_ref(),
1097            account_id.as_ref(),
1098            side,
1099        )
1100    }
1101
1102    #[pyo3(name = "orders_emulated_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1103    fn py_orders_emulated_count(
1104        &self,
1105        venue: Option<Venue>,
1106        instrument_id: Option<InstrumentId>,
1107        strategy_id: Option<StrategyId>,
1108        account_id: Option<AccountId>,
1109        side: Option<OrderSide>,
1110    ) -> usize {
1111        self.0.borrow().orders_emulated_count(
1112            venue.as_ref(),
1113            instrument_id.as_ref(),
1114            strategy_id.as_ref(),
1115            account_id.as_ref(),
1116            side,
1117        )
1118    }
1119
1120    #[pyo3(name = "orders_inflight_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1121    fn py_orders_inflight_count(
1122        &self,
1123        venue: Option<Venue>,
1124        instrument_id: Option<InstrumentId>,
1125        strategy_id: Option<StrategyId>,
1126        account_id: Option<AccountId>,
1127        side: Option<OrderSide>,
1128    ) -> usize {
1129        self.0.borrow().orders_inflight_count(
1130            venue.as_ref(),
1131            instrument_id.as_ref(),
1132            strategy_id.as_ref(),
1133            account_id.as_ref(),
1134            side,
1135        )
1136    }
1137
1138    #[pyo3(name = "orders_total_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1139    fn py_orders_total_count(
1140        &self,
1141        venue: Option<Venue>,
1142        instrument_id: Option<InstrumentId>,
1143        strategy_id: Option<StrategyId>,
1144        account_id: Option<AccountId>,
1145        side: Option<OrderSide>,
1146    ) -> usize {
1147        self.0.borrow().orders_total_count(
1148            venue.as_ref(),
1149            instrument_id.as_ref(),
1150            strategy_id.as_ref(),
1151            account_id.as_ref(),
1152            side,
1153        )
1154    }
1155
1156    #[pyo3(name = "order_list")]
1157    fn py_order_list(&self, order_list_id: OrderListId) -> Option<OrderList> {
1158        self.0.borrow().order_list(&order_list_id).cloned()
1159    }
1160
1161    #[pyo3(name = "order_lists", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None))]
1162    fn py_order_lists(
1163        &self,
1164        venue: Option<Venue>,
1165        instrument_id: Option<InstrumentId>,
1166        strategy_id: Option<StrategyId>,
1167        account_id: Option<AccountId>,
1168    ) -> Vec<OrderList> {
1169        let cache = self.0.borrow();
1170        cache
1171            .order_lists(
1172                venue.as_ref(),
1173                instrument_id.as_ref(),
1174                strategy_id.as_ref(),
1175                account_id.as_ref(),
1176            )
1177            .into_iter()
1178            .cloned()
1179            .collect()
1180    }
1181
1182    #[pyo3(name = "order_list_exists")]
1183    fn py_order_list_exists(&self, order_list_id: OrderListId) -> bool {
1184        self.0.borrow().order_list_exists(&order_list_id)
1185    }
1186
1187    #[pyo3(name = "orders_for_exec_algorithm", signature = (exec_algorithm_id, venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1188    #[expect(clippy::too_many_arguments)]
1189    fn py_orders_for_exec_algorithm(
1190        &self,
1191        py: Python,
1192        exec_algorithm_id: ExecAlgorithmId,
1193        venue: Option<Venue>,
1194        instrument_id: Option<InstrumentId>,
1195        strategy_id: Option<StrategyId>,
1196        account_id: Option<AccountId>,
1197        side: Option<OrderSide>,
1198    ) -> PyResult<Vec<Py<PyAny>>> {
1199        let cache = self.0.borrow();
1200        cache
1201            .orders_for_exec_algorithm(
1202                &exec_algorithm_id,
1203                venue.as_ref(),
1204                instrument_id.as_ref(),
1205                strategy_id.as_ref(),
1206                account_id.as_ref(),
1207                side,
1208            )
1209            .into_iter()
1210            .map(|o| order_any_to_pyobject(py, o.clone()))
1211            .collect()
1212    }
1213
1214    #[pyo3(name = "orders_for_exec_spawn")]
1215    fn py_orders_for_exec_spawn(
1216        &self,
1217        py: Python,
1218        exec_spawn_id: ClientOrderId,
1219    ) -> PyResult<Vec<Py<PyAny>>> {
1220        let cache = self.0.borrow();
1221        cache
1222            .orders_for_exec_spawn(&exec_spawn_id)
1223            .into_iter()
1224            .map(|o| order_any_to_pyobject(py, o.clone()))
1225            .collect()
1226    }
1227
1228    #[pyo3(name = "exec_spawn_total_quantity")]
1229    fn py_exec_spawn_total_quantity(
1230        &self,
1231        exec_spawn_id: ClientOrderId,
1232        active_only: bool,
1233    ) -> Option<Quantity> {
1234        self.0
1235            .borrow()
1236            .exec_spawn_total_quantity(&exec_spawn_id, active_only)
1237    }
1238
1239    #[pyo3(name = "exec_spawn_total_filled_qty")]
1240    fn py_exec_spawn_total_filled_qty(
1241        &self,
1242        exec_spawn_id: ClientOrderId,
1243        active_only: bool,
1244    ) -> Option<Quantity> {
1245        self.0
1246            .borrow()
1247            .exec_spawn_total_filled_qty(&exec_spawn_id, active_only)
1248    }
1249
1250    #[pyo3(name = "exec_spawn_total_leaves_qty")]
1251    fn py_exec_spawn_total_leaves_qty(
1252        &self,
1253        exec_spawn_id: ClientOrderId,
1254        active_only: bool,
1255    ) -> Option<Quantity> {
1256        self.0
1257            .borrow()
1258            .exec_spawn_total_leaves_qty(&exec_spawn_id, active_only)
1259    }
1260
1261    #[pyo3(name = "position")]
1262    fn py_position(&self, py: Python, position_id: PositionId) -> PyResult<Option<Py<PyAny>>> {
1263        let cache = self.0.borrow();
1264        match cache.position(&position_id) {
1265            Some(position) => Ok(Some(position.clone().into_pyobject(py)?.into())),
1266            None => Ok(None),
1267        }
1268    }
1269
1270    #[pyo3(name = "position_for_order")]
1271    fn py_position_for_order(
1272        &self,
1273        py: Python,
1274        client_order_id: ClientOrderId,
1275    ) -> PyResult<Option<Py<PyAny>>> {
1276        let cache = self.0.borrow();
1277        match cache.position_for_order(&client_order_id) {
1278            Some(position) => Ok(Some(position.clone().into_pyobject(py)?.into())),
1279            None => Ok(None),
1280        }
1281    }
1282
1283    #[pyo3(name = "position_id")]
1284    fn py_position_id(&self, client_order_id: ClientOrderId) -> Option<PositionId> {
1285        self.0.borrow().position_id(&client_order_id).copied()
1286    }
1287
1288    #[pyo3(name = "positions", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1289    fn py_positions(
1290        &self,
1291        py: Python,
1292        venue: Option<Venue>,
1293        instrument_id: Option<InstrumentId>,
1294        strategy_id: Option<StrategyId>,
1295        account_id: Option<AccountId>,
1296        side: Option<PositionSide>,
1297    ) -> PyResult<Vec<Py<PyAny>>> {
1298        let cache = self.0.borrow();
1299        cache
1300            .positions(
1301                venue.as_ref(),
1302                instrument_id.as_ref(),
1303                strategy_id.as_ref(),
1304                account_id.as_ref(),
1305                side,
1306            )
1307            .into_iter()
1308            .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
1309            .collect()
1310    }
1311
1312    #[pyo3(name = "positions_open", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1313    fn py_positions_open(
1314        &self,
1315        py: Python,
1316        venue: Option<Venue>,
1317        instrument_id: Option<InstrumentId>,
1318        strategy_id: Option<StrategyId>,
1319        account_id: Option<AccountId>,
1320        side: Option<PositionSide>,
1321    ) -> PyResult<Vec<Py<PyAny>>> {
1322        let cache = self.0.borrow();
1323        cache
1324            .positions_open(
1325                venue.as_ref(),
1326                instrument_id.as_ref(),
1327                strategy_id.as_ref(),
1328                account_id.as_ref(),
1329                side,
1330            )
1331            .into_iter()
1332            .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
1333            .collect()
1334    }
1335
1336    #[pyo3(name = "positions_closed", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1337    fn py_positions_closed(
1338        &self,
1339        py: Python,
1340        venue: Option<Venue>,
1341        instrument_id: Option<InstrumentId>,
1342        strategy_id: Option<StrategyId>,
1343        account_id: Option<AccountId>,
1344        side: Option<PositionSide>,
1345    ) -> PyResult<Vec<Py<PyAny>>> {
1346        let cache = self.0.borrow();
1347        cache
1348            .positions_closed(
1349                venue.as_ref(),
1350                instrument_id.as_ref(),
1351                strategy_id.as_ref(),
1352                account_id.as_ref(),
1353                side,
1354            )
1355            .into_iter()
1356            .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
1357            .collect()
1358    }
1359
1360    #[pyo3(name = "position_exists")]
1361    fn py_position_exists(&self, position_id: PositionId) -> bool {
1362        self.0.borrow().position_exists(&position_id)
1363    }
1364
1365    #[pyo3(name = "is_position_open")]
1366    fn py_is_position_open(&self, position_id: PositionId) -> bool {
1367        self.0.borrow().is_position_open(&position_id)
1368    }
1369
1370    #[pyo3(name = "is_position_closed")]
1371    fn py_is_position_closed(&self, position_id: PositionId) -> bool {
1372        self.0.borrow().is_position_closed(&position_id)
1373    }
1374
1375    #[pyo3(name = "positions_open_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1376    fn py_positions_open_count(
1377        &self,
1378        venue: Option<Venue>,
1379        instrument_id: Option<InstrumentId>,
1380        strategy_id: Option<StrategyId>,
1381        account_id: Option<AccountId>,
1382        side: Option<PositionSide>,
1383    ) -> usize {
1384        self.0.borrow().positions_open_count(
1385            venue.as_ref(),
1386            instrument_id.as_ref(),
1387            strategy_id.as_ref(),
1388            account_id.as_ref(),
1389            side,
1390        )
1391    }
1392
1393    #[pyo3(name = "positions_closed_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1394    fn py_positions_closed_count(
1395        &self,
1396        venue: Option<Venue>,
1397        instrument_id: Option<InstrumentId>,
1398        strategy_id: Option<StrategyId>,
1399        account_id: Option<AccountId>,
1400        side: Option<PositionSide>,
1401    ) -> usize {
1402        self.0.borrow().positions_closed_count(
1403            venue.as_ref(),
1404            instrument_id.as_ref(),
1405            strategy_id.as_ref(),
1406            account_id.as_ref(),
1407            side,
1408        )
1409    }
1410
1411    #[pyo3(name = "positions_total_count", signature = (venue=None, instrument_id=None, strategy_id=None, account_id=None, side=None))]
1412    fn py_positions_total_count(
1413        &self,
1414        venue: Option<Venue>,
1415        instrument_id: Option<InstrumentId>,
1416        strategy_id: Option<StrategyId>,
1417        account_id: Option<AccountId>,
1418        side: Option<PositionSide>,
1419    ) -> usize {
1420        self.0.borrow().positions_total_count(
1421            venue.as_ref(),
1422            instrument_id.as_ref(),
1423            strategy_id.as_ref(),
1424            account_id.as_ref(),
1425            side,
1426        )
1427    }
1428
1429    #[pyo3(name = "strategy_id_for_order")]
1430    fn py_strategy_id_for_order(&self, client_order_id: ClientOrderId) -> Option<StrategyId> {
1431        self.0
1432            .borrow()
1433            .strategy_id_for_order(&client_order_id)
1434            .copied()
1435    }
1436
1437    #[pyo3(name = "strategy_id_for_position")]
1438    fn py_strategy_id_for_position(&self, position_id: PositionId) -> Option<StrategyId> {
1439        self.0
1440            .borrow()
1441            .strategy_id_for_position(&position_id)
1442            .copied()
1443    }
1444
1445    #[pyo3(name = "position_snapshot_bytes")]
1446    fn py_position_snapshot_bytes(&self, position_id: PositionId) -> Option<Vec<Vec<u8>>> {
1447        self.0.borrow().position_snapshot_bytes(&position_id)
1448    }
1449
1450    #[pyo3(name = "snapshot_position")]
1451    #[expect(clippy::needless_pass_by_value)]
1452    fn py_snapshot_position(&self, py: Python, position: Py<PyAny>) -> PyResult<()> {
1453        let position_obj = position.extract::<Position>(py)?;
1454        self.0
1455            .borrow_mut()
1456            .snapshot_position(&position_obj)
1457            .map_err(to_pyvalue_err)
1458    }
1459
1460    #[pyo3(name = "position_snapshots", signature = (position_id=None, account_id=None))]
1461    fn py_position_snapshots(
1462        &self,
1463        py: Python,
1464        position_id: Option<PositionId>,
1465        account_id: Option<AccountId>,
1466    ) -> PyResult<Vec<Py<PyAny>>> {
1467        let cache = self.0.borrow();
1468        cache
1469            .position_snapshots(position_id.as_ref(), account_id.as_ref())
1470            .into_iter()
1471            .map(|p| Ok(p.into_pyobject(py)?.into()))
1472            .collect()
1473    }
1474}
1475
1476#[cfg(test)]
1477mod tests {
1478    use nautilus_core::UnixNanos;
1479    use nautilus_model::{
1480        data::{BookOrder, stubs::stub_instrument_close},
1481        enums::{BookType, InstrumentCloseType},
1482    };
1483    use pyo3::exceptions::PyValueError;
1484    use rstest::rstest;
1485
1486    use super::*;
1487
1488    fn book_order(side: OrderSide, price: &str, size: &str, id: u64) -> BookOrder {
1489        BookOrder::new(side, Price::from(price), Quantity::from(size), id)
1490    }
1491
1492    #[rstest]
1493    fn test_top_of_book_missing() {
1494        let cache = PyCache::from_rc(Rc::new(RefCell::new(Cache::default())));
1495
1496        assert_eq!(
1497            cache.py_top_of_book(InstrumentId::from("AUD/USD.SIM")),
1498            None
1499        );
1500    }
1501
1502    #[rstest]
1503    #[case::empty(None)]
1504    #[case::bid_only(Some(OrderSide::Buy))]
1505    #[case::ask_only(Some(OrderSide::Sell))]
1506    fn test_top_of_book_incomplete(#[case] side: Option<OrderSide>) {
1507        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1508        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
1509        if let Some(side) = side {
1510            book.add(book_order(side, "0.70000", "10", 1), 0, 1, 1.into());
1511        }
1512        let mut cache = Cache::default();
1513        cache.add_order_book(book).unwrap();
1514        let cache = PyCache::from_rc(Rc::new(RefCell::new(cache)));
1515
1516        assert_eq!(cache.py_top_of_book(instrument_id), None);
1517    }
1518
1519    #[rstest]
1520    fn test_top_of_book_python_values_and_resident_updates() {
1521        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1522        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
1523        book.add(
1524            book_order(OrderSide::Buy, "0.70000", "10", 1),
1525            0,
1526            1,
1527            1.into(),
1528        );
1529        book.add(
1530            book_order(OrderSide::Sell, "0.70010", "20", 2),
1531            0,
1532            2,
1533            2.into(),
1534        );
1535        let mut cache = Cache::default();
1536        cache.add_order_book(book).unwrap();
1537        let cache = Rc::new(RefCell::new(cache));
1538
1539        Python::initialize();
1540        Python::attach(|py| {
1541            let py_cache = Py::new(py, PyCache::from_rc(cache.clone())).unwrap();
1542            let original = py_cache
1543                .call_method1(py, "top_of_book", (instrument_id,))
1544                .unwrap();
1545            let expected = (
1546                Price::from("0.70000"),
1547                Quantity::from("10"),
1548                Price::from("0.70010"),
1549                Quantity::from("20"),
1550            );
1551            assert_eq!(
1552                original
1553                    .extract::<(Price, Quantity, Price, Quantity)>(py)
1554                    .unwrap(),
1555                expected
1556            );
1557
1558            {
1559                let mut cache = cache.borrow_mut();
1560                let book = cache.order_book_mut(&instrument_id).unwrap();
1561                book.update(
1562                    book_order(OrderSide::Buy, "0.70000", "15", 1),
1563                    0,
1564                    3,
1565                    3.into(),
1566                );
1567                book.add(
1568                    book_order(OrderSide::Sell, "0.70005", "25", 3),
1569                    0,
1570                    4,
1571                    4.into(),
1572                );
1573            }
1574            let updated = py_cache
1575                .call_method1(py, "top_of_book", (instrument_id,))
1576                .unwrap()
1577                .extract::<(Price, Quantity, Price, Quantity)>(py)
1578                .unwrap();
1579            assert_eq!(
1580                updated,
1581                (
1582                    Price::from("0.70000"),
1583                    Quantity::from("15"),
1584                    Price::from("0.70005"),
1585                    Quantity::from("25"),
1586                )
1587            );
1588            assert_eq!(
1589                original
1590                    .extract::<(Price, Quantity, Price, Quantity)>(py)
1591                    .unwrap(),
1592                expected
1593            );
1594
1595            cache
1596                .borrow_mut()
1597                .order_book_mut(&instrument_id)
1598                .unwrap()
1599                .clear_asks(5, 5.into());
1600            assert!(
1601                py_cache
1602                    .call_method1(py, "top_of_book", (instrument_id,))
1603                    .unwrap()
1604                    .is_none(py)
1605            );
1606        });
1607    }
1608
1609    #[rstest]
1610    fn test_top_of_book_l3_returns_first_order_sizes() {
1611        let instrument_id = InstrumentId::from("AUD/USD.SIM");
1612        let mut book = OrderBook::new(instrument_id, BookType::L3_MBO);
1613        let first_bid = book_order(OrderSide::Buy, "0.70000", "10", 1);
1614        let first_ask = book_order(OrderSide::Sell, "0.70010", "20", 3);
1615        book.add(first_bid, 0, 1, 1.into());
1616        book.add(
1617            book_order(OrderSide::Buy, "0.70000", "30", 2),
1618            0,
1619            2,
1620            2.into(),
1621        );
1622        book.add(first_ask, 0, 3, 3.into());
1623        book.add(
1624            book_order(OrderSide::Sell, "0.70010", "40", 4),
1625            0,
1626            4,
1627            4.into(),
1628        );
1629        let mut cache = Cache::default();
1630        cache.add_order_book(book).unwrap();
1631        let cache = PyCache::from_rc(Rc::new(RefCell::new(cache)));
1632
1633        assert_eq!(
1634            cache.py_top_of_book(instrument_id),
1635            Some((
1636                Price::from("0.70000"),
1637                Quantity::from("10"),
1638                Price::from("0.70010"),
1639                Quantity::from("20"),
1640            ))
1641        );
1642
1643        {
1644            let mut inner = cache.0.borrow_mut();
1645            let book = inner.order_book_mut(&instrument_id).unwrap();
1646            book.delete(first_bid, 0, 5, 5.into());
1647            book.delete(first_ask, 0, 6, 6.into());
1648        }
1649        assert_eq!(
1650            cache.py_top_of_book(instrument_id),
1651            Some((
1652                Price::from("0.70000"),
1653                Quantity::from("30"),
1654                Price::from("0.70010"),
1655                Quantity::from("40"),
1656            ))
1657        );
1658    }
1659
1660    fn create_order_list() -> OrderList {
1661        OrderList::new(
1662            OrderListId::from("OL-001"),
1663            InstrumentId::from("AUD/USD.SIM"),
1664            StrategyId::from("S-001"),
1665            vec![ClientOrderId::from("O-001")],
1666            UnixNanos::from(42_u64),
1667        )
1668    }
1669
1670    #[rstest]
1671    fn test_order_list_queries_preserve_concrete_type() {
1672        let order_list = create_order_list();
1673        let order_list_id = order_list.id;
1674        let cache = Rc::new(RefCell::new(Cache::default()));
1675        cache
1676            .borrow_mut()
1677            .add_order_list(order_list.clone())
1678            .unwrap();
1679        let py_cache = PyCache::from_rc(cache);
1680
1681        assert_eq!(
1682            py_cache.py_order_list(order_list_id),
1683            Some(order_list.clone()),
1684        );
1685        assert_eq!(
1686            py_cache.py_order_lists(None, None, None, None),
1687            vec![order_list],
1688        );
1689    }
1690
1691    #[rstest]
1692    fn test_add_instrument_close_replaces_existing() {
1693        let first = stub_instrument_close();
1694        let replacement = InstrumentClose::new(
1695            first.instrument_id,
1696            Price::from("0.00000"),
1697            InstrumentCloseType::EndOfSession,
1698            UnixNanos::from(3_u64),
1699            UnixNanos::from(4_u64),
1700        );
1701        let mut py_cache = PyCache::from_rc(Rc::new(RefCell::new(Cache::default())));
1702
1703        py_cache.py_add_instrument_close(first).unwrap();
1704        py_cache.py_add_instrument_close(replacement).unwrap();
1705
1706        assert_eq!(
1707            py_cache.py_instrument_close(first.instrument_id),
1708            Some(replacement)
1709        );
1710    }
1711
1712    #[rstest]
1713    fn test_py_cache_constructor_returns_value_error_for_invalid_config() {
1714        Python::initialize();
1715        let config = CacheConfig {
1716            data_capacity: 0,
1717            ..Default::default()
1718        };
1719
1720        let err = PyCache::py_new(Some(config)).expect_err("invalid capacity must be rejected");
1721
1722        Python::attach(|py| assert!(err.is_instance_of::<PyValueError>(py)));
1723    }
1724
1725    #[rstest]
1726    fn test_native_cache_binding_returns_value_error_for_invalid_config() {
1727        Python::initialize();
1728        let config = CacheConfig {
1729            bar_capacity: 0,
1730            ..Default::default()
1731        };
1732
1733        let err = Cache::py_new(Some(config)).expect_err("invalid capacity must be rejected");
1734
1735        Python::attach(|py| assert!(err.is_instance_of::<PyValueError>(py)));
1736    }
1737}
1738
1739#[cfg(feature = "defi")]
1740#[pymethods]
1741#[pyo3_stub_gen::derive::gen_stub_pymethods]
1742impl PyCache {
1743    #[pyo3(name = "pool")]
1744    fn py_pool(&self, instrument_id: InstrumentId) -> Option<Pool> {
1745        self.0
1746            .try_borrow()
1747            .ok()
1748            .and_then(|cache| cache.pool(&instrument_id).cloned())
1749    }
1750
1751    #[pyo3(name = "pool_profiler")]
1752    fn py_pool_profiler(&self, instrument_id: InstrumentId) -> Option<PoolProfiler> {
1753        self.0
1754            .try_borrow()
1755            .ok()
1756            .and_then(|cache| cache.pool_profiler(&instrument_id).cloned())
1757    }
1758}
1759
1760#[pymethods]
1761#[pyo3_stub_gen::derive::gen_stub_pymethods]
1762impl CacheConfig {
1763    /// Configuration for `Cache` instances.
1764    #[new]
1765    #[expect(clippy::too_many_arguments)]
1766    #[pyo3(signature = (
1767        encoding=None,
1768        timestamps_as_iso8601=None,
1769        buffer_interval_ms=None,
1770        bulk_read_batch_size=None,
1771        use_trader_prefix=None,
1772        use_instance_id=None,
1773        flush_on_start=None,
1774        drop_instruments_on_reset=None,
1775        data_capacity=None,
1776        bar_capacity=None,
1777        save_market_data=None,
1778        persist_account_events=None,
1779    ))]
1780    fn py_new(
1781        encoding: Option<SerializationEncoding>,
1782        timestamps_as_iso8601: Option<bool>,
1783        buffer_interval_ms: Option<usize>,
1784        bulk_read_batch_size: Option<usize>,
1785        use_trader_prefix: Option<bool>,
1786        use_instance_id: Option<bool>,
1787        flush_on_start: Option<bool>,
1788        drop_instruments_on_reset: Option<bool>,
1789        data_capacity: Option<usize>,
1790        bar_capacity: Option<usize>,
1791        save_market_data: Option<bool>,
1792        persist_account_events: Option<bool>,
1793    ) -> PyResult<Self> {
1794        let config = Self {
1795            encoding: encoding.unwrap_or_default(),
1796            timestamps_as_iso8601: timestamps_as_iso8601.unwrap_or(false),
1797            buffer_interval_ms,
1798            bulk_read_batch_size,
1799            use_trader_prefix: use_trader_prefix.unwrap_or(true),
1800            use_instance_id: use_instance_id.unwrap_or(false),
1801            flush_on_start: flush_on_start.unwrap_or(false),
1802            drop_instruments_on_reset: drop_instruments_on_reset.unwrap_or(true),
1803            data_capacity: data_capacity.unwrap_or(10_000),
1804            bar_capacity: bar_capacity.unwrap_or(10_000),
1805            persist_account_events: persist_account_events.unwrap_or(true),
1806            save_market_data: save_market_data.unwrap_or(false),
1807        };
1808        config.validate().map_err(config_error_to_pyvalue_err)?;
1809        Ok(config)
1810    }
1811
1812    fn __str__(&self) -> String {
1813        format!("{self:?}")
1814    }
1815
1816    fn __repr__(&self) -> String {
1817        format!("{self:?}")
1818    }
1819
1820    #[getter]
1821    fn encoding(&self) -> SerializationEncoding {
1822        self.encoding
1823    }
1824
1825    #[getter]
1826    fn timestamps_as_iso8601(&self) -> bool {
1827        self.timestamps_as_iso8601
1828    }
1829
1830    #[getter]
1831    fn buffer_interval_ms(&self) -> Option<usize> {
1832        self.buffer_interval_ms
1833    }
1834
1835    #[getter]
1836    fn bulk_read_batch_size(&self) -> Option<usize> {
1837        self.bulk_read_batch_size
1838    }
1839
1840    #[getter]
1841    fn use_trader_prefix(&self) -> bool {
1842        self.use_trader_prefix
1843    }
1844
1845    #[getter]
1846    fn use_instance_id(&self) -> bool {
1847        self.use_instance_id
1848    }
1849
1850    #[getter]
1851    fn flush_on_start(&self) -> bool {
1852        self.flush_on_start
1853    }
1854
1855    #[getter]
1856    fn drop_instruments_on_reset(&self) -> bool {
1857        self.drop_instruments_on_reset
1858    }
1859
1860    #[getter]
1861    fn data_capacity(&self) -> usize {
1862        self.data_capacity
1863    }
1864
1865    #[getter]
1866    fn bar_capacity(&self) -> usize {
1867        self.bar_capacity
1868    }
1869
1870    #[getter]
1871    fn persist_account_events(&self) -> bool {
1872        self.persist_account_events
1873    }
1874
1875    #[getter]
1876    fn save_market_data(&self) -> bool {
1877        self.save_market_data
1878    }
1879}
1880
1881#[pymethods]
1882impl Cache {
1883    /// A common in-memory `Cache` for market and execution related data.
1884    #[new]
1885    fn py_new(config: Option<CacheConfig>) -> PyResult<Self> {
1886        Self::try_new(config, None).map_err(config_error_to_pyvalue_err)
1887    }
1888
1889    fn __repr__(&self) -> String {
1890        format!("{self:?}")
1891    }
1892
1893    /// Resets the cache.
1894    ///
1895    /// All stateful fields are reset to their initial value. Instruments,
1896    /// currencies, and synthetics are retained when `drop_instruments_on_reset`
1897    /// is `false` so that repeated backtest runs can reuse the same dataset. External order claims
1898    /// and execution client account, route, and external client registrations are retained so
1899    /// registered strategy and client routing remain configured across resets.
1900    #[pyo3(name = "reset")]
1901    fn py_reset(&mut self) {
1902        self.reset();
1903    }
1904
1905    /// Dispose of the cache which will close any underlying database adapter.
1906    ///
1907    /// If closing the database connection fails, an error is logged.
1908    #[pyo3(name = "dispose")]
1909    fn py_dispose(&mut self) {
1910        self.dispose();
1911    }
1912
1913    /// Purges all closed orders from the cache that are older than `buffer_secs`.
1914    ///
1915    ///
1916    /// Only orders that have been closed for at least this amount of time will be purged.
1917    /// A value of 0 means purge all closed orders regardless of when they were closed.
1918    ///
1919    /// When `purge_from_database` is true, also requests deletion from the backing database.
1920    ///
1921    /// Persistence failures are logged without failing the operation.
1922    ///
1923    /// # Errors
1924    ///
1925    /// Returns an error if the backing reports a DeFi currency integrity error.
1926    #[pyo3(name = "purge_closed_orders", signature = (ts_now, buffer_secs=0, purge_from_database=false))]
1927    fn py_purge_closed_orders(
1928        &mut self,
1929        ts_now: u64,
1930        buffer_secs: u64,
1931        purge_from_database: bool,
1932    ) -> PyResult<()> {
1933        self.purge_closed_orders(ts_now.into(), buffer_secs, purge_from_database)
1934            .map_err(to_pyvalue_err)
1935    }
1936
1937    /// Purges all closed positions from the cache that are older than `buffer_secs`.
1938    ///
1939    /// When `purge_from_database` is true, also requests deletion from the backing database.
1940    ///
1941    /// Persistence failures are logged without failing the operation.
1942    ///
1943    /// # Errors
1944    ///
1945    /// Returns an error if the backing reports a DeFi currency integrity error.
1946    #[pyo3(name = "purge_closed_positions", signature = (ts_now, buffer_secs=0, purge_from_database=false))]
1947    fn py_purge_closed_positions(
1948        &mut self,
1949        ts_now: u64,
1950        buffer_secs: u64,
1951        purge_from_database: bool,
1952    ) -> PyResult<()> {
1953        self.purge_closed_positions(ts_now.into(), buffer_secs, purge_from_database)
1954            .map_err(to_pyvalue_err)
1955    }
1956
1957    /// Deletes persisted actor state. Does nothing without a database.
1958    ///
1959    /// Persistence failures are logged without failing the operation.
1960    ///
1961    /// # Errors
1962    ///
1963    /// Returns an error if the backing reports a DeFi currency integrity error.
1964    #[pyo3(name = "delete_actor")]
1965    fn py_delete_actor(&self, actor_id: ActorId) -> PyResult<()> {
1966        self.delete_actor(&actor_id).map_err(to_pyvalue_err)
1967    }
1968
1969    /// Deletes persisted strategy state. Does nothing without a database.
1970    ///
1971    /// Persistence failures are logged without failing the operation.
1972    ///
1973    /// # Errors
1974    ///
1975    /// Returns an error if the backing reports a DeFi currency integrity error.
1976    #[pyo3(name = "delete_strategy")]
1977    fn py_delete_strategy(&self, strategy_id: StrategyId) -> PyResult<()> {
1978        self.delete_strategy(&strategy_id).map_err(to_pyvalue_err)
1979    }
1980
1981    /// Persists the heartbeat timestamp. Does nothing without a database.
1982    ///
1983    /// Persistence failures are logged without failing the operation.
1984    ///
1985    /// # Errors
1986    ///
1987    /// Returns an error if the backing reports a DeFi currency integrity error.
1988    #[pyo3(name = "heartbeat")]
1989    fn py_heartbeat(&self, timestamp: u64) -> PyResult<()> {
1990        self.heartbeat(timestamp.into()).map_err(to_pyvalue_err)
1991    }
1992
1993    /// Loads an instrument from memory, falling back to the database and caching the result.
1994    ///
1995    /// # Errors
1996    ///
1997    /// Returns an error if loading the instrument fails.
1998    #[pyo3(name = "load_instrument")]
1999    fn py_load_instrument(
2000        &mut self,
2001        py: Python<'_>,
2002        instrument_id: InstrumentId,
2003    ) -> PyResult<Option<Py<PyAny>>> {
2004        let instrument = self
2005            .load_instrument(&instrument_id)
2006            .map_err(to_pyvalue_err)?;
2007        instrument
2008            .map(|instrument| instrument_any_to_pyobject(py, instrument))
2009            .transpose()
2010    }
2011
2012    /// Loads a synthetic from memory, falling back to the database and caching the result.
2013    ///
2014    /// # Errors
2015    ///
2016    /// Returns an error if the ID is not synthetic or loading the instrument fails.
2017    #[pyo3(name = "load_synthetic")]
2018    fn py_load_synthetic(
2019        &mut self,
2020        instrument_id: InstrumentId,
2021    ) -> PyResult<Option<SyntheticInstrument>> {
2022        self.load_synthetic(&instrument_id).map_err(to_pyvalue_err)
2023    }
2024
2025    /// Purges the order with the `client_order_id` from the cache (if found).
2026    ///
2027    /// For safety, an order is prevented from being purged if it's open.
2028    ///
2029    /// When `purge_from_database` is true, also requests deletion from the backing database.
2030    ///
2031    /// Persistence failures are logged without failing the operation.
2032    ///
2033    /// # Errors
2034    ///
2035    /// Returns an error if the backing reports a DeFi currency integrity error.
2036    #[pyo3(name = "purge_order", signature = (client_order_id, purge_from_database=false))]
2037    fn py_purge_order(
2038        &mut self,
2039        client_order_id: ClientOrderId,
2040        purge_from_database: bool,
2041    ) -> PyResult<()> {
2042        self.purge_order(client_order_id, purge_from_database)
2043            .map_err(to_pyvalue_err)
2044    }
2045
2046    /// Purges the position with the `position_id` from the cache (if found).
2047    ///
2048    /// For safety, a position is prevented from being purged if it's open.
2049    ///
2050    /// When `purge_from_database` is true, also requests deletion from the backing database.
2051    ///
2052    /// Persistence failures are logged without failing the operation.
2053    ///
2054    /// # Errors
2055    ///
2056    /// Returns an error if the backing reports a DeFi currency integrity error.
2057    #[pyo3(name = "purge_position", signature = (position_id, purge_from_database=false))]
2058    fn py_purge_position(
2059        &mut self,
2060        position_id: PositionId,
2061        purge_from_database: bool,
2062    ) -> PyResult<()> {
2063        self.purge_position(position_id, purge_from_database)
2064            .map_err(to_pyvalue_err)
2065    }
2066
2067    /// Purges the instrument with the `instrument_id` from the cache.
2068    ///
2069    /// This refuses to purge when associated orders or positions remain in
2070    /// non-terminal state.
2071    #[pyo3(name = "purge_instrument")]
2072    fn py_purge_instrument(&mut self, instrument_id: InstrumentId) {
2073        self.purge_instrument(instrument_id);
2074    }
2075
2076    /// Purges all account state events which are outside the lookback window.
2077    ///
2078    /// Only events which are outside the lookback window will be purged.
2079    /// A value of 0 purges all but the latest account state event.
2080    ///
2081    /// When `purge_from_database` is true, also requests deletion from the backing database.
2082    /// Redis and PostgreSQL log the request and retain the full account history for replay.
2083    ///
2084    /// Persistence failures are logged without failing the operation.
2085    ///
2086    /// # Errors
2087    ///
2088    /// Returns an error if the backing reports a DeFi currency integrity error.
2089    #[pyo3(name = "purge_account_events", signature = (ts_now, lookback_secs=0, purge_from_database=false))]
2090    fn py_purge_account_events(
2091        &mut self,
2092        ts_now: u64,
2093        lookback_secs: u64,
2094        purge_from_database: bool,
2095    ) -> PyResult<()> {
2096        self.purge_account_events(ts_now.into(), lookback_secs, purge_from_database)
2097            .map_err(to_pyvalue_err)
2098    }
2099
2100    /// Adds the `currency` to the cache.
2101    ///
2102    /// Persistence failures are logged without failing the operation.
2103    ///
2104    /// # Errors
2105    ///
2106    /// Returns an error if the currency definition conflicts with existing state or the backing
2107    /// reports a DeFi currency integrity error.
2108    #[pyo3(name = "add_currency")]
2109    fn py_add_currency(&mut self, currency: Currency) -> PyResult<()> {
2110        self.add_currency(currency).map_err(to_pyvalue_err)
2111    }
2112
2113    /// Adds the `instrument` to the cache.
2114    ///
2115    /// Persistence failures are logged without failing the operation.
2116    ///
2117    /// # Errors
2118    ///
2119    /// Returns an error if the instrument or its currency identities conflict with existing state,
2120    /// or the backing reports a DeFi currency integrity error.
2121    #[pyo3(name = "add_instrument")]
2122    fn py_add_instrument(&mut self, py: Python, instrument: Py<PyAny>) -> PyResult<()> {
2123        let instrument_any = pyobject_to_instrument_any(py, instrument)?;
2124        self.add_instrument(instrument_any).map_err(to_pyvalue_err)
2125    }
2126
2127    /// Returns a reference to the instrument for the `instrument_id` (if found).
2128    #[pyo3(name = "instrument")]
2129    fn py_instrument(
2130        &self,
2131        py: Python,
2132        instrument_id: InstrumentId,
2133    ) -> PyResult<Option<Py<PyAny>>> {
2134        match self.instrument(&instrument_id) {
2135            Some(instrument) => Ok(Some(instrument_any_to_pyobject(py, instrument.clone())?)),
2136            None => Ok(None),
2137        }
2138    }
2139
2140    /// Returns references to all instrument IDs for the `venue`.
2141    #[pyo3(name = "instrument_ids")]
2142    fn py_instrument_ids(&self, venue: Option<Venue>) -> Vec<InstrumentId> {
2143        self.instrument_ids(venue.as_ref())
2144            .into_iter()
2145            .copied()
2146            .collect()
2147    }
2148
2149    /// Returns references to all instruments for the `venue`.
2150    #[pyo3(name = "instruments")]
2151    fn py_instruments(&self, py: Python, venue: Option<Venue>) -> PyResult<Vec<Py<PyAny>>> {
2152        let mut py_instruments = Vec::new();
2153
2154        if let Some(venue) = venue {
2155            let instruments = self.instruments(&venue, None);
2156            for instrument in instruments {
2157                py_instruments.push(instrument_any_to_pyobject(py, (*instrument).clone())?);
2158            }
2159        } else {
2160            let instrument_ids = self.instrument_ids(None);
2161            for instrument_id in instrument_ids {
2162                if let Some(instrument) = self.instrument(instrument_id) {
2163                    py_instruments.push(instrument_any_to_pyobject(py, instrument.clone())?);
2164                }
2165            }
2166        }
2167
2168        Ok(py_instruments)
2169    }
2170
2171    /// Adds the `order` to the cache indexed with any given identifiers.
2172    ///
2173    /// Persistence failures are logged without failing the operation.
2174    ///
2175    /// # Parameters
2176    ///
2177    /// `replace_existing`: Replaces an existing order with the same client order ID. Emulated
2178    /// orders use this when release transforms them into another order type.
2179    ///
2180    /// # Errors
2181    ///
2182    /// Returns an error if the client order ID exists and `replace_existing` is false, a
2183    /// replacement claims another order's venue order ID, or the backing reports a DeFi currency
2184    /// integrity error.
2185    #[pyo3(name = "add_order")]
2186    fn py_add_order(
2187        &mut self,
2188        py: Python,
2189        order: Py<PyAny>,
2190        position_id: Option<PositionId>,
2191        client_id: Option<ClientId>,
2192        replace_existing: Option<bool>,
2193    ) -> PyResult<()> {
2194        let order_any = pyobject_to_order_any(py, order)?;
2195        self.add_order(
2196            order_any,
2197            position_id,
2198            client_id,
2199            replace_existing.unwrap_or(false),
2200        )
2201        .map_err(to_pyvalue_err)
2202    }
2203
2204    /// Gets a borrow of the order with the `client_order_id` (if found).
2205    ///
2206    /// Prefer `Self.order_ref` in new native code.
2207    #[pyo3(name = "order")]
2208    fn py_order(&self, py: Python, client_order_id: ClientOrderId) -> PyResult<Option<Py<PyAny>>> {
2209        match self.order(&client_order_id) {
2210            Some(order) => Ok(Some(order_any_to_pyobject(py, order.clone())?)),
2211            None => Ok(None),
2212        }
2213    }
2214
2215    /// Returns whether an order with the `client_order_id` exists.
2216    #[pyo3(name = "order_exists")]
2217    fn py_order_exists(&self, client_order_id: ClientOrderId) -> bool {
2218        self.order_exists(&client_order_id)
2219    }
2220
2221    /// Returns whether an order with the `client_order_id` is open.
2222    #[pyo3(name = "is_order_open")]
2223    fn py_is_order_open(&self, client_order_id: ClientOrderId) -> bool {
2224        self.is_order_open(&client_order_id)
2225    }
2226
2227    /// Returns whether an order with the `client_order_id` is closed.
2228    #[pyo3(name = "is_order_closed")]
2229    fn py_is_order_closed(&self, client_order_id: ClientOrderId) -> bool {
2230        self.is_order_closed(&client_order_id)
2231    }
2232
2233    /// Returns whether an order with the `client_order_id` is locally active.
2234    ///
2235    /// Locally active orders are in the `INITIALIZED`, `EMULATED`, or `RELEASED` state
2236    /// (a superset of emulated orders).
2237    #[pyo3(name = "is_order_active_local")]
2238    fn py_is_order_active_local(&self, client_order_id: ClientOrderId) -> bool {
2239        self.is_order_active_local(&client_order_id)
2240    }
2241
2242    /// Returns borrows of all locally active orders matching the optional filter parameters.
2243    ///
2244    /// Prefer `Self.orders_active_local_refs` in new native code.
2245    #[pyo3(name = "orders_active_local")]
2246    fn py_orders_active_local(
2247        &self,
2248        py: Python,
2249        venue: Option<Venue>,
2250        instrument_id: Option<InstrumentId>,
2251        strategy_id: Option<StrategyId>,
2252        account_id: Option<AccountId>,
2253        side: Option<OrderSide>,
2254    ) -> PyResult<Vec<Py<PyAny>>> {
2255        self.orders_active_local(
2256            venue.as_ref(),
2257            instrument_id.as_ref(),
2258            strategy_id.as_ref(),
2259            account_id.as_ref(),
2260            side,
2261        )
2262        .into_iter()
2263        .map(|order| order_any_to_pyobject(py, order.clone()))
2264        .collect()
2265    }
2266
2267    /// Returns the count of all locally active orders.
2268    ///
2269    /// Locally active orders are in the `INITIALIZED`, `EMULATED`, or `RELEASED` state
2270    /// (a superset of emulated orders).
2271    #[pyo3(name = "orders_active_local_count")]
2272    fn py_orders_active_local_count(
2273        &self,
2274        venue: Option<Venue>,
2275        instrument_id: Option<InstrumentId>,
2276        strategy_id: Option<StrategyId>,
2277        account_id: Option<AccountId>,
2278        side: Option<OrderSide>,
2279    ) -> usize {
2280        self.orders_active_local_count(
2281            venue.as_ref(),
2282            instrument_id.as_ref(),
2283            strategy_id.as_ref(),
2284            account_id.as_ref(),
2285            side,
2286        )
2287    }
2288
2289    /// Returns the count of all open orders.
2290    #[pyo3(name = "orders_open_count")]
2291    fn py_orders_open_count(
2292        &self,
2293        venue: Option<Venue>,
2294        instrument_id: Option<InstrumentId>,
2295        strategy_id: Option<StrategyId>,
2296        account_id: Option<AccountId>,
2297        side: Option<OrderSide>,
2298    ) -> usize {
2299        self.orders_open_count(
2300            venue.as_ref(),
2301            instrument_id.as_ref(),
2302            strategy_id.as_ref(),
2303            account_id.as_ref(),
2304            side,
2305        )
2306    }
2307
2308    /// Returns the count of all closed orders.
2309    #[pyo3(name = "orders_closed_count")]
2310    fn py_orders_closed_count(
2311        &self,
2312        venue: Option<Venue>,
2313        instrument_id: Option<InstrumentId>,
2314        strategy_id: Option<StrategyId>,
2315        account_id: Option<AccountId>,
2316        side: Option<OrderSide>,
2317    ) -> usize {
2318        self.orders_closed_count(
2319            venue.as_ref(),
2320            instrument_id.as_ref(),
2321            strategy_id.as_ref(),
2322            account_id.as_ref(),
2323            side,
2324        )
2325    }
2326
2327    /// Returns the count of all orders.
2328    #[pyo3(name = "orders_total_count")]
2329    fn py_orders_total_count(
2330        &self,
2331        venue: Option<Venue>,
2332        instrument_id: Option<InstrumentId>,
2333        strategy_id: Option<StrategyId>,
2334        account_id: Option<AccountId>,
2335        side: Option<OrderSide>,
2336    ) -> usize {
2337        self.orders_total_count(
2338            venue.as_ref(),
2339            instrument_id.as_ref(),
2340            strategy_id.as_ref(),
2341            account_id.as_ref(),
2342            side,
2343        )
2344    }
2345
2346    /// Adds the `position` to the cache.
2347    ///
2348    /// For `OmsType.Unspecified`, IDs matching `{instrument_id}-{strategy_id}` resolve to
2349    /// `OmsType.Netting`. Other IDs retain the supplied OMS type.
2350    ///
2351    /// Persistence failures are logged without failing the operation.
2352    ///
2353    /// # Errors
2354    ///
2355    /// Returns an error if validating or serializing the position metadata fails, or the backing
2356    /// reports a DeFi currency integrity error.
2357    #[pyo3(name = "add_position")]
2358    #[expect(clippy::needless_pass_by_value)]
2359    fn py_add_position(
2360        &mut self,
2361        py: Python,
2362        position: Py<PyAny>,
2363        oms_type: OmsType,
2364    ) -> PyResult<()> {
2365        let position_obj = position.extract::<Position>(py)?;
2366        self.add_position(&position_obj, oms_type)
2367            .map_err(to_pyvalue_err)
2368    }
2369
2370    /// Creates a snapshot of the `position` by cloning it, assigning a new ID, and storing it
2371    /// in the position snapshots.
2372    ///
2373    /// The copy excludes `replay_events` and `fill_voids`, which no snapshot consumer reads,
2374    /// so snapshot size stays independent of the fills applied to the position ID. The copy
2375    /// encodes only when a consumer asks for the bytes, so this call stays off the encode path
2376    /// unless a backing database has to persist the frame.
2377    ///
2378    /// Persistence failures are logged without failing the operation.
2379    ///
2380    /// # Errors
2381    ///
2382    /// Returns an error if serializing the snapshot or validating its cache entry fails, or the
2383    /// backing reports a DeFi currency integrity error.
2384    #[pyo3(name = "snapshot_position")]
2385    #[expect(clippy::needless_pass_by_value)]
2386    fn py_snapshot_position(&mut self, py: Python, position: Py<PyAny>) -> PyResult<()> {
2387        let position_obj = position.extract::<Position>(py)?;
2388        self.snapshot_position(&position_obj)
2389            .map_err(to_pyvalue_err)
2390    }
2391
2392    /// Returns a borrow of the position with the `position_id` (if found).
2393    ///
2394    /// Prefer `Self.position_ref` in new native code.
2395    #[pyo3(name = "position")]
2396    fn py_position(&self, py: Python, position_id: PositionId) -> PyResult<Option<Py<PyAny>>> {
2397        match self.position(&position_id) {
2398            Some(position) => Ok(Some(position.clone().into_pyobject(py)?.into())),
2399            None => Ok(None),
2400        }
2401    }
2402
2403    /// Returns whether a position with the `position_id` exists.
2404    #[pyo3(name = "position_exists")]
2405    fn py_position_exists(&self, position_id: PositionId) -> bool {
2406        self.position_exists(&position_id)
2407    }
2408
2409    /// Returns whether a position with the `position_id` is open.
2410    #[pyo3(name = "is_position_open")]
2411    fn py_is_position_open(&self, position_id: PositionId) -> bool {
2412        self.is_position_open(&position_id)
2413    }
2414
2415    /// Returns whether a position with the `position_id` is closed.
2416    #[pyo3(name = "is_position_closed")]
2417    fn py_is_position_closed(&self, position_id: PositionId) -> bool {
2418        self.is_position_closed(&position_id)
2419    }
2420
2421    /// Returns the count of all open positions.
2422    #[pyo3(name = "positions_open_count")]
2423    fn py_positions_open_count(
2424        &self,
2425        venue: Option<Venue>,
2426        instrument_id: Option<InstrumentId>,
2427        strategy_id: Option<StrategyId>,
2428        account_id: Option<AccountId>,
2429        side: Option<PositionSide>,
2430    ) -> usize {
2431        self.positions_open_count(
2432            venue.as_ref(),
2433            instrument_id.as_ref(),
2434            strategy_id.as_ref(),
2435            account_id.as_ref(),
2436            side,
2437        )
2438    }
2439
2440    /// Returns the count of all closed positions.
2441    #[pyo3(name = "positions_closed_count")]
2442    fn py_positions_closed_count(
2443        &self,
2444        venue: Option<Venue>,
2445        instrument_id: Option<InstrumentId>,
2446        strategy_id: Option<StrategyId>,
2447        account_id: Option<AccountId>,
2448        side: Option<PositionSide>,
2449    ) -> usize {
2450        self.positions_closed_count(
2451            venue.as_ref(),
2452            instrument_id.as_ref(),
2453            strategy_id.as_ref(),
2454            account_id.as_ref(),
2455            side,
2456        )
2457    }
2458
2459    /// Returns the count of all positions.
2460    #[pyo3(name = "positions_total_count")]
2461    fn py_positions_total_count(
2462        &self,
2463        venue: Option<Venue>,
2464        instrument_id: Option<InstrumentId>,
2465        strategy_id: Option<StrategyId>,
2466        account_id: Option<AccountId>,
2467        side: Option<PositionSide>,
2468    ) -> usize {
2469        self.positions_total_count(
2470            venue.as_ref(),
2471            instrument_id.as_ref(),
2472            strategy_id.as_ref(),
2473            account_id.as_ref(),
2474            side,
2475        )
2476    }
2477
2478    /// Adds the `quote` tick to the cache.
2479    ///
2480    /// Persistence failures are logged without failing the operation.
2481    ///
2482    /// # Errors
2483    ///
2484    /// Returns an error if the backing reports a DeFi currency integrity error.
2485    #[pyo3(name = "add_quote")]
2486    fn py_add_quote(&mut self, quote: QuoteTick) -> PyResult<()> {
2487        self.add_quote(quote).map_err(to_pyvalue_err)
2488    }
2489
2490    /// Adds the `trade` tick to the cache.
2491    ///
2492    /// Persistence failures are logged without failing the operation.
2493    ///
2494    /// # Errors
2495    ///
2496    /// Returns an error if the backing reports a DeFi currency integrity error.
2497    #[pyo3(name = "add_trade")]
2498    fn py_add_trade(&mut self, trade: TradeTick) -> PyResult<()> {
2499        self.add_trade(trade).map_err(to_pyvalue_err)
2500    }
2501
2502    /// Adds the `bar` to the cache, keeping the per-`bar_type` series newest-first.
2503    ///
2504    /// A newer bar is pushed, an older `ts_event` is skipped, and an equal
2505    /// `ts_event` replaces the front bar for time bars.
2506    ///
2507    /// Persistence failures are logged without failing the operation.
2508    ///
2509    /// # Errors
2510    ///
2511    /// Returns an error if the backing reports a DeFi currency integrity error.
2512    #[pyo3(name = "add_bar")]
2513    fn py_add_bar(&mut self, bar: Bar) -> PyResult<()> {
2514        self.add_bar(bar).map_err(to_pyvalue_err)
2515    }
2516
2517    /// Returns the most recently added quote for the `instrument_id`, or `None` if absent.
2518    #[pyo3(name = "quote")]
2519    fn py_quote(&self, instrument_id: InstrumentId) -> Option<QuoteTick> {
2520        self.quote(&instrument_id).copied()
2521    }
2522
2523    /// Returns the most recently added trade for the `instrument_id`, or `None` if absent.
2524    #[pyo3(name = "trade")]
2525    fn py_trade(&self, instrument_id: InstrumentId) -> Option<TradeTick> {
2526        self.trade(&instrument_id).copied()
2527    }
2528
2529    /// Returns the most recent bar by `ts_event` for the `bar_type`, or `None` if absent.
2530    #[pyo3(name = "bar")]
2531    fn py_bar(&self, bar_type: BarType) -> Option<Bar> {
2532        self.bar(&bar_type).copied()
2533    }
2534
2535    /// Returns cached quotes for the `instrument_id` in reverse insertion order.
2536    ///
2537    /// Index 0 is the most recently added quote. Entries are not sorted by timestamp.
2538    /// Returns `None` when no quotes are cached for the instrument.
2539    #[pyo3(name = "quotes")]
2540    fn py_quotes(&self, instrument_id: InstrumentId) -> Option<Vec<QuoteTick>> {
2541        self.quotes(&instrument_id)
2542    }
2543
2544    /// Returns cached trades for the `instrument_id` in reverse insertion order.
2545    ///
2546    /// Index 0 is the most recently added trade. Entries are not sorted by timestamp.
2547    /// Returns `None` when no trades are cached for the instrument.
2548    #[pyo3(name = "trades")]
2549    fn py_trades(&self, instrument_id: InstrumentId) -> Option<Vec<TradeTick>> {
2550        self.trades(&instrument_id)
2551    }
2552
2553    /// Returns cached bars for the `bar_type` in reverse chronological order by `ts_event`.
2554    ///
2555    /// Index 0 is the most recent bar. Returns `None` when no bars are cached for the bar type.
2556    #[pyo3(name = "bars")]
2557    fn py_bars(&self, bar_type: BarType) -> Option<Vec<Bar>> {
2558        self.bars(&bar_type)
2559    }
2560
2561    /// Returns whether the cache contains quotes for the `instrument_id`.
2562    #[pyo3(name = "has_quote_ticks")]
2563    fn py_has_quote_ticks(&self, instrument_id: InstrumentId) -> bool {
2564        self.has_quote_ticks(&instrument_id)
2565    }
2566
2567    /// Returns whether the cache contains trades for the `instrument_id`.
2568    #[pyo3(name = "has_trade_ticks")]
2569    fn py_has_trade_ticks(&self, instrument_id: InstrumentId) -> bool {
2570        self.has_trade_ticks(&instrument_id)
2571    }
2572
2573    /// Returns whether the cache contains mark price updates for the `instrument_id`.
2574    #[pyo3(name = "has_mark_prices")]
2575    fn py_has_mark_prices(&self, instrument_id: InstrumentId) -> bool {
2576        self.has_mark_prices(&instrument_id)
2577    }
2578
2579    /// Returns whether the cache contains index price updates for the `instrument_id`.
2580    #[pyo3(name = "has_index_prices")]
2581    fn py_has_index_prices(&self, instrument_id: InstrumentId) -> bool {
2582        self.has_index_prices(&instrument_id)
2583    }
2584
2585    /// Returns whether the cache contains funding rate updates for the `instrument_id`.
2586    #[pyo3(name = "has_funding_rates")]
2587    fn py_has_funding_rates(&self, instrument_id: InstrumentId) -> bool {
2588        self.has_funding_rates(&instrument_id)
2589    }
2590
2591    /// Returns whether the cache contains instrument status updates for the `instrument_id`.
2592    #[pyo3(name = "has_instrument_statuses")]
2593    fn py_has_instrument_statuses(&self, instrument_id: InstrumentId) -> bool {
2594        self.has_instrument_statuses(&instrument_id)
2595    }
2596
2597    /// Returns whether the cache contains a close for the `instrument_id`.
2598    #[pyo3(name = "has_instrument_close")]
2599    fn py_has_instrument_close(&self, instrument_id: InstrumentId) -> bool {
2600        self.has_instrument_close(&instrument_id)
2601    }
2602
2603    /// Returns whether the cache contains bars for the `bar_type`.
2604    #[pyo3(name = "has_bars")]
2605    fn py_has_bars(&self, bar_type: BarType) -> bool {
2606        self.has_bars(&bar_type)
2607    }
2608
2609    /// Gets the quote tick count for the `instrument_id`.
2610    #[pyo3(name = "quote_count")]
2611    fn py_quote_count(&self, instrument_id: InstrumentId) -> usize {
2612        self.quote_count(&instrument_id)
2613    }
2614
2615    /// Gets the trade tick count for the `instrument_id`.
2616    #[pyo3(name = "trade_count")]
2617    fn py_trade_count(&self, instrument_id: InstrumentId) -> usize {
2618        self.trade_count(&instrument_id)
2619    }
2620
2621    /// Gets the mark price update count for the `instrument_id`.
2622    #[pyo3(name = "mark_price_count")]
2623    fn py_mark_price_count(&self, instrument_id: InstrumentId) -> usize {
2624        self.mark_price_count(&instrument_id)
2625    }
2626
2627    /// Gets the index price update count for the `instrument_id`.
2628    #[pyo3(name = "index_price_count")]
2629    fn py_index_price_count(&self, instrument_id: InstrumentId) -> usize {
2630        self.index_price_count(&instrument_id)
2631    }
2632
2633    /// Gets the funding rate update count for the `instrument_id`.
2634    #[pyo3(name = "funding_rate_count")]
2635    fn py_funding_rate_count(&self, instrument_id: InstrumentId) -> usize {
2636        self.funding_rate_count(&instrument_id)
2637    }
2638
2639    /// Gets the instrument status update count for the `instrument_id`.
2640    #[pyo3(name = "instrument_status_count")]
2641    fn py_instrument_status_count(&self, instrument_id: InstrumentId) -> usize {
2642        self.instrument_status_count(&instrument_id)
2643    }
2644
2645    /// Gets the bar count for the `instrument_id`.
2646    #[pyo3(name = "bar_count")]
2647    fn py_bar_count(&self, bar_type: BarType) -> usize {
2648        self.bar_count(&bar_type)
2649    }
2650
2651    /// Returns the most recently added mark price update for the `instrument_id`, or `None` if absent.
2652    #[pyo3(name = "mark_price")]
2653    fn py_mark_price(&self, instrument_id: InstrumentId) -> Option<MarkPriceUpdate> {
2654        self.mark_price(&instrument_id).copied()
2655    }
2656
2657    /// Returns cached mark price updates for the `instrument_id` in reverse insertion order.
2658    ///
2659    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
2660    /// Returns `None` when no mark price updates are cached for the instrument.
2661    #[pyo3(name = "mark_prices")]
2662    fn py_mark_prices(&self, instrument_id: InstrumentId) -> Option<Vec<MarkPriceUpdate>> {
2663        self.mark_prices(&instrument_id)
2664    }
2665
2666    /// Returns the most recently added index price update for the `instrument_id`, or `None` if absent.
2667    #[pyo3(name = "index_price")]
2668    fn py_index_price(&self, instrument_id: InstrumentId) -> Option<IndexPriceUpdate> {
2669        self.index_price(&instrument_id).copied()
2670    }
2671
2672    /// Returns cached index price updates for the `instrument_id` in reverse insertion order.
2673    ///
2674    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
2675    /// Returns `None` when no index price updates are cached for the instrument.
2676    #[pyo3(name = "index_prices")]
2677    fn py_index_prices(&self, instrument_id: InstrumentId) -> Option<Vec<IndexPriceUpdate>> {
2678        self.index_prices(&instrument_id)
2679    }
2680
2681    /// Returns the most recently added funding rate update for the `instrument_id`, or `None` if absent.
2682    #[pyo3(name = "funding_rate")]
2683    fn py_funding_rate(&self, instrument_id: InstrumentId) -> Option<FundingRateUpdate> {
2684        self.funding_rate(&instrument_id).copied()
2685    }
2686
2687    /// Returns cached funding rate updates for the `instrument_id` in reverse insertion order.
2688    ///
2689    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
2690    /// Returns `None` when no funding rate updates are cached for the instrument.
2691    #[pyo3(name = "funding_rates")]
2692    fn py_funding_rates(&self, instrument_id: InstrumentId) -> Option<Vec<FundingRateUpdate>> {
2693        self.funding_rates(&instrument_id)
2694    }
2695
2696    /// Returns the most recently added instrument status for the `instrument_id`, or `None` if absent.
2697    #[pyo3(name = "instrument_status")]
2698    fn py_instrument_status(&self, instrument_id: InstrumentId) -> Option<InstrumentStatus> {
2699        self.instrument_status(&instrument_id).copied()
2700    }
2701
2702    /// Returns cached instrument status updates for the `instrument_id` in reverse insertion order.
2703    ///
2704    /// Index 0 is the most recently added update. Entries are not sorted by timestamp.
2705    /// Returns `None` when no instrument status updates are cached for the instrument.
2706    #[pyo3(name = "instrument_statuses")]
2707    fn py_instrument_statuses(&self, instrument_id: InstrumentId) -> Option<Vec<InstrumentStatus>> {
2708        self.instrument_statuses(&instrument_id)
2709    }
2710
2711    /// Returns the close cached for `instrument_id`, if present.
2712    ///
2713    /// A later insertion replaces the cached close for the instrument; no history is kept.
2714    #[pyo3(name = "instrument_close")]
2715    fn py_instrument_close(&self, instrument_id: InstrumentId) -> Option<InstrumentClose> {
2716        self.instrument_close(&instrument_id).copied()
2717    }
2718
2719    /// Returns the current order book for the `instrument_id`, or `None` if absent.
2720    ///
2721    /// The cache holds the current book state, not a history of book updates.
2722    #[pyo3(name = "order_book")]
2723    fn py_order_book(&self, instrument_id: InstrumentId) -> Option<OrderBook> {
2724        self.order_book(&instrument_id).cloned()
2725    }
2726
2727    /// Returns whether the cache contains an order book for the `instrument_id`.
2728    #[pyo3(name = "has_order_book")]
2729    fn py_has_order_book(&self, instrument_id: InstrumentId) -> bool {
2730        self.has_order_book(&instrument_id)
2731    }
2732
2733    /// Gets the order book update count for the `instrument_id`.
2734    #[pyo3(name = "book_update_count")]
2735    fn py_book_update_count(&self, instrument_id: InstrumentId) -> usize {
2736        self.book_update_count(&instrument_id)
2737    }
2738
2739    /// Returns a reference to the synthetic instrument for the `instrument_id` (if found).
2740    #[pyo3(name = "synthetic")]
2741    fn py_synthetic(&self, instrument_id: InstrumentId) -> Option<SyntheticInstrument> {
2742        self.synthetic(&instrument_id).cloned()
2743    }
2744
2745    /// Returns references to instrument IDs for all synthetic instruments contained in the cache.
2746    #[pyo3(name = "synthetic_ids")]
2747    fn py_synthetic_ids(&self) -> Vec<InstrumentId> {
2748        self.synthetic_ids().into_iter().copied().collect()
2749    }
2750
2751    /// Returns the `ClientOrderId`s of all orders.
2752    #[pyo3(name = "client_order_ids")]
2753    fn py_client_order_ids(
2754        &self,
2755        venue: Option<Venue>,
2756        instrument_id: Option<InstrumentId>,
2757        strategy_id: Option<StrategyId>,
2758        account_id: Option<AccountId>,
2759    ) -> Vec<ClientOrderId> {
2760        self.client_order_ids(
2761            venue.as_ref(),
2762            instrument_id.as_ref(),
2763            strategy_id.as_ref(),
2764            account_id.as_ref(),
2765        )
2766        .into_iter()
2767        .collect()
2768    }
2769
2770    /// Returns the `ClientOrderId`s of all open orders.
2771    #[pyo3(name = "client_order_ids_open")]
2772    fn py_client_order_ids_open(
2773        &self,
2774        venue: Option<Venue>,
2775        instrument_id: Option<InstrumentId>,
2776        strategy_id: Option<StrategyId>,
2777        account_id: Option<AccountId>,
2778    ) -> Vec<ClientOrderId> {
2779        self.client_order_ids_open(
2780            venue.as_ref(),
2781            instrument_id.as_ref(),
2782            strategy_id.as_ref(),
2783            account_id.as_ref(),
2784        )
2785        .into_iter()
2786        .collect()
2787    }
2788
2789    /// Returns the `ClientOrderId`s of all closed orders.
2790    #[pyo3(name = "client_order_ids_closed")]
2791    fn py_client_order_ids_closed(
2792        &self,
2793        venue: Option<Venue>,
2794        instrument_id: Option<InstrumentId>,
2795        strategy_id: Option<StrategyId>,
2796        account_id: Option<AccountId>,
2797    ) -> Vec<ClientOrderId> {
2798        self.client_order_ids_closed(
2799            venue.as_ref(),
2800            instrument_id.as_ref(),
2801            strategy_id.as_ref(),
2802            account_id.as_ref(),
2803        )
2804        .into_iter()
2805        .collect()
2806    }
2807
2808    /// Returns the `ClientOrderId`s of all emulated orders.
2809    #[pyo3(name = "client_order_ids_emulated")]
2810    fn py_client_order_ids_emulated(
2811        &self,
2812        venue: Option<Venue>,
2813        instrument_id: Option<InstrumentId>,
2814        strategy_id: Option<StrategyId>,
2815        account_id: Option<AccountId>,
2816    ) -> Vec<ClientOrderId> {
2817        self.client_order_ids_emulated(
2818            venue.as_ref(),
2819            instrument_id.as_ref(),
2820            strategy_id.as_ref(),
2821            account_id.as_ref(),
2822        )
2823        .into_iter()
2824        .collect()
2825    }
2826
2827    /// Returns the `ClientOrderId`s of all in-flight orders.
2828    #[pyo3(name = "client_order_ids_inflight")]
2829    fn py_client_order_ids_inflight(
2830        &self,
2831        venue: Option<Venue>,
2832        instrument_id: Option<InstrumentId>,
2833        strategy_id: Option<StrategyId>,
2834        account_id: Option<AccountId>,
2835    ) -> Vec<ClientOrderId> {
2836        self.client_order_ids_inflight(
2837            venue.as_ref(),
2838            instrument_id.as_ref(),
2839            strategy_id.as_ref(),
2840            account_id.as_ref(),
2841        )
2842        .into_iter()
2843        .collect()
2844    }
2845
2846    /// Returns `PositionId`s of all positions.
2847    #[pyo3(name = "position_ids")]
2848    fn py_position_ids(
2849        &self,
2850        venue: Option<Venue>,
2851        instrument_id: Option<InstrumentId>,
2852        strategy_id: Option<StrategyId>,
2853        account_id: Option<AccountId>,
2854    ) -> Vec<PositionId> {
2855        self.position_ids(
2856            venue.as_ref(),
2857            instrument_id.as_ref(),
2858            strategy_id.as_ref(),
2859            account_id.as_ref(),
2860        )
2861        .into_iter()
2862        .collect()
2863    }
2864
2865    /// Returns the `PositionId`s of all open positions.
2866    #[pyo3(name = "position_open_ids")]
2867    fn py_position_open_ids(
2868        &self,
2869        venue: Option<Venue>,
2870        instrument_id: Option<InstrumentId>,
2871        strategy_id: Option<StrategyId>,
2872        account_id: Option<AccountId>,
2873    ) -> Vec<PositionId> {
2874        self.position_open_ids(
2875            venue.as_ref(),
2876            instrument_id.as_ref(),
2877            strategy_id.as_ref(),
2878            account_id.as_ref(),
2879        )
2880        .into_iter()
2881        .collect()
2882    }
2883
2884    /// Returns the `PositionId`s of all closed positions.
2885    #[pyo3(name = "position_closed_ids")]
2886    fn py_position_closed_ids(
2887        &self,
2888        venue: Option<Venue>,
2889        instrument_id: Option<InstrumentId>,
2890        strategy_id: Option<StrategyId>,
2891        account_id: Option<AccountId>,
2892    ) -> Vec<PositionId> {
2893        self.position_closed_ids(
2894            venue.as_ref(),
2895            instrument_id.as_ref(),
2896            strategy_id.as_ref(),
2897            account_id.as_ref(),
2898        )
2899        .into_iter()
2900        .collect()
2901    }
2902
2903    /// Returns the `StrategyId`s of all strategies.
2904    #[pyo3(name = "strategy_ids")]
2905    fn py_strategy_ids(&self) -> Vec<StrategyId> {
2906        self.strategy_ids().into_iter().collect()
2907    }
2908
2909    /// Returns the `ExecAlgorithmId`s of all execution algorithms.
2910    #[pyo3(name = "exec_algorithm_ids")]
2911    fn py_exec_algorithm_ids(&self) -> Vec<ExecAlgorithmId> {
2912        self.exec_algorithm_ids().into_iter().collect()
2913    }
2914
2915    /// Gets a reference to the client order ID for the `venue_order_id` (if found).
2916    #[pyo3(name = "client_order_id")]
2917    fn py_client_order_id(&self, venue_order_id: VenueOrderId) -> Option<ClientOrderId> {
2918        self.client_order_id(&venue_order_id).copied()
2919    }
2920
2921    /// Gets a reference to the venue order ID for the `client_order_id` (if found).
2922    #[pyo3(name = "venue_order_id")]
2923    fn py_venue_order_id(&self, client_order_id: ClientOrderId) -> Option<VenueOrderId> {
2924        self.venue_order_id(&client_order_id).copied()
2925    }
2926
2927    /// Gets a reference to the client ID indexed for then `client_order_id` (if found).
2928    #[pyo3(name = "client_id")]
2929    fn py_client_id(&self, client_order_id: ClientOrderId) -> Option<ClientId> {
2930        self.client_id(&client_order_id).copied()
2931    }
2932
2933    /// Returns borrows of all orders matching the optional filter parameters.
2934    ///
2935    /// Prefer `Self.orders_refs` in new native code.
2936    #[pyo3(name = "orders")]
2937    fn py_orders(
2938        &self,
2939        py: Python,
2940        venue: Option<Venue>,
2941        instrument_id: Option<InstrumentId>,
2942        strategy_id: Option<StrategyId>,
2943        account_id: Option<AccountId>,
2944        side: Option<OrderSide>,
2945    ) -> PyResult<Vec<Py<PyAny>>> {
2946        self.orders(
2947            venue.as_ref(),
2948            instrument_id.as_ref(),
2949            strategy_id.as_ref(),
2950            account_id.as_ref(),
2951            side,
2952        )
2953        .into_iter()
2954        .map(|o| order_any_to_pyobject(py, o.clone()))
2955        .collect()
2956    }
2957
2958    /// Returns borrows of all open orders matching the optional filter parameters.
2959    ///
2960    /// Prefer `Self.orders_open_refs` in new native code.
2961    #[pyo3(name = "orders_open")]
2962    fn py_orders_open(
2963        &self,
2964        py: Python,
2965        venue: Option<Venue>,
2966        instrument_id: Option<InstrumentId>,
2967        strategy_id: Option<StrategyId>,
2968        account_id: Option<AccountId>,
2969        side: Option<OrderSide>,
2970    ) -> PyResult<Vec<Py<PyAny>>> {
2971        self.orders_open(
2972            venue.as_ref(),
2973            instrument_id.as_ref(),
2974            strategy_id.as_ref(),
2975            account_id.as_ref(),
2976            side,
2977        )
2978        .into_iter()
2979        .map(|o| order_any_to_pyobject(py, o.clone()))
2980        .collect()
2981    }
2982
2983    /// Returns borrows of all closed orders matching the optional filter parameters.
2984    ///
2985    /// Prefer `Self.orders_closed_refs` in new native code.
2986    #[pyo3(name = "orders_closed")]
2987    fn py_orders_closed(
2988        &self,
2989        py: Python,
2990        venue: Option<Venue>,
2991        instrument_id: Option<InstrumentId>,
2992        strategy_id: Option<StrategyId>,
2993        account_id: Option<AccountId>,
2994        side: Option<OrderSide>,
2995    ) -> PyResult<Vec<Py<PyAny>>> {
2996        self.orders_closed(
2997            venue.as_ref(),
2998            instrument_id.as_ref(),
2999            strategy_id.as_ref(),
3000            account_id.as_ref(),
3001            side,
3002        )
3003        .into_iter()
3004        .map(|o| order_any_to_pyobject(py, o.clone()))
3005        .collect()
3006    }
3007
3008    /// Returns borrows of all emulated orders matching the optional filter parameters.
3009    ///
3010    /// Prefer `Self.orders_emulated_refs` in new native code.
3011    #[pyo3(name = "orders_emulated")]
3012    fn py_orders_emulated(
3013        &self,
3014        py: Python,
3015        venue: Option<Venue>,
3016        instrument_id: Option<InstrumentId>,
3017        strategy_id: Option<StrategyId>,
3018        account_id: Option<AccountId>,
3019        side: Option<OrderSide>,
3020    ) -> PyResult<Vec<Py<PyAny>>> {
3021        self.orders_emulated(
3022            venue.as_ref(),
3023            instrument_id.as_ref(),
3024            strategy_id.as_ref(),
3025            account_id.as_ref(),
3026            side,
3027        )
3028        .into_iter()
3029        .map(|o| order_any_to_pyobject(py, o.clone()))
3030        .collect()
3031    }
3032
3033    /// Returns borrows of all in-flight orders matching the optional filter parameters.
3034    ///
3035    /// Prefer `Self.orders_inflight_refs` in new native code.
3036    #[pyo3(name = "orders_inflight")]
3037    fn py_orders_inflight(
3038        &self,
3039        py: Python,
3040        venue: Option<Venue>,
3041        instrument_id: Option<InstrumentId>,
3042        strategy_id: Option<StrategyId>,
3043        account_id: Option<AccountId>,
3044        side: Option<OrderSide>,
3045    ) -> PyResult<Vec<Py<PyAny>>> {
3046        self.orders_inflight(
3047            venue.as_ref(),
3048            instrument_id.as_ref(),
3049            strategy_id.as_ref(),
3050            account_id.as_ref(),
3051            side,
3052        )
3053        .into_iter()
3054        .map(|o| order_any_to_pyobject(py, o.clone()))
3055        .collect()
3056    }
3057
3058    /// Returns borrows of all orders for the `position_id`.
3059    #[pyo3(name = "orders_for_position")]
3060    fn py_orders_for_position(
3061        &self,
3062        py: Python,
3063        position_id: PositionId,
3064    ) -> PyResult<Vec<Py<PyAny>>> {
3065        self.orders_for_position(&position_id)
3066            .into_iter()
3067            .map(|o| order_any_to_pyobject(py, o.clone()))
3068            .collect()
3069    }
3070
3071    /// Returns whether an order with the `client_order_id` is emulated.
3072    #[pyo3(name = "is_order_emulated")]
3073    fn py_is_order_emulated(&self, client_order_id: ClientOrderId) -> bool {
3074        self.is_order_emulated(&client_order_id)
3075    }
3076
3077    /// Returns whether an order with the `client_order_id` is in-flight.
3078    #[pyo3(name = "is_order_inflight")]
3079    fn py_is_order_inflight(&self, client_order_id: ClientOrderId) -> bool {
3080        self.is_order_inflight(&client_order_id)
3081    }
3082
3083    /// Returns whether an order with the `client_order_id` is `PENDING_CANCEL` locally.
3084    #[pyo3(name = "is_order_pending_cancel_local")]
3085    fn py_is_order_pending_cancel_local(&self, client_order_id: ClientOrderId) -> bool {
3086        self.is_order_pending_cancel_local(&client_order_id)
3087    }
3088
3089    /// Returns the count of all emulated orders.
3090    #[pyo3(name = "orders_emulated_count")]
3091    fn py_orders_emulated_count(
3092        &self,
3093        venue: Option<Venue>,
3094        instrument_id: Option<InstrumentId>,
3095        strategy_id: Option<StrategyId>,
3096        account_id: Option<AccountId>,
3097        side: Option<OrderSide>,
3098    ) -> usize {
3099        self.orders_emulated_count(
3100            venue.as_ref(),
3101            instrument_id.as_ref(),
3102            strategy_id.as_ref(),
3103            account_id.as_ref(),
3104            side,
3105        )
3106    }
3107
3108    /// Returns the count of all in-flight orders.
3109    #[pyo3(name = "orders_inflight_count")]
3110    fn py_orders_inflight_count(
3111        &self,
3112        venue: Option<Venue>,
3113        instrument_id: Option<InstrumentId>,
3114        strategy_id: Option<StrategyId>,
3115        account_id: Option<AccountId>,
3116        side: Option<OrderSide>,
3117    ) -> usize {
3118        self.orders_inflight_count(
3119            venue.as_ref(),
3120            instrument_id.as_ref(),
3121            strategy_id.as_ref(),
3122            account_id.as_ref(),
3123            side,
3124        )
3125    }
3126
3127    /// Returns the order list for the `order_list_id`.
3128    #[pyo3(name = "order_list")]
3129    fn py_order_list(&self, order_list_id: OrderListId) -> Option<OrderList> {
3130        self.order_list(&order_list_id).cloned()
3131    }
3132
3133    /// Returns all order lists matching the optional filter parameters.
3134    #[pyo3(name = "order_lists")]
3135    fn py_order_lists(
3136        &self,
3137        venue: Option<Venue>,
3138        instrument_id: Option<InstrumentId>,
3139        strategy_id: Option<StrategyId>,
3140        account_id: Option<AccountId>,
3141    ) -> Vec<OrderList> {
3142        self.order_lists(
3143            venue.as_ref(),
3144            instrument_id.as_ref(),
3145            strategy_id.as_ref(),
3146            account_id.as_ref(),
3147        )
3148        .into_iter()
3149        .cloned()
3150        .collect()
3151    }
3152
3153    /// Returns whether an order list with the `order_list_id` exists.
3154    #[pyo3(name = "order_list_exists")]
3155    fn py_order_list_exists(&self, order_list_id: OrderListId) -> bool {
3156        self.order_list_exists(&order_list_id)
3157    }
3158
3159    /// Returns references to all orders associated with the `exec_algorithm_id` matching the
3160    /// optional filter parameters.
3161    #[pyo3(name = "orders_for_exec_algorithm")]
3162    #[expect(clippy::too_many_arguments)]
3163    fn py_orders_for_exec_algorithm(
3164        &self,
3165        py: Python,
3166        exec_algorithm_id: ExecAlgorithmId,
3167        venue: Option<Venue>,
3168        instrument_id: Option<InstrumentId>,
3169        strategy_id: Option<StrategyId>,
3170        account_id: Option<AccountId>,
3171        side: Option<OrderSide>,
3172    ) -> PyResult<Vec<Py<PyAny>>> {
3173        self.orders_for_exec_algorithm(
3174            &exec_algorithm_id,
3175            venue.as_ref(),
3176            instrument_id.as_ref(),
3177            strategy_id.as_ref(),
3178            account_id.as_ref(),
3179            side,
3180        )
3181        .into_iter()
3182        .map(|o| order_any_to_pyobject(py, o.clone()))
3183        .collect()
3184    }
3185
3186    /// Returns references to all orders with the `exec_spawn_id`.
3187    #[pyo3(name = "orders_for_exec_spawn")]
3188    fn py_orders_for_exec_spawn(
3189        &self,
3190        py: Python,
3191        exec_spawn_id: ClientOrderId,
3192    ) -> PyResult<Vec<Py<PyAny>>> {
3193        self.orders_for_exec_spawn(&exec_spawn_id)
3194            .into_iter()
3195            .map(|o| order_any_to_pyobject(py, o.clone()))
3196            .collect()
3197    }
3198
3199    /// Returns the total order quantity for the `exec_spawn_id`.
3200    #[pyo3(name = "exec_spawn_total_quantity")]
3201    fn py_exec_spawn_total_quantity(
3202        &self,
3203        exec_spawn_id: ClientOrderId,
3204        active_only: bool,
3205    ) -> Option<Quantity> {
3206        self.exec_spawn_total_quantity(&exec_spawn_id, active_only)
3207    }
3208
3209    /// Returns the total filled quantity for all orders with the `exec_spawn_id`.
3210    #[pyo3(name = "exec_spawn_total_filled_qty")]
3211    fn py_exec_spawn_total_filled_qty(
3212        &self,
3213        exec_spawn_id: ClientOrderId,
3214        active_only: bool,
3215    ) -> Option<Quantity> {
3216        self.exec_spawn_total_filled_qty(&exec_spawn_id, active_only)
3217    }
3218
3219    /// Returns the total leaves quantity for all orders with the `exec_spawn_id`.
3220    #[pyo3(name = "exec_spawn_total_leaves_qty")]
3221    fn py_exec_spawn_total_leaves_qty(
3222        &self,
3223        exec_spawn_id: ClientOrderId,
3224        active_only: bool,
3225    ) -> Option<Quantity> {
3226        self.exec_spawn_total_leaves_qty(&exec_spawn_id, active_only)
3227    }
3228
3229    /// Returns a borrow of the position for the `client_order_id` (if found).
3230    ///
3231    /// Prefer `Self.position_for_order_ref` in new native code.
3232    #[pyo3(name = "position_for_order")]
3233    fn py_position_for_order(
3234        &self,
3235        py: Python,
3236        client_order_id: ClientOrderId,
3237    ) -> PyResult<Option<Py<PyAny>>> {
3238        match self.position_for_order(&client_order_id) {
3239            Some(position) => Ok(Some(position.clone().into_pyobject(py)?.into())),
3240            None => Ok(None),
3241        }
3242    }
3243
3244    /// Returns a reference to the position ID for the `client_order_id` (if found).
3245    #[pyo3(name = "position_id")]
3246    fn py_position_id(&self, client_order_id: ClientOrderId) -> Option<PositionId> {
3247        self.position_id(&client_order_id).copied()
3248    }
3249
3250    /// Returns borrows of all positions matching the optional filter parameters.
3251    ///
3252    /// Prefer `Self.positions_refs` in new native code.
3253    #[pyo3(name = "positions")]
3254    fn py_positions(
3255        &self,
3256        py: Python,
3257        venue: Option<Venue>,
3258        instrument_id: Option<InstrumentId>,
3259        strategy_id: Option<StrategyId>,
3260        account_id: Option<AccountId>,
3261        side: Option<PositionSide>,
3262    ) -> PyResult<Vec<Py<PyAny>>> {
3263        self.positions(
3264            venue.as_ref(),
3265            instrument_id.as_ref(),
3266            strategy_id.as_ref(),
3267            account_id.as_ref(),
3268            side,
3269        )
3270        .into_iter()
3271        .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
3272        .collect()
3273    }
3274
3275    /// Returns borrows of all open positions matching the optional filter parameters.
3276    ///
3277    /// Prefer `Self.positions_open_refs` in new native code.
3278    #[pyo3(name = "positions_open")]
3279    fn py_positions_open(
3280        &self,
3281        py: Python,
3282        venue: Option<Venue>,
3283        instrument_id: Option<InstrumentId>,
3284        strategy_id: Option<StrategyId>,
3285        account_id: Option<AccountId>,
3286        side: Option<PositionSide>,
3287    ) -> PyResult<Vec<Py<PyAny>>> {
3288        self.positions_open(
3289            venue.as_ref(),
3290            instrument_id.as_ref(),
3291            strategy_id.as_ref(),
3292            account_id.as_ref(),
3293            side,
3294        )
3295        .into_iter()
3296        .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
3297        .collect()
3298    }
3299
3300    /// Returns borrows of all closed positions matching the optional filter parameters.
3301    ///
3302    /// Prefer `Self.positions_closed_refs` in new native code.
3303    #[pyo3(name = "positions_closed")]
3304    fn py_positions_closed(
3305        &self,
3306        py: Python,
3307        venue: Option<Venue>,
3308        instrument_id: Option<InstrumentId>,
3309        strategy_id: Option<StrategyId>,
3310        account_id: Option<AccountId>,
3311        side: Option<PositionSide>,
3312    ) -> PyResult<Vec<Py<PyAny>>> {
3313        self.positions_closed(
3314            venue.as_ref(),
3315            instrument_id.as_ref(),
3316            strategy_id.as_ref(),
3317            account_id.as_ref(),
3318            side,
3319        )
3320        .into_iter()
3321        .map(|p| Ok(p.clone().into_pyobject(py)?.into()))
3322        .collect()
3323    }
3324
3325    /// Gets a reference to the strategy ID for the `client_order_id` (if found).
3326    #[pyo3(name = "strategy_id_for_order")]
3327    fn py_strategy_id_for_order(&self, client_order_id: ClientOrderId) -> Option<StrategyId> {
3328        self.strategy_id_for_order(&client_order_id).copied()
3329    }
3330
3331    /// Gets a reference to the strategy ID for the `position_id` (if found).
3332    #[pyo3(name = "strategy_id_for_position")]
3333    fn py_strategy_id_for_position(&self, position_id: PositionId) -> Option<StrategyId> {
3334        self.strategy_id_for_position(&position_id).copied()
3335    }
3336
3337    /// Gets the serialized position snapshot frames for the `position_id`.
3338    ///
3339    /// Each element in the returned vector is one JSON-encoded `Position` snapshot,
3340    /// in the order they were taken. Frames that fail to serialize are skipped with a warning.
3341    #[pyo3(name = "position_snapshot_bytes")]
3342    fn py_position_snapshot_bytes(&self, position_id: PositionId) -> Option<Vec<Vec<u8>>> {
3343        self.position_snapshot_bytes(&position_id)
3344    }
3345
3346    /// Returns all position snapshots with the given optional filters.
3347    ///
3348    /// When `position_id` is `Some`, only snapshots for that position are returned.
3349    /// When `account_id` is `Some`, snapshots are filtered to that account.
3350    #[pyo3(name = "position_snapshots", signature = (position_id=None, account_id=None))]
3351    fn py_position_snapshots(
3352        &self,
3353        py: Python,
3354        position_id: Option<PositionId>,
3355        account_id: Option<AccountId>,
3356    ) -> PyResult<Vec<Py<PyAny>>> {
3357        self.position_snapshots(position_id.as_ref(), account_id.as_ref())
3358            .into_iter()
3359            .map(|p| Ok(p.into_pyobject(py)?.into()))
3360            .collect()
3361    }
3362
3363    /// Returns a borrow of the account for the `account_id` (if found).
3364    ///
3365    /// Prefer `Self.account_ref` in new native code.
3366    #[pyo3(name = "account")]
3367    fn py_account(&self, py: Python, account_id: AccountId) -> PyResult<Option<Py<PyAny>>> {
3368        match self.account(&account_id) {
3369            Some(account) => Ok(Some(account_any_to_pyobject(py, account.clone())?)),
3370            None => Ok(None),
3371        }
3372    }
3373
3374    /// Returns a borrow of the account for the `venue` (if found).
3375    ///
3376    /// Returns `None` when more than one account is issued under the `venue`; look those
3377    /// accounts up by account ID instead.
3378    #[pyo3(name = "account_for_venue")]
3379    fn py_account_for_venue(&self, py: Python, venue: Venue) -> PyResult<Option<Py<PyAny>>> {
3380        match self.account_for_venue(&venue) {
3381            Some(account) => Ok(Some(account_any_to_pyobject(py, account.clone())?)),
3382            None => Ok(None),
3383        }
3384    }
3385
3386    /// Returns a reference to the account ID for the `venue` (if found).
3387    ///
3388    /// Returns `None` when more than one account is issued under the `venue`.
3389    #[pyo3(name = "account_id")]
3390    fn py_account_id(&self, venue: Venue) -> Option<AccountId> {
3391        self.account_id(&venue).copied()
3392    }
3393
3394    /// Gets a reference to the general value for the `key` (if found).
3395    ///
3396    /// # Errors
3397    ///
3398    /// Returns an error if the `key` is invalid.
3399    #[pyo3(name = "get")]
3400    fn py_get(&self, key: &str) -> PyResult<Option<Vec<u8>>> {
3401        match self.get(key).map_err(to_pyvalue_err)? {
3402            Some(bytes) => Ok(Some(bytes.to_vec())),
3403            None => Ok(None),
3404        }
3405    }
3406
3407    /// Adds a general `value` to the cache for the given `key`.
3408    #[pyo3(name = "add")]
3409    fn py_add_general(&mut self, key: &str, value: Vec<u8>) -> PyResult<()> {
3410        self.add(key, Bytes::from(value)).map_err(to_pyvalue_err)
3411    }
3412
3413    /// Returns the price for the `instrument_id` and `price_type` (if found).
3414    ///
3415    /// For `Mid`, returns `None` if no quote is cached or either price is a sentinel.
3416    /// For quote precision `p`, the midpoint has precision `p + 1` when exactly representable,
3417    /// otherwise `p`, rounded half-even if necessary. The fallback applies when the precision
3418    /// limit or raw range rules out `p + 1`, and when `p` is the maximum float precision (16),
3419    /// so a midpoint of a float-convertible quote stays float-convertible.
3420    #[pyo3(name = "price")]
3421    fn py_price(&self, instrument_id: InstrumentId, price_type: PriceType) -> Option<Price> {
3422        self.price(&instrument_id, price_type)
3423    }
3424
3425    /// Returns the exchange rate for the given parameters.
3426    #[pyo3(name = "get_xrate")]
3427    fn py_get_xrate(
3428        &self,
3429        venue: Venue,
3430        from_currency: Currency,
3431        to_currency: Currency,
3432        price_type: PriceType,
3433    ) -> Option<f64> {
3434        self.get_xrate(venue, from_currency, to_currency, price_type)
3435            .and_then(|rate| rate.to_f64())
3436    }
3437
3438    /// Returns the mark exchange rate for the given currency pair, or `None` if not set.
3439    #[pyo3(name = "get_mark_xrate")]
3440    fn py_get_mark_xrate(&self, from_currency: Currency, to_currency: Currency) -> Option<f64> {
3441        self.get_mark_xrate(from_currency, to_currency)
3442    }
3443
3444    /// Sets the mark exchange rate for the given currency pair and automatically sets the inverse rate.
3445    #[pyo3(name = "set_mark_xrate")]
3446    fn py_set_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency, xrate: f64) {
3447        self.set_mark_xrate(from_currency, to_currency, xrate);
3448    }
3449
3450    /// Clears the mark exchange rate for the given currency pair direction.
3451    ///
3452    /// Removes only the `(from_currency, to_currency)` entry; the inverse rate written
3453    /// by `Self.set_mark_xrate` is retained until cleared separately or
3454    /// `Self.clear_mark_xrates` is called.
3455    #[pyo3(name = "clear_mark_xrate")]
3456    fn py_clear_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency) {
3457        self.clear_mark_xrate(from_currency, to_currency);
3458    }
3459
3460    /// Clears all mark exchange rates.
3461    #[pyo3(name = "clear_mark_xrates")]
3462    fn py_clear_mark_xrates(&mut self) {
3463        self.clear_mark_xrates();
3464    }
3465
3466    /// Calculates the unrealized PnL for the given position.
3467    #[pyo3(name = "calculate_unrealized_pnl")]
3468    #[expect(clippy::needless_pass_by_value)]
3469    fn py_calculate_unrealized_pnl(
3470        &self,
3471        py: Python,
3472        position: Py<PyAny>,
3473    ) -> PyResult<Option<Money>> {
3474        let position = position.extract::<Position>(py)?;
3475        Ok(self.calculate_unrealized_pnl(&position))
3476    }
3477
3478    /// Gets a reference to the own order book for the `instrument_id`.
3479    #[pyo3(name = "own_order_book")]
3480    fn py_own_order_book(&self, instrument_id: InstrumentId) -> Option<OwnOrderBook> {
3481        self.own_order_book(&instrument_id).cloned()
3482    }
3483
3484    /// Updates the own order book with an order.
3485    ///
3486    /// This method adds, updates, or removes an order from the own order book
3487    /// based on the order's current state.
3488    ///
3489    /// Orders without prices (MARKET, etc.) are skipped as they cannot be
3490    /// represented in own books.
3491    #[pyo3(name = "update_own_order_book")]
3492    fn py_update_own_order_book(&mut self, py: Python, order: Py<PyAny>) -> PyResult<()> {
3493        let order_any = pyobject_to_order_any(py, order)?;
3494        self.update_own_order_book(&order_any);
3495        Ok(())
3496    }
3497
3498    /// Force removal of an order from own order books and clean up all indexes.
3499    ///
3500    /// This method is used when order event application fails and we need to ensure
3501    /// terminal orders are properly cleaned up from own books and all relevant indexes.
3502    /// Replicates the index cleanup that `update_order` performs for closed orders.
3503    #[pyo3(name = "force_remove_from_own_order_book")]
3504    fn py_force_remove_from_own_order_book(&mut self, client_order_id: ClientOrderId) {
3505        self.force_remove_from_own_order_book(&client_order_id);
3506    }
3507
3508    /// Audit all own order books against active order indexes.
3509    ///
3510    /// Ensures orders absent from the open, inflight, and active-local indexes are removed from
3511    /// own order books.
3512    #[pyo3(name = "audit_own_order_books")]
3513    fn py_audit_own_order_books(&mut self) {
3514        self.audit_own_order_books();
3515    }
3516}
3517
3518#[cfg(feature = "defi")]
3519#[pymethods]
3520impl Cache {
3521    /// Adds a `Pool` to the cache.
3522    ///
3523    /// This function does not return errors; the result type matches the other add methods.
3524    #[pyo3(name = "add_pool")]
3525    fn py_add_pool(&mut self, pool: Pool) -> PyResult<()> {
3526        self.add_pool(pool).map_err(to_pyvalue_err)
3527    }
3528
3529    /// Gets a reference to the pool for the `instrument_id`.
3530    #[pyo3(name = "pool")]
3531    fn py_pool(&self, instrument_id: InstrumentId) -> Option<Pool> {
3532        self.pool(&instrument_id).cloned()
3533    }
3534
3535    /// Returns the instrument IDs of all pools in the cache, optionally filtered by `venue`.
3536    #[pyo3(name = "pool_ids")]
3537    fn py_pool_ids(&self, venue: Option<Venue>) -> Vec<InstrumentId> {
3538        self.pool_ids(venue.as_ref())
3539    }
3540
3541    /// Returns references to all pools in the cache, optionally filtered by `venue`.
3542    #[pyo3(name = "pools")]
3543    fn py_pools(&self, venue: Option<Venue>) -> Vec<Pool> {
3544        self.pools(venue.as_ref()).into_iter().cloned().collect()
3545    }
3546
3547    /// Adds a `PoolProfiler` to the cache.
3548    ///
3549    /// This function does not return errors; the result type matches the other add methods.
3550    #[pyo3(name = "add_pool_profiler")]
3551    fn py_add_pool_profiler(&mut self, pool_profiler: PoolProfiler) -> PyResult<()> {
3552        self.add_pool_profiler(pool_profiler)
3553            .map_err(to_pyvalue_err)
3554    }
3555
3556    /// Gets a reference to the pool profiler for the `instrument_id`.
3557    #[pyo3(name = "pool_profiler")]
3558    fn py_pool_profiler(&self, instrument_id: InstrumentId) -> Option<PoolProfiler> {
3559        self.pool_profiler(&instrument_id).cloned()
3560    }
3561
3562    /// Returns the instrument IDs of all pool profilers in the cache, optionally filtered by `venue`.
3563    #[pyo3(name = "pool_profiler_ids")]
3564    fn py_pool_profiler_ids(&self, venue: Option<Venue>) -> Vec<InstrumentId> {
3565        self.pool_profiler_ids(venue.as_ref())
3566    }
3567
3568    /// Returns references to all pool profilers in the cache, optionally filtered by `venue`.
3569    #[pyo3(name = "pool_profilers")]
3570    fn py_pool_profilers(&self, venue: Option<Venue>) -> Vec<PoolProfiler> {
3571        self.pool_profilers(venue.as_ref())
3572            .into_iter()
3573            .cloned()
3574            .collect()
3575    }
3576}