Skip to main content

nautilus_model/accounts/
any.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//! Enum wrapper providing a type-erased view over the various concrete [`Account`] implementations.
17//!
18//! The `AccountAny` enum is primarily used when heterogeneous account types need to be stored in a
19//! single collection (e.g. `Vec<AccountAny>`).  Each variant simply embeds one of the concrete
20//! account structs defined in this module.
21
22use enum_dispatch::enum_dispatch;
23use indexmap::IndexMap;
24use nautilus_core::correctness::{CorrectnessResult, CorrectnessResultExt, FAILED};
25use serde::{Deserialize, Serialize};
26
27use crate::{
28    accounts::{Account, BettingAccount, CashAccount, MarginAccount, WalletAccount},
29    enums::{AccountType, LiquiditySide},
30    events::{AccountState, OrderFilled},
31    fees::MakerTakerFeeRates,
32    identifiers::AccountId,
33    instruments::InstrumentAny,
34    position::Position,
35    types::{AccountBalance, Currency, Money, Price, Quantity},
36};
37
38/// Represents any account type, so accounts can be held in one collection.
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[enum_dispatch(Account)]
41pub enum AccountAny {
42    /// A margin account holding leveraged positions.
43    Margin(MarginAccount),
44    /// A cash account holding unleveraged positions.
45    Cash(CashAccount),
46    /// A betting account holding backed and laid stakes.
47    Betting(BettingAccount),
48    /// A blockchain wallet account holding native and token balances.
49    Wallet(WalletAccount),
50}
51
52impl AccountAny {
53    /// Returns a copy without stored account state events.
54    #[must_use]
55    pub fn clone_without_events(&self) -> Self {
56        match self {
57            Self::Margin(margin) => Self::Margin(margin.clone_without_events()),
58            Self::Cash(cash) => Self::Cash(cash.clone_without_events()),
59            Self::Betting(betting) => Self::Betting(betting.clone_without_events()),
60            Self::Wallet(wallet) => Self::Wallet(wallet.clone_without_events()),
61        }
62    }
63
64    #[must_use]
65    pub fn id(&self) -> AccountId {
66        Account::id(self)
67    }
68
69    #[must_use]
70    pub fn last_event(&self) -> Option<AccountState> {
71        Account::last_event(self)
72    }
73
74    #[must_use]
75    pub fn events(&self) -> Vec<AccountState> {
76        Account::events(self)
77    }
78
79    /// Applies an account state event to update the account.
80    ///
81    /// # Errors
82    ///
83    /// Returns an error if the event belongs to a different account or the account state cannot be
84    /// applied (e.g., negative balance when borrowing is not allowed for a cash account).
85    pub fn apply(&mut self, event: AccountState) -> anyhow::Result<()> {
86        Account::apply(self, event)
87    }
88
89    /// Sets whether account state should be recalculated from order fills.
90    pub fn set_calculate_account_state(&mut self, calculate_account_state: bool) {
91        match self {
92            Self::Margin(margin) => margin.base.calculate_account_state = calculate_account_state,
93            Self::Cash(cash) => cash.base.calculate_account_state = calculate_account_state,
94            Self::Betting(betting) => {
95                betting.base.calculate_account_state = calculate_account_state;
96            }
97            Self::Wallet(wallet) => {
98                wallet.base.calculate_account_state = calculate_account_state;
99            }
100        }
101    }
102
103    #[must_use]
104    pub fn balances(&self) -> IndexMap<Currency, AccountBalance> {
105        Account::balances(self)
106    }
107
108    #[must_use]
109    pub fn balances_locked(&self) -> IndexMap<Currency, Money> {
110        Account::balances_locked(self)
111    }
112
113    #[must_use]
114    pub fn base_currency(&self) -> Option<Currency> {
115        Account::base_currency(self)
116    }
117
118    /// # Errors
119    ///
120    /// Returns an error if `events` is empty or an account state cannot be created or applied.
121    pub fn from_events(events: &[AccountState]) -> anyhow::Result<Self> {
122        let Some((init_event, remaining_events)) = events.split_first() else {
123            anyhow::bail!("No account events provided to create `AccountAny`");
124        };
125
126        let mut account = Self::from_state_checked(init_event.clone())?;
127
128        for event in remaining_events {
129            account.apply(event.clone())?;
130        }
131
132        Ok(account)
133    }
134
135    /// # Errors
136    ///
137    /// Returns an error if calculating P&Ls fails for the underlying account.
138    pub fn calculate_pnls(
139        &self,
140        instrument: &InstrumentAny,
141        fill: &OrderFilled,
142        position: Option<Position>,
143    ) -> anyhow::Result<Vec<Money>> {
144        Account::calculate_pnls(self, instrument, fill, position)
145    }
146
147    /// # Errors
148    ///
149    /// Returns an error if calculating commission fails for the underlying account.
150    pub fn calculate_commission(
151        &self,
152        instrument: &InstrumentAny,
153        last_qty: Quantity,
154        last_px: Price,
155        liquidity_side: LiquiditySide,
156        fee_rates: MakerTakerFeeRates,
157        use_quote_for_inverse: Option<bool>,
158    ) -> anyhow::Result<Money> {
159        Account::calculate_commission(
160            self,
161            instrument,
162            last_qty,
163            last_px,
164            liquidity_side,
165            fee_rates,
166            use_quote_for_inverse,
167        )
168    }
169
170    #[must_use]
171    pub fn balance(&self, currency: Option<Currency>) -> Option<&AccountBalance> {
172        Account::balance(self, currency)
173    }
174}
175
176impl AccountAny {
177    /// Creates an `AccountAny` from an `AccountState`.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if a wallet account state is invalid.
182    pub fn try_from_state(event: AccountState) -> Result<Self, &'static str> {
183        Self::from_state_checked(event).map_err(|_| "Invalid wallet account state")
184    }
185
186    fn from_state_checked(event: AccountState) -> CorrectnessResult<Self> {
187        match event.account_type {
188            AccountType::Margin => Ok(Self::Margin(MarginAccount::new(event, false))),
189            AccountType::Cash => Ok(Self::Cash(CashAccount::new(event, false, false))),
190            AccountType::Betting => Ok(Self::Betting(BettingAccount::new(event, false))),
191            AccountType::Wallet => Ok(Self::Wallet(WalletAccount::new_checked(event, false)?)),
192        }
193    }
194}
195
196impl From<AccountState> for AccountAny {
197    /// Creates an `AccountAny` from an `AccountState`.
198    ///
199    /// # Panics
200    ///
201    /// Panics if a wallet account state is invalid.
202    /// Use [`AccountAny::try_from_state`] for fallible conversion.
203    fn from(event: AccountState) -> Self {
204        Self::from_state_checked(event).expect_display(FAILED)
205    }
206}
207
208impl PartialEq for AccountAny {
209    fn eq(&self, other: &Self) -> bool {
210        self.id() == other.id()
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use std::sync::Arc;
217
218    use rstest::rstest;
219    use rust_decimal::Decimal;
220
221    use crate::{
222        accounts::{
223            Account, AccountAny,
224            margin_model::{MarginModel, MarginModelAny, StandardMarginModel},
225        },
226        events::{AccountState, account::stubs::*},
227        identifiers::{AccountId, InstrumentId},
228        types::Money,
229    };
230
231    #[rstest]
232    fn test_from_events_empty_returns_error() {
233        let events: Vec<AccountState> = vec![];
234        let result = AccountAny::from_events(&events);
235
236        assert_eq!(
237            result.unwrap_err().to_string(),
238            "No account events provided to create `AccountAny`"
239        );
240    }
241
242    #[rstest]
243    fn test_from_events_single_cash_event(cash_account_state: AccountState) {
244        let result = AccountAny::from_events(&[cash_account_state]);
245        assert!(result.is_ok());
246        assert!(matches!(result.unwrap(), AccountAny::Cash(_)));
247    }
248
249    #[rstest]
250    fn test_from_events_rejects_different_account(cash_account_state: AccountState) {
251        let mut different_account = cash_account_state.clone();
252        different_account.account_id = AccountId::from("OTHER-001");
253
254        let result = AccountAny::from_events(&[cash_account_state, different_account]);
255
256        assert_eq!(
257            result.unwrap_err().to_string(),
258            "Account event had a different account ID: expected SIM-001, received OTHER-001"
259        );
260    }
261
262    #[rstest]
263    #[case::cash(cash_account_state())]
264    #[case::margin(margin_account_state())]
265    #[case::betting(betting_account_state())]
266    #[case::wallet(wallet_account_state())]
267    fn test_apply_rejects_different_account_without_mutation(#[case] state: AccountState) {
268        let mut account = AccountAny::try_from_state(state.clone()).unwrap();
269        let balances_before = account.balances();
270        let mut foreign = state;
271        foreign.account_id = AccountId::from("OTHER-001");
272
273        let error = account.apply(foreign).unwrap_err();
274
275        assert_eq!(
276            error.to_string(),
277            "Account event had a different account ID: expected SIM-001, received OTHER-001"
278        );
279        assert_eq!(account.event_count(), 1);
280        assert_eq!(account.balances(), balances_before);
281    }
282
283    #[rstest]
284    fn test_delegated_state_accessors(cash_account_state: AccountState) {
285        let balance = cash_account_state.balances[0];
286        let account = AccountAny::try_from_state(cash_account_state.clone()).unwrap();
287
288        assert_eq!(account.last_event(), Some(cash_account_state.clone()));
289        assert_eq!(account.events(), vec![cash_account_state.clone()]);
290        assert_eq!(account.base_currency(), cash_account_state.base_currency);
291        assert_eq!(
292            account.balances_locked().get(&balance.currency),
293            Some(&balance.locked)
294        );
295        assert_eq!(account.balances().get(&balance.currency), Some(&balance));
296    }
297
298    #[rstest]
299    fn test_equality_compares_account_ids(cash_account_state: AccountState) {
300        let account = AccountAny::try_from_state(cash_account_state.clone()).unwrap();
301        let same = AccountAny::try_from_state(cash_account_state.clone()).unwrap();
302        let mut other_state = cash_account_state;
303        other_state.account_id = AccountId::from("OTHER-001");
304        let other = AccountAny::try_from_state(other_state).unwrap();
305
306        assert_eq!(account, same);
307        assert_ne!(account, other);
308    }
309
310    #[rstest]
311    fn test_from_events_single_margin_event(margin_account_state: AccountState) {
312        let result = AccountAny::from_events(&[margin_account_state]);
313        assert!(result.is_ok());
314        assert!(matches!(result.unwrap(), AccountAny::Margin(_)));
315    }
316
317    #[rstest]
318    #[case::cash(cash_account_state())]
319    #[case::margin(margin_account_state())]
320    #[case::betting(betting_account_state())]
321    #[case::wallet(wallet_account_state())]
322    fn test_clone_without_events_preserves_current_state(#[case] state: AccountState) {
323        let currency = state.balances[0].currency;
324        let instrument_id = InstrumentId::from("CLONE-TEST.SIM");
325        let locked = Money::from_decimal(Decimal::new(725, 2), currency).unwrap();
326        let commission = Money::from_decimal(Decimal::new(135, 2), currency).unwrap();
327        let mut account = AccountAny::try_from_state(state.clone()).unwrap();
328        account.apply(state).unwrap();
329
330        let base = match &mut account {
331            AccountAny::Margin(account) => &mut account.base,
332            AccountAny::Cash(account) => &mut account.base,
333            AccountAny::Betting(account) => &mut account.base,
334            AccountAny::Wallet(account) => &mut account.base,
335        };
336        base.calculate_account_state = true;
337        base.commissions.insert(currency, commission);
338
339        match &mut account {
340            AccountAny::Margin(account) => {
341                account.set_default_leverage(Decimal::new(7, 0));
342                account.set_leverage(instrument_id, Decimal::new(3, 0));
343                account.set_margin_model(MarginModelAny::Standard(StandardMarginModel).into());
344            }
345            AccountAny::Cash(account) => {
346                account.allow_borrowing = true;
347                account
348                    .balances_locked
349                    .insert((instrument_id, currency), locked);
350            }
351            AccountAny::Betting(account) => {
352                account
353                    .balances_locked
354                    .insert((instrument_id, currency), locked);
355            }
356            AccountAny::Wallet(account) => {
357                account
358                    .balances_locked
359                    .insert((instrument_id, currency), locked);
360            }
361        }
362
363        let cloned = account.clone_without_events();
364        let mut expected = account.clone();
365
366        match &mut expected {
367            AccountAny::Margin(account) => account.base.events = Arc::default(),
368            AccountAny::Cash(account) => account.base.events = Arc::default(),
369            AccountAny::Betting(account) => account.base.events = Arc::default(),
370            AccountAny::Wallet(account) => account.base.events = Arc::default(),
371        }
372
373        assert_eq!(account.event_count(), 2);
374        assert_eq!(cloned.event_count(), 0);
375        match (&account, &cloned) {
376            (AccountAny::Margin(source), AccountAny::Margin(cloned)) => {
377                assert_eq!(cloned.margin_model().name(), source.margin_model().name());
378                assert_eq!(cloned.margin_model().name(), "standard");
379            }
380            (AccountAny::Cash(source), AccountAny::Cash(cloned)) => {
381                assert_eq!(cloned.balances_locked, source.balances_locked);
382                assert!(cloned.allow_borrowing);
383            }
384            (AccountAny::Betting(source), AccountAny::Betting(cloned)) => {
385                assert_eq!(cloned.balances_locked, source.balances_locked);
386            }
387            (AccountAny::Wallet(source), AccountAny::Wallet(cloned)) => {
388                assert_eq!(cloned.balances_locked, source.balances_locked);
389            }
390            _ => panic!("cloned account variant changed"),
391        }
392        assert_eq!(
393            serde_json::to_value(&cloned).unwrap(),
394            serde_json::to_value(&expected).unwrap()
395        );
396    }
397
398    #[rstest]
399    fn test_try_from_state_cash(cash_account_state: AccountState) {
400        let result: Result<AccountAny, &'static str> =
401            AccountAny::try_from_state(cash_account_state);
402        assert!(result.is_ok());
403        assert!(matches!(result.unwrap(), AccountAny::Cash(_)));
404    }
405
406    #[rstest]
407    fn test_try_from_state_margin(margin_account_state: AccountState) {
408        let result = AccountAny::try_from_state(margin_account_state);
409        assert!(result.is_ok());
410        assert!(matches!(result.unwrap(), AccountAny::Margin(_)));
411    }
412
413    #[rstest]
414    fn test_try_from_state_betting(betting_account_state: AccountState) {
415        let result = AccountAny::try_from_state(betting_account_state);
416        assert!(result.is_ok());
417        assert!(matches!(result.unwrap(), AccountAny::Betting(_)));
418    }
419
420    #[rstest]
421    fn test_try_from_state_wallet(wallet_account_state: AccountState) {
422        let result = AccountAny::try_from_state(wallet_account_state);
423        assert!(result.is_ok());
424        assert!(matches!(result.unwrap(), AccountAny::Wallet(_)));
425    }
426
427    #[rstest]
428    fn test_try_from_state_invalid_wallet_returns_static_error() {
429        let result: Result<AccountAny, &'static str> =
430            AccountAny::try_from_state(invalid_wallet_state());
431
432        assert_eq!(result.unwrap_err(), "Invalid wallet account state");
433    }
434
435    #[rstest]
436    fn test_from_events_wallet_applies_sequence(
437        wallet_account_state: AccountState,
438        wallet_account_state_changed: AccountState,
439    ) {
440        let result = AccountAny::from_events(&[wallet_account_state, wallet_account_state_changed]);
441        assert!(result.is_ok());
442        let account = result.unwrap();
443        assert!(matches!(account, AccountAny::Wallet(_)));
444        assert_eq!(account.event_count(), 2);
445    }
446
447    #[rstest]
448    fn test_from_events_wallet_rejects_negative_initial_balance() {
449        let result = AccountAny::from_events(&[invalid_wallet_state()]);
450
451        assert!(result.is_err());
452        assert_eq!(
453            result.unwrap_err().to_string(),
454            "Wallet account balance total was negative"
455        );
456    }
457
458    #[rstest]
459    #[case::cash(cash_account_state(), "Cash")]
460    #[case::margin(margin_account_state(), "Margin")]
461    #[case::betting(betting_account_state(), "Betting")]
462    #[case::wallet(wallet_account_state(), "Wallet")]
463    fn test_serde_round_trip_preserves_variant_payload(
464        #[case] state: AccountState,
465        #[case] expected_variant: &str,
466    ) {
467        let account = AccountAny::try_from_state(state).unwrap();
468
469        let value = serde_json::to_value(&account).unwrap();
470        let object = value.as_object().unwrap();
471        assert_eq!(object.len(), 1);
472        assert!(object.contains_key(expected_variant));
473
474        let deserialized: AccountAny = serde_json::from_value(value).unwrap();
475        assert_eq!(deserialized.id(), account.id());
476        assert_eq!(deserialized.events(), account.events());
477        assert_eq!(deserialized.balances(), account.balances());
478    }
479
480    #[rstest]
481    #[case::cash(include_str!("../../test_data/account_legacy_cash.json"), "Cash")]
482    #[case::margin(include_str!("../../test_data/account_legacy_margin.json"), "Margin")]
483    #[case::betting(include_str!("../../test_data/account_legacy_betting.json"), "Betting")]
484    fn test_deserializes_legacy_payload(#[case] json: &str, #[case] expected_variant: &str) {
485        let account: AccountAny = serde_json::from_str(json).unwrap();
486        let variant = match &account {
487            AccountAny::Cash(_) => "Cash",
488            AccountAny::Margin(_) => "Margin",
489            AccountAny::Betting(_) => "Betting",
490            AccountAny::Wallet(_) => "Wallet",
491        };
492        assert_eq!(variant, expected_variant);
493        assert_eq!(account.event_count(), 1);
494    }
495
496    fn invalid_wallet_state() -> AccountState {
497        AccountState::new(
498            AccountId::from("WALLET-001"),
499            crate::enums::AccountType::Wallet,
500            vec![crate::types::AccountBalance::new(
501                crate::types::Money::from("-1 ETH"),
502                crate::types::Money::from("0 ETH"),
503                crate::types::Money::from("-1 ETH"),
504            )],
505            vec![],
506            true,
507            crate::identifiers::stubs::uuid4(),
508            0.into(),
509            0.into(),
510            None,
511        )
512    }
513}