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