Skip to main content

rustrade_data/exchange/binance/
channel.rs

1use super::{Binance, futures::BinanceFuturesUsdMarket, spot::BinanceSpot};
2use crate::{
3    Identifier,
4    subscription::{
5        Subscription,
6        book::{OrderBooksL1, OrderBooksL2},
7        candle::{CandleInterval, Candles},
8        liquidation::Liquidations,
9        trade::PublicTrades,
10    },
11};
12use serde::Serialize;
13
14/// Type that defines how to translate a Barter [`Subscription`] into a [`Binance`]
15/// channel to be subscribed to.
16///
17/// See docs: <https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams>
18/// See docs: <https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams>
19#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize)]
20pub struct BinanceChannel(pub &'static str);
21
22impl BinanceChannel {
23    /// [`Binance`] real-time trades channel name.
24    ///
25    /// See docs: <https://binance-docs.github.io/apidocs/spot/en/#trade-streams>
26    ///
27    /// Note:
28    /// For [`BinanceFuturesUsd`](super::futures::BinanceFuturesUsd) this real-time
29    /// stream is undocumented.
30    ///
31    /// See discord: <https://discord.com/channels/910237311332151317/923160222711812126/975712874582388757>
32    pub const TRADES: Self = Self("@trade");
33
34    /// [`Binance`] real-time OrderBook Level1 (top of books) channel name.
35    ///
36    /// See docs:<https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-book-ticker-streams>
37    /// See docs:<https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams>
38    pub const ORDER_BOOK_L1: Self = Self("@bookTicker");
39
40    /// [`Binance`] OrderBook Level2 channel name (100ms delta updates).
41    ///
42    /// See docs: <https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream>
43    /// See docs: <https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams>
44    pub const ORDER_BOOK_L2: Self = Self("@depth@100ms");
45
46    /// [`BinanceFuturesUsd`](super::futures::BinanceFuturesUsd) liquidation orders channel name.
47    ///
48    /// Routed on Binance's `/market` WS tier (see
49    /// [`BinanceFuturesUsdMarket`]).
50    ///
51    /// See docs: <https://binance-docs.github.io/apidocs/futures/en/#liquidation-order-streams>
52    pub const LIQUIDATIONS: Self = Self("@forceOrder");
53
54    /// [`BinanceSpot`] kline (candle) channel name for the given [`CandleInterval`],
55    /// e.g. `@kline_1m`.
56    ///
57    /// The interval suffix is exactly [`CandleInterval::as_str`] — pinned by the
58    /// `spot_candle_channel_suffix_matches_interval` drift-guard test.
59    ///
60    /// See docs: <https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-streams>
61    #[must_use]
62    pub const fn spot_candle(interval: CandleInterval) -> Self {
63        match interval {
64            CandleInterval::Sec1 => Self("@kline_1s"),
65            CandleInterval::Min1 => Self("@kline_1m"),
66            CandleInterval::Min3 => Self("@kline_3m"),
67            CandleInterval::Min5 => Self("@kline_5m"),
68            CandleInterval::Min15 => Self("@kline_15m"),
69            CandleInterval::Min30 => Self("@kline_30m"),
70            CandleInterval::Hour1 => Self("@kline_1h"),
71            CandleInterval::Hour2 => Self("@kline_2h"),
72            CandleInterval::Hour4 => Self("@kline_4h"),
73            CandleInterval::Hour6 => Self("@kline_6h"),
74            CandleInterval::Hour8 => Self("@kline_8h"),
75            CandleInterval::Hour12 => Self("@kline_12h"),
76            CandleInterval::Day1 => Self("@kline_1d"),
77            CandleInterval::Day3 => Self("@kline_3d"),
78            CandleInterval::Week1 => Self("@kline_1w"),
79            CandleInterval::Month1 => Self("@kline_1M"),
80        }
81    }
82
83    /// [`BinanceFuturesUsd`](super::futures::BinanceFuturesUsd) continuous-contract
84    /// (perpetual) kline channel name for the given [`CandleInterval`], e.g.
85    /// `_perpetual@continuousKline_1m`.
86    ///
87    /// Routed on Binance's `/market` WS tier (see
88    /// [`BinanceFuturesUsdMarket`]). The
89    /// `contractType` is fixed `PERPETUAL` because [`BinanceFuturesUsd`](super::futures::BinanceFuturesUsd)
90    /// is perpetual-only. The interval suffix is exactly [`CandleInterval::as_str`] —
91    /// pinned by the `futures_candle_channel_suffix_matches_interval` drift-guard test.
92    ///
93    /// See docs: <https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-streams>
94    #[must_use]
95    pub const fn futures_candle(interval: CandleInterval) -> Self {
96        match interval {
97            CandleInterval::Sec1 => Self("_perpetual@continuousKline_1s"),
98            CandleInterval::Min1 => Self("_perpetual@continuousKline_1m"),
99            CandleInterval::Min3 => Self("_perpetual@continuousKline_3m"),
100            CandleInterval::Min5 => Self("_perpetual@continuousKline_5m"),
101            CandleInterval::Min15 => Self("_perpetual@continuousKline_15m"),
102            CandleInterval::Min30 => Self("_perpetual@continuousKline_30m"),
103            CandleInterval::Hour1 => Self("_perpetual@continuousKline_1h"),
104            CandleInterval::Hour2 => Self("_perpetual@continuousKline_2h"),
105            CandleInterval::Hour4 => Self("_perpetual@continuousKline_4h"),
106            CandleInterval::Hour6 => Self("_perpetual@continuousKline_6h"),
107            CandleInterval::Hour8 => Self("_perpetual@continuousKline_8h"),
108            CandleInterval::Hour12 => Self("_perpetual@continuousKline_12h"),
109            CandleInterval::Day1 => Self("_perpetual@continuousKline_1d"),
110            CandleInterval::Day3 => Self("_perpetual@continuousKline_3d"),
111            CandleInterval::Week1 => Self("_perpetual@continuousKline_1w"),
112            CandleInterval::Month1 => Self("_perpetual@continuousKline_1M"),
113        }
114    }
115}
116
117impl<Server, Instrument> Identifier<BinanceChannel>
118    for Subscription<Binance<Server>, Instrument, PublicTrades>
119{
120    fn id(&self) -> BinanceChannel {
121        BinanceChannel::TRADES
122    }
123}
124
125impl<Server, Instrument> Identifier<BinanceChannel>
126    for Subscription<Binance<Server>, Instrument, OrderBooksL1>
127{
128    fn id(&self) -> BinanceChannel {
129        BinanceChannel::ORDER_BOOK_L1
130    }
131}
132
133impl<Server, Instrument> Identifier<BinanceChannel>
134    for Subscription<Binance<Server>, Instrument, OrderBooksL2>
135{
136    fn id(&self) -> BinanceChannel {
137        BinanceChannel::ORDER_BOOK_L2
138    }
139}
140
141// `@forceOrder` is a Binance `/market`-tier stream, so liquidations route through
142// `BinanceFuturesUsdMarket` (not `BinanceFuturesUsd`/`/public`). Restricting the impl to
143// the market-tier server type makes a `/public`-tier liquidation subscription a compile error.
144impl<Instrument> Identifier<BinanceChannel>
145    for Subscription<BinanceFuturesUsdMarket, Instrument, Liquidations>
146{
147    fn id(&self) -> BinanceChannel {
148        BinanceChannel::LIQUIDATIONS
149    }
150}
151
152impl<Instrument> Identifier<BinanceChannel> for Subscription<BinanceSpot, Instrument, Candles> {
153    fn id(&self) -> BinanceChannel {
154        BinanceChannel::spot_candle(self.kind.interval)
155    }
156}
157
158// Futures klines ride the `@continuousKline_` `/market`-tier stream, so the channel impl is
159// specialised to `BinanceFuturesUsdMarket` — routing a kline sub to `/public` is a compile error.
160impl<Instrument> Identifier<BinanceChannel>
161    for Subscription<BinanceFuturesUsdMarket, Instrument, Candles>
162{
163    fn id(&self) -> BinanceChannel {
164        BinanceChannel::futures_candle(self.kind.interval)
165    }
166}
167
168impl AsRef<str> for BinanceChannel {
169    fn as_ref(&self) -> &str {
170        self.0
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    /// The spot kline channel must be `@kline_<interval>` where `<interval>` is exactly
179    /// [`CandleInterval::as_str`] for every variant — otherwise the channel string would
180    /// drift from the live Binance stream name and silently fail to match frames.
181    #[test]
182    fn spot_candle_channel_suffix_matches_interval() {
183        for interval in CandleInterval::ALL {
184            let channel = BinanceChannel::spot_candle(interval).0;
185            assert_eq!(
186                channel,
187                format!("@kline_{}", interval.as_str()),
188                "spot channel drifted for {interval:?}"
189            );
190        }
191    }
192
193    /// The futures continuous kline channel must be `_perpetual@continuousKline_<interval>`
194    /// where `<interval>` is exactly [`CandleInterval::as_str`] for every variant.
195    #[test]
196    fn futures_candle_channel_suffix_matches_interval() {
197        for interval in CandleInterval::ALL {
198            let channel = BinanceChannel::futures_candle(interval).0;
199            assert_eq!(
200                channel,
201                format!("_perpetual@continuousKline_{}", interval.as_str()),
202                "futures channel drifted for {interval:?}"
203            );
204        }
205    }
206}