nautilus_infrastructure/sql/models/
accounts.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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
16use std::str::FromStr;
17
18use nautilus_core::{UUID4, UnixNanos};
19use nautilus_model::{
20    enums::AccountType, events::AccountState, identifiers::AccountId, types::Currency,
21};
22use sqlx::{FromRow, Row, postgres::PgRow};
23
24pub struct AccountEventModel(pub AccountState);
25
26impl<'r> FromRow<'r, PgRow> for AccountEventModel {
27    fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
28        let event_id = row.try_get::<&str, _>("id").map(UUID4::from)?;
29        let account_id = row.try_get::<&str, _>("account_id").map(AccountId::from)?;
30        let account_type = AccountType::from_str(row.try_get::<&str, _>("kind")?).unwrap();
31        let is_reported = row.try_get::<bool, _>("is_reported")?;
32        let ts_event = row.try_get::<&str, _>("ts_event").map(UnixNanos::from)?;
33        let ts_init = row.try_get::<&str, _>("ts_init").map(UnixNanos::from)?;
34        let base_currency = row
35            .try_get::<Option<&str>, _>("base_currency")
36            .map(|res| res.map(Currency::from))?;
37        let balances: serde_json::Value = row.try_get("balances")?;
38        let margins: serde_json::Value = row.try_get("margins")?;
39        let account_event = AccountState::new(
40            account_id,
41            account_type,
42            serde_json::from_value(balances).unwrap(),
43            serde_json::from_value(margins).unwrap(),
44            is_reported,
45            event_id,
46            ts_event,
47            ts_init,
48            base_currency,
49        );
50        Ok(AccountEventModel(account_event))
51    }
52}