Skip to main content

ctrader_connector/fix/
amend.rs

1//! Changes to waiting orders of the trade session: cancelling and replacing.
2//!
3//! Both requests name the order by the identifier the client gave it. The report of a
4//! replacement carries the identifier of the replacement request, but the order goes on
5//! answering to the identifier it was placed under.
6//!
7//! The server refuses a change with an order cancel reject or, for an order it does not
8//! know, with a business message reject; both are reported as
9//! [`FixError::CancelRejected`].
10
11use crate::common::decimals::{Price, Volume};
12use crate::common::errors::{ConnectorError, FixError, RefusedChange};
13use crate::common::time::Timestamp;
14use crate::fix::client::FixClient;
15use crate::fix::messages::{
16    CancelRejectResponse, ExecType, Message, OrderCancelReplaceRequest, OrderCancelRequest,
17};
18use crate::fix::trading::{OrderReport, refused};
19
20const CANCEL_PREFIX: &str = "c";
21const REPLACE_PREFIX: &str = "r";
22
23/// New terms of a waiting order.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct Replacement {
26    quantity: Volume,
27    price: Option<Price>,
28    stop_price: Option<Price>,
29    expiry: Option<Timestamp>,
30}
31
32impl Replacement {
33    /// Starts the new terms with the quantity, which every replacement states.
34    #[must_use]
35    pub const fn new(quantity: Volume) -> Self {
36        Self {
37            quantity,
38            price: None,
39            stop_price: None,
40            expiry: None,
41        }
42    }
43
44    /// Sets the limit price of a limit order.
45    #[must_use]
46    pub const fn price(mut self, price: Price) -> Self {
47        self.price = Some(price);
48        self
49    }
50
51    /// Sets the stop price of a stop order.
52    #[must_use]
53    pub const fn stop_price(mut self, price: Price) -> Self {
54        self.stop_price = Some(price);
55        self
56    }
57
58    /// Sets the moment the order expires.
59    #[must_use]
60    pub const fn expires(mut self, at: Timestamp) -> Self {
61        self.expiry = Some(at);
62        self
63    }
64}
65
66const fn change(response_to: CancelRejectResponse) -> RefusedChange {
67    match response_to {
68        CancelRejectResponse::Cancel => RefusedChange::Cancel,
69        CancelRejectResponse::Replace => RefusedChange::Replace,
70    }
71}
72
73fn unchanged(
74    error: ConnectorError,
75    response_to: CancelRejectResponse,
76    cl_ord_id: &str,
77    orig_cl_ord_id: &str,
78) -> ConnectorError {
79    match error {
80        ConnectorError::Fix(FixError::BusinessRejected { text, .. }) => FixError::CancelRejected {
81            cl_ord_id: cl_ord_id.to_owned(),
82            orig_cl_ord_id: Some(orig_cl_ord_id.to_owned()),
83            change: change(response_to),
84            text,
85        }
86        .into(),
87        other => other,
88    }
89}
90
91impl FixClient {
92    async fn amend(
93        &self,
94        request: Message,
95        id: &str,
96        orig_cl_ord_id: &str,
97        response_to: CancelRejectResponse,
98    ) -> Result<OrderReport, ConnectorError> {
99        let wanted = match response_to {
100            CancelRejectResponse::Cancel => ExecType::Canceled,
101            CancelRejectResponse::Replace => ExecType::Replaced,
102        };
103        let pick = |message: &Message| match message {
104            Message::ExecutionReport(report) if report.cl_ord_id.as_deref() == Some(id) => {
105                if report.exec_type == wanted {
106                    Some(OrderReport::try_from(report.as_ref()).map_err(ConnectorError::from))
107                } else if report.exec_type == ExecType::Rejected {
108                    Some(Err(refused(report)))
109                } else {
110                    None
111                }
112            }
113            Message::OrderCancelReject(reject) if reject.cl_ord_id == id => {
114                Some(Err(FixError::CancelRejected {
115                    cl_ord_id: reject.cl_ord_id.clone(),
116                    orig_cl_ord_id: reject.orig_cl_ord_id.clone(),
117                    change: change(reject.response_to),
118                    text: reject.text.clone(),
119                }
120                .into()))
121            }
122            _ => None,
123        };
124        let outcome = match response_to {
125            CancelRejectResponse::Cancel => self.request(request, id, pick).await,
126            CancelRejectResponse::Replace => self.request_once(request, id, pick).await,
127        };
128        outcome.map_err(|error| unchanged(error, response_to, id, orig_cl_ord_id))
129    }
130
131    /// Cancels the waiting order the client gave the identifier `cl_ord_id` and returns the
132    /// report of the cancellation.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`ConnectorError::Fix`] with [`FixError::CancelRejected`] when the server
137    /// refuses, among others because it knows no such order, and otherwise the errors of
138    /// [`FixClient::request`]. A cancellation may be repeated after a
139    /// [`ConnectorError::Timeout`].
140    pub async fn cancel(&self, cl_ord_id: &str) -> Result<OrderReport, ConnectorError> {
141        let id = self.next_id(CANCEL_PREFIX);
142        let request = OrderCancelRequest {
143            orig_cl_ord_id: cl_ord_id.to_owned(),
144            order_id: None,
145            cl_ord_id: id.clone(),
146        };
147        self.amend(request.into(), &id, cl_ord_id, CancelRejectResponse::Cancel)
148            .await
149    }
150
151    /// Replaces the terms of the waiting order the client gave the identifier `cl_ord_id`
152    /// and returns the report of the order as replaced. The report carries the identifier of
153    /// the request; the order goes on answering to the identifier it was placed under.
154    ///
155    /// # Errors
156    ///
157    /// Returns [`ConnectorError::Fix`] with [`FixError::CancelRejected`] when the server
158    /// refuses, among others because it knows no such order,
159    /// [`ConnectorError::OutcomeUnknown`] when the answer does not arrive in time or the
160    /// session is lost first, and otherwise the errors of [`FixClient::request_once`].
161    pub async fn replace(
162        &self,
163        cl_ord_id: &str,
164        terms: Replacement,
165    ) -> Result<OrderReport, ConnectorError> {
166        let id = self.next_id(REPLACE_PREFIX);
167        let request = OrderCancelReplaceRequest {
168            orig_cl_ord_id: cl_ord_id.to_owned(),
169            order_id: None,
170            cl_ord_id: id.clone(),
171            order_qty: terms.quantity,
172            price: terms.price,
173            stop_px: terms.stop_price,
174            expire_time: terms.expiry,
175        };
176        self.amend(
177            request.into(),
178            &id,
179            cl_ord_id,
180            CancelRejectResponse::Replace,
181        )
182        .await
183    }
184}