barter_data/exchange/
subscription.rs

1use crate::{Identifier, subscription::Subscription};
2use barter_integration::subscription::SubscriptionId;
3use serde::Deserialize;
4
5/// Defines an exchange specific market and channel combination used by an exchange
6/// [`Connector`](super::Connector) to build the
7/// [`WsMessage`](barter_integration::protocol::websocket::WsMessage) subscription payloads to
8/// send to the exchange server.
9///
10/// ### Examples
11/// #### Binance OrderBooksL2
12/// ```json
13/// ExchangeSub {
14///     channel: BinanceChannel("@depth@100ms"),
15///     market: BinanceMarket("btcusdt"),
16/// }
17/// ```
18/// #### Kraken PublicTrades
19/// ```json
20/// ExchangeSub {
21///     channel: KrakenChannel("trade"),
22///     market: KrakenChannel("BTC/USDT")
23/// }
24/// ```
25#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize)]
26pub struct ExchangeSub<Channel, Market> {
27    /// Type that defines how to translate a Barter [`Subscription`] into an exchange specific
28    /// channel to be subscribed to.
29    ///
30    /// ### Examples
31    /// - [`BinanceChannel("@depth@100ms")`](super::binance::channel::BinanceChannel)
32    /// - [`KrakenChannel("trade")`](super::kraken::channel::KrakenChannel)
33    pub channel: Channel,
34
35    /// Type that defines how to translate a Barter [`Subscription`] into an exchange specific
36    /// market that can be subscribed to.
37    ///
38    /// ### Examples
39    /// - [`BinanceMarket("btcusdt")`](super::binance::market::BinanceMarket)
40    /// - [`KrakenMarket("BTC/USDT")`](super::kraken::market::KrakenMarket)
41    pub market: Market,
42}
43
44impl<Channel, Market> Identifier<SubscriptionId> for ExchangeSub<Channel, Market>
45where
46    Channel: AsRef<str>,
47    Market: AsRef<str>,
48{
49    fn id(&self) -> SubscriptionId {
50        SubscriptionId::from(format!(
51            "{}|{}",
52            self.channel.as_ref(),
53            self.market.as_ref()
54        ))
55    }
56}
57
58impl<Channel, Market> ExchangeSub<Channel, Market>
59where
60    Channel: AsRef<str>,
61    Market: AsRef<str>,
62{
63    /// Construct a new exchange specific [`Self`] with the Barter [`Subscription`] provided.
64    pub fn new<Exchange, Instrument, Kind>(sub: &Subscription<Exchange, Instrument, Kind>) -> Self
65    where
66        Subscription<Exchange, Instrument, Kind>: Identifier<Channel> + Identifier<Market>,
67    {
68        Self {
69            channel: sub.id(),
70            market: sub.id(),
71        }
72    }
73}
74
75impl<Channel, Market> From<(Channel, Market)> for ExchangeSub<Channel, Market>
76where
77    Channel: AsRef<str>,
78    Market: AsRef<str>,
79{
80    fn from((channel, market): (Channel, Market)) -> Self {
81        Self { channel, market }
82    }
83}