1use std::sync::Arc;
22
23use ahash::{AHashMap, AHashSet};
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, account::state::BALANCES_SNAPSHOT_COMPLETE_INFO_KEY},
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#[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 pub id: AccountId,
51 pub account_type: AccountType,
53 pub base_currency: Option<Currency>,
55 pub calculate_account_state: bool,
58 pub events: Arc<Vec<AccountState>>,
62 pub commissions: AHashMap<Currency, Money>,
64 pub balances: IndexMap<Currency, AccountBalance>,
66 pub balances_starting: IndexMap<Currency, Money>,
68}
69
70impl BaseAccount {
71 #[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 #[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(¤cy)
117 }
118
119 #[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 #[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 #[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 pub fn update_balances(&mut self, balances: &[AccountBalance]) {
185 for balance in balances {
186 self.balances.insert(balance.currency, *balance);
187 }
188 }
189
190 pub fn update_commissions(&mut self, commission: Money) {
197 self.try_update_commissions(commission)
198 .expect("commission total exceeded Money bounds");
199 }
200
201 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(¤cy)
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 #[must_use]
223 pub fn commission(&self, currency: &Currency) -> Option<Money> {
224 self.commissions.get(currency).copied()
225 }
226
227 #[must_use]
229 pub fn commissions(&self) -> AHashMap<Currency, Money> {
230 self.commissions.clone()
231 }
232
233 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 pub fn base_apply(&mut self, mut event: AccountState) {
260 check_equal(&event.account_id, &self.id, "event.account_id", "self.id").expect(FAILED);
261 let snapshot_is_current = self
262 .events
263 .last()
264 .is_none_or(|last| event.ts_event >= last.ts_event);
265 if snapshot_is_current
266 && event
267 .info
268 .as_ref()
269 .and_then(|info| info.get_bool(BALANCES_SNAPSHOT_COMPLETE_INFO_KEY))
270 == Some(true)
271 {
272 let reported: AHashSet<Currency> = event
273 .balances
274 .iter()
275 .map(|balance| balance.currency)
276 .collect();
277
278 let omitted = self
279 .balances
280 .keys()
281 .filter(|currency| !reported.contains(*currency))
282 .map(|currency| {
283 let zero = Money::zero(*currency);
284 AccountBalance::new(zero, zero, zero)
285 });
286
287 event.balances.extend(omitted);
288 }
289
290 self.update_balances(&event.balances);
291 Arc::make_mut(&mut self.events).push(event);
292 }
293
294 pub fn base_purge_account_events(&mut self, ts_now: UnixNanos, lookback_secs: u64) {
302 let Ok(lookback_ns) = DurationNanos::try_from_secs(lookback_secs) else {
303 log::warn!(
304 "Cannot purge account events: lookback_secs {lookback_secs} is not representable in `u64` nanoseconds"
305 );
306 return;
307 };
308 let purge_cutoff = ts_now.checked_sub(lookback_ns);
309
310 let mut retained_events = Vec::new();
311
312 for event in self.events.iter() {
313 if purge_cutoff.is_none_or(|cutoff| event.ts_event > cutoff) {
314 retained_events.push(event.clone());
315 }
316 }
317
318 if retained_events.is_empty() && !self.events.is_empty() {
320 retained_events.push(self.events.last().expect("events not empty").clone());
321 }
322
323 self.events = Arc::new(retained_events);
324 }
325
326 pub fn base_calculate_balance_locked(
334 &self,
335 instrument: &InstrumentAny,
336 side: OrderSide,
337 quantity: Quantity,
338 price: Price,
339 use_quote_for_inverse: Option<bool>,
340 ) -> anyhow::Result<Money> {
341 match side {
342 OrderSide::Buy => {
346 let notional =
347 calculate_notional(instrument, quantity, price, use_quote_for_inverse)?;
348 Ok(notional.max(Money::zero(notional.currency)))
349 }
350 OrderSide::Sell => match instrument.base_currency() {
352 Some(currency) => Ok(money_from_qty(quantity, currency)?),
353 None => Ok(Money::from_raw_checked(0, instrument.quote_currency())?),
354 },
355 }
356 }
357
358 #[allow(
373 clippy::needless_pass_by_value,
374 reason = "matches the owned Position input of Account::calculate_pnls"
375 )]
376 pub fn base_calculate_pnls(
377 &self,
378 instrument: &InstrumentAny,
379 fill: &OrderFilled,
380 position: Option<Position>,
381 ) -> anyhow::Result<Vec<Money>> {
382 if let Some(commission) = fill.commission {
383 amount(commission)?;
384 }
385
386 fill_position_pnl(instrument, fill, position.as_ref())?;
387
388 let mut pnls: IndexMap<Currency, Money> = IndexMap::new();
389 let base_currency = instrument.base_currency();
390
391 let fill_qty = fill.last_qty;
393 let notional = calculate_notional(instrument, fill_qty, fill.last_px, None)?;
394
395 if fill.order_side == OrderSide::Buy {
396 if let (Some(base_currency_value), None) = (base_currency, self.base_currency) {
397 pnls.insert(
398 base_currency_value,
399 money_from_qty(fill_qty, base_currency_value)?,
400 );
401 }
402 pnls.insert(notional.currency, -notional);
403 } else {
404 if let (Some(base_currency_value), None) = (base_currency, self.base_currency) {
405 pnls.insert(
406 base_currency_value,
407 -money_from_qty(fill_qty, base_currency_value)?,
408 );
409 }
410 pnls.insert(notional.currency, notional);
411 }
412 Ok(pnls.into_values().collect())
413 }
414
415 pub fn base_calculate_commission(
425 &self,
426 instrument: &InstrumentAny,
427 last_qty: Quantity,
428 last_px: Price,
429 liquidity_side: LiquiditySide,
430 fee_rates: MakerTakerFeeRates,
431 use_quote_for_inverse: Option<bool>,
432 ) -> anyhow::Result<Money> {
433 let rate = fee_rates.rate_for(liquidity_side)?;
434 calculate_maker_taker_commission(instrument, last_qty, last_px, rate, use_quote_for_inverse)
435 }
436}
437
438fn calculate_notional(
439 instrument: &InstrumentAny,
440 quantity: Quantity,
441 price: Price,
442 use_quote_for_inverse: Option<bool>,
443) -> anyhow::Result<Money> {
444 if instrument.is_inverse() && use_quote_for_inverse.unwrap_or(false) {
445 return Ok(money_from_qty(quantity, instrument.quote_currency())?);
446 }
447
448 let currency = if instrument.is_inverse() {
449 instrument
450 .base_currency()
451 .ok_or_else(|| anyhow::anyhow!("inverse instrument has no base currency"))?
452 } else {
453 instrument.cost_currency()
454 };
455
456 Ok(notional(
457 quantity,
458 price,
459 instrument.multiplier(),
460 instrument
461 .instrument_class()
462 .divides_notional_by_price(instrument.is_inverse()),
463 currency,
464 )?)
465}
466
467pub(crate) fn update_balance_locked(
479 balances: &mut IndexMap<Currency, AccountBalance>,
480 balances_locked: &mut AHashMap<(InstrumentId, Currency), Money>,
481 instrument_id: InstrumentId,
482 locked: Money,
483) -> anyhow::Result<()> {
484 anyhow::ensure!(
485 !locked.is_negative(),
486 "locked balance was negative: {locked}"
487 );
488
489 let currency = locked.currency;
490 let key = (instrument_id, currency);
491
492 let Some(current_balance) = balances.get(¤cy).copied() else {
493 balances_locked.insert(key, locked);
494 return Ok(());
495 };
496
497 anyhow::ensure!(
498 current_balance.currency.precision == currency.precision,
499 "Cannot update {currency} reservation: precision {} differed from balance precision {}",
500 currency.precision,
501 current_balance.currency.precision
502 );
503
504 let previous = balances_locked.insert(key, locked);
505
506 match balance_from_locks(current_balance, balances_locked) {
507 Ok(balance) => {
508 balances.insert(currency, balance);
509 Ok(())
510 }
511 Err(e) => {
512 match previous {
514 Some(previous) => balances_locked.insert(key, previous),
515 None => balances_locked.remove(&key),
516 };
517 Err(e.into())
518 }
519 }
520}
521
522pub(crate) fn clear_balance_locked(
524 balances: &mut IndexMap<Currency, AccountBalance>,
525 balances_locked: &mut AHashMap<(InstrumentId, Currency), Money>,
526 instrument_id: InstrumentId,
527) {
528 let currencies_to_recalc: Vec<Currency> = balances_locked
529 .keys()
530 .filter(|(id, _)| *id == instrument_id)
531 .map(|(_, currency)| *currency)
532 .collect();
533
534 for currency in ¤cies_to_recalc {
535 balances_locked.remove(&(instrument_id, *currency));
536 }
537
538 for currency in currencies_to_recalc {
539 recalculate_balance(balances, balances_locked, currency);
540 }
541}
542
543pub(crate) fn recalculate_balance(
548 balances: &mut IndexMap<Currency, AccountBalance>,
549 balances_locked: &AHashMap<(InstrumentId, Currency), Money>,
550 currency: Currency,
551) {
552 let current_balance = if let Some(balance) = balances.get(¤cy) {
553 *balance
554 } else {
555 log::debug!("Cannot recalculate balance when no current balance for {currency}");
556 return;
557 };
558
559 let new_balance = match balance_from_locks(current_balance, balances_locked) {
560 Ok(balance) => balance,
561 Err(e) => {
562 log::error!(
563 "Cannot recalculate {currency} balance from reservations: {e}; using a non-spendable balance"
564 );
565 non_spendable_balance(current_balance)
566 }
567 };
568
569 balances.insert(currency, new_balance);
570}
571
572pub(crate) fn balance_from_locks(
579 current_balance: AccountBalance,
580 balances_locked: &AHashMap<(InstrumentId, Currency), Money>,
581) -> CorrectnessResult<AccountBalance> {
582 let currency = current_balance.currency;
583 let mut locked_total = Money::zero(currency);
584
585 for locked in balances_locked
586 .values()
587 .filter(|locked| locked.currency == currency)
588 {
589 if locked.is_negative() {
590 return Err(CorrectnessError::PredicateViolation {
591 message: format!("locked balance was negative: {locked}"),
592 });
593 }
594
595 if locked.currency.precision != currency.precision {
596 return Err(CorrectnessError::PredicateViolation {
597 message: format!(
598 "locked balance precision {} differed from balance precision {} for {currency}",
599 locked.currency.precision, currency.precision
600 ),
601 });
602 }
603
604 let reservation = if current_balance.total.is_negative() {
605 *locked
606 } else {
607 (*locked).min(current_balance.total - locked_total)
608 };
609
610 locked_total = locked_total.checked_add(reservation).ok_or_else(|| {
611 CorrectnessError::PredicateViolation {
612 message: format!("derived locked balance exceeded Money bounds for {currency}"),
613 }
614 })?;
615 }
616
617 let free = current_balance
618 .total
619 .checked_sub(locked_total)
620 .ok_or_else(|| CorrectnessError::PredicateViolation {
621 message: format!(
622 "derived free balance exceeded Money bounds for total {} and locked {locked_total}",
623 current_balance.total
624 ),
625 })?;
626
627 AccountBalance::new_checked(current_balance.total, locked_total, free)
628}
629
630fn non_spendable_balance(current_balance: AccountBalance) -> AccountBalance {
631 let zero = Money::zero(current_balance.currency);
632
633 let (locked, free) = if current_balance.total.is_negative() {
634 (zero, current_balance.total)
635 } else {
636 (current_balance.total, zero)
637 };
638
639 AccountBalance {
640 currency: current_balance.currency,
641 total: current_balance.total,
642 locked,
643 free,
644 }
645}
646
647#[cfg(all(test, feature = "test-support"))]
648mod tests {
649 use nautilus_core::{Params, UUID4};
650 use rstest::rstest;
651 use rust_decimal::Decimal;
652 use rust_decimal_macros::dec;
653
654 use super::*;
655 use crate::{
656 events::account::{state::BALANCES_SNAPSHOT_COMPLETE_INFO_KEY, stubs::cash_account_state},
657 types::money::MONEY_RAW_MAX,
658 };
659
660 #[rstest]
661 fn test_base_purge_account_events_retains_latest_when_all_purged() {
662 use crate::{
663 enums::AccountType,
664 events::account::stubs::cash_account_state,
665 identifiers::stubs::{account_id, uuid4},
666 types::{Currency, stubs::stub_account_balance},
667 };
668
669 let mut account = BaseAccount::new(cash_account_state(), true);
670
671 let event1 = AccountState::new(
673 account_id(),
674 AccountType::Cash,
675 vec![stub_account_balance()],
676 vec![],
677 true,
678 uuid4(),
679 UnixNanos::from(100_000_000),
680 UnixNanos::from(100_000_000),
681 Some(Currency::USD()),
682 );
683 let event2 = AccountState::new(
684 account_id(),
685 AccountType::Cash,
686 vec![stub_account_balance()],
687 vec![],
688 true,
689 uuid4(),
690 UnixNanos::from(200_000_000),
691 UnixNanos::from(200_000_000),
692 Some(Currency::USD()),
693 );
694 let event3 = AccountState::new(
695 account_id(),
696 AccountType::Cash,
697 vec![stub_account_balance()],
698 vec![],
699 true,
700 uuid4(),
701 UnixNanos::from(300_000_000),
702 UnixNanos::from(300_000_000),
703 Some(Currency::USD()),
704 );
705
706 account.base_apply(event1);
707 account.base_apply(event2);
708 account.base_apply(event3.clone());
709
710 assert_eq!(account.events.len(), 4);
711
712 account.base_purge_account_events(UnixNanos::from(1_000_000_000), 0);
713
714 assert_eq!(account.events.len(), 1);
715 assert_eq!(account.events[0].ts_event, event3.ts_event);
716 assert_eq!(account.base_last_event().unwrap().ts_event, event3.ts_event);
717 }
718
719 #[rstest]
720 fn test_base_purge_account_events_retains_all_for_overflowing_lookback() {
721 let mut account = BaseAccount::new(cash_account_state(), true);
722 let mut event = cash_account_state();
723 event.ts_event = UnixNanos::from(1);
724 account.base_apply(event);
725
726 account.base_purge_account_events(UnixNanos::from(u64::MAX), u64::MAX);
727
728 assert_eq!(account.events.len(), 2);
729 }
730
731 #[rstest]
732 fn test_base_purge_account_events_drops_event_exactly_at_cutoff() {
733 let mut account = BaseAccount::new(cash_account_state(), true);
734 let mut at_cutoff = cash_account_state();
735 at_cutoff.ts_event = UnixNanos::from(200_000_000_000);
736 account.base_apply(at_cutoff);
737 let mut after_cutoff = cash_account_state();
738 after_cutoff.ts_event = UnixNanos::from(200_000_000_001);
739 account.base_apply(after_cutoff);
740
741 account.base_purge_account_events(UnixNanos::from(300_000_000_000), 100);
742
743 assert_eq!(account.events.len(), 1);
744 assert_eq!(account.events[0].ts_event, UnixNanos::from(200_000_000_001));
745 }
746
747 #[rstest]
748 fn test_base_purge_account_events_retains_future_event_without_overflow() {
749 let mut event = cash_account_state();
750 event.ts_event = UnixNanos::from(u64::MAX - 1);
751 let mut account = BaseAccount::new(event, true);
752
753 account.base_purge_account_events(UnixNanos::from(u64::MAX), 60);
754
755 assert_eq!(account.events.len(), 1);
756 }
757
758 #[rstest]
759 fn test_base_clone_shares_events() {
760 let account = BaseAccount::new(cash_account_state(), true);
761
762 let cloned = account.clone();
763
764 assert!(Arc::ptr_eq(&account.events, &cloned.events));
765 }
766
767 #[rstest]
768 fn test_base_apply_after_clone() {
769 let initial = cash_account_state();
770 let mut later = cash_account_state();
771 later.ts_event = UnixNanos::from(200_000_000_000);
772 let mut account = BaseAccount::new(initial.clone(), true);
773 let cloned = account.clone();
774
775 account.base_apply(later.clone());
776
777 assert_eq!(*account.events, vec![initial.clone(), later]);
778 assert_eq!(*cloned.events, vec![initial]);
779 }
780
781 #[rstest]
782 #[case::complete_snapshot(true, 2, "0 BTC", 2)]
783 #[case::partial_snapshot(false, 2, "1 BTC", 1)]
784 #[case::stale_complete_snapshot(true, 0, "1 BTC", 1)]
785 fn test_base_apply_zeroes_omitted_balances_only_for_complete_snapshots(
786 #[case] complete: bool,
787 #[case] event_ts: u64,
788 #[case] expected_btc: &str,
789 #[case] expected_event_balances: usize,
790 ) {
791 let balance = |total: Money| AccountBalance::new(total, Money::zero(total.currency), total);
792 let account_id = AccountId::from("SIM-001");
793
794 let initial = AccountState::new(
795 account_id,
796 AccountType::Cash,
797 vec![
798 balance(Money::from("1 BTC")),
799 balance(Money::from("100 USD")),
800 ],
801 vec![],
802 true,
803 UUID4::new(),
804 UnixNanos::from(1),
805 UnixNanos::from(1),
806 Some(Currency::USD()),
807 );
808
809 let mut account = BaseAccount::new(initial, true);
810
811 let info = complete.then(|| {
812 Params::new(IndexMap::from([(
813 BALANCES_SNAPSHOT_COMPLETE_INFO_KEY.to_string(),
814 serde_json::Value::Bool(true),
815 )]))
816 });
817
818 let later = AccountState::new(
819 account_id,
820 AccountType::Cash,
821 vec![balance(Money::from("90 USD"))],
822 vec![],
823 true,
824 UUID4::new(),
825 UnixNanos::from(event_ts),
826 UnixNanos::from(event_ts),
827 Some(Currency::USD()),
828 )
829 .with_info(info);
830
831 account.base_apply(later);
832
833 let expected_btc = Money::from(expected_btc);
834 let btc = account.base_balance(Some(Currency::BTC())).unwrap();
835 let usd = account.base_balance(Some(Currency::USD())).unwrap();
836 assert_eq!(btc.total, expected_btc);
837 assert_eq!(btc.locked, Money::zero(Currency::BTC()));
838 assert_eq!(btc.free, expected_btc);
839 assert_eq!(usd.total, Money::from("90 USD"));
840 assert_eq!(usd.locked, Money::zero(Currency::USD()));
841 assert_eq!(usd.free, Money::from("90 USD"));
842 assert_eq!(
843 account.events.last().unwrap().balances.len(),
844 expected_event_balances,
845 );
846 }
847
848 #[rstest]
849 fn test_base_purge_account_events_after_clone() {
850 let initial = cash_account_state();
851 let mut later = cash_account_state();
852 later.ts_event = UnixNanos::from(200_000_000_000);
853 let mut account = BaseAccount::new(initial.clone(), true);
854 account.base_apply(later.clone());
855 let cloned = account.clone();
856
857 account.base_purge_account_events(UnixNanos::from(300_000_000_000), 150);
858
859 assert_eq!(*account.events, vec![later.clone()]);
860 assert_eq!(*cloned.events, vec![initial, later]);
861 }
862
863 #[rstest]
864 #[should_panic(
865 expected = r#"lhs_param: "event.account_id", rhs_param: "self.id", lhs: "OTHER-001", rhs: "SIM-001""#
866 )]
867 fn test_base_apply_panics_on_different_account_id() {
868 let mut account = BaseAccount::new(cash_account_state(), true);
869 let mut event = cash_account_state();
870 event.account_id = AccountId::from("OTHER-001");
871
872 account.base_apply(event);
873 }
874
875 fn usd_balances(total: &str) -> IndexMap<Currency, AccountBalance> {
876 let total = Money::from(total);
877 let mut balances = IndexMap::new();
878 balances.insert(
879 Currency::USD(),
880 AccountBalance::new(total, Money::zero(Currency::USD()), total),
881 );
882 balances
883 }
884
885 fn mismatched_usd() -> Currency {
886 Currency::new(
887 "USD",
888 Currency::USD().precision + 1,
889 840,
890 "United States dollar",
891 crate::enums::CurrencyType::Fiat,
892 )
893 }
894
895 #[rstest]
898 #[case::observed_currency(true)]
899 #[case::unobserved_currency(false)]
900 fn test_update_balance_locked_rejects_negative_without_mutation(#[case] observed: bool) {
901 let mut balances = if observed {
902 usd_balances("1000 USD")
903 } else {
904 IndexMap::new()
905 };
906 let balances_before = balances.clone();
907 let mut balances_locked = AHashMap::new();
908 let instrument_id = InstrumentId::from("AUD/USD.SIM");
909
910 let error = update_balance_locked(
911 &mut balances,
912 &mut balances_locked,
913 instrument_id,
914 Money::from("-1 USD"),
915 )
916 .unwrap_err();
917
918 assert_eq!(error.to_string(), "locked balance was negative: -1.00 USD");
919 assert!(balances_locked.is_empty());
920 assert_eq!(balances, balances_before);
921 }
922
923 #[rstest]
924 fn test_update_balance_locked_restores_prior_reservation_on_failure() {
925 let usd = Currency::USD();
926 let mut balances = usd_balances("1000 USD");
927 let stale_key = (InstrumentId::from("EUR/USD.SIM"), mismatched_usd());
928 let stale = Money::from_decimal(Decimal::from(10), mismatched_usd()).unwrap();
929 let mut balances_locked = AHashMap::from([(stale_key, stale)]);
930 let instrument_id = InstrumentId::from("AUD/USD.SIM");
931
932 let result = update_balance_locked(
935 &mut balances,
936 &mut balances_locked,
937 instrument_id,
938 Money::from("100 USD"),
939 );
940
941 assert!(result.is_err());
942 assert_eq!(balances_locked, AHashMap::from([(stale_key, stale)]));
943 assert_eq!(balances, usd_balances("1000 USD"));
944 assert_eq!(balances[&usd].free, Money::from("1000 USD"));
945 }
946
947 #[rstest]
948 fn test_balance_from_locks_clamps_reservations_to_total() {
949 let usd = Currency::USD();
950 let total = Money::from("100 USD");
951 let current = AccountBalance::new(total, Money::zero(usd), total);
952 let mut balances_locked = AHashMap::new();
953 balances_locked.insert(
954 (InstrumentId::from("AUD/USD.SIM"), usd),
955 Money::from("60 USD"),
956 );
957 balances_locked.insert(
958 (InstrumentId::from("EUR/USD.SIM"), usd),
959 Money::from("60 USD"),
960 );
961
962 let balance = balance_from_locks(current, &balances_locked).unwrap();
963
964 assert_eq!(balance.total, total);
965 assert_eq!(balance.locked, total);
966 assert_eq!(balance.free, Money::zero(usd));
967 }
968
969 #[rstest]
970 #[case::positive_total("1000 USD", "1000 USD", "0 USD")]
971 #[case::negative_total("-1000 USD", "0 USD", "-1000 USD")]
972 fn test_recalculate_balance_degrades_to_non_spendable_for_invalid_reservation(
973 #[case] total: &str,
974 #[case] expected_locked: &str,
975 #[case] expected_free: &str,
976 ) {
977 use crate::{enums::CurrencyType, types::Currency};
978
979 let usd = Currency::USD();
980 let total = Money::from(total);
981 let mut balances = IndexMap::new();
982 balances.insert(usd, AccountBalance::new(total, Money::zero(usd), total));
983 let mismatched_usd = Currency::new(
985 "USD",
986 usd.precision + 1,
987 840,
988 "United States dollar",
989 CurrencyType::Fiat,
990 );
991 let mut balances_locked = AHashMap::new();
992 balances_locked.insert(
993 (InstrumentId::from("AUD/USD.SIM"), mismatched_usd),
994 Money::from_decimal(Decimal::from(100), mismatched_usd).unwrap(),
995 );
996
997 recalculate_balance(&mut balances, &balances_locked, usd);
998
999 let balance = balances.get(&usd).expect("balance should be retained");
1000 assert_eq!(balance.total, total);
1001 assert_eq!(balance.locked, Money::from(expected_locked));
1002 assert_eq!(balance.free, Money::from(expected_free));
1003 }
1004
1005 #[rstest]
1006 fn test_update_commissions_native_precision_preserved() {
1007 use crate::{
1008 events::account::stubs::cash_account_state,
1009 types::{Currency, Money},
1010 };
1011
1012 let mut account = BaseAccount::new(cash_account_state(), true);
1013 let usd = Currency::USD();
1014
1015 account.update_commissions(Money::from_raw(1, usd));
1016 account.update_commissions(Money::from_raw(2, usd));
1017
1018 assert_eq!(account.commission(&usd), Some(Money::from_raw(3, usd)));
1019 }
1020
1021 #[rstest]
1022 fn test_update_commissions_exact_usd_accumulates_with_legacy_money() {
1023 let mut account = BaseAccount::new(cash_account_state(), true);
1024 let usd = Currency::USD();
1025 let exact = Money::from_decimal_exact(dec!(0.000001), usd).unwrap();
1026 account.update_commissions(exact);
1027 account.update_commissions(Money::from("0.01 USD"));
1028
1029 assert_eq!(
1030 account.commission(&usd).unwrap().as_decimal(),
1031 dec!(0.010001)
1032 );
1033 }
1034
1035 #[rstest]
1036 fn test_commissions_returns_every_currency() {
1037 let mut account = BaseAccount::new(cash_account_state(), true);
1038 account.update_commissions(Money::from("2.50 USD"));
1039 account.update_commissions(Money::from("1.25 AUD"));
1040
1041 let commissions = account.commissions();
1042
1043 assert_eq!(commissions.len(), 2);
1044 assert_eq!(
1045 commissions.get(&Currency::USD()),
1046 Some(&Money::from("2.50 USD"))
1047 );
1048 assert_eq!(
1049 commissions.get(&Currency::AUD()),
1050 Some(&Money::from("1.25 AUD"))
1051 );
1052 }
1053
1054 #[rstest]
1055 fn test_try_update_commissions_overflow_preserves_total() {
1056 let mut account = BaseAccount::new(cash_account_state(), true);
1057 let usd = Currency::USD();
1058 let maximum = Money::from_raw(MONEY_RAW_MAX, usd);
1059
1060 account.try_update_commissions(maximum).unwrap();
1061 let result = account.try_update_commissions(Money::from("0.01 USD"));
1062
1063 assert!(result.is_err());
1064 assert_eq!(account.commission(&usd), Some(maximum));
1065 }
1066}