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