Skip to main content

nautilus_portfolio/
manager.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides account management functionality.
17
18use std::{cell::RefCell, cmp::Ordering, fmt::Debug, rc::Rc};
19
20use ahash::{AHashMap, AHashSet};
21use nautilus_common::{cache::Cache, clock::Clock};
22use nautilus_core::{UUID4, UnixNanos};
23use nautilus_model::{
24    accounts::{
25        Account, AccountAny, BaseAccount, BettingAccount, CashAccount, MarginAccount, WalletAccount,
26    },
27    enums::{AccountType, OrderSide, OrderType, PriceType},
28    events::{AccountState, OrderFilled},
29    identifiers::InstrumentId,
30    instruments::{Instrument, InstrumentAny},
31    orders::{Order, OrderAny},
32    position::{Position, fold_net_position},
33    types::{
34        AccountBalance, Currency, Money, Price, Quantity,
35        fixed::{FIXED_PRECISION, check_fixed_raw_i128, check_fixed_raw_u128},
36        money::MoneyRaw,
37    },
38};
39use rust_decimal::Decimal;
40
41/// Manages account balance updates and calculations for portfolio management.
42///
43/// The accounts manager handles balance updates for different account types,
44/// including cash and margin accounts, based on order fills and position changes.
45pub struct AccountsManager {
46    clock: Rc<RefCell<dyn Clock>>,
47    cache: Rc<RefCell<Cache>>,
48}
49
50impl Debug for AccountsManager {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct(stringify!(AccountsManager)).finish()
53    }
54}
55
56impl AccountsManager {
57    /// Creates a new [`AccountsManager`] instance.
58    pub fn new(clock: Rc<RefCell<dyn Clock>>, cache: Rc<RefCell<Cache>>) -> Self {
59        Self { clock, cache }
60    }
61
62    /// Updates the given account state based on a filled order.
63    ///
64    /// Mutations are applied to `account` in place so the caller can persist
65    /// the recalculated balances and commissions back to the cache. The account is
66    /// returned with its pre-fill balances when the update fails, alongside an error if
67    /// a cash, betting, or wallet account rejected the new balances, such as a balance
68    /// that would become negative without borrowing.
69    ///
70    /// # Panics
71    ///
72    /// Panics if the position list for the filled instrument is empty.
73    pub fn update_balances(
74        &self,
75        mut account: AccountAny,
76        instrument: &InstrumentAny,
77        fill: &OrderFilled,
78    ) -> (AccountAny, anyhow::Result<AccountState>) {
79        // Snapshot only what the balance update can mutate: cloning the account would
80        // deep-copy its event log, which grows by one entry per fill.
81        let base = base_account(&account);
82        let original_balances = base.balances.clone();
83        let original_commissions = base.commissions.clone();
84        let position_id = if let Some(position_id) = fill.position_id {
85            position_id
86        } else {
87            let cache = self.cache.borrow();
88            let positions_open = cache.positions_open(
89                None,
90                Some(&fill.instrument_id),
91                None,
92                Some(&fill.account_id),
93                None,
94            );
95            positions_open
96                .first()
97                .unwrap_or_else(|| panic!("List of Positions is empty"))
98                .id
99        };
100
101        let position = self
102            .cache
103            .borrow()
104            .position(&position_id)
105            .map(|position| position.clone_without_events());
106
107        let pnls = match account.calculate_pnls(instrument, fill, position) {
108            Ok(pnls) => pnls,
109            Err(e) => {
110                log::error!(
111                    "Cannot update balances for fill {}: failed to calculate PnL: {e}",
112                    fill.trade_id
113                );
114                return (account, Err(e));
115            }
116        };
117
118        // Calculate final PnL including commissions
119        let updated = match account.base_currency() {
120            Some(base_currency) => {
121                let pnl = pnls
122                    .first()
123                    .copied()
124                    .unwrap_or_else(|| Money::zero(base_currency));
125
126                self.update_balance_single_currency(&mut account, fill, pnl)
127            }
128            None => {
129                let mut pnl_list = pnls;
130                self.update_balance_multi_currency(&mut account, fill, &mut pnl_list)
131            }
132        };
133
134        if !matches!(updated, Ok(true)) {
135            let base = base_account_mut(&mut account);
136            base.balances = original_balances;
137            base.commissions = original_commissions;
138
139            if let Err(e) = updated {
140                return (account, Err(e));
141            }
142        }
143
144        let state = self.generate_account_state(&account, fill.ts_event);
145        (account, Ok(state))
146    }
147
148    /// Updates account balances based on open orders.
149    ///
150    /// For cash accounts, updates the balance locked by open orders.
151    /// For margin accounts, updates the initial margin requirements.
152    #[must_use]
153    pub fn update_orders(
154        &self,
155        account: &AccountAny,
156        instrument: &InstrumentAny,
157        orders_open: &[&OrderAny],
158        ts_event: UnixNanos,
159    ) -> Option<(AccountAny, AccountState)> {
160        let mut account = account.clone();
161        self.update_orders_in_place(&mut account, instrument, orders_open, ts_event)
162            .map(|state| (account, state))
163    }
164
165    /// Updates account balances based on open orders in place.
166    ///
167    /// For cash and wallet accounts, updates the balance locked by open orders.
168    /// For margin accounts, updates the initial margin requirements.
169    #[must_use]
170    pub fn update_orders_in_place(
171        &self,
172        account: &mut AccountAny,
173        instrument: &InstrumentAny,
174        orders_open: &[&OrderAny],
175        ts_event: UnixNanos,
176    ) -> Option<AccountState> {
177        match account {
178            AccountAny::Margin(margin_account) => {
179                self.update_margin_init(margin_account, instrument, orders_open, ts_event)
180            }
181            AccountAny::Cash(cash_account) => {
182                self.update_balance_locked(cash_account, instrument, orders_open, ts_event)
183            }
184            AccountAny::Betting(betting_account) => self.update_balance_locked_betting(
185                betting_account,
186                instrument,
187                orders_open,
188                ts_event,
189            ),
190            AccountAny::Wallet(wallet_account) => {
191                self.update_balance_locked_wallet(wallet_account, instrument, orders_open, ts_event)
192            }
193        }
194    }
195
196    /// Updates the account based on current open positions.
197    ///
198    /// # Panics
199    ///
200    /// Panics if any position's `instrument_id` does not match the provided `instrument`.
201    #[must_use]
202    pub fn update_positions(
203        &self,
204        account: &MarginAccount,
205        instrument: &InstrumentAny,
206        positions: Vec<&Position>,
207        ts_event: UnixNanos,
208    ) -> Option<(MarginAccount, AccountState)> {
209        let mut account = account.clone();
210        self.update_positions_in_place(&mut account, instrument, positions, ts_event)
211            .map(|state| (account, state))
212    }
213
214    /// Updates the account based on current open positions in place.
215    ///
216    /// Maintenance margin is computed on the net per-instrument exposure: open
217    /// positions are folded into a NETTING-equivalent state and the margin model
218    /// runs once on the result.
219    ///
220    /// # Panics
221    ///
222    /// Panics if any position's `instrument_id` does not match the provided `instrument`.
223    #[must_use]
224    pub fn update_positions_in_place(
225        &self,
226        account: &mut MarginAccount,
227        instrument: &InstrumentAny,
228        positions: Vec<&Position>,
229        ts_event: UnixNanos,
230    ) -> Option<AccountState> {
231        let mut ordered: Vec<&Position> = positions;
232        ordered.sort_by_key(|p| (p.ts_opened, p.id));
233
234        let legs: Vec<(Decimal, Decimal, u64)> = ordered
235            .iter()
236            .map(|p| {
237                assert_eq!(
238                    p.instrument_id,
239                    instrument.id(),
240                    "Position not for instrument {}",
241                    instrument.id()
242                );
243                (p.signed_decimal_qty(), p.avg_px_open, p.ts_opened.as_u64())
244            })
245            .collect();
246
247        let (net_signed_qty, net_avg_px) = fold_net_position(&legs);
248
249        let mut currency = account
250            .base_currency
251            .unwrap_or_else(|| instrument.settlement_currency());
252
253        let mut total_margin_maint = Decimal::ZERO;
254
255        let net_qty_precision = instrument.size_precision().max(
256            u8::try_from(net_signed_qty.normalize().scale()).expect("Decimal scale is at most 28"),
257        );
258
259        let net_qty = match Quantity::from_decimal_dp(net_signed_qty.abs(), net_qty_precision) {
260            Ok(q) if q.is_zero() => None,
261            Ok(q) => Some(q),
262            Err(e) => {
263                log::error!(
264                    "Cannot calculate maintenance (position) margin: net quantity \
265                     conversion failed for {}: {e}",
266                    instrument.id()
267                );
268                return None;
269            }
270        };
271
272        if let Some(quantity) = net_qty {
273            let price = Price::from_decimal_dp(net_avg_px, instrument.price_precision()).ok()?;
274            let net_entry = if net_signed_qty > Decimal::ZERO {
275                OrderSide::Buy
276            } else {
277                OrderSide::Sell
278            };
279
280            let margin_maint = match instrument {
281                InstrumentAny::Betting(i) => account
282                    .calculate_maintenance_margin(i, quantity, price, None)
283                    .ok()?,
284                InstrumentAny::BinaryOption(i) => account
285                    .calculate_maintenance_margin(i, quantity, price, None)
286                    .ok()?,
287                InstrumentAny::Cfd(i) => account
288                    .calculate_maintenance_margin(i, quantity, price, None)
289                    .ok()?,
290                InstrumentAny::Commodity(i) => account
291                    .calculate_maintenance_margin(i, quantity, price, None)
292                    .ok()?,
293                InstrumentAny::CryptoFuture(i) => account
294                    .calculate_maintenance_margin(i, quantity, price, None)
295                    .ok()?,
296                InstrumentAny::CryptoFuturesSpread(i) => account
297                    .calculate_maintenance_margin(i, quantity, price, None)
298                    .ok()?,
299                InstrumentAny::CryptoOption(i) => account
300                    .calculate_maintenance_margin(i, quantity, price, None)
301                    .ok()?,
302                InstrumentAny::CryptoOptionSpread(i) => account
303                    .calculate_maintenance_margin(i, quantity, price, None)
304                    .ok()?,
305                InstrumentAny::CryptoPerpetual(i) => account
306                    .calculate_maintenance_margin(i, quantity, price, None)
307                    .ok()?,
308                InstrumentAny::CurrencyPair(i) => account
309                    .calculate_maintenance_margin(i, quantity, price, None)
310                    .ok()?,
311                InstrumentAny::Equity(i) => account
312                    .calculate_maintenance_margin(i, quantity, price, None)
313                    .ok()?,
314                InstrumentAny::FuturesContract(i) => account
315                    .calculate_maintenance_margin(i, quantity, price, None)
316                    .ok()?,
317                InstrumentAny::FuturesSpread(i) => account
318                    .calculate_maintenance_margin(i, quantity, price, None)
319                    .ok()?,
320                InstrumentAny::IndexInstrument(i) => account
321                    .calculate_maintenance_margin(i, quantity, price, None)
322                    .ok()?,
323                InstrumentAny::OptionContract(i) => account
324                    .calculate_maintenance_margin(i, quantity, price, None)
325                    .ok()?,
326                InstrumentAny::OptionSpread(i) => account
327                    .calculate_maintenance_margin(i, quantity, price, None)
328                    .ok()?,
329                InstrumentAny::PerpetualContract(i) => account
330                    .calculate_maintenance_margin(i, quantity, price, None)
331                    .ok()?,
332                InstrumentAny::TokenizedAsset(i) => account
333                    .calculate_maintenance_margin(i, quantity, price, None)
334                    .ok()?,
335            };
336
337            let source_currency = margin_maint.currency;
338            total_margin_maint = margin_maint.as_decimal();
339
340            if let Some(base_currency) = account.base_currency {
341                if let Some(xrate) = self.calculate_xrate_to_base(
342                    account.base_currency,
343                    instrument,
344                    source_currency,
345                    net_entry,
346                ) {
347                    total_margin_maint *= xrate;
348                } else {
349                    log::debug!(
350                        "Cannot calculate maintenance (position) margin: insufficient data for {source_currency}/{base_currency}"
351                    );
352                    return None;
353                }
354            } else {
355                currency = source_currency;
356            }
357        }
358
359        let margin_maint = Money::from_decimal(total_margin_maint, currency).ok()?;
360        if total_margin_maint.is_zero() {
361            account.clear_maintenance_margin(instrument.id());
362        } else {
363            if let Some(existing) = account.margin(&instrument.id())
364                && existing.currency != margin_maint.currency
365            {
366                log::error!(
367                    "Cannot update maintenance margin for {}: existing currency {} differs from calculated currency {}",
368                    instrument.id(),
369                    existing.currency,
370                    margin_maint.currency
371                );
372                return None;
373            }
374            account.update_maintenance_margin(instrument.id(), margin_maint);
375        }
376
377        log::info!("{} margin_maint={margin_maint}", instrument.id());
378
379        Some(self.generate_margin_account_state(account, ts_event))
380    }
381
382    fn update_balance_locked(
383        &self,
384        account: &mut CashAccount,
385        instrument: &InstrumentAny,
386        orders_open: &[&OrderAny],
387        ts_event: UnixNanos,
388    ) -> Option<AccountState> {
389        let mut total_locked: AHashMap<Currency, Money> = AHashMap::new();
390
391        for order in orders_open {
392            assert_eq!(
393                order.instrument_id(),
394                instrument.id(),
395                "Order not for instrument {}",
396                instrument.id()
397            );
398            assert!(order.is_open(), "Order is not open");
399
400            let Some(price) = order.price().or_else(|| order.trigger_price()) else {
401                continue;
402            };
403
404            let cash_disposal = order.is_sell() && price.is_negative();
405            if order.is_reduce_only() && !cash_disposal {
406                continue;
407            }
408
409            let amounts = match Self::cash_order_locks(account, instrument, order, price) {
410                Ok(amounts) => amounts,
411                Err(e) => {
412                    log::error!("Cannot calculate balance locked: {e}");
413                    return None;
414                }
415            };
416
417            for locked in amounts.into_iter().flatten() {
418                let locked =
419                    self.convert_balance_locked(account, instrument, order.order_side(), locked)?;
420                let total = total_locked
421                    .entry(locked.currency)
422                    .or_insert_with(|| Money::zero(locked.currency));
423                *total = total.checked_add(locked).or_else(|| {
424                    log::error!(
425                        "Cannot calculate balance locked: {} total exceeds Money bounds",
426                        locked.currency
427                    );
428                    None
429                })?;
430            }
431        }
432
433        if total_locked.is_empty() {
434            account.clear_balance_locked(instrument.id());
435            return Some(self.generate_unleveraged_account_state(account, ts_event));
436        }
437
438        if !reservation_precisions_match(account, &total_locked) {
439            return None;
440        }
441
442        let balances_before = account.base.balances.clone();
443        let locks_before = account.balances_locked.clone();
444
445        // Clear existing locks before applying new ones to remove stale currency entries
446        account.clear_balance_locked(instrument.id());
447
448        for (_, balance_locked) in total_locked {
449            if let Err(e) = account.update_balance_locked(instrument.id(), balance_locked) {
450                log::error!("Cannot update balance locked: {e}");
451                account.base.balances = balances_before;
452                account.balances_locked = locks_before;
453                return None;
454            }
455            log::info!("{} balance_locked={balance_locked}", instrument.id());
456        }
457
458        Some(self.generate_unleveraged_account_state(account, ts_event))
459    }
460
461    fn update_balance_locked_wallet(
462        &self,
463        account: &mut WalletAccount,
464        instrument: &InstrumentAny,
465        orders: &[&OrderAny],
466        ts_event: UnixNanos,
467    ) -> Option<AccountState> {
468        let mut total_locked: AHashMap<Currency, Money> = AHashMap::new();
469        let mut fully_locked = AHashSet::new();
470
471        for order in orders {
472            if order.instrument_id() != instrument.id() {
473                log::error!(
474                    "Cannot calculate wallet balance locked: order {} is for instrument {}, expected {}",
475                    order.client_order_id(),
476                    order.instrument_id(),
477                    instrument.id()
478                );
479                return None;
480            }
481
482            if !(order.is_open() || order.is_inflight()) {
483                continue;
484            }
485
486            if order.is_pending_update() {
487                let source_currency = match order.order_side() {
488                    OrderSide::Buy if !instrument.is_inverse() => instrument.cost_currency(),
489                    OrderSide::Buy => instrument.quote_currency(),
490                    OrderSide::Sell => instrument
491                        .base_currency()
492                        .unwrap_or_else(|| instrument.quote_currency()),
493                };
494                let Some(total) = account.balance_total(Some(source_currency)) else {
495                    log::error!(
496                        "Cannot calculate wallet balance locked: no observed balance for {source_currency}"
497                    );
498                    return None;
499                };
500                total_locked.insert(total.currency, total);
501                fully_locked.insert(total.currency);
502                continue;
503            }
504
505            let quantity = order.leaves_qty();
506            if quantity.is_zero() {
507                continue;
508            }
509
510            let locked = match order.order_side() {
511                OrderSide::Sell if order.is_quote_quantity() => {
512                    log::error!(
513                        "Cannot calculate wallet balance locked for quote-denominated SELL order {}",
514                        order.client_order_id()
515                    );
516                    return None;
517                }
518                OrderSide::Sell => {
519                    let source_currency = instrument
520                        .base_currency()
521                        .unwrap_or_else(|| instrument.quote_currency());
522                    let Some(total) = account.balance_total(Some(source_currency)) else {
523                        log::error!(
524                            "Cannot calculate wallet balance locked: no observed balance for {source_currency}"
525                        );
526                        return None;
527                    };
528
529                    match wallet_money_from_quantity(quantity, total.currency) {
530                        Ok(locked) => locked,
531                        Err(e) => {
532                            log::error!("Cannot calculate wallet balance locked: {e}");
533                            return None;
534                        }
535                    }
536                }
537                OrderSide::Buy if order.is_quote_quantity() => {
538                    let source_currency = instrument.quote_currency();
539                    let Some(total) = account.balance_total(Some(source_currency)) else {
540                        log::error!(
541                            "Cannot calculate wallet balance locked: no observed balance for {source_currency}"
542                        );
543                        return None;
544                    };
545
546                    match wallet_money_from_quantity(quantity, total.currency) {
547                        Ok(locked) => locked,
548                        Err(e) => {
549                            log::error!("Cannot calculate wallet balance locked: {e}");
550                            return None;
551                        }
552                    }
553                }
554                OrderSide::Buy => {
555                    let Some(price) = order.price().or_else(|| order.trigger_price()) else {
556                        log::error!(
557                            "Cannot calculate wallet balance locked for order {} without a price",
558                            order.client_order_id()
559                        );
560                        return None;
561                    };
562
563                    match account.calculate_balance_locked(
564                        instrument,
565                        OrderSide::Buy,
566                        quantity,
567                        price,
568                        None,
569                    ) {
570                        Ok(locked) => locked,
571                        Err(e) => {
572                            log::error!("Cannot calculate wallet balance locked: {e}");
573                            return None;
574                        }
575                    }
576                }
577            };
578
579            if account.balance_total(Some(locked.currency)).is_none() {
580                log::error!(
581                    "Cannot calculate wallet balance locked: no observed balance for {}",
582                    locked.currency
583                );
584                return None;
585            }
586
587            if fully_locked.contains(&locked.currency) {
588                continue;
589            }
590
591            if let Some(total) = total_locked.get_mut(&locked.currency) {
592                let Some(sum) = total.checked_add(locked) else {
593                    log::error!(
594                        "Cannot calculate wallet balance locked: {} total exceeds Money bounds",
595                        locked.currency
596                    );
597                    return None;
598                };
599                *total = sum;
600            } else {
601                total_locked.insert(locked.currency, locked);
602            }
603        }
604
605        let balances_before = account.base.balances.clone();
606        let locks_before = account.balances_locked.clone();
607        account.clear_balance_locked(instrument.id());
608        if account
609            .balances_locked
610            .keys()
611            .any(|(instrument_id, _)| *instrument_id == instrument.id())
612        {
613            log::error!(
614                "Cannot update wallet balance locked: prior reservations for {} were not cleared",
615                instrument.id()
616            );
617            account.base.balances = balances_before;
618            account.balances_locked = locks_before;
619            return None;
620        }
621
622        for balance_locked in total_locked.into_values() {
623            if let Err(e) = account.update_balance_locked(instrument.id(), balance_locked) {
624                log::error!("Cannot update wallet balance locked: {e}");
625                account.base.balances = balances_before;
626                account.balances_locked = locks_before;
627                return None;
628            }
629            log::info!("{} balance_locked={balance_locked}", instrument.id());
630        }
631
632        Some(self.generate_unleveraged_account_state(account, ts_event))
633    }
634
635    fn update_margin_init(
636        &self,
637        account: &mut MarginAccount,
638        instrument: &InstrumentAny,
639        orders_open: &[&OrderAny],
640        ts_event: UnixNanos,
641    ) -> Option<AccountState> {
642        let mut total_margin_init = Decimal::ZERO;
643        let mut currency = instrument.settlement_currency();
644        let mut source_currency: Option<Currency> = None;
645
646        for order in orders_open {
647            assert_eq!(
648                order.instrument_id(),
649                instrument.id(),
650                "Order not for instrument {}",
651                instrument.id()
652            );
653
654            if !order.is_open() || (order.price().is_none() && order.trigger_price().is_none()) {
655                continue;
656            }
657
658            if order.is_reduce_only() {
659                continue; // Does not contribute to margin
660            }
661
662            let price = if order.price().is_some() {
663                order.price()
664            } else {
665                order.trigger_price()
666            };
667
668            let margin_init = match instrument {
669                InstrumentAny::Betting(i) => account
670                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
671                    .ok()?,
672                InstrumentAny::BinaryOption(i) => account
673                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
674                    .ok()?,
675                InstrumentAny::Cfd(i) => account
676                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
677                    .ok()?,
678                InstrumentAny::Commodity(i) => account
679                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
680                    .ok()?,
681                InstrumentAny::CryptoFuture(i) => account
682                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
683                    .ok()?,
684                InstrumentAny::CryptoFuturesSpread(i) => account
685                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
686                    .ok()?,
687                InstrumentAny::CryptoOption(i) => account
688                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
689                    .ok()?,
690                InstrumentAny::CryptoOptionSpread(i) => account
691                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
692                    .ok()?,
693                InstrumentAny::CryptoPerpetual(i) => account
694                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
695                    .ok()?,
696                InstrumentAny::CurrencyPair(i) => account
697                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
698                    .ok()?,
699                InstrumentAny::Equity(i) => account
700                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
701                    .ok()?,
702                InstrumentAny::FuturesContract(i) => account
703                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
704                    .ok()?,
705                InstrumentAny::FuturesSpread(i) => account
706                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
707                    .ok()?,
708                InstrumentAny::IndexInstrument(i) => account
709                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
710                    .ok()?,
711                InstrumentAny::OptionContract(i) => account
712                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
713                    .ok()?,
714                InstrumentAny::OptionSpread(i) => account
715                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
716                    .ok()?,
717                InstrumentAny::PerpetualContract(i) => account
718                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
719                    .ok()?,
720                InstrumentAny::TokenizedAsset(i) => account
721                    .calculate_initial_margin(i, order.leaves_qty(), price?, None)
722                    .ok()?,
723            };
724
725            let margin_currency = margin_init.currency;
726            let mut margin_init = margin_init.as_decimal();
727
728            if let Some(base_currency) = account.base_currency {
729                currency = base_currency;
730                if let Some(xrate) = self.calculate_xrate_to_base(
731                    account.base_currency,
732                    instrument,
733                    margin_currency,
734                    order.order_side(),
735                ) {
736                    margin_init *= xrate;
737                } else {
738                    log::debug!(
739                        "Cannot calculate initial margin: insufficient data for {margin_currency}/{base_currency}"
740                    );
741                    return None;
742                }
743            } else if let Some(source_currency) = source_currency {
744                if source_currency != margin_currency {
745                    log::error!(
746                        "Cannot calculate initial margin: mixed currencies {source_currency} and {margin_currency}"
747                    );
748                    return None;
749                }
750            } else {
751                currency = margin_currency;
752                source_currency = Some(margin_currency);
753            }
754
755            total_margin_init += margin_init;
756        }
757
758        let money = match Money::from_decimal(total_margin_init, currency) {
759            Ok(money) => money,
760            Err(e) => {
761                log::error!("Cannot calculate initial margin: {e}");
762                return None;
763            }
764        };
765        let margin_init = if total_margin_init.is_zero() {
766            account.clear_initial_margin(instrument.id());
767            money
768        } else {
769            if let Some(existing) = account.margin(&instrument.id())
770                && existing.currency != money.currency
771            {
772                log::error!(
773                    "Cannot update initial margin for {}: existing currency {} differs from calculated currency {}",
774                    instrument.id(),
775                    existing.currency,
776                    money.currency
777                );
778                return None;
779            }
780            account.update_initial_margin(instrument.id(), money);
781            money
782        };
783
784        log::info!("{} margin_init={margin_init}", instrument.id());
785
786        Some(self.generate_margin_account_state(account, ts_event))
787    }
788
789    fn update_balance_locked_betting(
790        &self,
791        account: &mut BettingAccount,
792        instrument: &InstrumentAny,
793        orders_open: &[&OrderAny],
794        ts_event: UnixNanos,
795    ) -> Option<AccountState> {
796        if orders_open.is_empty() {
797            account.clear_balance_locked(instrument.id());
798            return Some(self.generate_betting_account_state(account, ts_event));
799        }
800
801        let mut total_locked: AHashMap<Currency, Money> = AHashMap::new();
802
803        for order in orders_open {
804            assert_eq!(
805                order.instrument_id(),
806                instrument.id(),
807                "Order not for instrument {}",
808                instrument.id()
809            );
810            assert!(order.is_open(), "Order is not open");
811
812            if order.price().is_none() && order.trigger_price().is_none() {
813                continue;
814            }
815
816            if order.is_reduce_only() {
817                continue;
818            }
819
820            let price = if order.price().is_some() {
821                order.price()
822            } else {
823                order.trigger_price()
824            };
825
826            let mut locked = match account.calculate_balance_locked(
827                instrument,
828                order.order_side(),
829                order.leaves_qty(),
830                price?,
831                None,
832            ) {
833                Ok(locked) => locked,
834                Err(e) => {
835                    log::error!("Cannot calculate betting balance locked: {e}");
836                    return None;
837                }
838            };
839
840            if let Some(base_curr) = account.base_currency() {
841                if let Some(xrate) = self.cache.borrow().get_xrate(
842                    instrument.id().venue,
843                    locked.currency,
844                    base_curr,
845                    PriceType::Mid,
846                ) {
847                    locked = match Money::from_decimal(locked.as_decimal() * xrate, base_curr) {
848                        Ok(money) => money,
849                        Err(e) => {
850                            log::error!("Cannot calculate balance locked: {e}");
851                            return None;
852                        }
853                    };
854                } else {
855                    log::error!(
856                        "Cannot calculate balance locked: insufficient data for {}/{}",
857                        locked.currency,
858                        base_curr
859                    );
860                    return None;
861                }
862            }
863
864            if let Some(total) = total_locked.get_mut(&locked.currency) {
865                let Some(sum) = total.checked_add(locked) else {
866                    log::error!(
867                        "Cannot calculate betting balance locked: {} total exceeds Money bounds",
868                        locked.currency
869                    );
870                    return None;
871                };
872                *total = sum;
873            } else {
874                total_locked.insert(locked.currency, locked);
875            }
876        }
877
878        if total_locked.is_empty() {
879            account.clear_balance_locked(instrument.id());
880            return Some(self.generate_betting_account_state(account, ts_event));
881        }
882
883        if !reservation_precisions_match(account, &total_locked) {
884            return None;
885        }
886
887        let balances_before = account.base.balances.clone();
888        let locks_before = account.balances_locked.clone();
889
890        account.clear_balance_locked(instrument.id());
891
892        for (_, balance_locked) in total_locked {
893            if let Err(e) = account.update_balance_locked(instrument.id(), balance_locked) {
894                log::error!("Cannot update betting balance locked: {e}");
895                account.base.balances = balances_before;
896                account.balances_locked = locks_before;
897                return None;
898            }
899            log::info!("{} balance_locked={balance_locked}", instrument.id());
900        }
901
902        Some(self.generate_betting_account_state(account, ts_event))
903    }
904
905    fn update_balance_single_currency(
906        &self,
907        account: &mut AccountAny,
908        fill: &OrderFilled,
909        mut pnl: Money,
910    ) -> anyhow::Result<bool> {
911        let base_currency = if let Some(currency) = account.base_currency() {
912            currency
913        } else {
914            log::error!("Account has no base currency set");
915            return Ok(false);
916        };
917
918        let mut balances = Vec::new();
919        let mut commission = fill.commission;
920
921        if let Some(ref mut comm) = commission
922            && comm.currency != base_currency
923        {
924            let xrate = self.cache.borrow().get_xrate(
925                fill.instrument_id.venue,
926                comm.currency,
927                base_currency,
928                if fill.order_side == OrderSide::Sell {
929                    PriceType::Bid
930                } else {
931                    PriceType::Ask
932                },
933            );
934
935            if let Some(xrate) = xrate {
936                let Some(converted) = comm.as_decimal().checked_mul(xrate) else {
937                    log::error!("Cannot calculate account state: commission conversion overflow");
938                    return Ok(false);
939                };
940
941                *comm = match Money::from_decimal_native(converted, base_currency) {
942                    Ok(money) => money,
943                    Err(e) => {
944                        log::error!("Cannot calculate account state: {e}");
945                        return Ok(false);
946                    }
947                };
948            } else {
949                log::error!(
950                    "Cannot calculate account state: insufficient data for {}/{}",
951                    comm.currency,
952                    base_currency
953                );
954                return Ok(false);
955            }
956        }
957
958        if pnl.currency != base_currency {
959            let xrate = self.cache.borrow().get_xrate(
960                fill.instrument_id.venue,
961                pnl.currency,
962                base_currency,
963                if fill.order_side == OrderSide::Sell {
964                    PriceType::Bid
965                } else {
966                    PriceType::Ask
967                },
968            );
969
970            if let Some(xrate) = xrate {
971                let Some(converted) = pnl.as_decimal().checked_mul(xrate) else {
972                    log::error!("Cannot calculate account state: PnL conversion overflow");
973                    return Ok(false);
974                };
975
976                pnl = match Money::from_decimal_native(converted, base_currency) {
977                    Ok(money) => money,
978                    Err(e) => {
979                        log::error!("Cannot calculate account state: {e}");
980                        return Ok(false);
981                    }
982                };
983            } else {
984                log::error!(
985                    "Cannot calculate account state: insufficient data for {}/{}",
986                    pnl.currency,
987                    base_currency
988                );
989                return Ok(false);
990            }
991        }
992
993        if let Some(comm) = commission {
994            let Some(net_pnl) = pnl.checked_sub(comm) else {
995                log::error!("Cannot calculate account state: net PnL exceeds Money bounds");
996                return Ok(false);
997            };
998            pnl = net_pnl;
999        }
1000
1001        if pnl.is_zero() {
1002            commission
1003                .map(|fee| base_account_mut(account).try_update_commissions(fee))
1004                .transpose()?;
1005            return Ok(true);
1006        }
1007
1008        let existing_balances = account.balances();
1009        let balance = if let Some(b) = existing_balances.get(&pnl.currency) {
1010            b
1011        } else {
1012            log::error!(
1013                "Cannot complete transaction: no balance for {}",
1014                pnl.currency
1015            );
1016            return Ok(false);
1017        };
1018
1019        let Some(new_total) = balance.total.checked_add(pnl) else {
1020            log::error!("Cannot update {} balance: total overflow", pnl.currency);
1021            return Ok(false);
1022        };
1023
1024        let new_balance =
1025            match AccountBalance::from_money_total_and_locked(new_total, balance.locked) {
1026                Ok(new_balance) => new_balance,
1027                Err(e) => {
1028                    log::error!("Cannot update {} balance: {e}", pnl.currency);
1029                    return Ok(false);
1030                }
1031            };
1032
1033        balances.push(new_balance);
1034
1035        match account {
1036            AccountAny::Margin(margin) => {
1037                margin.update_balances(&balances);
1038
1039                if let Some(comm) = commission
1040                    && let Err(e) = margin.try_update_commissions(comm)
1041                {
1042                    log::error!("Cannot update margin account commissions: {e}");
1043                    return Ok(false);
1044                }
1045            }
1046            AccountAny::Cash(cash) => {
1047                if let Err(e) = cash.update_balances(&balances) {
1048                    anyhow::bail!(
1049                        "Cannot update cash account balance for fill {}: {e}",
1050                        fill.trade_id
1051                    );
1052                }
1053
1054                if let Some(comm) = commission
1055                    && let Err(e) = cash.try_update_commissions(comm)
1056                {
1057                    log::error!("Cannot update cash account commissions: {e}");
1058                    return Ok(false);
1059                }
1060            }
1061            AccountAny::Betting(betting) => {
1062                if let Err(e) = betting.update_balances(&balances) {
1063                    anyhow::bail!(
1064                        "Cannot update betting account balance for fill {}: {e}",
1065                        fill.trade_id
1066                    );
1067                }
1068
1069                if let Some(comm) = commission
1070                    && let Err(e) = betting.try_update_commissions(comm)
1071                {
1072                    log::error!("Cannot update betting account commissions: {e}");
1073                    return Ok(false);
1074                }
1075            }
1076            AccountAny::Wallet(wallet) => {
1077                if let Err(e) = wallet.update_balances(&balances) {
1078                    anyhow::bail!(
1079                        "Cannot update wallet account balance for fill {}: {e}",
1080                        fill.trade_id
1081                    );
1082                }
1083
1084                if let Some(comm) = commission
1085                    && let Err(e) = wallet.try_update_commissions(comm)
1086                {
1087                    log::error!("Cannot update wallet account commissions: {e}");
1088                    return Ok(false);
1089                }
1090            }
1091        }
1092        Ok(true)
1093    }
1094
1095    fn update_balance_multi_currency(
1096        &self,
1097        account: &mut AccountAny,
1098        fill: &OrderFilled,
1099        pnls: &mut [Money],
1100    ) -> anyhow::Result<bool> {
1101        let mut new_balances = Vec::new();
1102        let commission = fill.commission;
1103        let mut apply_commission = commission.is_some_and(|c| !c.is_zero());
1104
1105        for pnl in pnls.iter_mut() {
1106            if apply_commission && pnl.currency == commission.unwrap().currency {
1107                let Some(net_pnl) = pnl.checked_sub(commission.unwrap()) else {
1108                    log::error!("Cannot calculate account state: net PnL exceeds Money bounds");
1109                    return Ok(false);
1110                };
1111                *pnl = net_pnl;
1112                apply_commission = false;
1113            }
1114
1115            if pnl.is_zero() {
1116                continue; // No Adjustment
1117            }
1118
1119            let currency = pnl.currency;
1120            let balances = account.balances();
1121
1122            let new_balance = if let Some(balance) = balances.get(&currency) {
1123                let Some(new_total) = balance.total.checked_add(*pnl) else {
1124                    log::error!("Cannot update {currency} balance: total overflow");
1125                    return Ok(false);
1126                };
1127
1128                let mut new_locked = balance.locked;
1129                if pnl.is_negative()
1130                    && fill.order_type != OrderType::Market
1131                    && !self.is_sports_betting_fill(fill.instrument_id)
1132                {
1133                    let Some(updated_locked) = new_locked.checked_add(*pnl) else {
1134                        log::error!("Cannot update {currency} balance: locked amount overflow");
1135                        return Ok(false);
1136                    };
1137                    new_locked = updated_locked;
1138                    if new_locked.is_negative() {
1139                        new_locked = Money::zero(currency);
1140                    }
1141                }
1142
1143                match AccountBalance::from_money_total_and_locked(new_total, new_locked) {
1144                    Ok(new_balance) => new_balance,
1145                    Err(e) => {
1146                        log::error!("Cannot update {currency} balance: {e}");
1147                        return Ok(false);
1148                    }
1149                }
1150            } else {
1151                // Mirrors Python `_update_balance_multi_currency`: a fill that
1152                // would open a new debit currency on a non-seeded account is
1153                // rejected even when `allow_cash_borrowing=true`. The
1154                // existing-currency branch above lets the per-account
1155                // `update_balances` enforce the borrowing policy, so the two
1156                // branches are intentionally asymmetric until cross-currency
1157                // equity tracking is implemented.
1158                if pnl.is_negative() {
1159                    log::error!(
1160                        "Cannot complete transaction: no {currency} to deduct a {pnl} realized PnL from"
1161                    );
1162                    return Ok(false);
1163                }
1164                AccountBalance::new(*pnl, Money::zero(currency), *pnl)
1165            };
1166
1167            new_balances.push(new_balance);
1168        }
1169
1170        if apply_commission {
1171            let commission = commission.unwrap();
1172            let currency = commission.currency;
1173            let balances = account.balances();
1174
1175            let commission_balance = if let Some(balance) = balances.get(&currency) {
1176                let Some(new_total) = balance.total.checked_sub(commission) else {
1177                    log::error!("Cannot deduct {currency} commission: total overflow");
1178                    return Ok(false);
1179                };
1180
1181                match AccountBalance::from_money_total_and_locked(new_total, balance.locked) {
1182                    Ok(commission_balance) => commission_balance,
1183                    Err(e) => {
1184                        log::error!("Cannot deduct {currency} commission: {e}");
1185                        return Ok(false);
1186                    }
1187                }
1188            } else {
1189                if commission.is_positive() {
1190                    log::error!(
1191                        "Cannot complete transaction: no {currency} balance to deduct a {commission} commission from"
1192                    );
1193                    return Ok(false);
1194                }
1195
1196                match AccountBalance::from_money_total_and_locked(
1197                    -commission,
1198                    Money::zero(currency),
1199                ) {
1200                    Ok(commission_balance) => commission_balance,
1201                    Err(e) => {
1202                        log::error!("Cannot credit {currency} commission rebate: {e}");
1203                        return Ok(false);
1204                    }
1205                }
1206            };
1207            new_balances.push(commission_balance);
1208        }
1209
1210        if new_balances.is_empty() {
1211            commission
1212                .map(|fee| base_account_mut(account).try_update_commissions(fee))
1213                .transpose()?;
1214            return Ok(true);
1215        }
1216
1217        match account {
1218            AccountAny::Margin(margin) => {
1219                margin.update_balances(&new_balances);
1220
1221                if let Some(commission) = commission
1222                    && let Err(e) = margin.try_update_commissions(commission)
1223                {
1224                    log::error!("Cannot update margin account commissions: {e}");
1225                    return Ok(false);
1226                }
1227            }
1228            AccountAny::Cash(cash) => {
1229                if let Err(e) = cash.update_balances(&new_balances) {
1230                    anyhow::bail!(
1231                        "Cannot update cash account balance for fill {}: {e}",
1232                        fill.trade_id
1233                    );
1234                }
1235
1236                if let Some(commission) = commission
1237                    && let Err(e) = cash.try_update_commissions(commission)
1238                {
1239                    log::error!("Cannot update cash account commissions: {e}");
1240                    return Ok(false);
1241                }
1242            }
1243            AccountAny::Betting(betting) => {
1244                if let Err(e) = betting.update_balances(&new_balances) {
1245                    anyhow::bail!(
1246                        "Cannot update betting account balance for fill {}: {e}",
1247                        fill.trade_id
1248                    );
1249                }
1250
1251                if let Some(commission) = commission
1252                    && let Err(e) = betting.try_update_commissions(commission)
1253                {
1254                    log::error!("Cannot update betting account commissions: {e}");
1255                    return Ok(false);
1256                }
1257            }
1258            AccountAny::Wallet(wallet) => {
1259                if let Err(e) = wallet.update_balances(&new_balances) {
1260                    anyhow::bail!(
1261                        "Cannot update wallet account balance for fill {}: {e}",
1262                        fill.trade_id
1263                    );
1264                }
1265
1266                if let Some(commission) = commission
1267                    && let Err(e) = wallet.try_update_commissions(commission)
1268                {
1269                    log::error!("Cannot update wallet account commissions: {e}");
1270                    return Ok(false);
1271                }
1272            }
1273        }
1274        Ok(true)
1275    }
1276
1277    fn is_sports_betting_fill(&self, instrument_id: InstrumentId) -> bool {
1278        self.cache
1279            .borrow()
1280            .instrument(&instrument_id)
1281            .is_some_and(|instrument| matches!(instrument, InstrumentAny::Betting(_)))
1282    }
1283
1284    fn generate_account_state(&self, account: &AccountAny, ts_event: UnixNanos) -> AccountState {
1285        match account {
1286            AccountAny::Margin(margin_account) => {
1287                self.generate_margin_account_state(margin_account, ts_event)
1288            }
1289            AccountAny::Cash(cash_account) => {
1290                self.generate_unleveraged_account_state(cash_account, ts_event)
1291            }
1292            AccountAny::Betting(betting_account) => {
1293                self.generate_betting_account_state(betting_account, ts_event)
1294            }
1295            AccountAny::Wallet(wallet_account) => {
1296                self.generate_unleveraged_account_state(wallet_account, ts_event)
1297            }
1298        }
1299    }
1300
1301    fn generate_margin_account_state(
1302        &self,
1303        margin_account: &MarginAccount,
1304        ts_event: UnixNanos,
1305    ) -> AccountState {
1306        // Include both per-instrument (`margins`) and account-wide
1307        // (`account_margins`, keyed by collateral currency) entries so
1308        // regenerated state events preserve the full margin picture.
1309        let mut margins: Vec<_> = margin_account.margins.values().copied().collect();
1310        margins.extend(margin_account.account_margins.values().copied());
1311        AccountState::new(
1312            margin_account.id,
1313            AccountType::Margin,
1314            margin_account.balances.clone().into_values().collect(),
1315            margins,
1316            false,
1317            UUID4::new(),
1318            ts_event,
1319            self.clock.borrow().timestamp_ns(),
1320            margin_account.base_currency(),
1321        )
1322    }
1323
1324    fn generate_unleveraged_account_state(
1325        &self,
1326        account: &impl Account,
1327        ts_event: UnixNanos,
1328    ) -> AccountState {
1329        AccountState::new(
1330            account.id(),
1331            account.account_type(),
1332            account.balances().into_values().collect(),
1333            vec![],
1334            false,
1335            UUID4::new(),
1336            ts_event,
1337            self.clock.borrow().timestamp_ns(),
1338            account.base_currency(),
1339        )
1340    }
1341
1342    fn generate_betting_account_state(
1343        &self,
1344        betting_account: &BettingAccount,
1345        ts_event: UnixNanos,
1346    ) -> AccountState {
1347        AccountState::new(
1348            betting_account.id,
1349            AccountType::Betting,
1350            betting_account.balances.clone().into_values().collect(),
1351            vec![],
1352            false,
1353            UUID4::new(),
1354            ts_event,
1355            self.clock.borrow().timestamp_ns(),
1356            betting_account.base_currency(),
1357        )
1358    }
1359
1360    fn cash_order_locks(
1361        account: &CashAccount,
1362        instrument: &InstrumentAny,
1363        order: &OrderAny,
1364        price: Price,
1365    ) -> anyhow::Result<[Option<Money>; 2]> {
1366        let locked = if order.is_reduce_only() {
1367            None
1368        } else {
1369            Some(account.calculate_balance_locked(
1370                instrument,
1371                order.order_side(),
1372                order.leaves_qty(),
1373                price,
1374                None,
1375            )?)
1376        };
1377
1378        let disposal = if order.is_sell()
1379            && price.is_negative()
1380            && (order.is_reduce_only() || instrument.base_currency().is_some())
1381        {
1382            Some(account.calculate_balance_locked(
1383                instrument,
1384                OrderSide::Buy,
1385                order.leaves_qty(),
1386                -price,
1387                None,
1388            )?)
1389        } else {
1390            None
1391        };
1392
1393        Ok([locked, disposal])
1394    }
1395
1396    fn convert_balance_locked(
1397        &self,
1398        account: &CashAccount,
1399        instrument: &InstrumentAny,
1400        side: OrderSide,
1401        locked: Money,
1402    ) -> Option<Money> {
1403        let Some(base_curr) = account.base_currency() else {
1404            return Some(locked);
1405        };
1406
1407        let Some(xrate) = self.calculate_xrate_to_base(
1408            account.base_currency(),
1409            instrument,
1410            locked.currency,
1411            side,
1412        ) else {
1413            log::error!(
1414                "Cannot calculate balance locked: insufficient data for {}/{}",
1415                locked.currency,
1416                base_curr
1417            );
1418            return None;
1419        };
1420
1421        let amount = locked.as_decimal().checked_mul(xrate).or_else(|| {
1422            log::error!("Cannot calculate balance locked: exchange-rate conversion overflow");
1423            None
1424        })?;
1425
1426        match Money::from_decimal_native(amount, base_curr) {
1427            Ok(money) => Some(money),
1428            Err(e) => {
1429                log::error!("Cannot calculate balance locked: {e}");
1430                None
1431            }
1432        }
1433    }
1434
1435    fn calculate_xrate_to_base(
1436        &self,
1437        base_currency: Option<Currency>,
1438        instrument: &InstrumentAny,
1439        source_currency: Currency,
1440        side: OrderSide,
1441    ) -> Option<Decimal> {
1442        match base_currency {
1443            None => Some(Decimal::ONE),
1444            Some(base_curr) if source_currency == base_curr => Some(Decimal::ONE),
1445            Some(base_curr) => self.cache.borrow().get_xrate(
1446                instrument.id().venue,
1447                source_currency,
1448                base_curr,
1449                if side == OrderSide::Buy {
1450                    PriceType::Bid
1451                } else {
1452                    PriceType::Ask
1453                },
1454            ),
1455        }
1456    }
1457}
1458
1459#[allow(
1460    clippy::useless_conversion,
1461    reason = "the raw width differs when high-precision is disabled"
1462)]
1463fn wallet_money_from_quantity(quantity: Quantity, currency: Currency) -> anyhow::Result<Money> {
1464    anyhow::ensure!(!quantity.is_undefined(), "quantity was undefined");
1465    Quantity::from_raw_checked(quantity.raw(), quantity.precision)?;
1466    check_fixed_raw_u128(u128::from(quantity.raw()), quantity.precision)?;
1467
1468    let source_precision = quantity.precision.max(FIXED_PRECISION);
1469    let target_precision = currency.precision.max(FIXED_PRECISION);
1470    let raw = i128::try_from(u128::from(quantity.raw()))
1471        .map_err(|_| anyhow::anyhow!("quantity for {currency} exceeds signed raw bounds"))?;
1472    let raw = match source_precision.cmp(&target_precision) {
1473        Ordering::Less => {
1474            let scale = 10_i128.pow(u32::from(target_precision - source_precision));
1475            raw.checked_mul(scale).ok_or_else(|| {
1476                anyhow::anyhow!("quantity for {currency} overflowed while increasing raw scale")
1477            })?
1478        }
1479        Ordering::Greater => {
1480            let scale = 10_i128.pow(u32::from(source_precision - target_precision));
1481            anyhow::ensure!(
1482                raw % scale == 0,
1483                "quantity for {currency} loses precision when decreasing raw scale"
1484            );
1485            raw / scale
1486        }
1487        Ordering::Equal => raw,
1488    };
1489    check_fixed_raw_i128(raw, currency.precision)?;
1490    let raw: MoneyRaw = raw
1491        .try_into()
1492        .map_err(|_| anyhow::anyhow!("quantity for {currency} exceeds Money raw bounds"))?;
1493
1494    Money::from_raw_checked(raw, currency).map_err(Into::into)
1495}
1496
1497fn reservation_precisions_match(
1498    account: &dyn Account,
1499    reservations: &AHashMap<Currency, Money>,
1500) -> bool {
1501    for reservation in reservations.values() {
1502        let Some(balance) = account.balance(Some(reservation.currency)) else {
1503            continue;
1504        };
1505
1506        if balance.currency.precision != reservation.currency.precision {
1507            log::error!(
1508                "Cannot update {} reservation: precision {} differed from balance precision {}",
1509                reservation.currency,
1510                reservation.currency.precision,
1511                balance.currency.precision
1512            );
1513            return false;
1514        }
1515    }
1516
1517    true
1518}
1519
1520fn base_account(account: &AccountAny) -> &BaseAccount {
1521    match account {
1522        AccountAny::Margin(margin) => margin,
1523        AccountAny::Cash(cash) => cash,
1524        AccountAny::Betting(betting) => betting,
1525        AccountAny::Wallet(wallet) => wallet,
1526    }
1527}
1528
1529fn base_account_mut(account: &mut AccountAny) -> &mut BaseAccount {
1530    match account {
1531        AccountAny::Margin(margin) => margin,
1532        AccountAny::Cash(cash) => cash,
1533        AccountAny::Betting(betting) => betting,
1534        AccountAny::Wallet(wallet) => wallet,
1535    }
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use std::{cell::RefCell, rc::Rc, sync::Arc};
1541
1542    use nautilus_common::{cache::Cache, clock::VirtualClock};
1543    use nautilus_model::{
1544        accounts::{BettingAccount, CashAccount, MarginAccount},
1545        data::QuoteTick,
1546        enums::{AccountType, CurrencyType, OmsType, OrderSide, OrderType},
1547        events::{
1548            AccountState, OrderAccepted, OrderEventAny, OrderFilled, OrderSubmitted,
1549            account::stubs::wallet_account_state,
1550            order::spec::{
1551                OrderAcceptedSpec, OrderFilledSpec, OrderPendingUpdateSpec, OrderSubmittedSpec,
1552            },
1553        },
1554        identifiers::{
1555            AccountId, ClientOrderId, InstrumentId, PositionId, Symbol, TradeId, Venue,
1556            VenueOrderId,
1557        },
1558        instruments::{
1559            CryptoFuture, CurrencyPair, Instrument, InstrumentAny,
1560            stubs::{
1561                audusd_sim, betting, commodity_gold, crypto_future_btcusdt, currency_pair_btcusdt,
1562                currency_pair_ethusdt, default_fx_ccy, ethbtc_quanto,
1563            },
1564        },
1565        orders::{OrderAny, OrderTestBuilder},
1566        position::Position,
1567        types::{
1568            AccountBalance, Currency, MarginBalance, Money, Price, Quantity,
1569            money::{MONEY_MAX, MONEY_RAW_MAX, MoneyRaw},
1570        },
1571    };
1572    use rstest::rstest;
1573    use rust_decimal_macros::dec;
1574
1575    use super::*;
1576
1577    #[rstest]
1578    #[case::whole("1", "-6.00", dec!(6))]
1579    #[case::fractional("0.3", "-0.02", dec!(0.006))]
1580    #[case::subcurrency("0.3", "-0.00000001", dec!(0.000000003))]
1581    fn test_update_orders_locks_negative_price_disposal(
1582        #[case] quantity: &str,
1583        #[case] price: &str,
1584        #[case] expected: Decimal,
1585        #[values(false, true)] base_asset: bool,
1586        #[values(false, true)] reduce_only: bool,
1587    ) {
1588        let instrument = if base_asset {
1589            InstrumentAny::CryptoFuture(crypto_future_btcusdt(
1590                8,
1591                6,
1592                Price::from("0.00000001"),
1593                Quantity::from("0.000001"),
1594            ))
1595        } else {
1596            let mut commodity = commodity_gold();
1597            commodity.price_precision = 8;
1598            commodity.price_increment = Price::from("0.00000001");
1599            commodity.size_precision = 1;
1600            commodity.size_increment = Quantity::from("0.1");
1601            InstrumentAny::Commodity(commodity)
1602        };
1603
1604        let quantity = Quantity::from(quantity);
1605        let quote = instrument.quote_currency();
1606        let account_id = AccountId::from("SIM-001");
1607        let quote_total = Money::from_decimal(dec!(1000), quote).unwrap();
1608        let mut balances = vec![AccountBalance::new(
1609            quote_total,
1610            Money::zero(quote),
1611            quote_total,
1612        )];
1613
1614        if let Some(base) = instrument.base_currency() {
1615            let total = Money::from_decimal(dec!(2), base).unwrap();
1616            balances.push(AccountBalance::new(total, Money::zero(base), total));
1617        }
1618
1619        let state = AccountState::new(
1620            account_id,
1621            AccountType::Cash,
1622            balances,
1623            vec![],
1624            true,
1625            UUID4::new(),
1626            UnixNanos::default(),
1627            UnixNanos::default(),
1628            None,
1629        );
1630
1631        let account = AccountAny::Cash(CashAccount::new(state, true, false));
1632        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1633        let cache = Rc::new(RefCell::new(Cache::default()));
1634        let manager = AccountsManager::new(clock, cache);
1635        let mut order = OrderTestBuilder::new(OrderType::Limit)
1636            .instrument_id(instrument.id())
1637            .side(OrderSide::Sell)
1638            .quantity(quantity)
1639            .price(Price::from(price))
1640            .reduce_only(reduce_only)
1641            .build();
1642        let submitted = OrderSubmittedSpec::builder()
1643            .trader_id(order.trader_id())
1644            .strategy_id(order.strategy_id())
1645            .instrument_id(order.instrument_id())
1646            .client_order_id(order.client_order_id())
1647            .account_id(account_id)
1648            .build();
1649        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
1650        let accepted = OrderAcceptedSpec::builder()
1651            .trader_id(order.trader_id())
1652            .strategy_id(order.strategy_id())
1653            .instrument_id(order.instrument_id())
1654            .client_order_id(order.client_order_id())
1655            .account_id(account_id)
1656            .venue_order_id(VenueOrderId::from("V-001"))
1657            .build();
1658        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
1659
1660        let (account, state) = manager
1661            .update_orders(&account, &instrument, &[&order], UnixNanos::default())
1662            .unwrap();
1663
1664        let locked = Money::from_decimal_native(expected, quote).unwrap();
1665        let free = quote_total - locked;
1666        assert_eq!(account.balance_total(Some(quote)), Some(quote_total));
1667        assert_eq!(account.balance_locked(Some(quote)), Some(locked));
1668        assert_eq!(account.balance_free(Some(quote)), Some(free));
1669        let quote_balance = state
1670            .balances
1671            .iter()
1672            .find(|balance| balance.currency == quote)
1673            .unwrap();
1674        assert_eq!(
1675            *quote_balance,
1676            AccountBalance::new(quote_total, locked, free)
1677        );
1678        assert_eq!(state.balances.len(), if base_asset { 2 } else { 1 });
1679
1680        if let Some(base) = instrument.base_currency() {
1681            let total = Money::from_decimal(dec!(2), base).unwrap();
1682
1683            let locked = Money::from_decimal(
1684                if reduce_only {
1685                    dec!(0)
1686                } else {
1687                    quantity.as_decimal()
1688                },
1689                base,
1690            )
1691            .unwrap();
1692
1693            let free = total - locked;
1694            assert_eq!(account.balance_total(Some(base)), Some(total));
1695            assert_eq!(account.balance_locked(Some(base)), Some(locked));
1696            assert_eq!(account.balance_free(Some(base)), Some(free));
1697            let balance = state
1698                .balances
1699                .iter()
1700                .find(|balance| balance.currency == base)
1701                .unwrap();
1702            assert_eq!(*balance, AccountBalance::new(total, locked, free));
1703        }
1704    }
1705
1706    #[rstest]
1707    fn test_update_balance_locked_with_base_currency_multiple_orders() {
1708        let usd = Currency::USD();
1709        let account_state = AccountState::new(
1710            AccountId::new("SIM-001"),
1711            AccountType::Cash,
1712            vec![AccountBalance::new(
1713                Money::new(1_000_000.0, usd),
1714                Money::zero(usd),
1715                Money::new(1_000_000.0, usd),
1716            )],
1717            Vec::new(),
1718            true,
1719            UUID4::new(),
1720            UnixNanos::default(),
1721            UnixNanos::default(),
1722            Some(usd),
1723        );
1724
1725        let account = CashAccount::new(account_state, true, false);
1726
1727        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1728        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
1729        cache
1730            .borrow_mut()
1731            .add_account(AccountAny::Cash(account.clone()))
1732            .unwrap();
1733
1734        let manager = AccountsManager::new(clock, cache);
1735
1736        let instrument = audusd_sim();
1737
1738        let order1 = OrderTestBuilder::new(OrderType::Limit)
1739            .instrument_id(instrument.id())
1740            .side(OrderSide::Buy)
1741            .quantity(Quantity::from("100000"))
1742            .price(Price::from("0.75000"))
1743            .build();
1744
1745        let order2 = OrderTestBuilder::new(OrderType::Limit)
1746            .instrument_id(instrument.id())
1747            .side(OrderSide::Buy)
1748            .quantity(Quantity::from("50000"))
1749            .price(Price::from("0.74500"))
1750            .build();
1751
1752        let order3 = OrderTestBuilder::new(OrderType::Limit)
1753            .instrument_id(instrument.id())
1754            .side(OrderSide::Buy)
1755            .quantity(Quantity::from("75000"))
1756            .price(Price::from("0.74000"))
1757            .build();
1758
1759        let mut order1 = order1;
1760        let mut order2 = order2;
1761        let mut order3 = order3;
1762
1763        let submitted1 = order_submitted_for(&order1);
1764        let accepted1 = order_accepted_for(&order1, VenueOrderId::new("1"));
1765
1766        order1.apply(OrderEventAny::Submitted(submitted1)).unwrap();
1767        order1.apply(OrderEventAny::Accepted(accepted1)).unwrap();
1768
1769        let submitted2 = order_submitted_for(&order2);
1770        let accepted2 = order_accepted_for(&order2, VenueOrderId::new("2"));
1771
1772        order2.apply(OrderEventAny::Submitted(submitted2)).unwrap();
1773        order2.apply(OrderEventAny::Accepted(accepted2)).unwrap();
1774
1775        let submitted3 = order_submitted_for(&order3);
1776        let accepted3 = order_accepted_for(&order3, VenueOrderId::new("3"));
1777
1778        order3.apply(OrderEventAny::Submitted(submitted3)).unwrap();
1779        order3.apply(OrderEventAny::Accepted(accepted3)).unwrap();
1780
1781        let orders: Vec<&OrderAny> = vec![&order1, &order2, &order3];
1782
1783        let result = manager.update_orders(
1784            &AccountAny::Cash(account),
1785            &InstrumentAny::CurrencyPair(instrument),
1786            &orders,
1787            UnixNanos::default(),
1788        );
1789
1790        assert!(result.is_some());
1791        let (updated_account, _state) = result.unwrap();
1792
1793        if let AccountAny::Cash(cash_account) = updated_account {
1794            let locked_balance = cash_account.balance_locked(Some(usd));
1795
1796            // Order 1: 100k * 0.75 = 75k, Order 2: 50k * 0.745 = 37.25k, Order 3: 75k * 0.74 = 55.5k
1797            let expected_locked = Money::new(167_750.0, usd);
1798
1799            assert_eq!(locked_balance, Some(expected_locked));
1800            let aud = Currency::AUD();
1801            assert_eq!(cash_account.balance_locked(Some(aud)), None);
1802        } else {
1803            panic!("Expected CashAccount");
1804        }
1805    }
1806
1807    #[rstest]
1808    fn test_update_balance_locked_after_partial_fill() {
1809        let usd = Currency::USD();
1810        let account_state = AccountState::new(
1811            AccountId::new("SIM-001"),
1812            AccountType::Cash,
1813            vec![AccountBalance::new(
1814                Money::new(1_000_000.0, usd),
1815                Money::zero(usd),
1816                Money::new(1_000_000.0, usd),
1817            )],
1818            Vec::new(),
1819            true,
1820            UUID4::new(),
1821            UnixNanos::default(),
1822            UnixNanos::default(),
1823            Some(usd),
1824        );
1825        let account = CashAccount::new(account_state, true, false);
1826        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1827        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
1828        let manager = AccountsManager::new(clock, cache);
1829        let instrument = audusd_sim();
1830
1831        let mut order = OrderTestBuilder::new(OrderType::Limit)
1832            .instrument_id(instrument.id())
1833            .side(OrderSide::Buy)
1834            .quantity(Quantity::from("100000"))
1835            .price(Price::from("0.80000"))
1836            .build();
1837        order
1838            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
1839            .unwrap();
1840        order
1841            .apply(OrderEventAny::Accepted(order_accepted_for(
1842                &order,
1843                VenueOrderId::new("1"),
1844            )))
1845            .unwrap();
1846
1847        let (account, _) = manager
1848            .update_orders(
1849                &AccountAny::Cash(account),
1850                &InstrumentAny::CurrencyPair(instrument.clone()),
1851                &[&order],
1852                UnixNanos::default(),
1853            )
1854            .unwrap();
1855        let AccountAny::Cash(cash) = &account else {
1856            panic!("Expected CashAccount");
1857        };
1858        assert_eq!(
1859            cash.balance_total(Some(usd)),
1860            Some(Money::new(1_000_000.0, usd))
1861        );
1862        assert_eq!(
1863            cash.balance_locked(Some(usd)),
1864            Some(Money::new(80_000.0, usd))
1865        );
1866        assert_eq!(
1867            cash.balance_free(Some(usd)),
1868            Some(Money::new(920_000.0, usd))
1869        );
1870
1871        let fill = OrderFilledSpec::builder()
1872            .instrument_id(instrument.id())
1873            .client_order_id(order.client_order_id())
1874            .venue_order_id(VenueOrderId::new("1"))
1875            .order_side(OrderSide::Buy)
1876            .order_type(OrderType::Limit)
1877            .last_qty(Quantity::from("40000"))
1878            .last_px(Price::from("0.79000"))
1879            .position_id(PositionId::new("P-001"))
1880            .commission(Money::new(8.0, usd))
1881            .build();
1882        order.apply(OrderEventAny::Filled(fill.clone())).unwrap();
1883        let (account, _) = manager.update_balances(
1884            account,
1885            &InstrumentAny::CurrencyPair(instrument.clone()),
1886            &fill,
1887        );
1888
1889        let (account, _) = manager
1890            .update_orders(
1891                &account,
1892                &InstrumentAny::CurrencyPair(instrument),
1893                &[&order],
1894                UnixNanos::default(),
1895            )
1896            .unwrap();
1897
1898        let AccountAny::Cash(account) = account else {
1899            panic!("Expected CashAccount");
1900        };
1901        assert_eq!(order.leaves_qty(), Quantity::from("60000"));
1902        assert_eq!(
1903            account.balance_total(Some(usd)),
1904            Some(Money::new(968_392.0, usd))
1905        );
1906        assert_eq!(
1907            account.balance_locked(Some(usd)),
1908            Some(Money::new(48_000.0, usd))
1909        );
1910        assert_eq!(
1911            account.balance_free(Some(usd)),
1912            Some(Money::new(920_392.0, usd))
1913        );
1914        assert_eq!(account.commission(&usd), Some(Money::new(8.0, usd)));
1915    }
1916
1917    #[rstest]
1918    fn test_update_orders_cash_precision_mismatch_preserves_state() {
1919        let mut cash = multi_currency_cash_account(false);
1920        let usd = Currency::USD();
1921        let mut instrument = audusd_sim();
1922        let instrument_id = instrument.id();
1923        cash.update_balance_locked(instrument_id, Money::from("10 USD"))
1924            .unwrap();
1925        let balances_before = cash.base.balances.clone();
1926        let locks_before = cash.balances_locked.clone();
1927        let events_before = Arc::clone(&cash.base.events);
1928        instrument.quote_currency = Currency::new(
1929            "USD",
1930            usd.precision + 1,
1931            840,
1932            "US Dollar",
1933            CurrencyType::Fiat,
1934        );
1935        let mut order = OrderTestBuilder::new(OrderType::Limit)
1936            .instrument_id(instrument_id)
1937            .side(OrderSide::Buy)
1938            .quantity(Quantity::from("1"))
1939            .price(Price::from("0.75"))
1940            .build();
1941        order
1942            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
1943            .unwrap();
1944        order
1945            .apply(OrderEventAny::Accepted(order_accepted_for(
1946                &order,
1947                VenueOrderId::new("1"),
1948            )))
1949            .unwrap();
1950        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1951        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
1952        let manager = AccountsManager::new(clock, cache);
1953        let mut account = AccountAny::Cash(cash);
1954
1955        let result = manager.update_orders_in_place(
1956            &mut account,
1957            &InstrumentAny::CurrencyPair(instrument),
1958            &[&order],
1959            UnixNanos::default(),
1960        );
1961
1962        assert_eq!(result, None);
1963        let AccountAny::Cash(cash) = account else {
1964            panic!("Expected CashAccount")
1965        };
1966        assert_eq!(cash.base.balances, balances_before);
1967        assert_eq!(cash.balances_locked, locks_before);
1968        assert_eq!(cash.base.events, events_before);
1969    }
1970
1971    // A stale reservation recorded under another instrument passes `reservation_precisions_match`,
1972    // which only inspects incoming reservations, then fails inside `balance_from_locks`.
1973    #[rstest]
1974    fn test_update_orders_cash_error_restores_locks() {
1975        let mut cash = multi_currency_cash_account(false);
1976        let instrument = audusd_sim();
1977        let instrument_id = instrument.id();
1978        cash.update_balance_locked(instrument_id, Money::from("10 USD"))
1979            .unwrap();
1980        cash.balances_locked.insert(
1981            (InstrumentId::from("EURUSD.SIM"), Currency::USD()),
1982            Money::from("-1 USD"),
1983        );
1984        let balances_before = cash.base.balances.clone();
1985        let locks_before = cash.balances_locked.clone();
1986        let events_before = Arc::clone(&cash.base.events);
1987        let mut order = OrderTestBuilder::new(OrderType::Limit)
1988            .instrument_id(instrument_id)
1989            .side(OrderSide::Buy)
1990            .quantity(Quantity::from("1"))
1991            .price(Price::from("0.75"))
1992            .build();
1993        order
1994            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
1995            .unwrap();
1996        order
1997            .apply(OrderEventAny::Accepted(order_accepted_for(
1998                &order,
1999                VenueOrderId::new("1"),
2000            )))
2001            .unwrap();
2002        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2003        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2004        let manager = AccountsManager::new(clock, cache);
2005        let mut account = AccountAny::Cash(cash);
2006
2007        let result = manager.update_orders_in_place(
2008            &mut account,
2009            &InstrumentAny::CurrencyPair(instrument),
2010            &[&order],
2011            UnixNanos::default(),
2012        );
2013
2014        assert_eq!(result, None);
2015        let AccountAny::Cash(cash) = account else {
2016            panic!("Expected CashAccount")
2017        };
2018        assert_eq!(cash.base.balances, balances_before);
2019        assert_eq!(cash.balances_locked, locks_before);
2020        assert_eq!(cash.base.events, events_before);
2021    }
2022
2023    #[rstest]
2024    fn test_update_orders_betting_error_restores_locks() {
2025        let gbp = Currency::GBP();
2026        let account_state = AccountState::new(
2027            AccountId::new("BETTING-001"),
2028            AccountType::Betting,
2029            vec![AccountBalance::new(
2030                Money::from("1000 GBP"),
2031                Money::zero(gbp),
2032                Money::from("1000 GBP"),
2033            )],
2034            Vec::new(),
2035            true,
2036            UUID4::new(),
2037            UnixNanos::default(),
2038            UnixNanos::default(),
2039            None,
2040        );
2041        let mut betting_account = BettingAccount::new(account_state, true);
2042        let instrument = betting();
2043        let instrument_id = instrument.id();
2044        betting_account
2045            .update_balance_locked(instrument_id, Money::from("100 GBP"))
2046            .unwrap();
2047        betting_account.balances_locked.insert(
2048            (
2049                InstrumentId::from("BETFAIR-1.9999999-99999999-0.0.NONE"),
2050                gbp,
2051            ),
2052            Money::from("-1 GBP"),
2053        );
2054        let balances_before = betting_account.base.balances.clone();
2055        let locks_before = betting_account.balances_locked.clone();
2056        let events_before = Arc::clone(&betting_account.base.events);
2057        let mut order = OrderTestBuilder::new(OrderType::Limit)
2058            .instrument_id(instrument_id)
2059            .side(OrderSide::Sell)
2060            .quantity(Quantity::from("50"))
2061            .price(Price::from("2.0"))
2062            .build();
2063        order
2064            .apply(OrderEventAny::Submitted(order_submitted_for_account(
2065                &order,
2066                AccountId::new("BETTING-001"),
2067            )))
2068            .unwrap();
2069        order
2070            .apply(OrderEventAny::Accepted(order_accepted_for_account(
2071                &order,
2072                VenueOrderId::new("1"),
2073                AccountId::new("BETTING-001"),
2074            )))
2075            .unwrap();
2076        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2077        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2078        let manager = AccountsManager::new(clock, cache);
2079        let mut account = AccountAny::Betting(betting_account);
2080
2081        let result = manager.update_orders_in_place(
2082            &mut account,
2083            &InstrumentAny::Betting(instrument),
2084            &[&order],
2085            UnixNanos::default(),
2086        );
2087
2088        assert_eq!(result, None);
2089        let AccountAny::Betting(betting_account) = account else {
2090            panic!("Expected BettingAccount")
2091        };
2092        assert_eq!(betting_account.base.balances, balances_before);
2093        assert_eq!(betting_account.balances_locked, locks_before);
2094        assert_eq!(betting_account.base.events, events_before);
2095    }
2096
2097    #[rstest]
2098    fn test_update_orders_betting_account_uses_liability_for_locked_balance() {
2099        let gbp = Currency::GBP();
2100        let account_state = AccountState::new(
2101            AccountId::new("BETTING-001"),
2102            AccountType::Betting,
2103            vec![AccountBalance::new(
2104                Money::new(1_000.0, gbp),
2105                Money::zero(gbp),
2106                Money::new(1_000.0, gbp),
2107            )],
2108            Vec::new(),
2109            true,
2110            UUID4::new(),
2111            UnixNanos::default(),
2112            UnixNanos::default(),
2113            Some(gbp),
2114        );
2115
2116        let account = BettingAccount::new(account_state, true);
2117
2118        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2119        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2120        cache
2121            .borrow_mut()
2122            .add_account(AccountAny::Betting(account.clone()))
2123            .unwrap();
2124
2125        let manager = AccountsManager::new(clock, cache);
2126        let instrument = betting();
2127
2128        let mut back_order = OrderTestBuilder::new(OrderType::Limit)
2129            .instrument_id(instrument.id())
2130            .side(OrderSide::Buy)
2131            .quantity(Quantity::from("10"))
2132            .price(Price::from("1.25"))
2133            .build();
2134
2135        let mut lay_order = OrderTestBuilder::new(OrderType::Limit)
2136            .instrument_id(instrument.id())
2137            .side(OrderSide::Sell)
2138            .quantity(Quantity::from("12"))
2139            .price(Price::from("3.00"))
2140            .build();
2141
2142        let submitted_back =
2143            order_submitted_for_account(&back_order, AccountId::new("BETTING-001"));
2144        let accepted_back = order_accepted_for_account(
2145            &back_order,
2146            VenueOrderId::new("B1"),
2147            AccountId::new("BETTING-001"),
2148        );
2149        back_order
2150            .apply(OrderEventAny::Submitted(submitted_back))
2151            .unwrap();
2152        back_order
2153            .apply(OrderEventAny::Accepted(accepted_back))
2154            .unwrap();
2155
2156        let submitted_lay = order_submitted_for_account(&lay_order, AccountId::new("BETTING-001"));
2157        let accepted_lay = order_accepted_for_account(
2158            &lay_order,
2159            VenueOrderId::new("L1"),
2160            AccountId::new("BETTING-001"),
2161        );
2162        lay_order
2163            .apply(OrderEventAny::Submitted(submitted_lay))
2164            .unwrap();
2165        lay_order
2166            .apply(OrderEventAny::Accepted(accepted_lay))
2167            .unwrap();
2168
2169        let orders: Vec<&OrderAny> = vec![&back_order, &lay_order];
2170        let result = manager.update_orders(
2171            &AccountAny::Betting(account),
2172            &InstrumentAny::Betting(instrument),
2173            &orders,
2174            UnixNanos::default(),
2175        );
2176
2177        assert!(result.is_some());
2178        let (updated_account, state) = result.unwrap();
2179
2180        if let AccountAny::Betting(betting_account) = updated_account {
2181            assert_eq!(
2182                betting_account.balance_locked(Some(gbp)),
2183                Some(Money::new(14.5, gbp))
2184            );
2185            assert_eq!(
2186                betting_account.balance_free(Some(gbp)),
2187                Some(Money::new(985.5, gbp))
2188            );
2189            assert_eq!(state.account_type, AccountType::Betting);
2190        } else {
2191            panic!("Expected BettingAccount");
2192        }
2193    }
2194
2195    #[rstest]
2196    fn test_update_orders_betting_after_partial_fill() {
2197        let gbp = Currency::GBP();
2198        let account_id = AccountId::new("BETTING-001");
2199        let account_state = AccountState::new(
2200            account_id,
2201            AccountType::Betting,
2202            vec![AccountBalance::new(
2203                Money::new(1_000.0, gbp),
2204                Money::zero(gbp),
2205                Money::new(1_000.0, gbp),
2206            )],
2207            Vec::new(),
2208            true,
2209            UUID4::new(),
2210            UnixNanos::default(),
2211            UnixNanos::default(),
2212            Some(gbp),
2213        );
2214        let account = BettingAccount::new(account_state, true);
2215
2216        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2217        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2218        let manager = AccountsManager::new(clock, cache);
2219        let instrument = betting();
2220
2221        let mut order = OrderTestBuilder::new(OrderType::Limit)
2222            .instrument_id(instrument.id())
2223            .side(OrderSide::Sell)
2224            .quantity(Quantity::from("12"))
2225            .price(Price::from("3.00"))
2226            .build();
2227        order
2228            .apply(OrderEventAny::Submitted(order_submitted_for_account(
2229                &order, account_id,
2230            )))
2231            .unwrap();
2232        order
2233            .apply(OrderEventAny::Accepted(order_accepted_for_account(
2234                &order,
2235                VenueOrderId::new("L1"),
2236                account_id,
2237            )))
2238            .unwrap();
2239        let fill = OrderFilledSpec::builder()
2240            .instrument_id(instrument.id())
2241            .client_order_id(order.client_order_id())
2242            .venue_order_id(VenueOrderId::new("L1"))
2243            .account_id(account_id)
2244            .order_side(OrderSide::Sell)
2245            .order_type(OrderType::Limit)
2246            .last_qty(Quantity::from("5"))
2247            .last_px(Price::from("3.00"))
2248            .position_id(PositionId::new("P-001"))
2249            .build();
2250        order.apply(OrderEventAny::Filled(fill)).unwrap();
2251
2252        let (account, _) = manager
2253            .update_orders(
2254                &AccountAny::Betting(account),
2255                &InstrumentAny::Betting(instrument),
2256                &[&order],
2257                UnixNanos::default(),
2258            )
2259            .unwrap();
2260
2261        assert_eq!(order.leaves_qty(), Quantity::from("7"));
2262        assert_eq!(
2263            account.balance_locked(Some(gbp)),
2264            Some(Money::new(7.0, gbp))
2265        );
2266    }
2267
2268    #[rstest]
2269    fn test_update_orders_betting_precision_mismatch_preserves_state() {
2270        let gbp = Currency::GBP();
2271        let account_state = AccountState::new(
2272            AccountId::new("BETTING-001"),
2273            AccountType::Betting,
2274            vec![AccountBalance::new(
2275                Money::from("1000 GBP"),
2276                Money::zero(gbp),
2277                Money::from("1000 GBP"),
2278            )],
2279            Vec::new(),
2280            true,
2281            UUID4::new(),
2282            UnixNanos::default(),
2283            UnixNanos::default(),
2284            None,
2285        );
2286        let mut betting_account = BettingAccount::new(account_state, true);
2287        let mut instrument = betting();
2288        let instrument_id = instrument.id();
2289        betting_account
2290            .update_balance_locked(instrument_id, Money::from("100 GBP"))
2291            .unwrap();
2292        let balances_before = betting_account.base.balances.clone();
2293        let locks_before = betting_account.balances_locked.clone();
2294        let events_before = Arc::clone(&betting_account.base.events);
2295        instrument.currency = Currency::new(
2296            "GBP",
2297            gbp.precision + 1,
2298            826,
2299            "Pound Sterling",
2300            CurrencyType::Fiat,
2301        );
2302        let mut order = OrderTestBuilder::new(OrderType::Limit)
2303            .instrument_id(instrument_id)
2304            .side(OrderSide::Sell)
2305            .quantity(Quantity::from("50"))
2306            .price(Price::from("2.0"))
2307            .build();
2308        order
2309            .apply(OrderEventAny::Submitted(order_submitted_for_account(
2310                &order,
2311                AccountId::new("BETTING-001"),
2312            )))
2313            .unwrap();
2314        order
2315            .apply(OrderEventAny::Accepted(order_accepted_for_account(
2316                &order,
2317                VenueOrderId::new("1"),
2318                AccountId::new("BETTING-001"),
2319            )))
2320            .unwrap();
2321        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2322        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2323        let manager = AccountsManager::new(clock, cache);
2324        let mut account = AccountAny::Betting(betting_account);
2325
2326        let result = manager.update_orders_in_place(
2327            &mut account,
2328            &InstrumentAny::Betting(instrument),
2329            &[&order],
2330            UnixNanos::default(),
2331        );
2332
2333        assert_eq!(result, None);
2334        let AccountAny::Betting(betting_account) = account else {
2335            panic!("Expected BettingAccount")
2336        };
2337        assert_eq!(betting_account.base.balances, balances_before);
2338        assert_eq!(betting_account.balances_locked, locks_before);
2339        assert_eq!(betting_account.base.events, events_before);
2340    }
2341
2342    #[rstest]
2343    fn test_betting_order_canceled_releases_locked_balance() {
2344        let gbp = Currency::GBP();
2345        let account_state = AccountState::new(
2346            AccountId::new("BETFAIR-001"),
2347            AccountType::Betting,
2348            vec![AccountBalance::new(
2349                Money::new(1_000.0, gbp),
2350                Money::zero(gbp),
2351                Money::new(1_000.0, gbp),
2352            )],
2353            Vec::new(),
2354            true,
2355            UUID4::new(),
2356            UnixNanos::default(),
2357            UnixNanos::default(),
2358            Some(gbp),
2359        );
2360
2361        let account = BettingAccount::new(account_state, true);
2362
2363        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2364        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2365        cache
2366            .borrow_mut()
2367            .add_account(AccountAny::Betting(account.clone()))
2368            .unwrap();
2369
2370        let manager = AccountsManager::new(clock, cache);
2371        let instrument = betting();
2372
2373        let mut order = OrderTestBuilder::new(OrderType::Limit)
2374            .instrument_id(instrument.id())
2375            .side(OrderSide::Buy)
2376            .quantity(Quantity::from("10"))
2377            .price(Price::from("5.0"))
2378            .build();
2379
2380        let submitted = order_submitted_for_account(&order, AccountId::new("BETFAIR-001"));
2381        let accepted = order_accepted_for_account(
2382            &order,
2383            VenueOrderId::new("B2"),
2384            AccountId::new("BETFAIR-001"),
2385        );
2386
2387        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
2388        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
2389
2390        let result = manager.update_orders(
2391            &AccountAny::Betting(account),
2392            &InstrumentAny::Betting(instrument.clone()),
2393            &[&order],
2394            UnixNanos::default(),
2395        );
2396
2397        assert!(result.is_some());
2398        let (updated_account, _) = result.unwrap();
2399
2400        if let AccountAny::Betting(ref betting_account) = updated_account {
2401            assert_eq!(
2402                betting_account.balance_locked(Some(gbp)),
2403                Some(Money::new(40.0, gbp))
2404            );
2405            assert_eq!(
2406                betting_account.balance_free(Some(gbp)),
2407                Some(Money::new(960.0, gbp))
2408            );
2409        } else {
2410            panic!("Expected BettingAccount");
2411        }
2412
2413        let result = manager.update_orders(
2414            &updated_account,
2415            &InstrumentAny::Betting(instrument),
2416            &[],
2417            UnixNanos::default(),
2418        );
2419
2420        assert!(result.is_some());
2421        let (final_account, _) = result.unwrap();
2422
2423        if let AccountAny::Betting(betting_account) = final_account {
2424            assert_eq!(
2425                betting_account.balance_locked(Some(gbp)),
2426                Some(Money::zero(gbp))
2427            );
2428            assert_eq!(
2429                betting_account.balance_free(Some(gbp)),
2430                Some(Money::new(1_000.0, gbp))
2431            );
2432            assert_eq!(
2433                betting_account.balance_total(Some(gbp)),
2434                Some(Money::new(1_000.0, gbp))
2435            );
2436        } else {
2437            panic!("Expected BettingAccount");
2438        }
2439    }
2440
2441    #[rstest]
2442    fn test_update_orders_clears_stale_currency_locks_when_order_sides_change() {
2443        let usd = Currency::USD();
2444        let aud = Currency::AUD();
2445        let account_state = AccountState::new(
2446            AccountId::new("SIM-001"),
2447            AccountType::Cash,
2448            vec![
2449                AccountBalance::new(
2450                    Money::new(1_000_000.0, usd),
2451                    Money::zero(usd),
2452                    Money::new(1_000_000.0, usd),
2453                ),
2454                AccountBalance::new(
2455                    Money::new(1_000_000.0, aud),
2456                    Money::zero(aud),
2457                    Money::new(1_000_000.0, aud),
2458                ),
2459            ],
2460            Vec::new(),
2461            true,
2462            UUID4::new(),
2463            UnixNanos::default(),
2464            UnixNanos::default(),
2465            None,
2466        );
2467
2468        let account = CashAccount::new(account_state, true, false);
2469
2470        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2471        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2472        cache
2473            .borrow_mut()
2474            .add_account(AccountAny::Cash(account.clone()))
2475            .unwrap();
2476
2477        let manager = AccountsManager::new(clock, cache);
2478        let instrument = audusd_sim();
2479
2480        let mut buy_order = OrderTestBuilder::new(OrderType::Limit)
2481            .instrument_id(instrument.id())
2482            .side(OrderSide::Buy)
2483            .quantity(Quantity::from("100000"))
2484            .price(Price::from("0.80000"))
2485            .build();
2486
2487        let mut sell_order = OrderTestBuilder::new(OrderType::Limit)
2488            .instrument_id(instrument.id())
2489            .side(OrderSide::Sell)
2490            .quantity(Quantity::from("50000"))
2491            .price(Price::from("0.81000"))
2492            .build();
2493
2494        // Submit and accept orders
2495        let submitted_buy = order_submitted_for(&buy_order);
2496        let accepted_buy = order_accepted_for(&buy_order, VenueOrderId::new("1"));
2497        buy_order
2498            .apply(OrderEventAny::Submitted(submitted_buy))
2499            .unwrap();
2500        buy_order
2501            .apply(OrderEventAny::Accepted(accepted_buy))
2502            .unwrap();
2503
2504        let submitted_sell = order_submitted_for(&sell_order);
2505        let accepted_sell = order_accepted_for(&sell_order, VenueOrderId::new("2"));
2506        sell_order
2507            .apply(OrderEventAny::Submitted(submitted_sell))
2508            .unwrap();
2509        sell_order
2510            .apply(OrderEventAny::Accepted(accepted_sell))
2511            .unwrap();
2512
2513        let orders_both: Vec<&OrderAny> = vec![&buy_order, &sell_order];
2514        let result = manager.update_orders(
2515            &AccountAny::Cash(account),
2516            &InstrumentAny::CurrencyPair(instrument.clone()),
2517            &orders_both,
2518            UnixNanos::default(),
2519        );
2520
2521        assert!(result.is_some());
2522        let (updated_account, _) = result.unwrap();
2523
2524        if let AccountAny::Cash(cash_account) = &updated_account {
2525            assert_eq!(
2526                cash_account.balance_locked(Some(usd)),
2527                Some(Money::new(80_000.0, usd))
2528            );
2529            assert_eq!(
2530                cash_account.balance_locked(Some(aud)),
2531                Some(Money::new(50_000.0, aud))
2532            );
2533        } else {
2534            panic!("Expected CashAccount");
2535        }
2536
2537        // Cancel BUY order, only SELL remains - USD lock should be cleared
2538        let orders_sell_only: Vec<&OrderAny> = vec![&sell_order];
2539        let result = manager.update_orders(
2540            &updated_account,
2541            &InstrumentAny::CurrencyPair(instrument),
2542            &orders_sell_only,
2543            UnixNanos::default(),
2544        );
2545
2546        assert!(result.is_some());
2547        let (final_account, _) = result.unwrap();
2548
2549        if let AccountAny::Cash(cash_account) = final_account {
2550            assert_eq!(
2551                cash_account.balance_locked(Some(usd)),
2552                Some(Money::zero(usd))
2553            );
2554            assert_eq!(
2555                cash_account.balance_locked(Some(aud)),
2556                Some(Money::new(50_000.0, aud))
2557            );
2558        } else {
2559            panic!("Expected CashAccount");
2560        }
2561    }
2562
2563    #[rstest]
2564    fn test_update_orders_wallet_account_locks_submitted_reduce_only_market_sell() {
2565        let eth = Currency::ETH();
2566        let usdc = Currency::USDC();
2567        let account_state = AccountState::new(
2568            AccountId::new("WALLET-001"),
2569            AccountType::Wallet,
2570            vec![
2571                AccountBalance::new(
2572                    Money::new(10.0, eth),
2573                    Money::zero(eth),
2574                    Money::new(10.0, eth),
2575                ),
2576                AccountBalance::new(
2577                    Money::new(25_000.0, usdc),
2578                    Money::zero(usdc),
2579                    Money::new(25_000.0, usdc),
2580                ),
2581            ],
2582            Vec::new(),
2583            true,
2584            UUID4::new(),
2585            UnixNanos::default(),
2586            UnixNanos::default(),
2587            None,
2588        );
2589
2590        let account = WalletAccount::new(account_state, true);
2591
2592        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2593        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2594        cache
2595            .borrow_mut()
2596            .add_account(AccountAny::Wallet(account.clone()))
2597            .unwrap();
2598
2599        let manager = AccountsManager::new(clock, cache);
2600        let instrument = currency_pair_ethusdt();
2601
2602        let mut sell_order = OrderTestBuilder::new(OrderType::Market)
2603            .instrument_id(instrument.id())
2604            .side(OrderSide::Sell)
2605            .quantity(Quantity::from("2"))
2606            .reduce_only(true)
2607            .build();
2608
2609        let submitted = order_submitted_for(&sell_order);
2610        sell_order
2611            .apply(OrderEventAny::Submitted(submitted))
2612            .unwrap();
2613
2614        let orders: Vec<&OrderAny> = vec![&sell_order];
2615        let result = manager.update_orders(
2616            &AccountAny::Wallet(account),
2617            &InstrumentAny::CurrencyPair(instrument),
2618            &orders,
2619            UnixNanos::default(),
2620        );
2621
2622        assert!(result.is_some());
2623        let (updated_account, state) = result.unwrap();
2624
2625        assert_eq!(state.account_type, AccountType::Wallet);
2626        assert_eq!(state.balances.len(), 2);
2627        let AccountAny::Wallet(wallet_account) = &updated_account else {
2628            panic!("Expected WalletAccount")
2629        };
2630        assert_eq!(
2631            wallet_account.balance_locked(Some(eth)),
2632            Some(Money::new(2.0, eth))
2633        );
2634        assert_eq!(
2635            wallet_account.balance_free(Some(eth)),
2636            Some(Money::new(8.0, eth))
2637        );
2638        assert_eq!(
2639            wallet_account.balance_total(Some(eth)),
2640            Some(Money::new(10.0, eth))
2641        );
2642        assert_eq!(
2643            wallet_account.balance_locked(Some(usdc)),
2644            Some(Money::zero(usdc))
2645        );
2646    }
2647
2648    #[rstest]
2649    fn test_update_orders_wallet_wrong_instrument_preserves_locks() {
2650        let instrument = currency_pair_ethusdt();
2651        let mut wallet = WalletAccount::new(wallet_account_state(), true);
2652        wallet
2653            .update_balance_locked(instrument.id(), Money::from("2 ETH"))
2654            .unwrap();
2655        let mut account = AccountAny::Wallet(wallet);
2656        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2657        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2658        let manager = AccountsManager::new(clock, cache);
2659        let mut order = OrderTestBuilder::new(OrderType::Market)
2660            .instrument_id(currency_pair_btcusdt().id())
2661            .side(OrderSide::Sell)
2662            .quantity(Quantity::from("1"))
2663            .build();
2664        order
2665            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
2666            .unwrap();
2667
2668        let result = manager.update_orders_in_place(
2669            &mut account,
2670            &InstrumentAny::CurrencyPair(instrument),
2671            &[&order],
2672            UnixNanos::default(),
2673        );
2674
2675        assert_eq!(result, None);
2676        let AccountAny::Wallet(wallet) = account else {
2677            panic!("Expected WalletAccount")
2678        };
2679        assert_eq!(
2680            wallet.balance_locked(Some(Currency::ETH())),
2681            Some(Money::from("2 ETH"))
2682        );
2683        assert_eq!(
2684            wallet.balance_free(Some(Currency::ETH())),
2685            Some(Money::from("8 ETH"))
2686        );
2687    }
2688
2689    #[rstest]
2690    fn test_update_orders_wallet_error_restores_locks() {
2691        let instrument = currency_pair_ethusdt();
2692        let mut wallet = WalletAccount::new(wallet_account_state(), true);
2693        wallet
2694            .update_balance_locked(instrument.id(), Money::from("2 ETH"))
2695            .unwrap();
2696        wallet.balances_locked.insert(
2697            (InstrumentId::from("WETHDAI.BLOCKCHAIN"), Currency::ETH()),
2698            Money::from("-1 ETH"),
2699        );
2700        let balances_before = wallet.base.balances.clone();
2701        let locks_before = wallet.balances_locked.clone();
2702        let events_before = Arc::clone(&wallet.events);
2703        let mut account = AccountAny::Wallet(wallet);
2704        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2705        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2706        let manager = AccountsManager::new(clock, cache);
2707        let mut order = OrderTestBuilder::new(OrderType::Market)
2708            .instrument_id(instrument.id())
2709            .side(OrderSide::Sell)
2710            .quantity(Quantity::from("1"))
2711            .build();
2712        order
2713            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
2714            .unwrap();
2715
2716        let result = manager.update_orders_in_place(
2717            &mut account,
2718            &InstrumentAny::CurrencyPair(instrument),
2719            &[&order],
2720            UnixNanos::default(),
2721        );
2722
2723        assert_eq!(result, None);
2724        let AccountAny::Wallet(wallet) = account else {
2725            panic!("Expected WalletAccount")
2726        };
2727        assert_eq!(wallet.base.balances, balances_before);
2728        assert_eq!(wallet.balances_locked, locks_before);
2729        assert_eq!(wallet.events, events_before);
2730    }
2731
2732    #[rstest]
2733    fn test_update_orders_wallet_account_fully_locks_pending_update_debit_currency() {
2734        let account = WalletAccount::new(wallet_account_state(), true);
2735        let account_id = account.id;
2736        let eth = Currency::ETH();
2737        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2738        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2739        cache
2740            .borrow_mut()
2741            .add_account(AccountAny::Wallet(account.clone()))
2742            .unwrap();
2743
2744        let manager = AccountsManager::new(clock, cache);
2745        let instrument = currency_pair_ethusdt();
2746        let mut order = OrderTestBuilder::new(OrderType::Limit)
2747            .instrument_id(instrument.id())
2748            .side(OrderSide::Sell)
2749            .quantity(Quantity::from("2"))
2750            .price(Price::from("3000"))
2751            .build();
2752        order
2753            .apply(OrderEventAny::Submitted(order_submitted_for_account(
2754                &order, account_id,
2755            )))
2756            .unwrap();
2757        let venue_order_id = VenueOrderId::new("1");
2758        order
2759            .apply(OrderEventAny::Accepted(order_accepted_for_account(
2760                &order,
2761                venue_order_id,
2762                account_id,
2763            )))
2764            .unwrap();
2765        let pending_update = OrderPendingUpdateSpec::builder()
2766            .trader_id(order.trader_id())
2767            .strategy_id(order.strategy_id())
2768            .instrument_id(order.instrument_id())
2769            .client_order_id(order.client_order_id())
2770            .account_id(account_id)
2771            .venue_order_id(venue_order_id)
2772            .build();
2773        order
2774            .apply(OrderEventAny::PendingUpdate(pending_update))
2775            .unwrap();
2776
2777        let result = manager.update_orders(
2778            &AccountAny::Wallet(account),
2779            &InstrumentAny::CurrencyPair(instrument),
2780            &[&order],
2781            UnixNanos::default(),
2782        );
2783
2784        let (updated_account, _) = result.unwrap();
2785        let AccountAny::Wallet(wallet) = updated_account else {
2786            panic!("Expected WalletAccount")
2787        };
2788        assert_eq!(wallet.balance_total(Some(eth)), Some(Money::from("10 ETH")));
2789        assert_eq!(
2790            wallet.balance_locked(Some(eth)),
2791            Some(Money::from("10 ETH"))
2792        );
2793        assert_eq!(wallet.balance_free(Some(eth)), Some(Money::from("0 ETH")));
2794    }
2795
2796    #[rstest]
2797    fn test_update_orders_wallet_quanto_pending_update_locks_settlement_currency(
2798        ethbtc_quanto: CryptoFuture,
2799    ) {
2800        let usdt = Currency::USDT();
2801        let total = Money::from("100 USDT");
2802        let account = WalletAccount::new(
2803            AccountState::new(
2804                AccountId::new("WALLET-001"),
2805                AccountType::Wallet,
2806                vec![AccountBalance::new(total, Money::zero(usdt), total)],
2807                Vec::new(),
2808                true,
2809                UUID4::new(),
2810                UnixNanos::default(),
2811                UnixNanos::default(),
2812                None,
2813            ),
2814            true,
2815        );
2816        let account_id = account.id;
2817        let manager = AccountsManager::new(
2818            Rc::new(RefCell::new(VirtualClock::new())),
2819            Rc::new(RefCell::new(Cache::new(None, None))),
2820        );
2821        let mut order = OrderTestBuilder::new(OrderType::Limit)
2822            .instrument_id(ethbtc_quanto.id())
2823            .side(OrderSide::Buy)
2824            .quantity(Quantity::from("5.000"))
2825            .price(Price::from("0.03600"))
2826            .build();
2827        order
2828            .apply(OrderEventAny::Submitted(order_submitted_for_account(
2829                &order, account_id,
2830            )))
2831            .unwrap();
2832        let venue_order_id = VenueOrderId::new("1");
2833        order
2834            .apply(OrderEventAny::Accepted(order_accepted_for_account(
2835                &order,
2836                venue_order_id,
2837                account_id,
2838            )))
2839            .unwrap();
2840        let pending_update = OrderPendingUpdateSpec::builder()
2841            .trader_id(order.trader_id())
2842            .strategy_id(order.strategy_id())
2843            .instrument_id(order.instrument_id())
2844            .client_order_id(order.client_order_id())
2845            .account_id(account_id)
2846            .venue_order_id(venue_order_id)
2847            .build();
2848        order
2849            .apply(OrderEventAny::PendingUpdate(pending_update))
2850            .unwrap();
2851
2852        let (updated_account, _) = manager
2853            .update_orders(
2854                &AccountAny::Wallet(account),
2855                &InstrumentAny::CryptoFuture(ethbtc_quanto),
2856                &[&order],
2857                UnixNanos::default(),
2858            )
2859            .unwrap();
2860
2861        assert_eq!(updated_account.balance_locked(Some(usdt)), Some(total));
2862        assert_eq!(
2863            updated_account.balance_free(Some(usdt)),
2864            Some(Money::zero(usdt))
2865        );
2866    }
2867
2868    #[rstest]
2869    fn test_update_orders_wallet_preserves_dex_terms_at_observed_precision() {
2870        let Some((wallet, instrument, base, quote)) = wallet_precision_pair(18) else {
2871            return;
2872        };
2873        let mut sell = OrderTestBuilder::new(OrderType::Market)
2874            .instrument_id(instrument.id())
2875            .side(OrderSide::Sell)
2876            .quantity(Quantity::from_raw(1_234_567_890_123_456, 16))
2877            .build();
2878        let mut buy = OrderTestBuilder::new(OrderType::Limit)
2879            .instrument_id(instrument.id())
2880            .side(OrderSide::Buy)
2881            .quantity(Quantity::from_raw(1_000_000_000_000_000, 16))
2882            .price(Price::from_raw(1_234_567_890_123_456, 16))
2883            .build();
2884        let mut buy_quote = OrderTestBuilder::new(OrderType::Market)
2885            .instrument_id(instrument.id())
2886            .side(OrderSide::Buy)
2887            .quantity(Quantity::from_raw(1_234_567_890_123_456, 16))
2888            .quote_quantity(true)
2889            .build();
2890        sell.apply(OrderEventAny::Submitted(order_submitted_for(&sell)))
2891            .unwrap();
2892        buy.apply(OrderEventAny::Submitted(order_submitted_for(&buy)))
2893            .unwrap();
2894        buy_quote
2895            .apply(OrderEventAny::Submitted(order_submitted_for(&buy_quote)))
2896            .unwrap();
2897        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2898        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2899        let manager = AccountsManager::new(clock, cache);
2900
2901        let result = manager.update_orders(
2902            &AccountAny::Wallet(wallet),
2903            &InstrumentAny::CurrencyPair(instrument),
2904            &[&sell, &buy, &buy_quote],
2905            UnixNanos::default(),
2906        );
2907
2908        let (AccountAny::Wallet(wallet), _) = result.unwrap() else {
2909            panic!("Expected WalletAccount")
2910        };
2911        let base_balance = wallet.balance(Some(base)).unwrap();
2912        let quote_balance = wallet.balance(Some(quote)).unwrap();
2913        assert_eq!(base_balance.currency.precision, 18);
2914        assert_eq!(base_balance.total.raw(), 1_000_000_000_000_000_000);
2915        assert_eq!(base_balance.locked.raw(), 123_456_789_012_345_600);
2916        assert_eq!(base_balance.free.raw(), 876_543_210_987_654_400);
2917        assert_eq!(quote_balance.currency.precision, 18);
2918        assert_eq!(quote_balance.total.raw(), 2_000_000_000_000_000_000);
2919        assert_eq!(quote_balance.locked.raw(), 135_802_467_913_580_160);
2920        assert_eq!(quote_balance.free.raw(), 1_864_197_532_086_419_840);
2921    }
2922
2923    #[rstest]
2924    fn test_update_orders_wallet_uses_observed_currency_grid() {
2925        let Some((wallet, instrument, base, quote)) = wallet_precision_pair(6) else {
2926            return;
2927        };
2928        let mut sell = OrderTestBuilder::new(OrderType::Market)
2929            .instrument_id(instrument.id())
2930            .side(OrderSide::Sell)
2931            .quantity(Quantity::from_raw(1_234_560_000_000_000, 16))
2932            .build();
2933        let mut buy = OrderTestBuilder::new(OrderType::Limit)
2934            .instrument_id(instrument.id())
2935            .side(OrderSide::Buy)
2936            .quantity(Quantity::from_raw(1_000_000_000_000_000, 16))
2937            .price(Price::from_raw(12_345_670_000_000_000, 16))
2938            .build();
2939        let mut buy_quote = OrderTestBuilder::new(OrderType::Market)
2940            .instrument_id(instrument.id())
2941            .side(OrderSide::Buy)
2942            .quantity(Quantity::from_raw(2_345_670_000_000_000, 16))
2943            .quote_quantity(true)
2944            .build();
2945        sell.apply(OrderEventAny::Submitted(order_submitted_for(&sell)))
2946            .unwrap();
2947        buy.apply(OrderEventAny::Submitted(order_submitted_for(&buy)))
2948            .unwrap();
2949        buy_quote
2950            .apply(OrderEventAny::Submitted(order_submitted_for(&buy_quote)))
2951            .unwrap();
2952        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2953        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2954        let manager = AccountsManager::new(clock, cache);
2955        let scale = money_raw(10_i128.pow(u32::from(FIXED_PRECISION)));
2956        let grid = money_raw(10_i128.pow(u32::from(FIXED_PRECISION - quote.precision)));
2957
2958        let result = manager.update_orders(
2959            &AccountAny::Wallet(wallet),
2960            &InstrumentAny::CurrencyPair(instrument),
2961            &[&sell, &buy, &buy_quote],
2962            UnixNanos::default(),
2963        );
2964
2965        let (AccountAny::Wallet(wallet), _) = result.unwrap() else {
2966            panic!("Expected WalletAccount")
2967        };
2968        let base_balance = wallet.balance(Some(base)).unwrap();
2969        let quote_balance = wallet.balance(Some(quote)).unwrap();
2970        assert_eq!(base_balance.currency.precision, 6);
2971        assert_eq!(base_balance.total.raw(), scale);
2972        assert_eq!(base_balance.locked.raw(), 123_456 * grid);
2973        assert_eq!(base_balance.free.raw(), scale - 123_456 * grid);
2974        assert_eq!(quote_balance.currency.precision, 6);
2975        assert_eq!(quote_balance.total.raw(), 2 * scale);
2976        assert_eq!(quote_balance.locked.raw(), 358_024 * grid);
2977        assert_eq!(quote_balance.free.raw(), 2 * scale - 358_024 * grid);
2978    }
2979
2980    #[rstest]
2981    #[case::sell(OrderSide::Sell, false, 1, 18, 10_000_000_000_000_000)]
2982    #[case::buy_quote(OrderSide::Buy, true, 1, 18, 10_000_000_000_000_000)]
2983    #[case::sell_currency_grid(OrderSide::Sell, false, 1, 16, 10_000_000_000_000_000)]
2984    #[case::buy_quote_currency_grid(OrderSide::Buy, true, 1, 16, 10_000_000_000_000_000)]
2985    fn test_update_orders_wallet_explicit_quantity_loss_preserves_state(
2986        #[case] side: OrderSide,
2987        #[case] quote_quantity: bool,
2988        #[case] quantity_raw: u128,
2989        #[case] quantity_precision: u8,
2990        #[case] price_raw: i128,
2991    ) {
2992        let wallet_precision = if quantity_precision == 18 { 16 } else { 6 };
2993        let Some((mut wallet, instrument, base, _)) = wallet_precision_pair(wallet_precision)
2994        else {
2995            return;
2996        };
2997        let grid =
2998            money_raw(10_i128.pow(u32::from(FIXED_PRECISION.saturating_sub(wallet_precision))));
2999        wallet
3000            .update_balance_locked(
3001                InstrumentId::from("OTHER.BLOCKCHAIN"),
3002                Money::from_raw(grid, base),
3003            )
3004            .unwrap();
3005        let balances_before = wallet.base.balances.clone();
3006        let locks_before = wallet.balances_locked.clone();
3007        let events_before = Arc::clone(&wallet.events);
3008        let mut account = AccountAny::Wallet(wallet);
3009        #[allow(
3010            clippy::useless_conversion,
3011            reason = "the test input width differs when high-precision is disabled"
3012        )]
3013        let quantity_raw = quantity_raw.try_into().unwrap();
3014        #[allow(
3015            clippy::useless_conversion,
3016            reason = "the test input width differs when high-precision is disabled"
3017        )]
3018        let price_raw = price_raw.try_into().unwrap();
3019        let mut order = OrderTestBuilder::new(OrderType::Limit)
3020            .instrument_id(instrument.id())
3021            .side(side)
3022            .quantity(Quantity::from_raw(quantity_raw, quantity_precision))
3023            .price(Price::from_raw(price_raw, 16))
3024            .quote_quantity(quote_quantity)
3025            .build();
3026        order
3027            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3028            .unwrap();
3029        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3030        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3031        let manager = AccountsManager::new(clock, cache);
3032
3033        let result = manager.update_orders_in_place(
3034            &mut account,
3035            &InstrumentAny::CurrencyPair(instrument),
3036            &[&order],
3037            UnixNanos::default(),
3038        );
3039
3040        assert_eq!(result, None);
3041        let AccountAny::Wallet(wallet) = account else {
3042            panic!("Expected WalletAccount")
3043        };
3044        assert_eq!(wallet.base.balances, balances_before);
3045        assert_eq!(wallet.balances_locked, locks_before);
3046        assert_eq!(wallet.events, events_before);
3047    }
3048
3049    #[rstest]
3050    fn test_update_orders_wallet_aggregate_overflow_preserves_state() {
3051        let Some((mut wallet, instrument, base, _)) = wallet_precision_pair(16) else {
3052            return;
3053        };
3054        wallet
3055            .update_balance_locked(
3056                InstrumentId::from("OTHER.BLOCKCHAIN"),
3057                Money::from_raw(1_000, base),
3058            )
3059            .unwrap();
3060        let balances_before = wallet.base.balances.clone();
3061        let locks_before = wallet.balances_locked.clone();
3062        let events_before = Arc::clone(&wallet.events);
3063        let mut account = AccountAny::Wallet(wallet);
3064        let quantity_raw = MONEY_RAW_MAX.try_into().unwrap();
3065        let mut first = OrderTestBuilder::new(OrderType::Market)
3066            .instrument_id(instrument.id())
3067            .side(OrderSide::Buy)
3068            .quantity(Quantity::from_raw(quantity_raw, 16))
3069            .quote_quantity(true)
3070            .build();
3071        let mut second = OrderTestBuilder::new(OrderType::Market)
3072            .instrument_id(instrument.id())
3073            .side(OrderSide::Buy)
3074            .quantity(Quantity::from_raw(quantity_raw, 16))
3075            .quote_quantity(true)
3076            .build();
3077        first
3078            .apply(OrderEventAny::Submitted(order_submitted_for(&first)))
3079            .unwrap();
3080        second
3081            .apply(OrderEventAny::Submitted(order_submitted_for(&second)))
3082            .unwrap();
3083        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3084        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3085        let manager = AccountsManager::new(clock, cache);
3086
3087        let result = manager.update_orders_in_place(
3088            &mut account,
3089            &InstrumentAny::CurrencyPair(instrument),
3090            &[&first, &second],
3091            UnixNanos::default(),
3092        );
3093
3094        assert_eq!(result, None);
3095        let AccountAny::Wallet(wallet) = account else {
3096            panic!("Expected WalletAccount")
3097        };
3098        assert_eq!(wallet.base.balances, balances_before);
3099        assert_eq!(wallet.balances_locked, locks_before);
3100        assert_eq!(wallet.events, events_before);
3101    }
3102
3103    #[rstest]
3104    fn test_update_orders_margin_init_xrate_unavailable_returns_none() {
3105        let eur = Currency::EUR();
3106        let account_state = AccountState::new(
3107            AccountId::new("SIM-001"),
3108            AccountType::Margin,
3109            vec![AccountBalance::new(
3110                Money::new(1_000_000.0, eur),
3111                Money::zero(eur),
3112                Money::new(1_000_000.0, eur),
3113            )],
3114            Vec::new(),
3115            true,
3116            UUID4::new(),
3117            UnixNanos::default(),
3118            UnixNanos::default(),
3119            Some(eur),
3120        );
3121        let mut account = MarginAccount::new(account_state, true);
3122        let instrument = audusd_sim();
3123        let prior_margin = Money::new(10.0, eur);
3124        account.update_initial_margin(instrument.id(), prior_margin);
3125
3126        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3127        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3128        let manager = AccountsManager::new(clock, cache);
3129
3130        let mut order = OrderTestBuilder::new(OrderType::Limit)
3131            .instrument_id(instrument.id())
3132            .side(OrderSide::Buy)
3133            .quantity(Quantity::from("100000"))
3134            .price(Price::from("0.80000"))
3135            .build();
3136
3137        let submitted = order_submitted_for(&order);
3138        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
3139        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
3140        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
3141
3142        let mut account = AccountAny::Margin(account);
3143        let result = manager.update_orders_in_place(
3144            &mut account,
3145            &InstrumentAny::CurrencyPair(instrument.clone()),
3146            &[&order],
3147            UnixNanos::default(),
3148        );
3149
3150        assert!(result.is_none(), "xrate-unavailable must return None");
3151
3152        match account {
3153            AccountAny::Margin(margin_account) => {
3154                assert_eq!(margin_account.initial_margin(instrument.id()), prior_margin);
3155                assert_eq!(margin_account.balance_locked(Some(eur)), Some(prior_margin));
3156            }
3157            _ => panic!("Expected MarginAccount"),
3158        }
3159    }
3160
3161    #[rstest]
3162    fn test_update_balance_locked_quanto_locks_settlement_balance(ethbtc_quanto: CryptoFuture) {
3163        let usdt = Currency::USDT();
3164        let account_state = AccountState::new(
3165            AccountId::new("SIM-001"),
3166            AccountType::Cash,
3167            vec![AccountBalance::new(
3168                Money::new(1_000.0, usdt),
3169                Money::zero(usdt),
3170                Money::new(1_000.0, usdt),
3171            )],
3172            Vec::new(),
3173            true,
3174            UUID4::new(),
3175            UnixNanos::default(),
3176            UnixNanos::default(),
3177            None,
3178        );
3179        let account = CashAccount::new(account_state, true, false);
3180        let manager = AccountsManager::new(
3181            Rc::new(RefCell::new(VirtualClock::new())),
3182            Rc::new(RefCell::new(Cache::new(None, None))),
3183        );
3184        let mut order = OrderTestBuilder::new(OrderType::Limit)
3185            .instrument_id(ethbtc_quanto.id())
3186            .side(OrderSide::Buy)
3187            .quantity(Quantity::from("100.000"))
3188            .price(Price::from("0.05000"))
3189            .build();
3190        order
3191            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3192            .unwrap();
3193        order
3194            .apply(OrderEventAny::Accepted(order_accepted_for(
3195                &order,
3196                VenueOrderId::new("1"),
3197            )))
3198            .unwrap();
3199
3200        let (updated_account, _) = manager
3201            .update_orders(
3202                &AccountAny::Cash(account),
3203                &InstrumentAny::CryptoFuture(ethbtc_quanto),
3204                &[&order],
3205                UnixNanos::default(),
3206            )
3207            .unwrap();
3208
3209        // notional = 100 * 0.05 = 5 USDT
3210        assert_eq!(
3211            updated_account.balance_locked(Some(usdt)),
3212            Some(Money::new(5.0, usdt))
3213        );
3214        assert_eq!(
3215            updated_account.balance_free(Some(usdt)),
3216            Some(Money::new(995.0, usdt))
3217        );
3218    }
3219
3220    #[rstest]
3221    fn test_cash_balance_preserves_native_increment_near_limit() {
3222        let currency = Currency::USD();
3223        let total = Money::from_raw(MONEY_RAW_MAX - 100, currency);
3224        let mut cash = CashAccount::default();
3225        cash.update_balances(&[AccountBalance::new(total, Money::zero(currency), total)])
3226            .unwrap();
3227        let mut account = AccountAny::Cash(cash);
3228        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3229        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3230        let manager = AccountsManager::new(clock, cache);
3231        let fill = OrderFilledSpec::builder()
3232            .instrument_id(audusd_sim().id())
3233            .commission(Money::zero(currency))
3234            .build();
3235        let pnl = Money::from_raw(1, currency);
3236
3237        let updated = manager
3238            .update_balance_single_currency(&mut account, &fill, pnl)
3239            .unwrap();
3240
3241        let expected = Money::from_raw(MONEY_RAW_MAX - 99, currency);
3242        assert!(updated);
3243        assert_eq!(
3244            account.balance(Some(currency)).copied(),
3245            Some(AccountBalance::new(
3246                expected,
3247                Money::zero(currency),
3248                expected
3249            )),
3250        );
3251    }
3252
3253    #[rstest]
3254    fn test_cash_conversion_preserves_native_precision() {
3255        let currency = Currency::EUR();
3256        let total = Money::from("1 EUR");
3257
3258        let state = AccountState::new(
3259            AccountId::new("SIM-001"),
3260            AccountType::Cash,
3261            vec![AccountBalance::new(total, Money::zero(currency), total)],
3262            Vec::new(),
3263            true,
3264            UUID4::new(),
3265            UnixNanos::default(),
3266            UnixNanos::default(),
3267            Some(currency),
3268        );
3269        let account = CashAccount::new(state, true, false);
3270        let mut account = AccountAny::Cash(account);
3271        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3272        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3273        add_usdeur_quote(&cache, "0.90000", "1.10000");
3274        let manager = AccountsManager::new(clock, cache);
3275        let fill = OrderFilledSpec::builder()
3276            .instrument_id(audusd_sim().id())
3277            .order_side(OrderSide::Buy)
3278            .last_qty(Quantity::from("0.01"))
3279            .last_px(Price::from("0.1234"))
3280            .commission(Money::from_str_exact("0.000001 USD").unwrap())
3281            .build();
3282        let pnl = Money::from_str_exact("0.000002 USD").unwrap();
3283
3284        let updated = manager
3285            .update_balance_single_currency(&mut account, &fill, pnl)
3286            .unwrap();
3287
3288        let AccountAny::Cash(account) = account else {
3289            panic!("Expected CashAccount");
3290        };
3291
3292        let total = Money::from_str_exact("1.0000011 EUR").unwrap();
3293        assert!(updated);
3294        assert_eq!(
3295            account.balance(Some(currency)).copied(),
3296            Some(AccountBalance::new(total, Money::zero(currency), total)),
3297        );
3298        assert_eq!(
3299            account.commission(&currency),
3300            Some(Money::from_str_exact("0.0000011 EUR").unwrap()),
3301        );
3302    }
3303
3304    #[rstest]
3305    #[case("100", "2.00000", "180 EUR", "820 EUR")]
3306    #[case("0.01", "0.12340", "0.0011106 EUR", "999.9988894 EUR")]
3307    fn test_update_balance_locked_base_xrate_uses_bid_for_buy_order(
3308        #[case] qty: &str,
3309        #[case] price: &str,
3310        #[case] locked: &str,
3311        #[case] free: &str,
3312    ) {
3313        let eur = Currency::EUR();
3314        let account_state = AccountState::new(
3315            AccountId::new("SIM-001"),
3316            AccountType::Cash,
3317            vec![AccountBalance::new(
3318                Money::new(1_000.0, eur),
3319                Money::zero(eur),
3320                Money::new(1_000.0, eur),
3321            )],
3322            Vec::new(),
3323            true,
3324            UUID4::new(),
3325            UnixNanos::default(),
3326            UnixNanos::default(),
3327            Some(eur),
3328        );
3329        let account = CashAccount::new(account_state, true, false);
3330
3331        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3332        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3333        add_usdeur_quote(&cache, "0.90000", "1.10000");
3334        let manager = AccountsManager::new(clock, cache);
3335
3336        let instrument = audusd_sim();
3337        let mut order = OrderTestBuilder::new(OrderType::Limit)
3338            .instrument_id(instrument.id())
3339            .side(OrderSide::Buy)
3340            .quantity(Quantity::from(qty))
3341            .price(Price::from(price))
3342            .build();
3343
3344        let submitted = order_submitted_for(&order);
3345        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
3346        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
3347        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
3348
3349        let result = manager.update_orders(
3350            &AccountAny::Cash(account),
3351            &InstrumentAny::CurrencyPair(instrument),
3352            &[&order],
3353            UnixNanos::default(),
3354        );
3355
3356        assert!(result.is_some());
3357        let (updated_account, _) = result.unwrap();
3358
3359        match updated_account {
3360            AccountAny::Cash(cash) => {
3361                assert_eq!(
3362                    cash.balance(Some(eur)).copied(),
3363                    Some(AccountBalance::new(
3364                        Money::from("1000 EUR"),
3365                        Money::from_str_exact(locked).unwrap(),
3366                        Money::from_str_exact(free).unwrap(),
3367                    )),
3368                );
3369            }
3370            _ => panic!("Expected CashAccount"),
3371        }
3372    }
3373
3374    #[rstest]
3375    fn test_update_balance_locked_converts_each_calculated_currency() {
3376        let eur = Currency::EUR();
3377        let account_state = AccountState::new(
3378            AccountId::new("SIM-001"),
3379            AccountType::Cash,
3380            vec![AccountBalance::new(
3381                Money::new(1_000.0, eur),
3382                Money::zero(eur),
3383                Money::new(1_000.0, eur),
3384            )],
3385            Vec::new(),
3386            true,
3387            UUID4::new(),
3388            UnixNanos::default(),
3389            UnixNanos::default(),
3390            Some(eur),
3391        );
3392        let account = CashAccount::new(account_state, true, false);
3393        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3394        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3395        add_usdeur_quote(&cache, "0.90000", "1.10000");
3396        let etheur = default_fx_ccy(Symbol::from("ETH/EUR"), Some(Venue::from("SIM")));
3397        cache
3398            .borrow_mut()
3399            .add_instrument(InstrumentAny::CurrencyPair(etheur.clone()))
3400            .unwrap();
3401        cache
3402            .borrow_mut()
3403            .add_quote(QuoteTick::new(
3404                etheur.id(),
3405                Price::from("40.00000"),
3406                Price::from("50.00000"),
3407                Quantity::from("1"),
3408                Quantity::from("1"),
3409                UnixNanos::default(),
3410                UnixNanos::default(),
3411            ))
3412            .unwrap();
3413        let manager = AccountsManager::new(clock, cache);
3414        let instrument = usd_usdt_future();
3415        let mut buy_order = OrderTestBuilder::new(OrderType::Limit)
3416            .instrument_id(instrument.id())
3417            .side(OrderSide::Buy)
3418            .quantity(Quantity::from("2"))
3419            .price(Price::from("100.00"))
3420            .build();
3421        buy_order
3422            .apply(OrderEventAny::Submitted(order_submitted_for(&buy_order)))
3423            .unwrap();
3424        buy_order
3425            .apply(OrderEventAny::Accepted(order_accepted_for(
3426                &buy_order,
3427                VenueOrderId::new("1"),
3428            )))
3429            .unwrap();
3430        let mut sell_order = OrderTestBuilder::new(OrderType::Limit)
3431            .instrument_id(instrument.id())
3432            .side(OrderSide::Sell)
3433            .quantity(Quantity::from("3"))
3434            .price(Price::from("100.00"))
3435            .build();
3436        sell_order
3437            .apply(OrderEventAny::Submitted(order_submitted_for(&sell_order)))
3438            .unwrap();
3439        sell_order
3440            .apply(OrderEventAny::Accepted(order_accepted_for(
3441                &sell_order,
3442                VenueOrderId::new("2"),
3443            )))
3444            .unwrap();
3445
3446        let result = manager.update_orders(
3447            &AccountAny::Cash(account),
3448            &InstrumentAny::CryptoFuture(instrument),
3449            &[&buy_order, &sell_order],
3450            UnixNanos::default(),
3451        );
3452
3453        let (updated_account, _) =
3454            result.expect("USD and ETH locked balances should convert to EUR");
3455        let AccountAny::Cash(cash) = updated_account else {
3456            panic!("Expected CashAccount");
3457        };
3458        assert_eq!(cash.balance_locked(Some(eur)), Some(Money::new(330.0, eur)));
3459    }
3460
3461    #[rstest]
3462    fn test_update_balance_locked_fails_closed_on_money_overflow() {
3463        let usd = Currency::USD();
3464        let account_state = AccountState::new(
3465            AccountId::new("SIM-001"),
3466            AccountType::Cash,
3467            vec![AccountBalance::new(
3468                Money::new(1_000.0, usd),
3469                Money::zero(usd),
3470                Money::new(1_000.0, usd),
3471            )],
3472            Vec::new(),
3473            true,
3474            UUID4::new(),
3475            UnixNanos::default(),
3476            UnixNanos::default(),
3477            None,
3478        );
3479        let mut account = AccountAny::Cash(CashAccount::new(account_state, true, false));
3480        let instrument = audusd_sim();
3481        let open_order = |side: OrderSide, quantity: Quantity, venue_order_id: &str| {
3482            let mut order = OrderTestBuilder::new(OrderType::Limit)
3483                .instrument_id(instrument.id())
3484                .side(side)
3485                .quantity(quantity)
3486                .price(Price::from("1.00000"))
3487                .build();
3488            order
3489                .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3490                .unwrap();
3491            order
3492                .apply(OrderEventAny::Accepted(order_accepted_for(
3493                    &order,
3494                    VenueOrderId::new(venue_order_id),
3495                )))
3496                .unwrap();
3497            order
3498        };
3499        let half_max = Quantity::new(MONEY_MAX / 2.0 + 1.0, 0);
3500        let first = open_order(OrderSide::Buy, half_max, "1");
3501        let second = open_order(OrderSide::Buy, half_max, "2");
3502        let out_of_range = open_order(OrderSide::Sell, Quantity::new(MONEY_MAX + 1.0, 0), "3");
3503        let manager = AccountsManager::new(
3504            Rc::new(RefCell::new(VirtualClock::new())),
3505            Rc::new(RefCell::new(Cache::new(None, None))),
3506        );
3507
3508        let total_overflow = manager.update_orders_in_place(
3509            &mut account,
3510            &InstrumentAny::CurrencyPair(instrument.clone()),
3511            &[&first, &second],
3512            UnixNanos::default(),
3513        );
3514        let calculation_overflow = manager.update_orders_in_place(
3515            &mut account,
3516            &InstrumentAny::CurrencyPair(instrument),
3517            &[&out_of_range],
3518            UnixNanos::default(),
3519        );
3520
3521        assert!(total_overflow.is_none());
3522        assert!(calculation_overflow.is_none());
3523        let AccountAny::Cash(account) = account else {
3524            panic!("Expected CashAccount");
3525        };
3526        assert_eq!(account.balance_locked(Some(usd)), Some(Money::zero(usd)));
3527    }
3528
3529    #[rstest]
3530    fn test_update_betting_balance_locked_fails_closed_on_money_overflow() {
3531        let gbp = Currency::GBP();
3532        let account_state = AccountState::new(
3533            AccountId::new("BETTING-001"),
3534            AccountType::Betting,
3535            vec![AccountBalance::new(
3536                Money::new(1_000.0, gbp),
3537                Money::zero(gbp),
3538                Money::new(1_000.0, gbp),
3539            )],
3540            Vec::new(),
3541            true,
3542            UUID4::new(),
3543            UnixNanos::default(),
3544            UnixNanos::default(),
3545            Some(gbp),
3546        );
3547        let mut account = AccountAny::Betting(BettingAccount::new(account_state, true));
3548        let instrument = betting();
3549        let open_order = |quantity: Quantity, venue_order_id: &str| {
3550            let mut order = OrderTestBuilder::new(OrderType::Limit)
3551                .instrument_id(instrument.id())
3552                .side(OrderSide::Sell)
3553                .quantity(quantity)
3554                .price(Price::from("2.00"))
3555                .build();
3556            order
3557                .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3558                .unwrap();
3559            order
3560                .apply(OrderEventAny::Accepted(order_accepted_for(
3561                    &order,
3562                    VenueOrderId::new(venue_order_id),
3563                )))
3564                .unwrap();
3565            order
3566        };
3567        let half_max = Quantity::new(MONEY_MAX / 2.0 + 1.0, 0);
3568        let first = open_order(half_max, "1");
3569        let second = open_order(half_max, "2");
3570        let out_of_range = open_order(Quantity::new(MONEY_MAX + 1.0, 0), "3");
3571        let manager = AccountsManager::new(
3572            Rc::new(RefCell::new(VirtualClock::new())),
3573            Rc::new(RefCell::new(Cache::new(None, None))),
3574        );
3575
3576        let total_overflow = manager.update_orders_in_place(
3577            &mut account,
3578            &InstrumentAny::Betting(instrument.clone()),
3579            &[&first, &second],
3580            UnixNanos::default(),
3581        );
3582        let calculation_overflow = manager.update_orders_in_place(
3583            &mut account,
3584            &InstrumentAny::Betting(instrument),
3585            &[&out_of_range],
3586            UnixNanos::default(),
3587        );
3588
3589        assert!(total_overflow.is_none());
3590        assert!(calculation_overflow.is_none());
3591        let AccountAny::Betting(account) = account else {
3592            panic!("Expected BettingAccount");
3593        };
3594        assert_eq!(account.balance_locked(Some(gbp)), Some(Money::zero(gbp)));
3595    }
3596
3597    #[rstest]
3598    #[case(
3599        Some(Currency::EUR()),
3600        Currency::EUR(),
3601        Money::new(18.0, Currency::EUR())
3602    )]
3603    #[case(None, Currency::USD(), Money::new(20.0, Currency::USD()))]
3604    fn test_update_margins_use_calculated_currency(
3605        #[case] base_currency: Option<Currency>,
3606        #[case] balance_currency: Currency,
3607        #[case] expected_margin: Money,
3608    ) {
3609        let account_state = AccountState::new(
3610            AccountId::new("SIM-001"),
3611            AccountType::Margin,
3612            vec![AccountBalance::new(
3613                Money::new(1_000.0, balance_currency),
3614                Money::zero(balance_currency),
3615                Money::new(1_000.0, balance_currency),
3616            )],
3617            Vec::new(),
3618            true,
3619            UUID4::new(),
3620            UnixNanos::default(),
3621            UnixNanos::default(),
3622            base_currency,
3623        );
3624        let account = MarginAccount::new(account_state, true);
3625        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3626        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3627        add_usdeur_quote(&cache, "0.90000", "1.10000");
3628        let manager = AccountsManager::new(clock, cache);
3629        let instrument = usd_usdt_future();
3630        let instrument_any = InstrumentAny::CryptoFuture(instrument.clone());
3631        let mut order = OrderTestBuilder::new(OrderType::Limit)
3632            .instrument_id(instrument.id())
3633            .side(OrderSide::Buy)
3634            .quantity(Quantity::from("2"))
3635            .price(Price::from("100.00"))
3636            .build();
3637        order
3638            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3639            .unwrap();
3640        order
3641            .apply(OrderEventAny::Accepted(order_accepted_for(
3642                &order,
3643                VenueOrderId::new("1"),
3644            )))
3645            .unwrap();
3646
3647        let (updated_account, _) = manager
3648            .update_orders(
3649                &AccountAny::Margin(account),
3650                &instrument_any,
3651                &[&order],
3652                UnixNanos::default(),
3653            )
3654            .expect("USD initial margin should convert to EUR");
3655        let AccountAny::Margin(mut account) = updated_account else {
3656            panic!("Expected MarginAccount");
3657        };
3658        let position = build_hedging_position(&instrument_any, OrderSide::Buy, "2", "100.00", "P");
3659
3660        manager
3661            .update_positions_in_place(
3662                &mut account,
3663                &instrument_any,
3664                vec![&position],
3665                UnixNanos::default(),
3666            )
3667            .expect("USD maintenance margin should convert to EUR");
3668
3669        assert_eq!(account.initial_margin(instrument.id()), expected_margin);
3670        assert_eq!(account.maintenance_margin(instrument.id()), expected_margin);
3671    }
3672
3673    #[rstest]
3674    fn test_update_margins_reject_calculated_currency_change() {
3675        let usdt = Currency::USDT();
3676        let instrument = usd_usdt_future();
3677        let prior_margin = MarginBalance::new(
3678            Money::new(10.0, usdt),
3679            Money::new(5.0, usdt),
3680            Some(instrument.id()),
3681        );
3682        let account_state = AccountState::new(
3683            AccountId::new("SIM-001"),
3684            AccountType::Margin,
3685            vec![AccountBalance::new(
3686                Money::new(1_000.0, usdt),
3687                Money::new(15.0, usdt),
3688                Money::new(985.0, usdt),
3689            )],
3690            vec![prior_margin],
3691            true,
3692            UUID4::new(),
3693            UnixNanos::default(),
3694            UnixNanos::default(),
3695            None,
3696        );
3697        let mut account = MarginAccount::new(account_state, true);
3698        let manager = AccountsManager::new(
3699            Rc::new(RefCell::new(VirtualClock::new())),
3700            Rc::new(RefCell::new(Cache::new(None, None))),
3701        );
3702        let instrument_any = InstrumentAny::CryptoFuture(instrument.clone());
3703        let mut order = OrderTestBuilder::new(OrderType::Limit)
3704            .instrument_id(instrument.id())
3705            .side(OrderSide::Buy)
3706            .quantity(Quantity::from("2"))
3707            .price(Price::from("100.00"))
3708            .build();
3709        order
3710            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3711            .unwrap();
3712        order
3713            .apply(OrderEventAny::Accepted(order_accepted_for(
3714                &order,
3715                VenueOrderId::new("1"),
3716            )))
3717            .unwrap();
3718        let position = build_hedging_position(&instrument_any, OrderSide::Buy, "2", "100.00", "P");
3719
3720        let initial_result = manager.update_margin_init(
3721            &mut account,
3722            &instrument_any,
3723            &[&order],
3724            UnixNanos::default(),
3725        );
3726        let maintenance_result = manager.update_positions_in_place(
3727            &mut account,
3728            &instrument_any,
3729            vec![&position],
3730            UnixNanos::default(),
3731        );
3732
3733        assert!(initial_result.is_none());
3734        assert!(maintenance_result.is_none());
3735        assert_eq!(account.margin(&instrument.id()), Some(prior_margin));
3736        assert_eq!(
3737            account.balance_locked(Some(usdt)),
3738            Some(Money::new(15.0, usdt))
3739        );
3740    }
3741
3742    #[rstest]
3743    fn test_update_margins_lock_quanto_settlement_balance(mut ethbtc_quanto: CryptoFuture) {
3744        let usdt = Currency::USDT();
3745        let account_state = AccountState::new(
3746            AccountId::new("SIM-001"),
3747            AccountType::Margin,
3748            vec![AccountBalance::new(
3749                Money::new(1_000.0, usdt),
3750                Money::zero(usdt),
3751                Money::new(1_000.0, usdt),
3752            )],
3753            Vec::new(),
3754            true,
3755            UUID4::new(),
3756            UnixNanos::default(),
3757            UnixNanos::default(),
3758            None,
3759        );
3760        let account = MarginAccount::new(account_state, true);
3761        let manager = AccountsManager::new(
3762            Rc::new(RefCell::new(VirtualClock::new())),
3763            Rc::new(RefCell::new(Cache::new(None, None))),
3764        );
3765        ethbtc_quanto.margin_init = Decimal::new(1, 1);
3766        ethbtc_quanto.margin_maint = Decimal::new(5, 2);
3767        let instrument_any = InstrumentAny::CryptoFuture(ethbtc_quanto.clone());
3768        let mut order = OrderTestBuilder::new(OrderType::Limit)
3769            .instrument_id(ethbtc_quanto.id())
3770            .side(OrderSide::Buy)
3771            .quantity(Quantity::from("100.000"))
3772            .price(Price::from("0.05000"))
3773            .build();
3774        order
3775            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3776            .unwrap();
3777        order
3778            .apply(OrderEventAny::Accepted(order_accepted_for(
3779                &order,
3780                VenueOrderId::new("1"),
3781            )))
3782            .unwrap();
3783        let position =
3784            build_hedging_position(&instrument_any, OrderSide::Buy, "100.000", "0.05000", "P");
3785
3786        let (updated_account, _) = manager
3787            .update_orders(
3788                &AccountAny::Margin(account),
3789                &instrument_any,
3790                &[&order],
3791                UnixNanos::default(),
3792            )
3793            .unwrap();
3794        let AccountAny::Margin(mut account) = updated_account else {
3795            panic!("Expected MarginAccount");
3796        };
3797        manager
3798            .update_positions_in_place(
3799                &mut account,
3800                &instrument_any,
3801                vec![&position],
3802                UnixNanos::default(),
3803            )
3804            .unwrap();
3805
3806        // notional = 100 * 0.05 = 5 USDT
3807        assert_eq!(
3808            account.balance_locked(Some(usdt)),
3809            Some(Money::new(0.75, usdt))
3810        );
3811        assert_eq!(
3812            account.balance_free(Some(usdt)),
3813            Some(Money::new(999.25, usdt))
3814        );
3815        assert_eq!(
3816            account.initial_margin(ethbtc_quanto.id()),
3817            Money::new(0.5, usdt)
3818        );
3819        assert_eq!(
3820            account.maintenance_margin(ethbtc_quanto.id()),
3821            Money::new(0.25, usdt)
3822        );
3823    }
3824
3825    #[rstest]
3826    fn test_update_margins_convert_quanto_settlement_to_base_currency(
3827        mut ethbtc_quanto: CryptoFuture,
3828    ) {
3829        let usd = Currency::USD();
3830        let account_state = AccountState::new(
3831            AccountId::new("SIM-001"),
3832            AccountType::Margin,
3833            vec![AccountBalance::new(
3834                Money::new(1_000.0, usd),
3835                Money::zero(usd),
3836                Money::new(1_000.0, usd),
3837            )],
3838            Vec::new(),
3839            true,
3840            UUID4::new(),
3841            UnixNanos::default(),
3842            UnixNanos::default(),
3843            Some(usd),
3844        );
3845        let account = MarginAccount::new(account_state, true);
3846        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3847        let usdtusd = default_fx_ccy(Symbol::from("USDT/USD"), Some(ethbtc_quanto.id().venue));
3848        let quote = QuoteTick::new(
3849            usdtusd.id(),
3850            Price::from("0.99000"),
3851            Price::from("1.01000"),
3852            Quantity::from("1"),
3853            Quantity::from("1"),
3854            UnixNanos::default(),
3855            UnixNanos::default(),
3856        );
3857        cache
3858            .borrow_mut()
3859            .add_instrument(InstrumentAny::CurrencyPair(usdtusd))
3860            .unwrap();
3861        cache.borrow_mut().add_quote(quote).unwrap();
3862        let manager = AccountsManager::new(Rc::new(RefCell::new(VirtualClock::new())), cache);
3863        ethbtc_quanto.margin_init = Decimal::new(1, 1);
3864        ethbtc_quanto.margin_maint = Decimal::new(4, 2);
3865        let instrument_any = InstrumentAny::CryptoFuture(ethbtc_quanto.clone());
3866        let mut order = OrderTestBuilder::new(OrderType::Limit)
3867            .instrument_id(ethbtc_quanto.id())
3868            .side(OrderSide::Buy)
3869            .quantity(Quantity::from("1000.000"))
3870            .price(Price::from("0.05000"))
3871            .build();
3872        order
3873            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
3874            .unwrap();
3875        order
3876            .apply(OrderEventAny::Accepted(order_accepted_for(
3877                &order,
3878                VenueOrderId::new("1"),
3879            )))
3880            .unwrap();
3881        let position =
3882            build_hedging_position(&instrument_any, OrderSide::Buy, "1000.000", "0.05000", "P");
3883
3884        let (updated_account, _) = manager
3885            .update_orders(
3886                &AccountAny::Margin(account),
3887                &instrument_any,
3888                &[&order],
3889                UnixNanos::default(),
3890            )
3891            .unwrap();
3892        let AccountAny::Margin(mut account) = updated_account else {
3893            panic!("Expected MarginAccount");
3894        };
3895        manager
3896            .update_positions_in_place(
3897                &mut account,
3898                &instrument_any,
3899                vec![&position],
3900                UnixNanos::default(),
3901            )
3902            .unwrap();
3903
3904        // 5 USDT initial and 2 USDT maintenance, converted at the USDT/USD bid of 0.99
3905        assert_eq!(
3906            account.initial_margin(ethbtc_quanto.id()),
3907            Money::new(4.95, usd)
3908        );
3909        assert_eq!(
3910            account.maintenance_margin(ethbtc_quanto.id()),
3911            Money::new(1.98, usd)
3912        );
3913    }
3914
3915    #[rstest]
3916    fn test_update_margin_init_base_xrate_uses_ask_for_sell_order() {
3917        let eur = Currency::EUR();
3918        let account_state = AccountState::new(
3919            AccountId::new("SIM-001"),
3920            AccountType::Margin,
3921            vec![AccountBalance::new(
3922                Money::new(1_000.0, eur),
3923                Money::zero(eur),
3924                Money::new(1_000.0, eur),
3925            )],
3926            Vec::new(),
3927            true,
3928            UUID4::new(),
3929            UnixNanos::default(),
3930            UnixNanos::default(),
3931            Some(eur),
3932        );
3933        let account = MarginAccount::new(account_state, true);
3934
3935        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3936        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3937        add_usdeur_quote(&cache, "0.90000", "1.10000");
3938        let manager = AccountsManager::new(clock, cache);
3939
3940        let instrument = audusd_sim();
3941        let mut order = OrderTestBuilder::new(OrderType::Limit)
3942            .instrument_id(instrument.id())
3943            .side(OrderSide::Sell)
3944            .quantity(Quantity::from("100"))
3945            .price(Price::from("2.00000"))
3946            .build();
3947
3948        let submitted = order_submitted_for(&order);
3949        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
3950        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
3951        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
3952
3953        let result = manager.update_orders(
3954            &AccountAny::Margin(account),
3955            &InstrumentAny::CurrencyPair(instrument.clone()),
3956            &[&order],
3957            UnixNanos::default(),
3958        );
3959
3960        assert!(result.is_some());
3961        let (updated_account, _) = result.unwrap();
3962
3963        match updated_account {
3964            AccountAny::Margin(margin) => {
3965                assert_eq!(
3966                    margin.initial_margin(instrument.id()),
3967                    Money::new(6.60, eur)
3968                );
3969            }
3970            _ => panic!("Expected MarginAccount"),
3971        }
3972    }
3973
3974    #[rstest]
3975    fn test_update_margin_init_empty_orders_clears_prior_initial_margin() {
3976        let usd = Currency::USD();
3977        let mut account = build_margin_account_usd(1_000_000.0);
3978        let instrument = audusd_sim();
3979        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
3980        account.update_margin(MarginBalance::new(
3981            Money::new(25.0, usd),
3982            Money::zero(usd),
3983            Some(instrument.id()),
3984        ));
3985
3986        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3987        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3988        let manager = AccountsManager::new(clock, cache);
3989
3990        let state = manager
3991            .update_margin_init(&mut account, &instrument_any, &[], UnixNanos::default())
3992            .expect("initial margin clear should generate account state");
3993
3994        assert!(account.margin(&instrument.id()).is_none());
3995        assert!(state.margins.is_empty());
3996    }
3997
3998    #[rstest]
3999    fn test_update_margin_init_empty_orders_preserves_prior_maintenance_margin() {
4000        let usd = Currency::USD();
4001        let mut account = build_margin_account_usd(1_000_000.0);
4002        let instrument = audusd_sim();
4003        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
4004        let maintenance = Money::new(12.0, usd);
4005        account.update_margin(MarginBalance::new(
4006            Money::new(25.0, usd),
4007            maintenance,
4008            Some(instrument.id()),
4009        ));
4010
4011        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4012        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4013        let manager = AccountsManager::new(clock, cache);
4014
4015        let state = manager
4016            .update_margin_init(&mut account, &instrument_any, &[], UnixNanos::default())
4017            .expect("initial margin clear should generate account state");
4018
4019        let margin = account
4020            .margin(&instrument.id())
4021            .expect("maintenance margin should remain");
4022        assert_eq!(margin.initial, Money::zero(usd));
4023        assert_eq!(margin.maintenance, maintenance);
4024        assert_eq!(state.margins, vec![margin]);
4025    }
4026
4027    #[rstest]
4028    fn test_update_margin_init_after_partial_fill() {
4029        let usd = Currency::USD();
4030        let mut account = build_margin_account_usd(1_000_000.0);
4031        let instrument = audusd_sim();
4032        account.set_leverage(instrument.id(), Decimal::ONE);
4033        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
4034
4035        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4036        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4037        let manager = AccountsManager::new(clock, cache);
4038
4039        let mut order = OrderTestBuilder::new(OrderType::Limit)
4040            .instrument_id(instrument.id())
4041            .side(OrderSide::Buy)
4042            .quantity(Quantity::from("100"))
4043            .price(Price::from("1.00000"))
4044            .build();
4045        order
4046            .apply(OrderEventAny::Submitted(order_submitted_for(&order)))
4047            .unwrap();
4048        order
4049            .apply(OrderEventAny::Accepted(order_accepted_for(
4050                &order,
4051                VenueOrderId::new("1"),
4052            )))
4053            .unwrap();
4054        let fill = OrderFilledSpec::builder()
4055            .instrument_id(instrument.id())
4056            .client_order_id(order.client_order_id())
4057            .venue_order_id(VenueOrderId::new("1"))
4058            .order_side(OrderSide::Buy)
4059            .order_type(OrderType::Limit)
4060            .last_qty(Quantity::from("40"))
4061            .last_px(Price::from("1.00000"))
4062            .position_id(PositionId::new("P-001"))
4063            .build();
4064        order.apply(OrderEventAny::Filled(fill.clone())).unwrap();
4065        let position = Position::new(&instrument_any, fill);
4066
4067        manager
4068            .update_margin_init(
4069                &mut account,
4070                &instrument_any,
4071                &[&order],
4072                UnixNanos::default(),
4073            )
4074            .unwrap();
4075        manager
4076            .update_positions_in_place(
4077                &mut account,
4078                &instrument_any,
4079                vec![&position],
4080                UnixNanos::default(),
4081            )
4082            .unwrap();
4083
4084        assert_eq!(order.leaves_qty(), Quantity::from("60"));
4085        assert_eq!(
4086            account.maintenance_margin(instrument.id()),
4087            Money::new(1.20, usd)
4088        );
4089        assert_eq!(
4090            account.initial_margin(instrument.id()),
4091            Money::new(1.80, usd)
4092        );
4093        assert_eq!(
4094            account.balance_locked(Some(usd)),
4095            Some(Money::new(3.00, usd))
4096        );
4097    }
4098
4099    #[rstest]
4100    fn test_cash_account_rejects_negative_balance_when_borrowing_disabled() {
4101        let usd = Currency::USD();
4102        let account_state = AccountState::new(
4103            AccountId::new("SIM-001"),
4104            AccountType::Cash,
4105            vec![AccountBalance::new(
4106                Money::new(1_000.0, usd),
4107                Money::zero(usd),
4108                Money::new(1_000.0, usd),
4109            )],
4110            Vec::new(),
4111            true,
4112            UUID4::new(),
4113            UnixNanos::default(),
4114            UnixNanos::default(),
4115            Some(usd),
4116        );
4117
4118        let mut account = CashAccount::new(account_state, true, false);
4119
4120        let negative_balances = vec![AccountBalance::new(
4121            Money::new(-500.0, usd),
4122            Money::zero(usd),
4123            Money::new(-500.0, usd),
4124        )];
4125
4126        let result = account.update_balances(&negative_balances);
4127
4128        assert!(result.is_err());
4129        let err_msg = result.unwrap_err().to_string();
4130        assert!(err_msg.contains("negative"));
4131        assert!(err_msg.contains("borrowing not allowed"));
4132    }
4133
4134    #[rstest]
4135    fn test_manager_update_balances_returns_error_on_negative_balance() {
4136        let usd = Currency::USD();
4137        let account_state = AccountState::new(
4138            AccountId::new("SIM-001"),
4139            AccountType::Cash,
4140            vec![AccountBalance::new(
4141                Money::new(100.0, usd),
4142                Money::zero(usd),
4143                Money::new(100.0, usd),
4144            )],
4145            Vec::new(),
4146            true,
4147            UUID4::new(),
4148            UnixNanos::default(),
4149            UnixNanos::default(),
4150            Some(usd),
4151        );
4152
4153        let account = CashAccount::new(account_state, true, false);
4154        let initial_balance = account.balance_total(Some(usd)).unwrap();
4155
4156        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4157        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4158        cache
4159            .borrow_mut()
4160            .add_account(AccountAny::Cash(account.clone()))
4161            .unwrap();
4162
4163        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4164        let instrument = audusd_sim();
4165
4166        let mut order = OrderTestBuilder::new(OrderType::Market)
4167            .instrument_id(instrument.id())
4168            .side(OrderSide::Buy)
4169            .quantity(Quantity::from("100000"))
4170            .build();
4171
4172        let submitted = order_submitted_for(&order);
4173        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
4174        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
4175        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
4176
4177        cache
4178            .borrow_mut()
4179            .add_order(order.clone(), None, None, false)
4180            .unwrap();
4181
4182        // Fill with large cost ($80k) that exceeds $100 balance
4183        let fill = OrderFilledSpec::builder()
4184            .instrument_id(instrument.id())
4185            .client_order_id(order.client_order_id())
4186            .venue_order_id(VenueOrderId::new("1"))
4187            .last_qty(Quantity::from("100000"))
4188            .last_px(Price::from("0.80000"))
4189            .ts_event(UnixNanos::from(1))
4190            .ts_init(UnixNanos::from(1))
4191            .position_id(PositionId::new("P-001"))
4192            .commission(Money::new(20.0, usd))
4193            .build();
4194
4195        let position = Position::new(&InstrumentAny::CurrencyPair(instrument.clone()), fill);
4196        cache
4197            .borrow_mut()
4198            .add_position(&position, OmsType::Netting)
4199            .unwrap();
4200
4201        let fill2 = OrderFilledSpec::builder()
4202            .instrument_id(instrument.id())
4203            .client_order_id(order.client_order_id())
4204            .venue_order_id(VenueOrderId::new("2"))
4205            .trade_id(TradeId::new("2"))
4206            .last_qty(Quantity::from("100000"))
4207            .last_px(Price::from("0.80000"))
4208            .ts_event(UnixNanos::from(2))
4209            .ts_init(UnixNanos::from(2))
4210            .position_id(PositionId::new("P-001"))
4211            .commission(Money::new(20.0, usd))
4212            .build();
4213        let (updated, result) = manager.update_balances(
4214            AccountAny::Cash(account),
4215            &InstrumentAny::CurrencyPair(instrument),
4216            &fill2,
4217        );
4218
4219        let AccountAny::Cash(cash) = updated else {
4220            panic!("Expected CashAccount");
4221        };
4222        assert_eq!(cash.balance_total(Some(usd)), Some(initial_balance));
4223        assert!(cash.commissions().is_empty());
4224        assert_eq!(
4225            result.unwrap_err().to_string(),
4226            "Cannot update cash account balance for fill 2: Cash account balance would \
4227             become negative: -79920.00 USD (borrowing not allowed for SIM-001)"
4228        );
4229    }
4230
4231    #[rstest]
4232    fn test_order_canceled_releases_locked_balance() {
4233        // Regression test for https://github.com/nautechsystems/nautilus_trader/issues/3525
4234        let usd = Currency::USD();
4235        let account_state = AccountState::new(
4236            AccountId::new("SIM-001"),
4237            AccountType::Cash,
4238            vec![AccountBalance::new(
4239                Money::new(100_000.0, usd),
4240                Money::zero(usd),
4241                Money::new(100_000.0, usd),
4242            )],
4243            Vec::new(),
4244            true,
4245            UUID4::new(),
4246            UnixNanos::default(),
4247            UnixNanos::default(),
4248            Some(usd),
4249        );
4250
4251        let account = CashAccount::new(account_state, true, false);
4252
4253        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4254        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4255        cache
4256            .borrow_mut()
4257            .add_account(AccountAny::Cash(account.clone()))
4258            .unwrap();
4259
4260        let manager = AccountsManager::new(clock, cache);
4261        let instrument = audusd_sim();
4262
4263        let mut order = OrderTestBuilder::new(OrderType::Limit)
4264            .instrument_id(instrument.id())
4265            .side(OrderSide::Buy)
4266            .quantity(Quantity::from("100000"))
4267            .price(Price::from("0.80000"))
4268            .build();
4269
4270        let submitted = order_submitted_for(&order);
4271        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
4272
4273        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
4274        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
4275
4276        let result = manager.update_orders(
4277            &AccountAny::Cash(account),
4278            &InstrumentAny::CurrencyPair(instrument.clone()),
4279            &[&order],
4280            UnixNanos::default(),
4281        );
4282
4283        assert!(result.is_some());
4284        let (updated_account, _) = result.unwrap();
4285
4286        if let AccountAny::Cash(ref cash) = updated_account {
4287            // 100k * 0.80 = 80k USD locked
4288            assert_eq!(
4289                cash.balance_locked(Some(usd)),
4290                Some(Money::new(80_000.0, usd))
4291            );
4292            assert_eq!(
4293                cash.balance_free(Some(usd)),
4294                Some(Money::new(20_000.0, usd))
4295            );
4296        } else {
4297            panic!("Expected CashAccount");
4298        }
4299
4300        let result = manager.update_orders(
4301            &updated_account,
4302            &InstrumentAny::CurrencyPair(instrument),
4303            &[],
4304            UnixNanos::default(),
4305        );
4306
4307        assert!(result.is_some());
4308        let (final_account, _) = result.unwrap();
4309
4310        if let AccountAny::Cash(cash) = final_account {
4311            assert_eq!(cash.balance_locked(Some(usd)), Some(Money::zero(usd)));
4312            assert_eq!(
4313                cash.balance_free(Some(usd)),
4314                Some(Money::new(100_000.0, usd))
4315            );
4316            assert_eq!(
4317                cash.balance_total(Some(usd)),
4318                Some(Money::new(100_000.0, usd))
4319            );
4320        } else {
4321            panic!("Expected CashAccount");
4322        }
4323    }
4324
4325    #[rstest]
4326    fn test_generate_account_state_preserves_per_instrument_and_account_wide_margins() {
4327        let usd = Currency::USD();
4328        let audusd = InstrumentId::from("AUD/USD.SIM");
4329        let account_state = AccountState::new(
4330            AccountId::new("SIM-001"),
4331            AccountType::Margin,
4332            vec![AccountBalance::new(
4333                Money::new(1_000_000.0, usd),
4334                Money::zero(usd),
4335                Money::new(1_000_000.0, usd),
4336            )],
4337            Vec::new(),
4338            true,
4339            UUID4::new(),
4340            UnixNanos::default(),
4341            UnixNanos::default(),
4342            Some(usd),
4343        );
4344        let mut account = MarginAccount::new(account_state, false);
4345        account.update_margin(MarginBalance::new(
4346            Money::new(150.0, usd),
4347            Money::new(75.0, usd),
4348            Some(audusd),
4349        ));
4350        account.update_margin(MarginBalance::new(
4351            Money::new(500.0, usd),
4352            Money::new(250.0, usd),
4353            None,
4354        ));
4355
4356        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4357        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4358        let manager = AccountsManager::new(clock, cache);
4359
4360        let state =
4361            manager.generate_account_state(&AccountAny::Margin(account), UnixNanos::default());
4362
4363        assert_eq!(state.balances.len(), 1);
4364        assert_eq!(state.balances[0].currency, usd);
4365        assert_eq!(state.balances[0].total, Money::new(1_000_000.0, usd));
4366        assert_eq!(state.balances[0].locked, Money::new(975.0, usd));
4367        assert_eq!(state.balances[0].free, Money::new(999_025.0, usd));
4368
4369        assert_eq!(state.margins.len(), 2);
4370        let per_instrument: Vec<_> = state
4371            .margins
4372            .iter()
4373            .filter(|m| m.instrument_id.is_some())
4374            .collect();
4375        let account_wide: Vec<_> = state
4376            .margins
4377            .iter()
4378            .filter(|m| m.instrument_id.is_none())
4379            .collect();
4380        assert_eq!(per_instrument.len(), 1);
4381        assert_eq!(per_instrument[0].instrument_id, Some(audusd));
4382        assert_eq!(per_instrument[0].initial, Money::new(150.0, usd));
4383        assert_eq!(per_instrument[0].maintenance, Money::new(75.0, usd));
4384        assert_eq!(account_wide.len(), 1);
4385        assert_eq!(account_wide[0].currency, usd);
4386        assert_eq!(account_wide[0].initial, Money::new(500.0, usd));
4387        assert_eq!(account_wide[0].maintenance, Money::new(250.0, usd));
4388    }
4389
4390    #[rstest]
4391    fn test_update_balances_returns_recalculated_balance_for_cash_account() {
4392        let usd = Currency::USD();
4393        let account_state = AccountState::new(
4394            AccountId::new("SIM-001"),
4395            AccountType::Cash,
4396            vec![AccountBalance::new(
4397                Money::new(1_000_000.0, usd),
4398                Money::zero(usd),
4399                Money::new(1_000_000.0, usd),
4400            )],
4401            Vec::new(),
4402            true,
4403            UUID4::new(),
4404            UnixNanos::default(),
4405            UnixNanos::default(),
4406            Some(usd),
4407        );
4408
4409        let account = CashAccount::new(account_state, true, false);
4410
4411        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4412        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4413        cache
4414            .borrow_mut()
4415            .add_account(AccountAny::Cash(account.clone()))
4416            .unwrap();
4417
4418        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4419        let instrument = audusd_sim();
4420
4421        let mut order = OrderTestBuilder::new(OrderType::Market)
4422            .instrument_id(instrument.id())
4423            .side(OrderSide::Buy)
4424            .quantity(Quantity::from("100000"))
4425            .build();
4426        let submitted = order_submitted_for(&order);
4427        let accepted = order_accepted_for(&order, VenueOrderId::new("1"));
4428        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
4429        order.apply(OrderEventAny::Accepted(accepted)).unwrap();
4430        cache
4431            .borrow_mut()
4432            .add_order(order.clone(), None, None, false)
4433            .unwrap();
4434
4435        let fill = OrderFilledSpec::builder()
4436            .instrument_id(instrument.id())
4437            .client_order_id(order.client_order_id())
4438            .venue_order_id(VenueOrderId::new("1"))
4439            .last_qty(Quantity::from("100000"))
4440            .last_px(Price::from("0.80000"))
4441            .ts_event(UnixNanos::from(1))
4442            .ts_init(UnixNanos::from(1))
4443            .position_id(PositionId::new("P-001"))
4444            .commission(Money::new(20.0, usd))
4445            .build();
4446        let position = Position::new(
4447            &InstrumentAny::CurrencyPair(instrument.clone()),
4448            fill.clone(),
4449        );
4450        cache
4451            .borrow_mut()
4452            .add_position(&position, OmsType::Netting)
4453            .unwrap();
4454
4455        let (updated, state) = manager.update_balances(
4456            AccountAny::Cash(account),
4457            &InstrumentAny::CurrencyPair(instrument),
4458            &fill,
4459        );
4460        let state = state.unwrap();
4461
4462        // Buy 100k at 0.80 → 80,000 USD cost, 20 USD commission, expect 919,980 USD
4463        let expected = Money::new(919_980.0, usd);
4464
4465        match updated {
4466            AccountAny::Cash(cash) => {
4467                assert_eq!(cash.balance_total(Some(usd)), Some(expected));
4468                assert_eq!(cash.balance_free(Some(usd)), Some(expected));
4469            }
4470            _ => panic!("Expected CashAccount"),
4471        }
4472        assert_eq!(state.balances.len(), 1);
4473        assert_eq!(state.balances[0].currency, usd);
4474        assert_eq!(state.balances[0].total, expected);
4475        assert_eq!(state.balances[0].free, expected);
4476    }
4477
4478    #[rstest]
4479    fn test_update_balances_preserves_subincrement_base_commission() {
4480        let btc = Currency::BTC();
4481        let usdt = Currency::USDT();
4482        let account_id = AccountId::new("SIM-001");
4483        let account_state = AccountState::new(
4484            account_id,
4485            AccountType::Cash,
4486            vec![
4487                AccountBalance::new(Money::from("1 BTC"), Money::zero(btc), Money::from("1 BTC")),
4488                AccountBalance::new(
4489                    Money::from("1000 USDT"),
4490                    Money::zero(usdt),
4491                    Money::from("1000 USDT"),
4492                ),
4493            ],
4494            Vec::new(),
4495            true,
4496            UUID4::new(),
4497            UnixNanos::default(),
4498            UnixNanos::default(),
4499            None,
4500        );
4501        let account = CashAccount::new(account_state, true, false);
4502        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4503        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4504        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4505        let mut instrument = currency_pair_btcusdt();
4506        instrument.size_increment = Quantity::from("0.005000");
4507        let instrument = InstrumentAny::CurrencyPair(instrument);
4508        let position_id = PositionId::new("P-001");
4509        let fill = OrderFilledSpec::builder()
4510            .instrument_id(instrument.id())
4511            .account_id(account_id)
4512            .position_id(position_id)
4513            .order_side(OrderSide::Buy)
4514            .order_type(OrderType::Market)
4515            .last_qty(Quantity::from("0.003000"))
4516            .last_px(Price::from("50000.00"))
4517            .currency(usdt)
4518            .commission(Money::from("0.00040000 BTC"))
4519            .build();
4520        let position = Position::new(&instrument, fill.clone());
4521        cache
4522            .borrow_mut()
4523            .add_position(&position, OmsType::Netting)
4524            .unwrap();
4525
4526        let (updated, state) =
4527            manager.update_balances(AccountAny::Cash(account), &instrument, &fill);
4528        let state = state.unwrap();
4529        let AccountAny::Cash(cash) = updated else {
4530            panic!("Expected CashAccount");
4531        };
4532        let state_btc = state
4533            .balances
4534            .iter()
4535            .find(|balance| balance.currency == btc)
4536            .unwrap();
4537        let state_usdt = state
4538            .balances
4539            .iter()
4540            .find(|balance| balance.currency == usdt)
4541            .unwrap();
4542
4543        assert_eq!(position.quantity, Quantity::from("0.002600"));
4544        assert_eq!(
4545            cash.balance_total(Some(btc)),
4546            Some(Money::from("1.00260000 BTC")),
4547        );
4548        assert_eq!(
4549            cash.balance_total(Some(usdt)),
4550            Some(Money::from("850 USDT")),
4551        );
4552        assert_eq!(cash.commission(&btc), Some(Money::from("0.00040000 BTC")),);
4553        assert_eq!(state_btc.total, Money::from("1.00260000 BTC"));
4554        assert_eq!(state_usdt.total, Money::from("850 USDT"));
4555    }
4556
4557    #[rstest]
4558    fn test_update_balances_rollback_restores_balances_and_commissions() {
4559        // Overflowing the commission total is the only reachable trigger for a rollback after
4560        // the balance mutation: the realized PnL lands first, then the commission is rejected.
4561        let usd = Currency::USD();
4562        let account_state = AccountState::new(
4563            AccountId::new("SIM-001"),
4564            AccountType::Margin,
4565            vec![AccountBalance::new(
4566                Money::new(1_000_000.0, usd),
4567                Money::zero(usd),
4568                Money::new(1_000_000.0, usd),
4569            )],
4570            Vec::new(),
4571            true,
4572            UUID4::new(),
4573            UnixNanos::default(),
4574            UnixNanos::default(),
4575            Some(usd),
4576        );
4577        let mut account = MarginAccount::new(account_state, false);
4578        account.commissions.insert(usd, Money::new(MONEY_MAX, usd));
4579        let original_balances = account.balances.clone();
4580        let original_commissions = account.commissions.clone();
4581
4582        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4583        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4584        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4585        let instrument = audusd_sim();
4586        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
4587
4588        let entry = OrderFilledSpec::builder()
4589            .instrument_id(instrument.id())
4590            .order_side(OrderSide::Buy)
4591            .last_qty(Quantity::from("100000"))
4592            .last_px(Price::from("0.80000"))
4593            .position_id(PositionId::new("P-ROLLBACK"))
4594            .build();
4595        let position = Position::new(&instrument_any, entry);
4596        cache
4597            .borrow_mut()
4598            .add_position(&position, OmsType::Netting)
4599            .unwrap();
4600
4601        // Closing fill realizes 1,000 USD, less a 20 USD commission the total cannot absorb
4602        let closing = OrderFilledSpec::builder()
4603            .instrument_id(instrument.id())
4604            .order_side(OrderSide::Sell)
4605            .last_qty(Quantity::from("100000"))
4606            .last_px(Price::from("0.81000"))
4607            .trade_id(TradeId::new("2"))
4608            .ts_event(UnixNanos::from(1))
4609            .ts_init(UnixNanos::from(1))
4610            .position_id(PositionId::new("P-ROLLBACK"))
4611            .commission(Money::new(20.0, usd))
4612            .build();
4613
4614        let (updated, state) =
4615            manager.update_balances(AccountAny::Margin(account), &instrument_any, &closing);
4616        let state = state.unwrap();
4617
4618        let AccountAny::Margin(margin) = updated else {
4619            panic!("Expected MarginAccount");
4620        };
4621        assert_eq!(margin.balances, original_balances);
4622        assert_eq!(margin.commissions, original_commissions);
4623        assert_eq!(state.balances.len(), 1);
4624        assert_eq!(state.balances[0].total, Money::new(1_000_000.0, usd));
4625        assert_eq!(state.balances[0].free, Money::new(1_000_000.0, usd));
4626    }
4627
4628    #[rstest]
4629    #[case::long_fee(OrderSide::Buy, 1, false)]
4630    #[case::short_fee(OrderSide::Sell, 1, false)]
4631    #[case::long_rebate(OrderSide::Buy, -1, false)]
4632    #[case::short_rebate(OrderSide::Sell, -1, false)]
4633    #[case::long_increase_fee(OrderSide::Buy, 1, true)]
4634    #[case::short_increase_rebate(OrderSide::Sell, -1, true)]
4635    fn test_update_balances_matches_position_native_fee_rounding(
4636        #[case] side: OrderSide,
4637        #[case] fee_raw: i8,
4638        #[case] increase: bool,
4639        #[values(true, false)] single_currency: bool,
4640    ) {
4641        let usd = Currency::USD();
4642        let initial = Money::from("100 USD");
4643
4644        let state = AccountState::new(
4645            AccountId::new("SIM-001"),
4646            AccountType::Margin,
4647            vec![AccountBalance::new(initial, Money::zero(usd), initial)],
4648            vec![],
4649            true,
4650            UUID4::new(),
4651            UnixNanos::default(),
4652            UnixNanos::default(),
4653            single_currency.then_some(usd),
4654        );
4655        let mut account = AccountAny::Margin(MarginAccount::new(state, true));
4656        let cache = Rc::new(RefCell::new(Cache::default()));
4657
4658        let manager = AccountsManager::new(
4659            Rc::new(RefCell::new(VirtualClock::new())),
4660            Rc::clone(&cache),
4661        );
4662        let instrument = InstrumentAny::CurrencyPair(audusd_sim());
4663        let scalar = Price::from("1").raw();
4664        let precision = FIXED_PRECISION;
4665        let opening_px = Price::from_raw(
4666            scalar + if side == OrderSide::Buy { 1 } else { 2 },
4667            precision,
4668        );
4669        let closing_px = Price::from_raw(
4670            scalar + if side == OrderSide::Buy { 2 } else { 1 },
4671            precision,
4672        );
4673        let opening = OrderFilledSpec::builder()
4674            .instrument_id(instrument.id())
4675            .position_id(PositionId::new("P-NATIVE-FEE"))
4676            .order_side(side)
4677            .last_qty(Quantity::from(1))
4678            .last_px(opening_px)
4679            .commission(Money::zero(usd))
4680            .build();
4681        let mut position = Position::new(&instrument, opening.clone());
4682        cache
4683            .borrow_mut()
4684            .add_position(&position, OmsType::Netting)
4685            .unwrap();
4686        let fee = Money::from_raw(fee_raw.into(), usd);
4687        let mut fill = opening;
4688        fill.last_qty = Quantity::from("0.5");
4689        fill.last_px = closing_px;
4690        fill.order_side = side.opposite();
4691        fill.commission = Some(fee);
4692        let mut balances = Vec::new();
4693        let mut realized = Vec::new();
4694
4695        let mut legs = vec![(side.opposite(), Quantity::from("0.5"), fee)];
4696        if increase {
4697            legs.push((side, Quantity::from("0.5"), fee));
4698        }
4699
4700        let closing_qty = if increase {
4701            Quantity::from(1)
4702        } else {
4703            Quantity::from("0.5")
4704        };
4705
4706        legs.push((side.opposite(), closing_qty, Money::zero(usd)));
4707        for (index, (side, qty, commission)) in legs.into_iter().enumerate() {
4708            fill.trade_id = TradeId::from(format!("T-NATIVE-FEE-{index}"));
4709            fill.event_id = UUID4::new();
4710            fill.order_side = side;
4711            fill.last_qty = qty;
4712            fill.commission = Some(commission);
4713            let (updated, result) = manager.update_balances(account, &instrument, &fill);
4714            result.unwrap();
4715            account = updated;
4716            position.try_apply(&fill).unwrap();
4717            cache.borrow_mut().update_position(&position).unwrap();
4718            balances.push(account.balance_total(Some(usd)).unwrap() - initial);
4719            realized.push(position.realized_pnl.unwrap());
4720        }
4721
4722        let gross = Money::from_raw(1, usd);
4723
4724        let total_fee = if increase { fee + fee } else { fee };
4725        assert_eq!(balances, realized);
4726        assert_eq!(balances.last(), Some(&(gross - total_fee)));
4727
4728        let AccountAny::Margin(account) = account else {
4729            panic!("Expected MarginAccount");
4730        };
4731
4732        assert_eq!(account.commission(&usd), Some(total_fee));
4733        assert_eq!(position.quantity.as_decimal(), Decimal::ZERO);
4734        assert_eq!(position.realized_pnl_remainder, Decimal::ZERO);
4735    }
4736
4737    #[rstest]
4738    fn test_update_balances_notional_error_preserves_cash_balance_and_commission() {
4739        let usd = Currency::USD();
4740        let account_state = AccountState::new(
4741            AccountId::new("SIM-001"),
4742            AccountType::Cash,
4743            vec![AccountBalance::new(
4744                Money::new(1_000_000.0, usd),
4745                Money::zero(usd),
4746                Money::new(1_000_000.0, usd),
4747            )],
4748            Vec::new(),
4749            true,
4750            UUID4::new(),
4751            UnixNanos::default(),
4752            UnixNanos::default(),
4753            Some(usd),
4754        );
4755        let account = CashAccount::new(account_state, true, false);
4756        let before = (account.balances(), account.commissions(), account.events());
4757        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4758        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4759        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4760        let instrument = audusd_sim();
4761        let fill = OrderFilledSpec::builder()
4762            .instrument_id(instrument.id())
4763            .last_qty(Quantity::from("100000000"))
4764            .last_px(Price::from("100000000"))
4765            .ts_event(UnixNanos::from(1))
4766            .ts_init(UnixNanos::from(1))
4767            .position_id(PositionId::new("P-NOTIONAL-ERROR"))
4768            .commission(Money::new(20.0, usd))
4769            .build();
4770        let position = Position::new(
4771            &InstrumentAny::CurrencyPair(instrument.clone()),
4772            fill.clone(),
4773        );
4774        cache
4775            .borrow_mut()
4776            .add_position(&position, OmsType::Netting)
4777            .unwrap();
4778
4779        let (updated, state) = manager.update_balances(
4780            AccountAny::Cash(account),
4781            &InstrumentAny::CurrencyPair(instrument),
4782            &fill,
4783        );
4784        assert!(state.is_err());
4785
4786        let AccountAny::Cash(cash) = updated else {
4787            panic!("Expected CashAccount");
4788        };
4789        assert_eq!(
4790            cash.balance_total(Some(usd)),
4791            Some(Money::new(1_000_000.0, usd))
4792        );
4793        assert!(cash.commissions().is_empty());
4794        assert_eq!((cash.balances(), cash.commissions(), cash.events()), before);
4795    }
4796
4797    fn wallet_precision_pair(
4798        wallet_precision: u8,
4799    ) -> Option<(WalletAccount, CurrencyPair, Currency, Currency)> {
4800        Currency::new_checked("WPREC", 18, 0, "WPREC", CurrencyType::Crypto).ok()?;
4801        let instrument_base = Currency::new("WBASE", 16, 0, "WBASE", CurrencyType::Crypto);
4802        let instrument_quote = Currency::new("WQUOTE", 16, 0, "WQUOTE", CurrencyType::Crypto);
4803        let observed_base =
4804            Currency::new("WBASE", wallet_precision, 0, "WBASE", CurrencyType::Crypto);
4805        let observed_quote = Currency::new(
4806            "WQUOTE",
4807            wallet_precision,
4808            0,
4809            "WQUOTE",
4810            CurrencyType::Crypto,
4811        );
4812        let instrument = CurrencyPair::builder()
4813            .instrument_id(InstrumentId::from("WBASEWQUOTE.BLOCKCHAIN"))
4814            .raw_symbol(Symbol::from("WBASEWQUOTE"))
4815            .base_currency(instrument_base)
4816            .quote_currency(instrument_quote)
4817            .price_precision(16)
4818            .size_precision(16)
4819            .price_increment(Price::from_raw(1, 16))
4820            .size_increment(Quantity::from_raw(1, 16))
4821            .ts_event(UnixNanos::default())
4822            .ts_init(UnixNanos::default())
4823            .build()
4824            .unwrap();
4825        let scale = money_raw(10_i128.pow(u32::from(wallet_precision.max(FIXED_PRECISION))));
4826        let base_total = Money::from_raw(scale, observed_base);
4827        let quote_total = Money::from_raw(2 * scale, observed_quote);
4828        let wallet = WalletAccount::new(
4829            AccountState::new(
4830                AccountId::from("WALLET-PRECISION"),
4831                AccountType::Wallet,
4832                vec![
4833                    AccountBalance::new(base_total, Money::zero(observed_base), base_total),
4834                    AccountBalance::new(quote_total, Money::zero(observed_quote), quote_total),
4835                ],
4836                vec![],
4837                true,
4838                UUID4::new(),
4839                UnixNanos::default(),
4840                UnixNanos::default(),
4841                None,
4842            ),
4843            true,
4844        );
4845
4846        Some((wallet, instrument, observed_base, observed_quote))
4847    }
4848
4849    #[allow(
4850        clippy::useless_conversion,
4851        reason = "the raw width differs when high-precision is disabled"
4852    )]
4853    fn money_raw(raw: i128) -> MoneyRaw {
4854        raw.try_into().unwrap()
4855    }
4856
4857    fn multi_currency_cash_account(allow_borrowing: bool) -> CashAccount {
4858        let aud = Currency::AUD();
4859        let usd = Currency::USD();
4860        let account_state = AccountState::new(
4861            AccountId::new("SIM-001"),
4862            AccountType::Cash,
4863            vec![
4864                AccountBalance::new(
4865                    Money::new(10_000.0, aud),
4866                    Money::zero(aud),
4867                    Money::new(10_000.0, aud),
4868                ),
4869                AccountBalance::new(
4870                    Money::new(100.0, usd),
4871                    Money::zero(usd),
4872                    Money::new(100.0, usd),
4873                ),
4874            ],
4875            Vec::new(),
4876            true,
4877            UUID4::new(),
4878            UnixNanos::default(),
4879            UnixNanos::default(),
4880            None,
4881        );
4882        CashAccount::new(account_state, true, allow_borrowing)
4883    }
4884
4885    fn buy_audusd_fill(qty: &str, px: &str, commission: f64) -> OrderFilled {
4886        let instrument = audusd_sim();
4887        let usd = Currency::USD();
4888        OrderFilledSpec::builder()
4889            .instrument_id(instrument.id())
4890            .last_qty(Quantity::from(qty))
4891            .last_px(Price::from(px))
4892            .ts_event(UnixNanos::from(1))
4893            .ts_init(UnixNanos::from(1))
4894            .position_id(PositionId::new("P-001"))
4895            .commission(Money::new(commission, usd))
4896            .build()
4897    }
4898
4899    fn multi_currency_cash_account_with_usd_locked(total: f64, locked: f64) -> CashAccount {
4900        multi_currency_cash_account_with_usd_locked_and_borrowing(total, locked, false)
4901    }
4902
4903    fn multi_currency_cash_account_with_usd_locked_and_borrowing(
4904        total: f64,
4905        locked: f64,
4906        allow_borrowing: bool,
4907    ) -> CashAccount {
4908        let usd = Currency::USD();
4909        let account_state = AccountState::new(
4910            AccountId::new("SIM-001"),
4911            AccountType::Cash,
4912            vec![AccountBalance::new(
4913                Money::new(total, usd),
4914                Money::new(locked, usd),
4915                Money::new(total - locked, usd),
4916            )],
4917            Vec::new(),
4918            true,
4919            UUID4::new(),
4920            UnixNanos::default(),
4921            UnixNanos::default(),
4922            None,
4923        );
4924        CashAccount::new(account_state, true, allow_borrowing)
4925    }
4926
4927    fn multi_currency_betting_account_with_gbp_locked(total: f64, locked: f64) -> BettingAccount {
4928        let gbp = Currency::GBP();
4929        let account_state = AccountState::new(
4930            AccountId::new("BETFAIR-001"),
4931            AccountType::Betting,
4932            vec![AccountBalance::new(
4933                Money::new(total, gbp),
4934                Money::new(locked, gbp),
4935                Money::new(total - locked, gbp),
4936            )],
4937            Vec::new(),
4938            true,
4939            UUID4::new(),
4940            UnixNanos::default(),
4941            UnixNanos::default(),
4942            None,
4943        );
4944        BettingAccount::new(account_state, true)
4945    }
4946
4947    fn order_submitted_for(order: &OrderAny) -> OrderSubmitted {
4948        OrderSubmittedSpec::builder()
4949            .trader_id(order.trader_id())
4950            .strategy_id(order.strategy_id())
4951            .instrument_id(order.instrument_id())
4952            .client_order_id(order.client_order_id())
4953            .build()
4954    }
4955
4956    fn order_submitted_for_account(order: &OrderAny, account_id: AccountId) -> OrderSubmitted {
4957        OrderSubmittedSpec::builder()
4958            .trader_id(order.trader_id())
4959            .strategy_id(order.strategy_id())
4960            .instrument_id(order.instrument_id())
4961            .client_order_id(order.client_order_id())
4962            .account_id(account_id)
4963            .build()
4964    }
4965
4966    fn order_accepted_for(order: &OrderAny, venue_order_id: VenueOrderId) -> OrderAccepted {
4967        OrderAcceptedSpec::builder()
4968            .trader_id(order.trader_id())
4969            .strategy_id(order.strategy_id())
4970            .instrument_id(order.instrument_id())
4971            .client_order_id(order.client_order_id())
4972            .venue_order_id(venue_order_id)
4973            .build()
4974    }
4975
4976    fn order_accepted_for_account(
4977        order: &OrderAny,
4978        venue_order_id: VenueOrderId,
4979        account_id: AccountId,
4980    ) -> OrderAccepted {
4981        OrderAcceptedSpec::builder()
4982            .trader_id(order.trader_id())
4983            .strategy_id(order.strategy_id())
4984            .instrument_id(order.instrument_id())
4985            .client_order_id(order.client_order_id())
4986            .venue_order_id(venue_order_id)
4987            .account_id(account_id)
4988            .build()
4989    }
4990
4991    #[rstest]
4992    fn test_update_balance_multi_currency_market_debit_keeps_locked_balance() {
4993        let usd = Currency::USD();
4994        let account = multi_currency_cash_account_with_usd_locked(1_000.0, 200.0);
4995        let clock = Rc::new(RefCell::new(VirtualClock::new()));
4996        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4997        let manager = AccountsManager::new(clock, Rc::clone(&cache));
4998        let instrument = audusd_sim();
4999        cache
5000            .borrow_mut()
5001            .add_instrument(InstrumentAny::CurrencyPair(instrument.clone()))
5002            .unwrap();
5003
5004        let fill = OrderFilledSpec::builder()
5005            .instrument_id(instrument.id())
5006            .order_type(OrderType::Market)
5007            .commission(Money::new(20.0, usd))
5008            .build();
5009        let mut account = AccountAny::Cash(account);
5010        let mut pnls = vec![Money::new(-100.0, usd)];
5011
5012        manager
5013            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5014            .unwrap();
5015
5016        match account {
5017            AccountAny::Cash(cash) => {
5018                assert_eq!(cash.balance_total(Some(usd)), Some(Money::new(880.0, usd)));
5019                assert_eq!(cash.balance_locked(Some(usd)), Some(Money::new(200.0, usd)));
5020                assert_eq!(cash.balance_free(Some(usd)), Some(Money::new(680.0, usd)));
5021                assert_eq!(cash.commission(&usd), Some(Money::new(20.0, usd)));
5022            }
5023            _ => panic!("Expected CashAccount"),
5024        }
5025    }
5026
5027    #[rstest]
5028    fn test_update_balance_multi_currency_limit_debit_reduces_locked_balance() {
5029        let usd = Currency::USD();
5030        let account = multi_currency_cash_account_with_usd_locked(1_000.0, 200.0);
5031        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5032        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5033        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5034        let instrument = audusd_sim();
5035        cache
5036            .borrow_mut()
5037            .add_instrument(InstrumentAny::CurrencyPair(instrument.clone()))
5038            .unwrap();
5039
5040        let fill = OrderFilledSpec::builder()
5041            .instrument_id(instrument.id())
5042            .order_type(OrderType::Limit)
5043            .commission(Money::new(20.0, usd))
5044            .build();
5045        let mut account = AccountAny::Cash(account);
5046        let mut pnls = vec![Money::new(-100.0, usd)];
5047
5048        manager
5049            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5050            .unwrap();
5051
5052        match account {
5053            AccountAny::Cash(cash) => {
5054                assert_eq!(cash.balance_total(Some(usd)), Some(Money::new(880.0, usd)));
5055                assert_eq!(cash.balance_locked(Some(usd)), Some(Money::new(80.0, usd)));
5056                assert_eq!(cash.balance_free(Some(usd)), Some(Money::new(800.0, usd)));
5057                assert_eq!(cash.commission(&usd), Some(Money::new(20.0, usd)));
5058            }
5059            _ => panic!("Expected CashAccount"),
5060        }
5061    }
5062
5063    #[rstest]
5064    fn test_update_balance_multi_currency_limit_debit_spills_from_locked_to_free() {
5065        let usd = Currency::USD();
5066        let account = multi_currency_cash_account_with_usd_locked(1_000.0, 50.0);
5067        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5068        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5069        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5070        let instrument = audusd_sim();
5071        cache
5072            .borrow_mut()
5073            .add_instrument(InstrumentAny::CurrencyPair(instrument.clone()))
5074            .unwrap();
5075
5076        let fill = OrderFilledSpec::builder()
5077            .instrument_id(instrument.id())
5078            .order_type(OrderType::Limit)
5079            .commission(Money::new(20.0, usd))
5080            .build();
5081        let mut account = AccountAny::Cash(account);
5082        let mut pnls = vec![Money::new(-100.0, usd)];
5083
5084        manager
5085            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5086            .unwrap();
5087
5088        match account {
5089            AccountAny::Cash(cash) => {
5090                assert_eq!(cash.balance_total(Some(usd)), Some(Money::new(880.0, usd)));
5091                assert_eq!(cash.balance_locked(Some(usd)), Some(Money::zero(usd)));
5092                assert_eq!(cash.balance_free(Some(usd)), Some(Money::new(880.0, usd)));
5093                assert_eq!(cash.commission(&usd), Some(Money::new(20.0, usd)));
5094            }
5095            _ => panic!("Expected CashAccount"),
5096        }
5097    }
5098
5099    #[rstest]
5100    fn test_update_balance_multi_currency_limit_debit_floors_locked_on_negative_total() {
5101        let usd = Currency::USD();
5102        let account = multi_currency_cash_account_with_usd_locked_and_borrowing(100.0, 50.0, true);
5103        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5104        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5105        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5106        let instrument = audusd_sim();
5107        cache
5108            .borrow_mut()
5109            .add_instrument(InstrumentAny::CurrencyPair(instrument.clone()))
5110            .unwrap();
5111
5112        let fill = OrderFilledSpec::builder()
5113            .instrument_id(instrument.id())
5114            .order_type(OrderType::Limit)
5115            .commission(Money::new(20.0, usd))
5116            .build();
5117        let mut account = AccountAny::Cash(account);
5118        let mut pnls = vec![Money::new(-200.0, usd)];
5119
5120        manager
5121            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5122            .unwrap();
5123
5124        match account {
5125            AccountAny::Cash(cash) => {
5126                assert_eq!(cash.balance_total(Some(usd)), Some(Money::new(-120.0, usd)));
5127                assert_eq!(cash.balance_locked(Some(usd)), Some(Money::zero(usd)));
5128                assert_eq!(cash.balance_free(Some(usd)), Some(Money::new(-120.0, usd)));
5129                assert_eq!(cash.commission(&usd), Some(Money::new(20.0, usd)));
5130            }
5131            _ => panic!("Expected CashAccount"),
5132        }
5133    }
5134
5135    #[rstest]
5136    fn test_update_balance_multi_currency_betting_limit_debit_keeps_locked_balance() {
5137        let gbp = Currency::GBP();
5138        let account = multi_currency_betting_account_with_gbp_locked(1_000.0, 200.0);
5139        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5140        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5141        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5142        let instrument = betting();
5143        cache
5144            .borrow_mut()
5145            .add_instrument(InstrumentAny::Betting(instrument.clone()))
5146            .unwrap();
5147
5148        let fill = OrderFilledSpec::builder()
5149            .instrument_id(instrument.id())
5150            .order_type(OrderType::Limit)
5151            .commission(Money::new(20.0, gbp))
5152            .build();
5153        let mut account = AccountAny::Betting(account);
5154        let mut pnls = vec![Money::new(-100.0, gbp)];
5155
5156        manager
5157            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5158            .unwrap();
5159
5160        match account {
5161            AccountAny::Betting(betting_account) => {
5162                assert_eq!(
5163                    betting_account.balance_total(Some(gbp)),
5164                    Some(Money::new(880.0, gbp))
5165                );
5166                assert_eq!(
5167                    betting_account.balance_locked(Some(gbp)),
5168                    Some(Money::new(200.0, gbp))
5169                );
5170                assert_eq!(
5171                    betting_account.balance_free(Some(gbp)),
5172                    Some(Money::new(680.0, gbp))
5173                );
5174                assert_eq!(
5175                    betting_account.commission(&gbp),
5176                    Some(Money::new(20.0, gbp))
5177                );
5178            }
5179            _ => panic!("Expected BettingAccount"),
5180        }
5181    }
5182
5183    #[rstest]
5184    fn test_update_balance_multi_currency_persists_negative_balance_with_allow_borrowing() {
5185        let aud = Currency::AUD();
5186        let usd = Currency::USD();
5187        let account = multi_currency_cash_account(true);
5188        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5189        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5190        cache
5191            .borrow_mut()
5192            .add_account(AccountAny::Cash(account.clone()))
5193            .unwrap();
5194        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5195        let instrument = audusd_sim();
5196        let fill = buy_audusd_fill("10000", "0.80000", 20.0);
5197        let position = Position::new(
5198            &InstrumentAny::CurrencyPair(instrument.clone()),
5199            fill.clone(),
5200        );
5201        cache
5202            .borrow_mut()
5203            .add_position(&position, OmsType::Netting)
5204            .unwrap();
5205
5206        let (updated, _state) = manager.update_balances(
5207            AccountAny::Cash(account),
5208            &InstrumentAny::CurrencyPair(instrument),
5209            &fill,
5210        );
5211
5212        match updated {
5213            AccountAny::Cash(cash) => {
5214                assert_eq!(
5215                    cash.balance_total(Some(aud)),
5216                    Some(Money::new(20_000.0, aud))
5217                );
5218                assert_eq!(
5219                    cash.balance_total(Some(usd)),
5220                    Some(Money::new(-7_920.0, usd))
5221                );
5222            }
5223            _ => panic!("Expected CashAccount"),
5224        }
5225    }
5226
5227    #[rstest]
5228    fn test_update_balance_multi_currency_rejects_negative_balance_without_allow_borrowing() {
5229        let aud = Currency::AUD();
5230        let usd = Currency::USD();
5231        let account = multi_currency_cash_account(false);
5232        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5233        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5234        cache
5235            .borrow_mut()
5236            .add_account(AccountAny::Cash(account.clone()))
5237            .unwrap();
5238        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5239        let instrument = audusd_sim();
5240        let fill = buy_audusd_fill("10000", "0.80000", 20.0);
5241        let position = Position::new(
5242            &InstrumentAny::CurrencyPair(instrument.clone()),
5243            fill.clone(),
5244        );
5245        cache
5246            .borrow_mut()
5247            .add_position(&position, OmsType::Netting)
5248            .unwrap();
5249
5250        let (updated, _state) = manager.update_balances(
5251            AccountAny::Cash(account),
5252            &InstrumentAny::CurrencyPair(instrument),
5253            &fill,
5254        );
5255
5256        // Rejected by `cash.update_balances`: original balances preserved
5257        match updated {
5258            AccountAny::Cash(cash) => {
5259                assert_eq!(
5260                    cash.balance_total(Some(aud)),
5261                    Some(Money::new(10_000.0, aud))
5262                );
5263                assert_eq!(cash.balance_total(Some(usd)), Some(Money::new(100.0, usd)));
5264            }
5265            _ => panic!("Expected CashAccount"),
5266        }
5267    }
5268
5269    #[rstest]
5270    fn test_update_balance_multi_currency_rejects_new_currency_negative_pnl() {
5271        let aud = Currency::AUD();
5272        let account_state = AccountState::new(
5273            AccountId::new("SIM-001"),
5274            AccountType::Cash,
5275            vec![AccountBalance::new(
5276                Money::new(10_000.0, aud),
5277                Money::zero(aud),
5278                Money::new(10_000.0, aud),
5279            )],
5280            Vec::new(),
5281            true,
5282            UUID4::new(),
5283            UnixNanos::default(),
5284            UnixNanos::default(),
5285            None,
5286        );
5287        let account = CashAccount::new(account_state, true, true);
5288        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5289        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5290        cache
5291            .borrow_mut()
5292            .add_account(AccountAny::Cash(account.clone()))
5293            .unwrap();
5294        let manager = AccountsManager::new(clock, Rc::clone(&cache));
5295        let instrument = audusd_sim();
5296        // Buy AUD/USD on an AUD-only account: produces negative USD pnl on a missing currency,
5297        // which the documented Python-parity branch rejects even with `allow_borrowing=true`.
5298        let fill = buy_audusd_fill("10000", "0.80000", 0.0);
5299        let position = Position::new(
5300            &InstrumentAny::CurrencyPair(instrument.clone()),
5301            fill.clone(),
5302        );
5303        cache
5304            .borrow_mut()
5305            .add_position(&position, OmsType::Netting)
5306            .unwrap();
5307
5308        let (updated, _state) = manager.update_balances(
5309            AccountAny::Cash(account),
5310            &InstrumentAny::CurrencyPair(instrument),
5311            &fill,
5312        );
5313
5314        // Rejected at the no-existing-balance + negative-pnl branch (Python parity)
5315        match updated {
5316            AccountAny::Cash(cash) => {
5317                assert_eq!(
5318                    cash.balance_total(Some(aud)),
5319                    Some(Money::new(10_000.0, aud))
5320                );
5321                assert_eq!(cash.balance_total(Some(Currency::USD())), None);
5322            }
5323            _ => panic!("Expected CashAccount"),
5324        }
5325    }
5326
5327    // ~100M USDT total with non-zero locked margin: the raw fixed-point value exceeds f64's
5328    // exact-integer range (2^53), which is the condition that triggers issue #4165.
5329    fn large_locked_usdt_margin_account() -> (AccountAny, Money, Money) {
5330        let usdt = Currency::USDT();
5331        let total =
5332            Money::from_decimal(Decimal::from_str_exact("99999997.91829666").unwrap(), usdt)
5333                .unwrap();
5334        let locked =
5335            Money::from_decimal(Decimal::from_str_exact("32.85965").unwrap(), usdt).unwrap();
5336        let free = total - locked;
5337
5338        let account_state = AccountState::new(
5339            AccountId::new("SIM-001"),
5340            AccountType::Margin,
5341            vec![AccountBalance::new(total, locked, free)],
5342            Vec::new(),
5343            true,
5344            UUID4::new(),
5345            UnixNanos::default(),
5346            UnixNanos::default(),
5347            None, // No base currency routes PnL through `update_balance_multi_currency`
5348        );
5349        (
5350            AccountAny::Margin(MarginAccount::new(account_state, false)),
5351            total,
5352            locked,
5353        )
5354    }
5355
5356    #[rstest]
5357    fn test_update_balance_multi_currency_preserves_invariant_with_large_locked() {
5358        // Regression for issue #4165: applying realized PnL to a large multi-currency margin
5359        // balance via independent f64 round-trips drifts `total` and `free` relative to each
5360        // other, breaking `total == locked + free` and panicking `AccountBalance::new`.
5361        let usdt = Currency::USDT();
5362        let (mut account, total, locked) = large_locked_usdt_margin_account();
5363        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5364        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5365        let manager = AccountsManager::new(clock, cache);
5366
5367        // No commission on the fill: only the realized-PnL branch runs. This PnL lands on an
5368        // 8dp tick where the old independent f64 round-trips drifted by 2e-8.
5369        let fill = OrderFilledSpec::builder().build();
5370        let pnl =
5371            Money::from_decimal(Decimal::from_str_exact("0.00000064").unwrap(), usdt).unwrap();
5372        let mut pnls = [pnl];
5373        manager
5374            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5375            .unwrap();
5376
5377        let balances = account.balances();
5378        let balance = balances.get(&usdt).expect("USDT balance");
5379        assert_eq!(balance.locked, locked, "locked margin preserved");
5380        assert_eq!(balance.total, total + pnl, "total moved by realized PnL");
5381        assert_eq!(
5382            balance.total,
5383            balance.locked + balance.free,
5384            "invariant total == locked + free must hold"
5385        );
5386    }
5387
5388    #[rstest]
5389    fn test_update_balance_multi_currency_commission_preserves_invariant_with_large_locked() {
5390        // Regression for issue #4165: the commission branch had the same f64 round-trip drift.
5391        let usdt = Currency::USDT();
5392        let (mut account, total, locked) = large_locked_usdt_margin_account();
5393        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5394        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5395        let manager = AccountsManager::new(clock, cache);
5396
5397        // This commission reproduces the exact panic values from issue #4165: the old
5398        // Decimal-then-f64 round-trips yielded total=99999997.91829666, free=99999965.05864664.
5399        let commission =
5400            Money::from_decimal(Decimal::from_str_exact("0.00000001").unwrap(), usdt).unwrap();
5401        let fill = OrderFilledSpec::builder().commission(commission).build();
5402
5403        // No PnL entries: only the commission branch runs.
5404        let mut pnls: [Money; 0] = [];
5405        manager
5406            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5407            .unwrap();
5408
5409        let balances = account.balances();
5410        let balance = balances.get(&usdt).expect("USDT balance");
5411        assert_eq!(balance.locked, locked, "locked margin preserved");
5412        assert_eq!(
5413            balance.total,
5414            total - commission,
5415            "total reduced by commission"
5416        );
5417        assert_eq!(
5418            balance.total,
5419            balance.locked + balance.free,
5420            "invariant total == locked + free must hold"
5421        );
5422    }
5423
5424    #[rstest]
5425    fn test_update_balance_multi_currency_negative_commission_creates_rebate_balance() {
5426        let usd = Currency::USD();
5427        let account_state = AccountState::new(
5428            AccountId::new("SIM-001"),
5429            AccountType::Cash,
5430            Vec::new(),
5431            Vec::new(),
5432            true,
5433            UUID4::new(),
5434            UnixNanos::default(),
5435            UnixNanos::default(),
5436            None,
5437        );
5438        let mut account = AccountAny::Cash(CashAccount::new(account_state, true, false));
5439        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5440        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5441        let manager = AccountsManager::new(clock, cache);
5442
5443        let fill = OrderFilledSpec::builder()
5444            .commission(Money::new(-1.0, usd))
5445            .build();
5446        let mut pnls: [Money; 0] = [];
5447        manager
5448            .update_balance_multi_currency(&mut account, &fill, &mut pnls)
5449            .unwrap();
5450
5451        let AccountAny::Cash(cash) = account else {
5452            panic!("Expected CashAccount");
5453        };
5454        let balance = cash.balance(Some(usd)).expect("USD rebate balance");
5455        assert_eq!(balance.total, Money::new(1.0, usd));
5456        assert_eq!(balance.locked, Money::zero(usd));
5457        assert_eq!(balance.free, Money::new(1.0, usd));
5458        assert_eq!(cash.commission(&usd), Some(Money::new(-1.0, usd)));
5459    }
5460
5461    fn build_margin_account_usd(balance: f64) -> MarginAccount {
5462        let usd = Currency::USD();
5463        let account_state = AccountState::new(
5464            AccountId::new("SIM-001"),
5465            AccountType::Margin,
5466            vec![AccountBalance::new(
5467                Money::new(balance, usd),
5468                Money::zero(usd),
5469                Money::new(balance, usd),
5470            )],
5471            Vec::new(),
5472            true,
5473            UUID4::new(),
5474            UnixNanos::default(),
5475            UnixNanos::default(),
5476            None,
5477        );
5478        MarginAccount::new(account_state, false)
5479    }
5480
5481    fn build_margin_account_usdt(balance: f64) -> MarginAccount {
5482        let usdt = Currency::USDT();
5483        let account_state = AccountState::new(
5484            AccountId::new("SIM-001"),
5485            AccountType::Margin,
5486            vec![AccountBalance::new(
5487                Money::new(balance, usdt),
5488                Money::zero(usdt),
5489                Money::new(balance, usdt),
5490            )],
5491            Vec::new(),
5492            true,
5493            UUID4::new(),
5494            UnixNanos::default(),
5495            UnixNanos::default(),
5496            None,
5497        );
5498        MarginAccount::new(account_state, false)
5499    }
5500
5501    fn build_hedging_position(
5502        instrument: &InstrumentAny,
5503        side: OrderSide,
5504        qty: &str,
5505        price: &str,
5506        id: &str,
5507    ) -> Position {
5508        build_hedging_position_at(instrument, side, qty, price, id, UnixNanos::default())
5509    }
5510
5511    fn build_hedging_position_at(
5512        instrument: &InstrumentAny,
5513        side: OrderSide,
5514        qty: &str,
5515        price: &str,
5516        id: &str,
5517        ts_event: UnixNanos,
5518    ) -> Position {
5519        let fill = OrderFilledSpec::builder()
5520            .instrument_id(instrument.id())
5521            .client_order_id(ClientOrderId::new(id))
5522            .venue_order_id(VenueOrderId::new(id))
5523            .trade_id(TradeId::new(id))
5524            .order_side(side)
5525            .last_qty(Quantity::from(qty))
5526            .last_px(Price::from(price))
5527            .currency(instrument.settlement_currency())
5528            .ts_event(ts_event)
5529            .ts_init(ts_event)
5530            .position_id(PositionId::new(id))
5531            .build();
5532        Position::new(instrument, fill)
5533    }
5534
5535    #[rstest]
5536    fn test_update_positions_in_place_nets_hedging_subpositions() {
5537        let usd = Currency::USD();
5538        let mut account = build_margin_account_usd(1_000_000.0);
5539        let instrument = audusd_sim();
5540        account.set_leverage(instrument.id(), Decimal::ONE);
5541        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5542
5543        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5544        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5545        let manager = AccountsManager::new(clock, cache);
5546
5547        // 5 long + 2 short, each 50 @ 1.0: net long 150 -> 150 * 1.0 * 0.03 = 4.50 USD
5548        let mut positions: Vec<Position> = Vec::new();
5549        for i in 0..5 {
5550            positions.push(build_hedging_position(
5551                &instrument_any,
5552                OrderSide::Buy,
5553                "50",
5554                "1.00000",
5555                &format!("L{i}"),
5556            ));
5557        }
5558
5559        for i in 0..2 {
5560            positions.push(build_hedging_position(
5561                &instrument_any,
5562                OrderSide::Sell,
5563                "50",
5564                "1.00000",
5565                &format!("S{i}"),
5566            ));
5567        }
5568
5569        let position_refs: Vec<&Position> = positions.iter().collect();
5570        let result = manager.update_positions_in_place(
5571            &mut account,
5572            &instrument_any,
5573            position_refs,
5574            UnixNanos::default(),
5575        );
5576        assert!(result.is_some(), "update_positions_in_place returned None");
5577
5578        let margin_maint = account.maintenance_margin(instrument.id());
5579        assert_eq!(
5580            margin_maint,
5581            Money::new(4.50, usd),
5582            "Maintenance margin must reflect net exposure (150 @ 1.00), not per-position sum",
5583        );
5584    }
5585
5586    #[rstest]
5587    #[case(OrderSide::Buy, "0.4", "1.20 USD")]
5588    #[case(OrderSide::Sell, "0.4", "1.20 USD")]
5589    #[case(OrderSide::Buy, "0.561", "1.68 USD")]
5590    #[case(OrderSide::Sell, "0.561", "1.68 USD")]
5591    fn test_update_positions_in_place_preserves_fractional_net_qty(
5592        #[case] side: OrderSide,
5593        #[case] qty: &str,
5594        #[case] expected: &str,
5595    ) {
5596        let instrument = audusd_sim();
5597        let instrument = InstrumentAny::CurrencyPair(instrument);
5598        let mut account = build_margin_account_usd(1_000_000.0);
5599        account.set_leverage(instrument.id(), Decimal::ONE);
5600        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5601        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5602        let manager = AccountsManager::new(clock, cache);
5603        let position = build_hedging_position(&instrument, side, qty, "100.00000", "P-MARGIN");
5604        let state = manager
5605            .update_positions_in_place(
5606                &mut account,
5607                &instrument,
5608                vec![&position],
5609                UnixNanos::default(),
5610            )
5611            .unwrap();
5612        let expected = Money::from(expected);
5613
5614        assert_eq!(account.maintenance_margin(instrument.id()), expected);
5615        assert_eq!(
5616            account.balance_locked(Some(Currency::USD())),
5617            Some(expected)
5618        );
5619        assert_eq!(
5620            state.margins,
5621            vec![MarginBalance::new(
5622                Money::zero(Currency::USD()),
5623                expected,
5624                Some(instrument.id()),
5625            )]
5626        );
5627    }
5628
5629    #[rstest]
5630    fn test_update_positions_in_place_net_zero_hedge_has_no_margin() {
5631        let usd = Currency::USD();
5632        let mut account = build_margin_account_usd(1_000_000.0);
5633        let instrument = audusd_sim();
5634        account.set_leverage(instrument.id(), Decimal::ONE);
5635        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5636
5637        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5638        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5639        let manager = AccountsManager::new(clock, cache);
5640
5641        // Long 100 plus short 100 at the same price: net zero, margin zero
5642        let long = build_hedging_position(&instrument_any, OrderSide::Buy, "100", "1.00000", "L");
5643        let short = build_hedging_position(&instrument_any, OrderSide::Sell, "100", "1.00000", "S");
5644
5645        let state = manager
5646            .update_positions_in_place(
5647                &mut account,
5648                &instrument_any,
5649                vec![&long, &short],
5650                UnixNanos::default(),
5651            )
5652            .expect("update_positions_in_place returned None");
5653
5654        assert!(account.margin(&instrument.id()).is_none());
5655        assert!(state.margins.is_empty());
5656        assert_eq!(account.balance_locked(Some(usd)), Some(Money::zero(usd)));
5657    }
5658
5659    #[rstest]
5660    fn test_update_positions_in_place_uses_net_side_avg_open_price() {
5661        let usd = Currency::USD();
5662        let mut account = build_margin_account_usd(1_000_000.0);
5663        let instrument = audusd_sim();
5664        account.set_leverage(instrument.id(), Decimal::ONE);
5665        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5666
5667        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5668        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5669        let manager = AccountsManager::new(clock, cache);
5670
5671        // Long 300 @ 0.80, short 100 @ 1.00: short closes part of long, residual long 200
5672        // @ 0.80, margin = 200 * 0.80 * 0.03 = 4.80 USD
5673        let long = build_hedging_position(&instrument_any, OrderSide::Buy, "300", "0.80000", "L1");
5674        let short =
5675            build_hedging_position(&instrument_any, OrderSide::Sell, "100", "1.00000", "S1");
5676
5677        let result = manager.update_positions_in_place(
5678            &mut account,
5679            &instrument_any,
5680            vec![&long, &short],
5681            UnixNanos::default(),
5682        );
5683        assert!(result.is_some(), "update_positions_in_place returned None");
5684
5685        let margin_maint = account.maintenance_margin(instrument.id());
5686        assert_eq!(margin_maint, Money::new(4.80, usd));
5687    }
5688
5689    #[rstest]
5690    fn test_update_positions_in_place_floating_dust_clears_margin() {
5691        // Sub-precision dust on a flat hedge (e.g. 0.3 - 0.2 - 0.1) must clear the
5692        // margin instead of feeding a sub-tick quantity into `make_qty`.
5693        let usdt = Currency::USDT();
5694        let mut account = build_margin_account_usdt(1_000_000.0);
5695        let instrument = currency_pair_btcusdt();
5696        account.set_leverage(instrument.id(), Decimal::ONE);
5697        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5698
5699        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5700        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5701        let manager = AccountsManager::new(clock, cache);
5702
5703        // 0.3 - 0.2 - 0.1 as f64 leaves ~5.55e-17, well below size_precision 6
5704        let long =
5705            build_hedging_position(&instrument_any, OrderSide::Buy, "0.300000", "50000.00", "L");
5706        let short_a = build_hedging_position(
5707            &instrument_any,
5708            OrderSide::Sell,
5709            "0.200000",
5710            "50000.00",
5711            "S1",
5712        );
5713        let short_b = build_hedging_position(
5714            &instrument_any,
5715            OrderSide::Sell,
5716            "0.100000",
5717            "50000.00",
5718            "S2",
5719        );
5720
5721        let state = manager
5722            .update_positions_in_place(
5723                &mut account,
5724                &instrument_any,
5725                vec![&long, &short_a, &short_b],
5726                UnixNanos::default(),
5727            )
5728            .expect("update_positions_in_place returned None");
5729
5730        assert!(account.margin(&instrument.id()).is_none());
5731        assert!(state.margins.is_empty());
5732        assert_eq!(account.balance_locked(Some(usdt)), Some(Money::zero(usdt)));
5733    }
5734
5735    #[rstest]
5736    fn test_update_positions_in_place_net_flat_clears_prior_base_currency_margin() {
5737        // A net-flat snapshot must clear margin in the same currency the prior update
5738        // used, not strand a base-currency lock under a settlement-currency zero.
5739        let usdt = Currency::USDT();
5740        let account_state = AccountState::new(
5741            AccountId::new("SIM-001"),
5742            AccountType::Margin,
5743            vec![AccountBalance::new(
5744                Money::new(1_000_000.0, usdt),
5745                Money::zero(usdt),
5746                Money::new(1_000_000.0, usdt),
5747            )],
5748            Vec::new(),
5749            true,
5750            UUID4::new(),
5751            UnixNanos::default(),
5752            UnixNanos::default(),
5753            Some(usdt),
5754        );
5755        let mut account = MarginAccount::new(account_state, false);
5756        let instrument = currency_pair_btcusdt();
5757        account.set_leverage(instrument.id(), Decimal::ONE);
5758        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5759
5760        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5761        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5762        let manager = AccountsManager::new(clock, cache);
5763
5764        // First snapshot: net long 0.5 BTC @ 50_000 -> non-zero base-currency margin.
5765        let long =
5766            build_hedging_position(&instrument_any, OrderSide::Buy, "0.500000", "50000.00", "L");
5767        let first = manager.update_positions_in_place(
5768            &mut account,
5769            &instrument_any,
5770            vec![&long],
5771            UnixNanos::default(),
5772        );
5773        assert!(first.is_some());
5774        let prior_margin = account.maintenance_margin(instrument.id());
5775        assert!(prior_margin.as_decimal() > Decimal::ZERO);
5776        assert_eq!(prior_margin.currency, usdt);
5777        let prior_locked = account.balance_locked(Some(usdt)).unwrap();
5778        assert!(prior_locked.as_decimal() > Decimal::ZERO);
5779
5780        // Second snapshot: offsetting short closes the net exposure.
5781        let short = build_hedging_position(
5782            &instrument_any,
5783            OrderSide::Sell,
5784            "0.500000",
5785            "50000.00",
5786            "S",
5787        );
5788        let second = manager.update_positions_in_place(
5789            &mut account,
5790            &instrument_any,
5791            vec![&long, &short],
5792            UnixNanos::default(),
5793        );
5794        let second_state = second.expect("net-flat maintenance update should generate state");
5795
5796        // Net-flat: the per-instrument margin entry and resulting base-currency lock must clear.
5797        assert!(account.margin(&instrument.id()).is_none());
5798        assert!(second_state.margins.is_empty());
5799        assert_eq!(
5800            account.balance_locked(Some(usdt)).unwrap(),
5801            Money::zero(usdt)
5802        );
5803    }
5804
5805    #[rstest]
5806    fn test_update_positions_in_place_net_flat_preserves_prior_initial_margin() {
5807        let usd = Currency::USD();
5808        let mut account = build_margin_account_usd(1_000_000.0);
5809        let instrument = audusd_sim();
5810        account.set_leverage(instrument.id(), Decimal::ONE);
5811        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5812        let initial = Money::new(25.0, usd);
5813        account.update_margin(MarginBalance::new(
5814            initial,
5815            Money::new(5.0, usd),
5816            Some(instrument.id()),
5817        ));
5818
5819        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5820        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5821        let manager = AccountsManager::new(clock, cache);
5822
5823        let long = build_hedging_position(&instrument_any, OrderSide::Buy, "100", "1.00000", "L");
5824        let short = build_hedging_position(&instrument_any, OrderSide::Sell, "100", "1.00000", "S");
5825        let state = manager
5826            .update_positions_in_place(
5827                &mut account,
5828                &instrument_any,
5829                vec![&long, &short],
5830                UnixNanos::default(),
5831            )
5832            .expect("net-flat maintenance update should generate state");
5833
5834        let margin = account
5835            .margin(&instrument.id())
5836            .expect("initial margin should remain");
5837        assert_eq!(margin.initial, initial);
5838        assert_eq!(margin.maintenance, Money::zero(usd));
5839        assert_eq!(state.margins, vec![margin]);
5840    }
5841
5842    #[rstest]
5843    fn test_update_positions_in_place_flip_uses_flipping_fill_price() {
5844        // NETTING leaves the residual at the flipping fill's price; the replay must too,
5845        // or a gross net-side average will under-margin reversal cases.
5846        let usd = Currency::USD();
5847        let mut account = build_margin_account_usd(1_000_000.0);
5848        let instrument = audusd_sim();
5849        account.set_leverage(instrument.id(), Decimal::ONE);
5850        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5851
5852        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5853        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5854        let manager = AccountsManager::new(clock, cache);
5855
5856        // L100@1, S50@2, S100@3: NETTING residual short 50 @ 3 -> 4.50 USD,
5857        // a gross net-side average would give 4.00 USD (under-margin).
5858        let long = build_hedging_position_at(
5859            &instrument_any,
5860            OrderSide::Buy,
5861            "100",
5862            "1.00000",
5863            "L",
5864            UnixNanos::from(1),
5865        );
5866        let short_partial = build_hedging_position_at(
5867            &instrument_any,
5868            OrderSide::Sell,
5869            "50",
5870            "2.00000",
5871            "S1",
5872            UnixNanos::from(2),
5873        );
5874        let short_flip = build_hedging_position_at(
5875            &instrument_any,
5876            OrderSide::Sell,
5877            "100",
5878            "3.00000",
5879            "S2",
5880            UnixNanos::from(3),
5881        );
5882
5883        let result = manager.update_positions_in_place(
5884            &mut account,
5885            &instrument_any,
5886            vec![&long, &short_partial, &short_flip],
5887            UnixNanos::default(),
5888        );
5889        assert!(result.is_some(), "update_positions_in_place returned None");
5890
5891        let margin_maint = account.maintenance_margin(instrument.id());
5892        assert_eq!(margin_maint, Money::new(4.50, usd));
5893    }
5894
5895    #[rstest]
5896    fn test_update_positions_in_place_same_ts_legs_ordering_is_deterministic() {
5897        // positions_open iterates an AHashSet; without a tie-breaker the fold of
5898        // same-ts reversal legs would vary across runs.
5899        let usd = Currency::USD();
5900        let instrument = audusd_sim();
5901        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
5902
5903        // Same-ts reversal: long 100 @ 1.0 (A), short 50 @ 2.0 (B), short 100 @ 3.0 (C).
5904        // Ordered by position_id, the fold yields short 50 @ 3.0 -> 4.50 USD.
5905        let same_ts = UnixNanos::from(42);
5906        let l_a = build_hedging_position_at(
5907            &instrument_any,
5908            OrderSide::Buy,
5909            "100",
5910            "1.00000",
5911            "A",
5912            same_ts,
5913        );
5914        let s_b = build_hedging_position_at(
5915            &instrument_any,
5916            OrderSide::Sell,
5917            "50",
5918            "2.00000",
5919            "B",
5920            same_ts,
5921        );
5922        let s_c = build_hedging_position_at(
5923            &instrument_any,
5924            OrderSide::Sell,
5925            "100",
5926            "3.00000",
5927            "C",
5928            same_ts,
5929        );
5930
5931        let permutations: Vec<Vec<&Position>> = vec![
5932            vec![&l_a, &s_b, &s_c],
5933            vec![&s_c, &s_b, &l_a],
5934            vec![&s_b, &l_a, &s_c],
5935            vec![&s_c, &l_a, &s_b],
5936        ];
5937
5938        let mut results: Vec<Money> = Vec::new();
5939
5940        for perm in permutations {
5941            let mut account = build_margin_account_usd(1_000_000.0);
5942            account.set_leverage(instrument.id(), Decimal::ONE);
5943
5944            let clock = Rc::new(RefCell::new(VirtualClock::new()));
5945            let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5946            let manager = AccountsManager::new(clock, cache);
5947
5948            let result = manager.update_positions_in_place(
5949                &mut account,
5950                &instrument_any,
5951                perm,
5952                UnixNanos::default(),
5953            );
5954            assert!(result.is_some());
5955            results.push(account.maintenance_margin(instrument.id()));
5956        }
5957
5958        let first = results[0];
5959        for r in &results[1..] {
5960            assert_eq!(
5961                *r, first,
5962                "maintenance margin must be deterministic across permutations"
5963            );
5964        }
5965        // Canonical sorted order yields the NETTING residual short 50 @ 3.0
5966        assert_eq!(first, Money::new(4.50, usd));
5967    }
5968
5969    #[rstest]
5970    fn test_update_positions_in_place_xrate_unavailable_returns_none() {
5971        // EUR base account on a USD-settled instrument with no xrate must bail out
5972        // rather than write a stale or zero margin.
5973        let eur = Currency::EUR();
5974        let account_state = AccountState::new(
5975            AccountId::new("SIM-001"),
5976            AccountType::Margin,
5977            vec![AccountBalance::new(
5978                Money::new(1_000_000.0, eur),
5979                Money::zero(eur),
5980                Money::new(1_000_000.0, eur),
5981            )],
5982            Vec::new(),
5983            true,
5984            UUID4::new(),
5985            UnixNanos::default(),
5986            UnixNanos::default(),
5987            Some(eur),
5988        );
5989        let mut account = MarginAccount::new(account_state, false);
5990        let instrument = audusd_sim();
5991        account.set_leverage(instrument.id(), Decimal::ONE);
5992        let instrument_any = InstrumentAny::CurrencyPair(instrument);
5993
5994        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5995        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
5996        let manager = AccountsManager::new(clock, cache);
5997
5998        let pos = build_hedging_position(&instrument_any, OrderSide::Buy, "100", "1.00000", "L");
5999        let result = manager.update_positions_in_place(
6000            &mut account,
6001            &instrument_any,
6002            vec![&pos],
6003            UnixNanos::default(),
6004        );
6005        assert!(result.is_none(), "xrate-unavailable must return None");
6006    }
6007
6008    #[rstest]
6009    fn test_update_positions_in_place_base_xrate_uses_ask_for_short_net_position() {
6010        let eur = Currency::EUR();
6011        let account_state = AccountState::new(
6012            AccountId::new("SIM-001"),
6013            AccountType::Margin,
6014            vec![AccountBalance::new(
6015                Money::new(1_000.0, eur),
6016                Money::zero(eur),
6017                Money::new(1_000.0, eur),
6018            )],
6019            Vec::new(),
6020            true,
6021            UUID4::new(),
6022            UnixNanos::default(),
6023            UnixNanos::default(),
6024            Some(eur),
6025        );
6026        let mut account = MarginAccount::new(account_state, false);
6027        let instrument = audusd_sim();
6028        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
6029
6030        let clock = Rc::new(RefCell::new(VirtualClock::new()));
6031        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
6032        add_usdeur_quote(&cache, "0.90000", "1.10000");
6033        let manager = AccountsManager::new(clock, cache);
6034
6035        let position =
6036            build_hedging_position(&instrument_any, OrderSide::Sell, "100", "2.00000", "S");
6037        let result = manager.update_positions_in_place(
6038            &mut account,
6039            &instrument_any,
6040            vec![&position],
6041            UnixNanos::default(),
6042        );
6043
6044        assert!(result.is_some());
6045        assert_eq!(
6046            account.maintenance_margin(instrument.id()),
6047            Money::new(6.60, eur)
6048        );
6049    }
6050
6051    #[rstest]
6052    fn test_update_positions_in_place_closed_positions_filtered() {
6053        // Closed positions in the input must not contribute to net exposure.
6054        let usd = Currency::USD();
6055        let mut account = build_margin_account_usd(1_000_000.0);
6056        let instrument = audusd_sim();
6057        account.set_leverage(instrument.id(), Decimal::ONE);
6058        let instrument_any = InstrumentAny::CurrencyPair(instrument.clone());
6059
6060        let clock = Rc::new(RefCell::new(VirtualClock::new()));
6061        let cache = Rc::new(RefCell::new(Cache::new(None, None)));
6062        let manager = AccountsManager::new(clock, cache);
6063
6064        // Close a position by applying an offsetting fill
6065        let open_long = build_hedging_position_at(
6066            &instrument_any,
6067            OrderSide::Buy,
6068            "100",
6069            "1.00000",
6070            "C",
6071            UnixNanos::from(1),
6072        );
6073        let close_fill = OrderFilledSpec::builder()
6074            .instrument_id(instrument.id())
6075            .client_order_id(ClientOrderId::new("Cclose"))
6076            .venue_order_id(VenueOrderId::new("Cclose"))
6077            .trade_id(TradeId::new("Cclose"))
6078            .order_side(OrderSide::Sell)
6079            .last_qty(Quantity::from("100"))
6080            .last_px(Price::from("1.00000"))
6081            .currency(instrument.settlement_currency())
6082            .ts_event(UnixNanos::from(2))
6083            .ts_init(UnixNanos::from(2))
6084            .position_id(PositionId::new("C"))
6085            .build();
6086        let mut closed = open_long;
6087        closed.apply(&close_fill);
6088        assert!(closed.is_closed());
6089
6090        // Active open position alongside the closed one
6091        let live = build_hedging_position_at(
6092            &instrument_any,
6093            OrderSide::Buy,
6094            "50",
6095            "1.00000",
6096            "L",
6097            UnixNanos::from(3),
6098        );
6099
6100        let result = manager.update_positions_in_place(
6101            &mut account,
6102            &instrument_any,
6103            vec![&closed, &live],
6104            UnixNanos::default(),
6105        );
6106        assert!(result.is_some());
6107
6108        // Only the live 50 long contributes: margin = 50 * 1.0 * 0.03 = 1.50 USD
6109        assert_eq!(
6110            account.maintenance_margin(instrument.id()),
6111            Money::new(1.50, usd)
6112        );
6113    }
6114
6115    fn add_usdeur_quote(cache: &Rc<RefCell<Cache>>, bid: &str, ask: &str) {
6116        let instrument = default_fx_ccy(Symbol::from("USD/EUR"), Some(Venue::from("SIM")));
6117        let quote = QuoteTick::new(
6118            instrument.id(),
6119            Price::from(bid),
6120            Price::from(ask),
6121            Quantity::from("1"),
6122            Quantity::from("1"),
6123            UnixNanos::default(),
6124            UnixNanos::default(),
6125        );
6126        let mut cache = cache.borrow_mut();
6127        cache
6128            .add_instrument(InstrumentAny::CurrencyPair(instrument))
6129            .unwrap();
6130        cache.add_quote(quote).unwrap();
6131    }
6132
6133    fn usd_usdt_future() -> CryptoFuture {
6134        CryptoFuture::builder()
6135            .instrument_id(InstrumentId::from("ETHUSD-123.SIM"))
6136            .raw_symbol(Symbol::from("ETHUSD-123"))
6137            .underlying(Currency::ETH())
6138            .quote_currency(Currency::USD())
6139            .settlement_currency(Currency::USDT())
6140            .is_inverse(false)
6141            .activation_ns(0.into())
6142            .expiration_ns(0.into())
6143            .price_precision(2)
6144            .size_precision(0)
6145            .price_increment(Price::from("0.01"))
6146            .size_increment(Quantity::from("1"))
6147            .margin_init(Decimal::new(1, 1))
6148            .margin_maint(Decimal::new(1, 1))
6149            .ts_event(0.into())
6150            .ts_init(0.into())
6151            .build()
6152            .unwrap()
6153    }
6154}