Skip to main content

nautilus_model/python/account/
mod.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
16pub mod betting;
17pub mod cash;
18pub mod margin;
19pub mod margin_model;
20pub mod transformer;
21
22use nautilus_core::python::to_pyvalue_err;
23use pyo3::{Py, PyAny, PyResult, Python, conversion::IntoPyObjectExt};
24
25use crate::{
26    accounts::{AccountAny, BettingAccount, CashAccount, MarginAccount},
27    enums::AccountType,
28};
29
30/// Converts a Python account object into a Rust `AccountAny` enum.
31///
32/// # Errors
33///
34/// Returns a `PyErr` if:
35/// - retrieving the `account_type` attribute fails.
36/// - extracting the object into `CashAccount` or `MarginAccount` fails.
37/// - the `account_type` is unsupported.
38#[expect(clippy::needless_pass_by_value)]
39pub fn pyobject_to_account_any(py: Python, account: Py<PyAny>) -> PyResult<AccountAny> {
40    let account_type = account
41        .getattr(py, "account_type")?
42        .extract::<AccountType>(py)?;
43    if account_type == AccountType::Margin {
44        let margin = account.extract::<MarginAccount>(py)?;
45        Ok(AccountAny::Margin(margin))
46    } else if account_type == AccountType::Cash {
47        let cash = account.extract::<CashAccount>(py)?;
48        Ok(AccountAny::Cash(cash))
49    } else if account_type == AccountType::Betting {
50        let betting = account.extract::<BettingAccount>(py)?;
51        Ok(AccountAny::Betting(betting))
52    } else {
53        Err(to_pyvalue_err("Unsupported account type"))
54    }
55}
56
57/// Converts a Rust `AccountAny` into a Python account object.
58///
59/// # Errors
60///
61/// Returns a `PyErr` if converting the underlying account into a Python object fails.
62pub fn account_any_to_pyobject(py: Python, account: AccountAny) -> PyResult<Py<PyAny>> {
63    match account {
64        AccountAny::Margin(account) => account.into_py_any(py),
65        AccountAny::Cash(account) => account.into_py_any(py),
66        AccountAny::Betting(account) => account.into_py_any(py),
67    }
68}