ctrader_connector/open_api/
margin.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
50#[non_exhaustive]
51pub enum MarginCallLevel {
52 First,
54 Second,
56 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub struct MarginCall {
85 pub level: MarginCallLevel,
87 pub threshold: Decimal,
90 pub updated: Option<Timestamp>,
92}
93
94impl MarginCall {
95 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140#[non_exhaustive]
141pub struct MarginChange {
142 pub account: AccountId,
144 pub position: PositionId,
146 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
172#[non_exhaustive]
173pub enum MarginEvent {
174 Changed(MarginChange),
176 CallUpdated(MarginCall),
178 CallTriggered(MarginCall),
180}
181
182#[derive(Debug)]
194pub struct MarginStream {
195 feed: Feed,
196 account: AccountId,
197}
198
199impl MarginStream {
200 #[must_use]
202 pub const fn account(&self) -> AccountId {
203 self.account
204 }
205
206 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 #[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 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 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}