1pub mod config;
21pub mod database;
22
23mod index;
24
25#[cfg(test)]
26mod tests;
27
28use std::{
29 collections::VecDeque,
30 fmt::Debug,
31 time::{SystemTime, UNIX_EPOCH},
32};
33
34use ahash::{AHashMap, AHashSet};
35use bytes::Bytes;
36pub use config::CacheConfig; use database::{CacheDatabaseAdapter, CacheMap};
38use index::CacheIndex;
39use nautilus_core::{
40 UUID4, UnixNanos,
41 correctness::{
42 check_key_not_in_map, check_predicate_false, check_slice_not_empty, check_valid_string,
43 },
44 datetime::secs_to_nanos,
45};
46#[cfg(feature = "defi")]
47use nautilus_model::defi::Pool;
48use nautilus_model::{
49 accounts::{Account, AccountAny},
50 data::{
51 Bar, BarType, FundingRateUpdate, GreeksData, IndexPriceUpdate, MarkPriceUpdate, QuoteTick,
52 TradeTick, YieldCurveData,
53 },
54 enums::{AggregationSource, OmsType, OrderSide, PositionSide, PriceType, TriggerType},
55 identifiers::{
56 AccountId, ClientId, ClientOrderId, ComponentId, ExecAlgorithmId, InstrumentId,
57 OrderListId, PositionId, StrategyId, Venue, VenueOrderId,
58 },
59 instruments::{Instrument, InstrumentAny, SyntheticInstrument},
60 orderbook::{
61 OrderBook,
62 own::{OwnOrderBook, should_handle_own_book_order},
63 },
64 orders::{Order, OrderAny, OrderList},
65 position::Position,
66 types::{Currency, Money, Price, Quantity},
67};
68use ustr::Ustr;
69
70use crate::xrate::get_exchange_rate;
71
72#[cfg_attr(
74 feature = "python",
75 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.common", unsendable)
76)]
77pub struct Cache {
78 config: CacheConfig,
79 index: CacheIndex,
80 database: Option<Box<dyn CacheDatabaseAdapter>>,
81 general: AHashMap<String, Bytes>,
82 currencies: AHashMap<Ustr, Currency>,
83 instruments: AHashMap<InstrumentId, InstrumentAny>,
84 synthetics: AHashMap<InstrumentId, SyntheticInstrument>,
85 books: AHashMap<InstrumentId, OrderBook>,
86 own_books: AHashMap<InstrumentId, OwnOrderBook>,
87 quotes: AHashMap<InstrumentId, VecDeque<QuoteTick>>,
88 trades: AHashMap<InstrumentId, VecDeque<TradeTick>>,
89 mark_xrates: AHashMap<(Currency, Currency), f64>,
90 mark_prices: AHashMap<InstrumentId, VecDeque<MarkPriceUpdate>>,
91 index_prices: AHashMap<InstrumentId, VecDeque<IndexPriceUpdate>>,
92 funding_rates: AHashMap<InstrumentId, FundingRateUpdate>,
93 bars: AHashMap<BarType, VecDeque<Bar>>,
94 greeks: AHashMap<InstrumentId, GreeksData>,
95 yield_curves: AHashMap<String, YieldCurveData>,
96 accounts: AHashMap<AccountId, AccountAny>,
97 orders: AHashMap<ClientOrderId, OrderAny>,
98 order_lists: AHashMap<OrderListId, OrderList>,
99 positions: AHashMap<PositionId, Position>,
100 position_snapshots: AHashMap<PositionId, Bytes>,
101 #[cfg(feature = "defi")]
102 pools: AHashMap<InstrumentId, Pool>,
103}
104
105impl Debug for Cache {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct(stringify!(Cache))
108 .field("config", &self.config)
109 .field("index", &self.index)
110 .field("general", &self.general)
111 .field("currencies", &self.currencies)
112 .field("instruments", &self.instruments)
113 .field("synthetics", &self.synthetics)
114 .field("books", &self.books)
115 .field("own_books", &self.own_books)
116 .field("quotes", &self.quotes)
117 .field("trades", &self.trades)
118 .field("mark_xrates", &self.mark_xrates)
119 .field("mark_prices", &self.mark_prices)
120 .field("index_prices", &self.index_prices)
121 .field("funding_rates", &self.funding_rates)
122 .field("bars", &self.bars)
123 .field("greeks", &self.greeks)
124 .field("yield_curves", &self.yield_curves)
125 .field("accounts", &self.accounts)
126 .field("orders", &self.orders)
127 .field("order_lists", &self.order_lists)
128 .field("positions", &self.positions)
129 .field("position_snapshots", &self.position_snapshots)
130 .finish()
131 }
132}
133
134impl Default for Cache {
135 fn default() -> Self {
137 Self::new(Some(CacheConfig::default()), None)
138 }
139}
140
141impl Cache {
142 #[must_use]
144 pub fn new(
148 config: Option<CacheConfig>,
149 database: Option<Box<dyn CacheDatabaseAdapter>>,
150 ) -> Self {
151 Self {
152 config: config.unwrap_or_default(),
153 index: CacheIndex::default(),
154 database,
155 general: AHashMap::new(),
156 currencies: AHashMap::new(),
157 instruments: AHashMap::new(),
158 synthetics: AHashMap::new(),
159 books: AHashMap::new(),
160 own_books: AHashMap::new(),
161 quotes: AHashMap::new(),
162 trades: AHashMap::new(),
163 mark_xrates: AHashMap::new(),
164 mark_prices: AHashMap::new(),
165 index_prices: AHashMap::new(),
166 funding_rates: AHashMap::new(),
167 bars: AHashMap::new(),
168 greeks: AHashMap::new(),
169 yield_curves: AHashMap::new(),
170 accounts: AHashMap::new(),
171 orders: AHashMap::new(),
172 order_lists: AHashMap::new(),
173 positions: AHashMap::new(),
174 position_snapshots: AHashMap::new(),
175 #[cfg(feature = "defi")]
176 pools: AHashMap::new(),
177 }
178 }
179
180 #[must_use]
182 pub fn memory_address(&self) -> String {
183 format!("{:?}", std::ptr::from_ref(self))
184 }
185
186 pub fn cache_general(&mut self) -> anyhow::Result<()> {
194 self.general = match &mut self.database {
195 Some(db) => db.load()?,
196 None => AHashMap::new(),
197 };
198
199 log::info!(
200 "Cached {} general object(s) from database",
201 self.general.len()
202 );
203 Ok(())
204 }
205
206 pub async fn cache_all(&mut self) -> anyhow::Result<()> {
212 let cache_map = match &self.database {
213 Some(db) => db.load_all().await?,
214 None => CacheMap::default(),
215 };
216
217 self.currencies = cache_map.currencies;
218 self.instruments = cache_map.instruments;
219 self.synthetics = cache_map.synthetics;
220 self.accounts = cache_map.accounts;
221 self.orders = cache_map.orders;
222 self.positions = cache_map.positions;
223 Ok(())
224 }
225
226 pub async fn cache_currencies(&mut self) -> anyhow::Result<()> {
232 self.currencies = match &mut self.database {
233 Some(db) => db.load_currencies().await?,
234 None => AHashMap::new(),
235 };
236
237 log::info!("Cached {} currencies from database", self.general.len());
238 Ok(())
239 }
240
241 pub async fn cache_instruments(&mut self) -> anyhow::Result<()> {
247 self.instruments = match &mut self.database {
248 Some(db) => db.load_instruments().await?,
249 None => AHashMap::new(),
250 };
251
252 log::info!("Cached {} instruments from database", self.general.len());
253 Ok(())
254 }
255
256 pub async fn cache_synthetics(&mut self) -> anyhow::Result<()> {
262 self.synthetics = match &mut self.database {
263 Some(db) => db.load_synthetics().await?,
264 None => AHashMap::new(),
265 };
266
267 log::info!(
268 "Cached {} synthetic instruments from database",
269 self.general.len()
270 );
271 Ok(())
272 }
273
274 pub async fn cache_accounts(&mut self) -> anyhow::Result<()> {
280 self.accounts = match &mut self.database {
281 Some(db) => db.load_accounts().await?,
282 None => AHashMap::new(),
283 };
284
285 log::info!(
286 "Cached {} synthetic instruments from database",
287 self.general.len()
288 );
289 Ok(())
290 }
291
292 pub async fn cache_orders(&mut self) -> anyhow::Result<()> {
298 self.orders = match &mut self.database {
299 Some(db) => db.load_orders().await?,
300 None => AHashMap::new(),
301 };
302
303 log::info!("Cached {} orders from database", self.general.len());
304 Ok(())
305 }
306
307 pub async fn cache_positions(&mut self) -> anyhow::Result<()> {
313 self.positions = match &mut self.database {
314 Some(db) => db.load_positions().await?,
315 None => AHashMap::new(),
316 };
317
318 log::info!("Cached {} positions from database", self.general.len());
319 Ok(())
320 }
321
322 pub fn build_index(&mut self) {
324 log::debug!("Building index");
325
326 for account_id in self.accounts.keys() {
328 self.index
329 .venue_account
330 .insert(account_id.get_issuer(), *account_id);
331 }
332
333 for (client_order_id, order) in &self.orders {
335 let instrument_id = order.instrument_id();
336 let venue = instrument_id.venue;
337 let strategy_id = order.strategy_id();
338
339 self.index
341 .venue_orders
342 .entry(venue)
343 .or_default()
344 .insert(*client_order_id);
345
346 if let Some(venue_order_id) = order.venue_order_id() {
348 self.index
349 .venue_order_ids
350 .insert(venue_order_id, *client_order_id);
351 }
352
353 if let Some(position_id) = order.position_id() {
355 self.index
356 .order_position
357 .insert(*client_order_id, position_id);
358 }
359
360 self.index
362 .order_strategy
363 .insert(*client_order_id, order.strategy_id());
364
365 self.index
367 .instrument_orders
368 .entry(instrument_id)
369 .or_default()
370 .insert(*client_order_id);
371
372 self.index
374 .strategy_orders
375 .entry(strategy_id)
376 .or_default()
377 .insert(*client_order_id);
378
379 if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
381 self.index
382 .exec_algorithm_orders
383 .entry(exec_algorithm_id)
384 .or_default()
385 .insert(*client_order_id);
386 }
387
388 if let Some(exec_spawn_id) = order.exec_spawn_id() {
390 self.index
391 .exec_spawn_orders
392 .entry(exec_spawn_id)
393 .or_default()
394 .insert(*client_order_id);
395 }
396
397 self.index.orders.insert(*client_order_id);
399
400 if order.is_open() {
402 self.index.orders_open.insert(*client_order_id);
403 }
404
405 if order.is_closed() {
407 self.index.orders_closed.insert(*client_order_id);
408 }
409
410 if let Some(emulation_trigger) = order.emulation_trigger()
412 && emulation_trigger != TriggerType::NoTrigger
413 && !order.is_closed()
414 {
415 self.index.orders_emulated.insert(*client_order_id);
416 }
417
418 if order.is_inflight() {
420 self.index.orders_inflight.insert(*client_order_id);
421 }
422
423 self.index.strategies.insert(strategy_id);
425
426 if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
428 self.index.exec_algorithms.insert(exec_algorithm_id);
429 }
430 }
431
432 for (position_id, position) in &self.positions {
434 let instrument_id = position.instrument_id;
435 let venue = instrument_id.venue;
436 let strategy_id = position.strategy_id;
437
438 self.index
440 .venue_positions
441 .entry(venue)
442 .or_default()
443 .insert(*position_id);
444
445 self.index
447 .position_strategy
448 .insert(*position_id, position.strategy_id);
449
450 self.index
452 .position_orders
453 .entry(*position_id)
454 .or_default()
455 .extend(position.client_order_ids().into_iter());
456
457 self.index
459 .instrument_positions
460 .entry(instrument_id)
461 .or_default()
462 .insert(*position_id);
463
464 self.index
466 .strategy_positions
467 .entry(strategy_id)
468 .or_default()
469 .insert(*position_id);
470
471 self.index.positions.insert(*position_id);
473
474 if position.is_open() {
476 self.index.positions_open.insert(*position_id);
477 }
478
479 if position.is_closed() {
481 self.index.positions_closed.insert(*position_id);
482 }
483
484 self.index.strategies.insert(strategy_id);
486 }
487 }
488
489 #[must_use]
491 pub const fn has_backing(&self) -> bool {
492 self.config.database.is_some()
493 }
494
495 #[must_use]
497 pub fn calculate_unrealized_pnl(&self, position: &Position) -> Option<Money> {
498 let quote = if let Some(quote) = self.quote(&position.instrument_id) {
499 quote
500 } else {
501 log::warn!(
502 "Cannot calculate unrealized PnL for {}, no quotes for {}",
503 position.id,
504 position.instrument_id
505 );
506 return None;
507 };
508
509 let last = match position.side {
510 PositionSide::Flat | PositionSide::NoPositionSide => {
511 return Some(Money::new(0.0, position.settlement_currency));
512 }
513 PositionSide::Long => quote.ask_price,
514 PositionSide::Short => quote.bid_price,
515 };
516
517 Some(position.unrealized_pnl(last))
518 }
519
520 #[must_use]
529 pub fn check_integrity(&mut self) -> bool {
530 let mut error_count = 0;
531 let failure = "Integrity failure";
532
533 let timestamp_us = SystemTime::now()
535 .duration_since(UNIX_EPOCH)
536 .expect("Time went backwards")
537 .as_micros();
538
539 log::info!("Checking data integrity");
540
541 for account_id in self.accounts.keys() {
543 if !self
544 .index
545 .venue_account
546 .contains_key(&account_id.get_issuer())
547 {
548 log::error!(
549 "{failure} in accounts: {account_id} not found in `self.index.venue_account`",
550 );
551 error_count += 1;
552 }
553 }
554
555 for (client_order_id, order) in &self.orders {
556 if !self.index.order_strategy.contains_key(client_order_id) {
557 log::error!(
558 "{failure} in orders: {client_order_id} not found in `self.index.order_strategy`"
559 );
560 error_count += 1;
561 }
562 if !self.index.orders.contains(client_order_id) {
563 log::error!(
564 "{failure} in orders: {client_order_id} not found in `self.index.orders`",
565 );
566 error_count += 1;
567 }
568 if order.is_inflight() && !self.index.orders_inflight.contains(client_order_id) {
569 log::error!(
570 "{failure} in orders: {client_order_id} not found in `self.index.orders_inflight`",
571 );
572 error_count += 1;
573 }
574 if order.is_open() && !self.index.orders_open.contains(client_order_id) {
575 log::error!(
576 "{failure} in orders: {client_order_id} not found in `self.index.orders_open`",
577 );
578 error_count += 1;
579 }
580 if order.is_closed() && !self.index.orders_closed.contains(client_order_id) {
581 log::error!(
582 "{failure} in orders: {client_order_id} not found in `self.index.orders_closed`",
583 );
584 error_count += 1;
585 }
586 if let Some(exec_algorithm_id) = order.exec_algorithm_id() {
587 if !self
588 .index
589 .exec_algorithm_orders
590 .contains_key(&exec_algorithm_id)
591 {
592 log::error!(
593 "{failure} in orders: {client_order_id} not found in `self.index.exec_algorithm_orders`",
594 );
595 error_count += 1;
596 }
597 if order.exec_spawn_id().is_none()
598 && !self.index.exec_spawn_orders.contains_key(client_order_id)
599 {
600 log::error!(
601 "{failure} in orders: {client_order_id} not found in `self.index.exec_spawn_orders`",
602 );
603 error_count += 1;
604 }
605 }
606 }
607
608 for (position_id, position) in &self.positions {
609 if !self.index.position_strategy.contains_key(position_id) {
610 log::error!(
611 "{failure} in positions: {position_id} not found in `self.index.position_strategy`",
612 );
613 error_count += 1;
614 }
615 if !self.index.position_orders.contains_key(position_id) {
616 log::error!(
617 "{failure} in positions: {position_id} not found in `self.index.position_orders`",
618 );
619 error_count += 1;
620 }
621 if !self.index.positions.contains(position_id) {
622 log::error!(
623 "{failure} in positions: {position_id} not found in `self.index.positions`",
624 );
625 error_count += 1;
626 }
627 if position.is_open() && !self.index.positions_open.contains(position_id) {
628 log::error!(
629 "{failure} in positions: {position_id} not found in `self.index.positions_open`",
630 );
631 error_count += 1;
632 }
633 if position.is_closed() && !self.index.positions_closed.contains(position_id) {
634 log::error!(
635 "{failure} in positions: {position_id} not found in `self.index.positions_closed`",
636 );
637 error_count += 1;
638 }
639 }
640
641 for account_id in self.index.venue_account.values() {
643 if !self.accounts.contains_key(account_id) {
644 log::error!(
645 "{failure} in `index.venue_account`: {account_id} not found in `self.accounts`",
646 );
647 error_count += 1;
648 }
649 }
650
651 for client_order_id in self.index.venue_order_ids.values() {
652 if !self.orders.contains_key(client_order_id) {
653 log::error!(
654 "{failure} in `index.venue_order_ids`: {client_order_id} not found in `self.orders`",
655 );
656 error_count += 1;
657 }
658 }
659
660 for client_order_id in self.index.client_order_ids.keys() {
661 if !self.orders.contains_key(client_order_id) {
662 log::error!(
663 "{failure} in `index.client_order_ids`: {client_order_id} not found in `self.orders`",
664 );
665 error_count += 1;
666 }
667 }
668
669 for client_order_id in self.index.order_position.keys() {
670 if !self.orders.contains_key(client_order_id) {
671 log::error!(
672 "{failure} in `index.order_position`: {client_order_id} not found in `self.orders`",
673 );
674 error_count += 1;
675 }
676 }
677
678 for client_order_id in self.index.order_strategy.keys() {
680 if !self.orders.contains_key(client_order_id) {
681 log::error!(
682 "{failure} in `index.order_strategy`: {client_order_id} not found in `self.orders`",
683 );
684 error_count += 1;
685 }
686 }
687
688 for position_id in self.index.position_strategy.keys() {
689 if !self.positions.contains_key(position_id) {
690 log::error!(
691 "{failure} in `index.position_strategy`: {position_id} not found in `self.positions`",
692 );
693 error_count += 1;
694 }
695 }
696
697 for position_id in self.index.position_orders.keys() {
698 if !self.positions.contains_key(position_id) {
699 log::error!(
700 "{failure} in `index.position_orders`: {position_id} not found in `self.positions`",
701 );
702 error_count += 1;
703 }
704 }
705
706 for (instrument_id, client_order_ids) in &self.index.instrument_orders {
707 for client_order_id in client_order_ids {
708 if !self.orders.contains_key(client_order_id) {
709 log::error!(
710 "{failure} in `index.instrument_orders`: {instrument_id} not found in `self.orders`",
711 );
712 error_count += 1;
713 }
714 }
715 }
716
717 for instrument_id in self.index.instrument_positions.keys() {
718 if !self.index.instrument_orders.contains_key(instrument_id) {
719 log::error!(
720 "{failure} in `index.instrument_positions`: {instrument_id} not found in `index.instrument_orders`",
721 );
722 error_count += 1;
723 }
724 }
725
726 for client_order_ids in self.index.strategy_orders.values() {
727 for client_order_id in client_order_ids {
728 if !self.orders.contains_key(client_order_id) {
729 log::error!(
730 "{failure} in `index.strategy_orders`: {client_order_id} not found in `self.orders`",
731 );
732 error_count += 1;
733 }
734 }
735 }
736
737 for position_ids in self.index.strategy_positions.values() {
738 for position_id in position_ids {
739 if !self.positions.contains_key(position_id) {
740 log::error!(
741 "{failure} in `index.strategy_positions`: {position_id} not found in `self.positions`",
742 );
743 error_count += 1;
744 }
745 }
746 }
747
748 for client_order_id in &self.index.orders {
749 if !self.orders.contains_key(client_order_id) {
750 log::error!(
751 "{failure} in `index.orders`: {client_order_id} not found in `self.orders`",
752 );
753 error_count += 1;
754 }
755 }
756
757 for client_order_id in &self.index.orders_emulated {
758 if !self.orders.contains_key(client_order_id) {
759 log::error!(
760 "{failure} in `index.orders_emulated`: {client_order_id} not found in `self.orders`",
761 );
762 error_count += 1;
763 }
764 }
765
766 for client_order_id in &self.index.orders_inflight {
767 if !self.orders.contains_key(client_order_id) {
768 log::error!(
769 "{failure} in `index.orders_inflight`: {client_order_id} not found in `self.orders`",
770 );
771 error_count += 1;
772 }
773 }
774
775 for client_order_id in &self.index.orders_open {
776 if !self.orders.contains_key(client_order_id) {
777 log::error!(
778 "{failure} in `index.orders_open`: {client_order_id} not found in `self.orders`",
779 );
780 error_count += 1;
781 }
782 }
783
784 for client_order_id in &self.index.orders_closed {
785 if !self.orders.contains_key(client_order_id) {
786 log::error!(
787 "{failure} in `index.orders_closed`: {client_order_id} not found in `self.orders`",
788 );
789 error_count += 1;
790 }
791 }
792
793 for position_id in &self.index.positions {
794 if !self.positions.contains_key(position_id) {
795 log::error!(
796 "{failure} in `index.positions`: {position_id} not found in `self.positions`",
797 );
798 error_count += 1;
799 }
800 }
801
802 for position_id in &self.index.positions_open {
803 if !self.positions.contains_key(position_id) {
804 log::error!(
805 "{failure} in `index.positions_open`: {position_id} not found in `self.positions`",
806 );
807 error_count += 1;
808 }
809 }
810
811 for position_id in &self.index.positions_closed {
812 if !self.positions.contains_key(position_id) {
813 log::error!(
814 "{failure} in `index.positions_closed`: {position_id} not found in `self.positions`",
815 );
816 error_count += 1;
817 }
818 }
819
820 for strategy_id in &self.index.strategies {
821 if !self.index.strategy_orders.contains_key(strategy_id) {
822 log::error!(
823 "{failure} in `index.strategies`: {strategy_id} not found in `index.strategy_orders`",
824 );
825 error_count += 1;
826 }
827 }
828
829 for exec_algorithm_id in &self.index.exec_algorithms {
830 if !self
831 .index
832 .exec_algorithm_orders
833 .contains_key(exec_algorithm_id)
834 {
835 log::error!(
836 "{failure} in `index.exec_algorithms`: {exec_algorithm_id} not found in `index.exec_algorithm_orders`",
837 );
838 error_count += 1;
839 }
840 }
841
842 let total_us = SystemTime::now()
843 .duration_since(UNIX_EPOCH)
844 .expect("Time went backwards")
845 .as_micros()
846 - timestamp_us;
847
848 if error_count == 0 {
849 log::info!("Integrity check passed in {total_us}μs");
850 true
851 } else {
852 log::error!(
853 "Integrity check failed with {error_count} error{} in {total_us}μs",
854 if error_count == 1 { "" } else { "s" },
855 );
856 false
857 }
858 }
859
860 #[must_use]
864 pub fn check_residuals(&self) -> bool {
865 log::debug!("Checking residuals");
866
867 let mut residuals = false;
868
869 for order in self.orders_open(None, None, None, None) {
871 residuals = true;
872 log::warn!("Residual {order:?}");
873 }
874
875 for position in self.positions_open(None, None, None, None) {
877 residuals = true;
878 log::warn!("Residual {position}");
879 }
880
881 residuals
882 }
883
884 pub fn purge_closed_orders(&mut self, ts_now: UnixNanos, buffer_secs: u64) {
890 log::debug!(
891 "Purging closed orders{}",
892 if buffer_secs > 0 {
893 format!(" with buffer_secs={buffer_secs}")
894 } else {
895 String::new()
896 }
897 );
898
899 let buffer_ns = secs_to_nanos(buffer_secs as f64);
900
901 'outer: for client_order_id in self.index.orders_closed.clone() {
902 if let Some(order) = self.orders.get(&client_order_id)
903 && let Some(ts_closed) = order.ts_closed()
904 && ts_closed + buffer_ns <= ts_now
905 {
906 if let Some(linked_order_ids) = order.linked_order_ids() {
908 for linked_order_id in linked_order_ids {
909 if let Some(linked_order) = self.orders.get(linked_order_id)
910 && linked_order.is_open()
911 {
912 continue 'outer;
914 }
915 }
916 }
917
918 self.purge_order(client_order_id);
919 }
920 }
921 }
922
923 pub fn purge_closed_positions(&mut self, ts_now: UnixNanos, buffer_secs: u64) {
925 log::debug!(
926 "Purging closed positions{}",
927 if buffer_secs > 0 {
928 format!(" with buffer_secs={buffer_secs}")
929 } else {
930 String::new()
931 }
932 );
933
934 let buffer_ns = secs_to_nanos(buffer_secs as f64);
935
936 for position_id in self.index.positions_closed.clone() {
937 if let Some(position) = self.positions.get(&position_id)
938 && let Some(ts_closed) = position.ts_closed
939 && ts_closed + buffer_ns <= ts_now
940 {
941 self.purge_position(position_id);
942 }
943 }
944 }
945
946 pub fn purge_order(&mut self, client_order_id: ClientOrderId) {
950 if let Some(position_id) = self.index.order_position.get(&client_order_id)
952 && let Some(position) = self.positions.get_mut(position_id)
953 {
954 position.purge_events_for_order(client_order_id);
955 }
956
957 if let Some(order) = self.orders.remove(&client_order_id) {
958 if let Some(venue_orders) = self
960 .index
961 .venue_orders
962 .get_mut(&order.instrument_id().venue)
963 {
964 venue_orders.remove(&client_order_id);
965 }
966
967 if let Some(venue_order_id) = order.venue_order_id() {
969 self.index.venue_order_ids.remove(&venue_order_id);
970 }
971
972 if let Some(instrument_orders) =
974 self.index.instrument_orders.get_mut(&order.instrument_id())
975 {
976 instrument_orders.remove(&client_order_id);
977 }
978
979 if let Some(position_id) = order.position_id()
981 && let Some(position_orders) = self.index.position_orders.get_mut(&position_id)
982 {
983 position_orders.remove(&client_order_id);
984 }
985
986 if let Some(exec_algorithm_id) = order.exec_algorithm_id()
988 && let Some(exec_algorithm_orders) =
989 self.index.exec_algorithm_orders.get_mut(&exec_algorithm_id)
990 {
991 exec_algorithm_orders.remove(&client_order_id);
992 }
993
994 log::info!("Purged order {client_order_id}");
995 } else {
996 log::warn!("Order {client_order_id} not found when purging");
997 }
998
999 self.index.order_position.remove(&client_order_id);
1001 self.index.order_strategy.remove(&client_order_id);
1002 self.index.order_client.remove(&client_order_id);
1003 self.index.client_order_ids.remove(&client_order_id);
1004 self.index.exec_spawn_orders.remove(&client_order_id);
1005 self.index.orders.remove(&client_order_id);
1006 self.index.orders_closed.remove(&client_order_id);
1007 self.index.orders_emulated.remove(&client_order_id);
1008 self.index.orders_inflight.remove(&client_order_id);
1009 self.index.orders_pending_cancel.remove(&client_order_id);
1010 }
1011
1012 pub fn purge_position(&mut self, position_id: PositionId) {
1014 if let Some(position) = self.positions.remove(&position_id) {
1015 if let Some(venue_positions) = self
1017 .index
1018 .venue_positions
1019 .get_mut(&position.instrument_id.venue)
1020 {
1021 venue_positions.remove(&position_id);
1022 }
1023
1024 if let Some(instrument_positions) = self
1026 .index
1027 .instrument_positions
1028 .get_mut(&position.instrument_id)
1029 {
1030 instrument_positions.remove(&position_id);
1031 }
1032
1033 if let Some(strategy_positions) =
1035 self.index.strategy_positions.get_mut(&position.strategy_id)
1036 {
1037 strategy_positions.remove(&position_id);
1038 }
1039
1040 for client_order_id in position.client_order_ids() {
1042 self.index.order_position.remove(&client_order_id);
1043 }
1044
1045 log::info!("Purged position {position_id}");
1046 } else {
1047 log::warn!("Position {position_id} not found when purging");
1048 }
1049
1050 self.index.position_strategy.remove(&position_id);
1052 self.index.position_orders.remove(&position_id);
1053 self.index.positions.remove(&position_id);
1054 self.index.positions_open.remove(&position_id);
1055 self.index.positions_closed.remove(&position_id);
1056 }
1057
1058 pub fn purge_account_events(&mut self, ts_now: UnixNanos, lookback_secs: u64) {
1063 log::debug!(
1064 "Purging account events{}",
1065 if lookback_secs > 0 {
1066 format!(" with lookback_secs={lookback_secs}")
1067 } else {
1068 String::new()
1069 }
1070 );
1071
1072 for account in self.accounts.values_mut() {
1073 let event_count = account.event_count();
1074 account.purge_account_events(ts_now, lookback_secs);
1075 let count_diff = event_count - account.event_count();
1076 if count_diff > 0 {
1077 log::info!(
1078 "Purged {} event(s) from account {}",
1079 count_diff,
1080 account.id()
1081 );
1082 }
1083 }
1084 }
1085
1086 pub fn clear_index(&mut self) {
1088 self.index.clear();
1089 log::debug!("Cleared index");
1090 }
1091
1092 pub fn reset(&mut self) {
1096 log::debug!("Resetting cache");
1097
1098 self.general.clear();
1099 self.currencies.clear();
1100 self.instruments.clear();
1101 self.synthetics.clear();
1102 self.books.clear();
1103 self.own_books.clear();
1104 self.quotes.clear();
1105 self.trades.clear();
1106 self.mark_xrates.clear();
1107 self.mark_prices.clear();
1108 self.index_prices.clear();
1109 self.bars.clear();
1110 self.accounts.clear();
1111 self.orders.clear();
1112 self.order_lists.clear();
1113 self.positions.clear();
1114 self.position_snapshots.clear();
1115 self.greeks.clear();
1116 self.yield_curves.clear();
1117
1118 #[cfg(feature = "defi")]
1119 self.pools.clear();
1120
1121 self.clear_index();
1122
1123 log::info!("Reset cache");
1124 }
1125
1126 pub fn dispose(&mut self) {
1132 if let Some(database) = &mut self.database {
1133 database.close().expect("Failed to close database");
1134 }
1135 }
1136
1137 pub fn flush_db(&mut self) {
1143 if let Some(database) = &mut self.database {
1144 database.flush().expect("Failed to flush database");
1145 }
1146 }
1147
1148 pub fn add(&mut self, key: &str, value: Bytes) -> anyhow::Result<()> {
1156 check_valid_string(key, stringify!(key))?;
1157 check_predicate_false(value.is_empty(), stringify!(value))?;
1158
1159 log::debug!("Adding general {key}");
1160 self.general.insert(key.to_string(), value.clone());
1161
1162 if let Some(database) = &mut self.database {
1163 database.add(key.to_string(), value)?;
1164 }
1165 Ok(())
1166 }
1167
1168 pub fn add_order_book(&mut self, book: OrderBook) -> anyhow::Result<()> {
1174 log::debug!("Adding `OrderBook` {}", book.instrument_id);
1175
1176 if self.config.save_market_data
1177 && let Some(database) = &mut self.database
1178 {
1179 database.add_order_book(&book)?;
1180 }
1181
1182 self.books.insert(book.instrument_id, book);
1183 Ok(())
1184 }
1185
1186 pub fn add_own_order_book(&mut self, own_book: OwnOrderBook) -> anyhow::Result<()> {
1192 log::debug!("Adding `OwnOrderBook` {}", own_book.instrument_id);
1193
1194 self.own_books.insert(own_book.instrument_id, own_book);
1195 Ok(())
1196 }
1197
1198 #[cfg(feature = "defi")]
1204 pub fn add_pool(&mut self, pool: Pool) -> anyhow::Result<()> {
1205 log::debug!("Adding `Pool` {}", pool.instrument_id);
1206
1207 self.pools.insert(pool.instrument_id, pool);
1208 Ok(())
1209 }
1210
1211 pub fn add_mark_price(&mut self, mark_price: MarkPriceUpdate) -> anyhow::Result<()> {
1217 log::debug!("Adding `MarkPriceUpdate` for {}", mark_price.instrument_id);
1218
1219 if self.config.save_market_data {
1220 }
1222
1223 let mark_prices_deque = self
1224 .mark_prices
1225 .entry(mark_price.instrument_id)
1226 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1227 mark_prices_deque.push_front(mark_price);
1228 Ok(())
1229 }
1230
1231 pub fn add_index_price(&mut self, index_price: IndexPriceUpdate) -> anyhow::Result<()> {
1237 log::debug!(
1238 "Adding `IndexPriceUpdate` for {}",
1239 index_price.instrument_id
1240 );
1241
1242 if self.config.save_market_data {
1243 }
1245
1246 let index_prices_deque = self
1247 .index_prices
1248 .entry(index_price.instrument_id)
1249 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1250 index_prices_deque.push_front(index_price);
1251 Ok(())
1252 }
1253
1254 pub fn add_funding_rate(&mut self, funding_rate: FundingRateUpdate) -> anyhow::Result<()> {
1260 log::debug!(
1261 "Adding `FundingRateUpdate` for {}",
1262 funding_rate.instrument_id
1263 );
1264
1265 if self.config.save_market_data {
1266 }
1268
1269 self.funding_rates
1270 .insert(funding_rate.instrument_id, funding_rate);
1271 Ok(())
1272 }
1273
1274 pub fn add_quote(&mut self, quote: QuoteTick) -> anyhow::Result<()> {
1280 log::debug!("Adding `QuoteTick` {}", quote.instrument_id);
1281
1282 if self.config.save_market_data
1283 && let Some(database) = &mut self.database
1284 {
1285 database.add_quote("e)?;
1286 }
1287
1288 let quotes_deque = self
1289 .quotes
1290 .entry(quote.instrument_id)
1291 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1292 quotes_deque.push_front(quote);
1293 Ok(())
1294 }
1295
1296 pub fn add_quotes(&mut self, quotes: &[QuoteTick]) -> anyhow::Result<()> {
1302 check_slice_not_empty(quotes, stringify!(quotes))?;
1303
1304 let instrument_id = quotes[0].instrument_id;
1305 log::debug!("Adding `QuoteTick`[{}] {instrument_id}", quotes.len());
1306
1307 if self.config.save_market_data
1308 && let Some(database) = &mut self.database
1309 {
1310 for quote in quotes {
1311 database.add_quote(quote)?;
1312 }
1313 }
1314
1315 let quotes_deque = self
1316 .quotes
1317 .entry(instrument_id)
1318 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1319
1320 for quote in quotes {
1321 quotes_deque.push_front(*quote);
1322 }
1323 Ok(())
1324 }
1325
1326 pub fn add_trade(&mut self, trade: TradeTick) -> anyhow::Result<()> {
1332 log::debug!("Adding `TradeTick` {}", trade.instrument_id);
1333
1334 if self.config.save_market_data
1335 && let Some(database) = &mut self.database
1336 {
1337 database.add_trade(&trade)?;
1338 }
1339
1340 let trades_deque = self
1341 .trades
1342 .entry(trade.instrument_id)
1343 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1344 trades_deque.push_front(trade);
1345 Ok(())
1346 }
1347
1348 pub fn add_trades(&mut self, trades: &[TradeTick]) -> anyhow::Result<()> {
1354 check_slice_not_empty(trades, stringify!(trades))?;
1355
1356 let instrument_id = trades[0].instrument_id;
1357 log::debug!("Adding `TradeTick`[{}] {instrument_id}", trades.len());
1358
1359 if self.config.save_market_data
1360 && let Some(database) = &mut self.database
1361 {
1362 for trade in trades {
1363 database.add_trade(trade)?;
1364 }
1365 }
1366
1367 let trades_deque = self
1368 .trades
1369 .entry(instrument_id)
1370 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1371
1372 for trade in trades {
1373 trades_deque.push_front(*trade);
1374 }
1375 Ok(())
1376 }
1377
1378 pub fn add_bar(&mut self, bar: Bar) -> anyhow::Result<()> {
1384 log::debug!("Adding `Bar` {}", bar.bar_type);
1385
1386 if self.config.save_market_data
1387 && let Some(database) = &mut self.database
1388 {
1389 database.add_bar(&bar)?;
1390 }
1391
1392 let bars = self
1393 .bars
1394 .entry(bar.bar_type)
1395 .or_insert_with(|| VecDeque::with_capacity(self.config.bar_capacity));
1396 bars.push_front(bar);
1397 Ok(())
1398 }
1399
1400 pub fn add_bars(&mut self, bars: &[Bar]) -> anyhow::Result<()> {
1406 check_slice_not_empty(bars, stringify!(bars))?;
1407
1408 let bar_type = bars[0].bar_type;
1409 log::debug!("Adding `Bar`[{}] {bar_type}", bars.len());
1410
1411 if self.config.save_market_data
1412 && let Some(database) = &mut self.database
1413 {
1414 for bar in bars {
1415 database.add_bar(bar)?;
1416 }
1417 }
1418
1419 let bars_deque = self
1420 .bars
1421 .entry(bar_type)
1422 .or_insert_with(|| VecDeque::with_capacity(self.config.tick_capacity));
1423
1424 for bar in bars {
1425 bars_deque.push_front(*bar);
1426 }
1427 Ok(())
1428 }
1429
1430 pub fn add_greeks(&mut self, greeks: GreeksData) -> anyhow::Result<()> {
1436 log::debug!("Adding `GreeksData` {}", greeks.instrument_id);
1437
1438 if self.config.save_market_data
1439 && let Some(_database) = &mut self.database
1440 {
1441 }
1443
1444 self.greeks.insert(greeks.instrument_id, greeks);
1445 Ok(())
1446 }
1447
1448 pub fn greeks(&self, instrument_id: &InstrumentId) -> Option<GreeksData> {
1450 self.greeks.get(instrument_id).cloned()
1451 }
1452
1453 pub fn add_yield_curve(&mut self, yield_curve: YieldCurveData) -> anyhow::Result<()> {
1459 log::debug!("Adding `YieldCurveData` {}", yield_curve.curve_name);
1460
1461 if self.config.save_market_data
1462 && let Some(_database) = &mut self.database
1463 {
1464 }
1466
1467 self.yield_curves
1468 .insert(yield_curve.curve_name.clone(), yield_curve);
1469 Ok(())
1470 }
1471
1472 pub fn yield_curve(&self, key: &str) -> Option<Box<dyn Fn(f64) -> f64>> {
1474 self.yield_curves.get(key).map(|curve| {
1475 let curve_clone = curve.clone();
1476 Box::new(move |expiry_in_years: f64| curve_clone.get_rate(expiry_in_years))
1477 as Box<dyn Fn(f64) -> f64>
1478 })
1479 }
1480
1481 pub fn add_currency(&mut self, currency: Currency) -> anyhow::Result<()> {
1487 log::debug!("Adding `Currency` {}", currency.code);
1488
1489 if let Some(database) = &mut self.database {
1490 database.add_currency(¤cy)?;
1491 }
1492
1493 self.currencies.insert(currency.code, currency);
1494 Ok(())
1495 }
1496
1497 pub fn add_instrument(&mut self, instrument: InstrumentAny) -> anyhow::Result<()> {
1503 log::debug!("Adding `Instrument` {}", instrument.id());
1504
1505 if let Some(database) = &mut self.database {
1506 database.add_instrument(&instrument)?;
1507 }
1508
1509 self.instruments.insert(instrument.id(), instrument);
1510 Ok(())
1511 }
1512
1513 pub fn add_synthetic(&mut self, synthetic: SyntheticInstrument) -> anyhow::Result<()> {
1519 log::debug!("Adding `SyntheticInstrument` {}", synthetic.id);
1520
1521 if let Some(database) = &mut self.database {
1522 database.add_synthetic(&synthetic)?;
1523 }
1524
1525 self.synthetics.insert(synthetic.id, synthetic);
1526 Ok(())
1527 }
1528
1529 pub fn add_account(&mut self, account: AccountAny) -> anyhow::Result<()> {
1535 log::debug!("Adding `Account` {}", account.id());
1536
1537 if let Some(database) = &mut self.database {
1538 database.add_account(&account)?;
1539 }
1540
1541 let account_id = account.id();
1542 self.accounts.insert(account_id, account);
1543 self.index
1544 .venue_account
1545 .insert(account_id.get_issuer(), account_id);
1546 Ok(())
1547 }
1548
1549 pub fn add_venue_order_id(
1557 &mut self,
1558 client_order_id: &ClientOrderId,
1559 venue_order_id: &VenueOrderId,
1560 overwrite: bool,
1561 ) -> anyhow::Result<()> {
1562 if let Some(existing_venue_order_id) = self.index.client_order_ids.get(client_order_id)
1563 && !overwrite
1564 && existing_venue_order_id != venue_order_id
1565 {
1566 anyhow::bail!(
1567 "Existing {existing_venue_order_id} for {client_order_id}
1568 did not match the given {venue_order_id}.
1569 If you are writing a test then try a different `venue_order_id`,
1570 otherwise this is probably a bug."
1571 );
1572 }
1573
1574 self.index
1575 .client_order_ids
1576 .insert(*client_order_id, *venue_order_id);
1577 self.index
1578 .venue_order_ids
1579 .insert(*venue_order_id, *client_order_id);
1580
1581 Ok(())
1582 }
1583
1584 pub fn add_order(
1596 &mut self,
1597 order: OrderAny,
1598 position_id: Option<PositionId>,
1599 client_id: Option<ClientId>,
1600 replace_existing: bool,
1601 ) -> anyhow::Result<()> {
1602 let instrument_id = order.instrument_id();
1603 let venue = instrument_id.venue;
1604 let client_order_id = order.client_order_id();
1605 let strategy_id = order.strategy_id();
1606 let exec_algorithm_id = order.exec_algorithm_id();
1607 let exec_spawn_id = order.exec_spawn_id();
1608
1609 if !replace_existing {
1610 check_key_not_in_map(
1611 &client_order_id,
1612 &self.orders,
1613 stringify!(client_order_id),
1614 stringify!(orders),
1615 )?;
1616 }
1617
1618 log::debug!("Adding {order:?}");
1619
1620 self.index.orders.insert(client_order_id);
1621 self.index
1622 .order_strategy
1623 .insert(client_order_id, strategy_id);
1624 self.index.strategies.insert(strategy_id);
1625
1626 self.index
1628 .venue_orders
1629 .entry(venue)
1630 .or_default()
1631 .insert(client_order_id);
1632
1633 self.index
1635 .instrument_orders
1636 .entry(instrument_id)
1637 .or_default()
1638 .insert(client_order_id);
1639
1640 self.index
1642 .strategy_orders
1643 .entry(strategy_id)
1644 .or_default()
1645 .insert(client_order_id);
1646
1647 if let (Some(exec_algorithm_id), Some(exec_spawn_id)) = (exec_algorithm_id, exec_spawn_id) {
1650 self.index.exec_algorithms.insert(exec_algorithm_id);
1651
1652 self.index
1653 .exec_algorithm_orders
1654 .entry(exec_algorithm_id)
1655 .or_default()
1656 .insert(client_order_id);
1657
1658 self.index
1659 .exec_spawn_orders
1660 .entry(exec_spawn_id)
1661 .or_default()
1662 .insert(client_order_id);
1663 }
1664
1665 match order.emulation_trigger() {
1667 Some(_) => {
1668 self.index.orders_emulated.remove(&client_order_id);
1669 }
1670 None => {
1671 self.index.orders_emulated.insert(client_order_id);
1672 }
1673 }
1674
1675 if let Some(position_id) = position_id {
1677 self.add_position_id(
1678 &position_id,
1679 &order.instrument_id().venue,
1680 &client_order_id,
1681 &strategy_id,
1682 )?;
1683 }
1684
1685 if let Some(client_id) = client_id {
1687 self.index.order_client.insert(client_order_id, client_id);
1688 log::debug!("Indexed {client_id:?}");
1689 }
1690
1691 if let Some(database) = &mut self.database {
1692 database.add_order(&order, client_id)?;
1693 }
1698
1699 self.orders.insert(client_order_id, order);
1700
1701 Ok(())
1702 }
1703
1704 pub fn add_position_id(
1710 &mut self,
1711 position_id: &PositionId,
1712 venue: &Venue,
1713 client_order_id: &ClientOrderId,
1714 strategy_id: &StrategyId,
1715 ) -> anyhow::Result<()> {
1716 self.index
1717 .order_position
1718 .insert(*client_order_id, *position_id);
1719
1720 if let Some(database) = &mut self.database {
1722 database.index_order_position(*client_order_id, *position_id)?;
1723 }
1724
1725 self.index
1727 .position_strategy
1728 .insert(*position_id, *strategy_id);
1729
1730 self.index
1732 .position_orders
1733 .entry(*position_id)
1734 .or_default()
1735 .insert(*client_order_id);
1736
1737 self.index
1739 .strategy_positions
1740 .entry(*strategy_id)
1741 .or_default()
1742 .insert(*position_id);
1743
1744 self.index
1746 .venue_positions
1747 .entry(*venue)
1748 .or_default()
1749 .insert(*position_id);
1750
1751 Ok(())
1752 }
1753
1754 pub fn add_position(&mut self, position: Position, _oms_type: OmsType) -> anyhow::Result<()> {
1760 self.positions.insert(position.id, position.clone());
1761 self.index.positions.insert(position.id);
1762 self.index.positions_open.insert(position.id);
1763
1764 log::debug!("Adding {position}");
1765
1766 self.add_position_id(
1767 &position.id,
1768 &position.instrument_id.venue,
1769 &position.opening_order_id,
1770 &position.strategy_id,
1771 )?;
1772
1773 let venue = position.instrument_id.venue;
1774 let venue_positions = self.index.venue_positions.entry(venue).or_default();
1775 venue_positions.insert(position.id);
1776
1777 let instrument_id = position.instrument_id;
1779 let instrument_positions = self
1780 .index
1781 .instrument_positions
1782 .entry(instrument_id)
1783 .or_default();
1784 instrument_positions.insert(position.id);
1785
1786 if let Some(database) = &mut self.database {
1787 database.add_position(&position)?;
1788 }
1797
1798 Ok(())
1799 }
1800
1801 pub fn update_account(&mut self, account: AccountAny) -> anyhow::Result<()> {
1807 if let Some(database) = &mut self.database {
1808 database.update_account(&account)?;
1809 }
1810 Ok(())
1811 }
1812
1813 pub fn update_order(&mut self, order: &OrderAny) -> anyhow::Result<()> {
1819 let client_order_id = order.client_order_id();
1820
1821 if let Some(venue_order_id) = order.venue_order_id() {
1823 if !self.index.venue_order_ids.contains_key(&venue_order_id) {
1826 self.add_venue_order_id(&order.client_order_id(), &venue_order_id, false)?;
1828 }
1829 }
1830
1831 if order.is_inflight() {
1833 self.index.orders_inflight.insert(client_order_id);
1834 } else {
1835 self.index.orders_inflight.remove(&client_order_id);
1836 }
1837
1838 if order.is_open() {
1840 self.index.orders_closed.remove(&client_order_id);
1841 self.index.orders_open.insert(client_order_id);
1842 } else if order.is_closed() {
1843 self.index.orders_open.remove(&client_order_id);
1844 self.index.orders_pending_cancel.remove(&client_order_id);
1845 self.index.orders_closed.insert(client_order_id);
1846 }
1847
1848 if let Some(emulation_trigger) = order.emulation_trigger() {
1850 match emulation_trigger {
1851 TriggerType::NoTrigger => self.index.orders_emulated.remove(&client_order_id),
1852 _ => self.index.orders_emulated.insert(client_order_id),
1853 };
1854 }
1855
1856 if self.own_order_book(&order.instrument_id()).is_some()
1858 && should_handle_own_book_order(order)
1859 {
1860 self.update_own_order_book(order);
1861 }
1862
1863 if let Some(database) = &mut self.database {
1864 database.update_order(order.last_event())?;
1865 }
1870
1871 self.orders.insert(client_order_id, order.clone());
1873
1874 Ok(())
1875 }
1876
1877 pub fn update_order_pending_cancel_local(&mut self, order: &OrderAny) {
1879 self.index
1880 .orders_pending_cancel
1881 .insert(order.client_order_id());
1882 }
1883
1884 pub fn update_position(&mut self, position: &Position) -> anyhow::Result<()> {
1890 if position.is_open() {
1893 self.index.positions_open.insert(position.id);
1894 self.index.positions_closed.remove(&position.id);
1895 } else {
1896 self.index.positions_closed.insert(position.id);
1897 self.index.positions_open.remove(&position.id);
1898 }
1899
1900 if let Some(database) = &mut self.database {
1901 database.update_position(position)?;
1902 }
1907
1908 self.positions.insert(position.id, position.clone());
1909
1910 Ok(())
1911 }
1912
1913 pub fn snapshot_position(&mut self, position: &Position) -> anyhow::Result<()> {
1920 let position_id = position.id;
1921
1922 let mut copied_position = position.clone();
1923 let new_id = format!("{}-{}", position_id.as_str(), UUID4::new());
1924 copied_position.id = PositionId::new(new_id);
1925
1926 let position_serialized = serde_json::to_vec(&copied_position)?;
1928
1929 let snapshots: Option<&Bytes> = self.position_snapshots.get(&position_id);
1930 let new_snapshots = match snapshots {
1931 Some(existing_snapshots) => {
1932 let mut combined = existing_snapshots.to_vec();
1933 combined.extend(position_serialized);
1934 Bytes::from(combined)
1935 }
1936 None => Bytes::from(position_serialized),
1937 };
1938 self.position_snapshots.insert(position_id, new_snapshots);
1939
1940 log::debug!("Snapshot {copied_position}");
1941 Ok(())
1942 }
1943
1944 pub fn snapshot_position_state(
1950 &mut self,
1951 position: &Position,
1952 open_only: Option<bool>,
1955 ) -> anyhow::Result<()> {
1956 let open_only = open_only.unwrap_or(true);
1957
1958 if open_only && !position.is_open() {
1959 return Ok(());
1960 }
1961
1962 if let Some(database) = &mut self.database {
1963 database.snapshot_position_state(position).map_err(|e| {
1964 log::error!(
1965 "Failed to snapshot position state for {}: {e:?}",
1966 position.id
1967 );
1968 e
1969 })?;
1970 } else {
1971 log::warn!(
1972 "Cannot snapshot position state for {} (no database configured)",
1973 position.id
1974 );
1975 }
1976
1977 todo!()
1979 }
1980
1981 pub fn snapshot_order_state(&self, order: &OrderAny) -> anyhow::Result<()> {
1987 let database = if let Some(database) = &self.database {
1988 database
1989 } else {
1990 log::warn!(
1991 "Cannot snapshot order state for {} (no database configured)",
1992 order.client_order_id()
1993 );
1994 return Ok(());
1995 };
1996
1997 database.snapshot_order_state(order)
1998 }
1999
2000 fn build_order_query_filter_set(
2003 &self,
2004 venue: Option<&Venue>,
2005 instrument_id: Option<&InstrumentId>,
2006 strategy_id: Option<&StrategyId>,
2007 ) -> Option<AHashSet<ClientOrderId>> {
2008 let mut query: Option<AHashSet<ClientOrderId>> = None;
2009
2010 if let Some(venue) = venue {
2011 query = Some(
2012 self.index
2013 .venue_orders
2014 .get(venue)
2015 .cloned()
2016 .unwrap_or_default(),
2017 );
2018 }
2019
2020 if let Some(instrument_id) = instrument_id {
2021 let instrument_orders = self
2022 .index
2023 .instrument_orders
2024 .get(instrument_id)
2025 .cloned()
2026 .unwrap_or_default();
2027
2028 if let Some(existing_query) = &mut query {
2029 *existing_query = existing_query
2030 .intersection(&instrument_orders)
2031 .copied()
2032 .collect();
2033 } else {
2034 query = Some(instrument_orders);
2035 }
2036 }
2037
2038 if let Some(strategy_id) = strategy_id {
2039 let strategy_orders = self
2040 .index
2041 .strategy_orders
2042 .get(strategy_id)
2043 .cloned()
2044 .unwrap_or_default();
2045
2046 if let Some(existing_query) = &mut query {
2047 *existing_query = existing_query
2048 .intersection(&strategy_orders)
2049 .copied()
2050 .collect();
2051 } else {
2052 query = Some(strategy_orders);
2053 }
2054 }
2055
2056 query
2057 }
2058
2059 fn build_position_query_filter_set(
2060 &self,
2061 venue: Option<&Venue>,
2062 instrument_id: Option<&InstrumentId>,
2063 strategy_id: Option<&StrategyId>,
2064 ) -> Option<AHashSet<PositionId>> {
2065 let mut query: Option<AHashSet<PositionId>> = None;
2066
2067 if let Some(venue) = venue {
2068 query = Some(
2069 self.index
2070 .venue_positions
2071 .get(venue)
2072 .cloned()
2073 .unwrap_or_default(),
2074 );
2075 }
2076
2077 if let Some(instrument_id) = instrument_id {
2078 let instrument_positions = self
2079 .index
2080 .instrument_positions
2081 .get(instrument_id)
2082 .cloned()
2083 .unwrap_or_default();
2084
2085 if let Some(existing_query) = query {
2086 query = Some(
2087 existing_query
2088 .intersection(&instrument_positions)
2089 .copied()
2090 .collect(),
2091 );
2092 } else {
2093 query = Some(instrument_positions);
2094 }
2095 }
2096
2097 if let Some(strategy_id) = strategy_id {
2098 let strategy_positions = self
2099 .index
2100 .strategy_positions
2101 .get(strategy_id)
2102 .cloned()
2103 .unwrap_or_default();
2104
2105 if let Some(existing_query) = query {
2106 query = Some(
2107 existing_query
2108 .intersection(&strategy_positions)
2109 .copied()
2110 .collect(),
2111 );
2112 } else {
2113 query = Some(strategy_positions);
2114 }
2115 }
2116
2117 query
2118 }
2119
2120 fn get_orders_for_ids(
2126 &self,
2127 client_order_ids: &AHashSet<ClientOrderId>,
2128 side: Option<OrderSide>,
2129 ) -> Vec<&OrderAny> {
2130 let side = side.unwrap_or(OrderSide::NoOrderSide);
2131 let mut orders = Vec::new();
2132
2133 for client_order_id in client_order_ids {
2134 let order = self
2135 .orders
2136 .get(client_order_id)
2137 .unwrap_or_else(|| panic!("Order {client_order_id} not found"));
2138 if side == OrderSide::NoOrderSide || side == order.order_side() {
2139 orders.push(order);
2140 }
2141 }
2142
2143 orders
2144 }
2145
2146 fn get_positions_for_ids(
2152 &self,
2153 position_ids: &AHashSet<PositionId>,
2154 side: Option<PositionSide>,
2155 ) -> Vec<&Position> {
2156 let side = side.unwrap_or(PositionSide::NoPositionSide);
2157 let mut positions = Vec::new();
2158
2159 for position_id in position_ids {
2160 let position = self
2161 .positions
2162 .get(position_id)
2163 .unwrap_or_else(|| panic!("Position {position_id} not found"));
2164 if side == PositionSide::NoPositionSide || side == position.side {
2165 positions.push(position);
2166 }
2167 }
2168
2169 positions
2170 }
2171
2172 #[must_use]
2174 pub fn client_order_ids(
2175 &self,
2176 venue: Option<&Venue>,
2177 instrument_id: Option<&InstrumentId>,
2178 strategy_id: Option<&StrategyId>,
2179 ) -> AHashSet<ClientOrderId> {
2180 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2181 match query {
2182 Some(query) => self.index.orders.intersection(&query).copied().collect(),
2183 None => self.index.orders.clone(),
2184 }
2185 }
2186
2187 #[must_use]
2189 pub fn client_order_ids_open(
2190 &self,
2191 venue: Option<&Venue>,
2192 instrument_id: Option<&InstrumentId>,
2193 strategy_id: Option<&StrategyId>,
2194 ) -> AHashSet<ClientOrderId> {
2195 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2196 match query {
2197 Some(query) => self
2198 .index
2199 .orders_open
2200 .intersection(&query)
2201 .copied()
2202 .collect(),
2203 None => self.index.orders_open.clone(),
2204 }
2205 }
2206
2207 #[must_use]
2209 pub fn client_order_ids_closed(
2210 &self,
2211 venue: Option<&Venue>,
2212 instrument_id: Option<&InstrumentId>,
2213 strategy_id: Option<&StrategyId>,
2214 ) -> AHashSet<ClientOrderId> {
2215 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2216 match query {
2217 Some(query) => self
2218 .index
2219 .orders_closed
2220 .intersection(&query)
2221 .copied()
2222 .collect(),
2223 None => self.index.orders_closed.clone(),
2224 }
2225 }
2226
2227 #[must_use]
2229 pub fn client_order_ids_emulated(
2230 &self,
2231 venue: Option<&Venue>,
2232 instrument_id: Option<&InstrumentId>,
2233 strategy_id: Option<&StrategyId>,
2234 ) -> AHashSet<ClientOrderId> {
2235 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2236 match query {
2237 Some(query) => self
2238 .index
2239 .orders_emulated
2240 .intersection(&query)
2241 .copied()
2242 .collect(),
2243 None => self.index.orders_emulated.clone(),
2244 }
2245 }
2246
2247 #[must_use]
2249 pub fn client_order_ids_inflight(
2250 &self,
2251 venue: Option<&Venue>,
2252 instrument_id: Option<&InstrumentId>,
2253 strategy_id: Option<&StrategyId>,
2254 ) -> AHashSet<ClientOrderId> {
2255 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2256 match query {
2257 Some(query) => self
2258 .index
2259 .orders_inflight
2260 .intersection(&query)
2261 .copied()
2262 .collect(),
2263 None => self.index.orders_inflight.clone(),
2264 }
2265 }
2266
2267 #[must_use]
2269 pub fn position_ids(
2270 &self,
2271 venue: Option<&Venue>,
2272 instrument_id: Option<&InstrumentId>,
2273 strategy_id: Option<&StrategyId>,
2274 ) -> AHashSet<PositionId> {
2275 let query = self.build_position_query_filter_set(venue, instrument_id, strategy_id);
2276 match query {
2277 Some(query) => self.index.positions.intersection(&query).copied().collect(),
2278 None => self.index.positions.clone(),
2279 }
2280 }
2281
2282 #[must_use]
2284 pub fn position_open_ids(
2285 &self,
2286 venue: Option<&Venue>,
2287 instrument_id: Option<&InstrumentId>,
2288 strategy_id: Option<&StrategyId>,
2289 ) -> AHashSet<PositionId> {
2290 let query = self.build_position_query_filter_set(venue, instrument_id, strategy_id);
2291 match query {
2292 Some(query) => self
2293 .index
2294 .positions_open
2295 .intersection(&query)
2296 .copied()
2297 .collect(),
2298 None => self.index.positions_open.clone(),
2299 }
2300 }
2301
2302 #[must_use]
2304 pub fn position_closed_ids(
2305 &self,
2306 venue: Option<&Venue>,
2307 instrument_id: Option<&InstrumentId>,
2308 strategy_id: Option<&StrategyId>,
2309 ) -> AHashSet<PositionId> {
2310 let query = self.build_position_query_filter_set(venue, instrument_id, strategy_id);
2311 match query {
2312 Some(query) => self
2313 .index
2314 .positions_closed
2315 .intersection(&query)
2316 .copied()
2317 .collect(),
2318 None => self.index.positions_closed.clone(),
2319 }
2320 }
2321
2322 #[must_use]
2324 pub fn actor_ids(&self) -> AHashSet<ComponentId> {
2325 self.index.actors.clone()
2326 }
2327
2328 #[must_use]
2330 pub fn strategy_ids(&self) -> AHashSet<StrategyId> {
2331 self.index.strategies.clone()
2332 }
2333
2334 #[must_use]
2336 pub fn exec_algorithm_ids(&self) -> AHashSet<ExecAlgorithmId> {
2337 self.index.exec_algorithms.clone()
2338 }
2339
2340 #[must_use]
2344 pub fn order(&self, client_order_id: &ClientOrderId) -> Option<&OrderAny> {
2345 self.orders.get(client_order_id)
2346 }
2347
2348 #[must_use]
2350 pub fn mut_order(&mut self, client_order_id: &ClientOrderId) -> Option<&mut OrderAny> {
2351 self.orders.get_mut(client_order_id)
2352 }
2353
2354 #[must_use]
2356 pub fn client_order_id(&self, venue_order_id: &VenueOrderId) -> Option<&ClientOrderId> {
2357 self.index.venue_order_ids.get(venue_order_id)
2358 }
2359
2360 #[must_use]
2362 pub fn venue_order_id(&self, client_order_id: &ClientOrderId) -> Option<&VenueOrderId> {
2363 self.index.client_order_ids.get(client_order_id)
2364 }
2365
2366 #[must_use]
2368 pub fn client_id(&self, client_order_id: &ClientOrderId) -> Option<&ClientId> {
2369 self.index.order_client.get(client_order_id)
2370 }
2371
2372 #[must_use]
2374 pub fn orders(
2375 &self,
2376 venue: Option<&Venue>,
2377 instrument_id: Option<&InstrumentId>,
2378 strategy_id: Option<&StrategyId>,
2379 side: Option<OrderSide>,
2380 ) -> Vec<&OrderAny> {
2381 let client_order_ids = self.client_order_ids(venue, instrument_id, strategy_id);
2382 self.get_orders_for_ids(&client_order_ids, side)
2383 }
2384
2385 #[must_use]
2387 pub fn orders_open(
2388 &self,
2389 venue: Option<&Venue>,
2390 instrument_id: Option<&InstrumentId>,
2391 strategy_id: Option<&StrategyId>,
2392 side: Option<OrderSide>,
2393 ) -> Vec<&OrderAny> {
2394 let client_order_ids = self.client_order_ids_open(venue, instrument_id, strategy_id);
2395 self.get_orders_for_ids(&client_order_ids, side)
2396 }
2397
2398 #[must_use]
2400 pub fn orders_closed(
2401 &self,
2402 venue: Option<&Venue>,
2403 instrument_id: Option<&InstrumentId>,
2404 strategy_id: Option<&StrategyId>,
2405 side: Option<OrderSide>,
2406 ) -> Vec<&OrderAny> {
2407 let client_order_ids = self.client_order_ids_closed(venue, instrument_id, strategy_id);
2408 self.get_orders_for_ids(&client_order_ids, side)
2409 }
2410
2411 #[must_use]
2413 pub fn orders_emulated(
2414 &self,
2415 venue: Option<&Venue>,
2416 instrument_id: Option<&InstrumentId>,
2417 strategy_id: Option<&StrategyId>,
2418 side: Option<OrderSide>,
2419 ) -> Vec<&OrderAny> {
2420 let client_order_ids = self.client_order_ids_emulated(venue, instrument_id, strategy_id);
2421 self.get_orders_for_ids(&client_order_ids, side)
2422 }
2423
2424 #[must_use]
2426 pub fn orders_inflight(
2427 &self,
2428 venue: Option<&Venue>,
2429 instrument_id: Option<&InstrumentId>,
2430 strategy_id: Option<&StrategyId>,
2431 side: Option<OrderSide>,
2432 ) -> Vec<&OrderAny> {
2433 let client_order_ids = self.client_order_ids_inflight(venue, instrument_id, strategy_id);
2434 self.get_orders_for_ids(&client_order_ids, side)
2435 }
2436
2437 #[must_use]
2439 pub fn orders_for_position(&self, position_id: &PositionId) -> Vec<&OrderAny> {
2440 let client_order_ids = self.index.position_orders.get(position_id);
2441 match client_order_ids {
2442 Some(client_order_ids) => {
2443 self.get_orders_for_ids(&client_order_ids.iter().copied().collect(), None)
2444 }
2445 None => Vec::new(),
2446 }
2447 }
2448
2449 #[must_use]
2451 pub fn order_exists(&self, client_order_id: &ClientOrderId) -> bool {
2452 self.index.orders.contains(client_order_id)
2453 }
2454
2455 #[must_use]
2457 pub fn is_order_open(&self, client_order_id: &ClientOrderId) -> bool {
2458 self.index.orders_open.contains(client_order_id)
2459 }
2460
2461 #[must_use]
2463 pub fn is_order_closed(&self, client_order_id: &ClientOrderId) -> bool {
2464 self.index.orders_closed.contains(client_order_id)
2465 }
2466
2467 #[must_use]
2469 pub fn is_order_emulated(&self, client_order_id: &ClientOrderId) -> bool {
2470 self.index.orders_emulated.contains(client_order_id)
2471 }
2472
2473 #[must_use]
2475 pub fn is_order_inflight(&self, client_order_id: &ClientOrderId) -> bool {
2476 self.index.orders_inflight.contains(client_order_id)
2477 }
2478
2479 #[must_use]
2481 pub fn is_order_pending_cancel_local(&self, client_order_id: &ClientOrderId) -> bool {
2482 self.index.orders_pending_cancel.contains(client_order_id)
2483 }
2484
2485 #[must_use]
2487 pub fn orders_open_count(
2488 &self,
2489 venue: Option<&Venue>,
2490 instrument_id: Option<&InstrumentId>,
2491 strategy_id: Option<&StrategyId>,
2492 side: Option<OrderSide>,
2493 ) -> usize {
2494 self.orders_open(venue, instrument_id, strategy_id, side)
2495 .len()
2496 }
2497
2498 #[must_use]
2500 pub fn orders_closed_count(
2501 &self,
2502 venue: Option<&Venue>,
2503 instrument_id: Option<&InstrumentId>,
2504 strategy_id: Option<&StrategyId>,
2505 side: Option<OrderSide>,
2506 ) -> usize {
2507 self.orders_closed(venue, instrument_id, strategy_id, side)
2508 .len()
2509 }
2510
2511 #[must_use]
2513 pub fn orders_emulated_count(
2514 &self,
2515 venue: Option<&Venue>,
2516 instrument_id: Option<&InstrumentId>,
2517 strategy_id: Option<&StrategyId>,
2518 side: Option<OrderSide>,
2519 ) -> usize {
2520 self.orders_emulated(venue, instrument_id, strategy_id, side)
2521 .len()
2522 }
2523
2524 #[must_use]
2526 pub fn orders_inflight_count(
2527 &self,
2528 venue: Option<&Venue>,
2529 instrument_id: Option<&InstrumentId>,
2530 strategy_id: Option<&StrategyId>,
2531 side: Option<OrderSide>,
2532 ) -> usize {
2533 self.orders_inflight(venue, instrument_id, strategy_id, side)
2534 .len()
2535 }
2536
2537 #[must_use]
2539 pub fn orders_total_count(
2540 &self,
2541 venue: Option<&Venue>,
2542 instrument_id: Option<&InstrumentId>,
2543 strategy_id: Option<&StrategyId>,
2544 side: Option<OrderSide>,
2545 ) -> usize {
2546 self.orders(venue, instrument_id, strategy_id, side).len()
2547 }
2548
2549 #[must_use]
2551 pub fn order_list(&self, order_list_id: &OrderListId) -> Option<&OrderList> {
2552 self.order_lists.get(order_list_id)
2553 }
2554
2555 #[must_use]
2557 pub fn order_lists(
2558 &self,
2559 venue: Option<&Venue>,
2560 instrument_id: Option<&InstrumentId>,
2561 strategy_id: Option<&StrategyId>,
2562 ) -> Vec<&OrderList> {
2563 let mut order_lists = self.order_lists.values().collect::<Vec<&OrderList>>();
2564
2565 if let Some(venue) = venue {
2566 order_lists.retain(|ol| &ol.instrument_id.venue == venue);
2567 }
2568
2569 if let Some(instrument_id) = instrument_id {
2570 order_lists.retain(|ol| &ol.instrument_id == instrument_id);
2571 }
2572
2573 if let Some(strategy_id) = strategy_id {
2574 order_lists.retain(|ol| &ol.strategy_id == strategy_id);
2575 }
2576
2577 order_lists
2578 }
2579
2580 #[must_use]
2582 pub fn order_list_exists(&self, order_list_id: &OrderListId) -> bool {
2583 self.order_lists.contains_key(order_list_id)
2584 }
2585
2586 #[must_use]
2591 pub fn orders_for_exec_algorithm(
2592 &self,
2593 exec_algorithm_id: &ExecAlgorithmId,
2594 venue: Option<&Venue>,
2595 instrument_id: Option<&InstrumentId>,
2596 strategy_id: Option<&StrategyId>,
2597 side: Option<OrderSide>,
2598 ) -> Vec<&OrderAny> {
2599 let query = self.build_order_query_filter_set(venue, instrument_id, strategy_id);
2600 let exec_algorithm_order_ids = self.index.exec_algorithm_orders.get(exec_algorithm_id);
2601
2602 if let Some(query) = query
2603 && let Some(exec_algorithm_order_ids) = exec_algorithm_order_ids
2604 {
2605 let _exec_algorithm_order_ids = exec_algorithm_order_ids.intersection(&query);
2606 }
2607
2608 if let Some(exec_algorithm_order_ids) = exec_algorithm_order_ids {
2609 self.get_orders_for_ids(exec_algorithm_order_ids, side)
2610 } else {
2611 Vec::new()
2612 }
2613 }
2614
2615 #[must_use]
2617 pub fn orders_for_exec_spawn(&self, exec_spawn_id: &ClientOrderId) -> Vec<&OrderAny> {
2618 self.get_orders_for_ids(
2619 self.index
2620 .exec_spawn_orders
2621 .get(exec_spawn_id)
2622 .unwrap_or(&AHashSet::new()),
2623 None,
2624 )
2625 }
2626
2627 #[must_use]
2629 pub fn exec_spawn_total_quantity(
2630 &self,
2631 exec_spawn_id: &ClientOrderId,
2632 active_only: bool,
2633 ) -> Option<Quantity> {
2634 let exec_spawn_orders = self.orders_for_exec_spawn(exec_spawn_id);
2635
2636 let mut total_quantity: Option<Quantity> = None;
2637
2638 for spawn_order in exec_spawn_orders {
2639 if !active_only || !spawn_order.is_closed() {
2640 if let Some(mut total_quantity) = total_quantity {
2641 total_quantity += spawn_order.quantity();
2642 }
2643 } else {
2644 total_quantity = Some(spawn_order.quantity());
2645 }
2646 }
2647
2648 total_quantity
2649 }
2650
2651 #[must_use]
2653 pub fn exec_spawn_total_filled_qty(
2654 &self,
2655 exec_spawn_id: &ClientOrderId,
2656 active_only: bool,
2657 ) -> Option<Quantity> {
2658 let exec_spawn_orders = self.orders_for_exec_spawn(exec_spawn_id);
2659
2660 let mut total_quantity: Option<Quantity> = None;
2661
2662 for spawn_order in exec_spawn_orders {
2663 if !active_only || !spawn_order.is_closed() {
2664 if let Some(mut total_quantity) = total_quantity {
2665 total_quantity += spawn_order.filled_qty();
2666 }
2667 } else {
2668 total_quantity = Some(spawn_order.filled_qty());
2669 }
2670 }
2671
2672 total_quantity
2673 }
2674
2675 #[must_use]
2677 pub fn exec_spawn_total_leaves_qty(
2678 &self,
2679 exec_spawn_id: &ClientOrderId,
2680 active_only: bool,
2681 ) -> Option<Quantity> {
2682 let exec_spawn_orders = self.orders_for_exec_spawn(exec_spawn_id);
2683
2684 let mut total_quantity: Option<Quantity> = None;
2685
2686 for spawn_order in exec_spawn_orders {
2687 if !active_only || !spawn_order.is_closed() {
2688 if let Some(mut total_quantity) = total_quantity {
2689 total_quantity += spawn_order.leaves_qty();
2690 }
2691 } else {
2692 total_quantity = Some(spawn_order.leaves_qty());
2693 }
2694 }
2695
2696 total_quantity
2697 }
2698
2699 #[must_use]
2703 pub fn position(&self, position_id: &PositionId) -> Option<&Position> {
2704 self.positions.get(position_id)
2705 }
2706
2707 #[must_use]
2709 pub fn position_for_order(&self, client_order_id: &ClientOrderId) -> Option<&Position> {
2710 self.index
2711 .order_position
2712 .get(client_order_id)
2713 .and_then(|position_id| self.positions.get(position_id))
2714 }
2715
2716 #[must_use]
2718 pub fn position_id(&self, client_order_id: &ClientOrderId) -> Option<&PositionId> {
2719 self.index.order_position.get(client_order_id)
2720 }
2721
2722 #[must_use]
2724 pub fn positions(
2725 &self,
2726 venue: Option<&Venue>,
2727 instrument_id: Option<&InstrumentId>,
2728 strategy_id: Option<&StrategyId>,
2729 side: Option<PositionSide>,
2730 ) -> Vec<&Position> {
2731 let position_ids = self.position_ids(venue, instrument_id, strategy_id);
2732 self.get_positions_for_ids(&position_ids, side)
2733 }
2734
2735 #[must_use]
2737 pub fn positions_open(
2738 &self,
2739 venue: Option<&Venue>,
2740 instrument_id: Option<&InstrumentId>,
2741 strategy_id: Option<&StrategyId>,
2742 side: Option<PositionSide>,
2743 ) -> Vec<&Position> {
2744 let position_ids = self.position_open_ids(venue, instrument_id, strategy_id);
2745 self.get_positions_for_ids(&position_ids, side)
2746 }
2747
2748 #[must_use]
2750 pub fn positions_closed(
2751 &self,
2752 venue: Option<&Venue>,
2753 instrument_id: Option<&InstrumentId>,
2754 strategy_id: Option<&StrategyId>,
2755 side: Option<PositionSide>,
2756 ) -> Vec<&Position> {
2757 let position_ids = self.position_closed_ids(venue, instrument_id, strategy_id);
2758 self.get_positions_for_ids(&position_ids, side)
2759 }
2760
2761 #[must_use]
2763 pub fn position_exists(&self, position_id: &PositionId) -> bool {
2764 self.index.positions.contains(position_id)
2765 }
2766
2767 #[must_use]
2769 pub fn is_position_open(&self, position_id: &PositionId) -> bool {
2770 self.index.positions_open.contains(position_id)
2771 }
2772
2773 #[must_use]
2775 pub fn is_position_closed(&self, position_id: &PositionId) -> bool {
2776 self.index.positions_closed.contains(position_id)
2777 }
2778
2779 #[must_use]
2781 pub fn positions_open_count(
2782 &self,
2783 venue: Option<&Venue>,
2784 instrument_id: Option<&InstrumentId>,
2785 strategy_id: Option<&StrategyId>,
2786 side: Option<PositionSide>,
2787 ) -> usize {
2788 self.positions_open(venue, instrument_id, strategy_id, side)
2789 .len()
2790 }
2791
2792 #[must_use]
2794 pub fn positions_closed_count(
2795 &self,
2796 venue: Option<&Venue>,
2797 instrument_id: Option<&InstrumentId>,
2798 strategy_id: Option<&StrategyId>,
2799 side: Option<PositionSide>,
2800 ) -> usize {
2801 self.positions_closed(venue, instrument_id, strategy_id, side)
2802 .len()
2803 }
2804
2805 #[must_use]
2807 pub fn positions_total_count(
2808 &self,
2809 venue: Option<&Venue>,
2810 instrument_id: Option<&InstrumentId>,
2811 strategy_id: Option<&StrategyId>,
2812 side: Option<PositionSide>,
2813 ) -> usize {
2814 self.positions(venue, instrument_id, strategy_id, side)
2815 .len()
2816 }
2817
2818 #[must_use]
2822 pub fn strategy_id_for_order(&self, client_order_id: &ClientOrderId) -> Option<&StrategyId> {
2823 self.index.order_strategy.get(client_order_id)
2824 }
2825
2826 #[must_use]
2828 pub fn strategy_id_for_position(&self, position_id: &PositionId) -> Option<&StrategyId> {
2829 self.index.position_strategy.get(position_id)
2830 }
2831
2832 pub fn get(&self, key: &str) -> anyhow::Result<Option<&Bytes>> {
2840 check_valid_string(key, stringify!(key))?;
2841
2842 Ok(self.general.get(key))
2843 }
2844
2845 #[must_use]
2849 pub fn price(&self, instrument_id: &InstrumentId, price_type: PriceType) -> Option<Price> {
2850 match price_type {
2851 PriceType::Bid => self
2852 .quotes
2853 .get(instrument_id)
2854 .and_then(|quotes| quotes.front().map(|quote| quote.bid_price)),
2855 PriceType::Ask => self
2856 .quotes
2857 .get(instrument_id)
2858 .and_then(|quotes| quotes.front().map(|quote| quote.ask_price)),
2859 PriceType::Mid => self.quotes.get(instrument_id).and_then(|quotes| {
2860 quotes.front().map(|quote| {
2861 Price::new(
2862 f64::midpoint(quote.ask_price.as_f64(), quote.bid_price.as_f64()),
2863 quote.bid_price.precision + 1,
2864 )
2865 })
2866 }),
2867 PriceType::Last => self
2868 .trades
2869 .get(instrument_id)
2870 .and_then(|trades| trades.front().map(|trade| trade.price)),
2871 PriceType::Mark => self
2872 .mark_prices
2873 .get(instrument_id)
2874 .and_then(|marks| marks.front().map(|mark| mark.value)),
2875 }
2876 }
2877
2878 #[must_use]
2880 pub fn quotes(&self, instrument_id: &InstrumentId) -> Option<Vec<QuoteTick>> {
2881 self.quotes
2882 .get(instrument_id)
2883 .map(|quotes| quotes.iter().copied().collect())
2884 }
2885
2886 #[must_use]
2888 pub fn trades(&self, instrument_id: &InstrumentId) -> Option<Vec<TradeTick>> {
2889 self.trades
2890 .get(instrument_id)
2891 .map(|trades| trades.iter().copied().collect())
2892 }
2893
2894 #[must_use]
2896 pub fn mark_prices(&self, instrument_id: &InstrumentId) -> Option<Vec<MarkPriceUpdate>> {
2897 self.mark_prices
2898 .get(instrument_id)
2899 .map(|mark_prices| mark_prices.iter().copied().collect())
2900 }
2901
2902 #[must_use]
2904 pub fn index_prices(&self, instrument_id: &InstrumentId) -> Option<Vec<IndexPriceUpdate>> {
2905 self.index_prices
2906 .get(instrument_id)
2907 .map(|index_prices| index_prices.iter().copied().collect())
2908 }
2909
2910 #[must_use]
2912 pub fn bars(&self, bar_type: &BarType) -> Option<Vec<Bar>> {
2913 self.bars
2914 .get(bar_type)
2915 .map(|bars| bars.iter().copied().collect())
2916 }
2917
2918 #[must_use]
2920 pub fn order_book(&self, instrument_id: &InstrumentId) -> Option<&OrderBook> {
2921 self.books.get(instrument_id)
2922 }
2923
2924 #[must_use]
2926 pub fn order_book_mut(&mut self, instrument_id: &InstrumentId) -> Option<&mut OrderBook> {
2927 self.books.get_mut(instrument_id)
2928 }
2929
2930 #[must_use]
2932 pub fn own_order_book(&self, instrument_id: &InstrumentId) -> Option<&OwnOrderBook> {
2933 self.own_books.get(instrument_id)
2934 }
2935
2936 #[must_use]
2938 pub fn own_order_book_mut(
2939 &mut self,
2940 instrument_id: &InstrumentId,
2941 ) -> Option<&mut OwnOrderBook> {
2942 self.own_books.get_mut(instrument_id)
2943 }
2944
2945 #[cfg(feature = "defi")]
2947 #[must_use]
2948 pub fn pool(&self, instrument_id: &InstrumentId) -> Option<&Pool> {
2949 self.pools.get(instrument_id)
2950 }
2951
2952 #[cfg(feature = "defi")]
2954 #[must_use]
2955 pub fn pool_mut(&mut self, instrument_id: &InstrumentId) -> Option<&mut Pool> {
2956 self.pools.get_mut(instrument_id)
2957 }
2958
2959 #[must_use]
2961 pub fn quote(&self, instrument_id: &InstrumentId) -> Option<&QuoteTick> {
2962 self.quotes
2963 .get(instrument_id)
2964 .and_then(|quotes| quotes.front())
2965 }
2966
2967 #[must_use]
2969 pub fn trade(&self, instrument_id: &InstrumentId) -> Option<&TradeTick> {
2970 self.trades
2971 .get(instrument_id)
2972 .and_then(|trades| trades.front())
2973 }
2974
2975 #[must_use]
2977 pub fn mark_price(&self, instrument_id: &InstrumentId) -> Option<&MarkPriceUpdate> {
2978 self.mark_prices
2979 .get(instrument_id)
2980 .and_then(|mark_prices| mark_prices.front())
2981 }
2982
2983 #[must_use]
2985 pub fn index_price(&self, instrument_id: &InstrumentId) -> Option<&IndexPriceUpdate> {
2986 self.index_prices
2987 .get(instrument_id)
2988 .and_then(|index_prices| index_prices.front())
2989 }
2990
2991 #[must_use]
2993 pub fn funding_rate(&self, instrument_id: &InstrumentId) -> Option<&FundingRateUpdate> {
2994 self.funding_rates.get(instrument_id)
2995 }
2996
2997 #[must_use]
2999 pub fn bar(&self, bar_type: &BarType) -> Option<&Bar> {
3000 self.bars.get(bar_type).and_then(|bars| bars.front())
3001 }
3002
3003 #[must_use]
3005 pub fn book_update_count(&self, instrument_id: &InstrumentId) -> usize {
3006 self.books
3007 .get(instrument_id)
3008 .map_or(0, |book| book.update_count) as usize
3009 }
3010
3011 #[must_use]
3013 pub fn quote_count(&self, instrument_id: &InstrumentId) -> usize {
3014 self.quotes
3015 .get(instrument_id)
3016 .map_or(0, std::collections::VecDeque::len)
3017 }
3018
3019 #[must_use]
3021 pub fn trade_count(&self, instrument_id: &InstrumentId) -> usize {
3022 self.trades
3023 .get(instrument_id)
3024 .map_or(0, std::collections::VecDeque::len)
3025 }
3026
3027 #[must_use]
3029 pub fn bar_count(&self, bar_type: &BarType) -> usize {
3030 self.bars
3031 .get(bar_type)
3032 .map_or(0, std::collections::VecDeque::len)
3033 }
3034
3035 #[must_use]
3037 pub fn has_order_book(&self, instrument_id: &InstrumentId) -> bool {
3038 self.books.contains_key(instrument_id)
3039 }
3040
3041 #[must_use]
3043 pub fn has_quote_ticks(&self, instrument_id: &InstrumentId) -> bool {
3044 self.quote_count(instrument_id) > 0
3045 }
3046
3047 #[must_use]
3049 pub fn has_trade_ticks(&self, instrument_id: &InstrumentId) -> bool {
3050 self.trade_count(instrument_id) > 0
3051 }
3052
3053 #[must_use]
3055 pub fn has_bars(&self, bar_type: &BarType) -> bool {
3056 self.bar_count(bar_type) > 0
3057 }
3058
3059 #[must_use]
3060 pub fn get_xrate(
3061 &self,
3062 venue: Venue,
3063 from_currency: Currency,
3064 to_currency: Currency,
3065 price_type: PriceType,
3066 ) -> Option<f64> {
3067 if from_currency == to_currency {
3068 return Some(1.0);
3071 }
3072
3073 let (bid_quote, ask_quote) = self.build_quote_table(&venue);
3074
3075 match get_exchange_rate(
3076 from_currency.code,
3077 to_currency.code,
3078 price_type,
3079 bid_quote,
3080 ask_quote,
3081 ) {
3082 Ok(rate) => rate,
3083 Err(e) => {
3084 log::error!("Failed to calculate xrate: {e}");
3085 None
3086 }
3087 }
3088 }
3089
3090 fn build_quote_table(&self, venue: &Venue) -> (AHashMap<String, f64>, AHashMap<String, f64>) {
3091 let mut bid_quotes = AHashMap::new();
3092 let mut ask_quotes = AHashMap::new();
3093
3094 for instrument_id in self.instruments.keys() {
3095 if instrument_id.venue != *venue {
3096 continue;
3097 }
3098
3099 let (bid_price, ask_price) = if let Some(ticks) = self.quotes.get(instrument_id) {
3100 if let Some(tick) = ticks.front() {
3101 (tick.bid_price, tick.ask_price)
3102 } else {
3103 continue; }
3105 } else {
3106 let bid_bar = self
3107 .bars
3108 .iter()
3109 .find(|(k, _)| {
3110 k.instrument_id() == *instrument_id
3111 && matches!(k.spec().price_type, PriceType::Bid)
3112 })
3113 .map(|(_, v)| v);
3114
3115 let ask_bar = self
3116 .bars
3117 .iter()
3118 .find(|(k, _)| {
3119 k.instrument_id() == *instrument_id
3120 && matches!(k.spec().price_type, PriceType::Ask)
3121 })
3122 .map(|(_, v)| v);
3123
3124 match (bid_bar, ask_bar) {
3125 (Some(bid), Some(ask)) => {
3126 let bid_price = bid.front().unwrap().close;
3127 let ask_price = ask.front().unwrap().close;
3128
3129 (bid_price, ask_price)
3130 }
3131 _ => continue,
3132 }
3133 };
3134
3135 bid_quotes.insert(instrument_id.symbol.to_string(), bid_price.as_f64());
3136 ask_quotes.insert(instrument_id.symbol.to_string(), ask_price.as_f64());
3137 }
3138
3139 (bid_quotes, ask_quotes)
3140 }
3141
3142 #[must_use]
3144 pub fn get_mark_xrate(&self, from_currency: Currency, to_currency: Currency) -> Option<f64> {
3145 self.mark_xrates.get(&(from_currency, to_currency)).copied()
3146 }
3147
3148 pub fn set_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency, xrate: f64) {
3154 assert!(xrate > 0.0, "xrate was zero");
3155 self.mark_xrates.insert((from_currency, to_currency), xrate);
3156 self.mark_xrates
3157 .insert((to_currency, from_currency), 1.0 / xrate);
3158 }
3159
3160 pub fn clear_mark_xrate(&mut self, from_currency: Currency, to_currency: Currency) {
3162 let _ = self.mark_xrates.remove(&(from_currency, to_currency));
3163 }
3164
3165 pub fn clear_mark_xrates(&mut self) {
3167 self.mark_xrates.clear();
3168 }
3169
3170 #[must_use]
3174 pub fn instrument(&self, instrument_id: &InstrumentId) -> Option<&InstrumentAny> {
3175 self.instruments.get(instrument_id)
3176 }
3177
3178 #[must_use]
3180 pub fn instrument_ids(&self, venue: Option<&Venue>) -> Vec<&InstrumentId> {
3181 match venue {
3182 Some(v) => self.instruments.keys().filter(|i| &i.venue == v).collect(),
3183 None => self.instruments.keys().collect(),
3184 }
3185 }
3186
3187 #[must_use]
3189 pub fn instruments(&self, venue: &Venue, underlying: Option<&Ustr>) -> Vec<&InstrumentAny> {
3190 self.instruments
3191 .values()
3192 .filter(|i| &i.id().venue == venue)
3193 .filter(|i| underlying.is_none_or(|u| i.underlying() == Some(*u)))
3194 .collect()
3195 }
3196
3197 #[must_use]
3199 pub fn bar_types(
3200 &self,
3201 instrument_id: Option<&InstrumentId>,
3202 price_type: Option<&PriceType>,
3203 aggregation_source: AggregationSource,
3204 ) -> Vec<&BarType> {
3205 let mut bar_types = self
3206 .bars
3207 .keys()
3208 .filter(|bar_type| bar_type.aggregation_source() == aggregation_source)
3209 .collect::<Vec<&BarType>>();
3210
3211 if let Some(instrument_id) = instrument_id {
3212 bar_types.retain(|bar_type| bar_type.instrument_id() == *instrument_id);
3213 }
3214
3215 if let Some(price_type) = price_type {
3216 bar_types.retain(|bar_type| &bar_type.spec().price_type == price_type);
3217 }
3218
3219 bar_types
3220 }
3221
3222 #[must_use]
3226 pub fn synthetic(&self, instrument_id: &InstrumentId) -> Option<&SyntheticInstrument> {
3227 self.synthetics.get(instrument_id)
3228 }
3229
3230 #[must_use]
3232 pub fn synthetic_ids(&self) -> Vec<&InstrumentId> {
3233 self.synthetics.keys().collect()
3234 }
3235
3236 #[must_use]
3238 pub fn synthetics(&self) -> Vec<&SyntheticInstrument> {
3239 self.synthetics.values().collect()
3240 }
3241
3242 #[must_use]
3246 pub fn account(&self, account_id: &AccountId) -> Option<&AccountAny> {
3247 self.accounts.get(account_id)
3248 }
3249
3250 #[must_use]
3252 pub fn account_for_venue(&self, venue: &Venue) -> Option<&AccountAny> {
3253 self.index
3254 .venue_account
3255 .get(venue)
3256 .and_then(|account_id| self.accounts.get(account_id))
3257 }
3258
3259 #[must_use]
3261 pub fn account_id(&self, venue: &Venue) -> Option<&AccountId> {
3262 self.index.venue_account.get(venue)
3263 }
3264
3265 #[must_use]
3267 pub fn accounts(&self, account_id: &AccountId) -> Vec<&AccountAny> {
3268 self.accounts
3269 .values()
3270 .filter(|account| &account.id() == account_id)
3271 .collect()
3272 }
3273
3274 pub fn update_own_order_book(&mut self, order: &OrderAny) {
3279 let instrument_id = order.instrument_id();
3280
3281 let own_book = self
3283 .own_books
3284 .entry(instrument_id)
3285 .or_insert_with(|| OwnOrderBook::new(instrument_id));
3286
3287 let own_book_order = order.to_own_book_order();
3289
3290 if order.is_closed() {
3291 if let Err(e) = own_book.delete(own_book_order) {
3293 log::debug!(
3294 "Failed to delete order {} from own book: {}",
3295 order.client_order_id(),
3296 e
3297 );
3298 } else {
3299 log::debug!("Deleted order {} from own book", order.client_order_id());
3300 }
3301 } else {
3302 own_book.update(own_book_order).unwrap_or_else(|e| {
3304 log::debug!(
3305 "Failed to update order {} in own book: {}",
3306 order.client_order_id(),
3307 e
3308 );
3309 });
3310 log::debug!("Updated order {} in own book", order.client_order_id());
3311 }
3312 }
3313}