Skip to main content

rustrade_data/exchange/
mod.rs

1use self::subscription::ExchangeSub;
2use crate::{
3    MarketStream, SnapshotFetcher,
4    instrument::InstrumentData,
5    subscriber::{Subscriber, validator::SubscriptionValidator},
6    subscription::{Map, SubscriptionKind},
7};
8use rustrade_instrument::exchange::ExchangeId;
9use rustrade_integration::{Validator, error::SocketError, protocol::websocket::WsMessage};
10use serde::{Deserialize, Serialize, de::DeserializeOwned};
11use std::{fmt::Debug, time::Duration};
12use url::Url;
13
14/// `BinanceSpot` & `BinanceFuturesUsd` [`Connector`] and [`StreamSelector`] implementations.
15pub mod binance;
16
17/// `Bitfinex` [`Connector`] and [`StreamSelector`] implementations.
18pub mod bitfinex;
19
20/// `Bitmex [`Connector`] and [`StreamSelector`] implementations.
21pub mod bitmex;
22
23/// `Bybit` ['Connector'] and ['StreamSelector'] implementation
24pub mod bybit;
25
26/// `Coinbase` [`Connector`] and [`StreamSelector`] implementations.
27pub mod coinbase;
28
29/// `GateioSpot`, `GateioFuturesUsd` & `GateioFuturesBtc` [`Connector`] and [`StreamSelector`]
30/// implementations.
31pub mod gateio;
32
33/// `Kraken` [`Connector`] and [`StreamSelector`] implementations.
34pub mod kraken;
35
36/// `Okx` [`Connector`] and [`StreamSelector`] implementations.
37pub mod okx;
38
39/// `Hyperliquid` and `HyperliquidSpot` `Connector` and `StreamSelector` implementations (behind `hyperliquid` feature).
40#[cfg(feature = "hyperliquid")]
41pub mod hyperliquid;
42
43/// `Ibkr` market data stream (behind `ibkr` feature).
44#[cfg(feature = "ibkr")]
45pub mod ibkr;
46
47/// Defines the generic [`ExchangeSub`] containing a market and channel combination used by an
48/// exchange [`Connector`] to build [`WsMessage`] subscription payloads.
49pub mod subscription;
50
51/// Default [`Duration`] the [`Connector::SubValidator`] will wait to receive all success responses to actioned
52/// `Subscription` requests.
53pub const DEFAULT_SUBSCRIPTION_TIMEOUT: Duration = Duration::from_secs(10);
54
55/// Defines the [`MarketStream`] kind associated with an exchange
56/// `Subscription` [`SubscriptionKind`].
57///
58/// ### Notes
59/// Must be implemented by an exchange [`Connector`] if it supports a specific
60/// [`SubscriptionKind`].
61pub trait StreamSelector<Instrument, Kind>
62where
63    Self: Connector,
64    Instrument: InstrumentData,
65    Kind: SubscriptionKind,
66{
67    type SnapFetcher: SnapshotFetcher<Self, Kind>;
68    type Stream: MarketStream<Self, Instrument, Kind>;
69}
70
71/// Primary exchange abstraction. Defines how to translate Barter types into exchange specific
72/// types, as well as connecting, subscribing, and interacting with the exchange server.
73///
74/// ### Notes
75/// This must be implemented for a new exchange integration!
76pub trait Connector
77where
78    Self: Clone + Default + Debug + for<'de> Deserialize<'de> + Serialize + Sized,
79{
80    /// Unique identifier for the exchange server being connected with.
81    const ID: ExchangeId;
82
83    /// Type that defines how to translate a Barter `Subscription` into an exchange specific
84    /// channel to be subscribed to.
85    ///
86    /// ### Examples
87    /// - [`BinanceChannel("@depth@100ms")`](binance::channel::BinanceChannel)
88    /// - [`KrakenChannel("trade")`](kraken::channel::KrakenChannel)
89    type Channel: AsRef<str>;
90
91    /// Type that defines how to translate a Barter
92    /// `Subscription` into an exchange specific market that
93    /// can be subscribed to.
94    ///
95    /// ### Examples
96    /// - [`BinanceMarket("btcusdt")`](binance::market::BinanceMarket)
97    /// - [`KrakenMarket("BTC/USDT")`](kraken::market::KrakenMarket)
98    type Market: AsRef<str>;
99
100    /// [`Subscriber`] type that establishes a connection with the exchange server, and actions
101    /// `Subscription`s over the socket.
102    type Subscriber: Subscriber;
103
104    /// [`SubscriptionValidator`] type that listens to responses from the exchange server and
105    /// validates if the actioned `Subscription`s were
106    /// successful.
107    type SubValidator: SubscriptionValidator;
108
109    /// Deserialisable type that the [`Self::SubValidator`] expects to receive from the exchange server in
110    /// response to the `Subscription` [`Self::requests`]
111    /// sent over the [`WebSocket`](rustrade_integration::protocol::websocket::WebSocket). Implements
112    /// [`Validator`] in order to determine if [`Self`]
113    /// communicates a successful `Subscription` outcome.
114    type SubResponse: Validator<Error = SocketError> + Debug + DeserializeOwned;
115
116    /// Base [`Url`] of the exchange server being connected with.
117    fn url() -> Result<Url, url::ParseError>;
118
119    /// Defines [`PingInterval`] of custom application-level
120    /// [`WebSocket`](rustrade_integration::protocol::websocket::WebSocket) pings for the exchange
121    /// server being connected with.
122    ///
123    /// Defaults to `None`, meaning that no custom pings are sent.
124    fn ping_interval() -> Option<PingInterval> {
125        None
126    }
127
128    /// Defines how to translate a collection of [`ExchangeSub`]s into the [`WsMessage`]
129    /// subscription payloads sent to the exchange server.
130    fn requests(exchange_subs: Vec<ExchangeSub<Self::Channel, Self::Market>>) -> Vec<WsMessage>;
131
132    /// Number of `Subscription` responses expected from the
133    /// exchange server in responses to the requests send. Used to validate all
134    /// `Subscription`s were accepted.
135    fn expected_responses<InstrumentKey>(map: &Map<InstrumentKey>) -> usize {
136        map.0.len()
137    }
138
139    /// Expected [`Duration`] the [`SubscriptionValidator`] will wait to receive all success
140    /// responses to actioned `Subscription` requests.
141    fn subscription_timeout() -> Duration {
142        DEFAULT_SUBSCRIPTION_TIMEOUT
143    }
144}
145
146/// Used when an exchange has servers different
147/// [`InstrumentKind`](rustrade_instrument::instrument::kind::InstrumentKind) market data on distinct servers,
148/// allowing all the [`Connector`] logic to be identical apart from what this trait provides.
149///
150/// ### Examples
151/// - [`BinanceServerSpot`](binance::spot::BinanceServerSpot)
152/// - [`BinanceServerFuturesUsd`](binance::futures::BinanceServerFuturesUsd)
153pub trait ExchangeServer: Default + Debug + Clone + Send {
154    const ID: ExchangeId;
155    fn websocket_url() -> &'static str;
156}
157
158/// Defines the frequency and construction function for custom
159/// [`WebSocket`](rustrade_integration::protocol::websocket::WebSocket) pings - used for exchanges
160/// that require additional application-level pings.
161#[derive(Debug)]
162pub struct PingInterval {
163    pub interval: tokio::time::Interval,
164    pub ping: fn() -> WsMessage,
165}