Skip to main content

ctrader_connector/fix/
reports.rs

1//! State of the account as the trade session reports it: orders and positions.
2
3use crate::common::decimals::{Price, Volume};
4use crate::common::errors::{ConnectorError, FixError};
5use crate::common::ids::{PositionId, SymbolId};
6use crate::fix::client::FixClient;
7use crate::fix::messages::{
8    ExecType, Message, OrderMassStatusRequest, OrderStatusRequest, PositionReport,
9    RequestForPositions, Side,
10};
11use crate::fix::trading::OrderReport;
12
13const MASS_PREFIX: &str = "m";
14const POSITIONS_PREFIX: &str = "p";
15const ALL_ORDERS: u32 = 7;
16const NO_ORDERS: &str = "ORDER_NOT_FOUND";
17const VALID_REQUEST: u32 = 0;
18const NO_POSITIONS: u32 = 2;
19const TAG_POSITION_ID: u32 = 721;
20const TAG_SYMBOL: u32 = 55;
21const TAG_LONG_QTY: u32 = 704;
22
23/// An open position.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Position {
26    /// Identifier of the position, the same the other API of the server uses.
27    pub id: PositionId,
28    /// Symbol of the position.
29    pub symbol: SymbolId,
30    /// Side of the position: bought or sold.
31    pub side: Side,
32    /// Quantity held, in units of the base asset.
33    pub quantity: Volume,
34    /// Price the position was opened at.
35    pub entry_price: Option<Price>,
36}
37
38impl TryFrom<&PositionReport> for Position {
39    type Error = FixError;
40
41    fn try_from(report: &PositionReport) -> Result<Self, FixError> {
42        let missing = |tag| FixError::MissingField {
43            msg_type: PositionReport::MSG_TYPE.to_owned(),
44            tag,
45        };
46        let held = |quantity: Option<Volume>| quantity.filter(|held| !held.value().is_zero());
47        let (side, quantity) = match (held(report.long_qty), held(report.short_qty)) {
48            (Some(long), _) => (Side::Buy, long),
49            (None, Some(short)) => (Side::Sell, short),
50            (None, None) => return Err(missing(TAG_LONG_QTY)),
51        };
52        Ok(Self {
53            id: report.position_id.ok_or_else(|| missing(TAG_POSITION_ID))?,
54            symbol: report.symbol.ok_or_else(|| missing(TAG_SYMBOL))?,
55            side,
56            quantity,
57            entry_price: report.settl_price,
58        })
59    }
60}
61
62fn complete<T>(collected: &[T], total: u32) -> bool {
63    u32::try_from(collected.len()).is_ok_and(|count| count >= total)
64}
65
66impl FixClient {
67    /// Asks for the state of the order the client gave the identifier `cl_ord_id`.
68    ///
69    /// # Errors
70    ///
71    /// Returns [`ConnectorError::Fix`] with [`FixError::BusinessRejected`] when the server
72    /// knows no such order, and otherwise the errors of [`FixClient::request`].
73    pub async fn order_status(&self, cl_ord_id: &str) -> Result<OrderReport, ConnectorError> {
74        let request = OrderStatusRequest {
75            cl_ord_id: cl_ord_id.to_owned(),
76            side: None,
77        };
78        self.request(request.into(), cl_ord_id, |message| match message {
79            Message::ExecutionReport(report) if report.cl_ord_id.as_deref() == Some(cl_ord_id) => {
80                Some(OrderReport::try_from(report.as_ref()).map_err(ConnectorError::from))
81            }
82            _ => None,
83        })
84        .await
85    }
86
87    /// Lists the waiting orders of the account.
88    ///
89    /// # Errors
90    ///
91    /// Returns the errors of [`FixClient::request`]; when a report cannot be read or the
92    /// list stays incomplete no order is returned.
93    pub async fn open_orders(&self) -> Result<Vec<OrderReport>, ConnectorError> {
94        let id = self.next_id(MASS_PREFIX);
95        let request = OrderMassStatusRequest {
96            mass_status_req_id: id.clone(),
97            request_type: ALL_ORDERS,
98            issue_date: None,
99        };
100        let mut orders = Vec::new();
101        let listed = self
102            .request(request.into(), &id, |message| match message {
103                Message::ExecutionReport(report)
104                    if report.exec_type == ExecType::OrderStatus
105                        && report.mass_status_req_id.as_deref() == Some(&id) =>
106                {
107                    match OrderReport::try_from(report.as_ref()) {
108                        Ok(order) => orders.push(order),
109                        Err(error) => return Some(Err(error.into())),
110                    }
111                    complete(&orders, report.tot_num_reports.unwrap_or(1)).then_some(Ok(()))
112                }
113                _ => None,
114            })
115            .await;
116        match listed {
117            Ok(()) => Ok(orders),
118            Err(ConnectorError::Fix(FixError::BusinessRejected {
119                text: Some(text), ..
120            })) if text.starts_with(NO_ORDERS) => Ok(Vec::new()),
121            Err(error) => Err(error),
122        }
123    }
124
125    /// Lists the open positions of the account.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`ConnectorError::Fix`] with [`FixError::BusinessRejected`] when the server
130    /// reports the request as invalid, and otherwise the errors of [`FixClient::request`];
131    /// when a report cannot be read or the list stays incomplete no position is returned.
132    pub async fn positions(&self) -> Result<Vec<Position>, ConnectorError> {
133        let id = self.next_id(POSITIONS_PREFIX);
134        let request = RequestForPositions {
135            pos_req_id: id.clone(),
136            position_id: None,
137        };
138        let mut positions = Vec::new();
139        self.request(request.into(), &id, |message| match message {
140            Message::PositionReport(report) if report.pos_req_id == id => {
141                if report.result == NO_POSITIONS || report.total_reports == 0 {
142                    return Some(Ok(()));
143                }
144                if report.result != VALID_REQUEST {
145                    return Some(Err(FixError::BusinessRejected {
146                        ref_id: Some(id.clone()),
147                        reason: Some(report.result),
148                        text: None,
149                    }
150                    .into()));
151                }
152                match Position::try_from(report) {
153                    Ok(position) => positions.push(position),
154                    Err(error) => return Some(Err(error.into())),
155                }
156                complete(&positions, report.total_reports).then_some(Ok(()))
157            }
158            _ => None,
159        })
160        .await?;
161        Ok(positions)
162    }
163}