1use crate::common::decimals::{Price, Volume};
32use crate::common::errors::{ConnectorError, FixError};
33use crate::common::ids::{OrderId, PositionId, SymbolId};
34use crate::common::time::Timestamp;
35use crate::fix::client::FixClient;
36use crate::fix::messages::{
37 ExecType, ExecutionReport, Message, NewOrderSingle, OrderKind, OrderStatus, Side, TimeInForce,
38};
39
40const ORDER_PREFIX: &str = "o";
41const TAG_ORDER_ID: u32 = 37;
42const TAG_CL_ORD_ID: u32 = 11;
43const TAG_SYMBOL: u32 = 55;
44const TAG_SIDE: u32 = 54;
45const TAG_ORDER_QTY: u32 = 38;
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct NewOrder {
50 symbol: SymbolId,
51 side: Side,
52 quantity: Volume,
53 kind: OrderKind,
54 price: Option<Price>,
55 stop_price: Option<Price>,
56 expiry: Option<Timestamp>,
57 position: Option<PositionId>,
58 label: Option<String>,
59}
60
61impl NewOrder {
62 const fn new(symbol: SymbolId, side: Side, quantity: Volume, kind: OrderKind) -> Self {
63 Self {
64 symbol,
65 side,
66 quantity,
67 kind,
68 price: None,
69 stop_price: None,
70 expiry: None,
71 position: None,
72 label: None,
73 }
74 }
75
76 #[must_use]
78 pub const fn market(symbol: SymbolId, side: Side, quantity: Volume) -> Self {
79 Self::new(symbol, side, quantity, OrderKind::Market)
80 }
81
82 #[must_use]
84 pub const fn limit(symbol: SymbolId, side: Side, quantity: Volume, price: Price) -> Self {
85 let mut order = Self::new(symbol, side, quantity, OrderKind::Limit);
86 order.price = Some(price);
87 order
88 }
89
90 #[must_use]
92 pub const fn stop(symbol: SymbolId, side: Side, quantity: Volume, price: Price) -> Self {
93 let mut order = Self::new(symbol, side, quantity, OrderKind::Stop);
94 order.stop_price = Some(price);
95 order
96 }
97
98 #[must_use]
100 pub fn label(mut self, label: impl Into<String>) -> Self {
101 self.label = Some(label.into());
102 self
103 }
104
105 #[must_use]
108 pub const fn position(mut self, position: PositionId) -> Self {
109 self.position = Some(position);
110 self
111 }
112
113 #[must_use]
115 pub const fn expires(mut self, at: Timestamp) -> Self {
116 self.expiry = Some(at);
117 self
118 }
119
120 #[must_use]
122 pub const fn kind(&self) -> OrderKind {
123 self.kind
124 }
125
126 fn message(&self, cl_ord_id: &str) -> NewOrderSingle {
127 NewOrderSingle {
128 cl_ord_id: cl_ord_id.to_owned(),
129 symbol: self.symbol,
130 side: self.side,
131 transact_time: Timestamp::now(),
132 order_qty: self.quantity,
133 ord_type: self.kind,
134 price: self.price,
135 stop_px: self.stop_price,
136 time_in_force: self.expiry.map(|_| TimeInForce::GoodTillDate),
137 expire_time: self.expiry,
138 position_id: self.position,
139 designation: self.label.clone(),
140 }
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct OrderReport {
147 pub order_id: OrderId,
149 pub cl_ord_id: String,
151 pub exec_type: ExecType,
153 pub status: OrderStatus,
155 pub symbol: SymbolId,
157 pub side: Side,
159 pub quantity: Volume,
161 pub kind: Option<OrderKind>,
163 pub price: Option<Price>,
165 pub stop_price: Option<Price>,
167 pub time_in_force: Option<TimeInForce>,
169 pub expiry: Option<Timestamp>,
171 pub filled: Option<Volume>,
173 pub remaining: Option<Volume>,
175 pub last_quantity: Option<Volume>,
177 pub average_price: Option<Price>,
179 pub position: Option<PositionId>,
181 pub label: Option<String>,
183 pub time: Option<Timestamp>,
185 pub text: Option<String>,
187}
188
189impl TryFrom<&ExecutionReport> for OrderReport {
190 type Error = FixError;
191
192 fn try_from(report: &ExecutionReport) -> Result<Self, FixError> {
193 let missing = |tag| FixError::MissingField {
194 msg_type: ExecutionReport::MSG_TYPE.to_owned(),
195 tag,
196 };
197 Ok(Self {
198 order_id: report.order_id.ok_or_else(|| missing(TAG_ORDER_ID))?,
199 cl_ord_id: report
200 .cl_ord_id
201 .clone()
202 .ok_or_else(|| missing(TAG_CL_ORD_ID))?,
203 exec_type: report.exec_type,
204 status: report.ord_status,
205 symbol: report.symbol.ok_or_else(|| missing(TAG_SYMBOL))?,
206 side: report.side.ok_or_else(|| missing(TAG_SIDE))?,
207 quantity: report.order_qty.ok_or_else(|| missing(TAG_ORDER_QTY))?,
208 kind: report.ord_type,
209 price: report.price,
210 stop_price: report.stop_px,
211 time_in_force: report.time_in_force,
212 expiry: report.expire_time,
213 filled: report.cum_qty,
214 remaining: report.leaves_qty,
215 last_quantity: report.last_qty,
216 average_price: report.avg_px,
217 position: report.position_id,
218 label: report.designation.clone(),
219 time: report.transact_time,
220 text: report.text.clone(),
221 })
222 }
223}
224
225pub(crate) fn refused(report: &ExecutionReport) -> ConnectorError {
226 FixError::OrderRejected {
227 cl_ord_id: report.cl_ord_id.clone(),
228 reason: report.ord_rej_reason,
229 text: report.text.clone(),
230 }
231 .into()
232}
233
234fn placed(
235 report: &ExecutionReport,
236 kind: OrderKind,
237) -> Option<Result<OrderReport, ConnectorError>> {
238 match (report.exec_type, kind) {
239 (ExecType::New, OrderKind::Market) => None,
240 (ExecType::Rejected | ExecType::Canceled | ExecType::Expired, _) => {
241 Some(Err(refused(report)))
242 }
243 _ => Some(OrderReport::try_from(report).map_err(ConnectorError::from)),
244 }
245}
246
247impl FixClient {
248 pub async fn place(&self, order: NewOrder) -> Result<OrderReport, ConnectorError> {
263 let id = self.next_id(ORDER_PREFIX);
264 let kind = order.kind();
265 self.request_once(order.message(&id).into(), &id, |message| match message {
266 Message::ExecutionReport(report) if report.cl_ord_id.as_deref() == Some(&id) => {
267 placed(report, kind)
268 }
269 _ => None,
270 })
271 .await
272 }
273}