1pub mod config;
39pub mod database;
40pub mod fifo;
41pub mod quote;
42pub mod refs;
43
44mod api;
45mod bounded;
46mod error;
47mod filter;
48mod index;
49mod position;
50mod view;
51
52#[cfg(test)]
53mod tests;
54
55use std::{
56 borrow::Cow,
57 cell::RefCell,
58 cmp::{Ordering, Reverse},
59 fmt::{Debug, Display},
60 rc::Rc,
61 time::{SystemTime, UNIX_EPOCH},
62};
63
64use ahash::{AHashMap, AHashSet};
65pub use api::CacheApi; use bounded::BoundedVecDeque;
67use bytes::Bytes;
68pub use config::CacheConfig; use database::{CacheDatabaseAdapter, CacheMap, register_loaded_currencies};
70pub use error::{
71 ACCOUNT_NOT_FOUND, AccountLookupError, CURRENCY_NOT_FOUND, CurrencyLookupError,
72 INSTRUMENT_NOT_FOUND, InstrumentLookupError, ORDER_BOOK_NOT_FOUND, ORDER_LIST_NOT_FOUND,
73 ORDER_NOT_FOUND, OWN_ORDER_BOOK_NOT_FOUND, OrderBookLookupError, OrderListLookupError,
74 OrderLookupError, OwnOrderBookLookupError, POSITION_NOT_FOUND, PositionLookupError,
75 SYNTHETIC_INSTRUMENT_NOT_FOUND, SyntheticInstrumentLookupError, VenueOrderIdOwnershipError,
76};
77use filter::{FilterSources, intersect_pair_or_many};
78use index::CacheIndex;
79use indexmap::IndexMap;
80use nautilus_core::{
81 DurationNanos, SharedCell, UnixNanos,
82 correctness::{
83 check_key_not_in_map, check_predicate_false, check_slice_not_empty, check_valid_string_utf8,
84 },
85};
86use nautilus_model::{
87 accounts::{Account, AccountAny},
88 data::{
89 Bar, BarType, CustomData, DataType, FundingRateUpdate, GreeksData, IndexPriceUpdate,
90 InstrumentClose, InstrumentStatus, MarkPriceUpdate, QuoteTick, TradeTick, YieldCurve,
91 option_chain::OptionGreeks,
92 },
93 enums::{
94 AggregationSource, ContingencyType, InstrumentClass, OmsType, OrderSide, PositionSide,
95 PriceType,
96 },
97 events::{AccountState, OrderEventAny, OrderFilled, PositionAdjusted},
98 identifiers::{
99 AccountId, ActorId, ClientId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId,
100 PositionId, StrategyId, Venue, VenueOrderId,
101 },
102 instruments::{Instrument, InstrumentAny, SyntheticInstrument},
103 orderbook::{
104 OrderBook,
105 own::{OwnOrderBook, should_handle_own_book_order},
106 },
107 orders::{Order, OrderAny, OrderError, OrderList},
108 position::{Position, PositionReplayEvent},
109 types::{
110 Currency, ERROR_PRICE, Money, Price, Quantity,
111 fixed::{FIXED_PRECISION, MAX_FLOAT_PRECISION, check_fixed_precision},
112 price::PriceRaw,
113 },
114};
115pub use position::CacheSnapshotRef;
116use position::PositionSnapshotFrame;
117pub use refs::{AccountRef, AccountRefMut, OrderRef, OrderRefMut, PositionRef, PositionRefMut};
118use rust_decimal::Decimal;
119use ustr::Ustr;
120pub use view::CacheView; #[cfg(feature = "defi")]
123use crate::defi::cache::IntegrityError;
124use crate::xrate::{get_exchange_rate, get_exchange_rate_with_alternates};
125
126#[cfg_attr(
128 feature = "python",
129 pyo3::pyclass(module = "nautilus_trader.common", unsendable)
130)]
131pub struct Cache {
132 config: CacheConfig,
133 index: CacheIndex,
134 database: Option<Box<dyn CacheDatabaseAdapter>>,
135 general: AHashMap<String, Bytes>,
136 currencies: AHashMap<Ustr, Currency>,
137 instruments: AHashMap<InstrumentId, InstrumentAny>,
138 instrument_closes: AHashMap<InstrumentId, InstrumentClose>,
139 synthetics: AHashMap<InstrumentId, SyntheticInstrument>,
140 books: AHashMap<InstrumentId, OrderBook>,
141 own_books: AHashMap<InstrumentId, OwnOrderBook>,
142 quotes: AHashMap<InstrumentId, BoundedVecDeque<QuoteTick>>,
143 trades: AHashMap<InstrumentId, BoundedVecDeque<TradeTick>>,
144 mark_xrates: AHashMap<(Currency, Currency), f64>,
145 mark_prices: AHashMap<InstrumentId, BoundedVecDeque<MarkPriceUpdate>>,
146 index_prices: AHashMap<InstrumentId, BoundedVecDeque<IndexPriceUpdate>>,
147 funding_rates: AHashMap<InstrumentId, BoundedVecDeque<FundingRateUpdate>>,
148 instrument_statuses: AHashMap<InstrumentId, BoundedVecDeque<InstrumentStatus>>,
149 bars: AHashMap<BarType, BoundedVecDeque<Bar>>,
150 custom_data: AHashMap<DataType, BoundedVecDeque<CustomData>>,
151 greeks: AHashMap<InstrumentId, GreeksData>,
152 option_greeks: AHashMap<InstrumentId, OptionGreeks>,
153 yield_curves: AHashMap<String, YieldCurve>,
154 external_order_claims: AHashMap<InstrumentId, StrategyId>,
155 client_accounts: AHashMap<ClientId, AccountId>,
156 client_routes: AHashMap<Venue, ClientId>,
157 default_client_id: Option<ClientId>,
158 external_data_clients: AHashSet<ClientId>,
159 external_exec_clients: AHashSet<ClientId>,
160 accounts: AHashMap<AccountId, SharedCell<AccountAny>>,
161 orders: AHashMap<ClientOrderId, SharedCell<OrderAny>>,
162 orders_dispatched: AHashSet<ClientOrderId>,
163 order_lists: AHashMap<OrderListId, OrderList>,
164 positions: AHashMap<PositionId, SharedCell<Position>>,
165 position_snapshots: AHashMap<PositionId, Vec<PositionSnapshotFrame>>,
166 position_snapshot_revisions: AHashMap<PositionId, u64>,
167 #[cfg(feature = "defi")]
168 pub(crate) defi: crate::defi::cache::DefiCache,
169}
170
171impl Debug for Cache {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 f.debug_struct(stringify!(Cache))
174 .field("config", &self.config)
175 .field("index", &self.index)
176 .field("general", &self.general)
177 .field("currencies", &self.currencies)
178 .field("instruments", &self.instruments)
179 .field("synthetics", &self.synthetics)
180 .field("books", &self.books)
181 .field("own_books", &self.own_books)
182 .field("quotes", &self.quotes)
183 .field("trades", &self.trades)
184 .field("mark_xrates", &self.mark_xrates)
185 .field("mark_prices", &self.mark_prices)
186 .field("index_prices", &self.index_prices)
187 .field("funding_rates", &self.funding_rates)
188 .field("instrument_statuses", &self.instrument_statuses)
189 .field("instrument_closes", &self.instrument_closes)
190 .field("bars", &self.bars)
191 .field("custom_data", &self.custom_data)
192 .field("greeks", &self.greeks)
193 .field("option_greeks", &self.option_greeks)
194 .field("yield_curves", &self.yield_curves)
195 .field("external_order_claims", &self.external_order_claims)
196 .field("client_accounts", &self.client_accounts)
197 .field("client_routes", &self.client_routes)
198 .field("default_client_id", &self.default_client_id)
199 .field("external_data_clients", &self.external_data_clients)
200 .field("external_exec_clients", &self.external_exec_clients)
201 .field("accounts", &self.accounts)
202 .field("orders", &self.orders)
203 .field("orders_dispatched", &self.orders_dispatched)
204 .field("order_lists", &self.order_lists)
205 .field("positions", &self.positions)
206 .field("position_snapshots", &self.position_snapshots)
207 .finish()
208 }
209}
210
211impl Default for Cache {
212 fn default() -> Self {
214 Self::new(Some(CacheConfig::default()), None)
215 }
216}
217
218impl Cache {
219 #[must_use]
221 pub fn new(
229 config: Option<CacheConfig>,
230 database: Option<Box<dyn CacheDatabaseAdapter>>,
231 ) -> Self {
232 Self::try_new(config, database).expect("invalid `CacheConfig`")
233 }
234
235 pub fn try_new(
241 config: Option<CacheConfig>,
242 database: Option<Box<dyn CacheDatabaseAdapter>>,
243 ) -> crate::config::ConfigResult<Self> {
244 let config = config.unwrap_or_default();
245 config.validate()?;
246
247 Ok(Self {
248 config,
249 index: CacheIndex::default(),
250 database,
251 general: AHashMap::new(),
252 currencies: AHashMap::new(),
253 instruments: AHashMap::new(),
254 instrument_closes: AHashMap::new(),
255 synthetics: AHashMap::new(),
256 books: AHashMap::new(),
257 own_books: AHashMap::new(),
258 quotes: AHashMap::new(),
259 trades: AHashMap::new(),
260 mark_xrates: AHashMap::new(),
261 mark_prices: AHashMap::new(),
262 index_prices: AHashMap::new(),
263 funding_rates: AHashMap::new(),
264 instrument_statuses: AHashMap::new(),
265 bars: AHashMap::new(),
266 custom_data: AHashMap::new(),
267 greeks: AHashMap::new(),
268 option_greeks: AHashMap::new(),
269 yield_curves: AHashMap::new(),
270 external_order_claims: AHashMap::new(),
271 client_accounts: AHashMap::new(),
272 client_routes: AHashMap::new(),
273 default_client_id: None,
274 external_data_clients: AHashSet::new(),
275 external_exec_clients: AHashSet::new(),
276 accounts: AHashMap::new(),
277 orders: AHashMap::new(),
278 orders_dispatched: AHashSet::new(),
279 order_lists: AHashMap::new(),
280 positions: AHashMap::new(),
281 position_snapshots: AHashMap::new(),
282 position_snapshot_revisions: AHashMap::new(),
283 #[cfg(feature = "defi")]
284 defi: crate::defi::cache::DefiCache::default(),
285 })
286 }
287
288 #[must_use]
290 pub fn memory_address(&self) -> String {
291 format!("{:?}", std::ptr::from_ref(self))
292 }
293
294 #[must_use]
296 pub fn external_order_claim(&self, instrument_id: &InstrumentId) -> Option<StrategyId> {
297 self.external_order_claims.get(instrument_id).copied()
298 }
299
300 #[must_use]
305 pub fn external_order_claim_instrument_ids(
306 &self,
307 strategy_id: Option<StrategyId>,
308 ) -> AHashSet<InstrumentId> {
309 self.external_order_claims
310 .iter()
311 .filter_map(|(instrument_id, owner)| {
312 strategy_id
313 .is_none_or(|strategy_id| *owner == strategy_id)
314 .then_some(*instrument_id)
315 })
316 .collect()
317 }
318
319 pub fn set_external_order_claims(
331 &mut self,
332 strategy_id: StrategyId,
333 instrument_ids: &[InstrumentId],
334 ) -> anyhow::Result<()> {
335 let mut requested = AHashSet::with_capacity(instrument_ids.len());
336
337 for instrument_id in instrument_ids {
338 if !requested.insert(*instrument_id) {
339 anyhow::bail!(
340 "External order claim for {instrument_id} appears more than once for {strategy_id}"
341 );
342 }
343
344 if let Some(existing) = self.external_order_claims.get(instrument_id)
345 && *existing != strategy_id
346 {
347 anyhow::bail!(
348 "External order claim for {instrument_id} already exists for {existing}"
349 );
350 }
351 }
352
353 self.external_order_claims
354 .retain(|_, owner| *owner != strategy_id);
355 self.external_order_claims.extend(
356 requested
357 .into_iter()
358 .map(|instrument_id| (instrument_id, strategy_id)),
359 );
360
361 Ok(())
362 }
363
364 pub fn register_external_order_claims(
370 &mut self,
371 strategy_id: StrategyId,
372 instrument_ids: &[InstrumentId],
373 ) -> anyhow::Result<()> {
374 let mut requested = AHashSet::with_capacity(instrument_ids.len());
375
376 for instrument_id in instrument_ids {
377 if !requested.insert(*instrument_id) {
378 anyhow::bail!(
379 "External order claim for {instrument_id} appears more than once for {strategy_id}"
380 );
381 }
382
383 if let Some(existing) = self.external_order_claims.get(instrument_id) {
384 anyhow::bail!(
385 "External order claim for {instrument_id} already exists for {existing}"
386 );
387 }
388 }
389
390 self.external_order_claims.extend(
391 requested
392 .into_iter()
393 .map(|instrument_id| (instrument_id, strategy_id)),
394 );
395
396 Ok(())
397 }
398
399 #[must_use]
404 pub fn account_id_for_client(&self, client_id: &ClientId) -> Option<&AccountId> {
405 self.client_accounts.get(client_id)
406 }
407
408 pub fn add_client_account(&mut self, client_id: ClientId, account_id: AccountId) {
413 self.client_accounts.insert(client_id, account_id);
414 }
415
416 pub fn remove_client_account(&mut self, client_id: &ClientId) {
418 self.client_accounts.remove(client_id);
419 }
420
421 #[must_use]
423 pub fn client_id_for_venue(&self, venue: &Venue) -> Option<&ClientId> {
424 self.client_routes
425 .get(venue)
426 .or(self.default_client_id.as_ref())
427 }
428
429 pub fn add_client_route(&mut self, client_id: ClientId, venue: Venue) {
434 self.client_routes.insert(venue, client_id);
435 }
436
437 pub fn set_default_client(&mut self, client_id: ClientId) {
440 self.default_client_id = Some(client_id);
441 }
442
443 pub fn remove_client_routes(&mut self, client_id: &ClientId) {
445 self.client_routes.retain(|_, routed| routed != client_id);
446
447 if self.default_client_id.as_ref() == Some(client_id) {
448 self.default_client_id = None;
449 }
450 }
451
452 #[must_use]
455 pub fn is_external_data_client(&self, client_id: &ClientId) -> bool {
456 self.external_data_clients.contains(client_id)
457 }
458
459 #[must_use]
461 pub fn has_external_data_clients(&self) -> bool {
462 !self.external_data_clients.is_empty()
463 }
464
465 pub fn add_external_data_client(&mut self, client_id: ClientId) {
469 self.external_data_clients.insert(client_id);
470 }
471
472 #[must_use]
475 pub fn is_external_exec_client(&self, client_id: &ClientId) -> bool {
476 self.external_exec_clients.contains(client_id)
477 }
478
479 pub fn add_external_exec_client(&mut self, client_id: ClientId) {
483 self.external_exec_clients.insert(client_id);
484 }
485
486 pub fn set_database(&mut self, database: Box<dyn CacheDatabaseAdapter>) {
490 let type_name = std::any::type_name_of_val(&*database);
491 log::info!("Cache database adapter set: {type_name}");
492 self.database = Some(database);
493 }
494
495 pub fn cache_general(&mut self) -> anyhow::Result<()> {
503 self.general = match &mut self.database {
504 Some(db) => db.load()?,
505 None => AHashMap::new(),
506 };
507
508 log::info!(
509 "Cached {} general object(s) from database",
510 self.general.len()
511 );
512 Ok(())
513 }
514
515 pub async fn cache_all(&mut self) -> anyhow::Result<()> {
525 let mut cache_map = match &self.database {
526 Some(db) => db.load_all().await?,
527 None => CacheMap::default(),
528 };
529
530 for curve in cache_map.yield_curves.values() {
531 curve.validate()?;
532 }
533
534 register_loaded_currencies(&mut cache_map.currencies)?;
537 #[cfg(feature = "defi")]
538 self.defi.restore_currencies(&cache_map.currencies);
539
540 self.currencies = cache_map.currencies;
541 self.instruments = cache_map.instruments;
542 self.instrument_closes = cache_map.instrument_closes;
543 self.synthetics = cache_map.synthetics;
544 self.greeks = cache_map.greeks;
545 self.yield_curves = cache_map.yield_curves;
546 self.accounts = cache_map
547 .accounts
548 .into_iter()
549 .map(|(id, account)| (id, SharedCell::new(account)))
550 .collect();
551 self.orders = cache_map
552 .orders
553 .into_iter()
554 .map(|(id, order)| (id, SharedCell::new(order)))
555 .collect();
556 self.positions = cache_map
557 .positions
558 .into_iter()
559 .map(|(id, position)| (id, SharedCell::new(position)))
560 .collect();
561
562 if let Some(db) = &self.database {
563 let order_position = db.load_index_order_position()?;
564 self.index.order_position = self.sanitize_order_position_index(order_position);
565 self.index.order_client = db.load_index_order_client()?;
566 }
567
568 self.cache_position_oms()?;
569 self.assign_position_ids_to_contingencies();
570 Ok(())
571 }
572
573 pub async fn cache_currencies(&mut self) -> anyhow::Result<()> {
579 let mut currencies = match &mut self.database {
580 Some(db) => db.load_currencies().await?,
581 None => AHashMap::new(),
582 };
583
584 register_loaded_currencies(&mut currencies)?;
585 #[cfg(feature = "defi")]
586 self.defi.restore_currencies(¤cies);
587
588 self.currencies = currencies;
589
590 log::info!("Cached {} currencies from database", self.currencies.len());
591 Ok(())
592 }
593
594 pub async fn cache_instruments(&mut self) -> anyhow::Result<()> {
600 self.instruments = match &mut self.database {
601 Some(db) => db.load_instruments().await?,
602 None => AHashMap::new(),
603 };
604
605 log::info!("Cached {} instruments from database", self.general.len());
606 Ok(())
607 }
608
609 pub async fn cache_synthetics(&mut self) -> anyhow::Result<()> {
615 self.synthetics = match &mut self.database {
616 Some(db) => db.load_synthetics().await?,
617 None => AHashMap::new(),
618 };
619
620 log::info!(
621 "Cached {} synthetic instruments from database",
622 self.general.len()
623 );
624 Ok(())
625 }
626
627 pub async fn cache_accounts(&mut self) -> anyhow::Result<()> {
633 self.accounts = match &mut self.database {
634 Some(db) => db
635 .load_accounts()
636 .await?
637 .into_iter()
638 .map(|(id, account)| (id, SharedCell::new(account)))
639 .collect(),
640 None => AHashMap::new(),
641 };
642
643 log::info!(
644 "Cached {} synthetic instruments from database",
645 self.general.len()
646 );
647 Ok(())
648 }
649
650 pub async fn cache_orders(&mut self) -> anyhow::Result<()> {
656 self.orders = match &mut self.database {
657 Some(db) => db
658 .load_orders()
659 .await?
660 .into_iter()
661 .map(|(id, order)| (id, SharedCell::new(order)))
662 .collect(),
663 None => AHashMap::new(),
664 };
665
666 if let Some(db) = &self.database {
667 let order_position = db.load_index_order_position()?;
668 self.index.order_position = self.sanitize_order_position_index(order_position);
669 self.index.order_client = db.load_index_order_client()?;
670 }
671
672 log::info!("Cached {} orders from database", self.general.len());
673
674 self.assign_position_ids_to_contingencies();
675 Ok(())
676 }
677
678 fn sanitize_order_position_index(
679 &self,
680 mut order_position: AHashMap<ClientOrderId, PositionId>,
681 ) -> AHashMap<ClientOrderId, PositionId> {
682 let original_len = order_position.len();
683 order_position.retain(|client_order_id, _| self.orders.contains_key(client_order_id));
684 let removed = original_len - order_position.len();
685
686 if removed > 0 {
687 log::warn!(
688 "Filtered {removed} stale order-position index entries without backing orders during cache load"
689 );
690 }
691
692 order_position
693 }
694
695 pub async fn cache_positions(&mut self) -> anyhow::Result<()> {
701 self.positions = match &mut self.database {
702 Some(db) => db
703 .load_positions()
704 .await?
705 .into_iter()
706 .map(|(id, position)| (id, SharedCell::new(position)))
707 .collect(),
708 None => AHashMap::new(),
709 };
710
711 self.cache_position_oms()?;
712 log::info!("Cached {} positions from database", self.general.len());
713 Ok(())
714 }
715
716 fn cache_position_oms(&mut self) -> anyhow::Result<()> {
717 let persisted = match &self.database {
718 Some(database) => database.load()?,
719 None => self.general.clone(),
720 };
721
722 self.general
723 .retain(|key, _| !key.starts_with(POSITION_OMS_KEY_PREFIX));
724
725 for (key, value) in persisted {
726 if !key.starts_with(POSITION_OMS_KEY_PREFIX) {
727 continue;
728 }
729 self.general.insert(key, value);
730 }
731
732 self.index_position_oms();
733 Ok(())
734 }
735
736 pub fn build_index(&mut self) {
745 log::debug!("Building index");
746
747 self.index.clear_entities();
748 self.index
749 .venue_order_ids
750 .retain(|_, client_order_id| self.orders.contains_key(client_order_id));
751 self.index
752 .client_order_ids
753 .retain(|client_order_id, _| self.orders.contains_key(client_order_id));
754 self.index
755 .order_position
756 .retain(|client_order_id, _| self.orders.contains_key(client_order_id));
757 self.index
758 .order_client
759 .retain(|client_order_id, _| self.orders.contains_key(client_order_id));
760 self.index
761 .orders_pending_cancel
762 .retain(|client_order_id| self.orders.contains_key(client_order_id));
763
764 for account_id in self.accounts.keys() {
766 self.index.add_venue_account(*account_id);
767 }
768
769 for (client_order_id, order_cell) in &self.orders {
771 let order = order_cell.borrow();
772 let instrument_id = order.instrument_id();
773 let venue = instrument_id.venue;
774 let strategy_id = order.strategy_id();
775
776 self.index
778 .venue_orders
779 .entry(venue)
780 .or_default()
781 .insert(*client_order_id);
782
783 for venue_order_id in order.venue_order_ids() {
786 self.index
787 .venue_order_ids
788 .insert(*venue_order_id, *client_order_id);
789 }
790
791 if let Some(venue_order_id) = order.venue_order_id() {
792 self.index
793 .client_order_ids
794 .insert(*client_order_id, venue_order_id);
795 }
796
797 self.index.order_position.extend(
799 order
800 .position_id()
801 .map(|position_id| (*client_order_id, position_id)),
802 );
803
804 self.index
806 .order_strategy
807 .insert(*client_order_id, strategy_id);
808
809 self.index
811 .instrument_orders
812 .entry(instrument_id)
813 .or_default()
814 .insert(*client_order_id);
815
816 self.index
818 .strategy_orders
819 .entry(strategy_id)
820 .or_default()
821 .insert(*client_order_id);
822
823 if let Some(account_id) = order.account_id() {
825 self.index
826 .account_orders
827 .entry(account_id)
828 .or_default()
829 .insert(*client_order_id);
830 }
831
832 if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
834 self.index
835 .exec_algorithm_orders
836 .entry(exec_algorithm_id)
837 .or_default()
838 .insert(*client_order_id);
839 self.index.exec_algorithms.insert(exec_algorithm_id);
840 }
841
842 if let Some(exec_spawn_id) = order.exec_spawn_id() {
844 self.index
845 .exec_spawn_orders
846 .entry(exec_spawn_id)
847 .or_default()
848 .insert(*client_order_id);
849 }
850
851 self.index.orders.insert(*client_order_id);
853
854 if order.is_active_local() {
856 self.index.orders_active_local.insert(*client_order_id);
857 }
858
859 if order.is_open() {
861 self.index.orders_open.insert(*client_order_id);
862 }
863
864 if order.is_closed() {
866 self.index.orders_closed.insert(*client_order_id);
867 }
868
869 if order.emulation_trigger().is_some() && !order.is_closed() {
871 self.index.orders_emulated.insert(*client_order_id);
872 }
873
874 if order.is_inflight() {
876 self.index.orders_inflight.insert(*client_order_id);
877 }
878
879 self.index.strategies.insert(strategy_id);
881 }
882
883 for (position_id, position_cell) in &self.positions {
885 let position = position_cell.borrow();
886 let instrument_id = position.instrument_id;
887 let venue = instrument_id.venue;
888 let strategy_id = position.strategy_id;
889
890 self.index
892 .venue_positions
893 .entry(venue)
894 .or_default()
895 .insert(*position_id);
896
897 self.index
899 .position_strategy
900 .insert(*position_id, strategy_id);
901
902 let position_orders = self.index.position_orders.entry(*position_id).or_default();
904 position_orders.extend(
905 position
906 .client_order_ids()
907 .into_iter()
908 .filter(|client_order_id| self.orders.contains_key(client_order_id)),
909 );
910
911 self.index
913 .instrument_positions
914 .entry(instrument_id)
915 .or_default()
916 .insert(*position_id);
917 self.index
918 .instrument_orders
919 .entry(instrument_id)
920 .or_default();
921
922 self.index
924 .strategy_positions
925 .entry(strategy_id)
926 .or_default()
927 .insert(*position_id);
928 self.index.strategy_orders.entry(strategy_id).or_default();
929
930 self.index
932 .account_positions
933 .entry(position.account_id)
934 .or_default()
935 .insert(*position_id);
936
937 self.index.positions.insert(*position_id);
939
940 if position.is_open() {
942 self.index.positions_open.insert(*position_id);
943 }
944
945 if position.is_closed() {
947 self.index.positions_closed.insert(*position_id);
948 }
949
950 self.index.strategies.insert(strategy_id);
952 }
953
954 self.index_position_oms();
955 let client_order_ids: Vec<_> = self.orders.keys().copied().collect();
956 for client_order_id in client_order_ids {
957 self.reindex_hedging_position(client_order_id);
958 }
959 }
960
961 fn index_position_oms(&mut self) {
962 self.index.position_oms.clear();
963
964 for (key, value) in &self.general {
965 let Some(position_id) = key.strip_prefix(POSITION_OMS_KEY_PREFIX) else {
966 continue;
967 };
968 let position_id = PositionId::new(position_id);
969 if !self.positions.contains_key(&position_id) {
970 continue;
971 }
972
973 match serde_json::from_slice::<OmsType>(value) {
974 Ok(oms_type) => {
975 self.index.position_oms.insert(position_id, oms_type);
976 }
977 Err(e) => {
978 log::error!("Failed to decode position OMS for {position_id}: {e}");
979 }
980 }
981 }
982
983 for position in self.positions.values().map(|cell| cell.borrow()) {
984 if !self.index.position_oms.contains_key(&position.id)
985 && resolve_position_oms(&position, OmsType::Unspecified) == OmsType::Netting
986 {
987 self.index
988 .position_oms
989 .insert(position.id, OmsType::Netting);
990 }
991 }
992 }
993
994 #[must_use]
996 pub const fn has_backing(&self) -> bool {
997 self.database.is_some()
998 }
999
1000 pub fn load_instrument(
1006 &mut self,
1007 instrument_id: &InstrumentId,
1008 ) -> anyhow::Result<Option<InstrumentAny>> {
1009 if let Some(instrument) = self.instruments.get(instrument_id) {
1010 return Ok(Some(instrument.clone()));
1011 }
1012
1013 let Some(database) = &self.database else {
1014 return Ok(None);
1015 };
1016
1017 let instrument = database.load_instrument_sync(instrument_id)?;
1018 if let Some(instrument) = &instrument {
1019 self.instruments.insert(instrument.id(), instrument.clone());
1020 }
1021
1022 Ok(instrument)
1023 }
1024
1025 pub fn load_synthetic(
1031 &mut self,
1032 instrument_id: &InstrumentId,
1033 ) -> anyhow::Result<Option<SyntheticInstrument>> {
1034 anyhow::ensure!(
1035 instrument_id.is_synthetic(),
1036 "Instrument ID is not synthetic: {instrument_id}"
1037 );
1038
1039 if let Some(synthetic) = self.synthetics.get(instrument_id) {
1040 return Ok(Some(synthetic.clone()));
1041 }
1042
1043 let Some(database) = &self.database else {
1044 return Ok(None);
1045 };
1046
1047 let synthetic = database.load_synthetic_sync(instrument_id)?;
1048 if let Some(synthetic) = &synthetic {
1049 self.synthetics.insert(synthetic.id, synthetic.clone());
1050 }
1051
1052 Ok(synthetic)
1053 }
1054
1055 pub fn delete_actor(&self, actor_id: &ActorId) -> anyhow::Result<()> {
1063 if let Some(database) = &self.database {
1064 handle_persistence_result(
1065 format_args!("delete actor state {actor_id}"),
1066 database.delete_actor(actor_id),
1067 )?;
1068 }
1069
1070 Ok(())
1071 }
1072
1073 pub fn delete_strategy(&self, strategy_id: &StrategyId) -> anyhow::Result<()> {
1081 if let Some(database) = &self.database {
1082 handle_persistence_result(
1083 format_args!("delete strategy state {strategy_id}"),
1084 database.delete_strategy(strategy_id),
1085 )?;
1086 }
1087
1088 Ok(())
1089 }
1090
1091 pub fn heartbeat(&self, timestamp: UnixNanos) -> anyhow::Result<()> {
1099 if let Some(database) = &self.database {
1100 handle_persistence_result(
1101 format_args!("persist heartbeat {timestamp}"),
1102 database.heartbeat(timestamp),
1103 )?;
1104 }
1105
1106 Ok(())
1107 }
1108
1109 pub fn load_actor_state(
1117 &self,
1118 actor_id: &ActorId,
1119 ) -> anyhow::Result<Option<IndexMap<String, Vec<u8>>>> {
1120 self.database
1121 .as_ref()
1122 .map(|database| database.load_actor(actor_id))
1123 .transpose()
1124 .map(|state| state.map(Self::decode_component_state))
1125 }
1126
1127 pub fn load_strategy_state(
1135 &self,
1136 strategy_id: &StrategyId,
1137 ) -> anyhow::Result<Option<IndexMap<String, Vec<u8>>>> {
1138 self.database
1139 .as_ref()
1140 .map(|database| database.load_strategy(strategy_id))
1141 .transpose()
1142 .map(|state| state.map(Self::decode_component_state))
1143 }
1144
1145 pub fn update_actor_state(
1153 &self,
1154 actor_id: &ActorId,
1155 state: &IndexMap<String, Vec<u8>>,
1156 ) -> anyhow::Result<()> {
1157 if let Some(database) = &self.database {
1158 handle_persistence_result(
1159 format_args!("persist actor state {actor_id}"),
1160 database.update_actor(actor_id, &Self::encode_component_state(state)),
1161 )?;
1162 }
1163 Ok(())
1164 }
1165
1166 pub fn update_strategy_state(
1174 &self,
1175 strategy_id: &StrategyId,
1176 state: &IndexMap<String, Vec<u8>>,
1177 ) -> anyhow::Result<()> {
1178 if let Some(database) = &self.database {
1179 handle_persistence_result(
1180 format_args!("persist strategy state {strategy_id}"),
1181 database.update_strategy(strategy_id, &Self::encode_component_state(state)),
1182 )?;
1183 }
1184 Ok(())
1185 }
1186
1187 fn decode_component_state(state: AHashMap<String, Bytes>) -> IndexMap<String, Vec<u8>> {
1188 state
1189 .into_iter()
1190 .map(|(key, value)| (key, value.to_vec()))
1191 .collect()
1192 }
1193
1194 fn encode_component_state(state: &IndexMap<String, Vec<u8>>) -> AHashMap<String, Bytes> {
1195 state
1196 .iter()
1197 .map(|(key, value)| (key.clone(), Bytes::copy_from_slice(value)))
1198 .collect()
1199 }
1200
1201 #[must_use]
1203 pub fn calculate_unrealized_pnl(&self, position: &Position) -> Option<Money> {
1204 let instrument_id = &position.instrument_id;
1205 let price_type = match position.side {
1206 PositionSide::Long => PriceType::Bid,
1207 PositionSide::Short => PriceType::Ask,
1208 PositionSide::Flat => return Some(Money::zero(position.settlement_currency)),
1209 };
1210
1211 let allows_negative_price = self
1212 .instrument(instrument_id)
1213 .map(Instrument::allows_negative_price)
1214 .or(position.allows_negative_price);
1215 let allows_non_positive = |default| {
1216 !position
1217 .instrument_class
1218 .divides_notional_by_price(position.is_inverse)
1219 && allows_negative_price.unwrap_or(default)
1220 };
1221
1222 let is_valid = |price: &Price, non_positive_allowed| {
1223 !price.is_undefined()
1224 && !price.is_error()
1225 && price.precision != ERROR_PRICE.precision
1226 && (price.as_decimal() > Decimal::ZERO || non_positive_allowed)
1227 };
1228
1229 let fallback_is_valid = |price: &Price| {
1230 is_valid(
1231 price,
1232 allows_non_positive(position.instrument_class.allows_negative_price()),
1233 )
1234 };
1235 let quote_price = || {
1236 self.quote(instrument_id).and_then(|quote| {
1237 let (price, size) = match price_type {
1238 PriceType::Bid => (quote.bid_price, quote.bid_size),
1239 _ => (quote.ask_price, quote.ask_size),
1240 };
1241
1242 (is_valid(&price, allows_non_positive(true))
1244 && (price.as_decimal() > Decimal::ZERO || size.is_positive()))
1245 .then_some(price)
1246 })
1247 };
1248
1249 let bar_rank = |bar: &Bar| {
1252 let bar_price_type = bar.bar_type.spec().price_type;
1253 if bar_price_type == price_type {
1254 0
1255 } else {
1256 match bar_price_type {
1257 PriceType::Mark => 1,
1258 PriceType::Last => 2,
1259 PriceType::Mid => 3,
1260 PriceType::Bid | PriceType::Ask => 4,
1261 }
1262 }
1263 };
1264
1265 let bar_close = || {
1267 self.bars
1268 .iter()
1269 .filter(|(bar_type, _)| bar_type.instrument_id() == *instrument_id)
1270 .filter_map(|(_, bars)| bars.front())
1271 .filter(|bar| fallback_is_valid(&bar.close))
1272 .min_by_key(|bar| (Reverse(bar.ts_init), bar_rank(bar), bar.bar_type))
1273 .map(|bar| bar.close)
1274 };
1275
1276 let Some(last) = quote_price()
1279 .or_else(|| {
1280 self.price(instrument_id, PriceType::Mark)
1281 .filter(fallback_is_valid)
1282 })
1283 .or_else(|| {
1284 self.price(instrument_id, PriceType::Last)
1285 .filter(fallback_is_valid)
1286 })
1287 .or_else(bar_close)
1288 else {
1289 log::warn!(
1290 "Cannot calculate unrealized PnL for {}, no quotes, mark prices, trades, or bars for {instrument_id}",
1291 position.id,
1292 );
1293 return None;
1294 };
1295
1296 position
1297 .try_unrealized_pnl(last)
1298 .inspect_err(|e| {
1299 log::error!("Cannot calculate unrealized PnL for {}: {e}", position.id);
1300 })
1301 .ok()
1302 }
1303
1304 #[must_use]
1313 pub fn check_integrity(&mut self) -> bool {
1314 let mut error_count = 0;
1315
1316 let timestamp_us = SystemTime::now()
1318 .duration_since(UNIX_EPOCH)
1319 .expect("Time went backwards")
1320 .as_micros();
1321
1322 log::info!("Checking data integrity");
1323
1324 for account_id in self.accounts.keys() {
1326 if !self
1327 .index
1328 .venue_accounts
1329 .get(&account_id.get_issuer())
1330 .is_some_and(|account_ids| account_ids.contains(account_id))
1331 {
1332 log::error!(
1333 "{INTEGRITY_FAILURE} in accounts: {account_id} not found in `self.index.venue_accounts`",
1334 );
1335 error_count += 1;
1336 }
1337 }
1338
1339 for (client_order_id, order_cell) in &self.orders {
1340 let order = order_cell.borrow();
1341
1342 if !self.index.order_strategy.contains_key(client_order_id) {
1343 log::error!(
1344 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.order_strategy`"
1345 );
1346 error_count += 1;
1347 }
1348
1349 if !self.index.orders.contains(client_order_id) {
1350 log::error!(
1351 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.orders`",
1352 );
1353 error_count += 1;
1354 }
1355
1356 if order.is_inflight() && !self.index.orders_inflight.contains(client_order_id) {
1357 log::error!(
1358 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.orders_inflight`",
1359 );
1360 error_count += 1;
1361 }
1362
1363 if order.is_active_local() && !self.index.orders_active_local.contains(client_order_id)
1364 {
1365 log::error!(
1366 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.orders_active_local`",
1367 );
1368 error_count += 1;
1369 }
1370
1371 if order.is_open() && !self.index.orders_open.contains(client_order_id) {
1372 log::error!(
1373 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.orders_open`",
1374 );
1375 error_count += 1;
1376 }
1377
1378 if order.is_closed() && !self.index.orders_closed.contains(client_order_id) {
1379 log::error!(
1380 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.orders_closed`",
1381 );
1382 error_count += 1;
1383 }
1384
1385 if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
1386 if !self
1387 .index
1388 .exec_algorithm_orders
1389 .contains_key(&exec_algorithm_id)
1390 {
1391 log::error!(
1392 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.exec_algorithm_orders`",
1393 );
1394 error_count += 1;
1395 }
1396
1397 if order.exec_spawn_id().is_none()
1398 && !self.index.exec_spawn_orders.contains_key(client_order_id)
1399 {
1400 log::error!(
1401 "{INTEGRITY_FAILURE} in orders: {client_order_id} not found in `self.index.exec_spawn_orders`",
1402 );
1403 error_count += 1;
1404 }
1405 }
1406 }
1407
1408 for (position_id, position_cell) in &self.positions {
1409 let position = position_cell.borrow();
1410
1411 if !self.index.position_strategy.contains_key(position_id) {
1412 log::error!(
1413 "{INTEGRITY_FAILURE} in positions: {position_id} not found in `self.index.position_strategy`",
1414 );
1415 error_count += 1;
1416 }
1417
1418 if !self.index.position_orders.contains_key(position_id) {
1419 log::error!(
1420 "{INTEGRITY_FAILURE} in positions: {position_id} not found in `self.index.position_orders`",
1421 );
1422 error_count += 1;
1423 }
1424
1425 if !self.index.positions.contains(position_id) {
1426 log::error!(
1427 "{INTEGRITY_FAILURE} in positions: {position_id} not found in `self.index.positions`",
1428 );
1429 error_count += 1;
1430 }
1431
1432 if position.is_open() && !self.index.positions_open.contains(position_id) {
1433 log::error!(
1434 "{INTEGRITY_FAILURE} in positions: {position_id} not found in `self.index.positions_open`",
1435 );
1436 error_count += 1;
1437 }
1438
1439 if position.is_closed() && !self.index.positions_closed.contains(position_id) {
1440 log::error!(
1441 "{INTEGRITY_FAILURE} in positions: {position_id} not found in `self.index.positions_closed`",
1442 );
1443 error_count += 1;
1444 }
1445 }
1446
1447 let order_cached =
1449 |client_order_id: &ClientOrderId| self.orders.contains_key(client_order_id);
1450 let position_cached = |position_id: &PositionId| self.positions.contains_key(position_id);
1451
1452 error_count += Self::count_index_ids_missing(
1453 "venue_accounts",
1454 self.index.venue_accounts.values().flatten(),
1455 "self.accounts",
1456 |account_id| self.accounts.contains_key(account_id),
1457 );
1458 error_count += Self::count_index_ids_missing(
1459 "venue_order_ids",
1460 self.index.venue_order_ids.values(),
1461 "self.orders",
1462 order_cached,
1463 );
1464 error_count += Self::count_index_ids_missing(
1465 "client_order_ids",
1466 self.index.client_order_ids.keys(),
1467 "self.orders",
1468 order_cached,
1469 );
1470 error_count += Self::count_index_ids_missing(
1471 "order_position",
1472 self.index.order_position.keys(),
1473 "self.orders",
1474 order_cached,
1475 );
1476 error_count += Self::count_index_ids_missing(
1477 "order_strategy",
1478 self.index.order_strategy.keys(),
1479 "self.orders",
1480 order_cached,
1481 );
1482 error_count += Self::count_index_ids_missing(
1483 "position_strategy",
1484 self.index.position_strategy.keys(),
1485 "self.positions",
1486 position_cached,
1487 );
1488 error_count += Self::count_index_ids_missing(
1489 "position_orders",
1490 self.index.position_orders.keys(),
1491 "self.positions",
1492 position_cached,
1493 );
1494
1495 for (instrument_id, client_order_ids) in &self.index.instrument_orders {
1496 for client_order_id in client_order_ids {
1497 if !self.orders.contains_key(client_order_id) {
1498 log::error!(
1499 "{INTEGRITY_FAILURE} in `index.instrument_orders`: {instrument_id} not found in `self.orders`",
1500 );
1501 error_count += 1;
1502 }
1503 }
1504 }
1505
1506 error_count += Self::count_index_ids_missing(
1507 "instrument_positions",
1508 self.index.instrument_positions.keys(),
1509 "index.instrument_orders",
1510 |instrument_id| self.index.instrument_orders.contains_key(instrument_id),
1511 );
1512 error_count += Self::count_index_ids_missing(
1513 "strategy_orders",
1514 self.index.strategy_orders.values().flatten(),
1515 "self.orders",
1516 order_cached,
1517 );
1518 error_count += Self::count_index_ids_missing(
1519 "strategy_positions",
1520 self.index.strategy_positions.values().flatten(),
1521 "self.positions",
1522 position_cached,
1523 );
1524
1525 for (index_name, client_order_ids) in [
1526 ("orders", &self.index.orders),
1527 ("orders_emulated", &self.index.orders_emulated),
1528 ("orders_active_local", &self.index.orders_active_local),
1529 ("orders_inflight", &self.index.orders_inflight),
1530 ("orders_open", &self.index.orders_open),
1531 ("orders_closed", &self.index.orders_closed),
1532 ] {
1533 error_count += Self::count_index_ids_missing(
1534 index_name,
1535 client_order_ids,
1536 "self.orders",
1537 order_cached,
1538 );
1539 }
1540
1541 for (index_name, position_ids) in [
1542 ("positions", &self.index.positions),
1543 ("positions_open", &self.index.positions_open),
1544 ("positions_closed", &self.index.positions_closed),
1545 ] {
1546 error_count += Self::count_index_ids_missing(
1547 index_name,
1548 position_ids,
1549 "self.positions",
1550 position_cached,
1551 );
1552 }
1553
1554 error_count += Self::count_index_ids_missing(
1555 "strategies",
1556 &self.index.strategies,
1557 "index.strategy_orders",
1558 |strategy_id| self.index.strategy_orders.contains_key(strategy_id),
1559 );
1560 error_count += Self::count_index_ids_missing(
1561 "exec_algorithms",
1562 &self.index.exec_algorithms,
1563 "index.exec_algorithm_orders",
1564 |exec_algorithm_id| {
1565 self.index
1566 .exec_algorithm_orders
1567 .contains_key(exec_algorithm_id)
1568 },
1569 );
1570
1571 let total_us = SystemTime::now()
1572 .duration_since(UNIX_EPOCH)
1573 .expect("Time went backwards")
1574 .as_micros()
1575 - timestamp_us;
1576
1577 if error_count == 0 {
1578 log::info!("Integrity check passed in {total_us}μs");
1579 true
1580 } else {
1581 log::error!(
1582 "Integrity check failed with {error_count} error{} in {total_us}μs",
1583 if error_count == 1 { "" } else { "s" },
1584 );
1585 false
1586 }
1587 }
1588
1589 fn count_index_ids_missing<'a, T: Display + 'a>(
1590 index_name: &str,
1591 ids: impl IntoIterator<Item = &'a T>,
1592 source_name: &str,
1593 contains: impl Fn(&T) -> bool,
1594 ) -> usize {
1595 let mut count = 0;
1596
1597 for id in ids {
1598 if !contains(id) {
1599 log::error!(
1600 "{INTEGRITY_FAILURE} in `index.{index_name}`: {id} not found in `{source_name}`"
1601 );
1602 count += 1;
1603 }
1604 }
1605
1606 count
1607 }
1608
1609 #[must_use]
1613 pub fn check_residuals(&self) -> bool {
1614 log::debug!("Checking residuals");
1615
1616 let mut residuals = false;
1617
1618 for order in self.orders_open(None, None, None, None, None) {
1620 residuals = true;
1621 log::warn!("Residual {order}");
1622 }
1623
1624 for position in self.positions_open(None, None, None, None, None) {
1626 residuals = true;
1627 log::warn!("Residual {position}");
1628 }
1629
1630 residuals
1631 }
1632
1633 pub fn purge_closed_orders(
1647 &mut self,
1648 ts_now: UnixNanos,
1649 buffer_secs: u64,
1650 purge_from_database: bool,
1651 ) -> anyhow::Result<()> {
1652 log::debug!(
1653 "Purging closed orders{}",
1654 if buffer_secs > 0 {
1655 format!(" with buffer_secs={buffer_secs}")
1656 } else {
1657 String::new()
1658 }
1659 );
1660
1661 let Ok(buffer_ns) = DurationNanos::try_from_secs(buffer_secs) else {
1662 log::warn!(
1663 "Cannot purge closed orders: buffer_secs {buffer_secs} is not representable in `u64` nanoseconds"
1664 );
1665 return Ok(());
1666 };
1667 let purge_cutoff = ts_now.checked_sub(buffer_ns);
1668
1669 let mut affected_order_list_ids: AHashSet<OrderListId> = AHashSet::new();
1670 let mut purged_client_order_ids: AHashSet<ClientOrderId> = AHashSet::new();
1671 let mut result = Ok(());
1672
1673 'outer: for client_order_id in self.index.orders_closed.clone() {
1674 let purge_target = self.orders.get(&client_order_id).and_then(|order_cell| {
1675 let order = order_cell.borrow();
1676 if order.is_closed()
1677 && let Some(ts_closed) = order.ts_closed()
1678 && purge_cutoff.is_some_and(|cutoff| ts_closed <= cutoff)
1679 {
1680 let linked = order.linked_order_ids().map(<[_]>::to_vec);
1681 let order_list_id = order.order_list_id();
1682 Some((linked, order_list_id))
1683 } else {
1684 None
1685 }
1686 });
1687
1688 let Some((linked, order_list_id)) = purge_target else {
1689 continue;
1690 };
1691
1692 if let Some(linked_order_ids) = linked {
1694 for linked_order_id in &linked_order_ids {
1695 if let Some(linked_order_cell) = self.orders.get(linked_order_id)
1696 && linked_order_cell.borrow().is_open()
1697 {
1698 continue 'outer;
1700 }
1701 }
1702 }
1703
1704 if let Some(order_list_id) = order_list_id {
1705 affected_order_list_ids.insert(order_list_id);
1706 }
1707
1708 match self.purge_order_checked(client_order_id, purge_from_database) {
1709 Ok(true) => {
1710 purged_client_order_ids.insert(client_order_id);
1711 }
1712 Ok(false) => {}
1713 Err(e) => {
1714 result = Err(e);
1715 break;
1716 }
1717 }
1718 }
1719
1720 if !purged_client_order_ids.is_empty() {
1721 self.index
1722 .venue_order_ids
1723 .retain(|_, owner| !purged_client_order_ids.contains(owner));
1724 }
1725
1726 for order_list_id in affected_order_list_ids {
1727 if let Some(order_list) = self.order_lists.get(&order_list_id) {
1728 let all_purged = order_list
1729 .client_order_ids
1730 .iter()
1731 .all(|id| !self.orders.contains_key(id));
1732
1733 if all_purged {
1734 self.order_lists.remove(&order_list_id);
1735 log::info!("Purged {order_list_id}");
1736 }
1737 }
1738 }
1739
1740 result
1741 }
1742
1743 pub fn purge_closed_positions(
1753 &mut self,
1754 ts_now: UnixNanos,
1755 buffer_secs: u64,
1756 purge_from_database: bool,
1757 ) -> anyhow::Result<()> {
1758 log::debug!(
1759 "Purging closed positions{}",
1760 if buffer_secs > 0 {
1761 format!(" with buffer_secs={buffer_secs}")
1762 } else {
1763 String::new()
1764 }
1765 );
1766
1767 let Ok(buffer_ns) = DurationNanos::try_from_secs(buffer_secs) else {
1768 log::warn!(
1769 "Cannot purge closed positions: buffer_secs {buffer_secs} is not representable in `u64` nanoseconds"
1770 );
1771 return Ok(());
1772 };
1773 let purge_cutoff = ts_now.checked_sub(buffer_ns);
1774
1775 for position_id in self.index.positions_closed.clone() {
1776 let should_purge = self.positions.get(&position_id).is_some_and(|cell| {
1777 let position = cell.borrow();
1778 position.is_closed()
1779 && position.ts_closed.is_some_and(|ts_closed| {
1780 purge_cutoff.is_some_and(|cutoff| ts_closed <= cutoff)
1781 })
1782 });
1783
1784 if should_purge {
1785 self.purge_position(position_id, purge_from_database)?;
1786 }
1787 }
1788
1789 Ok(())
1790 }
1791
1792 pub fn purge_order(
1804 &mut self,
1805 client_order_id: ClientOrderId,
1806 purge_from_database: bool,
1807 ) -> anyhow::Result<()> {
1808 if self.purge_order_checked(client_order_id, purge_from_database)? {
1809 self.index
1810 .venue_order_ids
1811 .retain(|_, owner| owner != &client_order_id);
1812 }
1813
1814 Ok(())
1815 }
1816
1817 fn purge_order_checked(
1818 &mut self,
1819 client_order_id: ClientOrderId,
1820 purge_from_database: bool,
1821 ) -> anyhow::Result<bool> {
1822 if purge_from_database
1823 && let Some(database) = &self.database
1824 && self
1825 .orders
1826 .get(&client_order_id)
1827 .is_none_or(|order| !order.borrow().is_open())
1828 {
1829 handle_persistence_result(
1830 format_args!("delete order {client_order_id}"),
1831 database.delete_order(&client_order_id),
1832 )?;
1833 }
1834
1835 Ok(self.purge_order_except_aliases(client_order_id))
1836 }
1837
1838 fn purge_order_except_aliases(&mut self, client_order_id: ClientOrderId) -> bool {
1843 struct OrderDetails {
1844 is_open: bool,
1845 instrument_id: InstrumentId,
1846 strategy_id: StrategyId,
1847 account_id: Option<AccountId>,
1848 exec_algorithm_id: Option<ExecAlgorithmId>,
1849 exec_spawn_id: Option<ClientOrderId>,
1850 position_id: Option<PositionId>,
1851 }
1852
1853 let order_cell = self.orders.get(&client_order_id).cloned();
1854 let order_details = order_cell.as_ref().map(|cell| {
1855 let order = cell.borrow();
1856 OrderDetails {
1857 is_open: order.is_open(),
1858 instrument_id: order.instrument_id(),
1859 strategy_id: order.strategy_id(),
1860 account_id: order.account_id(),
1861 exec_algorithm_id: order.exec_algorithm_id(),
1862 exec_spawn_id: order.exec_spawn_id(),
1863 position_id: order.position_id(),
1864 }
1865 });
1866
1867 if order_details
1868 .as_ref()
1869 .is_some_and(|details| details.is_open)
1870 {
1871 log::warn!("Order {client_order_id} found open when purging, skipping purge");
1872 return false;
1873 }
1874
1875 if order_details.is_some() {
1876 self.orders.remove(&client_order_id);
1877 } else {
1878 log::warn!("Order {client_order_id} not found when purging");
1879 }
1880
1881 let indexed_position_id = self.index.order_position.remove(&client_order_id);
1882 let indexed_strategy_id = self.index.order_strategy.remove(&client_order_id);
1883 self.index.order_client.remove(&client_order_id);
1884 self.index.client_order_ids.remove(&client_order_id);
1885
1886 if let Some(details) = &order_details {
1887 if Self::remove_from_bucket(
1888 &mut self.index.venue_orders,
1889 &details.instrument_id.venue,
1890 &client_order_id,
1891 ) {
1892 self.index.venue_orders.remove(&details.instrument_id.venue);
1893 }
1894
1895 let instrument_orders_became_empty = Self::remove_from_bucket(
1898 &mut self.index.instrument_orders,
1899 &details.instrument_id,
1900 &client_order_id,
1901 );
1902
1903 let has_instrument_positions = self
1904 .index
1905 .instrument_positions
1906 .get(&details.instrument_id)
1907 .is_some_and(|positions| !positions.is_empty());
1908
1909 if instrument_orders_became_empty && !has_instrument_positions {
1910 self.index.instrument_orders.remove(&details.instrument_id);
1911 }
1912
1913 if let Some(exec_algorithm_id) = details.exec_algorithm_id
1914 && Self::remove_from_bucket(
1915 &mut self.index.exec_algorithm_orders,
1916 &exec_algorithm_id,
1917 &client_order_id,
1918 )
1919 {
1920 self.index.exec_algorithm_orders.remove(&exec_algorithm_id);
1921 self.index.exec_algorithms.remove(&exec_algorithm_id);
1922 }
1923
1924 if let Some(account_id) = details.account_id
1925 && Self::remove_from_bucket(
1926 &mut self.index.account_orders,
1927 &account_id,
1928 &client_order_id,
1929 )
1930 {
1931 self.index.account_orders.remove(&account_id);
1932 }
1933
1934 if let Some(exec_spawn_id) = details.exec_spawn_id
1935 && Self::remove_from_bucket(
1936 &mut self.index.exec_spawn_orders,
1937 &exec_spawn_id,
1938 &client_order_id,
1939 )
1940 {
1941 self.index.exec_spawn_orders.remove(&exec_spawn_id);
1942 }
1943 }
1944
1945 let mut position_ids = AHashSet::new();
1946 if let Some(position_id) = indexed_position_id {
1947 position_ids.insert(position_id);
1948 }
1949
1950 if let Some(position_id) = order_details
1951 .as_ref()
1952 .and_then(|details| details.position_id)
1953 {
1954 position_ids.insert(position_id);
1955 }
1956
1957 let mut strategy_ids = AHashSet::new();
1958 if let Some(strategy_id) = indexed_strategy_id {
1959 strategy_ids.insert(strategy_id);
1960 }
1961
1962 if let Some(details) = &order_details {
1963 strategy_ids.insert(details.strategy_id);
1964 }
1965
1966 for position_id in position_ids {
1967 if self.positions.contains_key(&position_id) {
1968 if let Some(position_orders) = self.index.position_orders.get_mut(&position_id) {
1969 position_orders.remove(&client_order_id);
1970 }
1971 continue;
1972 }
1973
1974 let has_other_orders =
1975 if let Some(position_orders) = self.index.position_orders.get_mut(&position_id) {
1976 position_orders.remove(&client_order_id);
1977 !position_orders.is_empty()
1978 } else {
1979 self.index
1980 .order_position
1981 .values()
1982 .any(|candidate| *candidate == position_id)
1983 };
1984
1985 if has_other_orders {
1986 continue;
1987 }
1988
1989 self.index.position_orders.remove(&position_id);
1990 if let Some(strategy_id) = self.index.position_strategy.remove(&position_id) {
1991 strategy_ids.insert(strategy_id);
1992 if Self::remove_from_bucket(
1993 &mut self.index.strategy_positions,
1994 &strategy_id,
1995 &position_id,
1996 ) {
1997 self.index.strategy_positions.remove(&strategy_id);
1998 }
1999 }
2000
2001 if let Some(details) = &order_details
2002 && Self::remove_from_bucket(
2003 &mut self.index.venue_positions,
2004 &details.instrument_id.venue,
2005 &position_id,
2006 )
2007 {
2008 self.index
2009 .venue_positions
2010 .remove(&details.instrument_id.venue);
2011 }
2012 }
2013
2014 for strategy_id in strategy_ids {
2015 let strategy_orders_became_empty = Self::remove_from_bucket(
2021 &mut self.index.strategy_orders,
2022 &strategy_id,
2023 &client_order_id,
2024 );
2025
2026 let has_positions = self
2027 .index
2028 .strategy_positions
2029 .get(&strategy_id)
2030 .is_some_and(|strategy_positions| !strategy_positions.is_empty());
2031
2032 if strategy_orders_became_empty && !has_positions {
2033 self.index.strategy_orders.remove(&strategy_id);
2034 self.index.strategies.remove(&strategy_id);
2035 }
2036 }
2037
2038 self.index.exec_spawn_orders.remove(&client_order_id);
2039
2040 self.index.orders.remove(&client_order_id);
2041 self.index.orders_active_local.remove(&client_order_id);
2042 self.index.orders_open.remove(&client_order_id);
2043 self.index.orders_closed.remove(&client_order_id);
2044 self.index.orders_emulated.remove(&client_order_id);
2045 self.index.orders_inflight.remove(&client_order_id);
2046 self.index.orders_pending_cancel.remove(&client_order_id);
2047
2048 if order_details.is_some() {
2049 log::info!("Purged order {client_order_id}");
2050 }
2051
2052 true
2053 }
2054
2055 pub fn purge_position(
2067 &mut self,
2068 position_id: PositionId,
2069 purge_from_database: bool,
2070 ) -> anyhow::Result<()> {
2071 let position_cell = self.positions.get(&position_id).cloned();
2073 let position = position_cell.as_ref().map(|cell| cell.borrow());
2074
2075 if let Some(ref pos) = position
2077 && pos.is_open()
2078 {
2079 log::warn!("Position {position_id} found open when purging, skipping purge");
2080 return Ok(());
2081 }
2082
2083 self.delete_position_from_database(position_id, purge_from_database)?;
2084
2085 if let Some(ref pos) = position {
2087 self.positions.remove(&position_id);
2088
2089 if Self::remove_from_bucket(
2091 &mut self.index.venue_positions,
2092 &pos.instrument_id.venue,
2093 &position_id,
2094 ) {
2095 self.index.venue_positions.remove(&pos.instrument_id.venue);
2096 }
2097
2098 if Self::remove_from_bucket(
2100 &mut self.index.instrument_positions,
2101 &pos.instrument_id,
2102 &position_id,
2103 ) {
2104 self.index.instrument_positions.remove(&pos.instrument_id);
2105 let instrument_orders_empty = self
2106 .index
2107 .instrument_orders
2108 .get(&pos.instrument_id)
2109 .is_some_and(|orders| orders.is_empty());
2110
2111 if instrument_orders_empty {
2112 self.index.instrument_orders.remove(&pos.instrument_id);
2113 }
2114 }
2115
2116 if Self::remove_from_bucket(
2118 &mut self.index.strategy_positions,
2119 &pos.strategy_id,
2120 &position_id,
2121 ) {
2122 self.index.strategy_positions.remove(&pos.strategy_id);
2123 let strategy_orders_empty = self
2124 .index
2125 .strategy_orders
2126 .get(&pos.strategy_id)
2127 .is_some_and(|orders| orders.is_empty());
2128
2129 if strategy_orders_empty {
2130 self.index.strategy_orders.remove(&pos.strategy_id);
2131 self.index.strategies.remove(&pos.strategy_id);
2132 }
2133 }
2134
2135 if Self::remove_from_bucket(
2137 &mut self.index.account_positions,
2138 &pos.account_id,
2139 &position_id,
2140 ) {
2141 self.index.account_positions.remove(&pos.account_id);
2142 }
2143
2144 for client_order_id in pos.client_order_ids() {
2146 self.index.order_position.remove(&client_order_id);
2147 }
2148
2149 log::info!("Purged position {position_id}");
2150 } else {
2151 log::warn!("Position {position_id} not found when purging");
2152 }
2153
2154 self.index.position_strategy.remove(&position_id);
2156 self.index.position_oms.remove(&position_id);
2157 self.index.position_orders.remove(&position_id);
2158 self.index.positions.remove(&position_id);
2159 self.index.positions_open.remove(&position_id);
2160 self.index.positions_closed.remove(&position_id);
2161
2162 self.position_snapshots.remove(&position_id);
2164 self.bump_position_snapshot_revision(position_id);
2165 Ok(())
2166 }
2167
2168 fn delete_position_from_database(
2169 &self,
2170 position_id: PositionId,
2171 requested: bool,
2172 ) -> anyhow::Result<()> {
2173 if requested && let Some(database) = &self.database {
2174 handle_persistence_result(
2175 format_args!("delete position {position_id}"),
2176 database.delete_position(&position_id),
2177 )?;
2178 }
2179
2180 Ok(())
2181 }
2182
2183 fn purge_instrument_inner(&mut self, instrument_id: InstrumentId, skip_order_guard: bool) {
2207 #[cfg(feature = "defi")]
2208 let defi_found =
2209 self.pool(&instrument_id).is_some() || self.pool_profiler(&instrument_id).is_some();
2210 #[cfg(not(feature = "defi"))]
2211 let defi_found = false;
2212
2213 let found = self.instruments.contains_key(&instrument_id)
2214 || self.synthetics.contains_key(&instrument_id)
2215 || defi_found;
2216
2217 if !found {
2218 log::warn!("Instrument {instrument_id} not found when purging");
2219 return;
2220 }
2221
2222 if !skip_order_guard && let Some(orders) = self.index.instrument_orders.get(&instrument_id)
2223 {
2224 let has_non_terminal = orders
2225 .iter()
2226 .any(|client_order_id| !self.index.orders_closed.contains(client_order_id));
2227
2228 if has_non_terminal {
2229 log::warn!(
2230 "Instrument {instrument_id} has non-terminal orders when purging, skipping purge"
2231 );
2232 return;
2233 }
2234 }
2235
2236 if let Some(positions) = self.index.instrument_positions.get(&instrument_id) {
2237 let has_non_closed = positions
2238 .iter()
2239 .any(|position_id| !self.index.positions_closed.contains(position_id));
2240
2241 if has_non_closed {
2242 log::warn!(
2243 "Instrument {instrument_id} has non-closed positions when purging, skipping purge"
2244 );
2245 return;
2246 }
2247 }
2248
2249 self.instruments.remove(&instrument_id);
2250 self.synthetics.remove(&instrument_id);
2251 self.books.remove(&instrument_id);
2252 self.own_books.remove(&instrument_id);
2253 self.quotes.remove(&instrument_id);
2254 self.trades.remove(&instrument_id);
2255 self.mark_prices.remove(&instrument_id);
2256 self.index_prices.remove(&instrument_id);
2257 self.funding_rates.remove(&instrument_id);
2258 self.instrument_statuses.remove(&instrument_id);
2259 self.instrument_closes.remove(&instrument_id);
2260 self.greeks.remove(&instrument_id);
2261 self.option_greeks.remove(&instrument_id);
2262 let identifier = instrument_id.to_string();
2263 self.custom_data
2264 .retain(|data_type, _| data_type.identifier() != Some(identifier.as_str()));
2265
2266 self.bars
2267 .retain(|bar_type, _| bar_type.instrument_id() != instrument_id);
2268
2269 #[cfg(feature = "defi")]
2270 self.defi.remove_instrument(&instrument_id);
2271
2272 log::info!("Purged instrument {instrument_id}");
2273 }
2274
2275 pub fn purge_instrument(&mut self, instrument_id: InstrumentId) {
2280 self.purge_instrument_inner(instrument_id, false);
2281 }
2282
2283 pub fn purge_instrument_skip_order_guard(&mut self, instrument_id: InstrumentId) {
2292 self.purge_instrument_inner(instrument_id, true);
2293 }
2294
2295 pub fn purge_account_events(
2309 &mut self,
2310 ts_now: UnixNanos,
2311 lookback_secs: u64,
2312 purge_from_database: bool,
2313 ) -> anyhow::Result<()> {
2314 log::debug!(
2315 "Purging account events{}",
2316 if lookback_secs > 0 {
2317 format!(" with lookback_secs={lookback_secs}")
2318 } else {
2319 String::new()
2320 }
2321 );
2322
2323 for account_cell in self.accounts.values() {
2324 let mut account = account_cell.borrow_mut();
2325 let event_count = account.event_count();
2326 let events_before =
2327 (purge_from_database && self.database.is_some()).then(|| account.events());
2328 account.purge_account_events(ts_now, lookback_secs);
2329 let count_diff = event_count - account.event_count();
2330 if count_diff > 0 {
2331 log::info!(
2332 "Purged {} event(s) from account {}",
2333 count_diff,
2334 account.id()
2335 );
2336
2337 if let Some(database) = &self.database
2338 && let Some(events_before) = events_before
2339 {
2340 Self::delete_purged_account_events(
2341 database.as_ref(),
2342 &account,
2343 &events_before,
2344 )?;
2345 }
2346 }
2347 }
2348
2349 Ok(())
2350 }
2351
2352 fn delete_purged_account_events(
2353 database: &dyn CacheDatabaseAdapter,
2354 account: &AccountAny,
2355 events_before: &[AccountState],
2356 ) -> anyhow::Result<()> {
2357 let retained: AHashSet<_> = account
2358 .events()
2359 .iter()
2360 .map(|event| event.event_id)
2361 .collect();
2362
2363 for event in events_before {
2364 if retained.contains(&event.event_id) {
2365 continue;
2366 }
2367
2368 handle_persistence_result(
2369 format_args!("delete account event {}", event.event_id),
2370 database.delete_account_event(&account.id(), &event.event_id.to_string()),
2371 )?;
2372 }
2373
2374 Ok(())
2375 }
2376
2377 pub fn clear_index(&mut self) {
2379 self.index.clear();
2380 log::debug!("Cleared index");
2381 }
2382
2383 pub fn reset(&mut self) {
2391 log::debug!("Resetting cache");
2392
2393 self.general.clear();
2394 self.books.clear();
2395 self.own_books.clear();
2396 self.quotes.clear();
2397 self.trades.clear();
2398 self.mark_xrates.clear();
2399 self.mark_prices.clear();
2400 self.index_prices.clear();
2401 self.funding_rates.clear();
2402 self.instrument_statuses.clear();
2403 self.instrument_closes.clear();
2404 self.bars.clear();
2405 self.accounts.clear();
2406 self.orders.clear();
2407 self.orders_dispatched.clear();
2408 self.order_lists.clear();
2409 self.positions.clear();
2410 self.position_snapshots.clear();
2411 self.position_snapshot_revisions.clear();
2412 self.greeks.clear();
2413 self.option_greeks.clear();
2414 self.yield_curves.clear();
2415 self.custom_data.clear();
2416
2417 if self.config.drop_instruments_on_reset {
2418 #[cfg(feature = "defi")]
2419 self.defi.clear_currencies();
2420 self.currencies.clear();
2421 self.instruments.clear();
2422 self.synthetics.clear();
2423 }
2424
2425 #[cfg(feature = "defi")]
2426 self.defi.clear_pools();
2427
2428 self.clear_index();
2429
2430 log::info!("Reset cache");
2431 }
2432
2433 pub fn dispose(&mut self) {
2437 self.reset();
2438
2439 if let Some(database) = &mut self.database
2440 && let Err(e) = database.close()
2441 {
2442 log::error!("Failed to close database during dispose: {e}");
2443 }
2444 }
2445
2446 pub fn flush_db(&mut self) -> anyhow::Result<()> {
2454 match &mut self.database {
2455 Some(database) => database.flush(),
2456 None => Ok(()),
2457 }
2458 }
2459
2460 pub fn add(&mut self, key: &str, value: Bytes) -> anyhow::Result<()> {
2471 check_valid_string_utf8(key, stringify!(key))?;
2473 check_predicate_false(value.is_empty(), stringify!(value))?;
2474
2475 log::debug!("Adding general {key}");
2476 self.general.insert(key.to_string(), value.clone());
2477
2478 if let Some(database) = &mut self.database {
2479 handle_persistence_result(
2480 format_args!("persist entry {key}"),
2481 database.add(key.to_string(), value),
2482 )?;
2483 }
2484 Ok(())
2485 }
2486
2487 pub fn add_order_book(&mut self, book: OrderBook) -> anyhow::Result<()> {
2495 log::debug!("Adding `OrderBook` {}", book.instrument_id);
2496
2497 if self.config.save_market_data
2498 && let Some(database) = &mut self.database
2499 {
2500 handle_persistence_result(
2501 format_args!("persist order book {}", book.instrument_id),
2502 database.add_order_book(&book),
2503 )?;
2504 }
2505
2506 self.books.insert(book.instrument_id, book);
2507 Ok(())
2508 }
2509
2510 #[expect(
2514 clippy::missing_errors_doc,
2515 reason = "infallible operation retains its existing public signature"
2516 )]
2517 pub fn add_own_order_book(&mut self, own_book: OwnOrderBook) -> anyhow::Result<()> {
2518 log::debug!("Adding `OwnOrderBook` {}", own_book.instrument_id);
2519
2520 self.own_books.insert(own_book.instrument_id, own_book);
2521 Ok(())
2522 }
2523
2524 #[expect(
2528 clippy::missing_errors_doc,
2529 reason = "infallible operation retains its existing public signature"
2530 )]
2531 pub fn add_mark_price(&mut self, mark_price: MarkPriceUpdate) -> anyhow::Result<()> {
2532 log::debug!("Adding `MarkPriceUpdate` for {}", mark_price.instrument_id);
2533
2534 if self.config.save_market_data {
2535 }
2537
2538 let mark_prices_deque = self
2539 .mark_prices
2540 .entry(mark_price.instrument_id)
2541 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2542 mark_prices_deque.push_front(mark_price);
2543 Ok(())
2544 }
2545
2546 #[expect(
2550 clippy::missing_errors_doc,
2551 reason = "infallible operation retains its existing public signature"
2552 )]
2553 pub fn add_index_price(&mut self, index_price: IndexPriceUpdate) -> anyhow::Result<()> {
2554 log::debug!(
2555 "Adding `IndexPriceUpdate` for {}",
2556 index_price.instrument_id
2557 );
2558
2559 if self.config.save_market_data {
2560 }
2562
2563 let index_prices_deque = self
2564 .index_prices
2565 .entry(index_price.instrument_id)
2566 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2567 index_prices_deque.push_front(index_price);
2568 Ok(())
2569 }
2570
2571 #[expect(
2575 clippy::missing_errors_doc,
2576 reason = "infallible operation retains its existing public signature"
2577 )]
2578 pub fn add_funding_rate(&mut self, funding_rate: FundingRateUpdate) -> anyhow::Result<()> {
2579 log::debug!(
2580 "Adding `FundingRateUpdate` for {}",
2581 funding_rate.instrument_id
2582 );
2583
2584 if self.config.save_market_data {
2585 }
2587
2588 let funding_rates_deque = self
2589 .funding_rates
2590 .entry(funding_rate.instrument_id)
2591 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2592 funding_rates_deque.push_front(funding_rate);
2593 Ok(())
2594 }
2595
2596 pub fn add_funding_rates(&mut self, funding_rates: &[FundingRateUpdate]) -> anyhow::Result<()> {
2604 check_slice_not_empty(funding_rates, stringify!(funding_rates))?;
2605
2606 log::debug!("Adding `FundingRateUpdate`[{}]", funding_rates.len());
2607
2608 if self.config.save_market_data
2609 && let Some(database) = &mut self.database
2610 {
2611 for funding_rate in funding_rates {
2612 handle_persistence_result(
2613 format_args!("persist funding rate {}", funding_rate.instrument_id),
2614 database.add_funding_rate(funding_rate),
2615 )?;
2616 }
2617 }
2618
2619 for funding_rate in funding_rates {
2620 let funding_rate_deque = self
2621 .funding_rates
2622 .entry(funding_rate.instrument_id)
2623 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2624 funding_rate_deque.push_front(*funding_rate);
2625 }
2626 Ok(())
2627 }
2628
2629 #[expect(
2633 clippy::missing_errors_doc,
2634 reason = "infallible operation retains its existing public signature"
2635 )]
2636 pub fn add_instrument_status(&mut self, status: InstrumentStatus) -> anyhow::Result<()> {
2637 log::debug!("Adding `InstrumentStatus` for {}", status.instrument_id);
2638
2639 if self.config.save_market_data {
2640 }
2642
2643 let statuses_deque = self
2644 .instrument_statuses
2645 .entry(status.instrument_id)
2646 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2647 statuses_deque.push_front(status);
2648 Ok(())
2649 }
2650
2651 pub fn add_instrument_close(&mut self, close: InstrumentClose) -> anyhow::Result<()> {
2661 log::debug!("Adding `InstrumentClose` for {}", close.instrument_id);
2662
2663 if let Some(database) = &self.database {
2664 handle_persistence_result(
2665 format_args!("persist instrument close {}", close.instrument_id),
2666 database.add_instrument_close(&close),
2667 )?;
2668 }
2669
2670 self.instrument_closes.insert(close.instrument_id, close);
2671 Ok(())
2672 }
2673
2674 pub fn add_quote(&mut self, quote: QuoteTick) -> anyhow::Result<()> {
2682 log::debug!("Adding `QuoteTick` {}", quote.instrument_id);
2683
2684 if self.config.save_market_data
2685 && let Some(database) = &mut self.database
2686 {
2687 handle_persistence_result(
2688 format_args!("persist quote {}", quote.instrument_id),
2689 database.add_quote("e),
2690 )?;
2691 }
2692
2693 let quotes_deque = self
2694 .quotes
2695 .entry(quote.instrument_id)
2696 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2697 quotes_deque.push_front(quote);
2698 Ok(())
2699 }
2700
2701 pub fn add_quotes(&mut self, quotes: &[QuoteTick]) -> anyhow::Result<()> {
2709 check_slice_not_empty(quotes, stringify!(quotes))?;
2710
2711 log::debug!("Adding `QuoteTick`[{}]", quotes.len());
2712
2713 if self.config.save_market_data
2714 && let Some(database) = &mut self.database
2715 {
2716 for quote in quotes {
2717 handle_persistence_result(
2718 format_args!("persist quote {}", quote.instrument_id),
2719 database.add_quote(quote),
2720 )?;
2721 }
2722 }
2723
2724 for quote in quotes {
2725 let quotes_deque = self
2726 .quotes
2727 .entry(quote.instrument_id)
2728 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2729 quotes_deque.push_front(*quote);
2730 }
2731 Ok(())
2732 }
2733
2734 pub fn add_trade(&mut self, trade: TradeTick) -> anyhow::Result<()> {
2742 log::debug!("Adding `TradeTick` {}", trade.instrument_id);
2743
2744 if self.config.save_market_data
2745 && let Some(database) = &mut self.database
2746 {
2747 handle_persistence_result(
2748 format_args!("persist trade {}", trade.instrument_id),
2749 database.add_trade(&trade),
2750 )?;
2751 }
2752
2753 let trades_deque = self
2754 .trades
2755 .entry(trade.instrument_id)
2756 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2757 trades_deque.push_front(trade);
2758 Ok(())
2759 }
2760
2761 pub fn add_trades(&mut self, trades: &[TradeTick]) -> anyhow::Result<()> {
2769 check_slice_not_empty(trades, stringify!(trades))?;
2770
2771 log::debug!("Adding `TradeTick`[{}]", trades.len());
2772
2773 if self.config.save_market_data
2774 && let Some(database) = &mut self.database
2775 {
2776 for trade in trades {
2777 handle_persistence_result(
2778 format_args!("persist trade {}", trade.instrument_id),
2779 database.add_trade(trade),
2780 )?;
2781 }
2782 }
2783
2784 for trade in trades {
2785 let trades_deque = self
2786 .trades
2787 .entry(trade.instrument_id)
2788 .or_insert_with(|| BoundedVecDeque::new(self.config.data_capacity));
2789 trades_deque.push_front(*trade);
2790 }
2791 Ok(())
2792 }
2793
2794 pub fn add_bar(&mut self, bar: Bar) -> anyhow::Result<()> {
2805 log::debug!("Adding `Bar` {}", bar.bar_type);
2806
2807 if self.config.save_market_data
2808 && let Some(database) = &mut self.database
2809 {
2810 handle_persistence_result(
2811 format_args!("persist bar {}", bar.bar_type),
2812 database.add_bar(&bar),
2813 )?;
2814 }
2815
2816 let bars = self
2817 .bars
2818 .entry(bar.bar_type)
2819 .or_insert_with(|| BoundedVecDeque::new(self.config.bar_capacity));
2820 insert_bar(bars, bar);
2821 Ok(())
2822 }
2823
2824 pub fn add_bars(&mut self, bars: &[Bar]) -> anyhow::Result<()> {
2832 check_slice_not_empty(bars, stringify!(bars))?;
2833
2834 log::debug!("Adding `Bar`[{}]", bars.len());
2835
2836 if self.config.save_market_data
2837 && let Some(database) = &mut self.database
2838 {
2839 for bar in bars {
2840 handle_persistence_result(
2841 format_args!("persist bar {}", bar.bar_type),
2842 database.add_bar(bar),
2843 )?;
2844 }
2845 }
2846
2847 for bar in bars {
2848 let bars_deque = self
2849 .bars
2850 .entry(bar.bar_type)
2851 .or_insert_with(|| BoundedVecDeque::new(self.config.bar_capacity));
2852 insert_bar(bars_deque, *bar);
2853 }
2854 Ok(())
2855 }
2856
2857 pub fn add_bar_historical(&mut self, bar: Bar) -> anyhow::Result<()> {
2868 log::debug!("Adding historical `Bar` {}", bar.bar_type);
2869
2870 if self.config.save_market_data
2871 && let Some(database) = &mut self.database
2872 {
2873 handle_persistence_result(
2874 format_args!("persist bar {}", bar.bar_type),
2875 database.add_bar(&bar),
2876 )?;
2877 }
2878
2879 let bars = self
2880 .bars
2881 .entry(bar.bar_type)
2882 .or_insert_with(|| BoundedVecDeque::new(self.config.bar_capacity));
2883 insert_bar_historical(bars, bar);
2884 Ok(())
2885 }
2886
2887 pub fn add_custom_data(&mut self, data: CustomData) {
2892 if let Some(history) = self.custom_data.get_mut(&data.data_type) {
2893 history.push_front(data);
2894 } else {
2895 let data_type = data.data_type.clone();
2896 let mut history = BoundedVecDeque::new(self.config.data_capacity);
2897 history.push_front(data);
2898 self.custom_data.insert(data_type, history);
2899 }
2900 }
2901
2902 pub fn add_greeks(&mut self, greeks: GreeksData) -> anyhow::Result<()> {
2910 log::debug!("Adding `GreeksData` {}", greeks.instrument_id);
2911
2912 if self.config.save_market_data
2913 && let Some(database) = &mut self.database
2914 {
2915 handle_persistence_result(
2916 format_args!("persist Greeks {}", greeks.instrument_id),
2917 database.add_greeks(&greeks),
2918 )?;
2919 }
2920
2921 self.greeks.insert(greeks.instrument_id, greeks);
2922 Ok(())
2923 }
2924
2925 pub fn greeks(&self, instrument_id: &InstrumentId) -> Option<GreeksData> {
2927 self.greeks.get(instrument_id).cloned()
2928 }
2929
2930 pub fn add_option_greeks(&mut self, greeks: OptionGreeks) {
2932 log::debug!("Adding `OptionGreeks` {}", greeks.instrument_id);
2933 self.option_greeks.insert(greeks.instrument_id, greeks);
2934 }
2935
2936 #[must_use]
2938 pub fn option_greeks(&self, instrument_id: &InstrumentId) -> Option<&OptionGreeks> {
2939 self.option_greeks.get(instrument_id)
2940 }
2941
2942 pub fn add_yield_curve(&mut self, yield_curve: YieldCurve) -> anyhow::Result<()> {
2952 yield_curve.validate()?;
2953
2954 log::debug!("Adding `YieldCurve` {}", yield_curve.curve_name);
2955
2956 if self.config.save_market_data
2957 && let Some(database) = &mut self.database
2958 {
2959 handle_persistence_result(
2960 format_args!("persist yield curve {}", yield_curve.curve_name),
2961 database.add_yield_curve(&yield_curve),
2962 )?;
2963 }
2964
2965 self.yield_curves
2966 .insert(yield_curve.curve_name.clone(), yield_curve);
2967 Ok(())
2968 }
2969
2970 pub fn yield_curve(&self, key: &str) -> Option<Box<dyn Fn(f64) -> f64>> {
2972 self.yield_curves.get(key).map(|curve| {
2973 let curve_clone = curve.clone();
2974 Box::new(move |expiry_in_years: f64| curve_clone.get_rate(expiry_in_years))
2975 as Box<dyn Fn(f64) -> f64>
2976 })
2977 }
2978
2979 pub fn add_currency(&mut self, currency: Currency) -> anyhow::Result<()> {
2988 #[cfg(feature = "defi")]
2989 let token = nautilus_model::defi::currency::check(currency)?.is_some();
2990 #[cfg(feature = "defi")]
2991 if token {
2992 if let Some(existing) = self.currencies.get(¤cy.code) {
2993 if !self.defi.contains_currency(¤cy.code) {
2994 anyhow::bail!("Legacy currency occupies token code {}", currency.code);
2995 }
2996
2997 nautilus_model::defi::currency::check(*existing)?;
2998 }
2999
3000 Currency::register(currency, false)?;
3001 }
3002
3003 if self.currencies.contains_key(¤cy.code) {
3004 return Ok(());
3005 }
3006 log::debug!("Adding `Currency` {}", currency.code);
3007
3008 if let Some(database) = &mut self.database {
3009 handle_persistence_result(
3010 format_args!("persist currency {}", currency.code),
3011 database.add_currency(¤cy),
3012 )?;
3013 }
3014
3015 self.currencies.insert(currency.code, currency);
3016
3017 #[cfg(feature = "defi")]
3018 if token {
3019 self.defi.add_currency(currency.code);
3020 }
3021
3022 Ok(())
3023 }
3024
3025 pub fn add_instrument(&mut self, instrument: InstrumentAny) -> anyhow::Result<()> {
3034 log::debug!("Adding `Instrument` {}", instrument.id());
3035
3036 #[cfg(feature = "defi")]
3037 let migration = self.check_instrument_migration(&instrument)?;
3038
3039 if let Some(base_currency) = instrument.base_currency() {
3041 self.add_currency(base_currency)?;
3042 }
3043 self.add_currency(instrument.quote_currency())?;
3044 self.add_currency(instrument.settlement_currency())?;
3045
3046 if let Some(database) = &mut self.database {
3047 #[cfg(feature = "defi")]
3048 if let Some(migration) = migration {
3049 handle_persistence_result(
3050 format_args!("persist instrument {}", instrument.id()),
3051 database.add_defi_instrument(&instrument, migration),
3052 )?;
3053 } else {
3054 handle_persistence_result(
3055 format_args!("persist instrument {}", instrument.id()),
3056 database.add_instrument(&instrument),
3057 )?;
3058 }
3059
3060 #[cfg(not(feature = "defi"))]
3061 handle_persistence_result(
3062 format_args!("persist instrument {}", instrument.id()),
3063 database.add_instrument(&instrument),
3064 )?;
3065 }
3066
3067 self.instruments.insert(instrument.id(), instrument);
3068 Ok(())
3069 }
3070
3071 pub fn add_synthetic(&mut self, synthetic: SyntheticInstrument) -> anyhow::Result<()> {
3079 log::debug!("Adding `SyntheticInstrument` {}", synthetic.id);
3080
3081 if let Some(database) = &mut self.database {
3082 handle_persistence_result(
3083 format_args!("persist synthetic {}", synthetic.id),
3084 database.add_synthetic(&synthetic),
3085 )?;
3086 }
3087
3088 self.synthetics.insert(synthetic.id, synthetic);
3089 Ok(())
3090 }
3091
3092 fn state_currencies(state: &AccountState) -> impl Iterator<Item = Currency> + '_ {
3094 state
3095 .balances
3096 .iter()
3097 .map(|balance| balance.currency)
3098 .chain(state.margins.iter().map(|margin| margin.currency))
3099 .chain(state.base_currency)
3100 }
3101
3102 fn add_account_currencies(&mut self, account: &AccountAny) -> anyhow::Result<()> {
3109 let Some(state) = account.last_event() else {
3110 return Ok(());
3111 };
3112
3113 for currency in Self::state_currencies(&state) {
3114 self.add_currency(currency)?;
3115 }
3116 Ok(())
3117 }
3118
3119 pub fn add_account(&mut self, account: AccountAny) -> anyhow::Result<()> {
3128 log::debug!("Adding `Account` {}", account.id());
3129
3130 self.add_account_currencies(&account)?;
3131
3132 if let Some(database) = &mut self.database {
3133 handle_persistence_result(
3134 format_args!("persist account {}", account.id()),
3135 database.add_account(&account),
3136 )?;
3137 }
3138
3139 let account_id = account.id();
3140 self.accounts.insert(account_id, SharedCell::new(account));
3141 self.index.add_venue_account(account_id);
3142 Ok(())
3143 }
3144
3145 pub fn add_venue_order_id(
3154 &mut self,
3155 client_order_id: &ClientOrderId,
3156 venue_order_id: &VenueOrderId,
3157 overwrite: bool,
3158 ) -> anyhow::Result<()> {
3159 self.validate_venue_order_id_claim(client_order_id, venue_order_id, overwrite)?;
3160
3161 self.index
3162 .client_order_ids
3163 .insert(*client_order_id, *venue_order_id);
3164 self.index
3165 .venue_order_ids
3166 .insert(*venue_order_id, *client_order_id);
3167
3168 Ok(())
3169 }
3170
3171 pub fn index_venue_order_id(
3182 &mut self,
3183 client_order_id: &ClientOrderId,
3184 venue_order_id: &VenueOrderId,
3185 ) -> anyhow::Result<()> {
3186 self.validate_venue_order_id_ownership(client_order_id, venue_order_id)?;
3187
3188 self.index
3189 .venue_order_ids
3190 .insert(*venue_order_id, *client_order_id);
3191 self.index
3192 .client_order_ids
3193 .entry(*client_order_id)
3194 .or_insert(*venue_order_id);
3195
3196 Ok(())
3197 }
3198
3199 fn validate_venue_order_id_claim(
3200 &self,
3201 client_order_id: &ClientOrderId,
3202 venue_order_id: &VenueOrderId,
3203 overwrite: bool,
3204 ) -> anyhow::Result<()> {
3205 self.validate_venue_order_id_ownership(client_order_id, venue_order_id)?;
3206
3207 if let Some(existing_venue_order_id) = self.index.client_order_ids.get(client_order_id)
3208 && !overwrite
3209 && existing_venue_order_id != venue_order_id
3210 {
3211 anyhow::bail!(
3212 "Existing {existing_venue_order_id} for {client_order_id}
3213 did not match the given {venue_order_id}.
3214 If you are writing a test then try a different `venue_order_id`,
3215 otherwise this is probably a bug."
3216 );
3217 }
3218
3219 Ok(())
3220 }
3221
3222 fn validate_venue_order_id_ownership(
3223 &self,
3224 client_order_id: &ClientOrderId,
3225 venue_order_id: &VenueOrderId,
3226 ) -> anyhow::Result<()> {
3227 if let Some(existing_client_order_id) = self.index.venue_order_ids.get(venue_order_id)
3228 && existing_client_order_id != client_order_id
3229 {
3230 return Err(VenueOrderIdOwnershipError {
3231 venue_order_id: *venue_order_id,
3232 existing_client_order_id: *existing_client_order_id,
3233 claimant_client_order_id: *client_order_id,
3234 }
3235 .into());
3236 }
3237
3238 Ok(())
3239 }
3240
3241 pub fn add_order(
3256 &mut self,
3257 order: OrderAny,
3258 position_id: Option<PositionId>,
3259 client_id: Option<ClientId>,
3260 replace_existing: bool,
3261 ) -> anyhow::Result<()> {
3262 let instrument_id = order.instrument_id();
3263 let venue = instrument_id.venue;
3264 let client_order_id = order.client_order_id();
3265 let strategy_id = order.strategy_id();
3266 let exec_algorithm_id = order.exec_algorithm_id();
3267 let exec_spawn_id = order.exec_spawn_id();
3268
3269 if !replace_existing {
3270 check_key_not_in_map(
3271 &client_order_id,
3272 &self.orders,
3273 stringify!(client_order_id),
3274 stringify!(orders),
3275 )?;
3276 }
3277
3278 log::debug!("Adding {order:?}");
3279
3280 let old_order_cell = self.orders.get(&client_order_id).cloned();
3281 let replacing = old_order_cell.is_some();
3282 if let Some(old_order_cell) = &old_order_cell {
3283 self.reindex_replaced_order(old_order_cell, &order, position_id)?;
3284 }
3285
3286 self.index.orders.insert(client_order_id);
3287
3288 if order.is_active_local() {
3289 self.index.orders_active_local.insert(client_order_id);
3290 }
3291
3292 if order.emulation_trigger().is_some() && (!replacing || !order.is_closed()) {
3293 self.index.orders_emulated.insert(client_order_id);
3294 }
3295
3296 self.index
3297 .order_strategy
3298 .insert(client_order_id, strategy_id);
3299 self.index.strategies.insert(strategy_id);
3300
3301 self.index
3303 .venue_orders
3304 .entry(venue)
3305 .or_default()
3306 .insert(client_order_id);
3307
3308 self.index
3310 .instrument_orders
3311 .entry(instrument_id)
3312 .or_default()
3313 .insert(client_order_id);
3314
3315 self.index
3317 .strategy_orders
3318 .entry(strategy_id)
3319 .or_default()
3320 .insert(client_order_id);
3321
3322 if let Some(account_id) = order.account_id() {
3324 self.index
3325 .account_orders
3326 .entry(account_id)
3327 .or_default()
3328 .insert(client_order_id);
3329 }
3330
3331 if let Some(exec_algorithm_id) = exec_algorithm_id {
3333 self.index.exec_algorithms.insert(exec_algorithm_id);
3334
3335 self.index
3336 .exec_algorithm_orders
3337 .entry(exec_algorithm_id)
3338 .or_default()
3339 .insert(client_order_id);
3340 }
3341
3342 if let Some(exec_spawn_id) = exec_spawn_id {
3344 self.index
3345 .exec_spawn_orders
3346 .entry(exec_spawn_id)
3347 .or_default()
3348 .insert(client_order_id);
3349 }
3350
3351 if let Some(position_id) = position_id {
3353 self.index_position_id_in_memory(&position_id, &venue, &client_order_id, &strategy_id);
3354 }
3355
3356 if let Some(client_id) = client_id {
3358 self.index.order_client.insert(client_order_id, client_id);
3359 log::debug!("Indexed {client_id:?}");
3360 }
3361
3362 let order_cell = if let Some(order_cell) = old_order_cell {
3365 *order_cell.borrow_mut() = order;
3366 order_cell
3367 } else {
3368 let order_cell = SharedCell::new(order);
3369 self.orders.insert(client_order_id, order_cell.clone());
3370 order_cell
3371 };
3372
3373 if let Some(position_id) = position_id {
3374 self.persist_position_id(&position_id, &client_order_id)?;
3375 }
3376
3377 if let Some(database) = &mut self.database {
3378 handle_persistence_result(
3379 format_args!("persist order {client_order_id}"),
3380 database.add_order(&order_cell.borrow(), client_id),
3381 )?;
3382 }
3387
3388 Ok(())
3389 }
3390
3391 fn reindex_replaced_order(
3392 &mut self,
3393 old_order_cell: &SharedCell<OrderAny>,
3394 order: &OrderAny,
3395 position_id: Option<PositionId>,
3396 ) -> anyhow::Result<()> {
3397 let client_order_id = order.client_order_id();
3398 let current_venue_order_id = order.venue_order_id();
3399 let venue_order_ids = order.venue_order_ids();
3400
3401 if let Some(venue_order_id) = current_venue_order_id {
3402 self.validate_venue_order_id_ownership(&client_order_id, &venue_order_id)?;
3403 }
3404
3405 for venue_order_id in &venue_order_ids {
3406 if current_venue_order_id == Some(**venue_order_id) {
3407 continue;
3408 }
3409
3410 self.validate_venue_order_id_ownership(&client_order_id, venue_order_id)?;
3411 }
3412
3413 {
3414 let old_order = old_order_cell.borrow();
3415
3416 if let Some(position_id) = position_id {
3417 Self::remove_replaced_order_position_memberships(
3418 &mut self.index,
3419 &self.positions,
3420 &old_order,
3421 position_id,
3422 );
3423 }
3424
3425 Self::remove_replaced_order_filter_memberships(&mut self.index, &old_order, order);
3426 }
3427
3428 self.index.orders_active_local.remove(&client_order_id);
3429 self.index.orders_open.remove(&client_order_id);
3430 self.index.orders_closed.remove(&client_order_id);
3431 self.index.orders_emulated.remove(&client_order_id);
3432 self.index.orders_inflight.remove(&client_order_id);
3433 if order.is_open() {
3434 self.index.orders_open.insert(client_order_id);
3435 }
3436
3437 if order.is_closed() {
3438 self.index.orders_pending_cancel.remove(&client_order_id);
3439 self.index.orders_closed.insert(client_order_id);
3440 }
3441
3442 if order.is_inflight() {
3443 self.index.orders_inflight.insert(client_order_id);
3444 }
3445
3446 self.index.client_order_ids.remove(&client_order_id);
3447
3448 if let Some(venue_order_id) = current_venue_order_id {
3449 self.index
3450 .client_order_ids
3451 .insert(client_order_id, venue_order_id);
3452 self.index
3453 .venue_order_ids
3454 .insert(venue_order_id, client_order_id);
3455 }
3456
3457 for venue_order_id in venue_order_ids {
3458 if current_venue_order_id != Some(*venue_order_id) {
3459 self.index
3460 .venue_order_ids
3461 .insert(*venue_order_id, client_order_id);
3462 }
3463 }
3464
3465 Ok(())
3466 }
3467
3468 fn remove_replaced_order_filter_memberships(
3469 index: &mut CacheIndex,
3470 old_order: &OrderAny,
3471 replacement: &OrderAny,
3472 ) {
3473 let client_order_id = old_order.client_order_id();
3474 let old_instrument_id = old_order.instrument_id();
3475 let new_instrument_id = replacement.instrument_id();
3476 let old_venue = old_instrument_id.venue;
3477 let old_strategy_id = old_order.strategy_id();
3478
3479 if old_venue != new_instrument_id.venue
3480 && Self::remove_from_bucket(&mut index.venue_orders, &old_venue, &client_order_id)
3481 {
3482 index.venue_orders.remove(&old_venue);
3483 }
3484
3485 if old_instrument_id != new_instrument_id {
3486 let became_empty = Self::remove_from_bucket(
3487 &mut index.instrument_orders,
3488 &old_instrument_id,
3489 &client_order_id,
3490 );
3491 let has_positions = index
3492 .instrument_positions
3493 .get(&old_instrument_id)
3494 .is_some_and(|positions| !positions.is_empty());
3495
3496 if became_empty && !has_positions {
3497 index.instrument_orders.remove(&old_instrument_id);
3498 }
3499 }
3500
3501 if old_strategy_id != replacement.strategy_id() {
3502 let became_empty = Self::remove_from_bucket(
3503 &mut index.strategy_orders,
3504 &old_strategy_id,
3505 &client_order_id,
3506 );
3507 let has_positions = index
3508 .strategy_positions
3509 .get(&old_strategy_id)
3510 .is_some_and(|positions| !positions.is_empty());
3511
3512 if became_empty && !has_positions {
3513 index.strategy_orders.remove(&old_strategy_id);
3514 index.strategies.remove(&old_strategy_id);
3515 }
3516 }
3517
3518 if let Some(account_id) = old_order.account_id()
3519 && Some(account_id) != replacement.account_id()
3520 && Self::remove_from_bucket(&mut index.account_orders, &account_id, &client_order_id)
3521 {
3522 index.account_orders.remove(&account_id);
3523 }
3524
3525 if let Some(exec_algorithm_id) = old_order.exec_algorithm_id()
3526 && Some(exec_algorithm_id) != replacement.exec_algorithm_id()
3527 && Self::remove_from_bucket(
3528 &mut index.exec_algorithm_orders,
3529 &exec_algorithm_id,
3530 &client_order_id,
3531 )
3532 {
3533 index.exec_algorithm_orders.remove(&exec_algorithm_id);
3534 index.exec_algorithms.remove(&exec_algorithm_id);
3535 }
3536
3537 if let Some(exec_spawn_id) = old_order.exec_spawn_id()
3538 && Some(exec_spawn_id) != replacement.exec_spawn_id()
3539 && Self::remove_from_bucket(
3540 &mut index.exec_spawn_orders,
3541 &exec_spawn_id,
3542 &client_order_id,
3543 )
3544 {
3545 index.exec_spawn_orders.remove(&exec_spawn_id);
3546 }
3547 }
3548
3549 fn remove_replaced_order_position_memberships(
3550 index: &mut CacheIndex,
3551 positions: &AHashMap<PositionId, SharedCell<Position>>,
3552 old_order: &OrderAny,
3553 new_position_id: PositionId,
3554 ) {
3555 let client_order_id = old_order.client_order_id();
3556 let indexed_position_id = index.order_position.get(&client_order_id).copied();
3557 let mut removed_position_id = None;
3558 for old_position_id in [indexed_position_id, old_order.position_id()]
3559 .into_iter()
3560 .flatten()
3561 {
3562 if old_position_id == new_position_id || removed_position_id == Some(old_position_id) {
3563 continue;
3564 }
3565
3566 removed_position_id = Some(old_position_id);
3567 Self::remove_replaced_order_position_membership(
3568 index,
3569 positions,
3570 client_order_id,
3571 old_position_id,
3572 old_order.instrument_id().venue,
3573 );
3574 }
3575 }
3576
3577 fn remove_replaced_order_position_membership(
3578 index: &mut CacheIndex,
3579 positions: &AHashMap<PositionId, SharedCell<Position>>,
3580 client_order_id: ClientOrderId,
3581 old_position_id: PositionId,
3582 old_venue: Venue,
3583 ) {
3584 let has_other_orders = if let Some(orders) = index.position_orders.get_mut(&old_position_id)
3585 {
3586 orders.remove(&client_order_id);
3587 !orders.is_empty()
3588 } else {
3589 index
3590 .order_position
3591 .iter()
3592 .any(|(candidate_id, candidate)| {
3593 *candidate_id != client_order_id && *candidate == old_position_id
3594 })
3595 };
3596
3597 if positions.contains_key(&old_position_id) || has_other_orders {
3598 return;
3599 }
3600
3601 index.position_orders.remove(&old_position_id);
3602 if let Some(strategy_id) = index.position_strategy.remove(&old_position_id)
3603 && Self::remove_from_bucket(
3604 &mut index.strategy_positions,
3605 &strategy_id,
3606 &old_position_id,
3607 )
3608 {
3609 index.strategy_positions.remove(&strategy_id);
3610 }
3611
3612 if Self::remove_from_bucket(&mut index.venue_positions, &old_venue, &old_position_id) {
3613 index.venue_positions.remove(&old_venue);
3614 }
3615 }
3616
3617 fn remove_from_bucket<K: Eq + std::hash::Hash, V: Eq + std::hash::Hash>(
3618 buckets: &mut AHashMap<K, AHashSet<V>>,
3619 key: &K,
3620 member: &V,
3621 ) -> bool {
3622 buckets.get_mut(key).is_some_and(|members| {
3623 members.remove(member);
3624 members.is_empty()
3625 })
3626 }
3627
3628 pub fn claim_order_clients(
3644 &mut self,
3645 claims: &[(ClientOrderId, ClientId)],
3646 ) -> anyhow::Result<()> {
3647 let mut requested = AHashMap::with_capacity(claims.len());
3648 let mut ordered_claims = Vec::with_capacity(claims.len());
3649
3650 for (client_order_id, client_id) in claims {
3651 if let Some(existing_client_id) = requested.get(client_order_id) {
3652 if existing_client_id != client_id {
3653 anyhow::bail!(
3654 "Conflicting execution client claims for {client_order_id}: \
3655 {existing_client_id} and {client_id}"
3656 );
3657 }
3658 continue;
3659 }
3660
3661 requested.insert(*client_order_id, *client_id);
3662 ordered_claims.push((*client_order_id, *client_id));
3663 }
3664
3665 let mut pending_claims = Vec::with_capacity(ordered_claims.len());
3666 for (client_order_id, client_id) in ordered_claims {
3667 if !self.orders.contains_key(&client_order_id) {
3668 return Err(OrderLookupError::not_found(client_order_id).into());
3669 }
3670
3671 match self.index.order_client.get(&client_order_id) {
3672 Some(existing_client_id) if *existing_client_id == client_id => {}
3673 Some(existing_client_id) => {
3674 anyhow::bail!(
3675 "Order {client_order_id} is already claimed by execution client \
3676 {existing_client_id} and cannot be claimed by {client_id}"
3677 );
3678 }
3679 None => pending_claims.push((client_order_id, client_id)),
3680 }
3681 }
3682
3683 if pending_claims.is_empty() {
3684 return Ok(());
3685 }
3686
3687 if let Some(database) = &self.database {
3688 handle_persistence_result(
3689 "persist execution client claims",
3690 database.index_order_clients(&pending_claims),
3691 )?;
3692 }
3693
3694 for (client_order_id, client_id) in pending_claims {
3695 self.index.order_client.insert(client_order_id, client_id);
3696 log::debug!("Claimed {client_order_id} for execution client {client_id}");
3697 }
3698
3699 Ok(())
3700 }
3701
3702 pub fn add_order_list(&mut self, order_list: OrderList) -> anyhow::Result<()> {
3708 let order_list_id = order_list.id;
3709 check_key_not_in_map(
3710 &order_list_id,
3711 &self.order_lists,
3712 stringify!(order_list_id),
3713 stringify!(order_lists),
3714 )?;
3715
3716 log::debug!("Adding {order_list}");
3717 self.order_lists.insert(order_list_id, order_list);
3718 Ok(())
3719 }
3720
3721 pub fn add_position_id(
3732 &mut self,
3733 position_id: &PositionId,
3734 venue: &Venue,
3735 client_order_id: &ClientOrderId,
3736 strategy_id: &StrategyId,
3737 ) -> anyhow::Result<()> {
3738 self.index_position_id_in_memory(position_id, venue, client_order_id, strategy_id);
3739 self.persist_position_id(position_id, client_order_id)
3740 }
3741
3742 fn index_position_id_in_memory(
3743 &mut self,
3744 position_id: &PositionId,
3745 venue: &Venue,
3746 client_order_id: &ClientOrderId,
3747 strategy_id: &StrategyId,
3748 ) {
3749 self.index
3750 .order_position
3751 .insert(*client_order_id, *position_id);
3752 self.index_position(position_id, venue, strategy_id);
3753 self.index
3754 .position_orders
3755 .entry(*position_id)
3756 .or_default()
3757 .insert(*client_order_id);
3758 }
3759
3760 fn persist_position_id(
3761 &mut self,
3762 position_id: &PositionId,
3763 client_order_id: &ClientOrderId,
3764 ) -> anyhow::Result<()> {
3765 if let Some(database) = &mut self.database {
3766 handle_persistence_result(
3767 format_args!("persist order position {client_order_id}"),
3768 database.index_order_position(*client_order_id, *position_id),
3769 )?;
3770 }
3771
3772 Ok(())
3773 }
3774
3775 fn index_position(
3776 &mut self,
3777 position_id: &PositionId,
3778 venue: &Venue,
3779 strategy_id: &StrategyId,
3780 ) {
3781 let strategy_id = self
3782 .positions
3783 .get(position_id)
3784 .map(|position| position.borrow().strategy_id)
3785 .filter(StrategyId::is_external)
3786 .unwrap_or(*strategy_id);
3787
3788 self.index
3790 .position_strategy
3791 .insert(*position_id, strategy_id);
3792
3793 self.index.position_orders.entry(*position_id).or_default();
3795
3796 self.index
3798 .strategy_positions
3799 .entry(strategy_id)
3800 .or_default()
3801 .insert(*position_id);
3802
3803 self.index
3805 .venue_positions
3806 .entry(*venue)
3807 .or_default()
3808 .insert(*position_id);
3809 }
3810
3811 fn assign_position_ids_to_contingencies(&mut self) {
3819 let mut assignments: Vec<(PositionId, ClientOrderId)> = Vec::new();
3820
3821 for parent_order_cell in self.orders.values() {
3822 let parent = parent_order_cell.borrow();
3823 if parent.contingency_type() != Some(ContingencyType::Oto) {
3824 continue;
3825 }
3826 let Some(parent_position_id) = parent.position_id() else {
3827 continue;
3828 };
3829 let Some(linked_order_ids) = parent.linked_order_ids() else {
3830 continue;
3831 };
3832
3833 for client_order_id in linked_order_ids {
3834 let Some(contingent_order_cell) = self.orders.get(client_order_id) else {
3835 log::error!("Contingency order {client_order_id} not found");
3836 continue;
3837 };
3838
3839 if contingent_order_cell.borrow().position_id().is_none() {
3840 assignments.push((parent_position_id, *client_order_id));
3841 }
3842 }
3843 }
3844
3845 for (position_id, client_order_id) in assignments {
3846 let Some((venue, strategy_id)) = self.orders.get(&client_order_id).map(|order_cell| {
3847 let mut contingent = order_cell.borrow_mut();
3848 contingent.set_position_id(Some(position_id));
3849 (contingent.instrument_id().venue, contingent.strategy_id())
3850 }) else {
3851 continue;
3852 };
3853
3854 if let Err(e) =
3856 self.add_position_id(&position_id, &venue, &client_order_id, &strategy_id)
3857 {
3858 log::error!("Failed to re-index {client_order_id} -> {position_id}: {e}");
3859 }
3860 }
3861 }
3862
3863 pub fn add_position(&mut self, position: &Position, oms_type: OmsType) -> anyhow::Result<()> {
3875 self.add_position_inner(position.clone(), oms_type, true, false)
3876 }
3877
3878 pub fn add_position_without_order(
3889 &mut self,
3890 position: &Position,
3891 oms_type: OmsType,
3892 ) -> anyhow::Result<()> {
3893 self.add_position_inner(position.clone(), oms_type, false, false)
3894 }
3895
3896 pub fn replace_position(
3912 &mut self,
3913 position: &Position,
3914 oms_type: OmsType,
3915 index_order: bool,
3916 carry_replay_state: bool,
3917 ) -> anyhow::Result<()> {
3918 self.add_position_inner(position.clone(), oms_type, index_order, carry_replay_state)
3919 }
3920
3921 fn add_position_inner(
3922 &mut self,
3923 mut position: Position,
3924 oms_type: OmsType,
3925 index_order: bool,
3926 carry_replay_state: bool,
3927 ) -> anyhow::Result<()> {
3928 let oms_type = resolve_position_oms(&position, oms_type);
3929
3930 let key = position_oms_key(position.id);
3935 check_valid_string_utf8(&key, stringify!(key))?;
3936 let value = Bytes::from(serde_json::to_vec(&oms_type)?);
3937 check_predicate_false(value.is_empty(), stringify!(value))?;
3938
3939 let position_id = position.id;
3940 let strategy_id = position.strategy_id;
3941 let instrument_id = position.instrument_id;
3942 let account_id = position.account_id;
3943 let opening_order_id = position.opening_order_id;
3944
3945 log::debug!("Adding {position}");
3946
3947 let position_cell = if let Some(position_cell) = self.positions.get(&position_id).cloned() {
3951 let mut prior = position_cell.borrow_mut();
3952 if carry_replay_state {
3953 position.transfer_replay_state_from(&mut prior);
3954 }
3955 *prior = position;
3956 drop(prior);
3957 position_cell
3958 } else {
3959 let position_cell = SharedCell::new(position);
3960 self.positions.insert(position_id, position_cell.clone());
3961 position_cell
3962 };
3963
3964 self.index.position_oms.insert(position_id, oms_type);
3965 self.index.positions.insert(position_id);
3966 self.refresh_position_indexes(&position_cell.borrow());
3967 self.index.strategies.insert(strategy_id);
3968 self.index.strategy_orders.entry(strategy_id).or_default();
3969
3970 if index_order {
3971 self.index_position_id_in_memory(
3972 &position_id,
3973 &instrument_id.venue,
3974 &opening_order_id,
3975 &strategy_id,
3976 );
3977 } else {
3978 self.index_position(&position_id, &instrument_id.venue, &strategy_id);
3979 }
3980
3981 let instrument_positions = self
3983 .index
3984 .instrument_positions
3985 .entry(instrument_id)
3986 .or_default();
3987 instrument_positions.insert(position_id);
3988 self.index
3989 .instrument_orders
3990 .entry(instrument_id)
3991 .or_default();
3992
3993 self.index
3995 .account_positions
3996 .entry(account_id)
3997 .or_default()
3998 .insert(position_id);
3999
4000 log::debug!("Adding general {key}");
4001 self.general.insert(key.clone(), value.clone());
4002
4003 if index_order {
4004 self.persist_position_id(&position_id, &opening_order_id)?;
4005 }
4006
4007 if let Some(database) = &mut self.database {
4008 handle_persistence_result(
4009 format_args!("persist position {position_id}"),
4010 database.add_position(&position_cell.borrow()),
4011 )?;
4012 handle_persistence_result(
4021 format_args!("persist OMS metadata for position {position_id}"),
4022 database.add(key, value),
4023 )?;
4024 }
4025
4026 Ok(())
4027 }
4028
4029 pub fn update_account(&mut self, account: &AccountAny) -> anyhow::Result<()> {
4041 let account_id = account.id();
4042 match self.accounts.get(&account_id) {
4043 Some(account_cell) => *account_cell.borrow_mut() = account.clone(),
4044 None => {
4045 self.accounts
4046 .insert(account_id, SharedCell::new(account.clone()));
4047 }
4048 }
4049
4050 self.add_account_currencies(account)?;
4051
4052 if let Some(database) = &mut self.database {
4053 handle_persistence_result(
4054 format_args!("persist account {account_id}"),
4055 database.update_account(account),
4056 )?;
4057 }
4058 Ok(())
4059 }
4060
4061 #[must_use]
4072 pub fn take_account(&mut self, account_id: &AccountId) -> Option<AccountAny> {
4073 let cell = self.accounts.remove(account_id)?;
4074 let rc: Rc<RefCell<AccountAny>> = cell.into();
4075
4076 match Rc::try_unwrap(rc) {
4077 Ok(cell) => Some(cell.into_inner()),
4078 Err(rc) => {
4079 log::error!(
4080 "Cannot move account {account_id} out of cache: account cell has an outstanding owner"
4081 );
4082 self.accounts.insert(*account_id, rc.into());
4083 None
4084 }
4085 }
4086 }
4087
4088 pub fn cache_account_owned(&mut self, account: AccountAny) {
4090 let account_id = account.id();
4091 self.index.add_venue_account(account_id);
4092 match self.accounts.get(&account_id) {
4093 Some(account_cell) => *account_cell.borrow_mut() = account,
4094 None => {
4095 self.accounts.insert(account_id, SharedCell::new(account));
4096 }
4097 }
4098 }
4099
4100 pub fn update_account_owned(&mut self, account: AccountAny) -> anyhow::Result<()> {
4109 let account_id = account.id();
4110 let currencies: Vec<Currency> = account
4112 .last_event()
4113 .map_or_default(|state| Self::state_currencies(&state).collect());
4114 self.cache_account_owned(account);
4115
4116 for currency in currencies {
4117 self.add_currency(currency)?;
4118 }
4119
4120 if let Some(database) = &mut self.database {
4121 let Some(account_cell) = self.accounts.get(&account_id) else {
4122 anyhow::bail!("Account {account_id} not found after cache update");
4123 };
4124
4125 handle_persistence_result(
4126 format_args!("persist account {account_id}"),
4127 database.update_account(&account_cell.borrow()),
4128 )?;
4129 }
4130 Ok(())
4131 }
4132
4133 pub fn update_account_state(&mut self, event: &AccountState) -> anyhow::Result<()> {
4146 let Some(cell) = self.accounts.get(&event.account_id) else {
4147 return self.add_account(AccountAny::from_events(std::slice::from_ref(event))?);
4148 };
4149
4150 cell.borrow_mut().apply(event.clone())?;
4152
4153 for currency in Self::state_currencies(event) {
4156 self.add_currency(currency)?;
4157 }
4158
4159 let Some(cell) = self.accounts.get(&event.account_id) else {
4160 anyhow::bail!("Account {} not found after apply", event.account_id);
4161 };
4162
4163 if let Some(database) = &mut self.database {
4164 handle_persistence_result(
4165 format_args!("persist account {}", event.account_id),
4166 database.update_account(&cell.borrow()),
4167 )?;
4168 }
4169 Ok(())
4170 }
4171
4172 pub fn replace_order(&mut self, order: &OrderAny) -> anyhow::Result<()> {
4184 let client_order_id = order.client_order_id();
4185 if let Some(venue_order_id) = order.venue_order_id() {
4186 self.validate_venue_order_id_ownership(&client_order_id, &venue_order_id)?;
4187 }
4188
4189 match self.orders.get(&client_order_id) {
4190 Some(order_cell) => *order_cell.borrow_mut() = order.clone(),
4193 None => {
4194 self.orders
4195 .insert(client_order_id, SharedCell::new(order.clone()));
4196 }
4197 }
4198
4199 self.refresh_order(order)
4200 }
4201
4202 pub fn update_order(&mut self, event: &OrderEventAny) -> anyhow::Result<OrderAny> {
4214 let event_client_order_id = event.client_order_id();
4215 let client_order_id = if self.order_exists(&event_client_order_id) {
4216 event_client_order_id
4217 } else if let Some(venue_order_id) = event.venue_order_id() {
4218 self.index
4219 .venue_order_ids
4220 .get(&venue_order_id)
4221 .copied()
4222 .ok_or(OrderError::NotFound(event_client_order_id))?
4223 } else {
4224 return Err(OrderError::NotFound(event_client_order_id).into());
4225 };
4226
4227 let order_cell = self
4228 .orders
4229 .get(&client_order_id)
4230 .cloned()
4231 .ok_or(OrderError::NotFound(client_order_id))?;
4232
4233 let mut snapshot = order_cell.borrow().clone();
4237 snapshot.apply(event.clone())?;
4238
4239 if let Some(venue_order_id) = snapshot.venue_order_id() {
4243 self.validate_venue_order_id_ownership(&client_order_id, &venue_order_id)?;
4244 }
4245
4246 *order_cell.borrow_mut() = snapshot.clone();
4247
4248 if matches!(event, OrderEventAny::FillVoided(_)) {
4249 self.reindex_hedging_position(client_order_id);
4250 }
4251
4252 if let Err(e) = self.refresh_order(&snapshot) {
4253 log::error!("Error updating order in cache: {e}");
4254 }
4255
4256 Ok(snapshot)
4257 }
4258
4259 fn refresh_order(&mut self, order: &OrderAny) -> anyhow::Result<()> {
4260 let client_order_id = order.client_order_id();
4261
4262 if let Some(venue_order_id) = order.venue_order_id() {
4265 let overwrite = matches!(order.last_event(), OrderEventAny::Updated(_));
4266 if let Err(e) = self.add_venue_order_id(&client_order_id, &venue_order_id, overwrite) {
4267 if e.is::<VenueOrderIdOwnershipError>() {
4268 return Err(e);
4269 }
4270 log::error!("Error indexing venue order ID in cache: {e}");
4271 }
4272 }
4273
4274 if order.is_active_local() {
4275 self.index.orders_active_local.insert(client_order_id);
4276 } else {
4277 self.index.orders_active_local.remove(&client_order_id);
4278 }
4279
4280 if order.is_inflight() {
4282 self.index.orders_inflight.insert(client_order_id);
4283 } else {
4284 self.index.orders_inflight.remove(&client_order_id);
4285 }
4286
4287 if order.is_open() {
4289 self.index.orders_closed.remove(&client_order_id);
4290 self.index.orders_open.insert(client_order_id);
4291 } else {
4292 self.index.orders_open.remove(&client_order_id);
4293 }
4294
4295 if order.is_closed() {
4296 self.index.orders_pending_cancel.remove(&client_order_id);
4297 self.index.orders_closed.insert(client_order_id);
4298 }
4299
4300 self.refresh_order_pending_cancel(order);
4301
4302 if order.emulation_trigger().is_some() && !order.is_closed() {
4304 self.index.orders_emulated.insert(client_order_id);
4305 } else {
4306 self.index.orders_emulated.remove(&client_order_id);
4307 }
4308
4309 if let Some(account_id) = order.account_id() {
4311 self.index
4312 .account_orders
4313 .entry(account_id)
4314 .or_default()
4315 .insert(client_order_id);
4316 }
4317
4318 if !self.own_books.is_empty() {
4320 let own_book = self.own_order_book(&order.instrument_id());
4321 if (own_book.is_some() && order.is_closed()) || should_handle_own_book_order(order) {
4322 self.update_own_order_book(order);
4323 }
4324 }
4325
4326 if let Some(database) = &mut self.database {
4327 handle_persistence_result(
4328 format_args!("persist order {}", order.client_order_id()),
4329 database.update_order(order.last_event()),
4330 )?;
4331 }
4336
4337 Ok(())
4338 }
4339
4340 fn refresh_order_pending_cancel(&mut self, order: &OrderAny) {
4341 if matches!(
4342 order.last_event(),
4343 OrderEventAny::CancelDenied(_) | OrderEventAny::CancelRejected(_)
4344 ) && !order.has_pending_cancel_command()
4345 {
4346 self.index
4347 .orders_pending_cancel
4348 .remove(&order.client_order_id());
4349 }
4350 }
4351
4352 pub fn update_order_pending_cancel_local(&mut self, order: &OrderAny) {
4354 self.index
4355 .orders_pending_cancel
4356 .insert(order.client_order_id());
4357 }
4358
4359 pub fn update_position(&mut self, position: &Position) -> anyhow::Result<()> {
4371 let Some(position_cell) = self.positions.get(&position.id).cloned() else {
4372 anyhow::bail!("Cannot update position {}: not found in cache", position.id);
4373 };
4374
4375 self.refresh_position_indexes(position);
4376
4377 *position_cell.borrow_mut() = position.clone();
4378
4379 if let Some(database) = &mut self.database {
4380 handle_persistence_result(
4381 format_args!("persist position {}", position.id),
4382 database.update_position(position),
4383 )?;
4384 }
4389
4390 Ok(())
4391 }
4392
4393 pub fn update_position_from_fill(
4405 &mut self,
4406 position_id: PositionId,
4407 fill: &OrderFilled,
4408 ) -> anyhow::Result<Position> {
4409 let Some(position_cell) = self.positions.get(&position_id).cloned() else {
4410 anyhow::bail!("Cannot update position {position_id}: not found in cache");
4411 };
4412
4413 let mut resolved_fill;
4414 let fill = if fill.position_id.is_none() {
4415 resolved_fill = fill.clone();
4416 resolved_fill.position_id = Some(position_id);
4417 &resolved_fill
4418 } else {
4419 fill
4420 };
4421
4422 let position = {
4423 let mut position = position_cell.borrow_mut();
4424 position.try_apply(fill)?;
4425 position.clone_without_events()
4426 };
4427
4428 self.refresh_position_indexes(&position);
4429
4430 if let Some(database) = &mut self.database {
4431 handle_persistence_result(
4432 format_args!("persist position {position_id}"),
4433 database.update_position(&position_cell.borrow()),
4434 )?;
4435 }
4436
4437 Ok(position)
4438 }
4439
4440 pub fn update_position_from_adjustment(
4453 &mut self,
4454 position_id: PositionId,
4455 adjustment: PositionAdjusted,
4456 ) -> anyhow::Result<()> {
4457 let Some(position_cell) = self.positions.get(&position_id).cloned() else {
4458 anyhow::bail!("Cannot update position {position_id}: not found in cache");
4459 };
4460
4461 position_cell.borrow_mut().apply_adjustment(adjustment)?;
4462 self.refresh_position_indexes(&position_cell.borrow());
4463
4464 if let Some(database) = &mut self.database {
4465 handle_persistence_result(
4466 format_args!("persist position {position_id}"),
4467 database.update_position(&position_cell.borrow()),
4468 )?;
4469 }
4470
4471 Ok(())
4472 }
4473
4474 pub fn revert_position_adjustment(&mut self, prior: &Position) -> anyhow::Result<()> {
4486 let Some(position_cell) = self.positions.get(&prior.id).cloned() else {
4487 anyhow::bail!("Cannot revert position {}: not found in cache", prior.id);
4488 };
4489
4490 position_cell.borrow_mut().revert_last_adjustment(prior)?;
4491 self.refresh_position_indexes(&position_cell.borrow());
4492
4493 if let Some(database) = &mut self.database {
4494 handle_persistence_result(
4495 format_args!("persist position {}", prior.id),
4496 database.update_position(&position_cell.borrow()),
4497 )?;
4498 }
4499
4500 Ok(())
4501 }
4502
4503 pub fn update_position_from_instrument_close(
4515 &mut self,
4516 position_id: PositionId,
4517 close: InstrumentClose,
4518 ) -> anyhow::Result<Position> {
4519 let Some(position_cell) = self.positions.get(&position_id).cloned() else {
4520 anyhow::bail!("Cannot update position {position_id}: not found in cache");
4521 };
4522
4523 let position = {
4524 let mut position = position_cell.borrow_mut();
4525 position.apply_instrument_close(close)?;
4526 position.clone_without_events()
4527 };
4528
4529 self.refresh_position_indexes(&position);
4530
4531 if let Some(database) = &mut self.database {
4532 handle_persistence_result(
4533 format_args!("persist instrument close for position {position_id}"),
4534 database.update_position(&position_cell.borrow()),
4535 )?;
4536 }
4537
4538 Ok(position)
4539 }
4540
4541 fn refresh_position_indexes(&mut self, position: &Position) {
4542 if position.is_open() {
4543 self.index.positions_open.insert(position.id);
4544 self.index.positions_closed.remove(&position.id);
4545 } else {
4546 self.index.positions_closed.insert(position.id);
4547 self.index.positions_open.remove(&position.id);
4548 }
4549 }
4550
4551 #[must_use]
4553 pub fn oms_type(&self, position_id: &PositionId) -> Option<OmsType> {
4554 self.index.position_oms.get(position_id).copied()
4555 }
4556
4557 pub fn snapshot_order_state(&self, order: &OrderAny) -> anyhow::Result<()> {
4565 let Some(database) = &self.database else {
4566 log::warn!(
4567 "Cannot snapshot order state for {} (no database configured)",
4568 order.client_order_id()
4569 );
4570 return Ok(());
4571 };
4572
4573 handle_persistence_result(
4574 format_args!("snapshot order {}", order.client_order_id()),
4575 database.snapshot_order_state(order),
4576 )
4577 }
4578
4579 fn collect_order_filter_sources<'a>(
4590 &'a self,
4591 venue: Option<&Venue>,
4592 instrument_id: Option<&InstrumentId>,
4593 strategy_id: Option<&StrategyId>,
4594 account_id: Option<&AccountId>,
4595 ) -> FilterSources<'a, ClientOrderId> {
4596 let mut sources: Vec<&AHashSet<ClientOrderId>> = Vec::with_capacity(4);
4597
4598 if let Some(venue) = venue {
4599 match self.index.venue_orders.get(venue) {
4600 Some(set) => sources.push(set),
4601 None => return FilterSources::Empty,
4602 }
4603 }
4604
4605 if let Some(instrument_id) = instrument_id {
4606 match self.index.instrument_orders.get(instrument_id) {
4607 Some(set) => sources.push(set),
4608 None => return FilterSources::Empty,
4609 }
4610 }
4611
4612 if let Some(strategy_id) = strategy_id {
4613 match self.index.strategy_orders.get(strategy_id) {
4614 Some(set) => sources.push(set),
4615 None => return FilterSources::Empty,
4616 }
4617 }
4618
4619 if let Some(account_id) = account_id {
4620 match self.index.account_orders.get(account_id) {
4621 Some(set) => sources.push(set),
4622 None => return FilterSources::Empty,
4623 }
4624 }
4625
4626 if sources.is_empty() {
4627 FilterSources::Unfiltered
4628 } else {
4629 FilterSources::Sets(sources)
4630 }
4631 }
4632
4633 fn collect_position_filter_sources<'a>(
4634 &'a self,
4635 venue: Option<&Venue>,
4636 instrument_id: Option<&InstrumentId>,
4637 strategy_id: Option<&StrategyId>,
4638 account_id: Option<&AccountId>,
4639 ) -> FilterSources<'a, PositionId> {
4640 let mut sources: Vec<&AHashSet<PositionId>> = Vec::with_capacity(4);
4641
4642 if let Some(venue) = venue {
4643 match self.index.venue_positions.get(venue) {
4644 Some(set) => sources.push(set),
4645 None => return FilterSources::Empty,
4646 }
4647 }
4648
4649 if let Some(instrument_id) = instrument_id {
4650 match self.index.instrument_positions.get(instrument_id) {
4651 Some(set) => sources.push(set),
4652 None => return FilterSources::Empty,
4653 }
4654 }
4655
4656 if let Some(strategy_id) = strategy_id {
4657 match self.index.strategy_positions.get(strategy_id) {
4658 Some(set) => sources.push(set),
4659 None => return FilterSources::Empty,
4660 }
4661 }
4662
4663 if let Some(account_id) = account_id {
4664 match self.index.account_positions.get(account_id) {
4665 Some(set) => sources.push(set),
4666 None => return FilterSources::Empty,
4667 }
4668 }
4669
4670 if sources.is_empty() {
4671 FilterSources::Unfiltered
4672 } else {
4673 FilterSources::Sets(sources)
4674 }
4675 }
4676
4677 fn query_orders_in_bucket(
4683 &self,
4684 bucket: &AHashSet<ClientOrderId>,
4685 venue: Option<&Venue>,
4686 instrument_id: Option<&InstrumentId>,
4687 strategy_id: Option<&StrategyId>,
4688 account_id: Option<&AccountId>,
4689 ) -> AHashSet<ClientOrderId> {
4690 match self.collect_order_filter_sources(venue, instrument_id, strategy_id, account_id) {
4691 FilterSources::Empty => AHashSet::new(),
4692 FilterSources::Unfiltered => bucket.clone(),
4693 FilterSources::Sets(sources) => intersect_pair_or_many(bucket, sources),
4694 }
4695 }
4696
4697 fn query_positions_in_bucket(
4698 &self,
4699 bucket: &AHashSet<PositionId>,
4700 venue: Option<&Venue>,
4701 instrument_id: Option<&InstrumentId>,
4702 strategy_id: Option<&StrategyId>,
4703 account_id: Option<&AccountId>,
4704 ) -> AHashSet<PositionId> {
4705 match self.collect_position_filter_sources(venue, instrument_id, strategy_id, account_id) {
4706 FilterSources::Empty => AHashSet::new(),
4707 FilterSources::Unfiltered => bucket.clone(),
4708 FilterSources::Sets(sources) => intersect_pair_or_many(bucket, sources),
4709 }
4710 }
4711
4712 fn view_orders_in_bucket<'a>(
4715 &'a self,
4716 bucket: &'a AHashSet<ClientOrderId>,
4717 venue: Option<&Venue>,
4718 instrument_id: Option<&InstrumentId>,
4719 strategy_id: Option<&StrategyId>,
4720 account_id: Option<&AccountId>,
4721 ) -> Cow<'a, AHashSet<ClientOrderId>> {
4722 match self.collect_order_filter_sources(venue, instrument_id, strategy_id, account_id) {
4723 FilterSources::Empty => Cow::Owned(AHashSet::new()),
4724 FilterSources::Unfiltered => Cow::Borrowed(bucket),
4725 FilterSources::Sets(sources) => Cow::Owned(intersect_pair_or_many(bucket, sources)),
4726 }
4727 }
4728
4729 fn view_positions_in_bucket<'a>(
4730 &'a self,
4731 bucket: &'a AHashSet<PositionId>,
4732 venue: Option<&Venue>,
4733 instrument_id: Option<&InstrumentId>,
4734 strategy_id: Option<&StrategyId>,
4735 account_id: Option<&AccountId>,
4736 ) -> Cow<'a, AHashSet<PositionId>> {
4737 match self.collect_position_filter_sources(venue, instrument_id, strategy_id, account_id) {
4738 FilterSources::Empty => Cow::Owned(AHashSet::new()),
4739 FilterSources::Unfiltered => Cow::Borrowed(bucket),
4740 FilterSources::Sets(sources) => Cow::Owned(intersect_pair_or_many(bucket, sources)),
4741 }
4742 }
4743
4744 fn iter_orders_in_bucket<'a>(
4749 &'a self,
4750 bucket: &'a AHashSet<ClientOrderId>,
4751 venue: Option<&Venue>,
4752 instrument_id: Option<&InstrumentId>,
4753 strategy_id: Option<&StrategyId>,
4754 account_id: Option<&AccountId>,
4755 ) -> Box<dyn Iterator<Item = ClientOrderId> + 'a> {
4756 match self.collect_order_filter_sources(venue, instrument_id, strategy_id, account_id) {
4757 FilterSources::Empty => Box::new(std::iter::empty()),
4758 FilterSources::Unfiltered => Box::new(bucket.iter().copied()),
4759 FilterSources::Sets(mut sources) => {
4760 sources.push(bucket);
4761 sources.sort_unstable_by_key(|s| s.len());
4762 let driver = sources[0];
4763 let rest: Vec<&'a AHashSet<ClientOrderId>> = sources[1..].to_vec();
4764 Box::new(
4765 driver
4766 .iter()
4767 .copied()
4768 .filter(move |id| rest.iter().all(|s| s.contains(id))),
4769 )
4770 }
4771 }
4772 }
4773
4774 fn iter_positions_in_bucket<'a>(
4775 &'a self,
4776 bucket: &'a AHashSet<PositionId>,
4777 venue: Option<&Venue>,
4778 instrument_id: Option<&InstrumentId>,
4779 strategy_id: Option<&StrategyId>,
4780 account_id: Option<&AccountId>,
4781 ) -> Box<dyn Iterator<Item = PositionId> + 'a> {
4782 match self.collect_position_filter_sources(venue, instrument_id, strategy_id, account_id) {
4783 FilterSources::Empty => Box::new(std::iter::empty()),
4784 FilterSources::Unfiltered => Box::new(bucket.iter().copied()),
4785 FilterSources::Sets(mut sources) => {
4786 sources.push(bucket);
4787 sources.sort_unstable_by_key(|s| s.len());
4788 let driver = sources[0];
4789 let rest: Vec<&'a AHashSet<PositionId>> = sources[1..].to_vec();
4790 Box::new(
4791 driver
4792 .iter()
4793 .copied()
4794 .filter(move |id| rest.iter().all(|s| s.contains(id))),
4795 )
4796 }
4797 }
4798 }
4799
4800 fn count_orders_in_bucket(
4806 &self,
4807 bucket: &AHashSet<ClientOrderId>,
4808 venue: Option<&Venue>,
4809 instrument_id: Option<&InstrumentId>,
4810 strategy_id: Option<&StrategyId>,
4811 account_id: Option<&AccountId>,
4812 side: Option<OrderSide>,
4813 ) -> usize {
4814 match self.collect_order_filter_sources(venue, instrument_id, strategy_id, account_id) {
4815 FilterSources::Empty => 0,
4816 FilterSources::Unfiltered => side.map_or_else(
4817 || bucket.len(),
4818 |side| {
4819 bucket
4820 .iter()
4821 .filter(|id| self.order_side_matches(id, side))
4822 .count()
4823 },
4824 ),
4825 FilterSources::Sets(mut sources) => {
4826 sources.push(bucket);
4827 sources.sort_unstable_by_key(|s| s.len());
4828 let driver = sources[0];
4829 let rest = &sources[1..];
4830
4831 driver
4832 .iter()
4833 .filter(|id| rest.iter().all(|s| s.contains(id)))
4834 .filter(|id| side.is_none_or(|side| self.order_side_matches(id, side)))
4835 .count()
4836 }
4837 }
4838 }
4839
4840 fn count_positions_in_bucket(
4841 &self,
4842 bucket: &AHashSet<PositionId>,
4843 venue: Option<&Venue>,
4844 instrument_id: Option<&InstrumentId>,
4845 strategy_id: Option<&StrategyId>,
4846 account_id: Option<&AccountId>,
4847 side: Option<PositionSide>,
4848 ) -> usize {
4849 match self.collect_position_filter_sources(venue, instrument_id, strategy_id, account_id) {
4850 FilterSources::Empty => 0,
4851 FilterSources::Unfiltered => side.map_or_else(
4852 || bucket.len(),
4853 |side| {
4854 bucket
4855 .iter()
4856 .filter(|id| self.position_side_matches(id, side))
4857 .count()
4858 },
4859 ),
4860 FilterSources::Sets(mut sources) => {
4861 sources.push(bucket);
4862 sources.sort_unstable_by_key(|s| s.len());
4863 let driver = sources[0];
4864 let rest = &sources[1..];
4865
4866 driver
4867 .iter()
4868 .filter(|id| rest.iter().all(|s| s.contains(id)))
4869 .filter(|id| side.is_none_or(|side| self.position_side_matches(id, side)))
4870 .count()
4871 }
4872 }
4873 }
4874
4875 fn any_orders_in_bucket(
4881 &self,
4882 bucket: &AHashSet<ClientOrderId>,
4883 venue: Option<&Venue>,
4884 instrument_id: Option<&InstrumentId>,
4885 strategy_id: Option<&StrategyId>,
4886 account_id: Option<&AccountId>,
4887 side: Option<OrderSide>,
4888 ) -> bool {
4889 match self.collect_order_filter_sources(venue, instrument_id, strategy_id, account_id) {
4890 FilterSources::Empty => false,
4891 FilterSources::Unfiltered => side.map_or_else(
4892 || !bucket.is_empty(),
4893 |side| bucket.iter().any(|id| self.order_side_matches(id, side)),
4894 ),
4895 FilterSources::Sets(mut sources) => {
4896 sources.push(bucket);
4897 sources.sort_unstable_by_key(|s| s.len());
4898 let driver = sources[0];
4899 let rest = &sources[1..];
4900
4901 driver
4902 .iter()
4903 .filter(|id| rest.iter().all(|s| s.contains(id)))
4904 .any(|id| side.is_none_or(|side| self.order_side_matches(id, side)))
4905 }
4906 }
4907 }
4908
4909 fn any_positions_in_bucket(
4910 &self,
4911 bucket: &AHashSet<PositionId>,
4912 venue: Option<&Venue>,
4913 instrument_id: Option<&InstrumentId>,
4914 strategy_id: Option<&StrategyId>,
4915 account_id: Option<&AccountId>,
4916 side: Option<PositionSide>,
4917 ) -> bool {
4918 match self.collect_position_filter_sources(venue, instrument_id, strategy_id, account_id) {
4919 FilterSources::Empty => false,
4920 FilterSources::Unfiltered => side.map_or_else(
4921 || !bucket.is_empty(),
4922 |side| bucket.iter().any(|id| self.position_side_matches(id, side)),
4923 ),
4924 FilterSources::Sets(mut sources) => {
4925 sources.push(bucket);
4926 sources.sort_unstable_by_key(|s| s.len());
4927 let driver = sources[0];
4928 let rest = &sources[1..];
4929
4930 driver
4931 .iter()
4932 .filter(|id| rest.iter().all(|s| s.contains(id)))
4933 .any(|id| side.is_none_or(|side| self.position_side_matches(id, side)))
4934 }
4935 }
4936 }
4937
4938 fn order_side_matches(&self, client_order_id: &ClientOrderId, side: OrderSide) -> bool {
4939 self.orders
4940 .get(client_order_id)
4941 .is_some_and(|cell| cell.borrow().order_side() == side)
4942 }
4943
4944 fn position_side_matches(&self, position_id: &PositionId, side: PositionSide) -> bool {
4945 self.positions
4946 .get(position_id)
4947 .is_some_and(|cell| cell.borrow().side == side)
4948 }
4949
4950 fn get_orders_for_ids(
4956 &self,
4957 client_order_ids: impl IntoIterator<Item = ClientOrderId>,
4958 side: Option<OrderSide>,
4959 ) -> Vec<OrderRef<'_>> {
4960 const UNCACHED_SORT_MAX_LEN: usize = 32;
4961
4962 let mut orders = Vec::new();
4963
4964 for client_order_id in client_order_ids {
4965 let order_cell = self
4966 .orders
4967 .get(&client_order_id)
4968 .unwrap_or_else(|| panic!("Order {client_order_id} not found"));
4969 let order = OrderRef::new(order_cell.borrow());
4970
4971 if side.is_none_or(|side| side == order.order_side()) {
4972 orders.push(order);
4973 }
4974 }
4975
4976 let key = |order: &OrderRef<'_>| order.client_order_id();
4979
4980 if orders.len() <= UNCACHED_SORT_MAX_LEN {
4981 orders.sort_by_key(key);
4982 } else {
4983 orders.sort_by_cached_key(key);
4984 }
4985
4986 orders
4987 }
4988
4989 fn get_positions_for_ids(
4999 &self,
5000 position_ids: &AHashSet<PositionId>,
5001 side: Option<PositionSide>,
5002 ) -> Vec<PositionRef<'_>> {
5003 const UNCACHED_SORT_MAX_LEN: usize = 32;
5004
5005 let mut positions = Vec::new();
5006
5007 for position_id in position_ids {
5008 let position_cell = self
5009 .positions
5010 .get(position_id)
5011 .unwrap_or_else(|| panic!("Position {position_id} not found"));
5012 let position = PositionRef::new(position_cell.borrow());
5013
5014 if side.is_none_or(|side| side == position.side) {
5015 positions.push(position);
5016 }
5017 }
5018
5019 let key = |position: &PositionRef<'_>| position.id;
5022 if positions.len() <= UNCACHED_SORT_MAX_LEN {
5023 positions.sort_by_key(key);
5024 } else {
5025 positions.sort_by_cached_key(key);
5026 }
5027
5028 positions
5029 }
5030
5031 #[must_use]
5033 pub fn client_order_ids(
5034 &self,
5035 venue: Option<&Venue>,
5036 instrument_id: Option<&InstrumentId>,
5037 strategy_id: Option<&StrategyId>,
5038 account_id: Option<&AccountId>,
5039 ) -> AHashSet<ClientOrderId> {
5040 self.query_orders_in_bucket(
5041 &self.index.orders,
5042 venue,
5043 instrument_id,
5044 strategy_id,
5045 account_id,
5046 )
5047 }
5048
5049 #[must_use]
5051 pub fn client_order_ids_open(
5052 &self,
5053 venue: Option<&Venue>,
5054 instrument_id: Option<&InstrumentId>,
5055 strategy_id: Option<&StrategyId>,
5056 account_id: Option<&AccountId>,
5057 ) -> AHashSet<ClientOrderId> {
5058 self.query_orders_in_bucket(
5059 &self.index.orders_open,
5060 venue,
5061 instrument_id,
5062 strategy_id,
5063 account_id,
5064 )
5065 }
5066
5067 #[must_use]
5069 pub fn client_order_ids_closed(
5070 &self,
5071 venue: Option<&Venue>,
5072 instrument_id: Option<&InstrumentId>,
5073 strategy_id: Option<&StrategyId>,
5074 account_id: Option<&AccountId>,
5075 ) -> AHashSet<ClientOrderId> {
5076 self.query_orders_in_bucket(
5077 &self.index.orders_closed,
5078 venue,
5079 instrument_id,
5080 strategy_id,
5081 account_id,
5082 )
5083 }
5084
5085 #[must_use]
5090 pub fn client_order_ids_active_local(
5091 &self,
5092 venue: Option<&Venue>,
5093 instrument_id: Option<&InstrumentId>,
5094 strategy_id: Option<&StrategyId>,
5095 account_id: Option<&AccountId>,
5096 ) -> AHashSet<ClientOrderId> {
5097 self.query_orders_in_bucket(
5098 &self.index.orders_active_local,
5099 venue,
5100 instrument_id,
5101 strategy_id,
5102 account_id,
5103 )
5104 }
5105
5106 #[must_use]
5108 pub fn client_order_ids_emulated(
5109 &self,
5110 venue: Option<&Venue>,
5111 instrument_id: Option<&InstrumentId>,
5112 strategy_id: Option<&StrategyId>,
5113 account_id: Option<&AccountId>,
5114 ) -> AHashSet<ClientOrderId> {
5115 self.query_orders_in_bucket(
5116 &self.index.orders_emulated,
5117 venue,
5118 instrument_id,
5119 strategy_id,
5120 account_id,
5121 )
5122 }
5123
5124 #[must_use]
5126 pub fn client_order_ids_inflight(
5127 &self,
5128 venue: Option<&Venue>,
5129 instrument_id: Option<&InstrumentId>,
5130 strategy_id: Option<&StrategyId>,
5131 account_id: Option<&AccountId>,
5132 ) -> AHashSet<ClientOrderId> {
5133 self.query_orders_in_bucket(
5134 &self.index.orders_inflight,
5135 venue,
5136 instrument_id,
5137 strategy_id,
5138 account_id,
5139 )
5140 }
5141
5142 #[must_use]
5144 pub fn position_ids(
5145 &self,
5146 venue: Option<&Venue>,
5147 instrument_id: Option<&InstrumentId>,
5148 strategy_id: Option<&StrategyId>,
5149 account_id: Option<&AccountId>,
5150 ) -> AHashSet<PositionId> {
5151 self.query_positions_in_bucket(
5152 &self.index.positions,
5153 venue,
5154 instrument_id,
5155 strategy_id,
5156 account_id,
5157 )
5158 }
5159
5160 #[must_use]
5162 pub fn position_open_ids(
5163 &self,
5164 venue: Option<&Venue>,
5165 instrument_id: Option<&InstrumentId>,
5166 strategy_id: Option<&StrategyId>,
5167 account_id: Option<&AccountId>,
5168 ) -> AHashSet<PositionId> {
5169 self.query_positions_in_bucket(
5170 &self.index.positions_open,
5171 venue,
5172 instrument_id,
5173 strategy_id,
5174 account_id,
5175 )
5176 }
5177
5178 #[must_use]
5180 pub fn position_closed_ids(
5181 &self,
5182 venue: Option<&Venue>,
5183 instrument_id: Option<&InstrumentId>,
5184 strategy_id: Option<&StrategyId>,
5185 account_id: Option<&AccountId>,
5186 ) -> AHashSet<PositionId> {
5187 self.query_positions_in_bucket(
5188 &self.index.positions_closed,
5189 venue,
5190 instrument_id,
5191 strategy_id,
5192 account_id,
5193 )
5194 }
5195
5196 #[must_use]
5203 pub fn client_order_ids_view(
5204 &self,
5205 venue: Option<&Venue>,
5206 instrument_id: Option<&InstrumentId>,
5207 strategy_id: Option<&StrategyId>,
5208 account_id: Option<&AccountId>,
5209 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5210 self.view_orders_in_bucket(
5211 &self.index.orders,
5212 venue,
5213 instrument_id,
5214 strategy_id,
5215 account_id,
5216 )
5217 }
5218
5219 #[must_use]
5221 pub fn client_order_ids_open_view(
5222 &self,
5223 venue: Option<&Venue>,
5224 instrument_id: Option<&InstrumentId>,
5225 strategy_id: Option<&StrategyId>,
5226 account_id: Option<&AccountId>,
5227 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5228 self.view_orders_in_bucket(
5229 &self.index.orders_open,
5230 venue,
5231 instrument_id,
5232 strategy_id,
5233 account_id,
5234 )
5235 }
5236
5237 #[must_use]
5239 pub fn client_order_ids_closed_view(
5240 &self,
5241 venue: Option<&Venue>,
5242 instrument_id: Option<&InstrumentId>,
5243 strategy_id: Option<&StrategyId>,
5244 account_id: Option<&AccountId>,
5245 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5246 self.view_orders_in_bucket(
5247 &self.index.orders_closed,
5248 venue,
5249 instrument_id,
5250 strategy_id,
5251 account_id,
5252 )
5253 }
5254
5255 #[must_use]
5257 pub fn client_order_ids_active_local_view(
5258 &self,
5259 venue: Option<&Venue>,
5260 instrument_id: Option<&InstrumentId>,
5261 strategy_id: Option<&StrategyId>,
5262 account_id: Option<&AccountId>,
5263 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5264 self.view_orders_in_bucket(
5265 &self.index.orders_active_local,
5266 venue,
5267 instrument_id,
5268 strategy_id,
5269 account_id,
5270 )
5271 }
5272
5273 #[must_use]
5275 pub fn client_order_ids_emulated_view(
5276 &self,
5277 venue: Option<&Venue>,
5278 instrument_id: Option<&InstrumentId>,
5279 strategy_id: Option<&StrategyId>,
5280 account_id: Option<&AccountId>,
5281 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5282 self.view_orders_in_bucket(
5283 &self.index.orders_emulated,
5284 venue,
5285 instrument_id,
5286 strategy_id,
5287 account_id,
5288 )
5289 }
5290
5291 #[must_use]
5293 pub fn client_order_ids_inflight_view(
5294 &self,
5295 venue: Option<&Venue>,
5296 instrument_id: Option<&InstrumentId>,
5297 strategy_id: Option<&StrategyId>,
5298 account_id: Option<&AccountId>,
5299 ) -> Cow<'_, AHashSet<ClientOrderId>> {
5300 self.view_orders_in_bucket(
5301 &self.index.orders_inflight,
5302 venue,
5303 instrument_id,
5304 strategy_id,
5305 account_id,
5306 )
5307 }
5308
5309 #[must_use]
5311 pub fn position_ids_view(
5312 &self,
5313 venue: Option<&Venue>,
5314 instrument_id: Option<&InstrumentId>,
5315 strategy_id: Option<&StrategyId>,
5316 account_id: Option<&AccountId>,
5317 ) -> Cow<'_, AHashSet<PositionId>> {
5318 self.view_positions_in_bucket(
5319 &self.index.positions,
5320 venue,
5321 instrument_id,
5322 strategy_id,
5323 account_id,
5324 )
5325 }
5326
5327 #[must_use]
5329 pub fn position_open_ids_view(
5330 &self,
5331 venue: Option<&Venue>,
5332 instrument_id: Option<&InstrumentId>,
5333 strategy_id: Option<&StrategyId>,
5334 account_id: Option<&AccountId>,
5335 ) -> Cow<'_, AHashSet<PositionId>> {
5336 self.view_positions_in_bucket(
5337 &self.index.positions_open,
5338 venue,
5339 instrument_id,
5340 strategy_id,
5341 account_id,
5342 )
5343 }
5344
5345 #[must_use]
5347 pub fn position_closed_ids_view(
5348 &self,
5349 venue: Option<&Venue>,
5350 instrument_id: Option<&InstrumentId>,
5351 strategy_id: Option<&StrategyId>,
5352 account_id: Option<&AccountId>,
5353 ) -> Cow<'_, AHashSet<PositionId>> {
5354 self.view_positions_in_bucket(
5355 &self.index.positions_closed,
5356 venue,
5357 instrument_id,
5358 strategy_id,
5359 account_id,
5360 )
5361 }
5362
5363 pub fn iter_client_order_ids(
5369 &self,
5370 venue: Option<&Venue>,
5371 instrument_id: Option<&InstrumentId>,
5372 strategy_id: Option<&StrategyId>,
5373 account_id: Option<&AccountId>,
5374 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5375 self.iter_orders_in_bucket(
5376 &self.index.orders,
5377 venue,
5378 instrument_id,
5379 strategy_id,
5380 account_id,
5381 )
5382 }
5383
5384 pub fn iter_client_order_ids_open(
5386 &self,
5387 venue: Option<&Venue>,
5388 instrument_id: Option<&InstrumentId>,
5389 strategy_id: Option<&StrategyId>,
5390 account_id: Option<&AccountId>,
5391 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5392 self.iter_orders_in_bucket(
5393 &self.index.orders_open,
5394 venue,
5395 instrument_id,
5396 strategy_id,
5397 account_id,
5398 )
5399 }
5400
5401 pub fn iter_client_order_ids_closed(
5403 &self,
5404 venue: Option<&Venue>,
5405 instrument_id: Option<&InstrumentId>,
5406 strategy_id: Option<&StrategyId>,
5407 account_id: Option<&AccountId>,
5408 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5409 self.iter_orders_in_bucket(
5410 &self.index.orders_closed,
5411 venue,
5412 instrument_id,
5413 strategy_id,
5414 account_id,
5415 )
5416 }
5417
5418 pub fn iter_client_order_ids_active_local(
5420 &self,
5421 venue: Option<&Venue>,
5422 instrument_id: Option<&InstrumentId>,
5423 strategy_id: Option<&StrategyId>,
5424 account_id: Option<&AccountId>,
5425 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5426 self.iter_orders_in_bucket(
5427 &self.index.orders_active_local,
5428 venue,
5429 instrument_id,
5430 strategy_id,
5431 account_id,
5432 )
5433 }
5434
5435 pub fn iter_client_order_ids_emulated(
5437 &self,
5438 venue: Option<&Venue>,
5439 instrument_id: Option<&InstrumentId>,
5440 strategy_id: Option<&StrategyId>,
5441 account_id: Option<&AccountId>,
5442 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5443 self.iter_orders_in_bucket(
5444 &self.index.orders_emulated,
5445 venue,
5446 instrument_id,
5447 strategy_id,
5448 account_id,
5449 )
5450 }
5451
5452 pub fn iter_client_order_ids_inflight(
5454 &self,
5455 venue: Option<&Venue>,
5456 instrument_id: Option<&InstrumentId>,
5457 strategy_id: Option<&StrategyId>,
5458 account_id: Option<&AccountId>,
5459 ) -> Box<dyn Iterator<Item = ClientOrderId> + '_> {
5460 self.iter_orders_in_bucket(
5461 &self.index.orders_inflight,
5462 venue,
5463 instrument_id,
5464 strategy_id,
5465 account_id,
5466 )
5467 }
5468
5469 pub fn iter_position_ids(
5471 &self,
5472 venue: Option<&Venue>,
5473 instrument_id: Option<&InstrumentId>,
5474 strategy_id: Option<&StrategyId>,
5475 account_id: Option<&AccountId>,
5476 ) -> Box<dyn Iterator<Item = PositionId> + '_> {
5477 self.iter_positions_in_bucket(
5478 &self.index.positions,
5479 venue,
5480 instrument_id,
5481 strategy_id,
5482 account_id,
5483 )
5484 }
5485
5486 pub fn iter_position_open_ids(
5488 &self,
5489 venue: Option<&Venue>,
5490 instrument_id: Option<&InstrumentId>,
5491 strategy_id: Option<&StrategyId>,
5492 account_id: Option<&AccountId>,
5493 ) -> Box<dyn Iterator<Item = PositionId> + '_> {
5494 self.iter_positions_in_bucket(
5495 &self.index.positions_open,
5496 venue,
5497 instrument_id,
5498 strategy_id,
5499 account_id,
5500 )
5501 }
5502
5503 pub fn iter_position_closed_ids(
5505 &self,
5506 venue: Option<&Venue>,
5507 instrument_id: Option<&InstrumentId>,
5508 strategy_id: Option<&StrategyId>,
5509 account_id: Option<&AccountId>,
5510 ) -> Box<dyn Iterator<Item = PositionId> + '_> {
5511 self.iter_positions_in_bucket(
5512 &self.index.positions_closed,
5513 venue,
5514 instrument_id,
5515 strategy_id,
5516 account_id,
5517 )
5518 }
5519
5520 #[must_use]
5522 pub fn strategy_ids(&self) -> AHashSet<StrategyId> {
5523 self.index.strategies.clone()
5524 }
5525
5526 #[must_use]
5528 pub fn exec_algorithm_ids(&self) -> AHashSet<ExecAlgorithmId> {
5529 self.index.exec_algorithms.clone()
5530 }
5531
5532 #[must_use]
5541 pub fn order_ref(&self, client_order_id: &ClientOrderId) -> Option<OrderRef<'_>> {
5542 self.orders
5543 .get(client_order_id)
5544 .map(|order_cell| OrderRef::new(order_cell.borrow()))
5545 }
5546
5547 #[must_use]
5551 pub fn order(&self, client_order_id: &ClientOrderId) -> Option<OrderRef<'_>> {
5552 self.order_ref(client_order_id)
5553 }
5554
5555 pub fn try_order_ref(
5561 &self,
5562 client_order_id: &ClientOrderId,
5563 ) -> Result<OrderRef<'_>, OrderLookupError> {
5564 self.orders
5565 .get(client_order_id)
5566 .map(|order_cell| OrderRef::new(order_cell.borrow()))
5567 .ok_or_else(|| OrderLookupError::not_found(*client_order_id))
5568 }
5569
5570 pub fn try_order(
5578 &self,
5579 client_order_id: &ClientOrderId,
5580 ) -> Result<OrderRef<'_>, OrderLookupError> {
5581 self.try_order_ref(client_order_id)
5582 }
5583
5584 #[must_use]
5594 pub fn order_mut(&mut self, client_order_id: &ClientOrderId) -> Option<OrderRefMut<'_>> {
5595 self.orders
5596 .get(client_order_id)
5597 .map(|order_cell| OrderRefMut::new(order_cell.borrow_mut()))
5598 }
5599
5600 #[must_use]
5605 pub fn order_owned(&self, client_order_id: &ClientOrderId) -> Option<OrderAny> {
5606 self.orders
5607 .get(client_order_id)
5608 .map(|order_cell| order_cell.borrow().clone())
5609 }
5610
5611 pub fn try_order_owned(
5617 &self,
5618 client_order_id: &ClientOrderId,
5619 ) -> Result<OrderAny, OrderLookupError> {
5620 self.try_order_ref(client_order_id)
5621 .map(|order| order.cloned())
5622 }
5623
5624 #[must_use]
5626 pub fn orders_for_ids(
5627 &self,
5628 client_order_ids: &[ClientOrderId],
5629 context: &dyn Display,
5630 ) -> Vec<OrderAny> {
5631 let mut orders = Vec::with_capacity(client_order_ids.len());
5632 for id in client_order_ids {
5633 match self.orders.get(id) {
5634 Some(order_cell) => orders.push(order_cell.borrow().clone()),
5635 None => log::error!("Order {id} not found in cache for {context}"),
5636 }
5637 }
5638 orders
5639 }
5640
5641 #[must_use]
5643 pub fn client_order_id(&self, venue_order_id: &VenueOrderId) -> Option<&ClientOrderId> {
5644 self.index.venue_order_ids.get(venue_order_id)
5645 }
5646
5647 #[must_use]
5649 pub fn venue_order_id(&self, client_order_id: &ClientOrderId) -> Option<&VenueOrderId> {
5650 self.index.client_order_ids.get(client_order_id)
5651 }
5652
5653 #[must_use]
5655 pub fn client_id(&self, client_order_id: &ClientOrderId) -> Option<&ClientId> {
5656 self.index.order_client.get(client_order_id)
5657 }
5658
5659 #[must_use]
5665 pub fn orders_refs(
5666 &self,
5667 venue: Option<&Venue>,
5668 instrument_id: Option<&InstrumentId>,
5669 strategy_id: Option<&StrategyId>,
5670 account_id: Option<&AccountId>,
5671 side: Option<OrderSide>,
5672 ) -> Vec<OrderRef<'_>> {
5673 if venue.is_none()
5674 && instrument_id.is_none()
5675 && strategy_id.is_none()
5676 && account_id.is_none()
5677 {
5678 return self.get_orders_for_ids(self.index.orders.iter().copied(), side);
5679 }
5680
5681 let client_order_ids =
5682 self.iter_client_order_ids(venue, instrument_id, strategy_id, account_id);
5683 self.get_orders_for_ids(client_order_ids, side)
5684 }
5685
5686 #[must_use]
5690 pub fn orders(
5691 &self,
5692 venue: Option<&Venue>,
5693 instrument_id: Option<&InstrumentId>,
5694 strategy_id: Option<&StrategyId>,
5695 account_id: Option<&AccountId>,
5696 side: Option<OrderSide>,
5697 ) -> Vec<OrderRef<'_>> {
5698 self.orders_refs(venue, instrument_id, strategy_id, account_id, side)
5699 }
5700
5701 #[must_use]
5703 pub fn orders_open_refs(
5704 &self,
5705 venue: Option<&Venue>,
5706 instrument_id: Option<&InstrumentId>,
5707 strategy_id: Option<&StrategyId>,
5708 account_id: Option<&AccountId>,
5709 side: Option<OrderSide>,
5710 ) -> Vec<OrderRef<'_>> {
5711 let client_order_ids =
5712 self.client_order_ids_open(venue, instrument_id, strategy_id, account_id);
5713 self.get_orders_for_ids(client_order_ids.iter().copied(), side)
5714 }
5715
5716 #[must_use]
5720 pub fn orders_open(
5721 &self,
5722 venue: Option<&Venue>,
5723 instrument_id: Option<&InstrumentId>,
5724 strategy_id: Option<&StrategyId>,
5725 account_id: Option<&AccountId>,
5726 side: Option<OrderSide>,
5727 ) -> Vec<OrderRef<'_>> {
5728 self.orders_open_refs(venue, instrument_id, strategy_id, account_id, side)
5729 }
5730
5731 #[must_use]
5733 pub fn orders_closed_refs(
5734 &self,
5735 venue: Option<&Venue>,
5736 instrument_id: Option<&InstrumentId>,
5737 strategy_id: Option<&StrategyId>,
5738 account_id: Option<&AccountId>,
5739 side: Option<OrderSide>,
5740 ) -> Vec<OrderRef<'_>> {
5741 let client_order_ids =
5742 self.client_order_ids_closed(venue, instrument_id, strategy_id, account_id);
5743 self.get_orders_for_ids(client_order_ids.iter().copied(), side)
5744 }
5745
5746 #[must_use]
5750 pub fn orders_closed(
5751 &self,
5752 venue: Option<&Venue>,
5753 instrument_id: Option<&InstrumentId>,
5754 strategy_id: Option<&StrategyId>,
5755 account_id: Option<&AccountId>,
5756 side: Option<OrderSide>,
5757 ) -> Vec<OrderRef<'_>> {
5758 self.orders_closed_refs(venue, instrument_id, strategy_id, account_id, side)
5759 }
5760
5761 #[must_use]
5766 pub fn orders_active_local_refs(
5767 &self,
5768 venue: Option<&Venue>,
5769 instrument_id: Option<&InstrumentId>,
5770 strategy_id: Option<&StrategyId>,
5771 account_id: Option<&AccountId>,
5772 side: Option<OrderSide>,
5773 ) -> Vec<OrderRef<'_>> {
5774 let client_order_ids =
5775 self.client_order_ids_active_local(venue, instrument_id, strategy_id, account_id);
5776 self.get_orders_for_ids(client_order_ids.iter().copied(), side)
5777 }
5778
5779 #[must_use]
5783 pub fn orders_active_local(
5784 &self,
5785 venue: Option<&Venue>,
5786 instrument_id: Option<&InstrumentId>,
5787 strategy_id: Option<&StrategyId>,
5788 account_id: Option<&AccountId>,
5789 side: Option<OrderSide>,
5790 ) -> Vec<OrderRef<'_>> {
5791 self.orders_active_local_refs(venue, instrument_id, strategy_id, account_id, side)
5792 }
5793
5794 #[must_use]
5796 pub fn orders_emulated_refs(
5797 &self,
5798 venue: Option<&Venue>,
5799 instrument_id: Option<&InstrumentId>,
5800 strategy_id: Option<&StrategyId>,
5801 account_id: Option<&AccountId>,
5802 side: Option<OrderSide>,
5803 ) -> Vec<OrderRef<'_>> {
5804 let client_order_ids =
5805 self.client_order_ids_emulated(venue, instrument_id, strategy_id, account_id);
5806 self.get_orders_for_ids(client_order_ids.iter().copied(), side)
5807 }
5808
5809 #[must_use]
5813 pub fn orders_emulated(
5814 &self,
5815 venue: Option<&Venue>,
5816 instrument_id: Option<&InstrumentId>,
5817 strategy_id: Option<&StrategyId>,
5818 account_id: Option<&AccountId>,
5819 side: Option<OrderSide>,
5820 ) -> Vec<OrderRef<'_>> {
5821 self.orders_emulated_refs(venue, instrument_id, strategy_id, account_id, side)
5822 }
5823
5824 #[must_use]
5826 pub fn orders_inflight_refs(
5827 &self,
5828 venue: Option<&Venue>,
5829 instrument_id: Option<&InstrumentId>,
5830 strategy_id: Option<&StrategyId>,
5831 account_id: Option<&AccountId>,
5832 side: Option<OrderSide>,
5833 ) -> Vec<OrderRef<'_>> {
5834 let client_order_ids =
5835 self.client_order_ids_inflight(venue, instrument_id, strategy_id, account_id);
5836 self.get_orders_for_ids(client_order_ids.iter().copied(), side)
5837 }
5838
5839 #[must_use]
5843 pub fn orders_inflight(
5844 &self,
5845 venue: Option<&Venue>,
5846 instrument_id: Option<&InstrumentId>,
5847 strategy_id: Option<&StrategyId>,
5848 account_id: Option<&AccountId>,
5849 side: Option<OrderSide>,
5850 ) -> Vec<OrderRef<'_>> {
5851 self.orders_inflight_refs(venue, instrument_id, strategy_id, account_id, side)
5852 }
5853
5854 #[must_use]
5856 pub fn orders_for_position(&self, position_id: &PositionId) -> Vec<OrderRef<'_>> {
5857 match self.index.position_orders.get(position_id) {
5858 Some(client_order_ids) => {
5859 self.get_orders_for_ids(client_order_ids.iter().copied(), None)
5860 }
5861 None => Vec::new(),
5862 }
5863 }
5864
5865 pub fn mark_orders_dispatched(
5869 &mut self,
5870 client_order_ids: impl IntoIterator<Item = ClientOrderId>,
5871 ) {
5872 self.orders_dispatched.extend(client_order_ids);
5873 }
5874
5875 pub fn clear_order_dispatch(&mut self, client_order_id: &ClientOrderId) {
5877 self.orders_dispatched.remove(client_order_id);
5878 }
5879
5880 #[must_use]
5882 pub fn is_order_dispatched(&self, client_order_id: &ClientOrderId) -> bool {
5883 self.orders_dispatched.contains(client_order_id)
5884 }
5885
5886 #[must_use]
5888 pub fn order_exists(&self, client_order_id: &ClientOrderId) -> bool {
5889 self.index.orders.contains(client_order_id)
5890 }
5891
5892 #[must_use]
5894 pub fn is_order_open(&self, client_order_id: &ClientOrderId) -> bool {
5895 self.index.orders_open.contains(client_order_id)
5896 }
5897
5898 #[must_use]
5900 pub fn is_order_closed(&self, client_order_id: &ClientOrderId) -> bool {
5901 self.index.orders_closed.contains(client_order_id)
5902 }
5903
5904 #[must_use]
5909 pub fn is_order_active_local(&self, client_order_id: &ClientOrderId) -> bool {
5910 self.index.orders_active_local.contains(client_order_id)
5911 }
5912
5913 #[must_use]
5915 pub fn is_order_emulated(&self, client_order_id: &ClientOrderId) -> bool {
5916 self.index.orders_emulated.contains(client_order_id)
5917 }
5918
5919 #[must_use]
5921 pub fn is_order_inflight(&self, client_order_id: &ClientOrderId) -> bool {
5922 self.index.orders_inflight.contains(client_order_id)
5923 }
5924
5925 #[must_use]
5927 pub fn is_order_pending_cancel_local(&self, client_order_id: &ClientOrderId) -> bool {
5928 self.index.orders_pending_cancel.contains(client_order_id)
5929 }
5930
5931 #[must_use]
5933 pub fn orders_open_count(
5934 &self,
5935 venue: Option<&Venue>,
5936 instrument_id: Option<&InstrumentId>,
5937 strategy_id: Option<&StrategyId>,
5938 account_id: Option<&AccountId>,
5939 side: Option<OrderSide>,
5940 ) -> usize {
5941 self.count_orders_in_bucket(
5942 &self.index.orders_open,
5943 venue,
5944 instrument_id,
5945 strategy_id,
5946 account_id,
5947 side,
5948 )
5949 }
5950
5951 #[must_use]
5953 pub fn orders_closed_count(
5954 &self,
5955 venue: Option<&Venue>,
5956 instrument_id: Option<&InstrumentId>,
5957 strategy_id: Option<&StrategyId>,
5958 account_id: Option<&AccountId>,
5959 side: Option<OrderSide>,
5960 ) -> usize {
5961 self.count_orders_in_bucket(
5962 &self.index.orders_closed,
5963 venue,
5964 instrument_id,
5965 strategy_id,
5966 account_id,
5967 side,
5968 )
5969 }
5970
5971 #[must_use]
5976 pub fn orders_active_local_count(
5977 &self,
5978 venue: Option<&Venue>,
5979 instrument_id: Option<&InstrumentId>,
5980 strategy_id: Option<&StrategyId>,
5981 account_id: Option<&AccountId>,
5982 side: Option<OrderSide>,
5983 ) -> usize {
5984 self.count_orders_in_bucket(
5985 &self.index.orders_active_local,
5986 venue,
5987 instrument_id,
5988 strategy_id,
5989 account_id,
5990 side,
5991 )
5992 }
5993
5994 #[must_use]
5996 pub fn orders_emulated_count(
5997 &self,
5998 venue: Option<&Venue>,
5999 instrument_id: Option<&InstrumentId>,
6000 strategy_id: Option<&StrategyId>,
6001 account_id: Option<&AccountId>,
6002 side: Option<OrderSide>,
6003 ) -> usize {
6004 self.count_orders_in_bucket(
6005 &self.index.orders_emulated,
6006 venue,
6007 instrument_id,
6008 strategy_id,
6009 account_id,
6010 side,
6011 )
6012 }
6013
6014 #[must_use]
6016 pub fn orders_inflight_count(
6017 &self,
6018 venue: Option<&Venue>,
6019 instrument_id: Option<&InstrumentId>,
6020 strategy_id: Option<&StrategyId>,
6021 account_id: Option<&AccountId>,
6022 side: Option<OrderSide>,
6023 ) -> usize {
6024 self.count_orders_in_bucket(
6025 &self.index.orders_inflight,
6026 venue,
6027 instrument_id,
6028 strategy_id,
6029 account_id,
6030 side,
6031 )
6032 }
6033
6034 #[must_use]
6036 pub fn orders_total_count(
6037 &self,
6038 venue: Option<&Venue>,
6039 instrument_id: Option<&InstrumentId>,
6040 strategy_id: Option<&StrategyId>,
6041 account_id: Option<&AccountId>,
6042 side: Option<OrderSide>,
6043 ) -> usize {
6044 self.count_orders_in_bucket(
6045 &self.index.orders,
6046 venue,
6047 instrument_id,
6048 strategy_id,
6049 account_id,
6050 side,
6051 )
6052 }
6053
6054 #[must_use]
6060 pub fn has_orders_open(
6061 &self,
6062 venue: Option<&Venue>,
6063 instrument_id: Option<&InstrumentId>,
6064 strategy_id: Option<&StrategyId>,
6065 account_id: Option<&AccountId>,
6066 side: Option<OrderSide>,
6067 ) -> bool {
6068 self.any_orders_in_bucket(
6069 &self.index.orders_open,
6070 venue,
6071 instrument_id,
6072 strategy_id,
6073 account_id,
6074 side,
6075 )
6076 }
6077
6078 #[must_use]
6080 pub fn has_orders_closed(
6081 &self,
6082 venue: Option<&Venue>,
6083 instrument_id: Option<&InstrumentId>,
6084 strategy_id: Option<&StrategyId>,
6085 account_id: Option<&AccountId>,
6086 side: Option<OrderSide>,
6087 ) -> bool {
6088 self.any_orders_in_bucket(
6089 &self.index.orders_closed,
6090 venue,
6091 instrument_id,
6092 strategy_id,
6093 account_id,
6094 side,
6095 )
6096 }
6097
6098 #[must_use]
6102 pub fn has_orders_active_local(
6103 &self,
6104 venue: Option<&Venue>,
6105 instrument_id: Option<&InstrumentId>,
6106 strategy_id: Option<&StrategyId>,
6107 account_id: Option<&AccountId>,
6108 side: Option<OrderSide>,
6109 ) -> bool {
6110 self.any_orders_in_bucket(
6111 &self.index.orders_active_local,
6112 venue,
6113 instrument_id,
6114 strategy_id,
6115 account_id,
6116 side,
6117 )
6118 }
6119
6120 #[must_use]
6122 pub fn has_orders_emulated(
6123 &self,
6124 venue: Option<&Venue>,
6125 instrument_id: Option<&InstrumentId>,
6126 strategy_id: Option<&StrategyId>,
6127 account_id: Option<&AccountId>,
6128 side: Option<OrderSide>,
6129 ) -> bool {
6130 self.any_orders_in_bucket(
6131 &self.index.orders_emulated,
6132 venue,
6133 instrument_id,
6134 strategy_id,
6135 account_id,
6136 side,
6137 )
6138 }
6139
6140 #[must_use]
6142 pub fn has_orders_inflight(
6143 &self,
6144 venue: Option<&Venue>,
6145 instrument_id: Option<&InstrumentId>,
6146 strategy_id: Option<&StrategyId>,
6147 account_id: Option<&AccountId>,
6148 side: Option<OrderSide>,
6149 ) -> bool {
6150 self.any_orders_in_bucket(
6151 &self.index.orders_inflight,
6152 venue,
6153 instrument_id,
6154 strategy_id,
6155 account_id,
6156 side,
6157 )
6158 }
6159
6160 #[must_use]
6162 pub fn has_orders(
6163 &self,
6164 venue: Option<&Venue>,
6165 instrument_id: Option<&InstrumentId>,
6166 strategy_id: Option<&StrategyId>,
6167 account_id: Option<&AccountId>,
6168 side: Option<OrderSide>,
6169 ) -> bool {
6170 self.any_orders_in_bucket(
6171 &self.index.orders,
6172 venue,
6173 instrument_id,
6174 strategy_id,
6175 account_id,
6176 side,
6177 )
6178 }
6179
6180 #[must_use]
6182 pub fn order_list(&self, order_list_id: &OrderListId) -> Option<&OrderList> {
6183 self.order_lists.get(order_list_id)
6184 }
6185
6186 pub fn try_order_list(
6192 &self,
6193 order_list_id: &OrderListId,
6194 ) -> Result<&OrderList, OrderListLookupError> {
6195 self.order_lists
6196 .get(order_list_id)
6197 .ok_or_else(|| OrderListLookupError::not_found(*order_list_id))
6198 }
6199
6200 #[must_use]
6202 pub fn order_lists(
6203 &self,
6204 venue: Option<&Venue>,
6205 instrument_id: Option<&InstrumentId>,
6206 strategy_id: Option<&StrategyId>,
6207 account_id: Option<&AccountId>,
6208 ) -> Vec<&OrderList> {
6209 let mut order_lists = self.order_lists.values().collect::<Vec<&OrderList>>();
6210
6211 if let Some(venue) = venue {
6212 order_lists.retain(|ol| &ol.instrument_id.venue == venue);
6213 }
6214
6215 if let Some(instrument_id) = instrument_id {
6216 order_lists.retain(|ol| &ol.instrument_id == instrument_id);
6217 }
6218
6219 if let Some(strategy_id) = strategy_id {
6220 order_lists.retain(|ol| &ol.strategy_id == strategy_id);
6221 }
6222
6223 if let Some(account_id) = account_id {
6224 order_lists.retain(|ol| {
6225 ol.client_order_ids.iter().any(|client_order_id| {
6226 self.orders.get(client_order_id).is_some_and(|order_cell| {
6227 order_cell.borrow().account_id().as_ref() == Some(account_id)
6228 })
6229 })
6230 });
6231 }
6232
6233 order_lists
6234 }
6235
6236 #[must_use]
6238 pub fn order_list_exists(&self, order_list_id: &OrderListId) -> bool {
6239 self.order_lists.contains_key(order_list_id)
6240 }
6241
6242 #[must_use]
6247 pub fn orders_for_exec_algorithm(
6248 &self,
6249 exec_algorithm_id: &ExecAlgorithmId,
6250 venue: Option<&Venue>,
6251 instrument_id: Option<&InstrumentId>,
6252 strategy_id: Option<&StrategyId>,
6253 account_id: Option<&AccountId>,
6254 side: Option<OrderSide>,
6255 ) -> Vec<OrderRef<'_>> {
6256 let Some(exec_algorithm_order_ids) =
6257 self.index.exec_algorithm_orders.get(exec_algorithm_id)
6258 else {
6259 return Vec::new();
6260 };
6261
6262 let filtered = self.query_orders_in_bucket(
6263 exec_algorithm_order_ids,
6264 venue,
6265 instrument_id,
6266 strategy_id,
6267 account_id,
6268 );
6269 self.get_orders_for_ids(filtered.iter().copied(), side)
6270 }
6271
6272 #[must_use]
6274 pub fn orders_for_exec_spawn(&self, exec_spawn_id: &ClientOrderId) -> Vec<OrderRef<'_>> {
6275 match self.index.exec_spawn_orders.get(exec_spawn_id) {
6276 Some(ids) => self.get_orders_for_ids(ids.iter().copied(), None),
6277 None => Vec::new(),
6278 }
6279 }
6280
6281 #[must_use]
6283 pub fn exec_spawn_total_quantity(
6284 &self,
6285 exec_spawn_id: &ClientOrderId,
6286 active_only: bool,
6287 ) -> Option<Quantity> {
6288 self.exec_spawn_total(exec_spawn_id, active_only, Order::quantity)
6289 }
6290
6291 #[must_use]
6293 pub fn exec_spawn_total_filled_qty(
6294 &self,
6295 exec_spawn_id: &ClientOrderId,
6296 active_only: bool,
6297 ) -> Option<Quantity> {
6298 self.exec_spawn_total(exec_spawn_id, active_only, Order::filled_qty)
6299 }
6300
6301 #[must_use]
6303 pub fn exec_spawn_total_leaves_qty(
6304 &self,
6305 exec_spawn_id: &ClientOrderId,
6306 active_only: bool,
6307 ) -> Option<Quantity> {
6308 self.exec_spawn_total(exec_spawn_id, active_only, Order::leaves_qty)
6309 }
6310
6311 fn exec_spawn_total(
6312 &self,
6313 exec_spawn_id: &ClientOrderId,
6314 active_only: bool,
6315 quantity: impl Fn(&OrderAny) -> Quantity,
6316 ) -> Option<Quantity> {
6317 self.orders_for_exec_spawn(exec_spawn_id)
6318 .into_iter()
6319 .filter(|order| !active_only || !order.is_closed())
6320 .map(|order| quantity(&order))
6321 .reduce(|total, quantity| total + quantity)
6322 }
6323
6324 #[must_use]
6328 pub fn position_ref(&self, position_id: &PositionId) -> Option<PositionRef<'_>> {
6329 self.positions
6330 .get(position_id)
6331 .map(|position_cell| PositionRef::new(position_cell.borrow()))
6332 }
6333
6334 #[must_use]
6338 pub fn position(&self, position_id: &PositionId) -> Option<PositionRef<'_>> {
6339 self.position_ref(position_id)
6340 }
6341
6342 pub fn try_position_ref(
6348 &self,
6349 position_id: &PositionId,
6350 ) -> Result<PositionRef<'_>, PositionLookupError> {
6351 self.positions
6352 .get(position_id)
6353 .map(|position_cell| PositionRef::new(position_cell.borrow()))
6354 .ok_or_else(|| PositionLookupError::not_found(*position_id))
6355 }
6356
6357 pub fn try_position(
6365 &self,
6366 position_id: &PositionId,
6367 ) -> Result<PositionRef<'_>, PositionLookupError> {
6368 self.try_position_ref(position_id)
6369 }
6370
6371 #[must_use]
6381 pub fn position_mut(&mut self, position_id: &PositionId) -> Option<PositionRefMut<'_>> {
6382 self.positions
6383 .get(position_id)
6384 .map(|position_cell| PositionRefMut::new(position_cell.borrow_mut()))
6385 }
6386
6387 #[must_use]
6392 pub fn position_owned(&self, position_id: &PositionId) -> Option<Position> {
6393 self.positions
6394 .get(position_id)
6395 .map(|position_cell| position_cell.borrow().clone())
6396 }
6397
6398 #[must_use]
6400 pub fn position_for_order_ref(
6401 &self,
6402 client_order_id: &ClientOrderId,
6403 ) -> Option<PositionRef<'_>> {
6404 self.index
6405 .order_position
6406 .get(client_order_id)
6407 .and_then(|position_id| self.positions.get(position_id))
6408 .map(|position_cell| PositionRef::new(position_cell.borrow()))
6409 }
6410
6411 #[must_use]
6415 pub fn position_for_order(&self, client_order_id: &ClientOrderId) -> Option<PositionRef<'_>> {
6416 self.position_for_order_ref(client_order_id)
6417 }
6418
6419 #[must_use]
6421 pub fn position_id(&self, client_order_id: &ClientOrderId) -> Option<&PositionId> {
6422 self.index.order_position.get(client_order_id)
6423 }
6424
6425 pub fn hedging_flip_position_ids(
6435 &self,
6436 client_order_id: ClientOrderId,
6437 ) -> anyhow::Result<Option<[PositionId; 2]>> {
6438 let Some(order) = self.order_ref(&client_order_id) else {
6439 return Ok(None);
6440 };
6441
6442 let mut flip = None;
6443 let mut corrected_source = None;
6444
6445 let mut replay_offsets = AHashMap::new();
6447
6448 for event in order.events() {
6449 let OrderEventAny::Filled(fill) = event else {
6450 continue;
6451 };
6452
6453 let Some(source_id) = fill.position_id.filter(PositionId::is_virtual) else {
6454 continue;
6455 };
6456
6457 let source = self.position_ref(&source_id);
6458 if source.is_some() && self.oms_type(&source_id) != Some(OmsType::Hedging) {
6459 continue;
6460 }
6461
6462 if source.as_ref().is_some_and(|source| {
6463 let offset = replay_offsets.entry(source_id).or_default();
6464 Self::replay_contains_fill(&source.replay_events, fill, offset)
6465 }) {
6466 continue;
6467 }
6468
6469 let closing = source.as_ref().and_then(|source| {
6470 source
6471 .fill_fragments(client_order_id, fill.trade_id)
6472 .into_iter()
6473 .find(|fragment| {
6474 fragment.event_id == fill.event_id && fragment.last_qty < fill.last_qty
6475 })
6476 .map(|closing| (source, closing))
6477 });
6478
6479 let Some((source, closing)) = closing else {
6480 let has_opening = self
6481 .positions_refs(
6482 None,
6483 Some(&fill.instrument_id),
6484 Some(&fill.strategy_id),
6485 Some(&fill.account_id),
6486 None,
6487 )
6488 .iter()
6489 .any(|position| {
6490 position.id != source_id
6491 && position.id.is_virtual()
6492 && self.oms_type(&position.id) == Some(OmsType::Hedging)
6493 && position.replay_events.iter().any(|event| {
6494 matches!(event, PositionReplayEvent::Filled(opening)
6495 if opening.causation_id == Some(fill.event_id)
6496 && opening.client_order_id == client_order_id
6497 && opening.trade_id == fill.trade_id)
6498 })
6499 });
6500
6501 anyhow::ensure!(
6502 !has_opening,
6503 "missing virtual flip source fragment for order {client_order_id}"
6504 );
6505 continue;
6506 };
6507
6508 let (positions, corrected_closing) =
6509 self.hedging_flip_destination(fill, source, closing)?;
6510 anyhow::ensure!(
6511 flip.is_none() || corrected_source == Some(source.id),
6512 "ambiguous virtual flip history for order {client_order_id}"
6513 );
6514 flip = Some(positions);
6515 corrected_source = corrected_closing.then_some(source.id);
6516 }
6517
6518 Ok(flip)
6519 }
6520
6521 fn replay_contains_fill(
6522 events: &[PositionReplayEvent],
6523 fill: &OrderFilled,
6524 offset: &mut usize,
6525 ) -> bool {
6526 let matches_fill = |event: &PositionReplayEvent| matches!(event, PositionReplayEvent::Filled(fragment) if fragment == fill);
6527
6528 if let Some(index) = events[*offset..].iter().position(matches_fill) {
6529 *offset += index + 1;
6530 return true;
6531 }
6532
6533 events[..*offset].iter().any(matches_fill)
6535 }
6536
6537 fn hedging_flip_destination(
6538 &self,
6539 fill: &OrderFilled,
6540 source: &Position,
6541 closing: &OrderFilled,
6542 ) -> anyhow::Result<([PositionId; 2], bool)> {
6543 let positions = self.positions_refs(
6544 None,
6545 Some(&fill.instrument_id),
6546 Some(&fill.strategy_id),
6547 Some(&fill.account_id),
6548 None,
6549 );
6550
6551 let mut openings = positions.iter().flat_map(|position| {
6552 position
6553 .replay_events
6554 .iter()
6555 .filter_map(move |event| match event {
6556 PositionReplayEvent::Filled(opening)
6557 if opening.causation_id == Some(fill.event_id)
6558 && position.id != source.id =>
6559 {
6560 Some((position, opening))
6561 }
6562 _ => None,
6563 })
6564 });
6565
6566 let (destination, opening) = openings.next().ok_or_else(|| {
6567 anyhow::anyhow!(
6568 "missing virtual flip fragment for order {}",
6569 fill.client_order_id
6570 )
6571 })?;
6572
6573 anyhow::ensure!(
6574 openings.next().is_none(),
6575 "ambiguous virtual flip fragments for order {}",
6576 fill.client_order_id
6577 );
6578 anyhow::ensure!(
6579 source.instrument_id == fill.instrument_id
6580 && source.account_id == fill.account_id
6581 && source.strategy_id == fill.strategy_id
6582 && destination.id.is_virtual()
6583 && self.oms_type(&destination.id) == Some(OmsType::Hedging),
6584 "conflicting virtual flip positions for order {}",
6585 fill.client_order_id
6586 );
6587 let (expected_closing, expected_opening) =
6588 fill.split_for_position_flip(closing.last_qty, Some(destination.id), opening.event_id)?;
6589 anyhow::ensure!(
6590 *closing == expected_closing && *opening == expected_opening,
6591 "conflicting virtual flip provenance for order {}",
6592 fill.client_order_id
6593 );
6594
6595 let corrected_closing = source.fill_voids.iter().any(|correction| {
6596 correction.event.client_order_id == fill.client_order_id
6597 && correction.event.trade_id == fill.trade_id
6598 && correction.voided_qty.non_zero()
6599 });
6600
6601 if corrected_closing && source.is_open() {
6602 anyhow::ensure!(
6603 !destination.is_open(),
6604 "ambiguous corrected virtual flip for order {}",
6605 fill.client_order_id
6606 );
6607 return Ok(([destination.id, source.id], corrected_closing));
6608 }
6609
6610 Ok(([source.id, destination.id], corrected_closing))
6611 }
6612
6613 fn reindex_hedging_position(&mut self, client_order_id: ClientOrderId) {
6614 match self.hedging_flip_position_ids(client_order_id) {
6615 Ok(Some([_, position_id])) => {
6616 let position = self
6617 .position_ref(&position_id)
6618 .expect("proven position is cached");
6619 let venue = position.instrument_id.venue;
6620 let strategy_id = position.strategy_id;
6621 drop(position);
6622
6623 if let Err(e) =
6624 self.add_position_id(&position_id, &venue, &client_order_id, &strategy_id)
6625 {
6626 log::error!("Failed to index virtual flip for order {client_order_id}: {e}");
6627 }
6628 }
6629 Ok(None) => {}
6630 Err(e) => {
6631 self.index.order_position.remove(&client_order_id);
6632
6633 log::error!("Cannot index virtual flip for order {client_order_id}: {e}");
6634 }
6635 }
6636 }
6637
6638 #[must_use]
6644 pub fn positions_refs(
6645 &self,
6646 venue: Option<&Venue>,
6647 instrument_id: Option<&InstrumentId>,
6648 strategy_id: Option<&StrategyId>,
6649 account_id: Option<&AccountId>,
6650 side: Option<PositionSide>,
6651 ) -> Vec<PositionRef<'_>> {
6652 let position_ids = self.position_ids(venue, instrument_id, strategy_id, account_id);
6653 self.get_positions_for_ids(&position_ids, side)
6654 }
6655
6656 #[must_use]
6660 pub fn positions(
6661 &self,
6662 venue: Option<&Venue>,
6663 instrument_id: Option<&InstrumentId>,
6664 strategy_id: Option<&StrategyId>,
6665 account_id: Option<&AccountId>,
6666 side: Option<PositionSide>,
6667 ) -> Vec<PositionRef<'_>> {
6668 self.positions_refs(venue, instrument_id, strategy_id, account_id, side)
6669 }
6670
6671 #[must_use]
6673 pub fn positions_open_refs(
6674 &self,
6675 venue: Option<&Venue>,
6676 instrument_id: Option<&InstrumentId>,
6677 strategy_id: Option<&StrategyId>,
6678 account_id: Option<&AccountId>,
6679 side: Option<PositionSide>,
6680 ) -> Vec<PositionRef<'_>> {
6681 let position_ids = self.position_open_ids(venue, instrument_id, strategy_id, account_id);
6682 self.get_positions_for_ids(&position_ids, side)
6683 }
6684
6685 #[must_use]
6689 pub fn positions_open(
6690 &self,
6691 venue: Option<&Venue>,
6692 instrument_id: Option<&InstrumentId>,
6693 strategy_id: Option<&StrategyId>,
6694 account_id: Option<&AccountId>,
6695 side: Option<PositionSide>,
6696 ) -> Vec<PositionRef<'_>> {
6697 self.positions_open_refs(venue, instrument_id, strategy_id, account_id, side)
6698 }
6699
6700 #[must_use]
6702 pub fn positions_closed_refs(
6703 &self,
6704 venue: Option<&Venue>,
6705 instrument_id: Option<&InstrumentId>,
6706 strategy_id: Option<&StrategyId>,
6707 account_id: Option<&AccountId>,
6708 side: Option<PositionSide>,
6709 ) -> Vec<PositionRef<'_>> {
6710 let position_ids = self.position_closed_ids(venue, instrument_id, strategy_id, account_id);
6711 self.get_positions_for_ids(&position_ids, side)
6712 }
6713
6714 #[must_use]
6718 pub fn positions_closed(
6719 &self,
6720 venue: Option<&Venue>,
6721 instrument_id: Option<&InstrumentId>,
6722 strategy_id: Option<&StrategyId>,
6723 account_id: Option<&AccountId>,
6724 side: Option<PositionSide>,
6725 ) -> Vec<PositionRef<'_>> {
6726 self.positions_closed_refs(venue, instrument_id, strategy_id, account_id, side)
6727 }
6728
6729 #[must_use]
6731 pub fn position_exists(&self, position_id: &PositionId) -> bool {
6732 self.index.positions.contains(position_id)
6733 }
6734
6735 #[must_use]
6737 pub fn is_position_open(&self, position_id: &PositionId) -> bool {
6738 self.index.positions_open.contains(position_id)
6739 }
6740
6741 #[must_use]
6743 pub fn is_position_closed(&self, position_id: &PositionId) -> bool {
6744 self.index.positions_closed.contains(position_id)
6745 }
6746
6747 #[must_use]
6749 pub fn positions_open_count(
6750 &self,
6751 venue: Option<&Venue>,
6752 instrument_id: Option<&InstrumentId>,
6753 strategy_id: Option<&StrategyId>,
6754 account_id: Option<&AccountId>,
6755 side: Option<PositionSide>,
6756 ) -> usize {
6757 self.count_positions_in_bucket(
6758 &self.index.positions_open,
6759 venue,
6760 instrument_id,
6761 strategy_id,
6762 account_id,
6763 side,
6764 )
6765 }
6766
6767 #[must_use]
6769 pub fn positions_closed_count(
6770 &self,
6771 venue: Option<&Venue>,
6772 instrument_id: Option<&InstrumentId>,
6773 strategy_id: Option<&StrategyId>,
6774 account_id: Option<&AccountId>,
6775 side: Option<PositionSide>,
6776 ) -> usize {
6777 self.count_positions_in_bucket(
6778 &self.index.positions_closed,
6779 venue,
6780 instrument_id,
6781 strategy_id,
6782 account_id,
6783 side,
6784 )
6785 }
6786
6787 #[must_use]
6789 pub fn positions_total_count(
6790 &self,
6791 venue: Option<&Venue>,
6792 instrument_id: Option<&InstrumentId>,
6793 strategy_id: Option<&StrategyId>,
6794 account_id: Option<&AccountId>,
6795 side: Option<PositionSide>,
6796 ) -> usize {
6797 self.count_positions_in_bucket(
6798 &self.index.positions,
6799 venue,
6800 instrument_id,
6801 strategy_id,
6802 account_id,
6803 side,
6804 )
6805 }
6806
6807 #[must_use]
6813 pub fn has_positions_open(
6814 &self,
6815 venue: Option<&Venue>,
6816 instrument_id: Option<&InstrumentId>,
6817 strategy_id: Option<&StrategyId>,
6818 account_id: Option<&AccountId>,
6819 side: Option<PositionSide>,
6820 ) -> bool {
6821 self.any_positions_in_bucket(
6822 &self.index.positions_open,
6823 venue,
6824 instrument_id,
6825 strategy_id,
6826 account_id,
6827 side,
6828 )
6829 }
6830
6831 #[must_use]
6833 pub fn has_positions_closed(
6834 &self,
6835 venue: Option<&Venue>,
6836 instrument_id: Option<&InstrumentId>,
6837 strategy_id: Option<&StrategyId>,
6838 account_id: Option<&AccountId>,
6839 side: Option<PositionSide>,
6840 ) -> bool {
6841 self.any_positions_in_bucket(
6842 &self.index.positions_closed,
6843 venue,
6844 instrument_id,
6845 strategy_id,
6846 account_id,
6847 side,
6848 )
6849 }
6850
6851 #[must_use]
6853 pub fn has_positions(
6854 &self,
6855 venue: Option<&Venue>,
6856 instrument_id: Option<&InstrumentId>,
6857 strategy_id: Option<&StrategyId>,
6858 account_id: Option<&AccountId>,
6859 side: Option<PositionSide>,
6860 ) -> bool {
6861 self.any_positions_in_bucket(
6862 &self.index.positions,
6863 venue,
6864 instrument_id,
6865 strategy_id,
6866 account_id,
6867 side,
6868 )
6869 }
6870
6871 #[must_use]
6875 pub fn strategy_id_for_order(&self, client_order_id: &ClientOrderId) -> Option<&StrategyId> {
6876 self.index.order_strategy.get(client_order_id)
6877 }
6878
6879 #[must_use]
6881 pub fn strategy_id_for_position(&self, position_id: &PositionId) -> Option<&StrategyId> {
6882 self.index.position_strategy.get(position_id)
6883 }
6884
6885 pub fn get(&self, key: &str) -> anyhow::Result<Option<&Bytes>> {
6893 check_valid_string_utf8(key, stringify!(key))?;
6894
6895 Ok(self.general.get(key))
6896 }
6897
6898 #[must_use]
6908 pub fn price(&self, instrument_id: &InstrumentId, price_type: PriceType) -> Option<Price> {
6909 match price_type {
6910 PriceType::Bid => self.quote(instrument_id).map(|quote| quote.bid_price),
6911 PriceType::Ask => self.quote(instrument_id).map(|quote| quote.ask_price),
6912 PriceType::Mid => self.quote(instrument_id).and_then(|quote| {
6913 let bid = quote.bid_price;
6914 let ask = quote.ask_price;
6915 if bid.is_undefined() || bid.is_error() || ask.is_undefined() || ask.is_error() {
6916 return None;
6917 }
6918
6919 let precision = bid.precision;
6921 check_fixed_precision(precision).ok()?;
6922
6923 #[allow(
6924 clippy::useless_conversion,
6925 reason = "i128::from is a widening conversion when PriceRaw is i64"
6926 )]
6927 let (mut bid_raw, mut ask_raw) = (i128::from(bid.raw()), i128::from(ask.raw()));
6928
6929 if precision < FIXED_PRECISION {
6930 let factor = 10_i128.pow(u32::from(FIXED_PRECISION - precision));
6931 bid_raw = (bid_raw / factor) * factor;
6932 ask_raw = (ask_raw / factor) * factor;
6933 }
6934 let sum = bid_raw.checked_add(ask_raw)?;
6935
6936 if precision < FIXED_PRECISION {
6937 let raw = PriceRaw::try_from(sum / 2).ok()?;
6938 return Price::from_raw_checked(raw, precision + 1).ok();
6939 }
6940
6941 if precision != MAX_FLOAT_PRECISION
6942 && let Some(price) = sum
6943 .checked_mul(5)
6944 .and_then(|raw| PriceRaw::try_from(raw).ok())
6945 .and_then(|raw| Price::from_raw_checked(raw, precision + 1).ok())
6946 {
6947 return Some(price);
6948 }
6949
6950 let mut raw = sum / 2;
6951 if sum % 2 != 0 && raw % 2 != 0 {
6952 raw += sum.signum();
6953 }
6954 let raw = PriceRaw::try_from(raw).ok()?;
6955 Price::from_raw_checked(raw, precision).ok()
6956 }),
6957 PriceType::Last => self.trade(instrument_id).map(|trade| trade.price),
6958 PriceType::Mark => self.mark_price(instrument_id).map(|mark| mark.value),
6959 }
6960 }
6961
6962 #[must_use]
6967 pub fn quotes(&self, instrument_id: &InstrumentId) -> Option<Vec<QuoteTick>> {
6968 self.quotes
6969 .get(instrument_id)
6970 .map(|quotes| quotes.iter().copied().collect())
6971 }
6972
6973 #[must_use]
6978 pub fn trades(&self, instrument_id: &InstrumentId) -> Option<Vec<TradeTick>> {
6979 self.trades
6980 .get(instrument_id)
6981 .map(|trades| trades.iter().copied().collect())
6982 }
6983
6984 #[must_use]
6989 pub fn mark_prices(&self, instrument_id: &InstrumentId) -> Option<Vec<MarkPriceUpdate>> {
6990 self.mark_prices
6991 .get(instrument_id)
6992 .map(|mark_prices| mark_prices.iter().copied().collect())
6993 }
6994
6995 #[must_use]
7000 pub fn index_prices(&self, instrument_id: &InstrumentId) -> Option<Vec<IndexPriceUpdate>> {
7001 self.index_prices
7002 .get(instrument_id)
7003 .map(|index_prices| index_prices.iter().copied().collect())
7004 }
7005
7006 #[must_use]
7011 pub fn funding_rates(&self, instrument_id: &InstrumentId) -> Option<Vec<FundingRateUpdate>> {
7012 self.funding_rates
7013 .get(instrument_id)
7014 .map(|funding_rates| funding_rates.iter().copied().collect())
7015 }
7016
7017 #[must_use]
7022 pub fn instrument_statuses(
7023 &self,
7024 instrument_id: &InstrumentId,
7025 ) -> Option<Vec<InstrumentStatus>> {
7026 self.instrument_statuses
7027 .get(instrument_id)
7028 .map(|statuses| statuses.iter().copied().collect())
7029 }
7030
7031 #[must_use]
7035 pub fn bars(&self, bar_type: &BarType) -> Option<Vec<Bar>> {
7036 self.bars
7037 .get(bar_type)
7038 .map(|bars| bars.iter().copied().collect())
7039 }
7040
7041 #[must_use]
7045 pub fn custom_data_history(&self, data_type: &DataType) -> Vec<CustomData> {
7046 self.custom_data
7047 .get(data_type)
7048 .map_or_default(|history| history.iter().cloned().collect())
7049 }
7050
7051 #[must_use]
7055 pub fn order_book(&self, instrument_id: &InstrumentId) -> Option<&OrderBook> {
7056 self.books.get(instrument_id)
7057 }
7058
7059 pub fn try_order_book(
7065 &self,
7066 instrument_id: &InstrumentId,
7067 ) -> Result<&OrderBook, OrderBookLookupError> {
7068 self.books
7069 .get(instrument_id)
7070 .ok_or_else(|| OrderBookLookupError::not_found(*instrument_id))
7071 }
7072
7073 #[must_use]
7075 pub fn order_book_mut(&mut self, instrument_id: &InstrumentId) -> Option<&mut OrderBook> {
7076 self.books.get_mut(instrument_id)
7077 }
7078
7079 #[must_use]
7081 pub fn own_order_book(&self, instrument_id: &InstrumentId) -> Option<&OwnOrderBook> {
7082 self.own_books.get(instrument_id)
7083 }
7084
7085 pub fn try_own_order_book(
7091 &self,
7092 instrument_id: &InstrumentId,
7093 ) -> Result<&OwnOrderBook, OwnOrderBookLookupError> {
7094 self.own_books
7095 .get(instrument_id)
7096 .ok_or_else(|| OwnOrderBookLookupError::not_found(*instrument_id))
7097 }
7098
7099 #[must_use]
7101 pub fn own_order_book_mut(
7102 &mut self,
7103 instrument_id: &InstrumentId,
7104 ) -> Option<&mut OwnOrderBook> {
7105 self.own_books.get_mut(instrument_id)
7106 }
7107
7108 #[must_use]
7110 #[inline]
7111 pub fn quote(&self, instrument_id: &InstrumentId) -> Option<&QuoteTick> {
7112 self.quotes
7113 .get(instrument_id)
7114 .and_then(|quotes| quotes.front())
7115 }
7116
7117 #[must_use]
7122 pub fn quote_at_index(&self, instrument_id: &InstrumentId, index: usize) -> Option<&QuoteTick> {
7123 self.quotes
7124 .get(instrument_id)
7125 .and_then(|quotes| quotes.get(index))
7126 }
7127
7128 #[must_use]
7130 #[inline]
7131 pub fn trade(&self, instrument_id: &InstrumentId) -> Option<&TradeTick> {
7132 self.trades
7133 .get(instrument_id)
7134 .and_then(|trades| trades.front())
7135 }
7136
7137 #[must_use]
7142 pub fn trade_at_index(&self, instrument_id: &InstrumentId, index: usize) -> Option<&TradeTick> {
7143 self.trades
7144 .get(instrument_id)
7145 .and_then(|trades| trades.get(index))
7146 }
7147
7148 #[must_use]
7150 #[inline]
7151 pub fn mark_price(&self, instrument_id: &InstrumentId) -> Option<&MarkPriceUpdate> {
7152 self.mark_prices
7153 .get(instrument_id)
7154 .and_then(|mark_prices| mark_prices.front())
7155 }
7156
7157 #[must_use]
7162 pub fn mark_price_at_index(
7163 &self,
7164 instrument_id: &InstrumentId,
7165 index: usize,
7166 ) -> Option<&MarkPriceUpdate> {
7167 self.mark_prices
7168 .get(instrument_id)
7169 .and_then(|mark_prices| mark_prices.get(index))
7170 }
7171
7172 #[must_use]
7174 pub fn index_price(&self, instrument_id: &InstrumentId) -> Option<&IndexPriceUpdate> {
7175 self.index_prices
7176 .get(instrument_id)
7177 .and_then(|index_prices| index_prices.front())
7178 }
7179
7180 #[must_use]
7185 pub fn index_price_at_index(
7186 &self,
7187 instrument_id: &InstrumentId,
7188 index: usize,
7189 ) -> Option<&IndexPriceUpdate> {
7190 self.index_prices
7191 .get(instrument_id)
7192 .and_then(|index_prices| index_prices.get(index))
7193 }
7194
7195 #[must_use]
7197 pub fn funding_rate(&self, instrument_id: &InstrumentId) -> Option<&FundingRateUpdate> {
7198 self.funding_rates
7199 .get(instrument_id)
7200 .and_then(|funding_rates| funding_rates.front())
7201 }
7202
7203 #[must_use]
7208 pub fn funding_rate_at_index(
7209 &self,
7210 instrument_id: &InstrumentId,
7211 index: usize,
7212 ) -> Option<&FundingRateUpdate> {
7213 self.funding_rates
7214 .get(instrument_id)
7215 .and_then(|funding_rates| funding_rates.get(index))
7216 }
7217
7218 #[must_use]
7220 pub fn instrument_status(&self, instrument_id: &InstrumentId) -> Option<&InstrumentStatus> {
7221 self.instrument_statuses
7222 .get(instrument_id)
7223 .and_then(|statuses| statuses.front())
7224 }
7225
7226 #[must_use]
7230 pub fn instrument_close(&self, instrument_id: &InstrumentId) -> Option<&InstrumentClose> {
7231 self.instrument_closes.get(instrument_id)
7232 }
7233
7234 #[must_use]
7236 pub fn instrument_close_ids(&self) -> Vec<&InstrumentId> {
7237 self.instrument_closes.keys().collect()
7238 }
7239
7240 #[must_use]
7242 pub fn bar(&self, bar_type: &BarType) -> Option<&Bar> {
7243 self.bars.get(bar_type).and_then(|bars| bars.front())
7244 }
7245
7246 #[must_use]
7251 pub fn bar_at_index(&self, bar_type: &BarType, index: usize) -> Option<&Bar> {
7252 self.bars.get(bar_type).and_then(|bars| bars.get(index))
7253 }
7254
7255 #[must_use]
7257 pub fn custom_data(&self, data_type: &DataType) -> Option<&CustomData> {
7258 self.custom_data_at_index(data_type, 0)
7259 }
7260
7261 #[must_use]
7266 pub fn custom_data_at_index(&self, data_type: &DataType, index: usize) -> Option<&CustomData> {
7267 self.custom_data
7268 .get(data_type)
7269 .and_then(|history| history.get(index))
7270 }
7271
7272 #[must_use]
7274 pub fn book_update_count(&self, instrument_id: &InstrumentId) -> usize {
7275 self.books
7276 .get(instrument_id)
7277 .map_or(0, |book| book.update_count) as usize
7278 }
7279
7280 #[must_use]
7282 pub fn quote_count(&self, instrument_id: &InstrumentId) -> usize {
7283 self.quotes
7284 .get(instrument_id)
7285 .map_or(0, BoundedVecDeque::len)
7286 }
7287
7288 #[must_use]
7290 pub fn trade_count(&self, instrument_id: &InstrumentId) -> usize {
7291 self.trades
7292 .get(instrument_id)
7293 .map_or(0, BoundedVecDeque::len)
7294 }
7295
7296 #[must_use]
7298 pub fn mark_price_count(&self, instrument_id: &InstrumentId) -> usize {
7299 self.mark_prices
7300 .get(instrument_id)
7301 .map_or(0, BoundedVecDeque::len)
7302 }
7303
7304 #[must_use]
7306 pub fn index_price_count(&self, instrument_id: &InstrumentId) -> usize {
7307 self.index_prices
7308 .get(instrument_id)
7309 .map_or(0, BoundedVecDeque::len)
7310 }
7311
7312 #[must_use]
7314 pub fn funding_rate_count(&self, instrument_id: &InstrumentId) -> usize {
7315 self.funding_rates
7316 .get(instrument_id)
7317 .map_or(0, BoundedVecDeque::len)
7318 }
7319
7320 #[must_use]
7322 pub fn instrument_status_count(&self, instrument_id: &InstrumentId) -> usize {
7323 self.instrument_statuses
7324 .get(instrument_id)
7325 .map_or(0, BoundedVecDeque::len)
7326 }
7327
7328 #[must_use]
7330 pub fn bar_count(&self, bar_type: &BarType) -> usize {
7331 self.bars.get(bar_type).map_or(0, BoundedVecDeque::len)
7332 }
7333
7334 #[must_use]
7336 pub fn has_order_book(&self, instrument_id: &InstrumentId) -> bool {
7337 self.books.contains_key(instrument_id)
7338 }
7339
7340 #[must_use]
7342 pub fn has_quote_ticks(&self, instrument_id: &InstrumentId) -> bool {
7343 self.quote_count(instrument_id) > 0
7344 }
7345
7346 #[must_use]
7348 pub fn has_trade_ticks(&self, instrument_id: &InstrumentId) -> bool {
7349 self.trade_count(instrument_id) > 0
7350 }
7351
7352 #[must_use]
7354 pub fn has_mark_prices(&self, instrument_id: &InstrumentId) -> bool {
7355 self.mark_price_count(instrument_id) > 0
7356 }
7357
7358 #[must_use]
7360 pub fn has_index_prices(&self, instrument_id: &InstrumentId) -> bool {
7361 self.index_price_count(instrument_id) > 0
7362 }
7363
7364 #[must_use]
7366 pub fn has_funding_rates(&self, instrument_id: &InstrumentId) -> bool {
7367 self.funding_rate_count(instrument_id) > 0
7368 }
7369
7370 #[must_use]
7372 pub fn has_instrument_statuses(&self, instrument_id: &InstrumentId) -> bool {
7373 self.instrument_status_count(instrument_id) > 0
7374 }
7375
7376 #[must_use]
7378 pub fn has_instrument_close(&self, instrument_id: &InstrumentId) -> bool {
7379 self.instrument_closes.contains_key(instrument_id)
7380 }
7381
7382 #[must_use]
7384 pub fn has_bars(&self, bar_type: &BarType) -> bool {
7385 self.bar_count(bar_type) > 0
7386 }
7387
7388 #[must_use]
7389 pub fn get_xrate(
7390 &self,
7391 venue: Venue,
7392 from_currency: Currency,
7393 to_currency: Currency,
7394 price_type: PriceType,
7395 ) -> Option<Decimal> {
7396 match self.try_get_xrate(venue, from_currency, to_currency, price_type) {
7397 Ok(rate) => rate,
7398 Err(e) => {
7399 log::error!("Failed to calculate xrate: {e}");
7400 None
7401 }
7402 }
7403 }
7404
7405 pub fn try_get_xrate(
7414 &self,
7415 venue: Venue,
7416 from_currency: Currency,
7417 to_currency: Currency,
7418 price_type: PriceType,
7419 ) -> anyhow::Result<Option<Decimal>> {
7420 if from_currency == to_currency {
7421 return Ok(Some(Decimal::ONE));
7424 }
7425
7426 let (bid_quote, ask_quote, alternates) = self.build_quote_table(&venue);
7427
7428 if alternates.is_empty() {
7429 get_exchange_rate(
7430 from_currency.code,
7431 to_currency.code,
7432 price_type,
7433 bid_quote,
7434 ask_quote,
7435 )
7436 } else {
7437 get_exchange_rate_with_alternates(
7438 from_currency.code,
7439 to_currency.code,
7440 price_type,
7441 &bid_quote,
7442 &ask_quote,
7443 &alternates,
7444 )
7445 }
7446 }
7447
7448 fn build_quote_table(&self, venue: &Venue) -> QuoteTable {
7449 let mut bid_quotes = AHashMap::new();
7450 let mut ask_quotes = AHashMap::new();
7451 let mut quote_sources = AHashMap::new();
7452 let mut alternates = Vec::new();
7453 let mut bar_quotes = None;
7454 let mut pair_buffer = String::new();
7455
7456 for (instrument_id, instrument) in &self.instruments {
7457 if instrument_id.venue != *venue {
7458 continue;
7459 }
7460
7461 let Some(base_currency) = instrument.base_currency() else {
7462 continue;
7463 };
7464
7465 let (bid_price, ask_price) = if let Some(ticks) = self.quotes.get(instrument_id) {
7466 if let Some(tick) = ticks.front() {
7467 (tick.bid_price, tick.ask_price)
7468 } else {
7469 continue; }
7471 } else {
7472 let quotes = bar_quotes.get_or_insert_with(|| self.build_bar_quote_table(venue));
7473 match (
7474 quotes.get(&(*instrument_id, PriceType::Bid)),
7475 quotes.get(&(*instrument_id, PriceType::Ask)),
7476 ) {
7477 (Some((_, bid_bar)), Some((_, ask_bar))) => (bid_bar.close, ask_bar.close),
7478 _ => continue,
7479 }
7480 };
7481
7482 let base = base_currency.code.as_str();
7483 let quote = instrument.quote_currency().code.as_str();
7484 pair_buffer.clear();
7485 pair_buffer.reserve(base.len() + 1 + quote.len());
7486 pair_buffer.push_str(base);
7487 pair_buffer.push('/');
7488 pair_buffer.push_str(quote);
7489 let pair = Ustr::from(pair_buffer.as_str());
7490 let preference = (
7491 bid_price.is_positive() && ask_price.is_positive(),
7492 instrument.instrument_class() == InstrumentClass::Spot,
7493 Reverse(*instrument_id),
7494 );
7495
7496 if quote_sources
7497 .get(&pair)
7498 .is_some_and(|current| current >= &preference)
7499 {
7500 alternates.push((
7501 preference,
7502 pair,
7503 bid_price.as_decimal(),
7504 ask_price.as_decimal(),
7505 ));
7506 continue;
7507 }
7508
7509 let previous = quote_sources.insert(pair, preference);
7510 if let (Some(preference), Some(bid), Some(ask)) = (
7511 previous,
7512 bid_quotes.insert(pair, bid_price.as_decimal()),
7513 ask_quotes.insert(pair, ask_price.as_decimal()),
7514 ) {
7515 alternates.push((preference, pair, bid, ask));
7516 }
7517 }
7518
7519 alternates.sort_unstable_by_key(|entry| Reverse(entry.0));
7520 let alternates = alternates
7521 .into_iter()
7522 .map(|(_, pair, bid, ask)| (pair, bid, ask))
7523 .collect();
7524
7525 (bid_quotes, ask_quotes, alternates)
7526 }
7527
7528 fn build_bar_quote_table(
7529 &self,
7530 venue: &Venue,
7531 ) -> AHashMap<(InstrumentId, PriceType), (&BarType, &Bar)> {
7532 let mut quotes: AHashMap<_, (&BarType, &Bar)> = AHashMap::new();
7533
7534 for (bar_type, bars) in &self.bars {
7535 let instrument_id = bar_type.instrument_id();
7536 let price_type = bar_type.spec().price_type;
7537
7538 if instrument_id.venue != *venue
7539 || !matches!(price_type, PriceType::Bid | PriceType::Ask)
7540 {
7541 continue;
7542 }
7543
7544 let Some(bar) = bars.front() else {
7545 continue;
7546 };
7547
7548 quotes
7550 .entry((instrument_id, price_type))
7551 .and_modify(|current| {
7552 if (current.1.ts_init, current.0) < (bar.ts_init, bar_type) {
7553 *current = (bar_type, bar);
7554 }
7555 })
7556 .or_insert((bar_type, bar));
7557 }
7558
7559 quotes
7560 }
7561
7562 #[must_use]
7564 pub fn get_mark_xrate(&self, from_currency: Currency, to_currency: Currency) -> Option<f64> {
7565 self.mark_xrates.get(&(from_currency, to_currency)).copied()
7566 }
7567
7568 pub fn set_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency, xrate: f64) {
7574 assert!(xrate > 0.0, "xrate was zero");
7575 self.mark_xrates.insert((from_currency, to_currency), xrate);
7576 self.mark_xrates
7577 .insert((to_currency, from_currency), 1.0 / xrate);
7578 }
7579
7580 pub fn clear_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency) {
7586 let _ = self.mark_xrates.remove(&(from_currency, to_currency));
7587 }
7588
7589 pub fn clear_mark_xrates(&mut self) {
7591 self.mark_xrates.clear();
7592 }
7593
7594 #[must_use]
7596 pub fn currency(&self, code: &Ustr) -> Option<&Currency> {
7597 self.currencies.get(code)
7598 }
7599
7600 pub fn try_currency(&self, code: &Ustr) -> Result<&Currency, CurrencyLookupError> {
7606 self.currencies
7607 .get(code)
7608 .ok_or_else(|| CurrencyLookupError::not_found(*code))
7609 }
7610
7611 #[must_use]
7615 pub fn instrument(&self, instrument_id: &InstrumentId) -> Option<&InstrumentAny> {
7616 self.instruments.get(instrument_id)
7617 }
7618
7619 pub fn try_instrument(
7625 &self,
7626 instrument_id: &InstrumentId,
7627 ) -> Result<&InstrumentAny, InstrumentLookupError> {
7628 self.instruments
7629 .get(instrument_id)
7630 .ok_or_else(|| InstrumentLookupError::not_found(*instrument_id))
7631 }
7632
7633 #[must_use]
7635 pub fn instrument_ids(&self, venue: Option<&Venue>) -> Vec<&InstrumentId> {
7636 match venue {
7637 Some(v) => self.instruments.keys().filter(|i| &i.venue == v).collect(),
7638 None => self.instruments.keys().collect(),
7639 }
7640 }
7641
7642 #[must_use]
7644 pub fn instruments(&self, venue: &Venue, underlying: Option<&Ustr>) -> Vec<&InstrumentAny> {
7645 self.instruments
7646 .values()
7647 .filter(|i| &i.id().venue == venue)
7648 .filter(|i| underlying.is_none_or(|u| i.underlying() == Some(*u)))
7649 .collect()
7650 }
7651
7652 #[must_use]
7659 pub fn instruments_by_parent(
7660 &self,
7661 venue: &Venue,
7662 root: &Ustr,
7663 class: InstrumentClass,
7664 ) -> Vec<&InstrumentAny> {
7665 self.instruments
7666 .values()
7667 .filter(|i| &i.id().venue == venue)
7668 .filter(|i| i.underlying() == Some(*root))
7669 .filter(|i| i.instrument_class() == class)
7670 .collect()
7671 }
7672
7673 #[must_use]
7675 pub fn bar_types(
7676 &self,
7677 instrument_id: Option<&InstrumentId>,
7678 price_type: Option<&PriceType>,
7679 aggregation_source: AggregationSource,
7680 ) -> Vec<&BarType> {
7681 let mut bar_types = self
7682 .bars
7683 .keys()
7684 .filter(|bar_type| bar_type.aggregation_source() == aggregation_source)
7685 .collect::<Vec<&BarType>>();
7686
7687 if let Some(instrument_id) = instrument_id {
7688 bar_types.retain(|bar_type| bar_type.instrument_id() == *instrument_id);
7689 }
7690
7691 if let Some(price_type) = price_type {
7692 bar_types.retain(|bar_type| &bar_type.spec().price_type == price_type);
7693 }
7694
7695 bar_types
7696 }
7697
7698 #[must_use]
7702 pub fn synthetic(&self, instrument_id: &InstrumentId) -> Option<&SyntheticInstrument> {
7703 self.synthetics.get(instrument_id)
7704 }
7705
7706 pub fn try_synthetic(
7712 &self,
7713 instrument_id: &InstrumentId,
7714 ) -> Result<&SyntheticInstrument, SyntheticInstrumentLookupError> {
7715 self.synthetics
7716 .get(instrument_id)
7717 .ok_or_else(|| SyntheticInstrumentLookupError::not_found(*instrument_id))
7718 }
7719
7720 #[must_use]
7722 pub fn synthetic_ids(&self) -> Vec<&InstrumentId> {
7723 self.synthetics.keys().collect()
7724 }
7725
7726 #[must_use]
7728 pub fn synthetics(&self) -> Vec<&SyntheticInstrument> {
7729 self.synthetics.values().collect()
7730 }
7731
7732 #[must_use]
7736 pub fn account_ref(&self, account_id: &AccountId) -> Option<AccountRef<'_>> {
7737 self.accounts
7738 .get(account_id)
7739 .map(|account_cell| AccountRef::new(account_cell.borrow()))
7740 }
7741
7742 #[must_use]
7746 pub fn account(&self, account_id: &AccountId) -> Option<AccountRef<'_>> {
7747 self.account_ref(account_id)
7748 }
7749
7750 pub fn try_account_ref(
7756 &self,
7757 account_id: &AccountId,
7758 ) -> Result<AccountRef<'_>, AccountLookupError> {
7759 self.accounts
7760 .get(account_id)
7761 .map(|account_cell| AccountRef::new(account_cell.borrow()))
7762 .ok_or_else(|| AccountLookupError::not_found(*account_id))
7763 }
7764
7765 pub fn try_account(
7773 &self,
7774 account_id: &AccountId,
7775 ) -> Result<AccountRef<'_>, AccountLookupError> {
7776 self.try_account_ref(account_id)
7777 }
7778
7779 #[must_use]
7789 pub fn account_mut(&mut self, account_id: &AccountId) -> Option<AccountRefMut<'_>> {
7790 self.accounts
7791 .get(account_id)
7792 .map(|account_cell| AccountRefMut::new(account_cell.borrow_mut()))
7793 }
7794
7795 #[must_use]
7801 pub fn account_owned(&self, account_id: &AccountId) -> Option<AccountAny> {
7802 self.accounts.get(account_id).and_then(|account_cell| {
7803 account_cell
7804 .try_borrow()
7805 .ok()
7806 .map(|account| account.clone())
7807 })
7808 }
7809
7810 #[must_use]
7815 pub fn account_for_venue(&self, venue: &Venue) -> Option<AccountRef<'_>> {
7816 self.account_id(venue)
7817 .and_then(|account_id| self.accounts.get(account_id))
7818 .map(|account_cell| AccountRef::new(account_cell.borrow()))
7819 }
7820
7821 #[must_use]
7827 pub fn account_for_venue_owned(&self, venue: &Venue) -> Option<AccountAny> {
7828 self.account_id(venue)
7829 .and_then(|account_id| self.accounts.get(account_id))
7830 .map(|account_cell| account_cell.borrow().clone())
7831 }
7832
7833 #[must_use]
7837 pub fn account_id(&self, venue: &Venue) -> Option<&AccountId> {
7838 let mut account_ids = self.index.venue_accounts.get(venue)?.iter();
7839 let account_id = account_ids.next()?;
7840 account_ids.next().is_none().then_some(account_id)
7841 }
7842
7843 #[must_use]
7849 pub fn accounts(&self, account_id: &AccountId) -> Vec<AccountRef<'_>> {
7850 self.accounts
7851 .values()
7852 .filter(|account_cell| &account_cell.borrow().id() == account_id)
7853 .map(|account_cell| AccountRef::new(account_cell.borrow()))
7854 .collect()
7855 }
7856
7857 #[must_use]
7859 pub fn accounts_all_owned(&self) -> Vec<AccountAny> {
7860 self.accounts
7861 .values()
7862 .map(|account_cell| account_cell.borrow().clone())
7863 .collect()
7864 }
7865
7866 pub fn update_own_order_book(&mut self, order: &OrderAny) {
7874 if !order.has_price() {
7875 return;
7876 }
7877
7878 let instrument_id = order.instrument_id();
7879
7880 if !self.own_books.contains_key(&instrument_id) {
7881 if order.is_closed() {
7882 return;
7883 }
7884
7885 self.own_books
7886 .insert(instrument_id, OwnOrderBook::new(instrument_id));
7887 }
7888
7889 let Some(own_book) = self.own_books.get_mut(&instrument_id) else {
7890 return;
7891 };
7892
7893 let own_book_order = order.to_own_book_order();
7894
7895 if order.is_closed() {
7896 if let Err(e) = own_book.delete(own_book_order) {
7897 log::debug!(
7898 "Failed to delete order {} from own book: {e}",
7899 order.client_order_id(),
7900 );
7901 } else {
7902 log::debug!("Deleted order {} from own book", order.client_order_id());
7903 }
7904 } else {
7905 if let Err(e) = own_book.update(own_book_order) {
7907 log::debug!(
7908 "Failed to update order {} in own book: {e}; inserting instead",
7909 order.client_order_id(),
7910 );
7911 own_book.add(own_book_order);
7912 }
7913 log::debug!("Updated order {} in own book", order.client_order_id());
7914 }
7915 }
7916
7917 pub fn force_remove_from_own_order_book(&mut self, client_order_id: &ClientOrderId) {
7923 let Some(order_cell) = self.orders.get(client_order_id) else {
7924 return;
7925 };
7926 let order = order_cell.borrow();
7927 let instrument_id = order.instrument_id();
7928 let own_book_order = if order.has_price() {
7929 Some(order.to_own_book_order())
7930 } else {
7931 None
7932 };
7933 drop(order);
7934
7935 self.index.orders_open.remove(client_order_id);
7936 self.index.orders_pending_cancel.remove(client_order_id);
7937 self.index.orders_inflight.remove(client_order_id);
7938 self.index.orders_emulated.remove(client_order_id);
7939 self.index.orders_active_local.remove(client_order_id);
7940
7941 if let Some(own_book) = self.own_books.get_mut(&instrument_id)
7942 && let Some(own_book_order) = own_book_order
7943 {
7944 if let Err(e) = own_book.delete(own_book_order) {
7945 log::debug!("Could not force delete {client_order_id} from own book: {e}");
7946 } else {
7947 log::debug!("Force deleted {client_order_id} from own book");
7948 }
7949 }
7950
7951 self.index.orders_closed.insert(*client_order_id);
7952 }
7953
7954 pub fn audit_own_order_books(&mut self) {
7959 log::debug!("Starting own books audit");
7960 let start = std::time::Instant::now();
7961
7962 let valid_order_ids: AHashSet<ClientOrderId> = self
7963 .index
7964 .orders_open
7965 .iter()
7966 .chain(&self.index.orders_inflight)
7967 .chain(&self.index.orders_active_local)
7968 .copied()
7969 .collect();
7970
7971 for own_book in self.own_books.values_mut() {
7972 own_book.audit_open_orders(&valid_order_ids);
7973 }
7974
7975 log::debug!("Completed own books audit in {:?}", start.elapsed());
7976 }
7977}
7978
7979type QuoteTable = (
7980 AHashMap<Ustr, Decimal>,
7981 AHashMap<Ustr, Decimal>,
7982 Vec<(Ustr, Decimal, Decimal)>,
7983);
7984
7985const POSITION_OMS_KEY_PREFIX: &str = "position_oms:";
7986const INTEGRITY_FAILURE: &str = "Integrity failure";
7987
7988#[cfg_attr(
7989 not(feature = "defi"),
7990 expect(
7991 clippy::unnecessary_wraps,
7992 reason = "only DeFi integrity rejections propagate"
7993 )
7994)]
7995fn handle_persistence_result(
7996 operation: impl Display,
7997 result: anyhow::Result<()>,
7998) -> anyhow::Result<()> {
7999 if let Err(e) = result {
8000 #[cfg(feature = "defi")]
8001 if e.is::<IntegrityError>() {
8002 return Err(e);
8003 }
8004
8005 log::error!("Failed to {operation}: {e:#}");
8006 }
8007
8008 Ok(())
8009}
8010
8011fn position_oms_key(position_id: PositionId) -> String {
8012 format!("{POSITION_OMS_KEY_PREFIX}{position_id}")
8013}
8014
8015fn resolve_position_oms(position: &Position, oms_type: OmsType) -> OmsType {
8016 if oms_type == OmsType::Unspecified
8017 && position.id.as_str() == format!("{}-{}", position.instrument_id, position.strategy_id)
8018 {
8019 OmsType::Netting
8020 } else {
8021 oms_type
8022 }
8023}
8024
8025fn insert_bar(bars: &mut BoundedVecDeque<Bar>, bar: Bar) {
8030 match bars.front() {
8031 None => bars.push_front(bar),
8032 Some(front) => match bar.ts_event.cmp(&front.ts_event) {
8033 Ordering::Greater => bars.push_front(bar),
8034 Ordering::Equal => {
8035 if bar.bar_type.spec().is_time_aggregated() {
8036 bars.replace_front(bar);
8037 } else {
8038 bars.push_front(bar);
8039 }
8040 }
8041 Ordering::Less => log::debug!(
8042 "Skipping bar {bar} with `ts_event` older than last bar `ts_event` {}",
8043 front.ts_event,
8044 ),
8045 },
8046 }
8047}
8048
8049fn insert_bar_historical(bars: &mut BoundedVecDeque<Bar>, bar: Bar) {
8054 let index = bars.partition_point(|cached| cached.ts_event > bar.ts_event);
8055
8056 if bar.bar_type.spec().is_time_aggregated()
8057 && bars
8058 .get(index)
8059 .is_some_and(|cached| cached.ts_event == bar.ts_event)
8060 {
8061 bars.replace(index, bar);
8062 } else {
8063 bars.insert(index, bar);
8064 }
8065}