ctrader_connector/open_api/
quotes.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
35pub enum QuoteSide {
36 Bid,
38 Ask,
40}
41
42pub(crate) fn wire_price(raw: u64) -> Result<Price, ValueError> {
44 Price::from_wire(raw, PRICE_SCALE)
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51#[non_exhaustive]
52pub struct Quote {
53 pub symbol: SymbolId,
55 pub bid: Option<Price>,
57 pub ask: Option<Price>,
59 pub timestamp: Option<Timestamp>,
61}
62
63impl Quote {
64 #[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#[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 #[must_use]
124 pub const fn account(&self) -> AccountId {
125 self.account
126 }
127
128 pub fn symbols(&self) -> impl Iterator<Item = SymbolId> + '_ {
130 self.symbols.iter().copied()
131 }
132
133 #[must_use]
135 pub fn last(&self, symbol: SymbolId) -> Option<&Quote> {
136 self.last.get(&symbol)
137 }
138
139 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 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 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 #[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}