Skip to main content

nautilus_portfolio/
portfolio.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides a generic `Portfolio` for all environments.
17
18use std::{
19    cell::{OnceCell, RefCell},
20    collections::{BTreeSet, VecDeque},
21    fmt::Debug,
22    rc::Rc,
23};
24
25use ahash::{AHashMap, AHashSet};
26use indexmap::{IndexMap, IndexSet};
27use nautilus_analysis::{
28    analyzer::{PortfolioAnalyzer, Statistic},
29    snapshot::PortfolioStatistics,
30};
31use nautilus_common::{
32    cache::{AccountLookupError, AccountRef, Cache, OrderRef},
33    clock::Clock,
34    enums::LogColor,
35    msgbus::{self, MessagingSwitchboard, TypedHandler, TypedIntoHandler},
36    timer::{TimeEvent, TimeEventCallback},
37};
38use nautilus_core::{DurationNanos, UUID4, UnixNanos, WeakCell};
39use nautilus_model::{
40    accounts::{Account, AccountAny},
41    data::{Bar, MarkPriceUpdate, QuoteTick},
42    enums::{OmsType, OrderType, PositionSide, PriceType},
43    events::{AccountState, OrderEventAny, PortfolioSnapshot, position::PositionEvent},
44    identifiers::{AccountId, InstrumentId, PositionId, Venue},
45    instruments::{Instrument, InstrumentAny},
46    orders::{Order, OrderAny},
47    position::{Position, PositionReplayEvent},
48    types::{AccountBalance, Currency, MarginBalance, Money, Price},
49};
50use rust_decimal::Decimal;
51
52use crate::{config::PortfolioConfig, manager::AccountsManager};
53
54// Sized for post-run backtest analysis (e.g. ~11 days at 1s cadence, or years
55// at per-minute cadence), long-lived live deployments should consume snapshots
56// via the message bus instead of relying on this buffer.
57const SNAPSHOT_BUFFER_CAP: usize = 1_000_000;
58const EQUITY_CURVE_TIMER_PREFIX: &str = "portfolio_equity_curve.";
59const SNAPSHOT_TIMER_PREFIX: &str = "portfolio_snapshot.";
60
61struct PortfolioState {
62    accounts: AccountsManager,
63    analyzer: PortfolioAnalyzer,
64    unrealized_pnls: IndexMap<InstrumentId, Money>,
65    realized_pnls: IndexMap<InstrumentId, Money>,
66    recorded_closed_position_cycles: AHashSet<(PositionId, UnixNanos, Option<[u8; 16]>)>,
67    snapshot_sum_per_position: AHashMap<PositionId, Money>,
68    snapshot_last_per_position: AHashMap<PositionId, LastSnapshotFrame>,
69    snapshot_currency_mismatches: AHashSet<PositionId>,
70    snapshot_aggregation_overflows: AHashSet<PositionId>,
71    snapshot_processed_counts: AHashMap<PositionId, usize>,
72    snapshot_processed_revisions: AHashMap<PositionId, u64>,
73    snapshot_account_ids: AHashMap<PositionId, AccountId>,
74    net_positions: IndexMap<InstrumentId, Decimal>,
75    pending_calcs: AHashSet<InstrumentId>,
76    bar_close_prices: AHashMap<InstrumentId, Price>,
77    last_prices: AHashMap<(InstrumentId, PositionSide), Price>,
78    last_xrates: AHashMap<(Venue, Currency, Currency), Decimal>,
79    stale_prices: AHashSet<(InstrumentId, PositionSide)>,
80    stale_xrates: AHashSet<(Venue, Currency, Currency)>,
81    initialized: bool,
82    last_account_state_log_ts: AHashMap<AccountId, UnixNanos>,
83    last_published_account_states: AHashMap<AccountId, UUID4>,
84    min_account_state_logging_interval_ns: DurationNanos,
85    venues_missing_price: AHashMap<Venue, AHashMap<Option<AccountId>, AHashSet<InstrumentId>>>,
86    account_open_positions: AHashMap<AccountId, usize>,
87    equity_curve_accounts: AHashSet<AccountId>,
88    equity_curve_finalized: bool,
89    portfolio_snapshots: AHashMap<AccountId, VecDeque<PortfolioSnapshot>>,
90    pre_position_fill_events: AHashSet<UUID4>,
91    balance_error: Option<String>,
92}
93
94struct LastSnapshotFrame {
95    realized_pnl: Money,
96    fill_ids: AHashSet<UUID4>,
97}
98
99impl LastSnapshotFrame {
100    fn new(snapshot: &Position, realized_pnl: Money) -> Self {
101        Self {
102            realized_pnl,
103            fill_ids: snapshot.events.iter().map(|fill| fill.event_id).collect(),
104        }
105    }
106
107    fn duplicates_closed_cycle(&self, position: &Position) -> bool {
108        if position.is_open() || position.realized_pnl != Some(self.realized_pnl) {
109            return false;
110        }
111
112        if position.events.is_empty() {
113            // Replay retains the cycle's fill IDs after every effective fill has been voided
114            self.fill_ids.is_empty()
115                || position.replay_events.iter().any(|event| {
116                    matches!(event, PositionReplayEvent::Filled(fill) if self.fill_ids.contains(&fill.event_id))
117                })
118        } else {
119            position
120                .events
121                .iter()
122                .any(|fill| self.fill_ids.contains(&fill.event_id))
123        }
124    }
125}
126
127#[derive(Clone, Copy)]
128enum OrderUpdateSource {
129    Endpoint,
130    Topic,
131}
132
133#[derive(Clone, Copy, PartialEq, Eq)]
134enum MarkValueMode {
135    Gross,
136    Equity,
137    Premium,
138}
139
140#[derive(Clone, Copy, PartialEq, Eq)]
141enum UnrealizedPnlError {
142    MissingInput,
143    Invalid,
144}
145
146impl PortfolioState {
147    fn new(
148        clock: Rc<RefCell<dyn Clock>>,
149        cache: Rc<RefCell<Cache>>,
150        config: &PortfolioConfig,
151    ) -> Self {
152        let min_account_state_logging_interval_ns = config
153            .min_account_state_logging_interval_ms
154            .map(DurationNanos::from_millis)
155            .unwrap_or_default();
156
157        Self {
158            accounts: AccountsManager::new(clock, cache),
159            analyzer: PortfolioAnalyzer::default(),
160            unrealized_pnls: IndexMap::new(),
161            realized_pnls: IndexMap::new(),
162            recorded_closed_position_cycles: AHashSet::new(),
163            snapshot_sum_per_position: AHashMap::new(),
164            snapshot_last_per_position: AHashMap::new(),
165            snapshot_currency_mismatches: AHashSet::new(),
166            snapshot_aggregation_overflows: AHashSet::new(),
167            snapshot_processed_counts: AHashMap::new(),
168            snapshot_processed_revisions: AHashMap::new(),
169            snapshot_account_ids: AHashMap::new(),
170            net_positions: IndexMap::new(),
171            pending_calcs: AHashSet::new(),
172            bar_close_prices: AHashMap::new(),
173            last_prices: AHashMap::new(),
174            last_xrates: AHashMap::new(),
175            stale_prices: AHashSet::new(),
176            stale_xrates: AHashSet::new(),
177            initialized: false,
178            last_account_state_log_ts: AHashMap::new(),
179            last_published_account_states: AHashMap::new(),
180            min_account_state_logging_interval_ns,
181            venues_missing_price: AHashMap::new(),
182            account_open_positions: AHashMap::new(),
183            equity_curve_accounts: AHashSet::new(),
184            equity_curve_finalized: false,
185            portfolio_snapshots: AHashMap::new(),
186            pre_position_fill_events: AHashSet::new(),
187            balance_error: None,
188        }
189    }
190
191    fn reset(&mut self) {
192        log::debug!("RESETTING");
193        self.net_positions.clear();
194        self.unrealized_pnls.clear();
195        self.realized_pnls.clear();
196        self.recorded_closed_position_cycles.clear();
197        self.snapshot_sum_per_position.clear();
198        self.snapshot_last_per_position.clear();
199        self.snapshot_currency_mismatches.clear();
200        self.snapshot_aggregation_overflows.clear();
201        self.snapshot_processed_counts.clear();
202        self.snapshot_processed_revisions.clear();
203        self.snapshot_account_ids.clear();
204        self.pending_calcs.clear();
205        self.bar_close_prices.clear();
206        self.last_prices.clear();
207        self.last_xrates.clear();
208        self.stale_prices.clear();
209        self.stale_xrates.clear();
210        self.last_account_state_log_ts.clear();
211        self.last_published_account_states.clear();
212        self.venues_missing_price.clear();
213        self.account_open_positions.clear();
214        self.equity_curve_accounts.clear();
215        self.equity_curve_finalized = false;
216        self.portfolio_snapshots.clear();
217        self.pre_position_fill_events.clear();
218        self.balance_error = None;
219        self.analyzer.reset();
220        self.initialized = false;
221        log::debug!("READY");
222    }
223}
224
225pub struct Portfolio {
226    pub(crate) clock: Rc<RefCell<dyn Clock>>,
227    pub(crate) cache: Rc<RefCell<Cache>>,
228    inner: Rc<RefCell<PortfolioState>>,
229    config: PortfolioConfig,
230}
231
232impl Debug for Portfolio {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        f.debug_struct(stringify!(Portfolio)).finish()
235    }
236}
237
238impl Portfolio {
239    pub fn new(
240        clock: Rc<RefCell<dyn Clock>>,
241        cache: Rc<RefCell<Cache>>,
242        config: Option<PortfolioConfig>,
243    ) -> Self {
244        let config = config.unwrap_or_default();
245        let inner = Rc::new(RefCell::new(PortfolioState::new(
246            Rc::clone(&clock),
247            Rc::clone(&cache),
248            &config,
249        )));
250
251        Self::register_message_handlers(&cache, &clock, &inner, config);
252
253        Self {
254            clock,
255            cache,
256            inner,
257            config,
258        }
259    }
260
261    /// Creates a shallow clone of the Portfolio that shares the same internal state.
262    ///
263    /// This is useful when multiple components need to reference the same Portfolio
264    /// without creating duplicate msgbus handler registrations.
265    #[must_use]
266    pub fn clone_shallow(&self) -> Self {
267        Self {
268            clock: Rc::clone(&self.clock),
269            cache: Rc::clone(&self.cache),
270            inner: Rc::clone(&self.inner),
271            config: self.config,
272        }
273    }
274
275    fn register_message_handlers(
276        cache: &Rc<RefCell<Cache>>,
277        clock: &Rc<RefCell<dyn Clock>>,
278        inner: &Rc<RefCell<PortfolioState>>,
279        config: PortfolioConfig,
280    ) {
281        let inner_weak = WeakCell::from(Rc::downgrade(inner));
282
283        // Typed handlers for subscriptions
284        let update_account_handler = {
285            let cache = Rc::clone(cache);
286            let clock = Rc::clone(clock);
287            let inner = WeakCell::clone(&inner_weak);
288
289            TypedHandler::from(move |event: &AccountState| {
290                if let Some(inner_rc) = inner.upgrade() {
291                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
292                    update_account(&clock, &cache, &inner_rc, config, event);
293                }
294            })
295        };
296
297        let update_position_handler = {
298            let cache = Rc::clone(cache);
299            let clock = Rc::clone(clock);
300            let inner = WeakCell::clone(&inner_weak);
301            TypedHandler::from(move |event: &PositionEvent| {
302                if let Some(inner_rc) = inner.upgrade() {
303                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
304                    update_position(&cache, &clock, &inner_rc, config, event);
305                }
306            })
307        };
308
309        let update_quote_handler = {
310            let cache = Rc::clone(cache);
311            let clock = Rc::clone(clock);
312            let inner = WeakCell::clone(&inner_weak);
313            TypedHandler::from(move |quote: &QuoteTick| {
314                if let Some(inner_rc) = inner.upgrade() {
315                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
316                    update_quote_tick(&cache, &clock, &inner_rc, config, quote);
317                }
318            })
319        };
320
321        let update_bar_handler = {
322            let cache = Rc::clone(cache);
323            let clock = Rc::clone(clock);
324            let inner = WeakCell::clone(&inner_weak);
325            TypedHandler::from(move |bar: &Bar| {
326                if let Some(inner_rc) = inner.upgrade() {
327                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
328                    update_bar(&cache, &clock, &inner_rc, config, bar);
329                }
330            })
331        };
332
333        let update_mark_price_handler = {
334            let cache = Rc::clone(cache);
335            let clock = Rc::clone(clock);
336            let inner = WeakCell::clone(&inner_weak);
337            TypedHandler::from(move |mark_price: &MarkPriceUpdate| {
338                if let Some(inner_rc) = inner.upgrade() {
339                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
340                    update_instrument_id(
341                        &cache,
342                        &clock,
343                        &inner_rc,
344                        config,
345                        &mark_price.instrument_id,
346                    );
347                }
348            })
349        };
350
351        let update_order_handler = {
352            let cache = Rc::clone(cache);
353            let clock = Rc::clone(clock);
354            let inner = WeakCell::clone(&inner_weak);
355            TypedHandler::from(move |event: &OrderEventAny| {
356                if let Some(inner_rc) = inner.upgrade() {
357                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
358                    on_order_event(&cache, &clock, &inner_rc, config, event);
359                }
360            })
361        };
362
363        let endpoint = MessagingSwitchboard::portfolio_update_account();
364        msgbus::register_account_state_endpoint(endpoint, update_account_handler);
365
366        let update_order_endpoint_handler = {
367            let cache = Rc::clone(cache);
368            let clock = Rc::clone(clock);
369            let inner = inner_weak;
370            TypedIntoHandler::from(move |event: OrderEventAny| {
371                if let Some(inner_rc) = inner.upgrade() {
372                    let inner_rc: Rc<RefCell<PortfolioState>> = inner_rc.into();
373                    update_order(
374                        &cache,
375                        &clock,
376                        &inner_rc,
377                        config,
378                        &event,
379                        OrderUpdateSource::Endpoint,
380                    );
381                }
382            })
383        };
384        msgbus::register_order_event_endpoint(
385            MessagingSwitchboard::portfolio_update_order(),
386            update_order_endpoint_handler,
387        );
388
389        msgbus::subscribe_quotes("data.quotes.*".into(), update_quote_handler, Some(10));
390
391        if config.bar_updates {
392            msgbus::subscribe_bars("data.bars.*EXTERNAL".into(), update_bar_handler, Some(10));
393        }
394
395        if config.use_mark_prices {
396            msgbus::subscribe_mark_prices(
397                "data.mark_prices.*".into(),
398                update_mark_price_handler,
399                Some(10),
400            );
401        }
402        msgbus::subscribe_order_events("events.order.*".into(), update_order_handler, Some(10));
403        msgbus::subscribe_position_events(
404            "events.position.*".into(),
405            update_position_handler,
406            Some(10),
407        );
408    }
409
410    pub fn reset(&mut self) {
411        log::debug!("RESETTING");
412        let (snapshot_accounts, equity_curve_accounts) = {
413            let inner = self.inner.borrow();
414            (
415                inner
416                    .account_open_positions
417                    .keys()
418                    .copied()
419                    .collect::<Vec<_>>(),
420                inner
421                    .equity_curve_accounts
422                    .iter()
423                    .copied()
424                    .collect::<Vec<_>>(),
425            )
426        };
427
428        for account_id in snapshot_accounts {
429            self.clock
430                .borrow_mut()
431                .cancel_timer(&snapshot_timer_name(account_id));
432        }
433
434        for account_id in equity_curve_accounts {
435            self.clock
436                .borrow_mut()
437                .cancel_timer(&equity_curve_timer_name(account_id));
438        }
439        self.inner.borrow_mut().reset();
440        log::debug!("READY");
441    }
442
443    /// Returns a reference to the cache.
444    #[must_use]
445    pub fn cache(&self) -> &Rc<RefCell<Cache>> {
446        &self.cache
447    }
448
449    /// Returns a reference to the clock.
450    #[must_use]
451    pub fn clock(&self) -> &Rc<RefCell<dyn Clock>> {
452        &self.clock
453    }
454
455    /// Returns `true` if the portfolio has been initialized.
456    #[must_use]
457    pub fn is_initialized(&self) -> bool {
458        self.inner.borrow().initialized
459    }
460
461    /// Returns the locked balances for the `account_id`, or for the account issued under `venue`
462    /// when no account ID is given.
463    ///
464    /// Locked balances represent funds reserved for open orders. A venue-only query resolves only
465    /// when exactly one account is issued under the venue; otherwise it returns an empty map.
466    #[must_use]
467    pub fn balances_locked(
468        &self,
469        venue: &Venue,
470        account_id: Option<&AccountId>,
471    ) -> IndexMap<Currency, Money> {
472        let cache = self.cache.borrow();
473        resolve_account(&cache, Some(venue), account_id).map_or_else(
474            || {
475                log::error!(
476                    "Cannot get balances locked: no account resolved for venue={venue}, account_id={account_id:?}"
477                );
478                IndexMap::new()
479            },
480            |account| account.balances_locked(),
481        )
482    }
483
484    /// Returns the initial margin requirements for the `account_id`, or for the account issued
485    /// under `venue` when no account ID is given.
486    ///
487    /// Only applicable for margin accounts. Returns empty map for cash accounts. A venue-only
488    /// query resolves only when exactly one account is issued under the venue; otherwise it
489    /// returns an empty map.
490    #[must_use]
491    pub fn instrument_initial_margins(
492        &self,
493        venue: &Venue,
494        account_id: Option<&AccountId>,
495    ) -> IndexMap<InstrumentId, Money> {
496        let cache = self.cache.borrow();
497        resolve_account(&cache, Some(venue), account_id).map_or_else(
498            || {
499                log::error!(
500                    "Cannot get initial (order) margins: no account resolved for venue={venue}, account_id={account_id:?}"
501                );
502                IndexMap::new()
503            },
504            |account| match &*account {
505                AccountAny::Margin(margin_account) => margin_account.initial_margins(),
506                AccountAny::Cash(_) | AccountAny::Betting(_) | AccountAny::Wallet(_) => {
507                    log::warn!("Initial margins not applicable for unleveraged account");
508                    IndexMap::new()
509                }
510            },
511        )
512    }
513
514    /// Returns the maintenance margin requirements for the `account_id`, or for the account
515    /// issued under `venue` when no account ID is given.
516    ///
517    /// Only applicable for margin accounts. Returns empty map for cash accounts. A venue-only
518    /// query resolves only when exactly one account is issued under the venue; otherwise it
519    /// returns an empty map.
520    #[must_use]
521    pub fn instrument_maintenance_margins(
522        &self,
523        venue: &Venue,
524        account_id: Option<&AccountId>,
525    ) -> IndexMap<InstrumentId, Money> {
526        let cache = self.cache.borrow();
527        resolve_account(&cache, Some(venue), account_id).map_or_else(
528            || {
529                log::error!(
530                    "Cannot get maintenance (position) margins: no account resolved for venue={venue}, account_id={account_id:?}"
531                );
532                IndexMap::new()
533            },
534            |account| match &*account {
535                AccountAny::Margin(margin_account) => margin_account.maintenance_margins(),
536                AccountAny::Cash(_) | AccountAny::Betting(_) | AccountAny::Wallet(_) => {
537                    log::warn!("Maintenance margins not applicable for unleveraged account");
538                    IndexMap::new()
539                }
540            },
541        )
542    }
543
544    /// Returns the unrealized PnLs for all positions at the given venue.
545    ///
546    /// Calculates mark-to-market PnL based on current market prices.
547    #[must_use]
548    pub fn unrealized_pnls(
549        &mut self,
550        venue: &Venue,
551        account_id: Option<&AccountId>,
552        target_currency: Option<Currency>,
553    ) -> Option<IndexMap<Currency, Money>> {
554        let (unrealized_pnls, unpriced) =
555            self.unrealized_pnls_with_missing(*venue, account_id, target_currency)?;
556
557        if account_id.is_some() {
558            self.update_missing_price_state(*venue, account_id.copied(), &unpriced);
559        }
560
561        if unpriced.is_empty() {
562            Some(unrealized_pnls)
563        } else {
564            None
565        }
566    }
567
568    fn unrealized_pnls_with_missing(
569        &self,
570        venue: Venue,
571        account_id: Option<&AccountId>,
572        target_currency: Option<Currency>,
573    ) -> Option<(IndexMap<Currency, Money>, AHashSet<InstrumentId>)> {
574        let instrument_ids = {
575            let cache = self.cache.borrow();
576            let positions = cache.positions_open(Some(&venue), None, None, account_id, None);
577
578            if positions.is_empty() {
579                return Some((IndexMap::new(), AHashSet::new()));
580            }
581
582            // IndexSet preserves the deterministic order of cache.positions
583            // through the dedup so the returned currency map iterates in a
584            // stable order across runs.
585            let instrument_ids: IndexSet<InstrumentId> =
586                positions.iter().map(|p| p.instrument_id).collect();
587
588            instrument_ids
589        };
590
591        let mut unrealized_pnls: IndexMap<Currency, Money> = IndexMap::new();
592        let mut unpriced: AHashSet<InstrumentId> = AHashSet::new();
593
594        for instrument_id in instrument_ids {
595            match self.unrealized_pnls_by_account(&instrument_id, None, account_id, target_currency)
596            {
597                Ok(pnls) => {
598                    for pnl in pnls {
599                        checked_add_money_map(&mut unrealized_pnls, pnl, "unrealized PnLs")?;
600                    }
601                }
602                Err(UnrealizedPnlError::MissingInput) => {
603                    unpriced.insert(instrument_id);
604                }
605                Err(UnrealizedPnlError::Invalid) => return None,
606            }
607        }
608
609        Some((unrealized_pnls, unpriced))
610    }
611
612    /// Returns the realized PnLs for all positions at the given venue.
613    ///
614    /// Calculates total realized profit and loss from closed positions.
615    #[must_use]
616    pub fn realized_pnls(
617        &mut self,
618        venue: &Venue,
619        account_id: Option<&AccountId>,
620        target_currency: Option<Currency>,
621    ) -> Option<IndexMap<Currency, Money>> {
622        let instrument_ids = {
623            let cache = self.cache.borrow();
624            let positions = cache.positions(Some(venue), None, None, account_id, None);
625
626            if positions.is_empty() {
627                return Some(IndexMap::new()); // Nothing to calculate
628            }
629
630            let instrument_ids: IndexSet<InstrumentId> =
631                positions.iter().map(|p| p.instrument_id).collect();
632
633            instrument_ids
634        };
635
636        let mut realized_pnls: IndexMap<Currency, Money> = IndexMap::new();
637
638        for instrument_id in instrument_ids {
639            self.ensure_snapshot_pnls_cached_for(&instrument_id);
640            for pnl in self.realized_pnls_by_account(&instrument_id, account_id, target_currency)? {
641                checked_add_money_map(&mut realized_pnls, pnl, "realized PnLs")?;
642            }
643        }
644
645        Some(realized_pnls)
646    }
647
648    #[must_use]
649    pub fn net_exposures(
650        &self,
651        venue: &Venue,
652        account_id: Option<&AccountId>,
653        target_currency: Option<Currency>,
654    ) -> Option<IndexMap<Currency, Money>> {
655        let cache = self.cache.borrow();
656
657        if let Some(id) = account_id
658            && cache.account(id).is_none()
659        {
660            log::error!("Cannot calculate net exposures: no account for {id}");
661            return None;
662        }
663
664        if account_id.is_none() && cache.account_for_venue(venue).is_none() {
665            let has_position_account = cache
666                .positions(Some(venue), None, None, None, None)
667                .iter()
668                .any(|position| cache.account(&position.account_id).is_some());
669            if !has_position_account {
670                log::error!("Cannot calculate net exposures: no account registered for {venue}");
671                return None;
672            }
673        }
674
675        let instrument_ids: IndexSet<InstrumentId> = {
676            let positions_open = cache.positions_open(Some(venue), None, None, account_id, None);
677            if positions_open.is_empty() {
678                return Some(IndexMap::new()); // Nothing to calculate
679            }
680            positions_open
681                .iter()
682                .map(|position| position.instrument_id)
683                .collect()
684        };
685        drop(cache);
686
687        let mut net_exposures = IndexMap::new();
688
689        for instrument_id in instrument_ids {
690            let exposure = self.net_exposure(&instrument_id, None, account_id, target_currency)?;
691            if exposure.is_zero() {
692                continue;
693            }
694            checked_add_money_map(&mut net_exposures, exposure, "net exposures")?;
695        }
696
697        Some(net_exposures)
698    }
699
700    #[must_use]
701    pub fn unrealized_pnl(&mut self, instrument_id: &InstrumentId) -> Option<Money> {
702        self.unrealized_pnl_for_account(instrument_id, None, None, None)
703    }
704
705    #[must_use]
706    pub fn unrealized_pnl_for_account(
707        &mut self,
708        instrument_id: &InstrumentId,
709        price: Option<Price>,
710        account_id: Option<&AccountId>,
711        target_currency: Option<Currency>,
712    ) -> Option<Money> {
713        let use_cache = price.is_none() && account_id.is_none() && target_currency.is_none();
714        if use_cache {
715            let has_open_position = !self
716                .cache
717                .borrow()
718                .positions_open(None, Some(instrument_id), None, None, None)
719                .is_empty();
720
721            if !has_open_position
722                && let Some(pnl) = self
723                    .inner
724                    .borrow()
725                    .unrealized_pnls
726                    .get(instrument_id)
727                    .copied()
728            {
729                return Some(pnl);
730            }
731        }
732
733        let pnl = self
734            .aggregate_unrealized_pnl_by_account(instrument_id, price, account_id, target_currency)
735            .ok()?;
736
737        if use_cache {
738            self.inner
739                .borrow_mut()
740                .unrealized_pnls
741                .insert(*instrument_id, pnl);
742        }
743        Some(pnl)
744    }
745
746    #[must_use]
747    pub fn realized_pnl(&mut self, instrument_id: &InstrumentId) -> Option<Money> {
748        self.realized_pnl_for_account(instrument_id, None, None)
749    }
750
751    #[must_use]
752    pub fn realized_pnl_for_account(
753        &mut self,
754        instrument_id: &InstrumentId,
755        account_id: Option<&AccountId>,
756        target_currency: Option<Currency>,
757    ) -> Option<Money> {
758        self.ensure_snapshot_pnls_cached_for(instrument_id);
759
760        let use_cache = account_id.is_none() && target_currency.is_none();
761        let pnl =
762            self.aggregate_realized_pnl_by_account(instrument_id, account_id, target_currency)?;
763
764        if use_cache {
765            self.inner
766                .borrow_mut()
767                .realized_pnls
768                .insert(*instrument_id, pnl);
769        }
770        Some(pnl)
771    }
772
773    /// Returns the total PnL for the given instrument ID.
774    ///
775    /// Total PnL = Realized PnL + Unrealized PnL
776    #[must_use]
777    pub fn total_pnl(&mut self, instrument_id: &InstrumentId) -> Option<Money> {
778        self.total_pnl_for_account(instrument_id, None, None, None)
779    }
780
781    #[must_use]
782    pub fn total_pnl_for_account(
783        &mut self,
784        instrument_id: &InstrumentId,
785        price: Option<Price>,
786        account_id: Option<&AccountId>,
787        target_currency: Option<Currency>,
788    ) -> Option<Money> {
789        let realized = self.realized_pnl_for_account(instrument_id, account_id, target_currency)?;
790        let unrealized =
791            self.unrealized_pnl_for_account(instrument_id, price, account_id, target_currency)?;
792
793        checked_add_money(realized, unrealized, "total PnL")
794    }
795
796    /// Returns the total PnLs for the given venue.
797    ///
798    /// Total PnL = Realized PnL + Unrealized PnL for each currency. Pass `account_id`
799    /// to scope the aggregation to a single account when multiple accounts share the venue.
800    #[must_use]
801    pub fn total_pnls(
802        &mut self,
803        venue: &Venue,
804        account_id: Option<&AccountId>,
805        target_currency: Option<Currency>,
806    ) -> Option<IndexMap<Currency, Money>> {
807        let realized_pnls = self.realized_pnls(venue, account_id, target_currency)?;
808        let unrealized_pnls = self.unrealized_pnls(venue, account_id, target_currency)?;
809
810        let mut total_pnls = realized_pnls;
811        for unrealized in unrealized_pnls.into_values() {
812            checked_add_money_map(&mut total_pnls, unrealized, "total PnLs")?;
813        }
814
815        Some(total_pnls)
816    }
817
818    /// Returns the per-currency mark-to-market value of open positions at the given venue.
819    ///
820    /// For each open position the valuation uses the portfolio's internal price
821    /// resolution, which prefers mark prices (when configured), falls back to
822    /// side-appropriate bid/ask, then last trade, then the most recent bar close.
823    /// Instruments without any available price are skipped and the venue is flagged
824    /// for a no-price warning. Pass `account_id` to scope the aggregation to a
825    /// single account when multiple accounts share the venue.
826    /// Returns an empty map if a per-currency total exceeds [`Money`] bounds.
827    #[must_use]
828    pub fn mark_values(
829        &mut self,
830        venue: &Venue,
831        account_id: Option<&AccountId>,
832    ) -> IndexMap<Currency, Money> {
833        self.mark_values_with_mode(*venue, account_id, MarkValueMode::Gross)
834    }
835
836    /// Returns the per-currency total equity for the given venue.
837    ///
838    /// For cash accounts: `balance.total + Σ mark_value(open positions)` per currency.
839    /// For calculated margin accounts: balance total plus signed mark values of premium-based
840    /// positions and unrealized PnL of other open positions, per currency.
841    /// For reported margin accounts: balance total plus unrealized PnL of all open positions.
842    /// Calculated accounts have `calculate_account_state` enabled and update balances from fills.
843    ///
844    /// Open-position instruments that cannot be priced are tracked via
845    /// [`Portfolio::missing_price_instruments`] (and warned once) for all account types,
846    /// so equity understatement does not go unnoticed. Pass `account_id` to scope
847    /// the aggregation to a single account when multiple accounts share the venue.
848    /// Venue-wide queries select premium mark or PnL valuation by each position's owning account.
849    /// Returns an empty map if a per-currency total exceeds [`Money`] bounds.
850    #[must_use]
851    pub fn equity(
852        &mut self,
853        venue: &Venue,
854        account_id: Option<&AccountId>,
855    ) -> IndexMap<Currency, Money> {
856        let (mut equity, is_margin) = {
857            let cache = self.cache.borrow();
858            let account = match account_id {
859                Some(id) => cache.account(id),
860                None => cache.account_for_venue(venue).or_else(|| {
861                    cache
862                        .positions(Some(venue), None, None, None, None)
863                        .into_iter()
864                        .next()
865                        .and_then(|p| cache.account(&p.account_id))
866                }),
867            };
868
869            match account {
870                Some(account) => {
871                    let equity: IndexMap<Currency, Decimal> = account
872                        .balances_total()
873                        .into_iter()
874                        .map(|(c, m)| (c, m.as_decimal()))
875                        .collect();
876                    (equity, matches!(&*account, AccountAny::Margin(_)))
877                }
878                None => return IndexMap::new(),
879            }
880        };
881
882        let mut unpriced: AHashSet<InstrumentId> = AHashSet::new();
883        if is_margin {
884            if self.accumulate_margin_equity(*venue, account_id, &mut equity, &mut unpriced) {
885                self.update_missing_price_state(*venue, account_id.copied(), &unpriced);
886            } else {
887                self.clear_missing_price_state(*venue, account_id.copied());
888            }
889        } else if self.accumulate_mark_values(
890            *venue,
891            account_id,
892            &mut equity,
893            &mut unpriced,
894            MarkValueMode::Equity,
895        ) {
896            self.update_missing_price_state(*venue, account_id.copied(), &unpriced);
897        } else {
898            self.clear_missing_price_state(*venue, account_id.copied());
899        }
900
901        decimal_map_to_money(equity).unwrap_or_default()
902    }
903
904    /// Builds a [`PortfolioSnapshot`] for the given account at the current clock time.
905    ///
906    /// Unrealized PnL and mark values span the venues the account currently
907    /// holds open positions on; realized PnL spans every venue the account has
908    /// touched (open or closed) so a multi-venue account where one venue is
909    /// now flat still reports its accumulated realized PnL. Returns `None` if
910    /// no account is registered or exact PnL or equity valuation fails, such as a
911    /// per-currency total exceeding [`Money`] bounds.
912    ///
913    /// Unpriced open positions are also recorded in the missing-price tracker
914    /// under the account's scope (see [`Portfolio::missing_price_instruments`]).
915    #[must_use]
916    pub fn build_snapshot(&mut self, account_id: &AccountId) -> Option<PortfolioSnapshot> {
917        self.build_snapshot_inner(*account_id, true)
918    }
919
920    fn build_snapshot_inner(
921        &mut self,
922        account_id: AccountId,
923        track_missing_prices: bool,
924    ) -> Option<PortfolioSnapshot> {
925        let account_id = &account_id;
926        // The snapshot reads only current balances and margins, so skip copying the account
927        // event history, which grows with every account state
928        let account = self
929            .cache
930            .borrow()
931            .account_ref(account_id)
932            .map(|account| account.clone_without_events())?;
933
934        let balances: Vec<AccountBalance> = account.balances().into_values().collect();
935        let margins: Vec<MarginBalance> = match &account {
936            AccountAny::Margin(m) => m
937                .margins
938                .values()
939                .copied()
940                .chain(m.account_margins.values().copied())
941                .collect(),
942            AccountAny::Cash(_) | AccountAny::Betting(_) | AccountAny::Wallet(_) => Vec::new(),
943        };
944
945        // Collect venues the account has touched. `open_venues` drives the
946        // unrealized PnL and mark-value sums; `all_venues` extends to closed
947        // positions so realized PnL on a venue with no open exposure (a
948        // multi-venue account where one venue is now flat) still rolls up.
949        let (open_venues, open_instrument_ids, open_price_keys) = {
950            let cache = self.cache.borrow();
951            let positions = cache.positions_open(None, None, None, Some(account_id), None);
952            let venues: AHashSet<Venue> = positions
953                .iter()
954                .map(|position| position.instrument_id.venue)
955                .collect();
956            let instrument_ids: AHashSet<InstrumentId> = positions
957                .iter()
958                .map(|position| position.instrument_id)
959                .collect();
960            let price_keys: AHashSet<(InstrumentId, PositionSide)> = positions
961                .iter()
962                .map(|position| (position.instrument_id, position.side))
963                .collect();
964            (venues, instrument_ids, price_keys)
965        };
966        let all_venues: AHashSet<Venue> = self
967            .cache
968            .borrow()
969            .positions(None, None, None, Some(account_id), None)
970            .iter()
971            .map(|p| p.instrument_id.venue)
972            .collect();
973        let mut unrealized: IndexMap<Currency, Money> = IndexMap::new();
974        let mut realized: IndexMap<Currency, Money> = IndexMap::new();
975        let mut snapshot_unpriced = AHashSet::new();
976
977        for venue in &open_venues {
978            let (unrealized_pnls, venue_unpriced) =
979                self.unrealized_pnls_with_missing(*venue, Some(account_id), None)?;
980
981            if track_missing_prices {
982                self.update_missing_price_state(*venue, Some(*account_id), &venue_unpriced);
983            }
984            snapshot_unpriced.extend(venue_unpriced);
985
986            for money in unrealized_pnls.into_values() {
987                checked_add_money_map(&mut unrealized, money, "snapshot unrealized PnL")?;
988            }
989        }
990
991        for venue in &all_venues {
992            let realized_pnls = match self.realized_pnls(venue, Some(account_id), None) {
993                Some(pnls) => pnls,
994                None if !self.has_nonzero_realized_pnl(*venue, *account_id) => IndexMap::new(),
995                None => return None,
996            };
997
998            for money in realized_pnls.into_values() {
999                checked_add_money_map(&mut realized, money, "snapshot realized PnL")?;
1000            }
1001        }
1002
1003        let equity = self.calculate_snapshot_equity(
1004            &account,
1005            &open_venues,
1006            &unrealized,
1007            &mut snapshot_unpriced,
1008            track_missing_prices,
1009        )?;
1010
1011        let base_currency_equity = if self.config.convert_to_account_base_currency {
1012            account
1013                .base_currency()
1014                .and_then(|currency| equity.get(&currency).copied())
1015        } else {
1016            None
1017        };
1018        let (mut stale_instruments, mut stale_currencies, mut unpriced_instruments) = {
1019            let inner = self.inner.borrow();
1020            let stale_instruments = inner
1021                .stale_prices
1022                .iter()
1023                .filter(|key| open_price_keys.contains(key))
1024                .map(|(instrument_id, _)| *instrument_id)
1025                .collect::<AHashSet<_>>()
1026                .into_iter()
1027                .collect::<Vec<_>>();
1028            let stale_currencies = account
1029                .base_currency()
1030                .map_or_else(Vec::new, |base_currency| {
1031                    inner
1032                        .stale_xrates
1033                        .iter()
1034                        .filter(|(venue, _, target)| {
1035                            open_venues.contains(venue) && *target == base_currency
1036                        })
1037                        .map(|(_, source, _)| *source)
1038                        .collect::<AHashSet<_>>()
1039                        .into_iter()
1040                        .collect()
1041                });
1042            let unpriced_instruments: Vec<InstrumentId> = snapshot_unpriced
1043                .iter()
1044                .filter(|instrument_id| open_instrument_ids.contains(instrument_id))
1045                .copied()
1046                .collect();
1047            (stale_instruments, stale_currencies, unpriced_instruments)
1048        };
1049        stale_instruments.sort_unstable();
1050        stale_currencies.sort_unstable_by_key(|currency| currency.code);
1051        unpriced_instruments.sort_unstable();
1052        let is_stale = !stale_instruments.is_empty()
1053            || !stale_currencies.is_empty()
1054            || !unpriced_instruments.is_empty();
1055
1056        let unrealized_pnls: Vec<Money> = unrealized.into_values().collect();
1057        let realized_pnls: Vec<Money> = realized.into_values().collect();
1058        let total_equity: Vec<Money> = equity.into_values().collect();
1059
1060        let ts_now = self.clock.borrow().timestamp_ns();
1061
1062        Some(PortfolioSnapshot::new(
1063            account.id(),
1064            account.account_type(),
1065            account.base_currency(),
1066            balances,
1067            margins,
1068            unrealized_pnls,
1069            realized_pnls,
1070            total_equity,
1071            base_currency_equity,
1072            is_stale,
1073            stale_instruments,
1074            stale_currencies,
1075            unpriced_instruments,
1076            UUID4::new(),
1077            ts_now,
1078            ts_now,
1079        ))
1080    }
1081
1082    fn calculate_snapshot_equity(
1083        &self,
1084        account: &AccountAny,
1085        open_venues: &AHashSet<Venue>,
1086        unrealized: &IndexMap<Currency, Money>,
1087        snapshot_unpriced: &mut AHashSet<InstrumentId>,
1088        track_missing_prices: bool,
1089    ) -> Option<IndexMap<Currency, Money>> {
1090        let account_id = account.id();
1091        let mut equity: IndexMap<Currency, Money> = account.balances_total().into_iter().collect();
1092
1093        if matches!(account, AccountAny::Margin(_)) && !account.calculated_account_state() {
1094            for value in unrealized.values() {
1095                checked_add_money_map(&mut equity, *value, "snapshot equity")?;
1096            }
1097
1098            return Some(equity);
1099        }
1100
1101        let mut margin_equity = matches!(account, AccountAny::Margin(_)).then(|| {
1102            equity
1103                .iter()
1104                .map(|(currency, money)| (*currency, money.as_decimal()))
1105                .collect::<IndexMap<Currency, Decimal>>()
1106        });
1107
1108        for venue in open_venues {
1109            let mut values = IndexMap::new();
1110            let mut venue_unpriced = AHashSet::new();
1111
1112            match account {
1113                AccountAny::Margin(_) => {
1114                    self.accumulate_margin_equity(
1115                        *venue,
1116                        Some(&account_id),
1117                        margin_equity.as_mut().unwrap_or(&mut values),
1118                        &mut venue_unpriced,
1119                    );
1120                }
1121                AccountAny::Cash(_) | AccountAny::Betting(_) | AccountAny::Wallet(_) => {
1122                    self.accumulate_mark_values(
1123                        *venue,
1124                        Some(&account_id),
1125                        &mut values,
1126                        &mut venue_unpriced,
1127                        MarkValueMode::Equity,
1128                    );
1129                }
1130            }
1131
1132            if track_missing_prices {
1133                self.update_missing_price_state(*venue, Some(account_id), &venue_unpriced);
1134            }
1135
1136            if margin_equity.is_none() {
1137                for money in decimal_map_to_money(values)?.into_values() {
1138                    checked_add_money_map(&mut equity, money, "snapshot equity")?;
1139                }
1140            }
1141
1142            snapshot_unpriced.extend(venue_unpriced);
1143        }
1144
1145        if let Some(margin_equity) = margin_equity {
1146            equity = decimal_map_to_money(margin_equity)?;
1147        }
1148
1149        Some(equity)
1150    }
1151
1152    fn has_nonzero_realized_pnl(&self, venue: Venue, account_id: AccountId) -> bool {
1153        let cache = self.cache.borrow();
1154        cache
1155            .positions(Some(&venue), None, None, Some(&account_id), None)
1156            .iter()
1157            .any(|position| position.realized_pnl.is_some_and(|pnl| !pnl.is_zero()))
1158            || cache
1159                .position_snapshots(None, Some(&account_id))
1160                .iter()
1161                .any(|position| {
1162                    position.instrument_id.venue == venue
1163                        && position.realized_pnl.is_some_and(|pnl| !pnl.is_zero())
1164                })
1165    }
1166
1167    /// Returns the recorded portfolio snapshots for the given account, in order of emission.
1168    ///
1169    /// With `equity_curve` enabled, snapshots are recorded at account registration, every
1170    /// UTC midnight including while flat, and shutdown. Setting `snapshot_interval_ms` adds
1171    /// fine-grained samples while the account holds an open position. The ring is bounded;
1172    /// long-lived live deployments should consume snapshots via the message bus instead of
1173    /// relying on this buffer. Cleared on [`Portfolio::reset`].
1174    #[must_use]
1175    pub fn snapshots(&self, account_id: &AccountId) -> Vec<PortfolioSnapshot> {
1176        self.inner
1177            .borrow()
1178            .portfolio_snapshots
1179            .get(account_id)
1180            .map(|ring| ring.iter().cloned().collect())
1181            .unwrap_or_default()
1182    }
1183
1184    /// Returns the first error from a cash, betting, or wallet account rejecting a fill's
1185    /// balances, such as a balance that would become negative without borrowing.
1186    ///
1187    /// The fill's balances are not applied. Cleared on [`Portfolio::reset`].
1188    #[doc(hidden)]
1189    #[must_use]
1190    pub fn balance_error(&self) -> Option<String> {
1191        self.inner.borrow().balance_error.clone()
1192    }
1193
1194    /// Records one final equity-curve sample for every registered account and stops its timer.
1195    ///
1196    /// Has no effect when `equity_curve` is disabled. Calling this method more than once
1197    /// before [`Portfolio::reset`] has no effect.
1198    pub fn finalize_equity_curve(&mut self) {
1199        if !self.config.equity_curve {
1200            return;
1201        }
1202
1203        let account_ids = {
1204            let mut inner = self.inner.borrow_mut();
1205            if inner.equity_curve_finalized {
1206                return;
1207            }
1208            inner.equity_curve_finalized = true;
1209            inner
1210                .equity_curve_accounts
1211                .iter()
1212                .copied()
1213                .collect::<Vec<_>>()
1214        };
1215        let ts_event = self.clock.borrow().timestamp_ns();
1216
1217        for account_id in account_ids {
1218            emit_snapshot(
1219                &self.cache,
1220                &self.clock,
1221                &self.inner,
1222                self.config,
1223                account_id,
1224                ts_event,
1225            );
1226            self.clock
1227                .borrow_mut()
1228                .cancel_timer(&equity_curve_timer_name(account_id));
1229        }
1230    }
1231
1232    /// Returns the instruments currently flagged as unpriceable for the given venue and account.
1233    ///
1234    /// An entry is added the first time [`Portfolio::mark_values`] cannot value an open position
1235    /// because its price is missing or its notional is invalid (after also emitting a warn log),
1236    /// and removed once the instrument can be valued again so a subsequent drop re-warns.
1237    #[must_use]
1238    pub fn missing_price_instruments(
1239        &self,
1240        venue: &Venue,
1241        account_id: Option<&AccountId>,
1242    ) -> Vec<InstrumentId> {
1243        let inner = self.inner.borrow();
1244        let observations = inner.venues_missing_price.get(venue);
1245        let mut ids: Vec<InstrumentId> = match account_id {
1246            Some(account_id) => observations
1247                .and_then(|observations| observations.get(&Some(*account_id)))
1248                .map(|ids| ids.iter().copied().collect())
1249                .unwrap_or_default(),
1250            None => observations
1251                .map(|observations| {
1252                    observations
1253                        .values()
1254                        .flat_map(|ids| ids.iter().copied())
1255                        .collect::<AHashSet<_>>()
1256                        .into_iter()
1257                        .collect()
1258                })
1259                .unwrap_or_default(),
1260        };
1261        // Sort so the public Vec is deterministic even though the underlying
1262        // tracking set is AHash-backed.
1263        ids.sort();
1264        ids
1265    }
1266
1267    fn update_missing_price_state(
1268        &self,
1269        venue: Venue,
1270        account_id: Option<AccountId>,
1271        unpriced: &AHashSet<InstrumentId>,
1272    ) {
1273        let mut inner = self.inner.borrow_mut();
1274        let tracked: AHashSet<InstrumentId> = inner
1275            .venues_missing_price
1276            .get(&venue)
1277            .into_iter()
1278            .flat_map(|observations| observations.values())
1279            .flatten()
1280            .copied()
1281            .collect();
1282
1283        // Sort first so the warn-log sequence is deterministic across runs.
1284        let mut ids: Vec<InstrumentId> = unpriced.iter().copied().collect();
1285        ids.sort();
1286        for instrument_id in ids {
1287            if !tracked.contains(&instrument_id) {
1288                log::warn!(
1289                    "Cannot value open position {instrument_id}; ensure its notional inputs are \
1290                    valid and subscribe to quotes, trades, or bars for continuous mark-to-market \
1291                    equity"
1292                );
1293            }
1294        }
1295
1296        let remove_venue = {
1297            let observations = inner.venues_missing_price.entry(venue).or_default();
1298            if unpriced.is_empty() {
1299                observations.remove(&account_id);
1300            } else {
1301                observations.insert(account_id, unpriced.clone());
1302            }
1303            observations.is_empty()
1304        };
1305
1306        if remove_venue {
1307            inner.venues_missing_price.remove(&venue);
1308        }
1309    }
1310
1311    fn clear_missing_price_state(&self, venue: Venue, account_id: Option<AccountId>) {
1312        let mut inner = self.inner.borrow_mut();
1313        let Some(account_id) = account_id else {
1314            inner.venues_missing_price.remove(&venue);
1315            return;
1316        };
1317        let remove_venue = if let Some(observations) = inner.venues_missing_price.get_mut(&venue) {
1318            observations.remove(&Some(account_id));
1319            observations.is_empty()
1320        } else {
1321            false
1322        };
1323
1324        if remove_venue {
1325            inner.venues_missing_price.remove(&venue);
1326        }
1327    }
1328
1329    fn mark_values_with_mode(
1330        &self,
1331        venue: Venue,
1332        account_id: Option<&AccountId>,
1333        mode: MarkValueMode,
1334    ) -> IndexMap<Currency, Money> {
1335        let mut values: IndexMap<Currency, Decimal> = IndexMap::new();
1336        let mut unpriced: AHashSet<InstrumentId> = AHashSet::new();
1337
1338        if self.accumulate_mark_values(venue, account_id, &mut values, &mut unpriced, mode) {
1339            self.update_missing_price_state(venue, account_id.copied(), &unpriced);
1340        } else {
1341            self.clear_missing_price_state(venue, account_id.copied());
1342        }
1343
1344        decimal_map_to_money(values).unwrap_or_default()
1345    }
1346
1347    fn accumulate_margin_equity(
1348        &self,
1349        venue: Venue,
1350        account_id: Option<&AccountId>,
1351        values: &mut IndexMap<Currency, Decimal>,
1352        unpriced: &mut AHashSet<InstrumentId>,
1353    ) -> bool {
1354        let mut instrument_ids = IndexSet::new();
1355        let mut instrument_accounts_reported = IndexSet::new();
1356        let mut has_premium = false;
1357
1358        let has_positions = {
1359            let cache = self.cache.borrow();
1360            let mut positions: Vec<_> = cache
1361                .iter_position_open_ids(Some(&venue), None, None, account_id)
1362                .map(|id| {
1363                    cache
1364                        .position(&id)
1365                        .expect("Open position is not in the cache")
1366                })
1367                .collect();
1368
1369            positions.sort_unstable_by_key(|position| position.id);
1370
1371            for position in &positions {
1372                if position_uses_premium_mark(position, &cache) {
1373                    has_premium = true;
1374                } else if position.instrument_class.is_premium_based() {
1375                    instrument_accounts_reported
1376                        .insert((position.instrument_id, position.account_id));
1377                } else {
1378                    instrument_ids.insert(position.instrument_id);
1379                }
1380            }
1381
1382            !positions.is_empty()
1383        };
1384
1385        if has_premium {
1386            self.accumulate_mark_values(
1387                venue,
1388                account_id,
1389                values,
1390                unpriced,
1391                MarkValueMode::Premium,
1392            );
1393        }
1394
1395        let instruments = instrument_ids
1396            .into_iter()
1397            .map(|id| (id, account_id.copied()))
1398            .chain(
1399                instrument_accounts_reported
1400                    .into_iter()
1401                    .map(|(id, account)| (id, Some(account))),
1402            );
1403
1404        for (instrument_id, pnl_account_id) in instruments {
1405            let pnl =
1406                self.calculate_unrealized_pnl(&instrument_id, None, pnl_account_id.as_ref(), None);
1407
1408            match pnl {
1409                Some(pnl) => {
1410                    *values.entry(pnl.currency).or_insert(Decimal::ZERO) += pnl.as_decimal();
1411                }
1412                None => {
1413                    unpriced.insert(instrument_id);
1414                }
1415            }
1416        }
1417
1418        has_positions
1419    }
1420
1421    // Returns `true` if at least one open position was seen (priced or not),
1422    // `false` if the venue is flat. Unpriced instruments are written to
1423    // `unpriced` for the caller to flow into `update_missing_price_state`.
1424    fn accumulate_mark_values(
1425        &self,
1426        venue: Venue,
1427        account_id: Option<&AccountId>,
1428        values: &mut IndexMap<Currency, Decimal>,
1429        unpriced: &mut AHashSet<InstrumentId>,
1430        mode: MarkValueMode,
1431    ) -> bool {
1432        let cache = self.cache.borrow();
1433        let mut positions = cache.positions_open(Some(&venue), None, None, account_id, None);
1434
1435        if positions.is_empty() {
1436            return false;
1437        }
1438
1439        let valuation_account = account_id.map_or_else(
1440            || {
1441                cache
1442                    .account_for_venue(&venue)
1443                    .or_else(|| positions.first().and_then(|p| cache.account(&p.account_id)))
1444            },
1445            |id| cache.account(id),
1446        );
1447
1448        let equity_account_id = if mode == MarkValueMode::Equity {
1449            valuation_account.as_ref().map(|a| a.id())
1450        } else {
1451            None
1452        };
1453        let mut xrate_cache: AHashMap<Currency, Option<Decimal>> = AHashMap::new();
1454
1455        positions
1456            .retain(|p| mode != MarkValueMode::Premium || position_uses_premium_mark(p, &cache));
1457
1458        for position in positions {
1459            let sign = match position.side {
1460                PositionSide::Long => Decimal::ONE,
1461                PositionSide::Short => Decimal::NEGATIVE_ONE,
1462                PositionSide::Flat => continue,
1463            };
1464
1465            let instrument = match cache.instrument(&position.instrument_id) {
1466                Some(i) => i,
1467                None => {
1468                    unpriced.insert(position.instrument_id);
1469                    continue;
1470                }
1471            };
1472
1473            let position_account = cache.account(&position.account_id);
1474            let base_currency_is_credited = mode == MarkValueMode::Equity
1475                && equity_account_id == Some(position.account_id)
1476                && position_account.as_ref().is_some_and(|account| {
1477                    matches!(&**account, AccountAny::Cash(_) | AccountAny::Wallet(_))
1478                        && account.base_currency().is_none()
1479                        && position.base_currency.is_some_and(|base| {
1480                            position.settlement_currency != base
1481                                && account.balances().contains_key(&base)
1482                        })
1483                });
1484
1485            if base_currency_is_credited {
1486                continue;
1487            }
1488
1489            let price = match self.get_price(&position) {
1490                Some(p) => p,
1491                None => {
1492                    unpriced.insert(position.instrument_id);
1493                    continue;
1494                }
1495            };
1496
1497            let notional = match position.try_notional_value(price) {
1498                Ok(notional) => notional,
1499                Err(e) => {
1500                    log::error!(
1501                        "Cannot calculate mark value: invalid notional value for {}: {e}",
1502                        position.instrument_id
1503                    );
1504                    unpriced.insert(position.instrument_id);
1505                    continue;
1506                }
1507            };
1508            let cost_currency = notional.currency;
1509
1510            let conversion = valuation_account.as_ref().and_then(|account| {
1511                self.conversion_base_currency(account)
1512                    .map(|currency| (account, currency))
1513            });
1514
1515            let (xrate, currency) = if let Some((account, base_currency)) = conversion {
1516                let xrate_opt = *xrate_cache.entry(cost_currency).or_insert_with(|| {
1517                    self.calculate_xrate_to_base(instrument, account, cost_currency)
1518                });
1519                let xrate = match xrate_opt {
1520                    Some(x) => x,
1521                    None => {
1522                        unpriced.insert(position.instrument_id);
1523                        continue;
1524                    }
1525                };
1526                (xrate, base_currency)
1527            } else {
1528                (Decimal::ONE, cost_currency)
1529            };
1530
1531            // Sum exact Decimals; the caller rounds once so sub-precision positions survive
1532            let value = notional.as_decimal() * xrate * sign;
1533            *values.entry(currency).or_insert(Decimal::ZERO) += value;
1534        }
1535
1536        true
1537    }
1538
1539    #[must_use]
1540    pub fn net_exposure(
1541        &self,
1542        instrument_id: &InstrumentId,
1543        price: Option<Price>,
1544        account_id: Option<&AccountId>,
1545        target_currency: Option<Currency>,
1546    ) -> Option<Money> {
1547        let cache = self.cache.borrow();
1548
1549        let instrument = if let Some(instrument) = cache.instrument(instrument_id) {
1550            instrument
1551        } else {
1552            log::error!("Cannot calculate net exposure: no instrument for {instrument_id}");
1553            return None;
1554        };
1555
1556        if let Some(account_id) = account_id
1557            && cache.account(account_id).is_none()
1558        {
1559            log::error!("Cannot calculate net exposure: no account for {account_id}");
1560            return None;
1561        }
1562
1563        let positions_open =
1564            cache.positions_open(None, Some(instrument_id), None, account_id, None);
1565
1566        if positions_open.is_empty() {
1567            return Some(Money::zero(
1568                target_currency.unwrap_or_else(|| instrument.cost_currency()),
1569            ));
1570        }
1571
1572        let mut net_exposure = Decimal::ZERO;
1573        let mut output_currency = target_currency;
1574        let mut native_currency: Option<Currency> = None;
1575
1576        for position in &positions_open {
1577            let sign = match position.side {
1578                PositionSide::Long => Decimal::ONE,
1579                PositionSide::Short => Decimal::NEGATIVE_ONE,
1580                PositionSide::Flat => {
1581                    log::error!(
1582                        "Cannot calculate net exposure: position is flat for {}",
1583                        position.instrument_id
1584                    );
1585                    continue; // Nothing to calculate
1586                }
1587            };
1588
1589            // Get account for THIS position
1590            let account = if let Some(account) = cache.account(&position.account_id) {
1591                account
1592            } else if account_id.is_none()
1593                && let Some(account) = cache.account_for_venue(&instrument.id().venue)
1594            {
1595                account
1596            } else {
1597                log::error!(
1598                    "Cannot calculate net exposure: no account for {}",
1599                    position.account_id
1600                );
1601                return None;
1602            };
1603
1604            let base_currency = self.conversion_base_currency(&account);
1605
1606            // Validate consistent base currency across accounts when the caller did not select a
1607            // target. An explicit target provides the common aggregation currency instead.
1608            if target_currency.is_none()
1609                && let Some(base) = base_currency
1610            {
1611                match output_currency {
1612                    None => {
1613                        output_currency = Some(base);
1614                    }
1615                    Some(first) if first != base => {
1616                        log::error!(
1617                            "Cannot calculate net exposure: accounts have different base \
1618                            currencies ({first} vs {base}); multi-account aggregation requires \
1619                            consistent base currencies"
1620                        );
1621                        return None;
1622                    }
1623                    _ => {}
1624                }
1625            }
1626
1627            let price = price.or_else(|| self.get_price(position))?;
1628            let notional_value = match position.try_notional_value(price) {
1629                Ok(notional) => notional,
1630                Err(e) => {
1631                    log::error!(
1632                        "Cannot calculate net exposure: invalid notional value for {}: {e}",
1633                        position.instrument_id
1634                    );
1635                    return None;
1636                }
1637            };
1638            let source_currency = notional_value.currency;
1639
1640            if target_currency.is_some() {
1641                match native_currency {
1642                    None => native_currency = Some(source_currency),
1643                    Some(first) if first != source_currency => {
1644                        log::error!(
1645                            "Cannot calculate net exposure: positions have different cost \
1646                            currencies ({first} vs {source_currency})"
1647                        );
1648                        return None;
1649                    }
1650                    _ => {}
1651                }
1652
1653                let Some(signed) = notional_value.as_decimal().checked_mul(sign) else {
1654                    log::error!("Cannot calculate net exposure: signed notional overflow");
1655                    return None;
1656                };
1657                let Some(updated) = net_exposure.checked_add(signed) else {
1658                    log::error!("Cannot calculate net exposure: total overflow");
1659                    return None;
1660                };
1661                net_exposure = updated;
1662                continue;
1663            }
1664
1665            if base_currency.is_none() {
1666                match output_currency {
1667                    None => output_currency = Some(source_currency),
1668                    Some(first) if first != source_currency => {
1669                        log::error!(
1670                            "Cannot calculate net exposure: positions have different cost \
1671                            currencies ({first} vs {source_currency})"
1672                        );
1673                        return None;
1674                    }
1675                    _ => {}
1676                }
1677            }
1678
1679            let xrate = self.calculate_xrate_to_base(instrument, &account, source_currency);
1680            let xrate = if let Some(xrate) = xrate {
1681                xrate
1682            } else {
1683                log::error!(
1684                    "Cannot calculate net exposures: insufficient data for {}/{:?}",
1685                    source_currency,
1686                    account.base_currency()
1687                );
1688                return None;
1689            };
1690
1691            let Some(converted) = notional_value.as_decimal().checked_mul(xrate) else {
1692                log::error!("Cannot calculate net exposure: currency conversion overflow");
1693                return None;
1694            };
1695            let Some(signed) = converted.checked_mul(sign) else {
1696                log::error!("Cannot calculate net exposure: signed notional overflow");
1697                return None;
1698            };
1699            let Some(updated) = net_exposure.checked_add(signed) else {
1700                log::error!("Cannot calculate net exposure: total overflow");
1701                return None;
1702            };
1703            net_exposure = updated;
1704        }
1705
1706        // Net exposure is reported as a magnitude once opposing sides are netted
1707        let mut net_exposure = if net_exposure.is_sign_negative() {
1708            let Some(value) = net_exposure.checked_mul(Decimal::NEGATIVE_ONE) else {
1709                log::error!("Cannot calculate net exposure: absolute value overflow");
1710                return None;
1711            };
1712            value
1713        } else {
1714            net_exposure
1715        };
1716
1717        if let Some(target_currency) = target_currency {
1718            if net_exposure == Decimal::ZERO {
1719                return Some(Money::zero(target_currency));
1720            }
1721
1722            let source_currency = native_currency.unwrap_or_else(|| instrument.cost_currency());
1723            let Some(xrate) = self.calculate_xrate(
1724                instrument.id().venue,
1725                source_currency,
1726                target_currency,
1727                false,
1728            ) else {
1729                log::error!(
1730                    "Cannot calculate net exposure: insufficient data for {source_currency}/{target_currency}"
1731                );
1732                return None;
1733            };
1734            let Some(converted) = net_exposure.checked_mul(xrate) else {
1735                log::error!("Cannot calculate net exposure: currency conversion overflow");
1736                return None;
1737            };
1738            net_exposure = converted.round_dp(u32::from(target_currency.precision));
1739        }
1740
1741        let output_currency = output_currency.unwrap_or_else(|| instrument.cost_currency());
1742        match Money::from_decimal(net_exposure, output_currency) {
1743            Ok(money) => Some(money),
1744            Err(e) => {
1745                log::error!("Cannot calculate net exposure: {e}");
1746                None
1747            }
1748        }
1749    }
1750
1751    #[must_use]
1752    pub fn net_position(&self, instrument_id: &InstrumentId) -> Decimal {
1753        self.inner
1754            .borrow()
1755            .net_positions
1756            .get(instrument_id)
1757            .copied()
1758            .unwrap_or(Decimal::ZERO)
1759    }
1760
1761    #[must_use]
1762    pub fn is_net_long(&self, instrument_id: &InstrumentId) -> bool {
1763        self.inner
1764            .borrow()
1765            .net_positions
1766            .get(instrument_id)
1767            .copied()
1768            .map_or_else(|| false, |net_position| net_position > Decimal::ZERO)
1769    }
1770
1771    #[must_use]
1772    pub fn is_net_short(&self, instrument_id: &InstrumentId) -> bool {
1773        self.inner
1774            .borrow()
1775            .net_positions
1776            .get(instrument_id)
1777            .copied()
1778            .map_or_else(|| false, |net_position| net_position < Decimal::ZERO)
1779    }
1780
1781    #[must_use]
1782    pub fn is_net_flat(&self, instrument_id: &InstrumentId) -> bool {
1783        self.inner
1784            .borrow()
1785            .net_positions
1786            .get(instrument_id)
1787            .copied()
1788            .map_or_else(|| true, |net_position| net_position == Decimal::ZERO)
1789    }
1790
1791    #[must_use]
1792    pub fn is_completely_net_flat(&self) -> bool {
1793        for net_position in self.inner.borrow().net_positions.values() {
1794            if *net_position != Decimal::ZERO {
1795                return false;
1796            }
1797        }
1798        true
1799    }
1800
1801    /// Initializes account margin based on existing open orders.
1802    ///
1803    /// Cash and margin accounts with `calculate_account_state` disabled retain reported balances
1804    /// and reservations.
1805    ///
1806    /// # Panics
1807    ///
1808    /// Panics if updating the cache with a mutated account fails.
1809    pub fn initialize_orders(&mut self) {
1810        let mut initialized = true;
1811        let orders_and_instruments = {
1812            let cache = self.cache.borrow();
1813
1814            let mut instruments_with_orders = Vec::new();
1815
1816            // Ordered so margin recalculation materializes any unreported balance currency
1817            // in a stable sequence; the account balance map preserves insertion order.
1818            let instruments: BTreeSet<_> = cache
1819                .iter_client_order_ids_open(None, None, None, None)
1820                .filter_map(|client_order_id| cache.order(&client_order_id))
1821                .map(|order| order.instrument_id())
1822                .collect();
1823
1824            for instrument_id in instruments {
1825                let Some(instrument) = cache.instrument(&instrument_id) else {
1826                    log::error!(
1827                        "Cannot update initial (order) margin: no instrument found for {instrument_id}"
1828                    );
1829                    self.inner.borrow_mut().pending_calcs.insert(instrument_id);
1830                    initialized = false;
1831                    continue;
1832                };
1833
1834                let orders = cache
1835                    .orders_open(None, Some(&instrument_id), None, None, None)
1836                    .into_iter()
1837                    .map(|order| order.clone())
1838                    .collect::<Vec<OrderAny>>();
1839                instruments_with_orders.push((instrument.clone(), orders));
1840            }
1841            instruments_with_orders
1842        };
1843
1844        for (instrument, orders_open) in &orders_and_instruments {
1845            let mut by_account: IndexMap<Option<AccountId>, Vec<&OrderAny>> = IndexMap::new();
1846            for order in orders_open {
1847                by_account
1848                    .entry(order.account_id())
1849                    .or_default()
1850                    .push(order);
1851            }
1852
1853            for (account_id, orders) in by_account {
1854                let account = {
1855                    let cache = self.cache.borrow();
1856
1857                    match resolve_account_for_instrument(
1858                        &cache,
1859                        &instrument.id(),
1860                        account_id.as_ref(),
1861                    ) {
1862                        Some(account)
1863                            if matches!(&*account, AccountAny::Cash(_) | AccountAny::Margin(_))
1864                                && !account.calculated_account_state() =>
1865                        {
1866                            continue;
1867                        }
1868                        Some(account) => account.cloned(),
1869                        None => {
1870                            log::error!(
1871                                "Cannot update initial (order) margin: no account registered for {}",
1872                                instrument.id().venue
1873                            );
1874                            self.inner
1875                                .borrow_mut()
1876                                .pending_calcs
1877                                .insert(instrument.id());
1878                            initialized = false;
1879                            continue;
1880                        }
1881                    }
1882                };
1883
1884                let result = self.inner.borrow_mut().accounts.update_orders(
1885                    &account,
1886                    instrument,
1887                    &orders,
1888                    self.clock.borrow().timestamp_ns(),
1889                );
1890
1891                match result {
1892                    Some((updated_account, _)) => {
1893                        self.cache
1894                            .borrow_mut()
1895                            .update_account(&updated_account)
1896                            .unwrap();
1897                    }
1898                    None => {
1899                        self.inner
1900                            .borrow_mut()
1901                            .pending_calcs
1902                            .insert(instrument.id());
1903                        initialized = false;
1904                    }
1905                }
1906            }
1907        }
1908
1909        let total_orders = orders_and_instruments
1910            .into_iter()
1911            .map(|(_, orders)| orders.len())
1912            .sum::<usize>();
1913
1914        log::info!(
1915            color = if total_orders > 0 { LogColor::Blue as u8 } else { LogColor::Normal as u8 };
1916            "Initialized {} open order{}",
1917            total_orders,
1918            if total_orders == 1 { "" } else { "s" }
1919        );
1920
1921        self.inner.borrow_mut().initialized = initialized;
1922    }
1923
1924    /// Rebuilds Wallet account reservations from locally active orders.
1925    ///
1926    /// This runs independently of venue reconciliation because Wallet reservations are transient
1927    /// and must be reconstructed after every cache restore.
1928    ///
1929    /// # Errors
1930    ///
1931    /// Returns an error if an active Wallet order cannot be resolved to an instrument or its debit
1932    /// reservation cannot be reconstructed exactly.
1933    pub fn initialize_wallet_orders(&mut self) -> anyhow::Result<()> {
1934        let grouped_orders = {
1935            let cache = self.cache.borrow();
1936            let mut client_order_ids = BTreeSet::new();
1937            client_order_ids.extend(cache.iter_client_order_ids_open(None, None, None, None));
1938            client_order_ids.extend(cache.iter_client_order_ids_inflight(None, None, None, None));
1939
1940            let mut grouped: IndexMap<(AccountId, InstrumentId), Vec<OrderAny>> = IndexMap::new();
1941
1942            for client_order_id in client_order_ids {
1943                let Some(order) = cache.order(&client_order_id) else {
1944                    continue;
1945                };
1946
1947                if !wallet_order_reserves_balance(&order) {
1948                    continue;
1949                }
1950
1951                let Some(account) = resolve_account_for_instrument(
1952                    &cache,
1953                    &order.instrument_id(),
1954                    order.account_id().as_ref(),
1955                ) else {
1956                    continue;
1957                };
1958
1959                if !matches!(&*account, AccountAny::Wallet(_)) {
1960                    continue;
1961                }
1962
1963                if cache.instrument(&order.instrument_id()).is_none() {
1964                    anyhow::bail!(
1965                        "cannot rebuild Wallet reservations: no instrument found for {}",
1966                        order.instrument_id()
1967                    );
1968                }
1969
1970                grouped
1971                    .entry((account.id(), order.instrument_id()))
1972                    .or_default()
1973                    .push((*order).clone());
1974            }
1975            grouped
1976        };
1977
1978        let total_orders = grouped_orders.values().map(Vec::len).sum::<usize>();
1979        for ((account_id, instrument_id), orders) in grouped_orders {
1980            let (account, instrument) = {
1981                let cache = self.cache.borrow();
1982                let account = cache.account_owned(&account_id).ok_or_else(|| {
1983                    anyhow::anyhow!(
1984                        "cannot rebuild Wallet reservations: account {account_id} not found"
1985                    )
1986                })?;
1987                let instrument = cache.instrument(&instrument_id).cloned().ok_or_else(|| {
1988                    anyhow::anyhow!(
1989                        "cannot rebuild Wallet reservations: instrument {instrument_id} not found"
1990                    )
1991                })?;
1992                (account, instrument)
1993            };
1994            let order_refs = orders.iter().collect::<Vec<_>>();
1995            let Some((updated_account, _)) = self.inner.borrow().accounts.update_orders(
1996                &account,
1997                &instrument,
1998                &order_refs,
1999                self.clock.borrow().timestamp_ns(),
2000            ) else {
2001                anyhow::bail!(
2002                    "cannot rebuild Wallet reservations for account {account_id} and instrument {instrument_id}"
2003                );
2004            };
2005            self.cache.borrow_mut().update_account(&updated_account)?;
2006        }
2007
2008        log::info!(
2009            color = if total_orders > 0 { LogColor::Blue as u8 } else { LogColor::Normal as u8 };
2010            "Initialized {} Wallet reservation{}",
2011            total_orders,
2012            if total_orders == 1 { "" } else { "s" }
2013        );
2014        Ok(())
2015    }
2016
2017    /// Initializes net positions, PnL, and calculated position margin.
2018    ///
2019    /// Margin accounts with `calculate_account_state` disabled retain reported balances and margins.
2020    ///
2021    /// # Panics
2022    ///
2023    /// Panics if calculation of PnL or updating the cache with a mutated account fails.
2024    pub fn initialize_positions(&mut self) {
2025        self.inner.borrow_mut().unrealized_pnls.clear();
2026        self.inner.borrow_mut().realized_pnls.clear();
2027        let all_positions_open: Vec<Position>;
2028
2029        // Ordered for the same reason as `initialize_orders`
2030        let mut instruments = BTreeSet::new();
2031        {
2032            let cache = self.cache.borrow();
2033            all_positions_open = cache
2034                .positions_open(None, None, None, None, None)
2035                .into_iter()
2036                .map(|p| p.cloned())
2037                .collect();
2038
2039            for position in &all_positions_open {
2040                instruments.insert(position.instrument_id);
2041            }
2042        }
2043
2044        let mut initialized = self.orders_initialized();
2045
2046        for instrument_id in instruments {
2047            let positions_open: Vec<Position> = {
2048                let cache = self.cache.borrow();
2049                cache
2050                    .positions_open(None, Some(&instrument_id), None, None, None)
2051                    .into_iter()
2052                    .map(|p| p.cloned())
2053                    .collect()
2054            };
2055
2056            let position_refs: Vec<&Position> = positions_open.iter().collect();
2057            self.update_net_position(&instrument_id, &position_refs);
2058
2059            if let Some(calculated_unrealized_pnl) =
2060                self.calculate_unrealized_pnl(&instrument_id, None, None, None)
2061            {
2062                self.inner
2063                    .borrow_mut()
2064                    .unrealized_pnls
2065                    .insert(instrument_id, calculated_unrealized_pnl);
2066            } else {
2067                log::debug!(
2068                    "Failed to calculate unrealized PnL for {instrument_id}, marking as pending"
2069                );
2070                self.inner.borrow_mut().pending_calcs.insert(instrument_id);
2071                initialized = false;
2072            }
2073
2074            if let Some(calculated_realized_pnl) =
2075                self.calculate_realized_pnl(&instrument_id, None, None)
2076            {
2077                self.inner
2078                    .borrow_mut()
2079                    .realized_pnls
2080                    .insert(instrument_id, calculated_realized_pnl);
2081            } else {
2082                log::warn!(
2083                    "Failed to calculate realized PnL for {instrument_id}, marking as pending"
2084                );
2085                self.inner.borrow_mut().pending_calcs.insert(instrument_id);
2086                initialized = false;
2087            }
2088
2089            let instrument = {
2090                let cache = self.cache.borrow();
2091                let Some(instrument) = cache.instrument(&instrument_id).cloned() else {
2092                    log::error!(
2093                        "Cannot update maintenance (position) margin: no instrument found for {instrument_id}"
2094                    );
2095                    initialized = false;
2096                    break;
2097                };
2098                instrument
2099            };
2100
2101            initialized &= self.initialize_position_margins(&instrument, &positions_open);
2102        }
2103
2104        let open_count = all_positions_open.len();
2105        self.inner.borrow_mut().initialized = initialized;
2106        log::info!(
2107            color = if open_count > 0 { LogColor::Blue as u8 } else { LogColor::Normal as u8 };
2108            "Initialized {} open position{}",
2109            open_count,
2110            if open_count == 1 { "" } else { "s" }
2111        );
2112
2113        if self.config.snapshot_interval_ms.is_some() {
2114            let account_ids: AHashSet<AccountId> =
2115                all_positions_open.iter().map(|p| p.account_id).collect();
2116
2117            for account_id in account_ids {
2118                update_snapshot_timer_state(
2119                    &self.cache,
2120                    &self.clock,
2121                    &self.inner,
2122                    self.config,
2123                    account_id,
2124                );
2125            }
2126        }
2127    }
2128
2129    fn initialize_position_margins(
2130        &self,
2131        instrument: &InstrumentAny,
2132        positions_open: &[Position],
2133    ) -> bool {
2134        let mut initialized = true;
2135        let mut by_account: IndexMap<AccountId, Vec<&Position>> = IndexMap::new();
2136        for position in positions_open {
2137            by_account
2138                .entry(position.account_id)
2139                .or_default()
2140                .push(position);
2141        }
2142
2143        for (account_id, positions) in by_account {
2144            let account = {
2145                let cache = self.cache.borrow();
2146
2147                let Some(account) = cache.account(&account_id).map(|a| a.cloned()) else {
2148                    log::error!(
2149                        "Cannot update maintenance (position) margin: no account registered for {account_id}"
2150                    );
2151                    initialized = false;
2152                    continue;
2153                };
2154
2155                account
2156            };
2157
2158            let AccountAny::Margin(margin_account) = account else {
2159                continue;
2160            };
2161
2162            if !margin_account.calculate_account_state {
2163                continue;
2164            }
2165
2166            let result = self.inner.borrow_mut().accounts.update_positions(
2167                &margin_account,
2168                instrument,
2169                positions,
2170                self.clock.borrow().timestamp_ns(),
2171            );
2172
2173            match result {
2174                Some((updated_account, _)) => {
2175                    self.cache
2176                        .borrow_mut()
2177                        .update_account(&AccountAny::Margin(updated_account))
2178                        .unwrap();
2179                }
2180                None => initialized = false,
2181            }
2182        }
2183
2184        initialized
2185    }
2186
2187    fn orders_initialized(&self) -> bool {
2188        let inner = self.inner.borrow();
2189        if inner.initialized {
2190            return true;
2191        }
2192
2193        let cache = self.cache.borrow();
2194        cache
2195            .iter_client_order_ids_open(None, None, None, None)
2196            .filter_map(|client_order_id| cache.order(&client_order_id))
2197            .all(|order| !inner.pending_calcs.contains(&order.instrument_id()))
2198    }
2199
2200    /// Updates portfolio calculations based on a new quote tick.
2201    ///
2202    /// Recalculates unrealized PnL for positions affected by the quote update.
2203    pub fn update_quote_tick(&mut self, quote: &QuoteTick) {
2204        update_quote_tick(&self.cache, &self.clock, &self.inner, self.config, quote);
2205    }
2206
2207    /// Updates portfolio calculations based on a new bar.
2208    ///
2209    /// Updates cached bar close prices and recalculates unrealized PnL.
2210    pub fn update_bar(&mut self, bar: &Bar) {
2211        update_bar(&self.cache, &self.clock, &self.inner, self.config, bar);
2212    }
2213
2214    /// Updates portfolio with a new account state event.
2215    pub fn update_account(&mut self, event: &AccountState) {
2216        update_account(&self.clock, &self.cache, &self.inner, self.config, event);
2217    }
2218
2219    /// Updates portfolio calculations based on an order event.
2220    ///
2221    /// Handles balance updates for order fills and margin calculations for order changes.
2222    pub fn update_order(&mut self, event: &OrderEventAny) {
2223        update_order(
2224            &self.cache,
2225            &self.clock,
2226            &self.inner,
2227            self.config,
2228            event,
2229            OrderUpdateSource::Topic,
2230        );
2231    }
2232
2233    /// Returns realized PnLs recorded during portfolio event processing.
2234    ///
2235    /// Each record is `(position_id, ts_event, realized_pnl)`.
2236    #[must_use]
2237    pub fn recorded_realized_pnls(&self) -> AHashMap<Currency, Vec<(PositionId, UnixNanos, f64)>> {
2238        self.inner.borrow().analyzer.recorded_realized_pnls.clone()
2239    }
2240
2241    /// Computes an owned [`PortfolioStatistics`] snapshot from the portfolio's current cache state.
2242    ///
2243    /// Aggregates balances across every account, includes cached positions and their snapshots, and
2244    /// merges close-time PnLs recorded during processing. Recomputes on each call; callers on hot paths
2245    /// should invoke it sparingly.
2246    #[must_use]
2247    pub fn statistics(&self) -> PortfolioStatistics {
2248        self.analyzer().statistics()
2249    }
2250
2251    /// Builds a [`PortfolioAnalyzer`] populated from the portfolio's current cache state.
2252    ///
2253    /// Aggregates balances across every account, includes cached positions and their snapshots,
2254    /// merges close-time PnLs recorded during processing, and carries the registered statistics
2255    /// so custom registrations participate. Every analysis path builds its analyzer here, so a
2256    /// new caller cannot omit the registrations. Recomputes on each call; callers on hot paths
2257    /// should invoke it sparingly.
2258    #[must_use]
2259    pub fn analyzer(&self) -> PortfolioAnalyzer {
2260        let cache = self.cache.borrow();
2261        let accounts = cache.accounts_all_owned();
2262        let positions: Vec<Position> = cache
2263            .positions(None, None, None, None, None)
2264            .into_iter()
2265            .map(|p| p.cloned())
2266            .collect();
2267        let mut snapshots = Vec::new();
2268        for position in &positions {
2269            snapshots.extend(cache.position_snapshots(Some(&position.id), None));
2270        }
2271
2272        let inner = self.inner.borrow();
2273        let recorded = inner.analyzer.recorded_realized_pnls.clone();
2274        let portfolio_snapshots = inner
2275            .portfolio_snapshots
2276            .values()
2277            .flat_map(|ring| ring.iter())
2278            .collect::<Vec<_>>();
2279        let mut analyzer = PortfolioAnalyzer::from_accounts_with_snapshots(
2280            &accounts,
2281            &positions,
2282            &snapshots,
2283            portfolio_snapshots,
2284            recorded,
2285        );
2286        analyzer.replace_statistics(inner.analyzer.statistics.clone());
2287
2288        analyzer
2289    }
2290
2291    /// Returns the statistics registered for portfolio and backtest analysis.
2292    ///
2293    /// The set contains the built-in defaults plus any statistic registered through
2294    /// [`Self::register_statistic`], minus any deregistered.
2295    #[must_use]
2296    pub fn registered_statistics(&self) -> AHashMap<String, Statistic> {
2297        self.inner.borrow().analyzer.statistics.clone()
2298    }
2299
2300    /// Registers `statistic` for inclusion in portfolio and backtest analysis.
2301    ///
2302    /// The registration persists across [`Self::statistics`] calls and analyzer state resets.
2303    /// Registering a statistic whose name matches an existing one replaces it.
2304    pub fn register_statistic(&mut self, statistic: Statistic) {
2305        self.inner
2306            .borrow_mut()
2307            .analyzer
2308            .register_statistic(statistic);
2309    }
2310
2311    /// Removes the statistic matching `statistic` by name from analysis.
2312    pub fn deregister_statistic(&mut self, statistic: &Statistic) {
2313        self.inner
2314            .borrow_mut()
2315            .analyzer
2316            .deregister_statistic(statistic);
2317    }
2318
2319    /// Removes all registered statistics, including the built-in defaults.
2320    pub fn deregister_statistics(&mut self) {
2321        self.inner.borrow_mut().analyzer.deregister_statistics();
2322    }
2323
2324    /// Updates portfolio calculations based on a position event.
2325    ///
2326    /// Recalculates net positions, unrealized PnL, and margin requirements.
2327    pub fn update_position(&mut self, event: &PositionEvent) {
2328        update_position(&self.cache, &self.clock, &self.inner, self.config, event);
2329    }
2330
2331    fn update_net_position(&self, instrument_id: &InstrumentId, positions: &[&Position]) {
2332        let mut net_position = Decimal::ZERO;
2333
2334        for open_position in positions {
2335            log::debug!("open_position: {}", *open_position);
2336            net_position += open_position.signed_decimal_qty();
2337        }
2338
2339        let existing_position = self.net_position(instrument_id);
2340        if existing_position != net_position {
2341            self.inner
2342                .borrow_mut()
2343                .net_positions
2344                .insert(*instrument_id, net_position);
2345            log::info!("{instrument_id} net_position={net_position}");
2346        }
2347    }
2348
2349    fn aggregate_unrealized_pnl_by_account(
2350        &self,
2351        instrument_id: &InstrumentId,
2352        price: Option<Price>,
2353        account_id: Option<&AccountId>,
2354        target_currency: Option<Currency>,
2355    ) -> Result<Money, UnrealizedPnlError> {
2356        let pnls =
2357            self.unrealized_pnls_by_account(instrument_id, price, account_id, target_currency)?;
2358        let mut total: Option<Money> = None;
2359        for pnl in pnls {
2360            total = Some(match total {
2361                Some(total) => checked_add_money(total, pnl, "PnL aggregation")
2362                    .ok_or(UnrealizedPnlError::Invalid)?,
2363                None => pnl,
2364            });
2365        }
2366
2367        total.ok_or(UnrealizedPnlError::Invalid)
2368    }
2369
2370    fn unrealized_pnls_by_account(
2371        &self,
2372        instrument_id: &InstrumentId,
2373        price: Option<Price>,
2374        account_id: Option<&AccountId>,
2375        target_currency: Option<Currency>,
2376    ) -> Result<Vec<Money>, UnrealizedPnlError> {
2377        let mut account_ids = if let Some(account_id) = account_id {
2378            vec![*account_id]
2379        } else {
2380            let cache = self.cache.borrow();
2381            cache
2382                .positions_open(None, Some(instrument_id), None, None, None)
2383                .iter()
2384                .map(|position| position.account_id)
2385                .collect::<Vec<_>>()
2386        };
2387
2388        account_ids.sort();
2389        account_ids.dedup();
2390        if account_ids.is_empty() {
2391            let cache = self.cache.borrow();
2392            let account_id = if let Some(account_id) = account_id {
2393                cache.account(account_id).map(|account| account.id())
2394            } else {
2395                cache
2396                    .account_for_venue(&instrument_id.venue)
2397                    .map(|account| account.id())
2398            }
2399            .ok_or(UnrealizedPnlError::Invalid)?;
2400            account_ids.push(account_id);
2401        }
2402
2403        let mut pnls = Vec::with_capacity(account_ids.len());
2404        for account_id in account_ids {
2405            let pnl = self.calculate_unrealized_pnl_result(
2406                instrument_id,
2407                price,
2408                Some(&account_id),
2409                target_currency,
2410            )?;
2411            pnls.push(pnl);
2412        }
2413
2414        Ok(pnls)
2415    }
2416
2417    fn aggregate_realized_pnl_by_account(
2418        &self,
2419        instrument_id: &InstrumentId,
2420        account_id: Option<&AccountId>,
2421        target_currency: Option<Currency>,
2422    ) -> Option<Money> {
2423        let pnls = self.realized_pnls_by_account(instrument_id, account_id, target_currency)?;
2424        let mut total: Option<Money> = None;
2425        for pnl in pnls {
2426            total = Some(match total {
2427                Some(total) => checked_add_money(total, pnl, "PnL aggregation")?,
2428                None => pnl,
2429            });
2430        }
2431
2432        total
2433    }
2434
2435    fn realized_pnls_by_account(
2436        &self,
2437        instrument_id: &InstrumentId,
2438        account_id: Option<&AccountId>,
2439        target_currency: Option<Currency>,
2440    ) -> Option<Vec<Money>> {
2441        let mut account_ids = if let Some(account_id) = account_id {
2442            vec![*account_id]
2443        } else {
2444            let cache = self.cache.borrow();
2445            cache
2446                .positions(None, Some(instrument_id), None, None, None)
2447                .iter()
2448                .map(|position| position.account_id)
2449                .collect::<Vec<_>>()
2450        };
2451
2452        if account_id.is_none() {
2453            let inner = self.inner.borrow();
2454            account_ids.extend(
2455                self.cache
2456                    .borrow()
2457                    .position_snapshot_ids(instrument_id)
2458                    .iter()
2459                    .filter_map(|position_id| inner.snapshot_account_ids.get(position_id))
2460                    .copied(),
2461            );
2462        }
2463
2464        account_ids.sort();
2465        account_ids.dedup();
2466        if account_ids.is_empty() {
2467            let cache = self.cache.borrow();
2468            let account_id = if let Some(account_id) = account_id {
2469                cache.account(account_id).map(|account| account.id())
2470            } else {
2471                cache
2472                    .account_for_venue(&instrument_id.venue)
2473                    .map(|account| account.id())
2474            }?;
2475            account_ids.push(account_id);
2476        }
2477
2478        let mut pnls = Vec::with_capacity(account_ids.len());
2479        for account_id in account_ids {
2480            let pnl =
2481                self.calculate_realized_pnl(instrument_id, Some(&account_id), target_currency)?;
2482            pnls.push(pnl);
2483        }
2484
2485        Some(pnls)
2486    }
2487
2488    fn calculate_unrealized_pnl(
2489        &self,
2490        instrument_id: &InstrumentId,
2491        price: Option<Price>,
2492        account_id: Option<&AccountId>,
2493        target_currency: Option<Currency>,
2494    ) -> Option<Money> {
2495        self.calculate_unrealized_pnl_result(instrument_id, price, account_id, target_currency)
2496            .ok()
2497    }
2498
2499    fn calculate_unrealized_pnl_result(
2500        &self,
2501        instrument_id: &InstrumentId,
2502        price: Option<Price>,
2503        account_id: Option<&AccountId>,
2504        target_currency: Option<Currency>,
2505    ) -> Result<Money, UnrealizedPnlError> {
2506        let cache = self.cache.borrow();
2507        let account = resolve_account_for_instrument(&cache, instrument_id, account_id);
2508        let account = if let Some(account) = account {
2509            account
2510        } else {
2511            log::error!(
2512                "Cannot calculate unrealized PnL: no account for {} / {account_id:?}",
2513                instrument_id.venue,
2514            );
2515            return Err(UnrealizedPnlError::Invalid);
2516        };
2517
2518        let conversion_currency =
2519            target_currency.or_else(|| self.conversion_base_currency(&account));
2520        let allow_stale_xrate = target_currency.is_none();
2521        let mut output_currency = conversion_currency;
2522
2523        let positions_open =
2524            cache.positions_open(None, Some(instrument_id), None, account_id, None);
2525
2526        if positions_open.is_empty()
2527            && let Some(currency) = cache
2528                .instrument(instrument_id)
2529                .map(Instrument::cost_currency)
2530                .or_else(|| {
2531                    cache
2532                        .positions(None, Some(instrument_id), None, account_id, None)
2533                        .first()
2534                        .map(|position| position.settlement_currency)
2535                })
2536        {
2537            return Ok(Money::zero(output_currency.unwrap_or(currency)));
2538        }
2539
2540        let Some(instrument) = cache.instrument(instrument_id) else {
2541            log::error!("Cannot calculate unrealized PnL: no instrument for {instrument_id}");
2542            return Err(UnrealizedPnlError::Invalid);
2543        };
2544
2545        let mut total_pnl = Decimal::ZERO;
2546        // Market data stays immutably borrowed, so each side needs only one price lookup
2547        let prices = [OnceCell::new(), OnceCell::new()];
2548
2549        for position in positions_open {
2550            if position.instrument_id != *instrument_id {
2551                continue; // Nothing to calculate
2552            }
2553
2554            if position.side == PositionSide::Flat {
2555                continue; // Nothing to calculate
2556            }
2557
2558            let price = if let Some(price) = price.or_else(|| {
2559                *prices[usize::from(position.side == PositionSide::Short)]
2560                    .get_or_init(|| self.get_price(&position))
2561            }) {
2562                price
2563            } else {
2564                log::debug!("Cannot calculate unrealized PnL: no prices for {instrument_id}");
2565                self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
2566                return Err(UnrealizedPnlError::MissingInput);
2567            };
2568
2569            let position_pnl = match position.try_unrealized_pnl(price) {
2570                Ok(pnl) => pnl,
2571                Err(e) => {
2572                    log::error!(
2573                        "Cannot calculate unrealized PnL for {}: {e}",
2574                        position.instrument_id
2575                    );
2576                    self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
2577                    return Err(UnrealizedPnlError::Invalid);
2578                }
2579            };
2580            let source_currency = position_pnl.currency;
2581            let currency = conversion_currency.unwrap_or(source_currency);
2582            match output_currency {
2583                None => output_currency = Some(currency),
2584                Some(first) if first != currency => {
2585                    log::error!(
2586                        "Cannot calculate unrealized PnL: positions have different output \
2587                        currencies ({first} vs {currency})"
2588                    );
2589                    return Err(UnrealizedPnlError::Invalid);
2590                }
2591                _ => {}
2592            }
2593
2594            let mut pnl = position_pnl.as_decimal();
2595
2596            if let Some(conversion_currency) = conversion_currency {
2597                let xrate = if let Some(xrate) = self.calculate_xrate(
2598                    instrument.id().venue,
2599                    source_currency,
2600                    conversion_currency,
2601                    allow_stale_xrate,
2602                ) {
2603                    xrate
2604                } else {
2605                    log::warn!(
2606                        // TODO: Improve logging
2607                        "Cannot calculate unrealized PnL: insufficient data for \
2608                        {source_currency}/{conversion_currency}"
2609                    );
2610                    self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
2611                    return Err(UnrealizedPnlError::MissingInput);
2612                };
2613
2614                let Some(converted) = pnl.checked_mul(xrate) else {
2615                    log::error!("Cannot calculate unrealized PnL: currency conversion overflow");
2616                    self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
2617                    return Err(UnrealizedPnlError::Invalid);
2618                };
2619                pnl = converted.round_dp(u32::from(currency.precision));
2620            }
2621
2622            let Some(updated_total) = total_pnl.checked_add(pnl) else {
2623                log::error!("Cannot calculate unrealized PnL: total overflow");
2624                self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
2625                return Err(UnrealizedPnlError::Invalid);
2626            };
2627            total_pnl = updated_total;
2628        }
2629
2630        let currency = output_currency.unwrap_or_else(|| instrument.cost_currency());
2631        match Money::from_decimal(total_pnl, currency) {
2632            Ok(money) => Ok(money),
2633            Err(e) => {
2634                log::error!("Cannot calculate unrealized PnL: {e}");
2635                Err(UnrealizedPnlError::Invalid)
2636            }
2637        }
2638    }
2639
2640    fn ensure_snapshot_pnls_cached_for(&self, instrument_id: &InstrumentId) {
2641        // Performance: This method maintains an incremental cache of snapshot PnLs
2642        // It only deserializes new snapshots that haven't been processed yet
2643        // Tracks sum and last PnL per position for efficient NETTING OMS support
2644
2645        // Get all position IDs that have snapshots for this instrument
2646        let snapshot_position_ids = self.cache.borrow().position_snapshot_ids(instrument_id);
2647
2648        if snapshot_position_ids.is_empty() {
2649            return; // Nothing to process
2650        }
2651
2652        let mut rebuild = false;
2653
2654        // Detect purge/reset (count regression) or a settle that replaced frames without moving
2655        // the count, both of which invalidate the cached per-position aggregates
2656        for position_id in &snapshot_position_ids {
2657            let curr_count = self.cache.borrow().position_snapshot_count(position_id);
2658            let curr_revision = self.cache.borrow().position_snapshot_revision(position_id);
2659            let prev_count = self
2660                .inner
2661                .borrow()
2662                .snapshot_processed_counts
2663                .get(position_id)
2664                .copied()
2665                .unwrap_or(0);
2666            let prev_revision = self
2667                .inner
2668                .borrow()
2669                .snapshot_processed_revisions
2670                .get(position_id)
2671                .copied()
2672                .unwrap_or(0);
2673
2674            if prev_count > curr_count || prev_revision != curr_revision {
2675                rebuild = true;
2676                break;
2677            }
2678        }
2679
2680        if rebuild {
2681            // Full rebuild: process all snapshots from scratch
2682            for position_id in &snapshot_position_ids {
2683                // Track the raw frame count, not the decoded count: snapshots that fail
2684                // to deserialize are skipped and would otherwise make the incremental
2685                // path reprocess trailing valid frames next time.
2686                let snapshot_count = self.cache.borrow().position_snapshot_count(position_id);
2687                let snapshot_revision = self.cache.borrow().position_snapshot_revision(position_id);
2688                let snapshots = self
2689                    .cache
2690                    .borrow()
2691                    .position_snapshots(Some(position_id), None);
2692
2693                let mut sum_pnl: Option<Money> = None;
2694                let mut last_frame: Option<(&Position, Money)> = None;
2695                let mut snapshot_account_id: Option<AccountId> = None;
2696                let mut currency_mismatch = false;
2697                let mut aggregation_overflow = false;
2698
2699                for snapshot in &snapshots {
2700                    snapshot_account_id.get_or_insert(snapshot.account_id);
2701                    if let Some(realized_pnl) = snapshot.realized_pnl {
2702                        if let Some(sum) = sum_pnl {
2703                            if sum.currency == realized_pnl.currency {
2704                                if let Some(updated) = sum.checked_add(realized_pnl) {
2705                                    sum_pnl = Some(updated);
2706                                } else {
2707                                    aggregation_overflow = true;
2708                                }
2709                            } else {
2710                                currency_mismatch = true;
2711                            }
2712                        } else {
2713                            sum_pnl = Some(realized_pnl);
2714                        }
2715
2716                        last_frame = Some((snapshot, realized_pnl));
2717                    }
2718                }
2719
2720                let mut inner = self.inner.borrow_mut();
2721
2722                if !aggregation_overflow && let Some(sum) = sum_pnl {
2723                    inner.snapshot_sum_per_position.insert(*position_id, sum);
2724                    if let Some((snapshot, last_pnl)) = last_frame {
2725                        inner
2726                            .snapshot_last_per_position
2727                            .insert(*position_id, LastSnapshotFrame::new(snapshot, last_pnl));
2728                    }
2729                } else {
2730                    inner.snapshot_sum_per_position.remove(position_id);
2731                    inner.snapshot_last_per_position.remove(position_id);
2732                }
2733
2734                if currency_mismatch {
2735                    inner.snapshot_currency_mismatches.insert(*position_id);
2736                } else {
2737                    inner.snapshot_currency_mismatches.remove(position_id);
2738                }
2739
2740                if aggregation_overflow {
2741                    inner.snapshot_aggregation_overflows.insert(*position_id);
2742                } else {
2743                    inner.snapshot_aggregation_overflows.remove(position_id);
2744                }
2745
2746                if let Some(account_id) = snapshot_account_id {
2747                    inner.snapshot_account_ids.insert(*position_id, account_id);
2748                } else {
2749                    inner.snapshot_account_ids.remove(position_id);
2750                }
2751
2752                inner
2753                    .snapshot_processed_counts
2754                    .insert(*position_id, snapshot_count);
2755                inner
2756                    .snapshot_processed_revisions
2757                    .insert(*position_id, snapshot_revision);
2758            }
2759            self.inner
2760                .borrow_mut()
2761                .realized_pnls
2762                .shift_remove(instrument_id);
2763        } else {
2764            let mut cache_changed = false;
2765            // Incremental path: only process new snapshots
2766            for position_id in &snapshot_position_ids {
2767                // Compare raw frame counts first so untouched positions skip any
2768                // allocation/serde cost on repeated PnL refreshes.
2769                let curr_count = self.cache.borrow().position_snapshot_count(position_id);
2770                let curr_revision = self.cache.borrow().position_snapshot_revision(position_id);
2771                let prev_count = self
2772                    .inner
2773                    .borrow()
2774                    .snapshot_processed_counts
2775                    .get(position_id)
2776                    .copied()
2777                    .unwrap_or(0);
2778
2779                if prev_count >= curr_count {
2780                    continue;
2781                }
2782                cache_changed = true;
2783
2784                let mut sum_pnl = self
2785                    .inner
2786                    .borrow()
2787                    .snapshot_sum_per_position
2788                    .get(position_id)
2789                    .copied();
2790                let mut last_frame: Option<(&Position, Money)> = None;
2791                let mut snapshot_account_id: Option<AccountId> = None;
2792                let mut currency_mismatch = self
2793                    .inner
2794                    .borrow()
2795                    .snapshot_currency_mismatches
2796                    .contains(position_id);
2797                let mut aggregation_overflow = self
2798                    .inner
2799                    .borrow()
2800                    .snapshot_aggregation_overflows
2801                    .contains(position_id);
2802
2803                let new_snapshots = self
2804                    .cache
2805                    .borrow()
2806                    .position_snapshots_from(position_id, prev_count);
2807
2808                for snapshot in &new_snapshots {
2809                    snapshot_account_id.get_or_insert(snapshot.account_id);
2810                    if let Some(realized_pnl) = snapshot.realized_pnl {
2811                        if let Some(sum) = sum_pnl {
2812                            if sum.currency == realized_pnl.currency {
2813                                if let Some(updated) = sum.checked_add(realized_pnl) {
2814                                    sum_pnl = Some(updated);
2815                                } else {
2816                                    aggregation_overflow = true;
2817                                }
2818                            } else {
2819                                currency_mismatch = true;
2820                            }
2821                        } else {
2822                            sum_pnl = Some(realized_pnl);
2823                        }
2824
2825                        last_frame = Some((snapshot, realized_pnl));
2826                    }
2827                }
2828
2829                let mut inner = self.inner.borrow_mut();
2830
2831                if !aggregation_overflow && let Some(sum) = sum_pnl {
2832                    inner.snapshot_sum_per_position.insert(*position_id, sum);
2833                    if let Some((snapshot, last_pnl)) = last_frame {
2834                        inner
2835                            .snapshot_last_per_position
2836                            .insert(*position_id, LastSnapshotFrame::new(snapshot, last_pnl));
2837                    }
2838                }
2839
2840                if currency_mismatch {
2841                    inner.snapshot_currency_mismatches.insert(*position_id);
2842                }
2843
2844                if aggregation_overflow {
2845                    inner.snapshot_aggregation_overflows.insert(*position_id);
2846                    inner.snapshot_sum_per_position.remove(position_id);
2847                    inner.snapshot_last_per_position.remove(position_id);
2848                }
2849
2850                if let Some(account_id) = snapshot_account_id
2851                    && !inner.snapshot_account_ids.contains_key(position_id)
2852                {
2853                    inner.snapshot_account_ids.insert(*position_id, account_id);
2854                }
2855
2856                inner
2857                    .snapshot_processed_counts
2858                    .insert(*position_id, curr_count);
2859                inner
2860                    .snapshot_processed_revisions
2861                    .insert(*position_id, curr_revision);
2862            }
2863
2864            if cache_changed {
2865                self.inner
2866                    .borrow_mut()
2867                    .realized_pnls
2868                    .shift_remove(instrument_id);
2869            }
2870        }
2871    }
2872
2873    fn calculate_realized_pnl(
2874        &self,
2875        instrument_id: &InstrumentId,
2876        account_id: Option<&AccountId>,
2877        target_currency: Option<Currency>,
2878    ) -> Option<Money> {
2879        // Ensure snapshot PnLs are cached for this instrument
2880        self.ensure_snapshot_pnls_cached_for(instrument_id);
2881
2882        let cache = self.cache.borrow();
2883        let account = resolve_account_for_instrument(&cache, instrument_id, account_id);
2884        let account = if let Some(account) = account {
2885            account
2886        } else {
2887            log::error!(
2888                "Cannot calculate realized PnL: no account for {} / {account_id:?}",
2889                instrument_id.venue,
2890            );
2891            return None;
2892        };
2893
2894        let instrument = cache.instrument(instrument_id);
2895        let positions = cache.positions(None, Some(instrument_id), None, account_id, None);
2896
2897        // Filter snapshots by account when requested so closed-position PnL
2898        // from other accounts on the same venue does not leak in. Sort the
2899        // collected IDs so the per-snapshot pending-calcs/early-return path
2900        // and the value accumulation iterate in a deterministic sequence.
2901        let mut snapshot_position_ids: Vec<PositionId> = if let Some(filter_id) = account_id {
2902            let inner = self.inner.borrow();
2903            cache
2904                .position_snapshot_ids(instrument_id)
2905                .into_iter()
2906                .filter(|pid| {
2907                    inner
2908                        .snapshot_account_ids
2909                        .get(pid)
2910                        .is_some_and(|id| id == filter_id)
2911                })
2912                .collect()
2913        } else {
2914            cache
2915                .position_snapshot_ids(instrument_id)
2916                .into_iter()
2917                .collect()
2918        };
2919        snapshot_position_ids.sort();
2920
2921        if snapshot_position_ids.iter().any(|position_id| {
2922            self.inner
2923                .borrow()
2924                .snapshot_currency_mismatches
2925                .contains(position_id)
2926        }) {
2927            log::error!(
2928                "Cannot calculate realized PnL: snapshots for {instrument_id} contain mixed \
2929                cost currencies"
2930            );
2931            return None;
2932        }
2933
2934        if snapshot_position_ids.iter().any(|position_id| {
2935            self.inner
2936                .borrow()
2937                .snapshot_aggregation_overflows
2938                .contains(position_id)
2939        }) {
2940            log::error!(
2941                "Cannot calculate realized PnL: snapshot aggregation for {instrument_id} exceeds Money bounds"
2942            );
2943            return None;
2944        }
2945
2946        let conversion_currency =
2947            target_currency.or_else(|| self.conversion_base_currency(&account));
2948        let allow_stale_xrate = target_currency.is_none();
2949
2950        // Recorded PnL retains its currency after the instrument definition is purged
2951        let currency = positions
2952            .first()
2953            .map(|position| position.settlement_currency)
2954            .or_else(|| {
2955                let inner = self.inner.borrow();
2956                snapshot_position_ids.iter().find_map(|position_id| {
2957                    inner
2958                        .snapshot_sum_per_position
2959                        .get(position_id)
2960                        .map(|pnl| pnl.currency)
2961                })
2962            })
2963            .or_else(|| instrument.map(Instrument::cost_currency))
2964            .or_else(|| {
2965                log::error!("Cannot calculate realized PnL: no instrument for {instrument_id}");
2966                None
2967            })?;
2968        let currency = conversion_currency.unwrap_or(currency);
2969
2970        // Check if we need to use NETTING OMS logic
2971        let is_netting = positions
2972            .iter()
2973            .any(|p| cache.oms_type(&p.id) == Some(OmsType::Netting));
2974
2975        let mut total_pnl = Decimal::ZERO;
2976
2977        if is_netting && !snapshot_position_ids.is_empty() {
2978            // NETTING OMS: Apply 3-case rule for position cycles
2979
2980            for position_id in &snapshot_position_ids {
2981                let position = positions.iter().find(|p| p.id == *position_id);
2982                let sum_pnl = self
2983                    .inner
2984                    .borrow()
2985                    .snapshot_sum_per_position
2986                    .get(position_id)
2987                    .copied();
2988
2989                // A closed position whose final cycle was snapshotted carries that cycle both in
2990                // its last frame and in its own realized PnL, which the loop below adds; drop
2991                // the frame here so the cycle lands once, matching fills as well as PnL since an
2992                // earlier cycle can realize the same amount.
2993                let sum_pnl = if let Some(sum_pnl) = sum_pnl {
2994                    let last_pnl = position.and_then(|position| {
2995                        self.inner
2996                            .borrow()
2997                            .snapshot_last_per_position
2998                            .get(position_id)
2999                            .filter(|last| last.duplicates_closed_cycle(position))
3000                            .map(|last| last.realized_pnl)
3001                    });
3002
3003                    Some(match last_pnl {
3004                        Some(last_pnl) => match sum_pnl.checked_sub(last_pnl) {
3005                            Some(remaining) => remaining,
3006                            None => {
3007                                log::error!(
3008                                    "Cannot calculate realized PnL: snapshot adjustment exceeds Money bounds"
3009                                );
3010                                return None;
3011                            }
3012                        },
3013                        None => sum_pnl,
3014                    })
3015                } else {
3016                    None
3017                };
3018
3019                if let Some(sum_pnl) = sum_pnl {
3020                    if !pnl_currency_is_compatible(conversion_currency, currency, sum_pnl.currency)
3021                    {
3022                        return None;
3023                    }
3024
3025                    let mut pnl = sum_pnl.as_decimal();
3026
3027                    if let Some(conversion_currency) = conversion_currency {
3028                        let xrate = if let Some(xrate) = self.calculate_xrate(
3029                            instrument_id.venue,
3030                            sum_pnl.currency,
3031                            conversion_currency,
3032                            allow_stale_xrate,
3033                        ) {
3034                            xrate
3035                        } else {
3036                            log::warn!(
3037                                "Cannot calculate realized PnL: insufficient exchange rate data for {}/{}, marking as pending calculation",
3038                                sum_pnl.currency,
3039                                conversion_currency
3040                            );
3041                            self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
3042                            return None;
3043                        };
3044
3045                        pnl = self.checked_convert_realized_pnl(
3046                            pnl,
3047                            xrate,
3048                            currency,
3049                            *instrument_id,
3050                        )?;
3051                    }
3052
3053                    total_pnl = self.checked_add_realized_pnl(total_pnl, pnl, *instrument_id)?;
3054                }
3055            }
3056
3057            // Add realized PnL from current active positions
3058            for position in positions {
3059                if position.instrument_id != *instrument_id {
3060                    continue;
3061                }
3062
3063                if let Some(realized_pnl) = position.realized_pnl {
3064                    if !pnl_currency_is_compatible(
3065                        conversion_currency,
3066                        currency,
3067                        realized_pnl.currency,
3068                    ) {
3069                        return None;
3070                    }
3071
3072                    let mut pnl = realized_pnl.as_decimal();
3073
3074                    if let Some(conversion_currency) = conversion_currency {
3075                        let xrate = if let Some(xrate) = self.calculate_xrate(
3076                            instrument_id.venue,
3077                            realized_pnl.currency,
3078                            conversion_currency,
3079                            allow_stale_xrate,
3080                        ) {
3081                            xrate
3082                        } else {
3083                            log::warn!(
3084                                "Cannot calculate realized PnL: insufficient exchange rate data for {}/{}, marking as pending calculation",
3085                                realized_pnl.currency,
3086                                conversion_currency
3087                            );
3088                            self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
3089                            return None;
3090                        };
3091
3092                        pnl = self.checked_convert_realized_pnl(
3093                            pnl,
3094                            xrate,
3095                            currency,
3096                            *instrument_id,
3097                        )?;
3098                    }
3099
3100                    total_pnl = self.checked_add_realized_pnl(total_pnl, pnl, *instrument_id)?;
3101                }
3102            }
3103        } else {
3104            // HEDGING OMS or no snapshots: Simple aggregation
3105            // Add snapshot PnLs (sum all)
3106            for position_id in &snapshot_position_ids {
3107                let sum_pnl = self
3108                    .inner
3109                    .borrow()
3110                    .snapshot_sum_per_position
3111                    .get(position_id)
3112                    .copied();
3113
3114                if let Some(sum_pnl) = sum_pnl {
3115                    if !pnl_currency_is_compatible(conversion_currency, currency, sum_pnl.currency)
3116                    {
3117                        return None;
3118                    }
3119
3120                    let mut pnl = sum_pnl.as_decimal();
3121
3122                    if let Some(conversion_currency) = conversion_currency {
3123                        let xrate = if let Some(xrate) = self.calculate_xrate(
3124                            instrument_id.venue,
3125                            sum_pnl.currency,
3126                            conversion_currency,
3127                            allow_stale_xrate,
3128                        ) {
3129                            xrate
3130                        } else {
3131                            log::warn!(
3132                                "Cannot calculate realized PnL: insufficient exchange rate data for {}/{}, marking as pending calculation",
3133                                sum_pnl.currency,
3134                                conversion_currency
3135                            );
3136                            self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
3137                            return None;
3138                        };
3139
3140                        pnl = self.checked_convert_realized_pnl(
3141                            pnl,
3142                            xrate,
3143                            currency,
3144                            *instrument_id,
3145                        )?;
3146                    }
3147
3148                    total_pnl = self.checked_add_realized_pnl(total_pnl, pnl, *instrument_id)?;
3149                }
3150            }
3151
3152            // Add realized PnL from current positions
3153            for position in positions {
3154                if position.instrument_id != *instrument_id {
3155                    continue;
3156                }
3157
3158                if let Some(realized_pnl) = position.realized_pnl {
3159                    if !pnl_currency_is_compatible(
3160                        conversion_currency,
3161                        currency,
3162                        realized_pnl.currency,
3163                    ) {
3164                        return None;
3165                    }
3166
3167                    let mut pnl = realized_pnl.as_decimal();
3168
3169                    if let Some(conversion_currency) = conversion_currency {
3170                        let xrate = if let Some(xrate) = self.calculate_xrate(
3171                            instrument_id.venue,
3172                            realized_pnl.currency,
3173                            conversion_currency,
3174                            allow_stale_xrate,
3175                        ) {
3176                            xrate
3177                        } else {
3178                            log::warn!(
3179                                "Cannot calculate realized PnL: insufficient exchange rate data for {}/{}, marking as pending calculation",
3180                                realized_pnl.currency,
3181                                conversion_currency
3182                            );
3183                            self.inner.borrow_mut().pending_calcs.insert(*instrument_id);
3184                            return None;
3185                        };
3186
3187                        pnl = self.checked_convert_realized_pnl(
3188                            pnl,
3189                            xrate,
3190                            currency,
3191                            *instrument_id,
3192                        )?;
3193                    }
3194
3195                    total_pnl = self.checked_add_realized_pnl(total_pnl, pnl, *instrument_id)?;
3196                }
3197            }
3198        }
3199
3200        match Money::from_decimal(total_pnl, currency) {
3201            Ok(money) => Some(money),
3202            Err(e) => {
3203                log::error!("Cannot calculate realized PnL: {e}");
3204                None
3205            }
3206        }
3207    }
3208
3209    fn checked_convert_realized_pnl(
3210        &self,
3211        pnl: Decimal,
3212        xrate: Decimal,
3213        currency: Currency,
3214        instrument_id: InstrumentId,
3215    ) -> Option<Decimal> {
3216        let Some(converted) = pnl.checked_mul(xrate) else {
3217            log::error!("Cannot calculate realized PnL: currency conversion overflow");
3218            self.inner.borrow_mut().pending_calcs.insert(instrument_id);
3219            return None;
3220        };
3221        Some(converted.round_dp(u32::from(currency.precision)))
3222    }
3223
3224    fn checked_add_realized_pnl(
3225        &self,
3226        total: Decimal,
3227        pnl: Decimal,
3228        instrument_id: InstrumentId,
3229    ) -> Option<Decimal> {
3230        let Some(total) = total.checked_add(pnl) else {
3231            log::error!("Cannot calculate realized PnL: total overflow");
3232            self.inner.borrow_mut().pending_calcs.insert(instrument_id);
3233            return None;
3234        };
3235        Some(total)
3236    }
3237
3238    fn get_price(&self, position: &Position) -> Option<Price> {
3239        let cache = self.cache.borrow();
3240        let instrument_id = &position.instrument_id;
3241
3242        let price_type = match position.side {
3243            PositionSide::Long => PriceType::Bid,
3244            PositionSide::Short => PriceType::Ask,
3245            PositionSide::Flat => {
3246                log::error!(
3247                    "Cannot get price for invalid position side {}",
3248                    position.side
3249                );
3250                return None;
3251            }
3252        };
3253
3254        // A price at or below zero is valid where the instrument allows it
3255        let allows_non_positive = || {
3256            cache
3257                .instrument(instrument_id)
3258                .is_some_and(Instrument::allows_negative_price)
3259        };
3260        let is_valid = |price: &Price| price.as_decimal() > Decimal::ZERO || allows_non_positive();
3261        let mark_price = if self.config.use_mark_prices {
3262            cache.mark_price(instrument_id).map(|mark| mark.value)
3263        } else {
3264            None
3265        };
3266        // An empty quote side can arrive as a zero price with zero size, so a price at or below
3267        // zero counts only with size behind it
3268        let quote_price = || {
3269            cache.quote(instrument_id).and_then(|quote| {
3270                let (price, size) = match price_type {
3271                    PriceType::Bid => (quote.bid_price, quote.bid_size),
3272                    _ => (quote.ask_price, quote.ask_size),
3273                };
3274                (is_valid(&price) && (price.as_decimal() > Decimal::ZERO || size.is_positive()))
3275                    .then_some(price)
3276            })
3277        };
3278        let current = mark_price
3279            .filter(is_valid)
3280            .or_else(quote_price)
3281            .or_else(|| cache.price(instrument_id, PriceType::Last).filter(is_valid))
3282            .or_else(|| {
3283                self.inner
3284                    .borrow()
3285                    .bar_close_prices
3286                    .get(instrument_id)
3287                    .filter(|price| is_valid(price))
3288                    .copied()
3289            });
3290        drop(cache);
3291
3292        let key = (*instrument_id, position.side);
3293        let mut inner = self.inner.borrow_mut();
3294        if let Some(price) = current {
3295            inner.last_prices.insert(key, price);
3296            inner.stale_prices.remove(&key);
3297            Some(price)
3298        } else if let Some(price) = inner.last_prices.get(&key).copied() {
3299            inner.stale_prices.insert(key);
3300            Some(price)
3301        } else {
3302            inner.stale_prices.remove(&key);
3303            None
3304        }
3305    }
3306
3307    fn calculate_xrate_to_base(
3308        &self,
3309        instrument: &InstrumentAny,
3310        account: &AccountAny,
3311        source_currency: Currency,
3312    ) -> Option<Decimal> {
3313        if !self.config.convert_to_account_base_currency {
3314            return Some(Decimal::ONE); // No conversion needed
3315        }
3316
3317        let base_currency = match account.base_currency() {
3318            Some(base_currency) => base_currency,
3319            None => return Some(Decimal::ONE),
3320        };
3321
3322        self.calculate_xrate(instrument.id().venue, source_currency, base_currency, true)
3323    }
3324
3325    fn calculate_xrate(
3326        &self,
3327        venue: Venue,
3328        source_currency: Currency,
3329        target_currency: Currency,
3330        allow_stale: bool,
3331    ) -> Option<Decimal> {
3332        if source_currency == target_currency {
3333            return Some(Decimal::ONE);
3334        }
3335
3336        let cache = self.cache.borrow();
3337        let mark_xrate = if self.config.use_mark_xrates {
3338            cache
3339                .get_mark_xrate(source_currency, target_currency)
3340                .and_then(|xrate| Decimal::try_from(xrate).ok())
3341        } else {
3342            None
3343        };
3344        let current = mark_xrate
3345            .filter(|xrate| *xrate > Decimal::ZERO)
3346            .or_else(|| {
3347                cache
3348                    .get_xrate(venue, source_currency, target_currency, PriceType::Mid)
3349                    .filter(|xrate| *xrate > Decimal::ZERO)
3350            });
3351        drop(cache);
3352
3353        let key = (venue, source_currency, target_currency);
3354        let mut inner = self.inner.borrow_mut();
3355        if let Some(xrate) = current {
3356            inner.last_xrates.insert(key, xrate);
3357            inner.stale_xrates.remove(&key);
3358            Some(xrate)
3359        } else if allow_stale && let Some(xrate) = inner.last_xrates.get(&key).copied() {
3360            inner.stale_xrates.insert(key);
3361            Some(xrate)
3362        } else {
3363            inner.stale_xrates.remove(&key);
3364            None
3365        }
3366    }
3367
3368    // Pairs with `calculate_xrate_to_base`, which yields a unit rate when conversion is disabled:
3369    // the output currency must ignore the account base currency for the same reason, otherwise a
3370    // native cost-currency amount is labeled with a currency it was never converted into.
3371    fn conversion_base_currency(&self, account: &AccountAny) -> Option<Currency> {
3372        if self.config.convert_to_account_base_currency {
3373            account.base_currency()
3374        } else {
3375            None
3376        }
3377    }
3378}
3379
3380fn checked_add_money(lhs: Money, rhs: Money, context: &str) -> Option<Money> {
3381    if lhs.currency != rhs.currency {
3382        log::error!(
3383            "Cannot calculate {context}: currency mismatch {} vs {}",
3384            lhs.currency,
3385            rhs.currency
3386        );
3387        return None;
3388    }
3389
3390    match lhs.checked_add(rhs) {
3391        Some(total) => Some(total),
3392        None => {
3393            log::error!("Cannot calculate {context}: total exceeds Money bounds");
3394            None
3395        }
3396    }
3397}
3398
3399fn checked_add_money_map(
3400    totals: &mut IndexMap<Currency, Money>,
3401    money: Money,
3402    context: &str,
3403) -> Option<()> {
3404    let currency = money.currency;
3405    match totals.get_mut(&currency) {
3406        Some(total) => *total = checked_add_money(*total, money, context)?,
3407        None => {
3408            totals.insert(currency, money);
3409        }
3410    }
3411    Some(())
3412}
3413
3414fn pnl_currency_is_compatible(
3415    base_currency: Option<Currency>,
3416    output_currency: Currency,
3417    source_currency: Currency,
3418) -> bool {
3419    if base_currency.is_none() && source_currency != output_currency {
3420        log::error!(
3421            "Cannot calculate realized PnL: records have different cost currencies \
3422            ({output_currency} vs {source_currency})"
3423        );
3424        false
3425    } else {
3426        true
3427    }
3428}
3429
3430fn position_uses_premium_mark(position: &Position, cache: &Cache) -> bool {
3431    position.instrument_class.is_premium_based()
3432        && cache
3433            .account_ref(&position.account_id)
3434            .is_some_and(|account| account.calculated_account_state())
3435}
3436
3437fn decimal_map_to_money(map: IndexMap<Currency, Decimal>) -> Option<IndexMap<Currency, Money>> {
3438    map.into_iter()
3439        .map(|(currency, amount)| {
3440            Money::from_decimal(amount, currency)
3441                .map(|money| (currency, money))
3442                .inspect_err(|e| log::error!("Cannot convert {currency} amount to Money: {e}"))
3443        })
3444        .collect::<Result<_, _>>()
3445        .ok()
3446}
3447
3448fn update_quote_tick(
3449    cache: &Rc<RefCell<Cache>>,
3450    clock: &Rc<RefCell<dyn Clock>>,
3451    inner: &Rc<RefCell<PortfolioState>>,
3452    config: PortfolioConfig,
3453    quote: &QuoteTick,
3454) {
3455    update_instrument_id(cache, clock, inner, config, &quote.instrument_id);
3456}
3457
3458fn update_bar(
3459    cache: &Rc<RefCell<Cache>>,
3460    clock: &Rc<RefCell<dyn Clock>>,
3461    inner: &Rc<RefCell<PortfolioState>>,
3462    config: PortfolioConfig,
3463    bar: &Bar,
3464) {
3465    let instrument_id = bar.bar_type.instrument_id();
3466    inner
3467        .borrow_mut()
3468        .bar_close_prices
3469        .insert(instrument_id, bar.close);
3470    update_instrument_id(cache, clock, inner, config, &instrument_id);
3471}
3472
3473pub(crate) fn resolve_account<'a>(
3474    cache: &'a Cache,
3475    venue: Option<&Venue>,
3476    account_id: Option<&AccountId>,
3477) -> Option<AccountRef<'a>> {
3478    match (account_id, venue) {
3479        (Some(account_id), _) => cache.account(account_id),
3480        (None, Some(venue)) => cache.account_for_venue(venue),
3481        (None, None) => None,
3482    }
3483}
3484
3485/// Account for an instrument. For instruments routed through an execution provider, the account
3486/// uses the provider venue (e.g. `IB`) while the instrument carries the exchange
3487/// MIC (e.g. `IBIS`); on venue miss, fall back to the position-owning account.
3488fn resolve_account_for_instrument<'a>(
3489    cache: &'a Cache,
3490    instrument_id: &InstrumentId,
3491    account_id: Option<&AccountId>,
3492) -> Option<AccountRef<'a>> {
3493    match account_id {
3494        Some(id) => cache.account(id),
3495        None => cache.account_for_venue(&instrument_id.venue).or_else(|| {
3496            cache
3497                .positions(None, Some(instrument_id), None, None, None)
3498                .into_iter()
3499                .next()
3500                .and_then(|p| cache.account(&p.account_id))
3501        }),
3502    }
3503}
3504
3505fn wallet_order_reserves_balance(order: &OrderAny) -> bool {
3506    order.is_open() || order.is_inflight()
3507}
3508
3509fn wallet_reservation_orders<'a>(
3510    cache: &'a Cache,
3511    instrument_id: &InstrumentId,
3512    account_id: AccountId,
3513) -> Vec<OrderRef<'a>> {
3514    let mut client_order_ids = BTreeSet::new();
3515    client_order_ids.extend(cache.iter_client_order_ids_open(
3516        None,
3517        Some(instrument_id),
3518        None,
3519        Some(&account_id),
3520    ));
3521    client_order_ids.extend(cache.iter_client_order_ids_inflight(
3522        None,
3523        Some(instrument_id),
3524        None,
3525        Some(&account_id),
3526    ));
3527
3528    client_order_ids
3529        .into_iter()
3530        .filter_map(|client_order_id| cache.order(&client_order_id))
3531        .filter(|order| wallet_order_reserves_balance(order))
3532        .collect()
3533}
3534
3535fn update_instrument_id(
3536    cache: &Rc<RefCell<Cache>>,
3537    clock: &Rc<RefCell<dyn Clock>>,
3538    inner: &Rc<RefCell<PortfolioState>>,
3539    config: PortfolioConfig,
3540    instrument_id: &InstrumentId,
3541) {
3542    inner
3543        .borrow_mut()
3544        .unrealized_pnls
3545        .shift_remove(instrument_id);
3546
3547    if inner.borrow().initialized || !inner.borrow().pending_calcs.contains(instrument_id) {
3548        return;
3549    }
3550
3551    let instrument = match cache.borrow().instrument(instrument_id) {
3552        Some(instrument) => instrument.clone(),
3553        None => {
3554            log::error!("Cannot update tick: no instrument found for {instrument_id}");
3555            return;
3556        }
3557    };
3558
3559    let mut by_account: IndexMap<AccountId, (Vec<OrderAny>, Vec<Position>)> = IndexMap::new();
3560    {
3561        let cache_ref = cache.borrow();
3562        for order in cache_ref
3563            .orders_open(None, Some(instrument_id), None, None, None)
3564            .iter()
3565            .map(|o| (*o).clone())
3566        {
3567            if let Some(account_id) = order.account_id() {
3568                by_account.entry(account_id).or_default().0.push(order);
3569            }
3570        }
3571
3572        for position in cache_ref
3573            .positions_open(None, Some(instrument_id), None, None, None)
3574            .iter()
3575            .map(|p| (*p).clone())
3576        {
3577            by_account
3578                .entry(position.account_id)
3579                .or_default()
3580                .1
3581                .push(position);
3582        }
3583
3584        if by_account.is_empty()
3585            && let Some(account) =
3586                resolve_account_for_instrument(&cache_ref, instrument_id, None).map(|a| a.cloned())
3587        {
3588            by_account.entry(account.id()).or_default();
3589        }
3590    }
3591
3592    if by_account.is_empty() {
3593        log::error!(
3594            "Cannot update tick: no account registered for {}",
3595            instrument_id.venue
3596        );
3597        return;
3598    }
3599
3600    let ts_event = clock.borrow().timestamp_ns();
3601    let (ok, has_margin_positions) =
3602        update_pending_accounts(cache, inner, &instrument, by_account, ts_event);
3603
3604    let portfolio_clone = Portfolio {
3605        clock: Rc::clone(clock),
3606        cache: Rc::clone(cache),
3607        inner: Rc::clone(inner),
3608        config,
3609    };
3610
3611    let result_unrealized_pnl: Option<Money> =
3612        portfolio_clone.calculate_unrealized_pnl(instrument_id, None, None, None);
3613
3614    if ok && (!has_margin_positions || result_unrealized_pnl.is_some()) {
3615        let mut inner = inner.borrow_mut();
3616        inner.pending_calcs.remove(instrument_id);
3617        inner.initialized = inner.pending_calcs.is_empty();
3618    }
3619}
3620
3621fn update_pending_accounts(
3622    cache: &Rc<RefCell<Cache>>,
3623    inner: &Rc<RefCell<PortfolioState>>,
3624    instrument: &InstrumentAny,
3625    by_account: IndexMap<AccountId, (Vec<OrderAny>, Vec<Position>)>,
3626    ts_event: UnixNanos,
3627) -> (bool, bool) {
3628    let mut ok = true;
3629    let mut has_margin_positions = false;
3630
3631    for (account_id, (orders, positions)) in by_account {
3632        let Some(mut account) = cache.borrow().account(&account_id).map(|a| a.cloned()) else {
3633            log::error!("Cannot update tick: no account registered for {account_id}");
3634            ok = false;
3635            continue;
3636        };
3637
3638        has_margin_positions |= matches!(account, AccountAny::Margin(_) if !positions.is_empty());
3639
3640        if matches!(account, AccountAny::Cash(_) | AccountAny::Margin(_))
3641            && !account.calculated_account_state()
3642        {
3643            continue;
3644        }
3645
3646        let orders = if matches!(account, AccountAny::Wallet(_)) {
3647            wallet_reservation_orders(&cache.borrow(), &instrument.id(), account_id)
3648                .into_iter()
3649                .map(|order| (*order).clone())
3650                .collect()
3651        } else {
3652            orders
3653        };
3654
3655        let orders_refs: Vec<&OrderAny> = orders.iter().collect();
3656        let mut account_updated = inner
3657            .borrow()
3658            .accounts
3659            .update_orders_in_place(&mut account, instrument, &orders_refs, ts_event)
3660            .is_some();
3661
3662        if !account_updated {
3663            ok = false;
3664        }
3665
3666        if let AccountAny::Margin(margin_account) = &mut account {
3667            let positions_updated = inner
3668                .borrow()
3669                .accounts
3670                .update_positions_in_place(
3671                    margin_account,
3672                    instrument,
3673                    positions.iter().collect(),
3674                    ts_event,
3675                )
3676                .is_some();
3677            account_updated |= positions_updated;
3678            ok &= positions_updated;
3679        }
3680
3681        if account_updated {
3682            cache.borrow_mut().update_account(&account).unwrap();
3683        }
3684    }
3685
3686    (ok, has_margin_positions)
3687}
3688
3689fn update_order(
3690    cache: &Rc<RefCell<Cache>>,
3691    clock: &Rc<RefCell<dyn Clock>>,
3692    inner: &Rc<RefCell<PortfolioState>>,
3693    config: PortfolioConfig,
3694    event: &OrderEventAny,
3695    source: OrderUpdateSource,
3696) {
3697    let mut mark_pre_position_fill_event = None;
3698
3699    if let OrderEventAny::Filled(order_filled) = event {
3700        match source {
3701            OrderUpdateSource::Endpoint => {
3702                mark_pre_position_fill_event = Some(order_filled.event_id);
3703            }
3704            OrderUpdateSource::Topic => {
3705                if inner
3706                    .borrow_mut()
3707                    .pre_position_fill_events
3708                    .remove(&order_filled.event_id)
3709                {
3710                    return;
3711                }
3712            }
3713        }
3714    }
3715
3716    let account_id = match event.account_id() {
3717        Some(account_id) => account_id,
3718        None => {
3719            return; // No Account Assigned
3720        }
3721    };
3722
3723    // Scoped borrow: must drop before taking the account out of the cache
3724    let (instrument, calculate_account_state, is_wallet) = {
3725        let cache_ref = cache.borrow();
3726
3727        let account = match cache_ref.try_account(&account_id) {
3728            Ok(account) => account,
3729            Err(e) => {
3730                log::error!("Cannot update order: {e}");
3731                return;
3732            }
3733        };
3734
3735        let (calculate_account_state, is_wallet) = match &*account {
3736            AccountAny::Margin(margin_account) => {
3737                (margin_account.base.calculate_account_state, false)
3738            }
3739            AccountAny::Cash(cash_account) => (cash_account.base.calculate_account_state, false),
3740            AccountAny::Betting(betting_account) => {
3741                (betting_account.base.calculate_account_state, false)
3742            }
3743            AccountAny::Wallet(wallet_account) => {
3744                (wallet_account.base.calculate_account_state, true)
3745            }
3746        };
3747
3748        if !calculate_account_state && !is_wallet {
3749            return;
3750        }
3751
3752        match event {
3753            OrderEventAny::Submitted(_)
3754            | OrderEventAny::Accepted(_)
3755            | OrderEventAny::Canceled(_)
3756            | OrderEventAny::Expired(_)
3757            | OrderEventAny::Rejected(_)
3758            | OrderEventAny::Triggered(_)
3759            | OrderEventAny::PendingUpdate(_)
3760            | OrderEventAny::PendingCancel(_)
3761            | OrderEventAny::ModifyDenied(_)
3762            | OrderEventAny::ModifyRejected(_)
3763            | OrderEventAny::CancelDenied(_)
3764            | OrderEventAny::CancelRejected(_)
3765            | OrderEventAny::Updated(_)
3766            | OrderEventAny::Filled(_)
3767            | OrderEventAny::FillVoided(_) => {}
3768            _ => {
3769                return;
3770            }
3771        }
3772
3773        let order = cache_ref.order(&event.client_order_id());
3774        if order.is_none() && !matches!(event, OrderEventAny::Filled(_)) {
3775            log::error!(
3776                "Cannot update order: {} not found in the cache",
3777                event.client_order_id()
3778            );
3779            return; // No Order Found
3780        }
3781
3782        if !is_wallet
3783            && matches!(event, OrderEventAny::Rejected(_))
3784            && order.is_some_and(|order| {
3785                !matches!(
3786                    (order.order_type(), order.ts_accepted()),
3787                    (OrderType::StopLimit, _)
3788                        | (
3789                            OrderType::LimitIfTouched | OrderType::TrailingStopLimit,
3790                            Some(_)
3791                        )
3792                )
3793            })
3794        {
3795            return; // No change to account state
3796        }
3797
3798        let instrument = if let Some(instrument) = cache_ref.instrument(&event.instrument_id()) {
3799            instrument.clone()
3800        } else {
3801            log::error!(
3802                "Cannot update order: no instrument found for {}",
3803                event.instrument_id()
3804            );
3805            return;
3806        };
3807
3808        (instrument, calculate_account_state, is_wallet)
3809    };
3810
3811    let mut working_account = match take_or_clone_account(cache, account_id) {
3812        Some(account) => account,
3813        None => {
3814            log::error!(
3815                "Cannot update order: {}",
3816                AccountLookupError::not_found(account_id)
3817            );
3818            return;
3819        }
3820    };
3821
3822    if let OrderEventAny::Filled(order_filled) = event
3823        && calculate_account_state
3824    {
3825        if !instrument.is_spread() {
3826            let (post_balance, result) =
3827                inner
3828                    .borrow()
3829                    .accounts
3830                    .update_balances(working_account, &instrument, order_filled);
3831            working_account = post_balance;
3832
3833            if let Err(e) = result {
3834                log::error!("{e}");
3835                inner
3836                    .borrow_mut()
3837                    .balance_error
3838                    .get_or_insert_with(|| e.to_string());
3839                cache.borrow_mut().cache_account_owned(working_account);
3840                inner
3841                    .borrow_mut()
3842                    .pre_position_fill_events
3843                    .extend(mark_pre_position_fill_event);
3844                return;
3845            }
3846        }
3847
3848        cache.borrow_mut().cache_account_owned(working_account);
3849
3850        let portfolio_clone = Portfolio {
3851            clock: Rc::clone(clock),
3852            cache: Rc::clone(cache),
3853            inner: Rc::clone(inner),
3854            config,
3855        };
3856
3857        match portfolio_clone.calculate_unrealized_pnl(
3858            &order_filled.instrument_id,
3859            None,
3860            Some(&account_id),
3861            None,
3862        ) {
3863            Some(unrealized_pnl) => {
3864                inner
3865                    .borrow_mut()
3866                    .unrealized_pnls
3867                    .insert(event.instrument_id(), unrealized_pnl);
3868            }
3869            None => {
3870                // The callee already logged the cause and marked the instrument pending; the
3871                // usual cause is a book-only run with no price yet, which is not an error
3872                log::debug!(
3873                    "Failed to calculate unrealized PnL for {}, marking as pending",
3874                    event.instrument_id()
3875                );
3876            }
3877        }
3878
3879        let Some(restored_account) = take_or_clone_account(cache, account_id) else {
3880            log::error!(
3881                "Cannot finish fill account update: account {account_id} could not be restored"
3882            );
3883            return;
3884        };
3885        working_account = restored_account;
3886    } else if let OrderEventAny::FillVoided(fill_voided) = event
3887        && calculate_account_state
3888    {
3889        cache.borrow_mut().cache_account_owned(working_account);
3890
3891        let portfolio = Portfolio {
3892            clock: Rc::clone(clock),
3893            cache: Rc::clone(cache),
3894            inner: Rc::clone(inner),
3895            config,
3896        };
3897        {
3898            let cache_ref = cache.borrow();
3899            let positions =
3900                cache_ref.positions_open(None, Some(&fill_voided.instrument_id), None, None, None);
3901            let positions: Vec<&Position> = positions.iter().map(|position| &**position).collect();
3902            portfolio.update_net_position(&fill_voided.instrument_id, &positions);
3903        }
3904
3905        if let Some(pnl) =
3906            portfolio.calculate_unrealized_pnl(&fill_voided.instrument_id, None, None, None)
3907        {
3908            inner
3909                .borrow_mut()
3910                .unrealized_pnls
3911                .insert(fill_voided.instrument_id, pnl);
3912        } else {
3913            inner
3914                .borrow_mut()
3915                .unrealized_pnls
3916                .shift_remove(&fill_voided.instrument_id);
3917        }
3918
3919        if let Some(pnl) = portfolio.calculate_realized_pnl(&fill_voided.instrument_id, None, None)
3920        {
3921            inner
3922                .borrow_mut()
3923                .realized_pnls
3924                .insert(fill_voided.instrument_id, pnl);
3925        } else {
3926            inner
3927                .borrow_mut()
3928                .realized_pnls
3929                .shift_remove(&fill_voided.instrument_id);
3930        }
3931
3932        if !is_wallet {
3933            log::debug!("Updated {event}");
3934            return;
3935        }
3936
3937        let Some(restored_account) = take_or_clone_account(cache, account_id) else {
3938            log::error!(
3939                "Cannot recalculate Wallet reservations: account {account_id} was not restored after fill void"
3940            );
3941            return;
3942        };
3943        working_account = restored_account;
3944    }
3945
3946    // AccountsManager only takes shared cache borrows, so orders stay borrowed from the cache
3947    let account_state = {
3948        let cache_ref = cache.borrow();
3949
3950        let orders_open = if is_wallet {
3951            wallet_reservation_orders(&cache_ref, &event.instrument_id(), account_id)
3952        } else {
3953            cache_ref.orders_open(
3954                None,
3955                Some(&event.instrument_id()),
3956                None,
3957                Some(&account_id),
3958                None,
3959            )
3960        };
3961
3962        let orders_open_refs: Vec<&OrderAny> = orders_open.iter().map(|order| &**order).collect();
3963
3964        inner.borrow().accounts.update_orders_in_place(
3965            &mut working_account,
3966            &instrument,
3967            &orders_open_refs,
3968            clock.borrow().timestamp_ns(),
3969        )
3970    };
3971
3972    let is_fill = matches!(event, OrderEventAny::Filled(_));
3973    let suppress_margin_fill_account_state =
3974        is_fill && matches!(working_account, AccountAny::Margin(_));
3975    let publish_account_state = !matches!(source, OrderUpdateSource::Endpoint) && !is_fill;
3976
3977    if !publish_account_state
3978        && !suppress_margin_fill_account_state
3979        && let Some(account_state) = account_state.as_ref()
3980        && let Err(e) = working_account.apply(account_state.clone())
3981    {
3982        log::error!("Cannot apply generated account state: {e}");
3983    }
3984
3985    let updated_account_id = working_account.id();
3986
3987    if account_state.is_some() || matches!(event, OrderEventAny::Filled(_)) {
3988        if let Err(e) = cache.borrow_mut().update_account_owned(working_account) {
3989            log::error!("Cannot persist updated account {updated_account_id}: {e}");
3990            return;
3991        }
3992    } else {
3993        cache.borrow_mut().cache_account_owned(working_account);
3994    }
3995
3996    // Consumed by the matching `events.order.*` topic handler; engine publishes after every endpoint send
3997    if let Some(event_id) = mark_pre_position_fill_event {
3998        inner.borrow_mut().pre_position_fill_events.insert(event_id);
3999    }
4000
4001    if let Some(account_state) = account_state {
4002        if publish_account_state {
4003            update_account(clock, cache, inner, config, &account_state);
4004        }
4005    } else {
4006        log::debug!("Added pending calculation for {}", instrument.id());
4007        inner.borrow_mut().pending_calcs.insert(instrument.id());
4008    }
4009
4010    log::debug!("Updated {event}");
4011}
4012
4013fn take_or_clone_account(cache: &Rc<RefCell<Cache>>, account_id: AccountId) -> Option<AccountAny> {
4014    let account = cache.borrow_mut().take_account(&account_id);
4015
4016    account.or_else(|| cache.borrow().account_owned(&account_id))
4017}
4018
4019fn on_order_event(
4020    cache: &Rc<RefCell<Cache>>,
4021    clock: &Rc<RefCell<dyn Clock>>,
4022    inner: &Rc<RefCell<PortfolioState>>,
4023    config: PortfolioConfig,
4024    event: &OrderEventAny,
4025) {
4026    if let OrderEventAny::Filled(order_filled) = event {
4027        inner
4028            .borrow_mut()
4029            .pre_position_fill_events
4030            .remove(&order_filled.event_id);
4031        return;
4032    }
4033
4034    let account_id = match event.account_id() {
4035        Some(account_id) => account_id,
4036        None => return,
4037    };
4038
4039    let is_wallet = cache
4040        .borrow()
4041        .account(&account_id)
4042        .is_some_and(|account| matches!(&*account, AccountAny::Wallet(_)));
4043
4044    match event {
4045        OrderEventAny::Accepted(_)
4046        | OrderEventAny::Canceled(_)
4047        | OrderEventAny::Expired(_)
4048        | OrderEventAny::Rejected(_)
4049        | OrderEventAny::Updated(_) => {}
4050        OrderEventAny::Submitted(_)
4051        | OrderEventAny::Triggered(_)
4052        | OrderEventAny::PendingUpdate(_)
4053        | OrderEventAny::PendingCancel(_)
4054        | OrderEventAny::ModifyDenied(_)
4055        | OrderEventAny::ModifyRejected(_)
4056        | OrderEventAny::CancelDenied(_)
4057        | OrderEventAny::CancelRejected(_)
4058        | OrderEventAny::FillVoided(_)
4059            if is_wallet => {}
4060        _ => return,
4061    }
4062
4063    let account_state = cache
4064        .borrow()
4065        .account(&account_id)
4066        .and_then(|account| account.last_event());
4067
4068    if let Some(account_state) = account_state {
4069        update_account(clock, cache, inner, config, &account_state);
4070    }
4071}
4072
4073/// Result of peeking at the cached account inside [`update_position`]: only a margin account
4074/// with `calculate_account_state` set needs the owned recompute path.
4075enum AccountPeek {
4076    MarginRecompute,
4077    LastEvent(Box<Option<AccountState>>),
4078    Missing,
4079}
4080
4081fn update_position(
4082    cache: &Rc<RefCell<Cache>>,
4083    clock: &Rc<RefCell<dyn Clock>>,
4084    inner: &Rc<RefCell<PortfolioState>>,
4085    config: PortfolioConfig,
4086    event: &PositionEvent,
4087) {
4088    let instrument_id = event.instrument_id();
4089    let account_id = event.account_id();
4090
4091    update_snapshot_timer_state(cache, clock, inner, config, account_id);
4092
4093    let portfolio_clone = Portfolio {
4094        clock: Rc::clone(clock),
4095        cache: Rc::clone(cache),
4096        inner: Rc::clone(inner),
4097        config,
4098    };
4099
4100    {
4101        let cache_ref = cache.borrow();
4102        let refs = cache_ref.positions_open(None, Some(&instrument_id), None, None, None);
4103        log::debug!("position fresh from cache -> {refs:?}");
4104        let positions: Vec<&Position> = refs.iter().map(|r| &**r).collect();
4105        portfolio_clone.update_net_position(&instrument_id, &positions);
4106    }
4107
4108    record_closed_position_pnl(cache, inner, config, event);
4109
4110    if let Some(calculated_unrealized_pnl) =
4111        portfolio_clone.calculate_unrealized_pnl(&instrument_id, None, None, None)
4112    {
4113        inner
4114            .borrow_mut()
4115            .unrealized_pnls
4116            .insert(event.instrument_id(), calculated_unrealized_pnl);
4117    } else {
4118        log::debug!(
4119            "Failed to calculate unrealized PnL for {}, marking as pending",
4120            event.instrument_id()
4121        );
4122        inner
4123            .borrow_mut()
4124            .pending_calcs
4125            .insert(event.instrument_id());
4126    }
4127
4128    if let Some(calculated_realized_pnl) =
4129        portfolio_clone.calculate_realized_pnl(&instrument_id, None, None)
4130    {
4131        inner
4132            .borrow_mut()
4133            .realized_pnls
4134            .insert(event.instrument_id(), calculated_realized_pnl);
4135    } else {
4136        inner
4137            .borrow_mut()
4138            .realized_pnls
4139            .shift_remove(&event.instrument_id());
4140        log::warn!(
4141            "Failed to calculate realized PnL for {}, marking as pending",
4142            event.instrument_id()
4143        );
4144        inner
4145            .borrow_mut()
4146            .pending_calcs
4147            .insert(event.instrument_id());
4148    }
4149
4150    // A PnL-only adjustment such as a funding payment leaves margins unchanged, and the balance
4151    // change arrives as its own account state, so this publishes that state once instead of
4152    // recomputing a copy of it under a new event id.
4153    let pnl_only = matches!(
4154        event,
4155        PositionEvent::PositionAdjusted(adjustment) if adjustment.quantity_change.is_none()
4156    );
4157
4158    // Peek under a borrow: the account event log grows per fill, so a clone here was O(n)
4159    let peek = {
4160        let cache_ref = cache.borrow();
4161        match cache_ref.account(&account_id) {
4162            Some(account) => match &*account {
4163                AccountAny::Margin(margin_account)
4164                    if margin_account.calculate_account_state && !pnl_only =>
4165                {
4166                    AccountPeek::MarginRecompute
4167                }
4168                account => AccountPeek::LastEvent(Box::new(account.last_event())),
4169            },
4170            None => AccountPeek::Missing,
4171        }
4172    };
4173    let account_state_to_publish = match peek {
4174        AccountPeek::MarginRecompute => {
4175            recompute_margin_account(cache, clock, inner, account_id, &instrument_id)
4176        }
4177        AccountPeek::LastEvent(last_event) => *last_event,
4178        AccountPeek::Missing => {
4179            log::error!(
4180                "Cannot update position: no account registered for {}",
4181                event.account_id()
4182            );
4183            None
4184        }
4185    };
4186
4187    if let Some(account_state) = account_state_to_publish {
4188        // A settlement adjusts every open position, so later adjustments find the state published
4189        let already_published = pnl_only
4190            && inner
4191                .borrow()
4192                .last_published_account_states
4193                .get(&account_id)
4194                .is_some_and(|event_id| *event_id == account_state.event_id);
4195
4196        if !already_published {
4197            update_account(clock, cache, inner, config, &account_state);
4198        }
4199    }
4200}
4201
4202/// Recalculates the margin account for `instrument_id` from the currently open positions.
4203///
4204/// Moves the account out of the cache for the recompute instead of cloning it, then moves it
4205/// back without a database write when the recompute produces no new state.
4206fn recompute_margin_account(
4207    cache: &Rc<RefCell<Cache>>,
4208    clock: &Rc<RefCell<dyn Clock>>,
4209    inner: &Rc<RefCell<PortfolioState>>,
4210    account_id: AccountId,
4211    instrument_id: &InstrumentId,
4212) -> Option<AccountState> {
4213    let instrument = { cache.borrow().instrument(instrument_id).cloned() };
4214    let Some(instrument) = instrument else {
4215        log::error!("Cannot update position: no instrument found for {instrument_id}");
4216        let cache_ref = cache.borrow();
4217        return cache_ref
4218            .account(&account_id)
4219            .and_then(|account| account.last_event());
4220    };
4221
4222    // Bind the taken account so the mutable cache borrow drops before the recompute
4223    let taken_account = cache.borrow_mut().take_account(&account_id);
4224    let mut account = taken_account?;
4225    let AccountAny::Margin(margin_account) = &mut account else {
4226        // The caller peeked a margin account, so this only restores an unexpected account type
4227        return restore_cached_account(cache, account);
4228    };
4229
4230    let recomputed = {
4231        let cache_ref = cache.borrow();
4232        let refs =
4233            cache_ref.positions_open(None, Some(instrument_id), None, Some(&account_id), None);
4234        let positions: Vec<&Position> = refs.iter().map(|r| &**r).collect();
4235        inner.borrow_mut().accounts.update_positions_in_place(
4236            margin_account,
4237            &instrument,
4238            positions,
4239            clock.borrow().timestamp_ns(),
4240        )
4241    };
4242
4243    match recomputed {
4244        Some(account_state) => {
4245            cache.borrow_mut().update_account_owned(account).unwrap();
4246            Some(account_state)
4247        }
4248        None => restore_cached_account(cache, account),
4249    }
4250}
4251
4252/// Returns the `account` to the cache without a database write and reports its last state event.
4253fn restore_cached_account(cache: &Rc<RefCell<Cache>>, account: AccountAny) -> Option<AccountState> {
4254    let last_event = account.last_event();
4255    cache.borrow_mut().cache_account_owned(account);
4256
4257    last_event
4258}
4259
4260fn record_closed_position_pnl(
4261    cache: &Rc<RefCell<Cache>>,
4262    inner: &Rc<RefCell<PortfolioState>>,
4263    config: PortfolioConfig,
4264    event: &PositionEvent,
4265) {
4266    let position_id = match event {
4267        PositionEvent::PositionOpened(event) => event.position_id,
4268        PositionEvent::PositionChanged(event) => event.position_id,
4269        PositionEvent::PositionClosed(event) => event.position_id,
4270        PositionEvent::PositionAdjusted(event) => event.position_id,
4271    };
4272
4273    let cache_ref = cache.borrow();
4274    let Some(position) = cache_ref.position(&position_id) else {
4275        return;
4276    };
4277
4278    let cycle_key = (position.id, position.ts_opened, None);
4279    let mut inner_ref = inner.borrow_mut();
4280
4281    if !position.is_closed()
4282        && !inner_ref
4283            .recorded_closed_position_cycles
4284            .contains(&cycle_key)
4285    {
4286        return;
4287    }
4288
4289    // Corrections can remove the opening fill, so remember every fill in the cycle
4290    let cycle_keys = position
4291        .events
4292        .iter()
4293        .map(|fill| {
4294            (
4295                position.id,
4296                position.ts_opened,
4297                Some(fill.event_id.as_bytes()),
4298            )
4299        })
4300        .chain(position.events.is_empty().then_some(cycle_key));
4301
4302    if cycle_keys
4303        .clone()
4304        .any(|key| inner_ref.recorded_closed_position_cycles.contains(&key))
4305    {
4306        inner_ref.recorded_closed_position_cycles.extend(cycle_keys);
4307        return;
4308    }
4309
4310    if !position.is_closed() {
4311        return;
4312    }
4313
4314    let Some(realized_pnl) = position.realized_pnl else {
4315        return;
4316    };
4317
4318    inner_ref.recorded_closed_position_cycles.extend(cycle_keys);
4319    inner_ref.recorded_closed_position_cycles.insert(cycle_key);
4320
4321    let converted_pnl =
4322        converted_realized_pnl(&cache_ref, config, event, position_id, realized_pnl);
4323
4324    let ts_event = position.ts_last;
4325    inner_ref
4326        .analyzer
4327        .record_trade(&position.id, ts_event, &realized_pnl);
4328
4329    if let Some(converted_pnl) = converted_pnl {
4330        inner_ref
4331            .analyzer
4332            .record_trade(&position.id, ts_event, &converted_pnl);
4333    }
4334}
4335
4336fn converted_realized_pnl(
4337    cache_ref: &Cache,
4338    config: PortfolioConfig,
4339    event: &PositionEvent,
4340    position_id: PositionId,
4341    realized_pnl: Money,
4342) -> Option<Money> {
4343    let account = cache_ref.account(&event.account_id())?;
4344    let base_currency = account.base_currency()?;
4345
4346    if realized_pnl.currency == base_currency {
4347        return None;
4348    }
4349
4350    let xrate = if config.use_mark_xrates {
4351        cache_ref
4352            .get_mark_xrate(realized_pnl.currency, base_currency)
4353            .and_then(|xrate| Decimal::try_from(xrate).ok())
4354    } else {
4355        cache_ref.get_xrate(
4356            event.instrument_id().venue,
4357            realized_pnl.currency,
4358            base_currency,
4359            PriceType::Mid,
4360        )
4361    };
4362
4363    let Some(xrate) = xrate else {
4364        log::warn!(
4365            "Cannot record account-currency realized PnL for {position_id}: conversion failed from {} to {base_currency}",
4366            realized_pnl.currency
4367        );
4368        return None;
4369    };
4370
4371    let amount = (realized_pnl.as_decimal() * xrate).round_dp(u32::from(base_currency.precision));
4372    match Money::from_decimal(amount, base_currency) {
4373        Ok(amount) => Some(amount),
4374        Err(e) => {
4375            log::warn!("Cannot record account-currency realized PnL for {position_id}: {e}");
4376            None
4377        }
4378    }
4379}
4380
4381fn update_account(
4382    clock: &Rc<RefCell<dyn Clock>>,
4383    cache: &Rc<RefCell<Cache>>,
4384    inner: &Rc<RefCell<PortfolioState>>,
4385    config: PortfolioConfig,
4386    event: &AccountState,
4387) {
4388    let already_applied = {
4389        cache
4390            .borrow()
4391            .account(&event.account_id)
4392            .and_then(|account| account.last_event())
4393            .is_some_and(|last_event| last_event.event_id == event.event_id)
4394    };
4395
4396    if !already_applied && let Err(e) = cache.borrow_mut().update_account_state(event) {
4397        log::error!("Failed to update account state: {e}");
4398        return;
4399    }
4400
4401    // Throttled logging logic
4402    let mut inner_ref = inner.borrow_mut();
4403    let should_log = if inner_ref.min_account_state_logging_interval_ns.is_zero() {
4404        true
4405    } else {
4406        let current_ts = event.ts_init;
4407        let last_ts = inner_ref
4408            .last_account_state_log_ts
4409            .get(&event.account_id)
4410            .copied()
4411            .unwrap_or_default();
4412
4413        // Saturating: an out-of-order event carrying an earlier `ts_init` keeps the throttle
4414        // engaged rather than wrapping into an interval that always logs.
4415        if last_ts.is_zero()
4416            || current_ts.saturating_duration_since(last_ts)
4417                >= inner_ref.min_account_state_logging_interval_ns
4418        {
4419            inner_ref
4420                .last_account_state_log_ts
4421                .insert(event.account_id, current_ts);
4422            true
4423        } else {
4424            false
4425        }
4426    };
4427
4428    if should_log {
4429        log::info!("Updated {event}");
4430    }
4431    drop(inner_ref);
4432
4433    register_equity_curve_account(clock, cache, inner, config, event.account_id);
4434    inner
4435        .borrow_mut()
4436        .last_published_account_states
4437        .insert(event.account_id, event.event_id);
4438    msgbus::publish_account_state(format!("events.account.{}", event.account_id).into(), event);
4439}
4440
4441fn equity_curve_timer_name(account_id: AccountId) -> String {
4442    format!("{EQUITY_CURVE_TIMER_PREFIX}{account_id}")
4443}
4444
4445fn register_equity_curve_account(
4446    clock: &Rc<RefCell<dyn Clock>>,
4447    cache: &Rc<RefCell<Cache>>,
4448    inner: &Rc<RefCell<PortfolioState>>,
4449    config: PortfolioConfig,
4450    account_id: AccountId,
4451) {
4452    if !config.equity_curve {
4453        return;
4454    }
4455
4456    let is_new = {
4457        let mut inner = inner.borrow_mut();
4458        if inner.equity_curve_finalized {
4459            return;
4460        }
4461        inner.equity_curve_accounts.insert(account_id)
4462    };
4463
4464    if !is_new {
4465        return;
4466    }
4467
4468    arm_equity_curve_timer(clock, cache, inner, config, account_id);
4469    let ts_event = clock.borrow().timestamp_ns();
4470    emit_snapshot(cache, clock, inner, config, account_id, ts_event);
4471}
4472
4473fn arm_equity_curve_timer(
4474    clock: &Rc<RefCell<dyn Clock>>,
4475    cache: &Rc<RefCell<Cache>>,
4476    inner: &Rc<RefCell<PortfolioState>>,
4477    config: PortfolioConfig,
4478    account_id: AccountId,
4479) {
4480    let day = DurationNanos::from_days(1);
4481    let Some(next_day) = clock.borrow().timestamp_ns().floor(day).checked_add(day) else {
4482        log::error!("Failed to calculate next equity curve sample for {account_id}");
4483        return;
4484    };
4485    let timer_name = equity_curve_timer_name(account_id);
4486    let cache_weak = Rc::downgrade(cache);
4487    let clock_weak = Rc::downgrade(clock);
4488    let inner_weak = Rc::downgrade(inner);
4489
4490    let callback: Rc<dyn Fn(TimeEvent)> = Rc::new(move |event| {
4491        let Some(cache) = cache_weak.upgrade() else {
4492            return;
4493        };
4494        let Some(clock) = clock_weak.upgrade() else {
4495            return;
4496        };
4497        let Some(inner) = inner_weak.upgrade() else {
4498            return;
4499        };
4500        emit_snapshot(&cache, &clock, &inner, config, account_id, event.ts_event);
4501    });
4502
4503    if let Err(e) = clock.borrow_mut().set_timer_ns(
4504        &timer_name,
4505        day,
4506        Some(next_day),
4507        None,
4508        Some(TimeEventCallback::from(callback)),
4509        Some(false),
4510        Some(true),
4511    ) {
4512        log::error!("Failed to arm portfolio equity curve timer for {account_id}: {e}");
4513    }
4514}
4515
4516fn snapshot_timer_name(account_id: AccountId) -> String {
4517    format!("{SNAPSHOT_TIMER_PREFIX}{account_id}")
4518}
4519
4520/// Returns whether the timer name uses a portfolio snapshot namespace.
4521///
4522/// Backtests use this classification so snapshot-only timestamps do not release older
4523/// latency-deferred commands.
4524#[doc(hidden)]
4525#[must_use]
4526pub fn is_snapshot_timer(name: &str) -> bool {
4527    name.starts_with(EQUITY_CURVE_TIMER_PREFIX) || name.starts_with(SNAPSHOT_TIMER_PREFIX)
4528}
4529
4530fn update_snapshot_timer_state(
4531    cache: &Rc<RefCell<Cache>>,
4532    clock: &Rc<RefCell<dyn Clock>>,
4533    inner: &Rc<RefCell<PortfolioState>>,
4534    config: PortfolioConfig,
4535    account_id: AccountId,
4536) {
4537    if config.snapshot_interval_ms.is_none() {
4538        return;
4539    }
4540
4541    let current_count = cache
4542        .borrow()
4543        .positions_open(None, None, None, Some(&account_id), None)
4544        .len();
4545
4546    let prev_count = inner
4547        .borrow()
4548        .account_open_positions
4549        .get(&account_id)
4550        .copied()
4551        .unwrap_or(0);
4552
4553    inner
4554        .borrow_mut()
4555        .account_open_positions
4556        .insert(account_id, current_count);
4557
4558    if prev_count == 0 && current_count > 0 {
4559        arm_snapshot_timer(cache, clock, inner, config, account_id);
4560    } else if prev_count > 0 && current_count == 0 {
4561        clock
4562            .borrow_mut()
4563            .cancel_timer(&snapshot_timer_name(account_id));
4564    }
4565}
4566
4567fn arm_snapshot_timer(
4568    cache: &Rc<RefCell<Cache>>,
4569    clock: &Rc<RefCell<dyn Clock>>,
4570    inner: &Rc<RefCell<PortfolioState>>,
4571    config: PortfolioConfig,
4572    account_id: AccountId,
4573) {
4574    let interval_ms = match config.snapshot_interval_ms {
4575        Some(ms) if ms > 0 => ms,
4576        _ => return,
4577    };
4578    let Ok(interval_ns) = DurationNanos::try_from_millis(interval_ms) else {
4579        log::error!("Failed to calculate portfolio snapshot interval for {account_id}");
4580        return;
4581    };
4582    let timer_name = snapshot_timer_name(account_id);
4583
4584    let cache_weak = Rc::downgrade(cache);
4585    let clock_weak = Rc::downgrade(clock);
4586    let inner_weak = Rc::downgrade(inner);
4587
4588    let callback: Rc<dyn Fn(TimeEvent)> = Rc::new(move |event| {
4589        let cache = match cache_weak.upgrade() {
4590            Some(c) => c,
4591            None => return,
4592        };
4593        let clock = match clock_weak.upgrade() {
4594            Some(c) => c,
4595            None => return,
4596        };
4597        let inner = match inner_weak.upgrade() {
4598            Some(i) => i,
4599            None => return,
4600        };
4601        emit_snapshot(&cache, &clock, &inner, config, account_id, event.ts_event);
4602    });
4603
4604    if let Err(e) = clock.borrow_mut().set_timer_ns(
4605        &timer_name,
4606        interval_ns,
4607        None,
4608        None,
4609        Some(TimeEventCallback::from(callback)),
4610        Some(true),
4611        Some(false),
4612    ) {
4613        log::error!("Failed to arm portfolio snapshot timer for {account_id}: {e}");
4614    }
4615}
4616
4617fn emit_snapshot(
4618    cache: &Rc<RefCell<Cache>>,
4619    clock: &Rc<RefCell<dyn Clock>>,
4620    inner: &Rc<RefCell<PortfolioState>>,
4621    config: PortfolioConfig,
4622    account_id: AccountId,
4623    ts_event: nautilus_core::UnixNanos,
4624) {
4625    let mut portfolio = Portfolio {
4626        cache: Rc::clone(cache),
4627        clock: Rc::clone(clock),
4628        inner: Rc::clone(inner),
4629        config,
4630    };
4631
4632    // Skip the missing-price tracker: no caller refreshes the account scope between
4633    // scheduled samples. The snapshot still reports its unpriced instruments.
4634    let mut snapshot = match portfolio.build_snapshot_inner(account_id, false) {
4635        Some(snapshot) => snapshot,
4636        None => return,
4637    };
4638    // Stamp the snapshot with the timer's scheduled fire time so the cadence
4639    // is preserved even if the dispatcher batches or runs late. ts_init stays
4640    // the construction time set by build_snapshot.
4641    snapshot.ts_event = ts_event;
4642
4643    msgbus::publish_portfolio_snapshot(format!("events.portfolio.{account_id}").into(), &snapshot);
4644
4645    let mut inner_mut = inner.borrow_mut();
4646    push_bounded(
4647        &mut inner_mut.portfolio_snapshots,
4648        account_id,
4649        snapshot,
4650        SNAPSHOT_BUFFER_CAP,
4651    );
4652}
4653
4654/// Appends `snapshot` onto the per-account ring, dropping the oldest entry when at `cap`.
4655fn push_bounded(
4656    snapshots: &mut AHashMap<AccountId, VecDeque<PortfolioSnapshot>>,
4657    account_id: AccountId,
4658    snapshot: PortfolioSnapshot,
4659    cap: usize,
4660) {
4661    let ring = snapshots.entry(account_id).or_default();
4662    if ring.len() == cap {
4663        ring.pop_front();
4664    }
4665    ring.push_back(snapshot);
4666}
4667
4668#[cfg(test)]
4669mod tests {
4670    use nautilus_common::clock::VirtualClock;
4671    use nautilus_core::{UUID4, UnixNanos};
4672    use nautilus_model::{
4673        enums::{AccountType, OrderSide},
4674        events::order::spec::OrderFilledSpec,
4675        identifiers::{AccountId, Symbol},
4676        instruments::stubs::option_contract_appl,
4677        types::{Quantity, money::MONEY_RAW_MAX},
4678    };
4679    use rstest::rstest;
4680
4681    use super::*;
4682
4683    #[rstest]
4684    fn test_decimal_map_to_money_rejects_partial_currency_buckets() {
4685        let usd = Currency::USD();
4686        let amount = Money::from_raw(MONEY_RAW_MAX / 4 * 3, usd).as_decimal();
4687        let values = IndexMap::from([(Currency::EUR(), Decimal::ONE), (usd, amount + amount)]);
4688
4689        assert_eq!(decimal_map_to_money(values), None);
4690    }
4691
4692    #[rstest]
4693    #[case::positive_cash(true)]
4694    #[case::negative_cash(false)]
4695    fn test_reported_snapshot_nets_venue_pnl_before_cash(#[case] positive_cash: bool) {
4696        let mut portfolio = Portfolio::new(
4697            Rc::new(RefCell::new(VirtualClock::new())),
4698            Rc::new(RefCell::new(Cache::new(None, None))),
4699            None,
4700        );
4701        let account_id = AccountId::new("BROKER-001");
4702        let cash_value = Money::from_raw(MONEY_RAW_MAX / 4 * 3, Currency::USD())
4703            .as_decimal()
4704            .round_dp(2);
4705
4706        let cash = Money::from_decimal(
4707            if positive_cash {
4708                cash_value
4709            } else {
4710                -cash_value
4711            },
4712            Currency::USD(),
4713        )
4714        .unwrap();
4715
4716        portfolio.update_account(&AccountState::new(
4717            account_id,
4718            AccountType::Margin,
4719            vec![AccountBalance::new(
4720                cash,
4721                Money::zero(Currency::USD()),
4722                cash,
4723            )],
4724            vec![],
4725            true,
4726            UUID4::new(),
4727            0.into(),
4728            0.into(),
4729            Some(Currency::USD()),
4730        ));
4731        let pnl = Money::from_raw(MONEY_RAW_MAX / 3, Currency::USD())
4732            .as_decimal()
4733            .round_dp(2);
4734        let mark = Price::from_decimal(pnl + Decimal::ONE).unwrap();
4735        let venues = AHashSet::from_iter([Venue::new("VENUE1"), Venue::new("VENUE2")]);
4736
4737        // Put the overflowing PnL first regardless of the hash iteration order
4738        for (index, venue) in venues.iter().enumerate() {
4739            let mut option = option_contract_appl();
4740            option.id = InstrumentId::new(Symbol::new("OPTION"), *venue);
4741            let instrument = InstrumentAny::OptionContract(option);
4742
4743            let side = if (index == 0) == positive_cash {
4744                OrderSide::Buy
4745            } else {
4746                OrderSide::Sell
4747            };
4748
4749            let fill = OrderFilledSpec::builder()
4750                .instrument_id(instrument.id())
4751                .account_id(account_id)
4752                .order_side(side)
4753                .last_qty(Quantity::from("1"))
4754                .last_px(Price::from("1.00"))
4755                .currency(Currency::USD())
4756                .position_id(PositionId::new(format!("P-{venue}")))
4757                .build();
4758            let position = Position::new(&instrument, fill);
4759            let mut cache = portfolio.cache.borrow_mut();
4760            cache.add_instrument(instrument.clone()).unwrap();
4761            cache.add_position(&position, OmsType::Hedging).unwrap();
4762            cache
4763                .add_mark_price(MarkPriceUpdate::new(
4764                    instrument.id(),
4765                    mark,
4766                    0.into(),
4767                    0.into(),
4768                ))
4769                .unwrap();
4770        }
4771
4772        let account = portfolio
4773            .cache
4774            .borrow()
4775            .account_ref(&account_id)
4776            .unwrap()
4777            .clone_without_events();
4778        let mut unpriced = AHashSet::new();
4779        let unrealized = IndexMap::from([(Currency::USD(), Money::zero(Currency::USD()))]);
4780        let equity = portfolio.calculate_snapshot_equity(
4781            &account,
4782            &venues,
4783            &unrealized,
4784            &mut unpriced,
4785            false,
4786        );
4787        let snapshot = portfolio.build_snapshot(&account_id).unwrap();
4788
4789        assert_eq!(equity, Some(IndexMap::from([(Currency::USD(), cash)])));
4790        assert_eq!(snapshot.unrealized_pnls, vec![Money::zero(Currency::USD())]);
4791        assert_eq!(snapshot.total_equity, vec![cash]);
4792        assert_eq!(unpriced, AHashSet::new());
4793        assert_eq!(snapshot.unpriced_instruments, Vec::<InstrumentId>::new());
4794        assert!(!snapshot.is_stale);
4795    }
4796
4797    #[rstest]
4798    #[case::equity_curve(equity_curve_timer_name(AccountId::new("SIM-001")), true)]
4799    #[case::snapshot(snapshot_timer_name(AccountId::new("SIM-001")), true)]
4800    #[case::strategy("settlement".to_string(), false)]
4801    #[case::similar_name("portfolio_snapshot_strategy".to_string(), false)]
4802    fn test_is_snapshot_timer(#[case] name: String, #[case] expected: bool) {
4803        assert_eq!(is_snapshot_timer(&name), expected);
4804    }
4805
4806    fn mk_snapshot(seq: u64) -> PortfolioSnapshot {
4807        PortfolioSnapshot::new(
4808            AccountId::new("SIM-001"),
4809            AccountType::Cash,
4810            None,
4811            Vec::new(),
4812            Vec::new(),
4813            Vec::new(),
4814            Vec::new(),
4815            Vec::new(),
4816            None,
4817            false,
4818            Vec::new(),
4819            Vec::new(),
4820            Vec::new(),
4821            UUID4::new(),
4822            UnixNanos::from(seq),
4823            UnixNanos::from(seq),
4824        )
4825    }
4826
4827    #[rstest]
4828    fn push_bounded_drops_oldest_when_at_cap() {
4829        let account_id = AccountId::new("SIM-001");
4830        let mut snapshots: AHashMap<AccountId, VecDeque<PortfolioSnapshot>> = AHashMap::new();
4831
4832        for seq in 0..5 {
4833            push_bounded(&mut snapshots, account_id, mk_snapshot(seq), 3);
4834        }
4835
4836        let ring = snapshots.get(&account_id).expect("ring exists");
4837        assert_eq!(ring.len(), 3);
4838        assert_eq!(ring.front().unwrap().ts_event, UnixNanos::from(2));
4839        assert_eq!(ring.back().unwrap().ts_event, UnixNanos::from(4));
4840    }
4841}