1use std::collections::{BTreeMap, BTreeSet};
25use std::fmt;
26
27use crate::common::decimals::{Price, Volume};
28use crate::common::errors::{ConnectorError, ValueError};
29use crate::common::ids::{AccountId, SymbolId};
30use crate::open_api::client::OpenApiClient;
31use crate::open_api::connection::{ReplayKey, ReplayStage};
32use crate::open_api::messages::{
33 ProtoOaDepthEvent, ProtoOaDepthQuote, ProtoOaSubscribeDepthQuotesReq,
34 ProtoOaUnsubscribeDepthQuotesReq,
35};
36use crate::open_api::quotes::{QuoteSide, wire_price};
37use crate::open_api::stream::{Feed, starts_replay};
38
39const DEPTH_SIZE: &str = "depth size";
40const DEPTH_SIDE: &str = "depth quote side";
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
44pub struct DepthQuoteId(u64);
45
46impl DepthQuoteId {
47 #[must_use]
49 pub const fn new(id: u64) -> Self {
50 Self(id)
51 }
52
53 #[must_use]
55 pub const fn get(self) -> u64 {
56 self.0
57 }
58}
59
60impl fmt::Display for DepthQuoteId {
61 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62 self.0.fmt(formatter)
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68#[non_exhaustive]
69pub struct DepthQuote {
70 pub id: DepthQuoteId,
72 pub side: QuoteSide,
74 pub price: Price,
76 pub size: Volume,
78}
79
80impl TryFrom<ProtoOaDepthQuote> for DepthQuote {
81 type Error = ValueError;
82
83 fn try_from(quote: ProtoOaDepthQuote) -> Result<Self, Self::Error> {
84 let (side, raw) = match (quote.bid, quote.ask) {
85 (Some(bid), None) => (QuoteSide::Bid, bid),
86 (None, Some(ask)) => (QuoteSide::Ask, ask),
87 _ => return Err(ValueError::OutOfRange { kind: DEPTH_SIDE }),
88 };
89 let volume =
90 i64::try_from(quote.size).map_err(|_| ValueError::OutOfRange { kind: DEPTH_SIZE })?;
91 Ok(Self {
92 id: DepthQuoteId(quote.id),
93 side,
94 price: wire_price(raw)?,
95 size: Volume::from_wire(volume)?,
96 })
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Hash)]
102#[non_exhaustive]
103pub struct DepthUpdate {
104 pub symbol: SymbolId,
106 pub new_quotes: Vec<DepthQuote>,
108 pub deleted_quotes: Vec<DepthQuoteId>,
110}
111
112impl DepthUpdate {
113 fn parse(symbol: SymbolId, event: ProtoOaDepthEvent) -> Result<Self, ValueError> {
114 Ok(Self {
115 symbol,
116 new_quotes: event
117 .new_quotes
118 .into_iter()
119 .map(DepthQuote::try_from)
120 .collect::<Result<_, _>>()?,
121 deleted_quotes: event.deleted_quotes.into_iter().map(DepthQuoteId).collect(),
122 })
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Default)]
128pub struct DepthBook {
129 quotes: BTreeMap<DepthQuoteId, DepthQuote>,
130}
131
132impl DepthBook {
133 #[must_use]
135 pub fn new() -> Self {
136 Self::default()
137 }
138
139 pub fn apply(&mut self, update: &DepthUpdate) {
141 for id in &update.deleted_quotes {
142 self.quotes.remove(id);
143 }
144 for quote in &update.new_quotes {
145 self.quotes.insert(quote.id, *quote);
146 }
147 }
148
149 fn side(&self, side: QuoteSide) -> Vec<DepthQuote> {
150 let mut quotes: Vec<DepthQuote> = self
151 .quotes
152 .values()
153 .filter(|quote| quote.side == side)
154 .copied()
155 .collect();
156 quotes.sort_by_key(|quote| (quote.price, quote.id));
157 quotes
158 }
159
160 #[must_use]
162 pub fn bids(&self) -> Vec<DepthQuote> {
163 let mut bids = self.side(QuoteSide::Bid);
164 bids.reverse();
165 bids
166 }
167
168 #[must_use]
170 pub fn asks(&self) -> Vec<DepthQuote> {
171 self.side(QuoteSide::Ask)
172 }
173
174 fn prices(&self, side: QuoteSide) -> impl Iterator<Item = Price> + '_ {
175 self.quotes
176 .values()
177 .filter(move |quote| quote.side == side)
178 .map(|quote| quote.price)
179 }
180
181 #[must_use]
183 pub fn best_bid(&self) -> Option<Price> {
184 self.prices(QuoteSide::Bid).max()
185 }
186
187 #[must_use]
189 pub fn best_ask(&self) -> Option<Price> {
190 self.prices(QuoteSide::Ask).min()
191 }
192
193 #[must_use]
195 pub fn len(&self) -> usize {
196 self.quotes.len()
197 }
198
199 #[must_use]
201 pub fn is_empty(&self) -> bool {
202 self.quotes.is_empty()
203 }
204}
205
206fn depth_key(account: AccountId, symbol: SymbolId) -> ReplayKey {
207 ReplayKey::new(
208 ReplayStage::Subscription,
209 format!("depth/{account}/{symbol}"),
210 )
211}
212
213#[derive(Debug)]
229pub struct DepthStream {
230 client: OpenApiClient,
231 feed: Feed,
232 account: AccountId,
233 symbols: BTreeSet<SymbolId>,
234 books: BTreeMap<SymbolId, DepthBook>,
235 stale: bool,
236}
237
238impl DepthStream {
239 #[must_use]
241 pub const fn account(&self) -> AccountId {
242 self.account
243 }
244
245 pub fn symbols(&self) -> impl Iterator<Item = SymbolId> + '_ {
247 self.symbols.iter().copied()
248 }
249
250 #[must_use]
256 pub fn book(&self, symbol: SymbolId) -> Option<&DepthBook> {
257 self.books.get(&symbol)
258 }
259
260 #[must_use]
263 pub const fn is_stale(&self) -> bool {
264 self.stale
265 }
266
267 pub async fn resync(&mut self) -> Result<(), ConnectorError> {
279 let symbols: Vec<SymbolId> = self.symbols.iter().copied().collect();
280 self.stale = true;
281 self.books.clear();
282 self.client
283 .unsubscribe_depth(self.account, &symbols)
284 .await?;
285 self.feed = Feed::new(self.client.connection(), self.account);
286 self.client.request_depth(self.account, &symbols).await?;
287 self.stale = false;
288 Ok(())
289 }
290
291 pub async fn next(&mut self) -> Result<DepthUpdate, ConnectorError> {
301 loop {
302 let event = match self.feed.next().await {
303 Ok(event) => event,
304 Err(error) => {
305 if matches!(error, ConnectorError::Lagged { .. }) {
306 self.books.clear();
307 self.stale = true;
308 }
309 return Err(error);
310 }
311 };
312 if starts_replay(&event) {
313 self.books.clear();
314 self.stale = false;
315 continue;
316 }
317 let Some(depth) = event.decode::<ProtoOaDepthEvent>() else {
318 continue;
319 };
320 if depth.ctid_trader_account_id != self.account.get() {
321 continue;
322 }
323 let Some(symbol) = self
324 .symbols
325 .iter()
326 .copied()
327 .find(|symbol| u64::try_from(symbol.get()) == Ok(depth.symbol_id))
328 else {
329 continue;
330 };
331 let update = DepthUpdate::parse(symbol, depth)?;
332 if !self.stale {
333 self.books.entry(symbol).or_default().apply(&update);
334 }
335 return Ok(update);
336 }
337 }
338
339 pub async fn unsubscribe(self) -> Result<(), ConnectorError> {
345 let symbols: Vec<SymbolId> = self.symbols.into_iter().collect();
346 self.client.unsubscribe_depth(self.account, &symbols).await
347 }
348}
349
350impl OpenApiClient {
351 pub async fn subscribe_depth(
363 &self,
364 account: AccountId,
365 symbols: &[SymbolId],
366 ) -> Result<DepthStream, ConnectorError> {
367 let stream = DepthStream {
368 client: self.clone(),
369 feed: Feed::new(self.connection(), account),
370 account,
371 symbols: symbols.iter().copied().collect(),
372 books: BTreeMap::new(),
373 stale: false,
374 };
375 self.request_depth(account, symbols).await?;
376 Ok(stream)
377 }
378
379 async fn request_depth(
380 &self,
381 account: AccountId,
382 symbols: &[SymbolId],
383 ) -> Result<(), ConnectorError> {
384 let request = |symbols: &[SymbolId]| ProtoOaSubscribeDepthQuotesReq {
385 payload_type: None,
386 ctid_trader_account_id: account.get(),
387 symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
388 };
389 self.connection().request(&request(symbols)).await?;
390 for symbol in symbols {
391 self.connection()
392 .register_replay(depth_key(account, *symbol), &request(&[*symbol]))
393 .await?;
394 }
395 Ok(())
396 }
397
398 pub async fn unsubscribe_depth(
405 &self,
406 account: AccountId,
407 symbols: &[SymbolId],
408 ) -> Result<(), ConnectorError> {
409 let request = ProtoOaUnsubscribeDepthQuotesReq {
410 payload_type: None,
411 ctid_trader_account_id: account.get(),
412 symbol_id: symbols.iter().map(|symbol| symbol.get()).collect(),
413 };
414 self.connection().request(&request).await?;
415 for symbol in symbols {
416 self.connection()
417 .remove_replay(depth_key(account, *symbol))
418 .await?;
419 }
420 Ok(())
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::{DepthBook, DepthQuote, DepthQuoteId, DepthUpdate};
427 use crate::common::errors::ValueError;
428 use crate::common::ids::SymbolId;
429 use crate::open_api::messages::{ProtoOaDepthEvent, ProtoOaDepthQuote};
430 use crate::open_api::quotes::QuoteSide;
431
432 fn bid(id: u64, price: u64, size: u64) -> ProtoOaDepthQuote {
433 ProtoOaDepthQuote {
434 id,
435 size,
436 bid: Some(price),
437 ask: None,
438 }
439 }
440
441 fn ask(id: u64, price: u64, size: u64) -> ProtoOaDepthQuote {
442 ProtoOaDepthQuote {
443 id,
444 size,
445 bid: None,
446 ask: Some(price),
447 }
448 }
449
450 fn update(new: Vec<ProtoOaDepthQuote>, deleted: Vec<u64>) -> DepthUpdate {
451 let event = ProtoOaDepthEvent {
452 payload_type: None,
453 ctid_trader_account_id: 7,
454 symbol_id: 1,
455 new_quotes: new,
456 deleted_quotes: deleted,
457 };
458 DepthUpdate::parse(SymbolId::new(1).expect("symbol id"), event).expect("update")
459 }
460
461 #[test]
462 fn depth_quote_is_parsed_from_the_wire() {
463 let quote = DepthQuote::try_from(bid(3, 108_512, 150_000)).expect("quote");
464 assert_eq!(quote.id, DepthQuoteId::new(3));
465 assert_eq!(quote.id.get(), 3);
466 assert_eq!(quote.id.to_string(), "3");
467 assert_eq!(quote.side, QuoteSide::Bid);
468 assert_eq!(quote.price.to_string(), "1.08512");
469 assert_eq!(quote.size.to_string(), "1500.00");
470 let quote = DepthQuote::try_from(ask(4, 108_520, 0)).expect("quote");
471 assert_eq!(quote.side, QuoteSide::Ask);
472 assert_eq!(quote.size.to_string(), "0.00");
473 }
474
475 #[test]
476 fn depth_quotes_without_one_side_or_with_a_huge_size_are_rejected() {
477 let side = Err(ValueError::OutOfRange {
478 kind: "depth quote side",
479 });
480 let neither = ProtoOaDepthQuote {
481 id: 1,
482 size: 1,
483 bid: None,
484 ask: None,
485 };
486 assert_eq!(DepthQuote::try_from(neither), side);
487 let both = ProtoOaDepthQuote {
488 ask: Some(2),
489 ..bid(1, 1, 1)
490 };
491 assert_eq!(DepthQuote::try_from(both), side);
492 assert_eq!(
493 DepthQuote::try_from(bid(1, 1, u64::MAX)),
494 Err(ValueError::OutOfRange { kind: "depth size" })
495 );
496 }
497
498 #[test]
499 fn book_applies_new_replaced_and_deleted_entries() {
500 let mut book = DepthBook::new();
501 assert!(book.is_empty());
502 assert_eq!(book.best_bid(), None);
503 assert_eq!(book.best_ask(), None);
504 book.apply(&update(
505 vec![
506 bid(1, 100, 10),
507 bid(2, 99, 20),
508 ask(3, 102, 30),
509 ask(4, 103, 40),
510 ],
511 Vec::new(),
512 ));
513 assert_eq!(book.len(), 4);
514 let ids = |quotes: Vec<DepthQuote>| quotes.iter().map(|q| q.id.get()).collect::<Vec<_>>();
515 assert_eq!(ids(book.bids()), vec![1, 2]);
516 assert_eq!(ids(book.asks()), vec![3, 4]);
517 assert_eq!(
518 book.best_bid().map(|p| p.to_string()).as_deref(),
519 Some("0.00100")
520 );
521 assert_eq!(
522 book.best_ask().map(|p| p.to_string()).as_deref(),
523 Some("0.00102")
524 );
525 book.apply(&update(vec![bid(2, 101, 5), ask(5, 102, 1)], vec![3, 9]));
526 assert_eq!(ids(book.bids()), vec![2, 1]);
527 assert_eq!(ids(book.asks()), vec![5, 4]);
528 assert_eq!(
529 book.best_bid().map(|p| p.to_string()).as_deref(),
530 Some("0.00101")
531 );
532 book.apply(&update(Vec::new(), vec![1, 2, 4, 5]));
533 assert!(book.is_empty());
534 }
535}