Skip to main content

ctrader_connector/open_api/
margin.rs

1//! Margin of positions and margin calls of an account.
2//!
3//! The server reports by itself when the margin a position uses changes, when a margin call
4//! of an account is changed and when one is triggered; nothing is subscribed to.
5//!
6//! ```no_run
7//! use ctrader_connector::common::config::ConfigurationOpenApi;
8//! use ctrader_connector::open_api::client::OpenApiClient;
9//! use ctrader_connector::open_api::margin::MarginEvent;
10//!
11//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
12//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
13//! client.authorise_application().await?;
14//! let account = client.accounts().await?[0].id;
15//! client.authorise_account(account).await?;
16//! for call in client.margin_calls(account).await? {
17//!     println!("{:?} at {}", call.level, call.threshold);
18//! }
19//! let mut margin = client.margin_events(account);
20//! loop {
21//!     if let MarginEvent::Changed(change) = margin.next().await? {
22//!         println!("{} uses {}", change.position, change.used_margin);
23//!     }
24//! }
25//! # }
26//! ```
27
28use rust_decimal::Decimal;
29use rust_decimal::prelude::ToPrimitive;
30
31use crate::common::errors::{ConnectorError, ValueError};
32use crate::common::ids::{AccountId, PositionId};
33use crate::common::time::Timestamp;
34use crate::open_api::client::OpenApiClient;
35use crate::open_api::messages::{
36    ProtoOaMarginCall, ProtoOaMarginCallListReq, ProtoOaMarginCallTriggerEvent,
37    ProtoOaMarginCallUpdateEvent, ProtoOaMarginCallUpdateReq, ProtoOaMarginChangedEvent,
38    ProtoOaNotificationType,
39};
40use crate::open_api::stream::Feed;
41use crate::open_api::trading::DEFAULT_MONEY_DIGITS;
42
43const MARGIN_CALL_LEVEL: &str = "level of margin call";
44const THRESHOLD: &str = "margin level threshold";
45const USED_MARGIN: &str = "used margin";
46const POSITION: &str = "position id";
47
48/// Which of the margin calls of an account one is.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50#[non_exhaustive]
51pub enum MarginCallLevel {
52    /// First margin call.
53    First,
54    /// Second margin call.
55    Second,
56    /// Third margin call.
57    Third,
58}
59
60impl MarginCallLevel {
61    fn from_wire(raw: i32) -> Result<Self, ValueError> {
62        match ProtoOaNotificationType::try_from(raw) {
63            Ok(ProtoOaNotificationType::MarginLevelThreshold1) => Ok(Self::First),
64            Ok(ProtoOaNotificationType::MarginLevelThreshold2) => Ok(Self::Second),
65            Ok(ProtoOaNotificationType::MarginLevelThreshold3) => Ok(Self::Third),
66            Err(_) => Err(ValueError::OutOfRange {
67                kind: MARGIN_CALL_LEVEL,
68            }),
69        }
70    }
71
72    const fn to_wire(self) -> ProtoOaNotificationType {
73        match self {
74            Self::First => ProtoOaNotificationType::MarginLevelThreshold1,
75            Self::Second => ProtoOaNotificationType::MarginLevelThreshold2,
76            Self::Third => ProtoOaNotificationType::MarginLevelThreshold3,
77        }
78    }
79}
80
81/// Margin call of an account: the margin level at which the account is notified.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub struct MarginCall {
85    /// Which margin call of the account this is.
86    pub level: MarginCallLevel,
87    /// Margin level at or below which the margin call is triggered, as a ratio of equity to
88    /// used margin: 1.5 stands for 150 %.
89    pub threshold: Decimal,
90    /// Moment the margin call was last changed.
91    pub updated: Option<Timestamp>,
92}
93
94impl MarginCall {
95    /// Describes a margin call with the given threshold, a ratio of equity to used margin.
96    #[must_use]
97    pub const fn new(level: MarginCallLevel, threshold: Decimal) -> Self {
98        Self {
99            level,
100            threshold,
101            updated: None,
102        }
103    }
104
105    fn to_wire(self) -> Result<ProtoOaMarginCall, ValueError> {
106        let unrepresentable = ValueError::Unrepresentable {
107            kind: THRESHOLD,
108            value: self.threshold,
109        };
110        if self.threshold.is_sign_negative() {
111            return Err(unrepresentable);
112        }
113        Ok(ProtoOaMarginCall {
114            margin_call_type: self.level.to_wire().into(),
115            margin_level_threshold: self.threshold.to_f64().ok_or(unrepresentable)?,
116            utc_last_update_timestamp: None,
117        })
118    }
119}
120
121impl TryFrom<ProtoOaMarginCall> for MarginCall {
122    type Error = ValueError;
123
124    fn try_from(call: ProtoOaMarginCall) -> Result<Self, Self::Error> {
125        let threshold = Decimal::try_from(call.margin_level_threshold)
126            .map_err(|_| ValueError::OutOfRange { kind: THRESHOLD })?;
127        Ok(Self {
128            level: MarginCallLevel::from_wire(call.margin_call_type)?,
129            threshold: threshold.normalize(),
130            updated: call
131                .utc_last_update_timestamp
132                .map(Timestamp::from_millis)
133                .transpose()?,
134        })
135    }
136}
137
138/// Change of the margin a position uses.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140#[non_exhaustive]
141pub struct MarginChange {
142    /// Account the position belongs to.
143    pub account: AccountId,
144    /// Position whose margin changed.
145    pub position: PositionId,
146    /// Margin the position uses after the change, in the deposit currency.
147    pub used_margin: Decimal,
148}
149
150impl TryFrom<ProtoOaMarginChangedEvent> for MarginChange {
151    type Error = ValueError;
152
153    fn try_from(event: ProtoOaMarginChangedEvent) -> Result<Self, Self::Error> {
154        let position = i64::try_from(event.position_id)
155            .map_err(|_| ValueError::OutOfRange { kind: POSITION })?;
156        let used = i64::try_from(event.used_margin)
157            .ok()
158            .and_then(|raw| {
159                Decimal::try_new(raw, event.money_digits.unwrap_or(DEFAULT_MONEY_DIGITS)).ok()
160            })
161            .ok_or(ValueError::OutOfRange { kind: USED_MARGIN })?;
162        Ok(Self {
163            account: AccountId::new(event.ctid_trader_account_id)?,
164            position: PositionId::new(position)?,
165            used_margin: used,
166        })
167    }
168}
169
170/// One event about the margin of an account.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
172#[non_exhaustive]
173pub enum MarginEvent {
174    /// The margin a position uses changed.
175    Changed(MarginChange),
176    /// A margin call of the account was changed.
177    CallUpdated(MarginCall),
178    /// The margin level of the account reached the threshold of a margin call.
179    CallTriggered(MarginCall),
180}
181
182/// Margin events of one account, in the order the server sent them.
183///
184/// The stream starts with the first event that arrives after it was created and goes on
185/// across reconnections; events the server sent while the connection was down are not sent
186/// again.
187///
188/// A stream that is read too slowly loses events: the connection holds a limited number of
189/// them, set with
190/// [`ConnectionOptions::event_capacity`](crate::open_api::connection::ConnectionOptions::event_capacity).
191/// The loss is reported once by [`MarginStream::next`] with [`ConnectorError::Lagged`] and the
192/// stream then goes on with the oldest event still held.
193#[derive(Debug)]
194pub struct MarginStream {
195    feed: Feed,
196    account: AccountId,
197}
198
199impl MarginStream {
200    /// Returns the account the events belong to.
201    #[must_use]
202    pub const fn account(&self) -> AccountId {
203        self.account
204    }
205
206    /// Waits for the next margin event of the account.
207    ///
208    /// # Errors
209    ///
210    /// Returns [`ConnectorError::Closed`] when the connection is shut down,
211    /// [`ConnectorError::SessionEnded`] when the server ended the authorisation of the account,
212    /// [`ConnectorError::Lagged`] when events were dropped because the stream was read too
213    /// slowly, and [`ConnectorError::Value`] when the server sends a value out of range; the
214    /// stream can be read on after the last two.
215    pub async fn next(&mut self) -> Result<MarginEvent, ConnectorError> {
216        let account = self.account.get();
217        loop {
218            let event = self.feed.next().await?;
219            if let Some(change) = event.decode::<ProtoOaMarginChangedEvent>() {
220                if change.ctid_trader_account_id == account {
221                    return Ok(MarginEvent::Changed(MarginChange::try_from(change)?));
222                }
223            } else if let Some(update) = event.decode::<ProtoOaMarginCallUpdateEvent>() {
224                if update.ctid_trader_account_id == account {
225                    let call = MarginCall::try_from(update.margin_call)?;
226                    return Ok(MarginEvent::CallUpdated(call));
227                }
228            } else if let Some(trigger) = event.decode::<ProtoOaMarginCallTriggerEvent>() {
229                if trigger.ctid_trader_account_id == account {
230                    let call = MarginCall::try_from(trigger.margin_call)?;
231                    return Ok(MarginEvent::CallTriggered(call));
232                }
233            }
234        }
235    }
236}
237
238impl OpenApiClient {
239    /// Starts to read the margin events of an authorised account.
240    ///
241    /// Nothing is sent: the server delivers these events for every account authorised on the
242    /// connection. Create the stream before the request whose events are to be read.
243    #[must_use]
244    pub fn margin_events(&self, account: AccountId) -> MarginStream {
245        MarginStream {
246            feed: Feed::new(self.connection(), account),
247            account,
248        }
249    }
250
251    /// Lists the margin calls of an authorised account.
252    ///
253    /// # Errors
254    ///
255    /// Returns [`ConnectorError::Server`] when the server refuses the request,
256    /// [`ConnectorError::Value`] when a margin call carries a value out of range, and the
257    /// errors of [`Connection::request`](crate::open_api::connection::Connection::request)
258    /// otherwise.
259    pub async fn margin_calls(
260        &self,
261        account: AccountId,
262    ) -> Result<Vec<MarginCall>, ConnectorError> {
263        let request = ProtoOaMarginCallListReq {
264            payload_type: None,
265            ctid_trader_account_id: account.get(),
266        };
267        let response = self.connection().request(&request).await?;
268        let calls: Result<Vec<MarginCall>, ValueError> = response
269            .margin_call
270            .into_iter()
271            .map(MarginCall::try_from)
272            .collect();
273        Ok(calls?)
274    }
275
276    /// Sets the threshold of a margin call of an authorised account.
277    ///
278    /// The request states the whole margin call and has the same outcome however often it
279    /// arrives, so it is sent again after a reconnection like a request that reads.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`ConnectorError::Value`] when the threshold is negative, in which case nothing
284    /// is sent, [`ConnectorError::Server`] when the server refuses the request, and the errors
285    /// of [`Connection::request`](crate::open_api::connection::Connection::request) otherwise.
286    pub async fn update_margin_call(
287        &self,
288        account: AccountId,
289        call: MarginCall,
290    ) -> Result<(), ConnectorError> {
291        let request = ProtoOaMarginCallUpdateReq {
292            payload_type: None,
293            ctid_trader_account_id: account.get(),
294            margin_call: call.to_wire()?,
295        };
296        self.connection().request(&request).await?;
297        Ok(())
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use rust_decimal::Decimal;
304
305    use super::{MarginCall, MarginCallLevel, MarginChange};
306    use crate::common::errors::ValueError;
307    use crate::open_api::messages::{ProtoOaMarginCall, ProtoOaMarginChangedEvent};
308
309    #[test]
310    fn margin_call_keeps_its_level_and_threshold_across_the_wire() {
311        for (level, raw) in [
312            (MarginCallLevel::First, 61),
313            (MarginCallLevel::Second, 62),
314            (MarginCallLevel::Third, 63),
315        ] {
316            let wire = MarginCall::new(level, Decimal::new(15, 1))
317                .to_wire()
318                .expect("wire");
319            assert_eq!(wire.margin_call_type, raw);
320            assert_eq!(wire.utc_last_update_timestamp, None);
321            let back = MarginCall::try_from(ProtoOaMarginCall {
322                utc_last_update_timestamp: Some(5),
323                ..wire
324            })
325            .expect("margin call");
326            assert_eq!((back.level, back.threshold), (level, Decimal::new(15, 1)));
327            assert_eq!(
328                back.updated,
329                crate::common::time::Timestamp::from_millis(5).ok()
330            );
331        }
332        assert!(MarginCallLevel::First < MarginCallLevel::Third);
333    }
334
335    #[test]
336    fn margin_call_out_of_range_is_refused() {
337        let call = |kind, threshold| {
338            MarginCall::try_from(ProtoOaMarginCall {
339                margin_call_type: kind,
340                margin_level_threshold: threshold,
341                utc_last_update_timestamp: None,
342            })
343        };
344        assert!(matches!(call(60, 1.0), Err(ValueError::OutOfRange { .. })));
345        assert!(matches!(
346            call(61, f64::NAN),
347            Err(ValueError::OutOfRange { .. })
348        ));
349        assert!(matches!(call(61, 1e40), Err(ValueError::OutOfRange { .. })));
350        assert!(matches!(
351            MarginCall::new(MarginCallLevel::First, Decimal::new(-1, 1)).to_wire(),
352            Err(ValueError::Unrepresentable { .. })
353        ));
354        assert_eq!(
355            MarginCall::new(MarginCallLevel::Second, Decimal::ZERO)
356                .to_wire()
357                .map(|wire| wire.margin_level_threshold.to_bits()),
358            Ok(0.0_f64.to_bits())
359        );
360    }
361
362    #[test]
363    fn margin_change_scales_the_margin_and_refuses_what_does_not_fit() {
364        let event = |position, used, digits| ProtoOaMarginChangedEvent {
365            payload_type: None,
366            ctid_trader_account_id: 101,
367            position_id: position,
368            used_margin: used,
369            money_digits: digits,
370        };
371        let change = MarginChange::try_from(event(7, 12_345, None)).expect("change");
372        assert_eq!(change.account.get(), 101);
373        assert_eq!(change.position.get(), 7);
374        assert_eq!(change.used_margin.to_string(), "123.45");
375        let fine = MarginChange::try_from(event(7, 12_345, Some(4))).expect("change");
376        assert_eq!(fine.used_margin.to_string(), "1.2345");
377        for refused in [
378            event(u64::MAX, 1, None),
379            event(0, 1, None),
380            event(7, u64::MAX, None),
381            event(7, 1, Some(99)),
382        ] {
383            assert!(MarginChange::try_from(refused).is_err());
384        }
385    }
386}