Skip to main content

ctrader_connector/fix/
quotes.rs

1//! Prices of the quote session: spot prices and the depth of the market.
2//!
3//! A subscription is a stream of its own. A [`SpotStream`] yields the best bid and offer of a
4//! symbol each time the server reports them; a [`DepthStream`] keeps the [`Book`] of a symbol
5//! up to date and yields it after every change. The server tags every report with the
6//! identifier of the subscription it belongs to, so that streams of the same symbol do not
7//! mix. It sends the best prices as full snapshots, and the depth as an empty snapshot
8//! followed by changes.
9//!
10//! A stream outlives a lost connection: it reports the loss once as an error, and when the
11//! session is logged on again it subscribes anew, since the server has forgotten the
12//! subscription. The depth then starts over from an empty book.
13//!
14//! ```no_run
15//! use ctrader_connector::common::config::ConfigurationFix;
16//! use ctrader_connector::common::ids::SymbolId;
17//! use ctrader_connector::fix::client::FixClient;
18//! use ctrader_connector::fix::session::SessionKind;
19//!
20//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
21//! let client = FixClient::connect(ConfigurationFix::from_env()?, SessionKind::Quote).await?;
22//! let mut spots = client.subscribe_spot(SymbolId::new(1)?).await?;
23//! let quote = spots.next().await?;
24//! println!("{:?} / {:?}", quote.bid, quote.offer);
25//! spots.unsubscribe().await?;
26//! client.logout().await?;
27//! # Ok(())
28//! # }
29//! ```
30
31use std::collections::BTreeMap;
32
33use tokio::sync::broadcast;
34use tokio::sync::broadcast::error::RecvError;
35use tokio::time::timeout;
36
37use crate::common::decimals::{Price, Volume};
38use crate::common::errors::{ConnectorError, FixError, TransportError};
39use crate::common::ids::SymbolId;
40use crate::fix::client::FixClient;
41use crate::fix::messages::{
42    BookSide, BookUpdate, MarketDataRequest, MarketDataSnapshot, MarketDepth, Message,
43};
44use crate::fix::session::Event;
45
46const REQUEST_PREFIX: &str = "md";
47
48/// Best prices of a symbol.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct SpotQuote {
51    /// Symbol the prices belong to.
52    pub symbol: SymbolId,
53    /// Best bid, absent while the server reports none.
54    pub bid: Option<Price>,
55    /// Best offer, absent while the server reports none.
56    pub offer: Option<Price>,
57}
58
59/// One entry of a book.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct BookEntry {
62    /// Identifier of the entry, by which the server removes it.
63    pub id: String,
64    /// Side of the entry.
65    pub side: BookSide,
66    /// Price.
67    pub price: Price,
68    /// Quantity offered at the price.
69    pub size: Option<Volume>,
70}
71
72/// Depth of the market of one symbol.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Book {
75    symbol: SymbolId,
76    entries: BTreeMap<String, BookEntry>,
77}
78
79impl Book {
80    /// Creates the empty book of a symbol.
81    #[must_use]
82    pub const fn new(symbol: SymbolId) -> Self {
83        Self {
84            symbol,
85            entries: BTreeMap::new(),
86        }
87    }
88
89    /// Returns the symbol the book belongs to.
90    #[must_use]
91    pub const fn symbol(&self) -> SymbolId {
92        self.symbol
93    }
94
95    /// Returns the number of entries.
96    #[must_use]
97    pub fn len(&self) -> usize {
98        self.entries.len()
99    }
100
101    /// Tells whether the book holds no entry.
102    #[must_use]
103    pub fn is_empty(&self) -> bool {
104        self.entries.is_empty()
105    }
106
107    /// Returns the bids, the highest price first.
108    #[must_use]
109    pub fn bids(&self) -> Vec<&BookEntry> {
110        let mut bids = self.side(BookSide::Bid);
111        bids.sort_by(|a, b| b.price.cmp(&a.price));
112        bids
113    }
114
115    /// Returns the offers, the lowest price first.
116    #[must_use]
117    pub fn offers(&self) -> Vec<&BookEntry> {
118        let mut offers = self.side(BookSide::Offer);
119        offers.sort_by(|a, b| a.price.cmp(&b.price));
120        offers
121    }
122
123    fn side(&self, side: BookSide) -> Vec<&BookEntry> {
124        self.entries
125            .values()
126            .filter(|entry| entry.side == side)
127            .collect()
128    }
129
130    /// Replaces the content of the book by a snapshot of the same symbol; a snapshot of
131    /// another symbol is ignored.
132    pub fn replace(&mut self, snapshot: &MarketDataSnapshot) {
133        if snapshot.symbol != self.symbol {
134            return;
135        }
136        self.entries.clear();
137        for (position, entry) in snapshot.entries.iter().enumerate() {
138            let id = entry
139                .id
140                .clone()
141                .unwrap_or_else(|| format!("{}{position}", entry.side.as_str()));
142            self.entries.insert(
143                id.clone(),
144                BookEntry {
145                    id,
146                    side: entry.side,
147                    price: entry.price,
148                    size: entry.size,
149                },
150            );
151        }
152    }
153
154    /// Applies one change; a change of another symbol is ignored.
155    pub fn apply(&mut self, update: &BookUpdate) {
156        match update {
157            BookUpdate::New {
158                side,
159                id,
160                symbol,
161                price,
162                size,
163            } if *symbol == self.symbol => {
164                self.entries.insert(
165                    id.clone(),
166                    BookEntry {
167                        id: id.clone(),
168                        side: *side,
169                        price: *price,
170                        size: *size,
171                    },
172                );
173            }
174            BookUpdate::Delete { id, symbol } if *symbol == self.symbol => {
175                self.entries.remove(id);
176            }
177            _ => {}
178        }
179    }
180}
181
182enum Step {
183    Snapshot(MarketDataSnapshot),
184    Changes(Vec<BookUpdate>),
185}
186
187#[derive(Debug)]
188struct Feed {
189    client: FixClient,
190    events: broadcast::Receiver<Event>,
191    md_req_id: String,
192    symbol: SymbolId,
193    depth: MarketDepth,
194    seq: u64,
195    ended: bool,
196}
197
198impl Feed {
199    fn request(&self, subscribe: bool) -> Message {
200        MarketDataRequest {
201            md_req_id: self.md_req_id.clone(),
202            subscribe,
203            depth: self.depth,
204            symbols: vec![self.symbol],
205            sides: vec![BookSide::Bid, BookSide::Offer],
206        }
207        .into()
208    }
209
210    async fn open(
211        client: &FixClient,
212        symbol: SymbolId,
213        depth: MarketDepth,
214    ) -> Result<Self, ConnectorError> {
215        let mut feed = Self {
216            client: client.clone(),
217            events: client.events(),
218            md_req_id: client.next_id(REQUEST_PREFIX),
219            symbol,
220            depth,
221            seq: 0,
222            ended: false,
223        };
224        feed.seq = client.send(feed.request(true)).await?;
225        Ok(feed)
226    }
227
228    fn mine(&self, md_req_id: Option<&str>) -> bool {
229        md_req_id == Some(self.md_req_id.as_str())
230    }
231
232    async fn step(&mut self) -> Result<Step, ConnectorError> {
233        if self.ended {
234            return Err(ConnectorError::Closed);
235        }
236        loop {
237            let inbound = match self.events.recv().await {
238                Ok(Event::Message(inbound)) => inbound,
239                Ok(Event::Disconnected(error)) => return Err(error.into()),
240                Ok(Event::LoggedOut { .. } | Event::Ended) | Err(RecvError::Closed) => {
241                    self.ended = true;
242                    return Err(TransportError::Closed.into());
243                }
244                Ok(Event::Reconnected { .. }) => {
245                    self.seq = self.client.send(self.request(true)).await?;
246                    continue;
247                }
248                Ok(_) => continue,
249                Err(RecvError::Lagged(skipped)) => {
250                    return Err(ConnectorError::Lagged { skipped });
251                }
252            };
253            match inbound.message {
254                Message::MarketDataSnapshot(snapshot)
255                    if self.mine(snapshot.md_req_id.as_deref())
256                        && snapshot.symbol == self.symbol =>
257                {
258                    return Ok(Step::Snapshot(snapshot));
259                }
260                Message::MarketDataIncremental(changes)
261                    if self.mine(changes.md_req_id.as_deref()) =>
262                {
263                    return Ok(Step::Changes(changes.entries));
264                }
265                Message::MarketDataReject(reject) if reject.md_req_id == self.md_req_id => {
266                    return Err(FixError::MarketDataRejected {
267                        reason: reject.reason,
268                        text: reject.text,
269                    }
270                    .into());
271                }
272                Message::Reject(reject) if reject.ref_seq_num == self.seq => {
273                    return Err(FixError::Rejected {
274                        ref_seq_num: self.seq,
275                        tag: reject.ref_tag_id,
276                        reason: reject.reason,
277                        text: reject.text,
278                    }
279                    .into());
280                }
281                Message::BusinessReject(reject)
282                    if reject.ref_seq_num == Some(self.seq)
283                        || reject.ref_id.as_deref() == Some(self.md_req_id.as_str()) =>
284                {
285                    return Err(FixError::BusinessRejected {
286                        ref_id: reject.ref_id,
287                        reason: reject.reason,
288                        text: reject.text,
289                    }
290                    .into());
291                }
292                _ => {}
293            }
294        }
295    }
296
297    async fn first(&mut self) -> Result<Step, ConnectorError> {
298        let limit = self.client.timeout();
299        timeout(limit, self.step())
300            .await
301            .map_err(|_| ConnectorError::Timeout(limit))?
302    }
303
304    async fn close(&self) -> Result<(), ConnectorError> {
305        self.client.send(self.request(false)).await.map(|_| ())
306    }
307}
308
309/// Stream of the best prices of one symbol.
310#[derive(Debug)]
311pub struct SpotStream {
312    feed: Feed,
313    last: SpotQuote,
314}
315
316impl SpotStream {
317    /// Returns the symbol the stream reports.
318    #[must_use]
319    pub const fn symbol(&self) -> SymbolId {
320        self.feed.symbol
321    }
322
323    /// Returns the prices reported last.
324    #[must_use]
325    pub const fn last(&self) -> SpotQuote {
326        self.last
327    }
328
329    fn take(&mut self, step: Step) -> Option<SpotQuote> {
330        let Step::Snapshot(snapshot) = step else {
331            return None;
332        };
333        let best = |side: BookSide| {
334            snapshot
335                .entries
336                .iter()
337                .find(|entry| entry.side == side)
338                .map(|entry| entry.price)
339        };
340        self.last = SpotQuote {
341            symbol: snapshot.symbol,
342            bid: best(BookSide::Bid),
343            offer: best(BookSide::Offer),
344        };
345        Some(self.last)
346    }
347
348    /// Waits for the next report of the prices.
349    ///
350    /// The wait has no deadline of its own: a market may stand still. The session notices a
351    /// server that has gone silent and ends the wait with an error.
352    ///
353    /// # Errors
354    ///
355    /// Returns [`ConnectorError::Transport`] when the connection is lost, after which the
356    /// stream goes on once the session is logged on again, or when the session ends,
357    /// [`ConnectorError::Closed`] when it has ended before,
358    /// [`ConnectorError::Lagged`] when the reader fell behind and reports were skipped, and
359    /// [`ConnectorError::Fix`] when the server refuses the subscription.
360    pub async fn next(&mut self) -> Result<SpotQuote, ConnectorError> {
361        loop {
362            let step = self.feed.step().await?;
363            if let Some(quote) = self.take(step) {
364                return Ok(quote);
365            }
366        }
367    }
368
369    /// Ends the subscription.
370    ///
371    /// # Errors
372    ///
373    /// Returns [`ConnectorError::Transport`] when the request cannot be written and
374    /// [`ConnectorError::Closed`] when the session has ended already.
375    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
376        self.feed.close().await
377    }
378}
379
380/// Stream of the depth of the market of one symbol.
381#[derive(Debug)]
382pub struct DepthStream {
383    feed: Feed,
384    book: Book,
385}
386
387impl DepthStream {
388    /// Returns the symbol the stream reports.
389    #[must_use]
390    pub const fn symbol(&self) -> SymbolId {
391        self.feed.symbol
392    }
393
394    /// Returns the book as of the last change.
395    #[must_use]
396    pub const fn book(&self) -> &Book {
397        &self.book
398    }
399
400    fn take(&mut self, step: &Step) {
401        match step {
402            Step::Snapshot(snapshot) => self.book.replace(snapshot),
403            Step::Changes(changes) => {
404                for change in changes {
405                    self.book.apply(change);
406                }
407            }
408        }
409    }
410
411    /// Waits for the next change and returns the book after it.
412    ///
413    /// The wait has no deadline of its own: a market may stand still. The session notices a
414    /// server that has gone silent and ends the wait with an error.
415    ///
416    /// # Errors
417    ///
418    /// Returns [`ConnectorError::Transport`] when the connection is lost, after which the
419    /// stream goes on from an empty book once the session is logged on again, or when the
420    /// session ends, [`ConnectorError::Closed`] when it has ended before,
421    /// [`ConnectorError::Lagged`] when the reader fell behind, and [`ConnectorError::Fix`]
422    /// when the server refuses the subscription. After changes were skipped the book is no
423    /// longer that of the server; the subscription has to be opened anew.
424    pub async fn next(&mut self) -> Result<&Book, ConnectorError> {
425        let step = self.feed.step().await?;
426        self.take(&step);
427        Ok(&self.book)
428    }
429
430    /// Ends the subscription.
431    ///
432    /// # Errors
433    ///
434    /// Returns [`ConnectorError::Transport`] when the request cannot be written and
435    /// [`ConnectorError::Closed`] when the session has ended already.
436    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
437        self.feed.close().await
438    }
439}
440
441impl FixClient {
442    /// Subscribes to the best prices of a symbol and waits for the first report.
443    ///
444    /// # Errors
445    ///
446    /// Returns [`ConnectorError::Fix`] when the server refuses the subscription,
447    /// [`ConnectorError::Timeout`] when no price arrives in time, and
448    /// [`ConnectorError::Transport`] or [`ConnectorError::Closed`] when the session ends.
449    pub async fn subscribe_spot(&self, symbol: SymbolId) -> Result<SpotStream, ConnectorError> {
450        let mut stream = SpotStream {
451            feed: Feed::open(self, symbol, MarketDepth::Spot).await?,
452            last: SpotQuote {
453                symbol,
454                bid: None,
455                offer: None,
456            },
457        };
458        loop {
459            let step = stream.feed.first().await?;
460            if stream.take(step).is_some() {
461                return Ok(stream);
462            }
463        }
464    }
465
466    /// Subscribes to the depth of the market of a symbol and waits for the first book, which
467    /// the server sends empty; the entries follow as changes.
468    ///
469    /// # Errors
470    ///
471    /// Returns the errors of [`FixClient::subscribe_spot`].
472    pub async fn subscribe_depth(&self, symbol: SymbolId) -> Result<DepthStream, ConnectorError> {
473        let mut stream = DepthStream {
474            feed: Feed::open(self, symbol, MarketDepth::Full).await?,
475            book: Book::new(symbol),
476        };
477        let step = stream.feed.first().await?;
478        stream.take(&step);
479        Ok(stream)
480    }
481}