nautilus_infrastructure/sql/models/
accounts.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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
24#[derive(Debug)]
25pub struct AccountEventModel(pub AccountState);
26
27impl<'r> FromRow<'r, PgRow> for AccountEventModel {
28    fn from_row(row: &'r PgRow) -> Result<Self, sqlx::Error> {
29        let event_id = row.try_get::<&str, _>("id").map(UUID4::from)?;
30        let account_id = row.try_get::<&str, _>("account_id").map(AccountId::from)?;
31        let account_type = AccountType::from_str(row.try_get::<&str, _>("kind")?).unwrap();
32        let is_reported = row.try_get::<bool, _>("is_reported")?;
33        let ts_event = row.try_get::<&str, _>("ts_event").map(UnixNanos::from)?;
34        let ts_init = row.try_get::<&str, _>("ts_init").map(UnixNanos::from)?;
35        let base_currency = row
36            .try_get::<Option<&str>, _>("base_currency")
37            .map(|res| res.map(Currency::from))?;
38        let balances: serde_json::Value = row.try_get("balances")?;
39        let margins: serde_json::Value = row.try_get("margins")?;
40        let account_event = AccountState::new(
41            account_id,
42            account_type,
43            serde_json::from_value(balances).unwrap(),
44            serde_json::from_value(margins).unwrap(),
45            is_reported,
46            event_id,
47            ts_event,
48            ts_init,
49            base_currency,
50        );
51        Ok(Self(account_event))
52    }
53}