Skip to main content

nautilus_model/accounts/
base.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//! Base traits and common types shared by all account implementations.
17//!
18//! Concrete account types (`CashAccount`, `MarginAccount`, etc.) build on the abstractions defined
19//! in this file.
20
21use std::sync::Arc;
22
23use ahash::AHashMap;
24use indexmap::IndexMap;
25use nautilus_core::{
26    DurationNanos, UnixNanos,
27    correctness::{CorrectnessError, CorrectnessResult, FAILED, check_equal},
28};
29use serde::{Deserialize, Serialize};
30
31use crate::{
32    accounts::fill_position_pnl,
33    enums::{AccountType, LiquiditySide, OrderSide},
34    events::{AccountState, OrderFilled},
35    fees::{MakerTakerFeeRates, calculate_maker_taker_commission},
36    identifiers::{AccountId, InstrumentId},
37    instruments::{Instrument, InstrumentAny},
38    position::{Position, amount, money_from_qty, notional},
39    types::{AccountBalance, Currency, Money, Price, Quantity},
40};
41
42/// Represents the account state shared by every account type.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44#[cfg_attr(
45    feature = "python",
46    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
47)]
48pub struct BaseAccount {
49    /// The account ID.
50    pub id: AccountId,
51    /// The type of the account (e.g., margin, spot, etc.).
52    pub account_type: AccountType,
53    /// The base currency for the account, if applicable.
54    pub base_currency: Option<Currency>,
55    /// Indicates if the account state is recalculated from order fills
56    /// (as opposed to taken from venue reports).
57    pub calculate_account_state: bool,
58    /// The account state events, oldest first.
59    ///
60    /// Clones share this history until one of them is modified.
61    pub events: Arc<Vec<AccountState>>,
62    /// The commissions charged so far, keyed by currency.
63    pub commissions: AHashMap<Currency, Money>,
64    /// The current balances in the account, keyed by currency.
65    pub balances: IndexMap<Currency, AccountBalance>,
66    /// The total balances the account started with, keyed by currency.
67    pub balances_starting: IndexMap<Currency, Money>,
68}
69
70impl BaseAccount {
71    /// Creates a new [`BaseAccount`] instance.
72    #[must_use]
73    pub fn new(event: AccountState, calculate_account_state: bool) -> Self {
74        let mut balances_starting: IndexMap<Currency, Money> = IndexMap::new();
75        let mut balances: IndexMap<Currency, AccountBalance> = IndexMap::new();
76        event.balances.iter().for_each(|balance| {
77            balances_starting.insert(balance.currency, balance.total);
78            balances.insert(balance.currency, *balance);
79        });
80        Self {
81            id: event.account_id,
82            account_type: event.account_type,
83            base_currency: event.base_currency,
84            calculate_account_state,
85            events: Arc::new(vec![event]),
86            commissions: AHashMap::new(),
87            balances,
88            balances_starting,
89        }
90    }
91
92    #[must_use]
93    pub(crate) fn clone_without_events(&self) -> Self {
94        Self {
95            id: self.id,
96            account_type: self.account_type,
97            base_currency: self.base_currency,
98            calculate_account_state: self.calculate_account_state,
99            events: Arc::default(),
100            commissions: self.commissions.clone(),
101            balances: self.balances.clone(),
102            balances_starting: self.balances_starting.clone(),
103        }
104    }
105
106    /// Returns a reference to the `AccountBalance` for the specified currency, or `None` if absent.
107    ///
108    /// # Panics
109    ///
110    /// Panics if `currency` is `None` and `self.base_currency` is `None`.
111    #[must_use]
112    pub fn base_balance(&self, currency: Option<Currency>) -> Option<&AccountBalance> {
113        let currency = currency
114            .or(self.base_currency)
115            .expect("Currency must be specified");
116        self.balances.get(&currency)
117    }
118
119    /// Returns the total `Money` balance for the specified currency, or `None` if absent.
120    ///
121    /// # Panics
122    ///
123    /// Panics if `currency` is `None` and `self.base_currency` is `None`.
124    #[must_use]
125    pub fn base_balance_total(&self, currency: Option<Currency>) -> Option<Money> {
126        self.base_balance(currency).map(|balance| balance.total)
127    }
128
129    #[must_use]
130    pub fn base_balances_total(&self) -> IndexMap<Currency, Money> {
131        self.balances
132            .iter()
133            .map(|(currency, balance)| (*currency, balance.total))
134            .collect()
135    }
136
137    /// Returns the free `Money` balance for the specified currency, or `None` if absent.
138    ///
139    /// # Panics
140    ///
141    /// Panics if `currency` is `None` and `self.base_currency` is `None`.
142    #[must_use]
143    pub fn base_balance_free(&self, currency: Option<Currency>) -> Option<Money> {
144        self.base_balance(currency).map(|balance| balance.free)
145    }
146
147    #[must_use]
148    pub fn base_balances_free(&self) -> IndexMap<Currency, Money> {
149        self.balances
150            .iter()
151            .map(|(currency, balance)| (*currency, balance.free))
152            .collect()
153    }
154
155    /// Returns the locked `Money` balance for the specified currency, or `None` if absent.
156    ///
157    /// # Panics
158    ///
159    /// Panics if `currency` is `None` and `self.base_currency` is `None`.
160    #[must_use]
161    pub fn base_balance_locked(&self, currency: Option<Currency>) -> Option<Money> {
162        self.base_balance(currency).map(|balance| balance.locked)
163    }
164
165    #[must_use]
166    pub fn base_balances_locked(&self) -> IndexMap<Currency, Money> {
167        self.balances
168            .iter()
169            .map(|(currency, balance)| (*currency, balance.locked))
170            .collect()
171    }
172
173    #[must_use]
174    pub fn base_last_event(&self) -> Option<AccountState> {
175        self.events.last().cloned()
176    }
177
178    /// Updates the account balances with the provided list of `AccountBalance` instances.
179    ///
180    /// Note: This method does NOT validate negative balances. Derived account types
181    /// (`CashAccount`, `MarginAccount`) should perform their own validation in `apply()`:
182    /// - `MarginAccount`: allows negative balances (normal for margin trading)
183    /// - `CashAccount`: rejects negative unless `allow_borrowing` is true
184    pub fn update_balances(&mut self, balances: &[AccountBalance]) {
185        for balance in balances {
186            self.balances.insert(balance.currency, *balance);
187        }
188    }
189
190    /// Updates the account commissions with the provided amount.
191    ///
192    /// # Panics
193    ///
194    /// Panics if the accumulated commission exceeds [`Money`] bounds. Operational callers should
195    /// use [`Self::try_update_commissions`] when the input is not already known to fit.
196    pub fn update_commissions(&mut self, commission: Money) {
197        self.try_update_commissions(commission)
198            .expect("commission total exceeded Money bounds");
199    }
200
201    /// Updates the account commissions with the provided amount.
202    ///
203    /// # Errors
204    ///
205    /// Returns an error if the accumulated commission exceeds [`Money`] bounds.
206    pub fn try_update_commissions(&mut self, commission: Money) -> anyhow::Result<()> {
207        if commission.is_zero() {
208            return Ok(());
209        }
210        let currency = commission.currency;
211        let total = self
212            .commissions
213            .get(&currency)
214            .copied()
215            .map_or(Some(commission), |total| total.checked_add(commission))
216            .ok_or_else(|| anyhow::anyhow!("{currency} commission total exceeds Money bounds"))?;
217        self.commissions.insert(currency, total);
218        Ok(())
219    }
220
221    /// Returns the total commission for the specified currency.
222    #[must_use]
223    pub fn commission(&self, currency: &Currency) -> Option<Money> {
224        self.commissions.get(currency).copied()
225    }
226
227    /// Returns a map of all commissions by currency.
228    #[must_use]
229    pub fn commissions(&self) -> AHashMap<Currency, Money> {
230        self.commissions.clone()
231    }
232
233    /// Checks the event belongs to this account.
234    ///
235    /// Concrete accounts call this before mutating any state, so a foreign event is rejected
236    /// rather than partially applied.
237    ///
238    /// # Errors
239    ///
240    /// Returns an error if `event.account_id` does not match this account's ID.
241    pub(crate) fn check_event_account_id(&self, event: &AccountState) -> anyhow::Result<()> {
242        anyhow::ensure!(
243            event.account_id == self.id,
244            "Account event had a different account ID: expected {}, received {}",
245            self.id,
246            event.account_id
247        );
248        Ok(())
249    }
250
251    /// Applies an [`AccountState`] event, updating balances.
252    ///
253    /// # Panics
254    ///
255    /// Panics if `event.account_id` does not match this account's ID. Every account rejects a
256    /// foreign event before reaching here, so this remains an internal invariant.
257    pub fn base_apply(&mut self, event: AccountState) {
258        check_equal(&event.account_id, &self.id, "event.account_id", "self.id").expect(FAILED);
259        self.update_balances(&event.balances);
260        Arc::make_mut(&mut self.events).push(event);
261    }
262
263    /// Purges all account state events which are outside the lookback window.
264    ///
265    /// Guaranteed to retain at least the latest event.
266    ///
267    /// # Panics
268    ///
269    /// Panics if the purging implementation is changed and all events are purged.
270    pub fn base_purge_account_events(&mut self, ts_now: UnixNanos, lookback_secs: u64) {
271        let Ok(lookback_ns) = DurationNanos::try_from_secs(lookback_secs) else {
272            log::warn!(
273                "Cannot purge account events: lookback_secs {lookback_secs} is not representable in `u64` nanoseconds"
274            );
275            return;
276        };
277        let purge_cutoff = ts_now.checked_sub(lookback_ns);
278
279        let mut retained_events = Vec::new();
280
281        for event in self.events.iter() {
282            if purge_cutoff.is_none_or(|cutoff| event.ts_event > cutoff) {
283                retained_events.push(event.clone());
284            }
285        }
286
287        // Guarantee ≥ 1 event
288        if retained_events.is_empty() && !self.events.is_empty() {
289            retained_events.push(self.events.last().expect("events not empty").clone());
290        }
291
292        self.events = Arc::new(retained_events);
293    }
294
295    /// Calculates the amount of balance to lock for a new order based on the given side, quantity, and price.
296    ///
297    /// Projects the reservation at native [`Money`] precision with midpoint-to-even rounding.
298    ///
299    /// # Errors
300    ///
301    /// Returns an error if an input or the locked amount exceeds the accounting bounds.
302    pub fn base_calculate_balance_locked(
303        &self,
304        instrument: &InstrumentAny,
305        side: OrderSide,
306        quantity: Quantity,
307        price: Price,
308        use_quote_for_inverse: Option<bool>,
309    ) -> anyhow::Result<Money> {
310        match side {
311            // A buy at a negative price settles as a credit rather than a debit, so it
312            // reserves nothing. Clamping per order rather than after aggregation keeps a
313            // negative-price buy from financing a positive-price one before either fills.
314            OrderSide::Buy => {
315                let notional =
316                    calculate_notional(instrument, quantity, price, use_quote_for_inverse)?;
317                Ok(notional.max(Money::zero(notional.currency)))
318            }
319            // No modeled base asset means nothing to reserve; inventory is venue-enforced.
320            OrderSide::Sell => match instrument.base_currency() {
321                Some(currency) => Ok(money_from_qty(quantity, currency)?),
322                None => Ok(Money::from_raw_checked(0, instrument.quote_currency())?),
323            },
324        }
325    }
326
327    /// Calculates profit and loss amounts for a filled order.
328    ///
329    /// For cash accounts, this calculates the balance impact of a fill:
330    /// - BUY: gain base currency quantity, lose quote currency notional.
331    /// - SELL: lose base currency quantity, gain quote currency notional.
332    ///
333    /// Note: Unlike betting accounts, cash accounts do NOT cap to position quantity.
334    /// The full fill quantity is used for PnL calculation.
335    ///
336    /// Projects each cash flow at native [`Money`] precision with midpoint-to-even rounding.
337    ///
338    /// # Errors
339    ///
340    /// Returns an error if an input, cash flow, or resulting position exceeds the accounting bounds.
341    #[allow(
342        clippy::needless_pass_by_value,
343        reason = "matches the owned Position input of Account::calculate_pnls"
344    )]
345    pub fn base_calculate_pnls(
346        &self,
347        instrument: &InstrumentAny,
348        fill: &OrderFilled,
349        position: Option<Position>,
350    ) -> anyhow::Result<Vec<Money>> {
351        if let Some(commission) = fill.commission {
352            amount(commission)?;
353        }
354
355        fill_position_pnl(instrument, fill, position.as_ref())?;
356
357        let mut pnls: IndexMap<Currency, Money> = IndexMap::new();
358        let base_currency = instrument.base_currency();
359
360        // No quantity capping (betting accounts cap to position qty, cash accounts don't)
361        let fill_qty = fill.last_qty;
362        let notional = calculate_notional(instrument, fill_qty, fill.last_px, None)?;
363
364        if fill.order_side == OrderSide::Buy {
365            if let (Some(base_currency_value), None) = (base_currency, self.base_currency) {
366                pnls.insert(
367                    base_currency_value,
368                    money_from_qty(fill_qty, base_currency_value)?,
369                );
370            }
371            pnls.insert(notional.currency, -notional);
372        } else {
373            if let (Some(base_currency_value), None) = (base_currency, self.base_currency) {
374                pnls.insert(
375                    base_currency_value,
376                    -money_from_qty(fill_qty, base_currency_value)?,
377                );
378            }
379            pnls.insert(notional.currency, notional);
380        }
381        Ok(pnls.into_values().collect())
382    }
383
384    /// Calculates commission fees for a filled order from explicitly resolved fee rates.
385    ///
386    /// Fee policy belongs to the account-owned schedule, not the instrument. Callers must
387    /// resolve `fee_rates` for the instrument (including any exact override) before calling.
388    ///
389    /// # Errors
390    ///
391    /// Returns an error if `liquidity_side` is invalid, the notional value cannot be calculated,
392    /// or the commission cannot be represented in the target currency.
393    pub fn base_calculate_commission(
394        &self,
395        instrument: &InstrumentAny,
396        last_qty: Quantity,
397        last_px: Price,
398        liquidity_side: LiquiditySide,
399        fee_rates: MakerTakerFeeRates,
400        use_quote_for_inverse: Option<bool>,
401    ) -> anyhow::Result<Money> {
402        let rate = fee_rates.rate_for(liquidity_side)?;
403        calculate_maker_taker_commission(instrument, last_qty, last_px, rate, use_quote_for_inverse)
404    }
405}
406
407fn calculate_notional(
408    instrument: &InstrumentAny,
409    quantity: Quantity,
410    price: Price,
411    use_quote_for_inverse: Option<bool>,
412) -> anyhow::Result<Money> {
413    if instrument.is_inverse() && use_quote_for_inverse.unwrap_or(false) {
414        return Ok(money_from_qty(quantity, instrument.quote_currency())?);
415    }
416
417    let currency = if instrument.is_inverse() {
418        instrument
419            .base_currency()
420            .ok_or_else(|| anyhow::anyhow!("inverse instrument has no base currency"))?
421    } else {
422        instrument.cost_currency()
423    };
424
425    Ok(notional(
426        quantity,
427        price,
428        instrument.multiplier(),
429        instrument
430            .instrument_class()
431            .divides_notional_by_price(instrument.is_inverse()),
432        currency,
433    )?)
434}
435
436/// Updates the locked balance for the given instrument and currency, then recalculates the
437/// account balance for that currency from all per-(instrument, currency) locks.
438///
439/// The reservation is recorded without a balance when the currency has no observed balance yet,
440/// so a later balance report derives from it.
441///
442/// # Errors
443///
444/// Returns an error if `locked` is negative, its precision differs from the balance precision,
445/// or the reservations cannot produce a valid balance. Balances and reservations are left
446/// unchanged when an error is returned.
447pub(crate) fn update_balance_locked(
448    balances: &mut IndexMap<Currency, AccountBalance>,
449    balances_locked: &mut AHashMap<(InstrumentId, Currency), Money>,
450    instrument_id: InstrumentId,
451    locked: Money,
452) -> anyhow::Result<()> {
453    anyhow::ensure!(
454        !locked.is_negative(),
455        "locked balance was negative: {locked}"
456    );
457
458    let currency = locked.currency;
459    let key = (instrument_id, currency);
460
461    let Some(current_balance) = balances.get(&currency).copied() else {
462        balances_locked.insert(key, locked);
463        return Ok(());
464    };
465
466    anyhow::ensure!(
467        current_balance.currency.precision == currency.precision,
468        "Cannot update {currency} reservation: precision {} differed from balance precision {}",
469        currency.precision,
470        current_balance.currency.precision
471    );
472
473    let previous = balances_locked.insert(key, locked);
474
475    match balance_from_locks(current_balance, balances_locked) {
476        Ok(balance) => {
477            balances.insert(currency, balance);
478            Ok(())
479        }
480        Err(e) => {
481            // Restore the prior reservation so a rejected update leaves nothing behind
482            match previous {
483                Some(previous) => balances_locked.insert(key, previous),
484                None => balances_locked.remove(&key),
485            };
486            Err(e.into())
487        }
488    }
489}
490
491/// Clears all locked balances for the given instrument ID, recalculating each affected currency.
492pub(crate) fn clear_balance_locked(
493    balances: &mut IndexMap<Currency, AccountBalance>,
494    balances_locked: &mut AHashMap<(InstrumentId, Currency), Money>,
495    instrument_id: InstrumentId,
496) {
497    let currencies_to_recalc: Vec<Currency> = balances_locked
498        .keys()
499        .filter(|(id, _)| *id == instrument_id)
500        .map(|(_, currency)| *currency)
501        .collect();
502
503    for currency in &currencies_to_recalc {
504        balances_locked.remove(&(instrument_id, *currency));
505    }
506
507    for currency in currencies_to_recalc {
508        recalculate_balance(balances, balances_locked, currency);
509    }
510}
511
512/// Recalculates the account balance for the specified currency based on per-instrument locks.
513///
514/// Sums all per-instrument locked amounts for the currency and updates the balance.
515/// If the total locked exceeds the total balance, clamps to total (free = 0).
516pub(crate) fn recalculate_balance(
517    balances: &mut IndexMap<Currency, AccountBalance>,
518    balances_locked: &AHashMap<(InstrumentId, Currency), Money>,
519    currency: Currency,
520) {
521    let current_balance = if let Some(balance) = balances.get(&currency) {
522        *balance
523    } else {
524        log::debug!("Cannot recalculate balance when no current balance for {currency}");
525        return;
526    };
527
528    let new_balance = match balance_from_locks(current_balance, balances_locked) {
529        Ok(balance) => balance,
530        Err(e) => {
531            log::error!(
532                "Cannot recalculate {currency} balance from reservations: {e}; using a non-spendable balance"
533            );
534            non_spendable_balance(current_balance)
535        }
536    };
537
538    balances.insert(currency, new_balance);
539}
540
541/// Derives an account balance from its total and all local reservations for its currency.
542///
543/// # Errors
544///
545/// Returns an error if a reservation is negative, uses a different fixed precision, or the
546/// derived locked or free balance exceeds [`Money`] bounds.
547pub(crate) fn balance_from_locks(
548    current_balance: AccountBalance,
549    balances_locked: &AHashMap<(InstrumentId, Currency), Money>,
550) -> CorrectnessResult<AccountBalance> {
551    let currency = current_balance.currency;
552    let mut locked_total = Money::zero(currency);
553
554    for locked in balances_locked
555        .values()
556        .filter(|locked| locked.currency == currency)
557    {
558        if locked.is_negative() {
559            return Err(CorrectnessError::PredicateViolation {
560                message: format!("locked balance was negative: {locked}"),
561            });
562        }
563
564        if locked.currency.precision != currency.precision {
565            return Err(CorrectnessError::PredicateViolation {
566                message: format!(
567                    "locked balance precision {} differed from balance precision {} for {currency}",
568                    locked.currency.precision, currency.precision
569                ),
570            });
571        }
572
573        let reservation = if current_balance.total.is_negative() {
574            *locked
575        } else {
576            (*locked).min(current_balance.total - locked_total)
577        };
578
579        locked_total = locked_total.checked_add(reservation).ok_or_else(|| {
580            CorrectnessError::PredicateViolation {
581                message: format!("derived locked balance exceeded Money bounds for {currency}"),
582            }
583        })?;
584    }
585
586    let free = current_balance
587        .total
588        .checked_sub(locked_total)
589        .ok_or_else(|| CorrectnessError::PredicateViolation {
590            message: format!(
591                "derived free balance exceeded Money bounds for total {} and locked {locked_total}",
592                current_balance.total
593            ),
594        })?;
595
596    AccountBalance::new_checked(current_balance.total, locked_total, free)
597}
598
599fn non_spendable_balance(current_balance: AccountBalance) -> AccountBalance {
600    let zero = Money::zero(current_balance.currency);
601
602    let (locked, free) = if current_balance.total.is_negative() {
603        (zero, current_balance.total)
604    } else {
605        (current_balance.total, zero)
606    };
607
608    AccountBalance {
609        currency: current_balance.currency,
610        total: current_balance.total,
611        locked,
612        free,
613    }
614}
615
616#[cfg(all(test, feature = "test-support"))]
617mod tests {
618    use rstest::rstest;
619    use rust_decimal::Decimal;
620    use rust_decimal_macros::dec;
621
622    use super::*;
623    use crate::{events::account::stubs::cash_account_state, types::money::MONEY_RAW_MAX};
624
625    #[rstest]
626    fn test_base_purge_account_events_retains_latest_when_all_purged() {
627        use crate::{
628            enums::AccountType,
629            events::account::stubs::cash_account_state,
630            identifiers::stubs::{account_id, uuid4},
631            types::{Currency, stubs::stub_account_balance},
632        };
633
634        let mut account = BaseAccount::new(cash_account_state(), true);
635
636        // Create events with different timestamps manually
637        let event1 = AccountState::new(
638            account_id(),
639            AccountType::Cash,
640            vec![stub_account_balance()],
641            vec![],
642            true,
643            uuid4(),
644            UnixNanos::from(100_000_000),
645            UnixNanos::from(100_000_000),
646            Some(Currency::USD()),
647        );
648        let event2 = AccountState::new(
649            account_id(),
650            AccountType::Cash,
651            vec![stub_account_balance()],
652            vec![],
653            true,
654            uuid4(),
655            UnixNanos::from(200_000_000),
656            UnixNanos::from(200_000_000),
657            Some(Currency::USD()),
658        );
659        let event3 = AccountState::new(
660            account_id(),
661            AccountType::Cash,
662            vec![stub_account_balance()],
663            vec![],
664            true,
665            uuid4(),
666            UnixNanos::from(300_000_000),
667            UnixNanos::from(300_000_000),
668            Some(Currency::USD()),
669        );
670
671        account.base_apply(event1);
672        account.base_apply(event2);
673        account.base_apply(event3.clone());
674
675        assert_eq!(account.events.len(), 4);
676
677        account.base_purge_account_events(UnixNanos::from(1_000_000_000), 0);
678
679        assert_eq!(account.events.len(), 1);
680        assert_eq!(account.events[0].ts_event, event3.ts_event);
681        assert_eq!(account.base_last_event().unwrap().ts_event, event3.ts_event);
682    }
683
684    #[rstest]
685    fn test_base_purge_account_events_retains_all_for_overflowing_lookback() {
686        let mut account = BaseAccount::new(cash_account_state(), true);
687        let mut event = cash_account_state();
688        event.ts_event = UnixNanos::from(1);
689        account.base_apply(event);
690
691        account.base_purge_account_events(UnixNanos::from(u64::MAX), u64::MAX);
692
693        assert_eq!(account.events.len(), 2);
694    }
695
696    #[rstest]
697    fn test_base_purge_account_events_drops_event_exactly_at_cutoff() {
698        let mut account = BaseAccount::new(cash_account_state(), true);
699        let mut at_cutoff = cash_account_state();
700        at_cutoff.ts_event = UnixNanos::from(200_000_000_000);
701        account.base_apply(at_cutoff);
702        let mut after_cutoff = cash_account_state();
703        after_cutoff.ts_event = UnixNanos::from(200_000_000_001);
704        account.base_apply(after_cutoff);
705
706        account.base_purge_account_events(UnixNanos::from(300_000_000_000), 100);
707
708        assert_eq!(account.events.len(), 1);
709        assert_eq!(account.events[0].ts_event, UnixNanos::from(200_000_000_001));
710    }
711
712    #[rstest]
713    fn test_base_purge_account_events_retains_future_event_without_overflow() {
714        let mut event = cash_account_state();
715        event.ts_event = UnixNanos::from(u64::MAX - 1);
716        let mut account = BaseAccount::new(event, true);
717
718        account.base_purge_account_events(UnixNanos::from(u64::MAX), 60);
719
720        assert_eq!(account.events.len(), 1);
721    }
722
723    #[rstest]
724    fn test_base_clone_shares_events() {
725        let account = BaseAccount::new(cash_account_state(), true);
726
727        let cloned = account.clone();
728
729        assert!(Arc::ptr_eq(&account.events, &cloned.events));
730    }
731
732    #[rstest]
733    fn test_base_apply_after_clone() {
734        let initial = cash_account_state();
735        let mut later = cash_account_state();
736        later.ts_event = UnixNanos::from(200_000_000_000);
737        let mut account = BaseAccount::new(initial.clone(), true);
738        let cloned = account.clone();
739
740        account.base_apply(later.clone());
741
742        assert_eq!(*account.events, vec![initial.clone(), later]);
743        assert_eq!(*cloned.events, vec![initial]);
744    }
745
746    #[rstest]
747    fn test_base_purge_account_events_after_clone() {
748        let initial = cash_account_state();
749        let mut later = cash_account_state();
750        later.ts_event = UnixNanos::from(200_000_000_000);
751        let mut account = BaseAccount::new(initial.clone(), true);
752        account.base_apply(later.clone());
753        let cloned = account.clone();
754
755        account.base_purge_account_events(UnixNanos::from(300_000_000_000), 150);
756
757        assert_eq!(*account.events, vec![later.clone()]);
758        assert_eq!(*cloned.events, vec![initial, later]);
759    }
760
761    #[rstest]
762    #[should_panic(
763        expected = r#"lhs_param: "event.account_id", rhs_param: "self.id", lhs: "OTHER-001", rhs: "SIM-001""#
764    )]
765    fn test_base_apply_panics_on_different_account_id() {
766        let mut account = BaseAccount::new(cash_account_state(), true);
767        let mut event = cash_account_state();
768        event.account_id = AccountId::from("OTHER-001");
769
770        account.base_apply(event);
771    }
772
773    fn usd_balances(total: &str) -> IndexMap<Currency, AccountBalance> {
774        let total = Money::from(total);
775        let mut balances = IndexMap::new();
776        balances.insert(
777            Currency::USD(),
778            AccountBalance::new(total, Money::zero(Currency::USD()), total),
779        );
780        balances
781    }
782
783    fn mismatched_usd() -> Currency {
784        Currency::new(
785            "USD",
786            Currency::USD().precision + 1,
787            840,
788            "United States dollar",
789            crate::enums::CurrencyType::Fiat,
790        )
791    }
792
793    // The observed case also exercises `balance_from_locks`; the unobserved case reaches the
794    // early return, so only the guard in `update_balance_locked` can reject it.
795    #[rstest]
796    #[case::observed_currency(true)]
797    #[case::unobserved_currency(false)]
798    fn test_update_balance_locked_rejects_negative_without_mutation(#[case] observed: bool) {
799        let mut balances = if observed {
800            usd_balances("1000 USD")
801        } else {
802            IndexMap::new()
803        };
804        let balances_before = balances.clone();
805        let mut balances_locked = AHashMap::new();
806        let instrument_id = InstrumentId::from("AUD/USD.SIM");
807
808        let error = update_balance_locked(
809            &mut balances,
810            &mut balances_locked,
811            instrument_id,
812            Money::from("-1 USD"),
813        )
814        .unwrap_err();
815
816        assert_eq!(error.to_string(), "locked balance was negative: -1.00 USD");
817        assert!(balances_locked.is_empty());
818        assert_eq!(balances, balances_before);
819    }
820
821    #[rstest]
822    fn test_update_balance_locked_restores_prior_reservation_on_failure() {
823        let usd = Currency::USD();
824        let mut balances = usd_balances("1000 USD");
825        let stale_key = (InstrumentId::from("EUR/USD.SIM"), mismatched_usd());
826        let stale = Money::from_decimal(Decimal::from(10), mismatched_usd()).unwrap();
827        let mut balances_locked = AHashMap::from([(stale_key, stale)]);
828        let instrument_id = InstrumentId::from("AUD/USD.SIM");
829
830        // A reservation that is valid on its own, but cannot derive a balance alongside the
831        // stale entry already recorded for this currency
832        let result = update_balance_locked(
833            &mut balances,
834            &mut balances_locked,
835            instrument_id,
836            Money::from("100 USD"),
837        );
838
839        assert!(result.is_err());
840        assert_eq!(balances_locked, AHashMap::from([(stale_key, stale)]));
841        assert_eq!(balances, usd_balances("1000 USD"));
842        assert_eq!(balances[&usd].free, Money::from("1000 USD"));
843    }
844
845    #[rstest]
846    fn test_balance_from_locks_clamps_reservations_to_total() {
847        let usd = Currency::USD();
848        let total = Money::from("100 USD");
849        let current = AccountBalance::new(total, Money::zero(usd), total);
850        let mut balances_locked = AHashMap::new();
851        balances_locked.insert(
852            (InstrumentId::from("AUD/USD.SIM"), usd),
853            Money::from("60 USD"),
854        );
855        balances_locked.insert(
856            (InstrumentId::from("EUR/USD.SIM"), usd),
857            Money::from("60 USD"),
858        );
859
860        let balance = balance_from_locks(current, &balances_locked).unwrap();
861
862        assert_eq!(balance.total, total);
863        assert_eq!(balance.locked, total);
864        assert_eq!(balance.free, Money::zero(usd));
865    }
866
867    #[rstest]
868    #[case::positive_total("1000 USD", "1000 USD", "0 USD")]
869    #[case::negative_total("-1000 USD", "0 USD", "-1000 USD")]
870    fn test_recalculate_balance_degrades_to_non_spendable_for_invalid_reservation(
871        #[case] total: &str,
872        #[case] expected_locked: &str,
873        #[case] expected_free: &str,
874    ) {
875        use crate::{enums::CurrencyType, types::Currency};
876
877        let usd = Currency::USD();
878        let total = Money::from(total);
879        let mut balances = IndexMap::new();
880        balances.insert(usd, AccountBalance::new(total, Money::zero(usd), total));
881        // A reservation at a differing precision cannot derive a valid balance
882        let mismatched_usd = Currency::new(
883            "USD",
884            usd.precision + 1,
885            840,
886            "United States dollar",
887            CurrencyType::Fiat,
888        );
889        let mut balances_locked = AHashMap::new();
890        balances_locked.insert(
891            (InstrumentId::from("AUD/USD.SIM"), mismatched_usd),
892            Money::from_decimal(Decimal::from(100), mismatched_usd).unwrap(),
893        );
894
895        recalculate_balance(&mut balances, &balances_locked, usd);
896
897        let balance = balances.get(&usd).expect("balance should be retained");
898        assert_eq!(balance.total, total);
899        assert_eq!(balance.locked, Money::from(expected_locked));
900        assert_eq!(balance.free, Money::from(expected_free));
901    }
902
903    #[rstest]
904    fn test_update_commissions_native_precision_preserved() {
905        use crate::{
906            events::account::stubs::cash_account_state,
907            types::{Currency, Money},
908        };
909
910        let mut account = BaseAccount::new(cash_account_state(), true);
911        let usd = Currency::USD();
912
913        account.update_commissions(Money::from_raw(1, usd));
914        account.update_commissions(Money::from_raw(2, usd));
915
916        assert_eq!(account.commission(&usd), Some(Money::from_raw(3, usd)));
917    }
918
919    #[rstest]
920    fn test_update_commissions_exact_usd_accumulates_with_legacy_money() {
921        let mut account = BaseAccount::new(cash_account_state(), true);
922        let usd = Currency::USD();
923        let exact = Money::from_decimal_exact(dec!(0.000001), usd).unwrap();
924        account.update_commissions(exact);
925        account.update_commissions(Money::from("0.01 USD"));
926
927        assert_eq!(
928            account.commission(&usd).unwrap().as_decimal(),
929            dec!(0.010001)
930        );
931    }
932
933    #[rstest]
934    fn test_commissions_returns_every_currency() {
935        let mut account = BaseAccount::new(cash_account_state(), true);
936        account.update_commissions(Money::from("2.50 USD"));
937        account.update_commissions(Money::from("1.25 AUD"));
938
939        let commissions = account.commissions();
940
941        assert_eq!(commissions.len(), 2);
942        assert_eq!(
943            commissions.get(&Currency::USD()),
944            Some(&Money::from("2.50 USD"))
945        );
946        assert_eq!(
947            commissions.get(&Currency::AUD()),
948            Some(&Money::from("1.25 AUD"))
949        );
950    }
951
952    #[rstest]
953    fn test_try_update_commissions_overflow_preserves_total() {
954        let mut account = BaseAccount::new(cash_account_state(), true);
955        let usd = Currency::USD();
956        let maximum = Money::from_raw(MONEY_RAW_MAX, usd);
957
958        account.try_update_commissions(maximum).unwrap();
959        let result = account.try_update_commissions(Money::from("0.01 USD"));
960
961        assert!(result.is_err());
962        assert_eq!(account.commission(&usd), Some(maximum));
963    }
964}