nautilus-model 0.62.0

Domain model for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Enum wrapper providing a type-erased view over the various concrete [`Account`] implementations.
//!
//! The `AccountAny` enum is primarily used when heterogeneous account types need to be stored in a
//! single collection (e.g. `Vec<AccountAny>`).  Each variant simply embeds one of the concrete
//! account structs defined in this module.

use enum_dispatch::enum_dispatch;
use indexmap::IndexMap;
use nautilus_core::correctness::{CorrectnessResult, CorrectnessResultExt, FAILED};
use serde::{Deserialize, Serialize};

use crate::{
    accounts::{Account, BettingAccount, CashAccount, MarginAccount, WalletAccount},
    enums::{AccountType, LiquiditySide},
    events::{AccountState, OrderFilled},
    identifiers::AccountId,
    instruments::InstrumentAny,
    position::Position,
    types::{AccountBalance, Currency, Money, Price, Quantity},
};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[enum_dispatch(Account)]
pub enum AccountAny {
    Margin(MarginAccount),
    Cash(CashAccount),
    Betting(BettingAccount),
    Wallet(WalletAccount),
}

impl AccountAny {
    #[must_use]
    pub fn id(&self) -> AccountId {
        match self {
            Self::Margin(margin) => margin.id,
            Self::Cash(cash) => cash.id,
            Self::Betting(betting) => betting.id,
            Self::Wallet(wallet) => wallet.id,
        }
    }

    #[must_use]
    pub fn last_event(&self) -> Option<AccountState> {
        match self {
            Self::Margin(margin) => margin.last_event(),
            Self::Cash(cash) => cash.last_event(),
            Self::Betting(betting) => betting.last_event(),
            Self::Wallet(wallet) => wallet.last_event(),
        }
    }

    #[must_use]
    pub fn events(&self) -> Vec<AccountState> {
        match self {
            Self::Margin(margin) => margin.events(),
            Self::Cash(cash) => cash.events(),
            Self::Betting(betting) => betting.events(),
            Self::Wallet(wallet) => wallet.events(),
        }
    }

    /// Applies an account state event to update the account.
    ///
    /// # Errors
    ///
    /// Returns an error if the event belongs to a different account or the account state cannot be
    /// applied (e.g., negative balance when borrowing is not allowed for a cash account).
    pub fn apply(&mut self, event: AccountState) -> anyhow::Result<()> {
        anyhow::ensure!(
            event.account_id == self.id(),
            "Account event had a different account ID: expected {}, received {}",
            self.id(),
            event.account_id
        );

        match self {
            Self::Margin(margin) => margin.apply(event),
            Self::Cash(cash) => cash.apply(event),
            Self::Betting(betting) => betting.apply(event),
            Self::Wallet(wallet) => wallet.apply(event),
        }
    }

    /// Sets whether account state should be recalculated from order fills.
    pub fn set_calculate_account_state(&mut self, calculate_account_state: bool) {
        match self {
            Self::Margin(margin) => margin.base.calculate_account_state = calculate_account_state,
            Self::Cash(cash) => cash.base.calculate_account_state = calculate_account_state,
            Self::Betting(betting) => {
                betting.base.calculate_account_state = calculate_account_state;
            }
            Self::Wallet(wallet) => {
                wallet.base.calculate_account_state = calculate_account_state;
            }
        }
    }

    #[must_use]
    pub fn balances(&self) -> IndexMap<Currency, AccountBalance> {
        match self {
            Self::Margin(margin) => margin.balances(),
            Self::Cash(cash) => cash.balances(),
            Self::Betting(betting) => betting.balances(),
            Self::Wallet(wallet) => wallet.balances(),
        }
    }

    #[must_use]
    pub fn balances_locked(&self) -> IndexMap<Currency, Money> {
        match self {
            Self::Margin(margin) => margin.balances_locked(),
            Self::Cash(cash) => cash.balances_locked(),
            Self::Betting(betting) => betting.balances_locked(),
            Self::Wallet(wallet) => wallet.balances_locked(),
        }
    }

    #[must_use]
    pub fn base_currency(&self) -> Option<Currency> {
        match self {
            Self::Margin(margin) => margin.base_currency(),
            Self::Cash(cash) => cash.base_currency(),
            Self::Betting(betting) => betting.base_currency(),
            Self::Wallet(wallet) => wallet.base_currency(),
        }
    }

    /// # Errors
    ///
    /// Returns an error if `events` is empty or an account state cannot be created or applied.
    pub fn from_events(events: &[AccountState]) -> anyhow::Result<Self> {
        let Some((init_event, remaining_events)) = events.split_first() else {
            anyhow::bail!("No account events provided to create `AccountAny`");
        };

        let mut account = Self::from_state_checked(init_event.clone())?;

        for event in remaining_events {
            account.apply(event.clone())?;
        }

        Ok(account)
    }

    /// # Errors
    ///
    /// Returns an error if calculating P&Ls fails for the underlying account.
    pub fn calculate_pnls(
        &self,
        instrument: &InstrumentAny,
        fill: &OrderFilled,
        position: Option<Position>,
    ) -> anyhow::Result<Vec<Money>> {
        match self {
            Self::Margin(margin) => margin.calculate_pnls(instrument, fill, position),
            Self::Cash(cash) => cash.calculate_pnls(instrument, fill, position),
            Self::Betting(betting) => betting.calculate_pnls(instrument, fill, position),
            Self::Wallet(wallet) => wallet.calculate_pnls(instrument, fill, position),
        }
    }

    /// # Errors
    ///
    /// Returns an error if calculating commission fails for the underlying account.
    pub fn calculate_commission(
        &self,
        instrument: &InstrumentAny,
        last_qty: Quantity,
        last_px: Price,
        liquidity_side: LiquiditySide,
        use_quote_for_inverse: Option<bool>,
    ) -> anyhow::Result<Money> {
        match self {
            Self::Margin(margin) => margin.calculate_commission(
                instrument,
                last_qty,
                last_px,
                liquidity_side,
                use_quote_for_inverse,
            ),
            Self::Cash(cash) => cash.calculate_commission(
                instrument,
                last_qty,
                last_px,
                liquidity_side,
                use_quote_for_inverse,
            ),
            Self::Betting(betting) => betting.calculate_commission(
                instrument,
                last_qty,
                last_px,
                liquidity_side,
                use_quote_for_inverse,
            ),
            Self::Wallet(wallet) => wallet.calculate_commission(
                instrument,
                last_qty,
                last_px,
                liquidity_side,
                use_quote_for_inverse,
            ),
        }
    }

    #[must_use]
    pub fn balance(&self, currency: Option<Currency>) -> Option<&AccountBalance> {
        match self {
            Self::Margin(margin) => margin.balance(currency),
            Self::Cash(cash) => cash.balance(currency),
            Self::Betting(betting) => betting.balance(currency),
            Self::Wallet(wallet) => wallet.balance(currency),
        }
    }
}

impl AccountAny {
    /// Creates an `AccountAny` from an `AccountState`.
    ///
    /// # Errors
    ///
    /// Returns an error if a wallet account state is invalid.
    pub fn try_from_state(event: AccountState) -> Result<Self, &'static str> {
        Self::from_state_checked(event).map_err(|_| "Invalid wallet account state")
    }

    fn from_state_checked(event: AccountState) -> CorrectnessResult<Self> {
        match event.account_type {
            AccountType::Margin => Ok(Self::Margin(MarginAccount::new(event, false))),
            AccountType::Cash => Ok(Self::Cash(CashAccount::new(event, false, false))),
            AccountType::Betting => Ok(Self::Betting(BettingAccount::new(event, false))),
            AccountType::Wallet => Ok(Self::Wallet(WalletAccount::new_checked(event, false)?)),
        }
    }
}

impl From<AccountState> for AccountAny {
    /// Creates an `AccountAny` from an `AccountState`.
    ///
    /// # Panics
    ///
    /// Panics if a wallet account state is invalid.
    /// Use [`AccountAny::try_from_state`] for fallible conversion.
    fn from(event: AccountState) -> Self {
        Self::from_state_checked(event).expect_display(FAILED)
    }
}

impl PartialEq for AccountAny {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use crate::{
        accounts::{Account, AccountAny},
        events::{AccountState, account::stubs::*},
        identifiers::AccountId,
    };

    #[rstest]
    fn test_from_events_empty_returns_error() {
        let events: Vec<AccountState> = vec![];
        let result = AccountAny::from_events(&events);

        assert_eq!(
            result.unwrap_err().to_string(),
            "No account events provided to create `AccountAny`"
        );
    }

    #[rstest]
    fn test_from_events_single_cash_event(cash_account_state: AccountState) {
        let result = AccountAny::from_events(&[cash_account_state]);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Cash(_)));
    }

    #[rstest]
    fn test_from_events_rejects_different_account(cash_account_state: AccountState) {
        let mut different_account = cash_account_state.clone();
        different_account.account_id = AccountId::from("OTHER-001");

        let result = AccountAny::from_events(&[cash_account_state, different_account]);

        assert_eq!(
            result.unwrap_err().to_string(),
            "Account event had a different account ID: expected SIM-001, received OTHER-001"
        );
    }

    #[rstest]
    fn test_from_events_single_margin_event(margin_account_state: AccountState) {
        let result = AccountAny::from_events(&[margin_account_state]);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Margin(_)));
    }

    #[rstest]
    fn test_try_from_state_cash(cash_account_state: AccountState) {
        let result: Result<AccountAny, &'static str> =
            AccountAny::try_from_state(cash_account_state);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Cash(_)));
    }

    #[rstest]
    fn test_try_from_state_margin(margin_account_state: AccountState) {
        let result = AccountAny::try_from_state(margin_account_state);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Margin(_)));
    }

    #[rstest]
    fn test_try_from_state_betting(betting_account_state: AccountState) {
        let result = AccountAny::try_from_state(betting_account_state);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Betting(_)));
    }

    #[rstest]
    fn test_try_from_state_wallet(wallet_account_state: AccountState) {
        let result = AccountAny::try_from_state(wallet_account_state);
        assert!(result.is_ok());
        assert!(matches!(result.unwrap(), AccountAny::Wallet(_)));
    }

    #[rstest]
    fn test_try_from_state_invalid_wallet_returns_static_error() {
        let result: Result<AccountAny, &'static str> =
            AccountAny::try_from_state(invalid_wallet_state());

        assert_eq!(result.unwrap_err(), "Invalid wallet account state");
    }

    #[rstest]
    fn test_from_events_wallet_applies_sequence(
        wallet_account_state: AccountState,
        wallet_account_state_changed: AccountState,
    ) {
        let result = AccountAny::from_events(&[wallet_account_state, wallet_account_state_changed]);
        assert!(result.is_ok());
        let account = result.unwrap();
        assert!(matches!(account, AccountAny::Wallet(_)));
        assert_eq!(account.event_count(), 2);
    }

    #[rstest]
    fn test_from_events_wallet_rejects_negative_initial_balance() {
        let result = AccountAny::from_events(&[invalid_wallet_state()]);

        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Wallet account balance total was negative"
        );
    }

    #[rstest]
    #[case::cash(cash_account_state(), "Cash")]
    #[case::margin(margin_account_state(), "Margin")]
    #[case::betting(betting_account_state(), "Betting")]
    #[case::wallet(wallet_account_state(), "Wallet")]
    fn test_serde_round_trip_preserves_variant_payload(
        #[case] state: AccountState,
        #[case] expected_variant: &str,
    ) {
        let account = AccountAny::try_from_state(state).unwrap();

        let value = serde_json::to_value(&account).unwrap();
        let object = value.as_object().unwrap();
        assert_eq!(object.len(), 1);
        assert!(object.contains_key(expected_variant));

        let deserialized: AccountAny = serde_json::from_value(value).unwrap();
        assert_eq!(deserialized.id(), account.id());
        assert_eq!(deserialized.events(), account.events());
        assert_eq!(deserialized.balances(), account.balances());
    }

    #[rstest]
    #[case::cash(include_str!("../../test_data/account_legacy_cash.json"), "Cash")]
    #[case::margin(include_str!("../../test_data/account_legacy_margin.json"), "Margin")]
    #[case::betting(include_str!("../../test_data/account_legacy_betting.json"), "Betting")]
    fn test_deserializes_legacy_payload(#[case] json: &str, #[case] expected_variant: &str) {
        let account: AccountAny = serde_json::from_str(json).unwrap();
        let variant = match &account {
            AccountAny::Cash(_) => "Cash",
            AccountAny::Margin(_) => "Margin",
            AccountAny::Betting(_) => "Betting",
            AccountAny::Wallet(_) => "Wallet",
        };
        assert_eq!(variant, expected_variant);
        assert_eq!(account.event_count(), 1);
    }

    fn invalid_wallet_state() -> AccountState {
        AccountState::new(
            AccountId::from("WALLET-001"),
            crate::enums::AccountType::Wallet,
            vec![crate::types::AccountBalance::new(
                crate::types::Money::from("-1 ETH"),
                crate::types::Money::from("0 ETH"),
                crate::types::Money::from("-1 ETH"),
            )],
            vec![],
            true,
            crate::identifiers::stubs::uuid4(),
            0.into(),
            0.into(),
            None,
        )
    }
}