Skip to main content

ctrader_connector/fix/
trading.rs

1//! Orders of the trade session.
2//!
3//! A [`NewOrder`] is built for one of the three kinds the session takes, at the market, at
4//! a limit or at a stop, and placed with [`FixClient::place`]. The answer is an
5//! [`OrderReport`], the execution report of the server with the fields every such report of
6//! an order carries made mandatory.
7//!
8//! The quantity of an order counts units of the base asset of the symbol, not lots: the
9//! server accepts `0.01` for a symbol traded in hundredths and `1000` for one traded in
10//! thousands, and reports the same number back.
11//!
12//! ```no_run
13//! use ctrader_connector::common::config::ConfigurationFix;
14//! use ctrader_connector::common::ids::SymbolId;
15//! use ctrader_connector::fix::client::FixClient;
16//! use ctrader_connector::fix::messages::Side;
17//! use ctrader_connector::fix::session::SessionKind;
18//! use ctrader_connector::fix::trading::NewOrder;
19//!
20//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
21//! let client = FixClient::connect(ConfigurationFix::from_env()?, SessionKind::Trade).await?;
22//! let order = NewOrder::limit(SymbolId::new(1)?, Side::Buy, "1000".parse()?, "0.9".parse()?)
23//!     .label("example");
24//! let report = client.place(order).await?;
25//! println!("{} is {:?}", report.order_id, report.status);
26//! client.logout().await?;
27//! # Ok(())
28//! # }
29//! ```
30
31use 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/// An order to be placed.
48#[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    /// Starts an order executed at once at the price of the market.
77    #[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    /// Starts an order that waits for the given price or a better one.
83    #[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    /// Starts an order that becomes a market order once the given price is reached.
91    #[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    /// Sets the label the order and its position carry.
99    #[must_use]
100    pub fn label(mut self, label: impl Into<String>) -> Self {
101        self.label = Some(label.into());
102        self
103    }
104
105    /// Names the position the order adds to or reduces; without it the order opens a
106    /// position of its own.
107    #[must_use]
108    pub const fn position(mut self, position: PositionId) -> Self {
109        self.position = Some(position);
110        self
111    }
112
113    /// Sets the moment a waiting order expires; without it the order waits until cancelled.
114    #[must_use]
115    pub const fn expires(mut self, at: Timestamp) -> Self {
116        self.expiry = Some(at);
117        self
118    }
119
120    /// Returns the kind of the order.
121    #[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/// State of an order as the server reports it.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct OrderReport {
147    /// Identifier the server gave the order, the same the other API of the server uses.
148    pub order_id: OrderId,
149    /// Identifier the client gave the order.
150    pub cl_ord_id: String,
151    /// What the report tells: an acceptance, a fill, a change, a cancellation or a state.
152    pub exec_type: ExecType,
153    /// State of the order.
154    pub status: OrderStatus,
155    /// Symbol of the order.
156    pub symbol: SymbolId,
157    /// Side of the order.
158    pub side: Side,
159    /// Quantity ordered, in units of the base asset.
160    pub quantity: Volume,
161    /// Kind of the order.
162    pub kind: Option<OrderKind>,
163    /// Limit price.
164    pub price: Option<Price>,
165    /// Stop price.
166    pub stop_price: Option<Price>,
167    /// How long the order stays in force.
168    pub time_in_force: Option<TimeInForce>,
169    /// Moment the order expires.
170    pub expiry: Option<Timestamp>,
171    /// Quantity filled so far.
172    pub filled: Option<Volume>,
173    /// Quantity still open.
174    pub remaining: Option<Volume>,
175    /// Quantity of the fill the report tells of.
176    pub last_quantity: Option<Volume>,
177    /// Average price of the fills.
178    pub average_price: Option<Price>,
179    /// Position the order belongs to.
180    pub position: Option<PositionId>,
181    /// Label of the order.
182    pub label: Option<String>,
183    /// Moment of the report.
184    pub time: Option<Timestamp>,
185    /// Explanation of the server.
186    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    /// Places an order and returns the report that settles the request: the fill of a market
249    /// order, the acceptance of a limit or stop order.
250    ///
251    /// The order is sent once and never again by the library.
252    ///
253    /// # Errors
254    ///
255    /// Returns [`ConnectorError::Fix`] with [`FixError::OrderRejected`] when the server
256    /// accepts the message and then refuses, cancels or expires the order, with
257    /// [`FixError::BusinessRejected`] or [`FixError::Rejected`] when it refuses the message,
258    /// and with [`FixError::MissingField`] when its report lacks a field every report of an
259    /// order carries. Returns [`ConnectorError::OutcomeUnknown`] when the answer does not
260    /// arrive in time or the session is lost first: the order may or may not exist. Returns
261    /// otherwise the errors of [`FixClient::request_once`].
262    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}