Skip to main content

nautilus_model/accounts/
cash.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//! A cash account that cannot hold leveraged positions.
17//!
18//! # Balance locking
19//!
20//! The account tracks locked balances per `(InstrumentId, Currency)` to support
21//! instruments that lock different currencies depending on order side.
22//! The portfolio computes locks for open orders as follows:
23//! - BUY orders lock quote currency (cost of purchase), unless marked `reduce_only`.
24//! - SELL orders lock base currency (assets being sold), unless marked `reduce_only`.
25//! - Negative-price SELL orders also lock the cash disposal cost, including `reduce_only` orders.
26//!
27//! Instruments that model no base currency (binary options, equities, and the other types whose
28//! `base_currency()` is `None`) have no asset to reserve, so a SELL locks only a negative-price
29//! disposal cost, when present. Inventory availability for those instruments is not
30//! tracked or checked locally, including across concurrent SELLs, and is left to the venue,
31//! whose rejections arrive through the normal order lifecycle.
32//!
33//! Callers must clear all existing locks via [`CashAccount::clear_balance_locked`]
34//! before applying new locks. This prevents stale currency entries when order
35//! compositions change.
36//!
37//! # Graceful degradation
38//!
39//! When total locked exceeds total balance (e.g., due to venue/client state latency),
40//! the account clamps locked to total rather than raising an error. This yields zero
41//! free balance, preventing new orders while avoiding crashes in live trading.
42
43use std::{
44    fmt::Display,
45    ops::{Deref, DerefMut},
46};
47
48use ahash::AHashMap;
49use serde::{Deserialize, Serialize};
50
51use crate::{
52    accounts::{
53        Account,
54        base::{self, BaseAccount},
55    },
56    enums::{AccountType, OrderSide},
57    events::{AccountState, OrderFilled},
58    identifiers::InstrumentId,
59    instruments::{Instrument, InstrumentAny},
60    position::Position,
61    types::{AccountBalance, Currency, Money, Price, Quantity},
62};
63
64/// Represents a cash account that cannot hold leveraged positions.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66#[cfg_attr(
67    feature = "python",
68    pyo3::pyclass(module = "nautilus_trader.model", from_py_object)
69)]
70#[cfg_attr(
71    feature = "python",
72    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
73)]
74pub struct CashAccount {
75    /// The account state shared by every account type.
76    pub base: BaseAccount,
77    /// Indicates if a balance may go negative.
78    pub allow_borrowing: bool,
79    /// Per-(instrument, currency) locked balances (transient, not persisted).
80    #[serde(skip, default)]
81    pub balances_locked: AHashMap<(InstrumentId, Currency), Money>,
82}
83
84impl CashAccount {
85    /// Creates a new [`CashAccount`] instance.
86    #[must_use]
87    pub fn new(event: AccountState, calculate_account_state: bool, allow_borrowing: bool) -> Self {
88        Self {
89            base: BaseAccount::new(event, calculate_account_state),
90            allow_borrowing,
91            balances_locked: AHashMap::new(),
92        }
93    }
94
95    #[must_use]
96    pub(crate) fn clone_without_events(&self) -> Self {
97        Self {
98            base: self.base.clone_without_events(),
99            allow_borrowing: self.allow_borrowing,
100            balances_locked: self.balances_locked.clone(),
101        }
102    }
103
104    /// Updates the locked balance for the given instrument and currency.
105    ///
106    /// # Errors
107    ///
108    /// Returns an error if `locked` is negative, its precision differs from the balance
109    /// precision, or the reservations cannot produce a valid balance. The balance and
110    /// reservations are left unchanged when an error is returned.
111    pub fn update_balance_locked(
112        &mut self,
113        instrument_id: InstrumentId,
114        locked: Money,
115    ) -> anyhow::Result<()> {
116        base::update_balance_locked(
117            &mut self.base.balances,
118            &mut self.balances_locked,
119            instrument_id,
120            locked,
121        )
122    }
123
124    /// Clears all locked balances for the given instrument ID.
125    pub fn clear_balance_locked(&mut self, instrument_id: InstrumentId) {
126        base::clear_balance_locked(
127            &mut self.base.balances,
128            &mut self.balances_locked,
129            instrument_id,
130        );
131    }
132
133    /// Updates the account balances, enforcing borrowing constraints.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if `allow_borrowing` is false and any balance has a negative total.
138    pub fn update_balances(&mut self, balances: &[AccountBalance]) -> anyhow::Result<()> {
139        if !self.allow_borrowing {
140            for balance in balances {
141                if balance.total.is_negative() {
142                    anyhow::bail!(
143                        "Cash account balance would become negative: {} {} (borrowing not allowed for {})",
144                        balance.total.as_decimal(),
145                        balance.currency.code,
146                        self.id
147                    );
148                }
149            }
150        }
151        self.base.update_balances(balances);
152        Ok(())
153    }
154
155    #[must_use]
156    pub fn is_cash_account(&self) -> bool {
157        self.account_type == AccountType::Cash
158    }
159
160    #[must_use]
161    pub fn is_margin_account(&self) -> bool {
162        self.account_type == AccountType::Margin
163    }
164
165    #[must_use]
166    pub const fn is_unleveraged(&self) -> bool {
167        true
168    }
169
170    /// Recalculates the account balance for the specified currency based on per-instrument locks.
171    ///
172    /// Sums all per-instrument locked amounts for the currency and updates the balance.
173    /// If the total locked exceeds the total balance, clamps to total (free = 0).
174    pub fn recalculate_balance(&mut self, currency: Currency) {
175        base::recalculate_balance(&mut self.base.balances, &self.balances_locked, currency);
176    }
177}
178
179impl Account for CashAccount {
180    impl_account_base_members!();
181
182    fn is_cash_account(&self) -> bool {
183        self.account_type == AccountType::Cash
184    }
185
186    fn is_margin_account(&self) -> bool {
187        self.account_type == AccountType::Margin
188    }
189
190    fn apply(&mut self, event: AccountState) -> anyhow::Result<()> {
191        self.check_event_account_id(&event)?;
192
193        if !self.allow_borrowing {
194            for balance in &event.balances {
195                if balance.total.is_negative() {
196                    anyhow::bail!(
197                        "Cannot apply account state: balance would be negative {} {} \
198                        (borrowing not allowed for {})",
199                        balance.total.as_decimal(),
200                        balance.currency.code,
201                        self.id
202                    );
203                }
204            }
205        }
206
207        // Only clear locks when the venue reports a fresh balance snapshot
208        if event.is_reported && !event.balances.is_empty() {
209            self.balances_locked.clear();
210        }
211
212        self.base_apply(event);
213        Ok(())
214    }
215
216    fn calculate_balance_locked(
217        &self,
218        instrument: &InstrumentAny,
219        side: OrderSide,
220        quantity: Quantity,
221        price: Price,
222        use_quote_for_inverse: Option<bool>,
223    ) -> anyhow::Result<Money> {
224        if side == OrderSide::Sell && price.is_negative() && instrument.base_currency().is_none() {
225            return self.base_calculate_balance_locked(
226                instrument,
227                OrderSide::Buy,
228                quantity,
229                -price,
230                use_quote_for_inverse,
231            );
232        }
233
234        self.base_calculate_balance_locked(instrument, side, quantity, price, use_quote_for_inverse)
235    }
236
237    fn calculate_pnls(
238        &self,
239        instrument: &InstrumentAny,
240        fill: &OrderFilled,
241        position: Option<Position>,
242    ) -> anyhow::Result<Vec<Money>> {
243        self.base_calculate_pnls(instrument, fill, position)
244    }
245}
246
247impl Deref for CashAccount {
248    type Target = BaseAccount;
249
250    fn deref(&self) -> &Self::Target {
251        &self.base
252    }
253}
254
255impl DerefMut for CashAccount {
256    fn deref_mut(&mut self) -> &mut Self::Target {
257        &mut self.base
258    }
259}
260
261impl PartialEq for CashAccount {
262    fn eq(&self, other: &Self) -> bool {
263        self.id == other.id
264    }
265}
266
267impl Eq for CashAccount {}
268
269impl Display for CashAccount {
270    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271        write!(
272            f,
273            "CashAccount(id={}, type={}, base={})",
274            self.id,
275            self.account_type,
276            self.base_currency.map_or_else(
277                || "None".to_string(),
278                |base_currency| format!("{}", base_currency.code)
279            ),
280        )
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use ahash::AHashSet;
287    use indexmap::IndexMap;
288    use rstest::rstest;
289    use rust_decimal::Decimal;
290    use rust_decimal_macros::dec;
291
292    use crate::{
293        accounts::{Account, CashAccount, stubs::*},
294        enums::{AccountType, CurrencyType, LiquiditySide, OrderSide, OrderType},
295        events::{AccountState, account::stubs::*, order::spec::OrderFilledSpec},
296        fees::MakerTakerFeeRates,
297        identifiers::{AccountId, InstrumentId, position_id::PositionId, stubs::uuid4},
298        instruments::{
299            BinaryOption, Commodity, CryptoFuture, CryptoPerpetual, CurrencyPair, Equity,
300            Instrument, InstrumentAny, stubs::*,
301        },
302        orders::{builder::OrderTestBuilder, stubs::TestOrderEventStubs},
303        position::Position,
304        types::{AccountBalance, Currency, Money, Price, Quantity},
305    };
306
307    #[rstest]
308    fn test_account_type_predicates(cash_account: CashAccount) {
309        assert!(cash_account.is_cash_account());
310        assert!(!cash_account.is_margin_account());
311        assert!(cash_account.is_unleveraged());
312        assert!(Account::is_cash_account(&cash_account));
313        assert!(!Account::is_margin_account(&cash_account));
314    }
315
316    #[rstest]
317    fn test_equality_compares_account_ids(cash_account_state: AccountState) {
318        let account = CashAccount::new(cash_account_state.clone(), true, false);
319        let same = CashAccount::new(cash_account_state.clone(), true, false);
320        let mut other_state = cash_account_state;
321        other_state.account_id = AccountId::from("OTHER-001");
322        let other = CashAccount::new(other_state, true, false);
323
324        assert_eq!(account, same);
325        assert_ne!(account, other);
326    }
327
328    #[rstest]
329    fn test_display(cash_account: CashAccount) {
330        assert_eq!(
331            format!("{cash_account}"),
332            "CashAccount(id=SIM-001, type=CASH, base=USD)"
333        );
334    }
335
336    #[rstest]
337    fn test_calculate_balance_locked_buy_at_negative_price_reserves_nothing(
338        mut cash_account: CashAccount,
339        commodity_gold: Commodity,
340    ) {
341        let instrument = InstrumentAny::Commodity(commodity_gold);
342        assert!(
343            instrument.allows_negative_price(),
344            "fixture must admit a negative price for this case to arise"
345        );
346
347        let locked = cash_account
348            .calculate_balance_locked(
349                &instrument,
350                OrderSide::Buy,
351                Quantity::from("1"),
352                Price::from("-10.00"),
353                None,
354            )
355            .unwrap();
356
357        assert_eq!(locked, Money::from("0.00 USD"));
358
359        // Storing it must not trip the non-negative invariant in `update_balance_locked`.
360        cash_account
361            .update_balance_locked(instrument.id(), locked)
362            .unwrap();
363    }
364
365    #[rstest]
366    #[case::whole("3", "-7.00", dec!(21))]
367    #[case::fractional("0.3", "-0.02", dec!(0.006))]
368    #[case::subcurrency("0.3", "-0.00000001", dec!(0.000000003))]
369    fn test_calculate_balance_locked_negative_price_sell_reserves_disposal_cost(
370        #[case] quantity: &str,
371        #[case] price: &str,
372        #[case] expected: Decimal,
373        cash_account: CashAccount,
374        mut commodity_gold: Commodity,
375    ) {
376        commodity_gold.price_precision = 8;
377        commodity_gold.price_increment = Price::from("0.00000001");
378        commodity_gold.size_precision = 1;
379        commodity_gold.size_increment = Quantity::from("0.1");
380        let instrument = InstrumentAny::Commodity(commodity_gold);
381
382        let locked = cash_account
383            .calculate_balance_locked(
384                &instrument,
385                OrderSide::Sell,
386                Quantity::from(quantity),
387                Price::from(price),
388                None,
389            )
390            .unwrap();
391
392        assert_eq!(
393            locked,
394            Money::from_decimal_native(expected, Currency::USD()).unwrap()
395        );
396    }
397
398    #[rstest]
399    fn test_calculate_balance_locked_buy_at_positive_price_reserves_the_notional(
400        cash_account: CashAccount,
401        commodity_gold: Commodity,
402    ) {
403        let instrument = InstrumentAny::Commodity(commodity_gold);
404
405        let locked = cash_account
406            .calculate_balance_locked(
407                &instrument,
408                OrderSide::Buy,
409                Quantity::from("1"),
410                Price::from("10.00"),
411                None,
412            )
413            .unwrap();
414
415        assert_eq!(locked, Money::from("10.00 USD"));
416    }
417
418    #[rstest]
419    fn test_calculated_account_state_returns_field_value(cash_account_state: AccountState) {
420        assert!(
421            CashAccount::new(cash_account_state.clone(), true, false).calculated_account_state()
422        );
423        assert!(!CashAccount::new(cash_account_state, false, false).calculated_account_state());
424    }
425
426    #[rstest]
427    fn test_instantiate_single_asset_cash_account(
428        cash_account: CashAccount,
429        cash_account_state: AccountState,
430    ) {
431        assert_eq!(cash_account.id, AccountId::from("SIM-001"));
432        assert_eq!(cash_account.account_type, AccountType::Cash);
433        assert_eq!(cash_account.base_currency, Some(Currency::from("USD")));
434        assert_eq!(cash_account.last_event(), Some(cash_account_state.clone()));
435        assert_eq!(cash_account.events(), vec![cash_account_state]);
436        assert_eq!(cash_account.event_count(), 1);
437        assert_eq!(
438            cash_account.balance_total(None),
439            Some(Money::from("1525000 USD"))
440        );
441        assert_eq!(
442            cash_account.balance_free(None),
443            Some(Money::from("1500000 USD"))
444        );
445        assert_eq!(
446            cash_account.balance_locked(None),
447            Some(Money::from("25000 USD"))
448        );
449        let mut balances_total_expected = IndexMap::new();
450        balances_total_expected.insert(Currency::from("USD"), Money::from("1525000 USD"));
451        assert_eq!(cash_account.balances_total(), balances_total_expected);
452        let mut balances_free_expected = IndexMap::new();
453        balances_free_expected.insert(Currency::from("USD"), Money::from("1500000 USD"));
454        assert_eq!(cash_account.balances_free(), balances_free_expected);
455        let mut balances_locked_expected = IndexMap::new();
456        balances_locked_expected.insert(Currency::from("USD"), Money::from("25000 USD"));
457        assert_eq!(cash_account.balances_locked(), balances_locked_expected);
458    }
459
460    #[rstest]
461    fn test_instantiate_multi_asset_cash_account(
462        cash_account_multi: CashAccount,
463        cash_account_state_multi: AccountState,
464    ) {
465        assert_eq!(cash_account_multi.id, AccountId::from("SIM-001"));
466        assert_eq!(cash_account_multi.account_type, AccountType::Cash);
467        assert_eq!(
468            cash_account_multi.last_event(),
469            Some(cash_account_state_multi.clone())
470        );
471        assert_eq!(cash_account_state_multi.base_currency, None);
472        assert_eq!(cash_account_multi.events(), vec![cash_account_state_multi]);
473        assert_eq!(cash_account_multi.event_count(), 1);
474        assert_eq!(
475            cash_account_multi.balance_total(Some(Currency::BTC())),
476            Some(Money::from("10 BTC"))
477        );
478        assert_eq!(
479            cash_account_multi.balance_total(Some(Currency::ETH())),
480            Some(Money::from("20 ETH"))
481        );
482        assert_eq!(
483            cash_account_multi.balance_free(Some(Currency::BTC())),
484            Some(Money::from("10 BTC"))
485        );
486        assert_eq!(
487            cash_account_multi.balance_free(Some(Currency::ETH())),
488            Some(Money::from("20 ETH"))
489        );
490        assert_eq!(
491            cash_account_multi.balance_locked(Some(Currency::BTC())),
492            Some(Money::from("0 BTC"))
493        );
494        assert_eq!(
495            cash_account_multi.balance_locked(Some(Currency::ETH())),
496            Some(Money::from("0 ETH"))
497        );
498        let mut balances_total_expected = IndexMap::new();
499        balances_total_expected.insert(Currency::from("BTC"), Money::from("10 BTC"));
500        balances_total_expected.insert(Currency::from("ETH"), Money::from("20 ETH"));
501        assert_eq!(cash_account_multi.balances_total(), balances_total_expected);
502        let mut balances_free_expected = IndexMap::new();
503        balances_free_expected.insert(Currency::from("BTC"), Money::from("10 BTC"));
504        balances_free_expected.insert(Currency::from("ETH"), Money::from("20 ETH"));
505        assert_eq!(cash_account_multi.balances_free(), balances_free_expected);
506        let mut balances_locked_expected = IndexMap::new();
507        balances_locked_expected.insert(Currency::from("BTC"), Money::from("0 BTC"));
508        balances_locked_expected.insert(Currency::from("ETH"), Money::from("0 ETH"));
509        assert_eq!(
510            cash_account_multi.balances_locked(),
511            balances_locked_expected
512        );
513    }
514
515    #[rstest]
516    fn test_cash_account_balances_preserve_insertion_order(cash_account_multi: CashAccount) {
517        // Locks in IndexMap iteration order for BaseAccount.balances:
518        // currencies appear in the same order as the AccountState.balances
519        // Vec they were initialized from. Drives the deterministic ordering
520        // of regenerated AccountState events in portfolio::manager.
521        let keys: Vec<Currency> = cash_account_multi.balances().keys().copied().collect();
522        assert_eq!(keys, vec![Currency::from("BTC"), Currency::from("ETH")]);
523
524        let totals: Vec<(Currency, Money)> =
525            cash_account_multi.balances_total().into_iter().collect();
526        assert_eq!(
527            totals,
528            vec![
529                (Currency::from("BTC"), Money::from("10 BTC")),
530                (Currency::from("ETH"), Money::from("20 ETH")),
531            ]
532        );
533    }
534
535    #[rstest]
536    fn test_apply_given_new_state_event_updates_correctly(
537        mut cash_account_multi: CashAccount,
538        cash_account_state_multi: AccountState,
539        cash_account_state_multi_changed_btc: AccountState,
540    ) {
541        // Apply second account event
542        cash_account_multi
543            .apply(cash_account_state_multi_changed_btc.clone())
544            .unwrap();
545        assert_eq!(
546            cash_account_multi.last_event(),
547            Some(cash_account_state_multi_changed_btc.clone())
548        );
549        assert_eq!(
550            *cash_account_multi.events,
551            vec![
552                cash_account_state_multi,
553                cash_account_state_multi_changed_btc
554            ]
555        );
556        assert_eq!(cash_account_multi.event_count(), 2);
557        assert_eq!(
558            cash_account_multi.balance_total(Some(Currency::BTC())),
559            Some(Money::from("9 BTC"))
560        );
561        assert_eq!(
562            cash_account_multi.balance_free(Some(Currency::BTC())),
563            Some(Money::from("8.5 BTC"))
564        );
565        assert_eq!(
566            cash_account_multi.balance_locked(Some(Currency::BTC())),
567            Some(Money::from("0.5 BTC"))
568        );
569        assert_eq!(
570            cash_account_multi.balance_total(Some(Currency::ETH())),
571            Some(Money::from("20 ETH"))
572        );
573        assert_eq!(
574            cash_account_multi.balance_free(Some(Currency::ETH())),
575            Some(Money::from("20 ETH"))
576        );
577        assert_eq!(
578            cash_account_multi.balance_locked(Some(Currency::ETH())),
579            Some(Money::from("0 ETH"))
580        );
581    }
582
583    #[rstest]
584    fn test_calculate_balance_locked_buy(
585        cash_account_million_usd: CashAccount,
586        audusd_sim: CurrencyPair,
587    ) {
588        let balance_locked = cash_account_million_usd
589            .calculate_balance_locked(
590                &audusd_sim.into_any(),
591                OrderSide::Buy,
592                Quantity::from("1000000"),
593                Price::from("0.8"),
594                None,
595            )
596            .unwrap();
597        assert_eq!(balance_locked, Money::from("800000 USD"));
598    }
599
600    #[rstest]
601    #[case(OrderSide::Buy, "0.01", "0.001234 USD")]
602    #[case(OrderSide::Sell, "0.0001", "0.0001 AUD")]
603    fn test_balance_locked_preserves_native_precision(
604        mut cash_account_million_usd: CashAccount,
605        audusd_sim: CurrencyPair,
606        #[case] side: OrderSide,
607        #[case] qty: &str,
608        #[case] expected: &str,
609    ) {
610        let instrument = audusd_sim.into_any();
611        let locked = cash_account_million_usd
612            .calculate_balance_locked(
613                &instrument,
614                side,
615                Quantity::from(qty),
616                Price::from("0.1234"),
617                None,
618            )
619            .unwrap();
620        cash_account_million_usd
621            .update_balance_locked(instrument.id(), locked)
622            .unwrap();
623        let expected = Money::from_str_exact(expected).unwrap();
624
625        assert_eq!(locked, expected);
626        assert_eq!(
627            cash_account_million_usd.balances_locked[&(instrument.id(), expected.currency)],
628            expected,
629        );
630
631        if side == OrderSide::Buy {
632            assert_eq!(
633                cash_account_million_usd
634                    .balance(Some(Currency::USD()))
635                    .copied(),
636                Some(AccountBalance::new(
637                    Money::from("1000000 USD"),
638                    expected,
639                    Money::from_str_exact("999999.998766 USD").unwrap(),
640                )),
641            );
642        }
643    }
644
645    #[rstest]
646    #[case::profit("0 USD", "1000000.000001 USD")]
647    #[case::fee("0.000001 USD", "1000000 USD")]
648    fn test_fill_cash_flows_preserve_micro_profit_and_fee(
649        mut cash_account_million_usd: CashAccount,
650        audusd_sim: CurrencyPair,
651        #[case] fee: &str,
652        #[case] expected: &str,
653    ) {
654        let instrument = audusd_sim.into_any();
655        let fee = Money::from_str_exact(fee).unwrap();
656        let mut cash_flows = Vec::new();
657
658        for (side, price, commission) in [
659            (OrderSide::Buy, "0.1234", fee),
660            (OrderSide::Sell, "0.1235", Money::zero(Currency::USD())),
661        ] {
662            let fill = OrderFilledSpec::builder()
663                .instrument_id(instrument.id())
664                .order_side(side)
665                .last_qty(Quantity::from("0.01"))
666                .last_px(Price::from(price))
667                .commission(commission)
668                .build();
669            let pnls = cash_account_million_usd
670                .calculate_pnls(&instrument, &fill, None)
671                .unwrap();
672            let current = cash_account_million_usd.balance_total(None).unwrap();
673            let total = current
674                .checked_add(pnls[0])
675                .unwrap()
676                .checked_sub(commission)
677                .unwrap();
678            let balance = AccountBalance::new(total, Money::zero(Currency::USD()), total);
679            cash_account_million_usd
680                .update_balances(&[balance])
681                .unwrap();
682            cash_flows.extend(pnls);
683        }
684
685        let expected = Money::from_str_exact(expected).unwrap();
686        assert_eq!(
687            cash_flows,
688            vec![
689                Money::from_str_exact("-0.001234 USD").unwrap(),
690                Money::from_str_exact("0.001235 USD").unwrap(),
691            ],
692        );
693        assert_eq!(
694            cash_account_million_usd.balance(None).copied(),
695            Some(AccountBalance::new(
696                expected,
697                Money::zero(Currency::USD()),
698                expected
699            )),
700        );
701    }
702
703    #[rstest]
704    fn test_calculate_balance_locked_buy_returns_error_for_unrepresentable_notional(
705        cash_account_million_usd: CashAccount,
706        audusd_sim: CurrencyPair,
707    ) {
708        let result = cash_account_million_usd.calculate_balance_locked(
709            &audusd_sim.into_any(),
710            OrderSide::Buy,
711            Quantity::from("100000000"),
712            Price::from("100000000"),
713            None,
714        );
715
716        assert!(result.is_err());
717    }
718
719    #[rstest]
720    fn test_calculate_balance_locked_buy_quanto_uses_settlement_currency(
721        cash_account_million_usd: CashAccount,
722        ethbtc_quanto: CryptoFuture,
723    ) {
724        let balance_locked = cash_account_million_usd
725            .calculate_balance_locked(
726                &ethbtc_quanto.into_any(),
727                OrderSide::Buy,
728                Quantity::from("5"),
729                Price::from("0.036"),
730                None,
731            )
732            .unwrap();
733        assert_eq!(balance_locked, Money::from("0.18 USDT"));
734    }
735
736    #[rstest]
737    #[case(false, Money::from("0.002 BTC"))]
738    #[case(true, Money::from("100 USD"))]
739    fn test_calculate_balance_locked_buy_inverse_respects_quote_flag(
740        #[case] use_quote_for_inverse: bool,
741        #[case] expected: Money,
742        cash_account_million_usd: CashAccount,
743        btcusd_inverse_perp: CryptoPerpetual,
744    ) {
745        let balance_locked = cash_account_million_usd
746            .calculate_balance_locked(
747                &btcusd_inverse_perp.into_any(),
748                OrderSide::Buy,
749                Quantity::from("100"),
750                Price::from("50000"),
751                Some(use_quote_for_inverse),
752            )
753            .unwrap();
754        assert_eq!(balance_locked, expected);
755    }
756
757    #[rstest]
758    fn test_calculate_balance_locked_sell(
759        cash_account_million_usd: CashAccount,
760        audusd_sim: CurrencyPair,
761    ) {
762        let balance_locked = cash_account_million_usd
763            .calculate_balance_locked(
764                &audusd_sim.into_any(),
765                OrderSide::Sell,
766                Quantity::from("1000000"),
767                Price::from("0.8"),
768                None,
769            )
770            .unwrap();
771        assert_eq!(balance_locked, Money::from("1000000 AUD"));
772    }
773
774    #[rstest]
775    fn test_calculate_balance_locked_sell_no_base_currency(
776        cash_account_million_usd: CashAccount,
777        equity_aapl: Equity,
778    ) {
779        let balance_locked = cash_account_million_usd
780            .calculate_balance_locked(
781                &equity_aapl.into_any(),
782                OrderSide::Sell,
783                Quantity::from("100"),
784                Price::from("1500.0"),
785                None,
786            )
787            .unwrap();
788        assert_eq!(balance_locked, Money::zero(Currency::USD()));
789    }
790
791    #[rstest]
792    fn test_calculate_balance_locked_sell_binary_option_reserves_nothing(
793        cash_account_million_usd: CashAccount,
794        binary_option: BinaryOption,
795    ) {
796        // BinaryOption::base_currency() is None: there is no modeled asset to reserve, so a
797        // SELL must not reserve quote collateral.
798        let balance_locked = cash_account_million_usd
799            .calculate_balance_locked(
800                &InstrumentAny::BinaryOption(binary_option),
801                OrderSide::Sell,
802                Quantity::from("5.00"),
803                Price::from("0.500"),
804                None,
805            )
806            .unwrap();
807        assert_eq!(balance_locked, Money::zero(Currency::USDC()));
808    }
809
810    #[rstest]
811    fn test_calculate_balance_locked_buy_no_base_currency_still_reserves_notional(
812        cash_account_million_usd: CashAccount,
813        binary_option: BinaryOption,
814    ) {
815        let balance_locked = cash_account_million_usd
816            .calculate_balance_locked(
817                &binary_option.into_any(),
818                OrderSide::Buy,
819                Quantity::from("5"),
820                Price::from("0.500"),
821                None,
822            )
823            .unwrap();
824        assert_eq!(balance_locked, Money::new(2.5, Currency::USDC()));
825    }
826
827    #[rstest]
828    fn test_calculate_pnls_for_single_currency_cash_account(
829        cash_account_million_usd: CashAccount,
830        audusd_sim: CurrencyPair,
831    ) {
832        let audusd_sim = InstrumentAny::CurrencyPair(audusd_sim);
833        let order = OrderTestBuilder::new(OrderType::Market)
834            .instrument_id(audusd_sim.id())
835            .side(OrderSide::Buy)
836            .quantity(Quantity::from("1000000"))
837            .build();
838        let fill = TestOrderEventStubs::filled(
839            &order,
840            &audusd_sim,
841            None,
842            Some(PositionId::new("P-123456")),
843            Some(Price::from("0.8")),
844            None,
845            None,
846            None,
847            None,
848            Some(AccountId::from("SIM-001")),
849        );
850        let position = Position::new(&audusd_sim, fill.clone().into());
851        let fill_owned: crate::events::OrderFilled = fill.into();
852        let pnls = cash_account_million_usd
853            .calculate_pnls(&audusd_sim, &fill_owned, Some(position))
854            .unwrap();
855        assert_eq!(pnls, vec![Money::from("-800000 USD")]);
856    }
857
858    #[cfg(feature = "defi")]
859    #[rstest]
860    fn test_fill_cash_flows_reject_unrepresentable_foreign_commission(
861        cash_account: CashAccount,
862        audusd_sim: CurrencyPair,
863    ) {
864        let instrument = audusd_sim.into_any();
865        let fill = OrderFilledSpec::builder()
866            .instrument_id(instrument.id())
867            .last_qty(Quantity::from("0.01"))
868            .last_px(Price::from("0.1234"))
869            .commission(Money::from_raw(
870                100_000_000_000_000_000_000_000_000_001,
871                Currency::EUR(),
872            ))
873            .build();
874
875        let error = cash_account
876            .calculate_pnls(&instrument, &fill, None)
877            .unwrap_err();
878
879        assert_eq!(
880            error.to_string(),
881            "position input exceeds exact Decimal representation"
882        );
883    }
884
885    #[rstest]
886    fn test_fill_cash_flows_preserve_sub_cent_base_and_quote(
887        cash_account_multi: CashAccount,
888        audusd_sim: CurrencyPair,
889    ) {
890        let instrument = audusd_sim.into_any();
891        let fill = OrderFilledSpec::builder()
892            .instrument_id(instrument.id())
893            .order_side(OrderSide::Buy)
894            .last_qty(Quantity::from("0.0001"))
895            .last_px(Price::from("0.1234"))
896            .commission(Money::zero(Currency::USD()))
897            .build();
898
899        let pnls = cash_account_multi
900            .calculate_pnls(&instrument, &fill, None)
901            .unwrap();
902
903        assert_eq!(
904            pnls,
905            vec![
906                Money::from_str_exact("0.0001 AUD").unwrap(),
907                Money::from_str_exact("-0.00001234 USD").unwrap(),
908            ],
909        );
910    }
911
912    #[rstest]
913    fn test_calculate_pnls_for_multi_currency_cash_account_btcusdt(
914        cash_account_multi: CashAccount,
915        currency_pair_btcusdt: CurrencyPair,
916    ) {
917        let btcusdt = InstrumentAny::CurrencyPair(currency_pair_btcusdt.clone());
918        let order1 = OrderTestBuilder::new(OrderType::Market)
919            .instrument_id(currency_pair_btcusdt.id)
920            .side(OrderSide::Sell)
921            .quantity(Quantity::from("0.5"))
922            .build();
923        let fill1 = TestOrderEventStubs::filled(
924            &order1,
925            &btcusdt,
926            None,
927            Some(PositionId::new("P-123456")),
928            Some(Price::from("45500.00")),
929            None,
930            None,
931            None,
932            None,
933            Some(AccountId::from("SIM-001")),
934        );
935        let position = Position::new(&btcusdt, fill1.clone().into());
936        let fill1_owned: crate::events::OrderFilled = fill1.into();
937        let result1 = cash_account_multi
938            .calculate_pnls(&btcusdt, &fill1_owned, Some(position.clone()))
939            .unwrap();
940        let order2 = OrderTestBuilder::new(OrderType::Market)
941            .instrument_id(currency_pair_btcusdt.id)
942            .side(OrderSide::Buy)
943            .quantity(Quantity::from("0.5"))
944            .build();
945        let fill2 = TestOrderEventStubs::filled(
946            &order2,
947            &btcusdt,
948            None,
949            Some(PositionId::new("P-123456")),
950            Some(Price::from("45500.00")),
951            None,
952            None,
953            None,
954            None,
955            Some(AccountId::from("SIM-001")),
956        );
957        let fill2_owned: crate::events::OrderFilled = fill2.into();
958        let result2 = cash_account_multi
959            .calculate_pnls(
960                &currency_pair_btcusdt.into_any(),
961                &fill2_owned,
962                Some(position),
963            )
964            .unwrap();
965        // use hash set to ignore order of results
966        let result1_set: AHashSet<Money> = result1.into_iter().collect();
967        let result1_expected: AHashSet<Money> =
968            vec![Money::from("22750 USDT"), Money::from("-0.5 BTC")]
969                .into_iter()
970                .collect();
971        let result2_set: AHashSet<Money> = result2.into_iter().collect();
972        let result2_expected: AHashSet<Money> =
973            vec![Money::from("-22750 USDT"), Money::from("0.5 BTC")]
974                .into_iter()
975                .collect();
976        assert_eq!(result1_set, result1_expected);
977        assert_eq!(result2_set, result2_expected);
978    }
979
980    #[rstest]
981    #[case(false, Money::from("-0.00218331 BTC"))]
982    #[case(true, Money::from("-25.0 USD"))]
983    fn test_calculate_commission_for_inverse_maker_crypto(
984        #[case] use_quote_for_inverse: bool,
985        #[case] expected: Money,
986        cash_account_million_usd: CashAccount,
987        btcusd_bybit: CryptoPerpetual,
988    ) {
989        let fee_rates = MakerTakerFeeRates::new(dec!(-0.00025), dec!(0.00075));
990        let result = cash_account_million_usd
991            .calculate_commission(
992                &btcusd_bybit.into_any(),
993                Quantity::from("100000"),
994                Price::from("11450.50"),
995                LiquiditySide::Maker,
996                fee_rates,
997                Some(use_quote_for_inverse),
998            )
999            .unwrap();
1000        assert_eq!(result, expected);
1001    }
1002
1003    #[rstest]
1004    fn test_calculate_commission_for_taker_fx(
1005        cash_account_million_usd: CashAccount,
1006        audusd_sim: CurrencyPair,
1007    ) {
1008        let fee_rates = MakerTakerFeeRates::new(dec!(0.00002), dec!(0.00002));
1009        let result = cash_account_million_usd
1010            .calculate_commission(
1011                &audusd_sim.into_any(),
1012                Quantity::from("1500000"),
1013                Price::from("0.8005"),
1014                LiquiditySide::Taker,
1015                fee_rates,
1016                None,
1017            )
1018            .unwrap();
1019        assert_eq!(result, Money::from("24.02 USD"));
1020    }
1021
1022    #[rstest]
1023    fn test_calculate_commission_crypto_taker(
1024        cash_account_million_usd: CashAccount,
1025        btcusd_bybit: CryptoPerpetual,
1026    ) {
1027        let fee_rates = MakerTakerFeeRates::new(dec!(-0.00025), dec!(0.00075));
1028        let result = cash_account_million_usd
1029            .calculate_commission(
1030                &btcusd_bybit.into_any(),
1031                Quantity::from("100000"),
1032                Price::from("11450.50"),
1033                LiquiditySide::Taker,
1034                fee_rates,
1035                None,
1036            )
1037            .unwrap();
1038        assert_eq!(result, Money::from("0.00654993 BTC"));
1039    }
1040
1041    #[rstest]
1042    fn test_calculate_commission_fx_taker(cash_account_million_usd: CashAccount) {
1043        let instrument = usdjpy_idealpro();
1044        let fee_rates = MakerTakerFeeRates::new(dec!(0.00002), dec!(0.00002));
1045        let result = cash_account_million_usd
1046            .calculate_commission(
1047                &instrument.into_any(),
1048                Quantity::from("2200000"),
1049                Price::from("120.310"),
1050                LiquiditySide::Taker,
1051                fee_rates,
1052                None,
1053            )
1054            .unwrap();
1055        assert_eq!(result, Money::from("5294 JPY"));
1056    }
1057
1058    #[rstest]
1059    fn test_update_balance_locked_per_instrument_currency(
1060        mut cash_account_multi: CashAccount,
1061        currency_pair_btcusdt: CurrencyPair,
1062    ) {
1063        assert!(cash_account_multi.balances_locked.is_empty());
1064
1065        let instrument_id = currency_pair_btcusdt.id;
1066
1067        let usdt_lock = Money::from("1000 USDT");
1068        cash_account_multi
1069            .update_balance_locked(instrument_id, usdt_lock)
1070            .unwrap();
1071
1072        let btc_lock = Money::from("0.5 BTC");
1073        cash_account_multi
1074            .update_balance_locked(instrument_id, btc_lock)
1075            .unwrap();
1076        assert_eq!(cash_account_multi.balances_locked.len(), 2);
1077        assert_eq!(
1078            cash_account_multi
1079                .balances_locked
1080                .get(&(instrument_id, Currency::USDT())),
1081            Some(&usdt_lock)
1082        );
1083        assert_eq!(
1084            cash_account_multi
1085                .balances_locked
1086                .get(&(instrument_id, Currency::BTC())),
1087            Some(&btc_lock)
1088        );
1089    }
1090
1091    #[rstest]
1092    fn test_clear_balance_locked_removes_all_currencies_for_instrument(
1093        mut cash_account_multi: CashAccount,
1094        currency_pair_btcusdt: CurrencyPair,
1095    ) {
1096        let instrument_id = currency_pair_btcusdt.id;
1097
1098        cash_account_multi
1099            .update_balance_locked(instrument_id, Money::from("1000 USDT"))
1100            .unwrap();
1101        cash_account_multi
1102            .update_balance_locked(instrument_id, Money::from("0.5 BTC"))
1103            .unwrap();
1104        assert_eq!(cash_account_multi.balances_locked.len(), 2);
1105
1106        cash_account_multi.clear_balance_locked(instrument_id);
1107
1108        assert!(cash_account_multi.balances_locked.is_empty());
1109    }
1110
1111    #[rstest]
1112    fn test_clear_balance_locked_only_removes_target_instrument(
1113        mut cash_account_multi: CashAccount,
1114        currency_pair_btcusdt: CurrencyPair,
1115    ) {
1116        let btcusdt_id = currency_pair_btcusdt.id;
1117        let ethusdt_id = InstrumentId::from("ETHUSDT.BINANCE");
1118
1119        cash_account_multi
1120            .update_balance_locked(btcusdt_id, Money::from("1000 USDT"))
1121            .unwrap();
1122        cash_account_multi
1123            .update_balance_locked(ethusdt_id, Money::from("500 USDT"))
1124            .unwrap();
1125        assert_eq!(cash_account_multi.balances_locked.len(), 2);
1126
1127        cash_account_multi.clear_balance_locked(btcusdt_id);
1128        assert_eq!(cash_account_multi.balances_locked.len(), 1);
1129        assert_eq!(
1130            cash_account_multi
1131                .balances_locked
1132                .get(&(ethusdt_id, Currency::USDT())),
1133            Some(&Money::from("500 USDT"))
1134        );
1135    }
1136
1137    #[rstest]
1138    fn test_recalculate_balance_clamps_when_locked_exceeds_total(
1139        mut cash_account_multi: CashAccount,
1140        currency_pair_btcusdt: CurrencyPair,
1141    ) {
1142        let initial_balance = *cash_account_multi.balance(Some(Currency::BTC())).unwrap();
1143        assert_eq!(initial_balance.total, Money::from("10 BTC"));
1144
1145        // Lock more than total to simulate latency/state mismatch
1146        let instrument_id = currency_pair_btcusdt.id;
1147        cash_account_multi
1148            .update_balance_locked(instrument_id, Money::from("15 BTC"))
1149            .unwrap();
1150
1151        let balance = cash_account_multi.balance(Some(Currency::BTC())).unwrap();
1152        assert_eq!(balance.total, Money::from("10 BTC"));
1153        assert_eq!(balance.locked, Money::from("10 BTC"));
1154        assert_eq!(balance.free, Money::from("0 BTC"));
1155    }
1156
1157    #[rstest]
1158    fn test_recalculate_balance_sums_multiple_instrument_locks(
1159        mut cash_account_multi: CashAccount,
1160    ) {
1161        let btcusdt_id = InstrumentId::from("BTCUSDT.BINANCE");
1162        let btceth_id = InstrumentId::from("BTCETH.BINANCE");
1163
1164        cash_account_multi
1165            .update_balance_locked(btcusdt_id, Money::from("3 BTC"))
1166            .unwrap();
1167        cash_account_multi
1168            .update_balance_locked(btceth_id, Money::from("2 BTC"))
1169            .unwrap();
1170
1171        let balance = cash_account_multi.balance(Some(Currency::BTC())).unwrap();
1172        assert_eq!(balance.total, Money::from("10 BTC"));
1173        assert_eq!(balance.locked, Money::from("5 BTC"));
1174        assert_eq!(balance.free, Money::from("5 BTC"));
1175    }
1176
1177    #[rstest]
1178    fn test_update_balance_locked_precision_mismatch_preserves_state(
1179        mut cash_account_multi: CashAccount,
1180    ) {
1181        let instrument_id = InstrumentId::from("BTCUSDT.BINANCE");
1182        let btc = Currency::BTC();
1183        cash_account_multi
1184            .update_balance_locked(instrument_id, Money::from("3 BTC"))
1185            .unwrap();
1186        let balance_before = *cash_account_multi.balance(Some(btc)).unwrap();
1187        let locks_before = cash_account_multi.balances_locked.clone();
1188        let mismatched_btc =
1189            Currency::new("BTC", btc.precision - 1, 0, "Bitcoin", CurrencyType::Crypto);
1190        let locked = Money::from_decimal(Decimal::from(2), mismatched_btc).unwrap();
1191
1192        let error = cash_account_multi
1193            .update_balance_locked(instrument_id, locked)
1194            .unwrap_err();
1195
1196        assert_eq!(
1197            error.to_string(),
1198            "Cannot update BTC reservation: precision 7 differed from balance precision 8"
1199        );
1200        assert_eq!(cash_account_multi.balance(Some(btc)), Some(&balance_before));
1201        assert_eq!(cash_account_multi.balances_locked, locks_before);
1202    }
1203
1204    #[rstest]
1205    fn test_recalculate_balance_no_clamp_when_total_negative_borrowing() {
1206        // Create account with negative balance (simulating borrowing)
1207        let negative_balance_event = AccountState::new(
1208            AccountId::from("SIM-001"),
1209            AccountType::Cash,
1210            vec![AccountBalance::new(
1211                Money::from("-1000 USD"), // Negative total (borrowed)
1212                Money::from("0 USD"),
1213                Money::from("-1000 USD"),
1214            )],
1215            vec![],
1216            true,
1217            uuid4(),
1218            0.into(),
1219            0.into(),
1220            Some(Currency::USD()),
1221        );
1222
1223        let mut account = CashAccount::new(negative_balance_event, false, true);
1224        let instrument_id = InstrumentId::from("EURUSD.SIM");
1225
1226        account
1227            .update_balance_locked(instrument_id, Money::from("500 USD"))
1228            .unwrap();
1229
1230        // Locked not clamped to negative total, free = total - locked
1231        let balance = account.balance(Some(Currency::USD())).unwrap();
1232        assert_eq!(balance.total, Money::from("-1000 USD"));
1233        assert_eq!(balance.locked, Money::from("500 USD"));
1234        assert_eq!(balance.free, Money::from("-1500 USD"));
1235    }
1236
1237    #[rstest]
1238    fn test_update_balances_rejects_negative_total_when_borrowing_disabled(
1239        mut cash_account: CashAccount,
1240    ) {
1241        let usd = Currency::USD();
1242        let balances_before = cash_account.balances();
1243
1244        let result = cash_account.update_balances(&[AccountBalance::new(
1245            Money::from("-500 USD"),
1246            Money::zero(usd),
1247            Money::from("-500 USD"),
1248        )]);
1249
1250        assert_eq!(
1251            result.unwrap_err().to_string(),
1252            "Cash account balance would become negative: -500.00 USD (borrowing not allowed for SIM-001)"
1253        );
1254        assert_eq!(cash_account.balances(), balances_before);
1255    }
1256
1257    #[rstest]
1258    fn test_update_balances_accepts_negative_total_when_borrowing_enabled(
1259        mut cash_account_borrowing: CashAccount,
1260    ) {
1261        let usd = Currency::USD();
1262        let balance = AccountBalance::new(
1263            Money::from("-500 USD"),
1264            Money::zero(usd),
1265            Money::from("-500 USD"),
1266        );
1267
1268        cash_account_borrowing.update_balances(&[balance]).unwrap();
1269
1270        assert_eq!(cash_account_borrowing.balance(Some(usd)), Some(&balance));
1271    }
1272
1273    #[rstest]
1274    fn test_apply_returns_error_when_negative_balance_and_borrowing_disabled() {
1275        let initial_event = AccountState::new(
1276            AccountId::from("SIM-001"),
1277            AccountType::Cash,
1278            vec![AccountBalance::new(
1279                Money::from("1000 USD"),
1280                Money::from("0 USD"),
1281                Money::from("1000 USD"),
1282            )],
1283            vec![],
1284            true,
1285            uuid4(),
1286            0.into(),
1287            0.into(),
1288            Some(Currency::USD()),
1289        );
1290
1291        let mut account = CashAccount::new(initial_event, false, false);
1292
1293        let negative_balance_event = AccountState::new(
1294            AccountId::from("SIM-001"),
1295            AccountType::Cash,
1296            vec![AccountBalance::new(
1297                Money::from("-500 USD"),
1298                Money::from("0 USD"),
1299                Money::from("-500 USD"),
1300            )],
1301            vec![],
1302            true,
1303            uuid4(),
1304            1.into(),
1305            1.into(),
1306            Some(Currency::USD()),
1307        );
1308
1309        let result = account.apply(negative_balance_event);
1310
1311        assert!(result.is_err());
1312        let err_msg = result.unwrap_err().to_string();
1313        assert!(err_msg.contains("negative"));
1314        assert!(err_msg.contains("borrowing not allowed"));
1315    }
1316
1317    #[rstest]
1318    fn test_apply_succeeds_when_negative_balance_and_borrowing_enabled() {
1319        let initial_event = AccountState::new(
1320            AccountId::from("SIM-001"),
1321            AccountType::Cash,
1322            vec![AccountBalance::new(
1323                Money::from("1000 USD"),
1324                Money::from("0 USD"),
1325                Money::from("1000 USD"),
1326            )],
1327            vec![],
1328            true,
1329            uuid4(),
1330            0.into(),
1331            0.into(),
1332            Some(Currency::USD()),
1333        );
1334
1335        let mut account = CashAccount::new(initial_event, false, true);
1336
1337        let negative_balance_event = AccountState::new(
1338            AccountId::from("SIM-001"),
1339            AccountType::Cash,
1340            vec![AccountBalance::new(
1341                Money::from("-500 USD"),
1342                Money::from("0 USD"),
1343                Money::from("-500 USD"),
1344            )],
1345            vec![],
1346            true,
1347            uuid4(),
1348            1.into(),
1349            1.into(),
1350            Some(Currency::USD()),
1351        );
1352
1353        let result = account.apply(negative_balance_event);
1354
1355        assert!(result.is_ok());
1356        assert_eq!(
1357            account.balance_total(Some(Currency::USD())),
1358            Some(Money::from("-500 USD"))
1359        );
1360    }
1361
1362    #[rstest]
1363    fn test_apply_clears_per_instrument_locks() {
1364        let initial_event = AccountState::new(
1365            AccountId::from("SIM-001"),
1366            AccountType::Cash,
1367            vec![AccountBalance::new(
1368                Money::from("10000 USD"),
1369                Money::from("0 USD"),
1370                Money::from("10000 USD"),
1371            )],
1372            vec![],
1373            true,
1374            uuid4(),
1375            0.into(),
1376            0.into(),
1377            Some(Currency::USD()),
1378        );
1379
1380        let mut account = CashAccount::new(initial_event, false, false);
1381        let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1382
1383        // Set per-instrument lock
1384        account
1385            .update_balance_locked(instrument_id, Money::from("5000 USD"))
1386            .unwrap();
1387        assert_eq!(account.balances_locked.len(), 1);
1388
1389        // Apply new state - should clear per-instrument locks
1390        let new_event = AccountState::new(
1391            AccountId::from("SIM-001"),
1392            AccountType::Cash,
1393            vec![AccountBalance::new(
1394                Money::from("8000 USD"),
1395                Money::from("0 USD"),
1396                Money::from("8000 USD"),
1397            )],
1398            vec![],
1399            true,
1400            uuid4(),
1401            1.into(),
1402            1.into(),
1403            Some(Currency::USD()),
1404        );
1405
1406        account.apply(new_event).unwrap();
1407
1408        assert!(account.balances_locked.is_empty());
1409        assert_eq!(
1410            account.balance_total(Some(Currency::USD())),
1411            Some(Money::from("8000 USD"))
1412        );
1413    }
1414
1415    #[rstest]
1416    fn test_apply_empty_balances_preserves_per_instrument_locks() {
1417        let initial_event = AccountState::new(
1418            AccountId::from("SIM-001"),
1419            AccountType::Cash,
1420            vec![AccountBalance::new(
1421                Money::from("10000 USD"),
1422                Money::from("0 USD"),
1423                Money::from("10000 USD"),
1424            )],
1425            vec![],
1426            true,
1427            uuid4(),
1428            0.into(),
1429            0.into(),
1430            Some(Currency::USD()),
1431        );
1432
1433        let mut account = CashAccount::new(initial_event, false, false);
1434        let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1435        account
1436            .update_balance_locked(instrument_id, Money::from("5000 USD"))
1437            .unwrap();
1438        assert_eq!(account.balances_locked.len(), 1);
1439
1440        let empty_event = AccountState::new(
1441            AccountId::from("SIM-001"),
1442            AccountType::Cash,
1443            vec![],
1444            vec![],
1445            true,
1446            uuid4(),
1447            1.into(),
1448            1.into(),
1449            Some(Currency::USD()),
1450        );
1451
1452        account.apply(empty_event).unwrap();
1453
1454        assert_eq!(account.balances_locked.len(), 1);
1455        assert_eq!(
1456            account.balance_total(Some(Currency::USD())),
1457            Some(Money::from("10000 USD"))
1458        );
1459        assert_eq!(account.event_count(), 2);
1460    }
1461}