Skip to main content

ctrader_connector/open_api/
account.rs

1//! Details of a trading account: its balance, deposit currency, leverage and kind.
2//!
3//! ```no_run
4//! use ctrader_connector::common::config::ConfigurationOpenApi;
5//! use ctrader_connector::open_api::client::OpenApiClient;
6//!
7//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
8//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
9//! client.authorise_application().await?;
10//! let account = client.accounts().await?[0].id;
11//! client.authorise_account(account).await?;
12//! let trader = client.trader(account).await?;
13//! println!("{} {}", trader.balance, trader.currency);
14//! # Ok(())
15//! # }
16//! ```
17
18use rust_decimal::Decimal;
19
20use crate::common::errors::{ConnectorError, ValueError};
21use crate::common::ids::{AccountId, AssetId};
22use crate::common::time::Timestamp;
23use crate::open_api::client::OpenApiClient;
24use crate::open_api::messages::{
25    ProtoOaAccessRights, ProtoOaAccountType, ProtoOaTrader, ProtoOaTraderReq,
26};
27use crate::open_api::symbols::Asset;
28use crate::open_api::trading::{DEFAULT_MONEY_DIGITS, money};
29
30const LEVERAGE_SCALE: u32 = 2;
31
32const ACCOUNT_TYPE: &str = "account type";
33const ACCESS_RIGHTS: &str = "access rights";
34const DEPOSIT_ASSET: &str = "deposit asset";
35
36/// How the positions of an account are kept.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum AccountType {
40    /// Several positions of a symbol, in either direction, exist side by side.
41    Hedged,
42    /// One position per symbol, the net of all trades.
43    Netted,
44    /// Spread betting.
45    SpreadBetting,
46}
47
48impl AccountType {
49    fn from_wire(raw: Option<i32>) -> Result<Self, ValueError> {
50        let Some(raw) = raw else {
51            return Ok(Self::Hedged);
52        };
53        match ProtoOaAccountType::try_from(raw) {
54            Ok(ProtoOaAccountType::Hedged) => Ok(Self::Hedged),
55            Ok(ProtoOaAccountType::Netted) => Ok(Self::Netted),
56            Ok(ProtoOaAccountType::SpreadBetting) => Ok(Self::SpreadBetting),
57            Err(_) => Err(ValueError::OutOfRange { kind: ACCOUNT_TYPE }),
58        }
59    }
60}
61
62/// What the account is allowed to do.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64#[non_exhaustive]
65pub enum AccessRights {
66    /// Trading without restriction.
67    FullAccess,
68    /// Positions can be closed and nothing opened.
69    CloseOnly,
70    /// No trading; the account can be read.
71    NoTrading,
72    /// The account cannot be used.
73    NoLogin,
74}
75
76impl AccessRights {
77    fn from_wire(raw: Option<i32>) -> Result<Self, ValueError> {
78        let Some(raw) = raw else {
79            return Ok(Self::FullAccess);
80        };
81        match ProtoOaAccessRights::try_from(raw) {
82            Ok(ProtoOaAccessRights::FullAccess) => Ok(Self::FullAccess),
83            Ok(ProtoOaAccessRights::CloseOnly) => Ok(Self::CloseOnly),
84            Ok(ProtoOaAccessRights::NoTrading) => Ok(Self::NoTrading),
85            Ok(ProtoOaAccessRights::NoLogin) => Ok(Self::NoLogin),
86            Err(_) => Err(ValueError::OutOfRange {
87                kind: ACCESS_RIGHTS,
88            }),
89        }
90    }
91}
92
93/// Trading account as the server knows it.
94///
95/// Amounts of money are in the deposit currency, scaled by the money digits of the account.
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97#[non_exhaustive]
98pub struct Trader {
99    /// Identifier of the account.
100    pub account: AccountId,
101    /// Balance of the account.
102    pub balance: Decimal,
103    /// Number of decimal places the amounts of the account are kept with.
104    pub money_digits: u32,
105    /// Asset the account is kept in.
106    pub deposit_asset: AssetId,
107    /// Name of the deposit asset, such as `USD`.
108    pub currency: String,
109    /// Leverage of the account, such as `100` for 1:100.
110    pub leverage: Option<Decimal>,
111    /// Largest leverage the account can be given.
112    pub max_leverage: Option<u32>,
113    /// How the positions of the account are kept.
114    pub account_type: AccountType,
115    /// What the account is allowed to do.
116    pub access_rights: AccessRights,
117    /// Tells whether no swap is charged on the account.
118    pub swap_free: bool,
119    /// Tells whether the loss of every position of the account is limited by a guaranteed stop
120    /// loss.
121    pub limited_risk: bool,
122    /// Bonus given by the manager of the account.
123    pub manager_bonus: Option<Decimal>,
124    /// Bonus given by the introducing broker.
125    pub ib_bonus: Option<Decimal>,
126    /// Part of the bonus that cannot be withdrawn.
127    pub non_withdrawable_bonus: Option<Decimal>,
128    /// Name of the broker the account is held with.
129    pub broker_name: Option<String>,
130    /// Moment the account was registered.
131    pub registered: Option<Timestamp>,
132}
133
134impl Trader {
135    /// Builds the account from its wire form and the assets of the account, among which the
136    /// deposit asset is looked up.
137    fn parse(trader: ProtoOaTrader, assets: &[Asset]) -> Result<Self, ValueError> {
138        let digits = trader.money_digits;
139        let amount = |raw: Option<i64>| raw.map(|raw| money(raw, digits)).transpose();
140        let deposit_asset = AssetId::new(trader.deposit_asset_id)?;
141        let currency = assets
142            .iter()
143            .find(|asset| asset.id == deposit_asset)
144            .map(|asset| asset.name.clone())
145            .ok_or(ValueError::OutOfRange {
146                kind: DEPOSIT_ASSET,
147            })?;
148        Ok(Self {
149            account: AccountId::new(trader.ctid_trader_account_id)?,
150            balance: money(trader.balance, digits)?,
151            money_digits: digits.unwrap_or(DEFAULT_MONEY_DIGITS),
152            deposit_asset,
153            currency,
154            leverage: trader
155                .leverage_in_cents
156                .map(|cents| Decimal::new(i64::from(cents), LEVERAGE_SCALE).normalize()),
157            max_leverage: trader.max_leverage,
158            account_type: AccountType::from_wire(trader.account_type)?,
159            access_rights: AccessRights::from_wire(trader.access_rights)?,
160            swap_free: trader.swap_free.unwrap_or(false),
161            limited_risk: trader.is_limited_risk.unwrap_or(false),
162            manager_bonus: amount(trader.manager_bonus)?,
163            ib_bonus: amount(trader.ib_bonus)?,
164            non_withdrawable_bonus: amount(trader.non_withdrawable_bonus)?,
165            broker_name: trader.broker_name,
166            registered: trader
167                .registration_timestamp
168                .map(Timestamp::from_millis)
169                .transpose()?,
170        })
171    }
172}
173
174impl OpenApiClient {
175    /// Reads the details of an authorised account: its balance, deposit currency, leverage and
176    /// kind.
177    ///
178    /// Two requests are made: one for the account and one for the assets of the account, among
179    /// which the name of the deposit asset is looked up.
180    ///
181    /// # Errors
182    ///
183    /// Returns [`ConnectorError::Server`] when the server refuses a request,
184    /// [`ConnectorError::Value`] when the account carries a value out of range or a deposit
185    /// asset the server does not list, and the errors of
186    /// [`Connection::request`](crate::open_api::connection::Connection::request) otherwise.
187    pub async fn trader(&self, account: AccountId) -> Result<Trader, ConnectorError> {
188        let request = ProtoOaTraderReq {
189            payload_type: None,
190            ctid_trader_account_id: account.get(),
191        };
192        let trader = self.connection().request(&request).await?.trader;
193        let assets = self.assets(account).await?;
194        Ok(Trader::parse(trader, &assets)?)
195    }
196}