Skip to main content

ctrader_connector/open_api/
quotes.rs

1//! Stream of spot quotes of subscribed symbols.
2//!
3//! ```no_run
4//! use ctrader_connector::common::config::ConfigurationOpenApi;
5//! use ctrader_connector::common::ids::SymbolId;
6//! use ctrader_connector::open_api::client::OpenApiClient;
7//!
8//! # async fn run() -> Result<(), ctrader_connector::common::errors::ConnectorError> {
9//! let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
10//! client.authorise_application().await?;
11//! let account = client.accounts().await?[0].id;
12//! client.authorise_account(account).await?;
13//! let mut quotes = client.subscribe_quotes(account, &[SymbolId::new(1)?]).await?;
14//! for _ in 0..10 {
15//!     let quote = quotes.next().await?;
16//!     println!("{}: {:?} / {:?}", quote.symbol, quote.bid, quote.ask);
17//! }
18//! quotes.unsubscribe().await?;
19//! # Ok(())
20//! # }
21//! ```
22
23use std::collections::{BTreeMap, BTreeSet};
24
25use crate::common::decimals::{PRICE_SCALE, Price};
26use crate::common::errors::{ConnectorError, ValueError};
27use crate::common::ids::{AccountId, SymbolId};
28use crate::common::time::Timestamp;
29use crate::open_api::client::OpenApiClient;
30use crate::open_api::messages::ProtoOaSpotEvent;
31use crate::open_api::stream::{Feed, starts_replay};
32
33/// Side of a quote.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
35pub enum QuoteSide {
36    /// Price at which the market buys.
37    Bid,
38    /// Price at which the market sells.
39    Ask,
40}
41
42/// Converts a price of a spot, tick or bar message, an integer in 1/100000 of a unit.
43pub(crate) fn wire_price(raw: u64) -> Result<Price, ValueError> {
44    Price::from_wire(raw, PRICE_SCALE)
45}
46
47/// Latest known prices of a symbol.
48///
49/// The server sends only the side that changed; the other side keeps its last known value.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51#[non_exhaustive]
52pub struct Quote {
53    /// Symbol the prices belong to.
54    pub symbol: SymbolId,
55    /// Last known bid, absent until the server has sent one.
56    pub bid: Option<Price>,
57    /// Last known ask, absent until the server has sent one.
58    pub ask: Option<Price>,
59    /// Moment of the change, when the server reports it.
60    pub timestamp: Option<Timestamp>,
61}
62
63impl Quote {
64    /// Returns the last known price of the given side.
65    #[must_use]
66    pub const fn price(&self, side: QuoteSide) -> Option<Price> {
67        match side {
68            QuoteSide::Bid => self.bid,
69            QuoteSide::Ask => self.ask,
70        }
71    }
72
73    pub(crate) fn updated(
74        previous: Option<&Self>,
75        symbol: SymbolId,
76        spot: &ProtoOaSpotEvent,
77    ) -> Result<Self, ValueError> {
78        let bid = spot.bid.map(wire_price).transpose()?;
79        let ask = spot.ask.map(wire_price).transpose()?;
80        Ok(Self {
81            symbol,
82            bid: bid.or(previous.and_then(|quote| quote.bid)),
83            ask: ask.or(previous.and_then(|quote| quote.ask)),
84            timestamp: spot.timestamp.map(Timestamp::from_millis).transpose()?,
85        })
86    }
87}
88
89/// Quotes of the symbols of one account, in the order the server sends them.
90///
91/// The subscription behind the stream is restored after a reconnection, so the stream goes on
92/// without further calls. The last known prices are forgotten the moment the loss of the
93/// connection is reported, so a price from before the loss is never combined with one from
94/// after it.
95///
96/// A stream that is read too slowly loses events: the connection holds a limited number of
97/// them, set with
98/// [`ConnectionOptions::event_capacity`](crate::open_api::connection::ConnectionOptions::event_capacity).
99/// The loss is reported once by [`QuoteStream::next`] with [`ConnectorError::Lagged`] and the
100/// last known prices are forgotten, so a quote delivered afterwards carries only sides the
101/// server has sent since. The stream stays usable.
102#[derive(Debug)]
103pub struct QuoteStream {
104    client: OpenApiClient,
105    feed: Feed,
106    account: AccountId,
107    symbols: BTreeSet<SymbolId>,
108    last: BTreeMap<SymbolId, Quote>,
109}
110
111impl QuoteStream {
112    fn new(client: &OpenApiClient, account: AccountId, symbols: &[SymbolId]) -> Self {
113        Self {
114            client: client.clone(),
115            feed: Feed::new(client.connection(), account),
116            account,
117            symbols: symbols.iter().copied().collect(),
118            last: BTreeMap::new(),
119        }
120    }
121
122    /// Returns the account the quotes belong to.
123    #[must_use]
124    pub const fn account(&self) -> AccountId {
125        self.account
126    }
127
128    /// Returns the symbols the stream delivers quotes of, in ascending order.
129    pub fn symbols(&self) -> impl Iterator<Item = SymbolId> + '_ {
130        self.symbols.iter().copied()
131    }
132
133    /// Returns the latest quote the stream has delivered for the symbol.
134    #[must_use]
135    pub fn last(&self, symbol: SymbolId) -> Option<&Quote> {
136        self.last.get(&symbol)
137    }
138
139    /// Waits for the next quote of one of the symbols of the stream.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`ConnectorError::Closed`] when the connection is shut down,
144    /// [`ConnectorError::SessionEnded`] when the server ended the authorisation of the account,
145    /// [`ConnectorError::Lagged`] when events were dropped because the stream was read too
146    /// slowly, and [`ConnectorError::Value`] when the server sends a value out of range.
147    pub async fn next(&mut self) -> Result<Quote, ConnectorError> {
148        loop {
149            let event = match self.feed.next().await {
150                Ok(event) => event,
151                Err(error) => {
152                    if matches!(error, ConnectorError::Lagged { .. }) {
153                        self.last.clear();
154                    }
155                    return Err(error);
156                }
157            };
158            if starts_replay(&event) {
159                self.last.clear();
160                continue;
161            }
162            let Some(spot) = event.decode::<ProtoOaSpotEvent>() else {
163                continue;
164            };
165            if spot.ctid_trader_account_id != self.account.get()
166                || (spot.bid.is_none() && spot.ask.is_none())
167            {
168                continue;
169            }
170            let Some(symbol) = self
171                .symbols
172                .iter()
173                .copied()
174                .find(|symbol| symbol.get() == spot.symbol_id)
175            else {
176                continue;
177            };
178            let quote = Quote::updated(self.last.get(&symbol), symbol, &spot)?;
179            self.last.insert(symbol, quote);
180            return Ok(quote);
181        }
182    }
183
184    /// Ends the subscription to the spot prices of the symbols of the stream.
185    ///
186    /// # Errors
187    ///
188    /// Fails like [`OpenApiClient::unsubscribe_spots`].
189    pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
190        let symbols: Vec<SymbolId> = self.symbols.into_iter().collect();
191        self.client.unsubscribe_spots(self.account, &symbols).await
192    }
193}
194
195impl OpenApiClient {
196    /// Subscribes to the spot prices of the given symbols on an authorised account and returns
197    /// their quotes as a stream.
198    ///
199    /// The stream starts to listen before the subscription is requested, so the first prices
200    /// the server sends are not missed. The subscription is restored after a reconnection.
201    ///
202    /// # Errors
203    ///
204    /// Fails like [`OpenApiClient::subscribe_spots`].
205    pub async fn subscribe_quotes(
206        &self,
207        account: AccountId,
208        symbols: &[SymbolId],
209    ) -> Result<QuoteStream, ConnectorError> {
210        let stream = QuoteStream::new(self, account, symbols);
211        self.subscribe_spots(account, symbols).await?;
212        Ok(stream)
213    }
214
215    /// Returns the quotes of symbols that are subscribed already, without subscribing.
216    ///
217    /// The stream delivers quotes that arrive after this call and stays silent for symbols
218    /// without a subscription.
219    #[must_use]
220    pub fn quotes(&self, account: AccountId, symbols: &[SymbolId]) -> QuoteStream {
221        QuoteStream::new(self, account, symbols)
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::{Quote, QuoteSide};
228    use crate::common::errors::ValueError;
229    use crate::common::ids::SymbolId;
230    use crate::common::time::Timestamp;
231    use crate::open_api::messages::ProtoOaSpotEvent;
232
233    fn spot(bid: Option<u64>, ask: Option<u64>, timestamp: Option<i64>) -> ProtoOaSpotEvent {
234        ProtoOaSpotEvent {
235            ctid_trader_account_id: 7,
236            symbol_id: 1,
237            bid,
238            ask,
239            timestamp,
240            ..ProtoOaSpotEvent::default()
241        }
242    }
243
244    fn text(quote: &Quote, side: QuoteSide) -> Option<String> {
245        quote.price(side).map(|price| price.to_string())
246    }
247
248    #[test]
249    fn a_side_the_event_leaves_out_keeps_its_last_known_price() {
250        let symbol = SymbolId::new(1).expect("symbol id");
251        let first =
252            Quote::updated(None, symbol, &spot(Some(108_512), None, Some(1_000))).expect("quote");
253        assert_eq!(first.symbol, symbol);
254        assert_eq!(text(&first, QuoteSide::Bid).as_deref(), Some("1.08512"));
255        assert_eq!(first.ask, None);
256        assert_eq!(first.timestamp.map(Timestamp::as_millis), Some(1_000));
257        let second =
258            Quote::updated(Some(&first), symbol, &spot(None, Some(108_520), None)).expect("quote");
259        assert_eq!(text(&second, QuoteSide::Bid).as_deref(), Some("1.08512"));
260        assert_eq!(text(&second, QuoteSide::Ask).as_deref(), Some("1.08520"));
261        assert_eq!(second.timestamp, None);
262        let third =
263            Quote::updated(Some(&second), symbol, &spot(Some(108_500), None, None)).expect("quote");
264        assert_eq!(text(&third, QuoteSide::Bid).as_deref(), Some("1.08500"));
265        assert_eq!(text(&third, QuoteSide::Ask).as_deref(), Some("1.08520"));
266    }
267
268    #[test]
269    fn values_out_of_range_are_rejected() {
270        let symbol = SymbolId::new(1).expect("symbol id");
271        assert_eq!(
272            Quote::updated(None, symbol, &spot(Some(1), None, Some(-1))),
273            Err(ValueError::OutOfRange { kind: "timestamp" })
274        );
275        assert!(Quote::updated(None, symbol, &spot(Some(u64::MAX), None, None)).is_ok());
276    }
277}