ctrader_connector/fix/client.rs
1//! Client of one FIX session of a trading account.
2//!
3//! An account has two sessions, one for prices and one for trading; each is a connection of
4//! its own and a [`FixClient`] of its own.
5//!
6//! ```no_run
7//! use ctrader_connector::common::config::ConfigurationFix;
8//! use ctrader_connector::fix::client::FixClient;
9//! use ctrader_connector::fix::session::SessionKind;
10//!
11//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
12//! let client = FixClient::connect(ConfigurationFix::from_env()?, SessionKind::Quote).await?;
13//! client.logout().await?;
14//! # Ok(())
15//! # }
16//! ```
17
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::time::Duration;
21
22use tokio::sync::broadcast::error::RecvError;
23use tokio::sync::{broadcast, mpsc, oneshot, watch};
24use tokio::time::timeout;
25
26use crate::common::config::ConfigurationFix;
27use crate::common::errors::{ConnectorError, FixError, Interruption, TransportError};
28use crate::common::time::Timestamp;
29use crate::common::transport::{Connect, Plain, Tls};
30use crate::fix::messages::Message;
31use crate::fix::session::{Command, Event, SessionKind, start};
32
33/// Cloneable client of one FIX session.
34#[derive(Debug, Clone)]
35pub struct FixClient {
36 commands: mpsc::Sender<Command>,
37 events: broadcast::Sender<Event>,
38 closed: watch::Receiver<bool>,
39 kind: SessionKind,
40 timeout: Duration,
41 counter: Arc<AtomicU64>,
42}
43
44impl FixClient {
45 /// Connects to the host named by the configuration and logs on to the session.
46 ///
47 /// The connection runs over TLS unless the configuration asks for none.
48 ///
49 /// # Errors
50 ///
51 /// Returns [`ConnectorError::Transport`] when the connection cannot be established,
52 /// [`ConnectorError::Fix`] with [`FixError::LogonRefused`] when the server answers the
53 /// logon with a logout, and [`ConnectorError::Timeout`] when it does not answer in time.
54 pub async fn connect(
55 configuration: ConfigurationFix,
56 kind: SessionKind,
57 ) -> Result<Self, ConnectorError> {
58 if configuration.encrypted() {
59 Self::connect_with(configuration, kind, Tls::new()?).await
60 } else {
61 Self::connect_with(configuration, kind, Plain).await
62 }
63 }
64
65 /// Connects through the given connector and logs on to the session.
66 ///
67 /// # Errors
68 ///
69 /// Returns the errors of [`FixClient::connect`].
70 pub async fn connect_with<C: Connect>(
71 configuration: ConfigurationFix,
72 kind: SessionKind,
73 connector: C,
74 ) -> Result<Self, ConnectorError> {
75 let limit = configuration.timeout();
76 let started = start(connector, configuration, kind).await?;
77 Ok(Self {
78 commands: started.commands,
79 events: started.events,
80 closed: started.closed,
81 kind,
82 timeout: limit,
83 counter: Arc::new(AtomicU64::new(0)),
84 })
85 }
86
87 /// Returns which session the client serves.
88 #[must_use]
89 pub const fn kind(&self) -> SessionKind {
90 self.kind
91 }
92
93 /// Returns the longest wait for an answer of the server.
94 #[must_use]
95 pub const fn timeout(&self) -> Duration {
96 self.timeout
97 }
98
99 /// Subscribes to the events of the session from this moment on.
100 ///
101 /// A reader that falls behind loses the oldest events and is told how many.
102 #[must_use]
103 pub fn events(&self) -> broadcast::Receiver<Event> {
104 self.events.subscribe()
105 }
106
107 /// Sends a message and returns the sequence number it was given.
108 ///
109 /// The message goes out as it is, with one exception: a business message reject (j) is
110 /// never sent. It is refused here, before anything is written and without a sequence
111 /// number, because the server refuses one with a reject and closes the connection.
112 /// Every message of the application passes through this method, those of
113 /// [`FixClient::request`] and [`FixClient::request_once`] included.
114 ///
115 /// # Errors
116 ///
117 /// Returns [`ConnectorError::Fix`] with [`FixError::Unsendable`] for a business message
118 /// reject and with another [`FixError`] when the message cannot be encoded,
119 /// [`ConnectorError::Transport`] when the write fails, and [`ConnectorError::Closed`]
120 /// when the session has ended or is between two connections; the message was not sent
121 /// then.
122 pub async fn send(&self, message: Message) -> Result<u64, ConnectorError> {
123 if matches!(message, Message::BusinessReject(_)) {
124 return Err(FixError::Unsendable(message.msg_type().to_owned()).into());
125 }
126 let (reply, answer) = oneshot::channel();
127 self.commands
128 .send(Command::Send { message, reply })
129 .await
130 .map_err(|_| ConnectorError::Closed)?;
131 answer.await.map_err(|_| ConnectorError::Closed)?
132 }
133
134 /// Logs out and closes the connection; the session ends for every clone of the client.
135 ///
136 /// # Errors
137 ///
138 /// Returns [`ConnectorError::Timeout`] when the server does not confirm the logout in
139 /// time, [`ConnectorError::Transport`] when the connection fails first, and
140 /// [`ConnectorError::Closed`] when the session has ended already. The connection is
141 /// closed in every case. A logout between two connections ends the session without
142 /// an exchange and returns `Ok`.
143 pub async fn logout(&self) -> Result<(), ConnectorError> {
144 let (reply, answer) = oneshot::channel();
145 self.commands
146 .send(Command::Logout { reply })
147 .await
148 .map_err(|_| ConnectorError::Closed)?;
149 answer.await.map_err(|_| ConnectorError::Closed)?
150 }
151
152 /// Drops the connection on this side, which starts a reconnection as a loss would.
153 ///
154 /// # Errors
155 ///
156 /// Returns [`ConnectorError::Closed`] when the session has ended.
157 pub async fn force_reconnect(&self) -> Result<(), ConnectorError> {
158 let (reply, answer) = oneshot::channel();
159 self.commands
160 .send(Command::Reconnect { reply })
161 .await
162 .map_err(|_| ConnectorError::Closed)?;
163 answer.await.map_err(|_| ConnectorError::Closed)?
164 }
165
166 /// Waits until the session has ended.
167 pub async fn closed(&self) {
168 let mut closed = self.closed.clone();
169 let _ = closed.wait_for(|closed| *closed).await;
170 }
171
172 /// Sends a request and waits for the message `pick` accepts as its answer.
173 ///
174 /// `pick` sees every message that arrives after the request was sent and returns the
175 /// outcome once it recognises the answer. `reference` is the identifier the request
176 /// carries, by which a refusal of the server names it; it may be empty.
177 ///
178 /// # Errors
179 ///
180 /// Returns [`ConnectorError::Fix`] with [`FixError::Rejected`] or
181 /// [`FixError::BusinessRejected`] when the server refuses the request,
182 /// [`ConnectorError::Timeout`] when no answer arrives in time,
183 /// [`ConnectorError::OutcomeUnknown`] when the server asks for the request again, which
184 /// the library never sends twice,
185 /// [`ConnectorError::Transport`] when the connection is lost first,
186 /// [`ConnectorError::Lagged`] when the reader fell behind and the answer may have been
187 /// skipped, and [`ConnectorError::Closed`] when the session has ended already or has no
188 /// connection at the moment, between [`Event::Disconnected`] and [`Event::Reconnected`].
189 pub async fn request<T>(
190 &self,
191 message: Message,
192 reference: &str,
193 pick: impl FnMut(&Message) -> Option<Result<T, ConnectorError>>,
194 ) -> Result<T, ConnectorError> {
195 self.exchange(message, reference, false, pick).await
196 }
197
198 /// Sends a request that must not be sent twice, such as an order, and waits for its answer.
199 ///
200 /// # Errors
201 ///
202 /// Returns the errors of [`FixClient::request`], except that a wait cut short by the
203 /// deadline or by the loss of the session is reported as
204 /// [`ConnectorError::OutcomeUnknown`]: the server may have acted on the request.
205 pub async fn request_once<T>(
206 &self,
207 message: Message,
208 reference: &str,
209 pick: impl FnMut(&Message) -> Option<Result<T, ConnectorError>>,
210 ) -> Result<T, ConnectorError> {
211 self.exchange(message, reference, true, pick).await
212 }
213
214 /// Returns an identifier no other request of this client carries.
215 #[must_use]
216 pub fn next_id(&self, prefix: &str) -> String {
217 let number = self.counter.fetch_add(1, Ordering::Relaxed);
218 format!("{prefix}{}n{number}", Timestamp::now().as_millis())
219 }
220
221 /// Sends a request and waits for what `pick` accepts as its answer.
222 ///
223 /// A reject of the session level or of the application level that refers to the request,
224 /// by its sequence number or by `reference`, ends the wait with a typed error. For a
225 /// `critical` request, one that must not be sent twice, a wait cut short by the deadline
226 /// or by the loss of the connection is reported as [`ConnectorError::OutcomeUnknown`].
227 async fn exchange<T>(
228 &self,
229 message: Message,
230 reference: &str,
231 critical: bool,
232 mut pick: impl FnMut(&Message) -> Option<Result<T, ConnectorError>>,
233 ) -> Result<T, ConnectorError> {
234 let interrupted = |interruption: Interruption| match (critical, interruption) {
235 (true, interruption) => ConnectorError::OutcomeUnknown(interruption),
236 (false, Interruption::Timeout(limit)) => ConnectorError::Timeout(limit),
237 (false, Interruption::Transport(error)) => ConnectorError::Transport(error),
238 (false, Interruption::Skipped) => ConnectorError::OutcomeUnknown(Interruption::Skipped),
239 };
240 let mut events = self.events.subscribe();
241 let seq = match self.send(message).await {
242 Err(ConnectorError::Transport(error)) => {
243 return Err(interrupted(Interruption::Transport(error)));
244 }
245 sent => sent?,
246 };
247 let limit = self.timeout;
248 let waited = timeout(limit, async {
249 loop {
250 let inbound = match events.recv().await {
251 Ok(Event::Message(inbound)) => inbound,
252 Ok(Event::Disconnected(error)) => {
253 return Err(interrupted(Interruption::Transport(error)));
254 }
255 Ok(Event::LoggedOut { .. } | Event::Ended) | Err(RecvError::Closed) => {
256 return Err(interrupted(Interruption::Transport(TransportError::Closed)));
257 }
258 Ok(Event::Skipped { from, to }) if (from..=to).contains(&seq) => {
259 return Err(ConnectorError::OutcomeUnknown(Interruption::Skipped));
260 }
261 Ok(_) => continue,
262 Err(RecvError::Lagged(skipped)) => {
263 return Err(ConnectorError::Lagged { skipped });
264 }
265 };
266 match &inbound.message {
267 Message::Reject(reject) if reject.ref_seq_num == seq => {
268 return Err(FixError::Rejected {
269 ref_seq_num: seq,
270 tag: reject.ref_tag_id,
271 reason: reject.reason,
272 text: reject.text.clone(),
273 }
274 .into());
275 }
276 Message::BusinessReject(reject)
277 if reject.ref_seq_num == Some(seq)
278 || (!reference.is_empty()
279 && reject.ref_id.as_deref() == Some(reference)) =>
280 {
281 return Err(FixError::BusinessRejected {
282 ref_id: reject.ref_id.clone(),
283 reason: reject.reason,
284 text: reject.text.clone(),
285 }
286 .into());
287 }
288 other => {
289 if let Some(result) = pick(other) {
290 return result;
291 }
292 }
293 }
294 }
295 })
296 .await;
297 waited.unwrap_or_else(|_| Err(interrupted(Interruption::Timeout(limit))))
298 }
299}