exc_types/
book.rs

1use std::fmt;
2
3use crate::Str;
4use futures::stream::BoxStream;
5use indicator::{Tick, TickValue, Tickable};
6use rust_decimal::Decimal;
7use serde::{Deserialize, Serialize};
8use time::OffsetDateTime;
9
10use exc_service::{ExchangeError, Request};
11
12/// Best bid and ask Stream.
13pub type BidAskStream = BoxStream<'static, Result<BidAsk, ExchangeError>>;
14
15/// Current best bid and best ask.
16#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
17pub struct BidAsk {
18    /// Timestamp.
19    #[serde(with = "time::serde::rfc3339")]
20    pub ts: OffsetDateTime,
21    /// Current best bid (price, size).
22    pub bid: Option<(Decimal, Decimal)>,
23    /// Current best ask (price, size).
24    pub ask: Option<(Decimal, Decimal)>,
25}
26
27impl fmt::Display for BidAsk {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match (self.bid, self.ask) {
30            (Some((bid, bid_size)), Some((ask, ask_size))) => write!(
31                f,
32                "ts={}, bid=({bid}, {bid_size}), ask=({ask}, {ask_size})",
33                self.ts
34            ),
35            (Some((bid, bid_size)), None) => {
36                write!(f, "ts={}, bid=({bid}, {bid_size}), ask=null", self.ts)
37            }
38            (None, Some((ask, ask_size))) => {
39                write!(f, "ts={}, bid=null, ask=({ask}, {ask_size})", self.ts)
40            }
41            _ => write!(f, "ts={}, bid=null, ask=null", self.ts),
42        }
43    }
44}
45
46impl Tickable for BidAsk {
47    type Value = Self;
48
49    fn tick(&self) -> Tick {
50        Tick::new(self.ts)
51    }
52
53    fn value(&self) -> &Self::Value {
54        self
55    }
56
57    fn into_tick_value(self) -> TickValue<Self::Value> {
58        TickValue::new(self.ts, self)
59    }
60}
61
62/// Subscribe current best bid and ask.
63#[derive(Debug, Clone)]
64pub struct SubscribeBidAsk {
65    /// Instrument.
66    pub instrument: Str,
67}
68
69impl SubscribeBidAsk {
70    /// Create a new [`SubscribeBidAsk`] request.
71    pub fn new(inst: impl AsRef<str>) -> Self {
72        Self {
73            instrument: Str::new(inst),
74        }
75    }
76}
77
78impl Request for SubscribeBidAsk {
79    type Response = BidAskStream;
80}