ctrader_connector/fix/
reports.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Position {
26 pub id: PositionId,
28 pub symbol: SymbolId,
30 pub side: Side,
32 pub quantity: Volume,
34 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 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 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 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}