Skip to main content

rustrade_data/exchange/binance/
mod.rs

1use self::{
2    book::l1::BinanceOrderBookL1, channel::BinanceChannel, futures::BinanceFuturesUsd,
3    kline::BinanceKline, market::BinanceMarket, spot::BinanceSpot,
4    subscription::BinanceSubResponse, trade::BinanceTrade,
5};
6use crate::{
7    ExchangeWsStream, NoInitialSnapshots,
8    exchange::{Connector, ExchangeServer, ExchangeSub, StreamSelector},
9    instrument::InstrumentData,
10    subscriber::{WebSocketSubscriber, validator::WebSocketSubValidator},
11    subscription::{
12        Map,
13        book::OrderBooksL1,
14        candle::{CandleInterval, Candles},
15        trade::PublicTrades,
16    },
17    transformer::stateless::StatelessTransformer,
18};
19use rustrade_instrument::exchange::ExchangeId;
20use rustrade_integration::protocol::websocket::{WebSocketSerdeParser, WsMessage};
21use std::{fmt::Debug, marker::PhantomData};
22use url::Url;
23
24/// OrderBook types common to both [`BinanceSpot`] and
25/// [`BinanceFuturesUsd`].
26pub mod book;
27
28/// Defines the type that translates a Barter [`Subscription`](crate::subscription::Subscription)
29/// into an exchange [`Connector`] specific channel used for generating [`Connector::requests`].
30pub mod channel;
31
32/// Dedicated error type for the Binance historical klines REST client.
33mod error;
34pub use error::BinanceDataError;
35
36/// Historical klines (OHLCV candles) via Binance's public, unauthenticated REST
37/// endpoints — spot (`/api/v3/klines`) and futures continuous
38/// (`/fapi/v1/continuousKlines`).
39pub mod historical;
40pub use historical::BinanceHistoricalClient;
41
42/// [`ExchangeServer`] and [`StreamSelector`] implementations for
43/// [`BinanceFuturesUsd`].
44pub mod futures;
45
46/// Live kline (candle) wire models common to [`BinanceSpot`] (`@kline_`)
47/// and [`BinanceFuturesUsd`] (`@continuousKline_`).
48pub mod kline;
49
50/// Defines the type that translates a Barter [`Subscription`](crate::subscription::Subscription)
51/// into an exchange [`Connector`] specific market used for generating [`Connector::requests`].
52pub mod market;
53
54/// [`ExchangeServer`] and [`StreamSelector`] implementations for
55/// [`BinanceSpot`].
56pub mod spot;
57
58/// [`Subscription`](crate::subscription::Subscription) response type and response
59/// [`Validator`](rustrade_integration::Validator) common to both [`BinanceSpot`]
60/// and [`BinanceFuturesUsd`].
61pub mod subscription;
62
63/// Public trade types common to both [`BinanceSpot`] and
64/// [`BinanceFuturesUsd`].
65pub mod trade;
66
67/// Convenient type alias for a Binance [`ExchangeWsStream`] using [`WebSocketSerdeParser`].
68pub type BinanceWsStream<Transformer> = ExchangeWsStream<WebSocketSerdeParser, Transformer>;
69
70/// Whether Binance publishes klines at the given [`CandleInterval`].
71///
72/// [`CandleInterval`] is the venue-agnostic union of every resolution any connector
73/// supports, so it is a **superset** of Binance's kline menu: Binance's only
74/// sub-minute kline is `1s`, and it serves no `5s`/`15s`/`30s` stream (nor the
75/// matching REST `interval`, which 400s).
76///
77/// # Where this is applied
78///
79/// Only the **dynamic** builder gates on this:
80/// [`exchange_supports_instrument_kind_sub_kind`](crate::subscription::exchange_supports_instrument_kind_sub_kind)
81/// consults it for [`SubKind::Candles`](crate::subscription::SubKind::Candles), so an unsupported
82/// interval is rejected before a socket is opened.
83///
84/// The **typed** builder does not. Its validation goes through
85/// [`exchange_supports_instrument_kind`](crate::subscription::exchange_supports_instrument_kind),
86/// which never inspects the resolution, and
87/// [`BinanceChannel::spot_candle`](channel::BinanceChannel::spot_candle) /
88/// [`futures_candle`](channel::BinanceChannel::futures_candle) are infallible by the
89/// [`Identifier`](crate::Identifier) contract — so a typed `5s` subscription builds a well-formed
90/// `@kline_5s` channel name for a stream Binance does not publish, and is rejected only once
91/// Binance answers the SUBSCRIBE (surfaced by
92/// [`BinanceSubResponse`]'s
93/// [`Validator`](rustrade_integration::Validator)).
94///
95/// The failure is observable either way; call this yourself before a typed subscription if you
96/// want it before the socket rather than after.
97#[must_use]
98pub fn supports_candle_interval(interval: CandleInterval) -> bool {
99    match interval {
100        CandleInterval::Sec5 | CandleInterval::Sec15 | CandleInterval::Sec30 => false,
101        CandleInterval::Sec1
102        | CandleInterval::Min1
103        | CandleInterval::Min3
104        | CandleInterval::Min5
105        | CandleInterval::Min15
106        | CandleInterval::Min30
107        | CandleInterval::Hour1
108        | CandleInterval::Hour2
109        | CandleInterval::Hour4
110        | CandleInterval::Hour6
111        | CandleInterval::Hour8
112        | CandleInterval::Hour12
113        | CandleInterval::Day1
114        | CandleInterval::Day3
115        | CandleInterval::Week1
116        | CandleInterval::Month1 => true,
117    }
118}
119
120/// Generic [`Binance<Server>`](Binance) exchange.
121///
122/// ### Notes
123/// A `Server` [`ExchangeServer`] implementations exists for
124/// [`BinanceSpot`] and [`BinanceFuturesUsd`].
125#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
126pub struct Binance<Server> {
127    server: PhantomData<Server>,
128}
129
130impl<Server> Connector for Binance<Server>
131where
132    Server: ExchangeServer,
133{
134    const ID: ExchangeId = Server::ID;
135    type Channel = BinanceChannel;
136    type Market = BinanceMarket;
137    type Subscriber = WebSocketSubscriber;
138    type SubValidator = WebSocketSubValidator;
139    type SubResponse = BinanceSubResponse;
140
141    fn url() -> Result<Url, url::ParseError> {
142        Url::parse(Server::websocket_url())
143    }
144
145    fn requests(exchange_subs: Vec<ExchangeSub<Self::Channel, Self::Market>>) -> Vec<WsMessage> {
146        let stream_names = exchange_subs
147            .into_iter()
148            .map(|sub| {
149                // Note:
150                // Market must be lowercase when subscribing, but lowercase in general since
151                // Binance sends message with uppercase MARKET (eg/ BTCUSDT).
152                format!(
153                    "{}{}",
154                    sub.market.as_ref().to_lowercase(),
155                    sub.channel.as_ref()
156                )
157            })
158            .collect::<Vec<String>>();
159
160        vec![WsMessage::text(
161            serde_json::json!({
162                "method": "SUBSCRIBE",
163                "params": stream_names,
164                "id": 1
165            })
166            .to_string(),
167        )]
168    }
169
170    fn expected_responses<InstrumentKey>(_: &Map<InstrumentKey>) -> usize {
171        1
172    }
173}
174
175// `PublicTrades` and `OrderBooksL1` are implemented per-server (NOT blanket over
176// `Binance<Server>`) so they ride only the `/public`-tier server types — `BinanceSpot` (`/ws`)
177// and `BinanceFuturesUsd` (`/public/ws`). The market-tier `BinanceFuturesUsdMarket` (`/market/ws`)
178// deliberately has no such impl, making a trade/L1 subscription on that tier — which Binance
179// would silently dead-stream — a compile error instead. This mirrors `OrderBooksL2`, which is
180// already per-server.
181impl<Instrument> StreamSelector<Instrument, PublicTrades> for BinanceSpot
182where
183    Instrument: InstrumentData,
184{
185    type SnapFetcher = NoInitialSnapshots;
186    type Stream =
187        BinanceWsStream<StatelessTransformer<Self, Instrument::Key, PublicTrades, BinanceTrade>>;
188}
189
190impl<Instrument> StreamSelector<Instrument, PublicTrades> for BinanceFuturesUsd
191where
192    Instrument: InstrumentData,
193{
194    type SnapFetcher = NoInitialSnapshots;
195    type Stream =
196        BinanceWsStream<StatelessTransformer<Self, Instrument::Key, PublicTrades, BinanceTrade>>;
197}
198
199impl<Instrument> StreamSelector<Instrument, OrderBooksL1> for BinanceSpot
200where
201    Instrument: InstrumentData,
202{
203    type SnapFetcher = NoInitialSnapshots;
204    type Stream = BinanceWsStream<
205        StatelessTransformer<Self, Instrument::Key, OrderBooksL1, BinanceOrderBookL1>,
206    >;
207}
208
209impl<Instrument> StreamSelector<Instrument, OrderBooksL1> for BinanceFuturesUsd
210where
211    Instrument: InstrumentData,
212{
213    type SnapFetcher = NoInitialSnapshots;
214    type Stream = BinanceWsStream<
215        StatelessTransformer<Self, Instrument::Key, OrderBooksL1, BinanceOrderBookL1>,
216    >;
217}
218
219// Live spot klines: `@kline_<interval>` on `BinanceSpot`'s `/ws` tier.
220impl<Instrument> StreamSelector<Instrument, Candles> for BinanceSpot
221where
222    Instrument: InstrumentData,
223{
224    type SnapFetcher = NoInitialSnapshots;
225    type Stream =
226        BinanceWsStream<StatelessTransformer<Self, Instrument::Key, Candles, BinanceKline>>;
227}
228
229impl<'de, Server> serde::Deserialize<'de> for Binance<Server>
230where
231    Server: ExchangeServer,
232{
233    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
234    where
235        D: serde::de::Deserializer<'de>,
236    {
237        let input = <String as serde::Deserialize>::deserialize(deserializer)?;
238
239        if input.as_str() == Self::ID.as_str() {
240            Ok(Self::default())
241        } else {
242            Err(serde::de::Error::invalid_value(
243                serde::de::Unexpected::Str(input.as_str()),
244                &Self::ID.as_str(),
245            ))
246        }
247    }
248}
249
250impl<Server> serde::Serialize for Binance<Server>
251where
252    Server: ExchangeServer,
253{
254    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
255    where
256        S: serde::ser::Serializer,
257    {
258        serializer.serialize_str(Self::ID.as_str())
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    /// `CandleInterval` is a union across venues, so this guard must be re-reviewed
267    /// whenever a variant is added — the exhaustive `match` inside
268    /// `supports_candle_interval` is the compile gate, and this test pins the answer.
269    #[test]
270    fn supports_candle_interval_rejects_only_the_sub_minute_intervals_binance_lacks() {
271        for interval in CandleInterval::ALL {
272            let expected = !matches!(
273                interval,
274                CandleInterval::Sec5 | CandleInterval::Sec15 | CandleInterval::Sec30
275            );
276            assert_eq!(
277                supports_candle_interval(interval),
278                expected,
279                "interval {interval}"
280            );
281        }
282    }
283}