1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use crate::client::{de_str_to_f64, ClientConfig};
use crate::connection::ConnectionHandler;
use crate::error::ClientError;
use crate::model::BuyerType;
use crate::{connect, Candle, ExchangeClient, Identifier, StreamIdentifier, Subscription, Trade};
use async_trait::async_trait;
use chrono::{DateTime, NaiveDateTime, Utc};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;

/// [ExchangeClient] implementation for Binance.
pub struct Binance {
    /// [Subscription] request channel transmitter. Transmits a tuple of [Subscription] and a data
    /// channel transmitter. This data channel transmitter is used to send messages relating the
    /// [Subscription] back to this Binance client from the [ConnectionHandler].
    subscription_tx: mpsc::Sender<(BinanceSub, mpsc::UnboundedSender<BinanceMessage>)>,
}

#[async_trait]
impl ExchangeClient for Binance {
    async fn consume_trades(
        &mut self,
        symbol: String,
    ) -> Result<UnboundedReceiverStream<Trade>, ClientError> {
        // Construct trades channel that ConnectionHandler will distribute trade stream data on
        let (binance_trade_tx, mut binance_trade_rx) = mpsc::unbounded_channel();

        // Construct Subscription for the ConnectionHandler to action
        let trades_subscription = BinanceSub::new(String::from(Binance::TRADE_STREAM), symbol);

        // Subscribe by passing a tuple of (Subscription, trade_tx) to the ConnectionHandler
        if let Err(err) = self
            .subscription_tx
            .send((trades_subscription, binance_trade_tx))
            .await
        {
            error!("Subscription request receiver has dropped by the ConnectionHandler - closing transmitter: {:?}", err);
            return Err(ClientError::SendFailure);
        }

        // Construct channel to distribute normalised Trade data to downstream consumers
        let (trade_tx, trade_rx) = mpsc::unbounded_channel();

        tokio::spawn(async move {
            while let Some(binance_message) = binance_trade_rx.recv().await {
                match binance_message {
                    BinanceMessage::Trade(binance_trade) => {
                        if trade_tx.send(Trade::from(binance_trade)).is_err() {
                            info!("Receiver for Binance Trades has been dropped - closing stream.");
                            return;
                        }
                    }
                    _ => warn!("consume_trades() received BinanceMessage that was not a Trade"),
                }
            }
        });

        // Return normalised Trade stream to consumer
        Ok(UnboundedReceiverStream::new(trade_rx))
    }

    async fn consume_candles(
        &mut self,
        symbol: String,
        interval: &str,
    ) -> Result<UnboundedReceiverStream<Candle>, ClientError> {
        // Construct trades channel that ConnectionHandler will distribute trade stream data on
        let (binance_candle_tx, mut binance_candle_rx) = mpsc::unbounded_channel();

        // Construct Subscription for the ConnectionHandler to action
        let candles_subscription = BinanceSub::new(
            Binance::CANDLE_STREAM.replace("<interval>", interval),
            symbol,
        );

        // Subscribe by passing a tuple of (Subscription, trade_tx) to the ConnectionHandler
        if let Err(err) = self
            .subscription_tx
            .send((candles_subscription, binance_candle_tx))
            .await
        {
            error!("Subscription request receiver has dropped by the ConnectionHandler - closing transmitter: {:?}", err);
            return Err(ClientError::SendFailure);
        }

        // Construct channel to distribute normalised Trade data to downstream consumers
        let (candle_tx, candle_rx) = mpsc::unbounded_channel();

        // Async task to consume from binance_trades_tx and produce normalised Trades via the trades_tx
        tokio::spawn(async move {
            while let Some(binance_message) = binance_candle_rx.recv().await {
                match binance_message {
                    BinanceMessage::Kline(binance_kline) => {
                        if binance_kline.data.kline_closed == false {
                            continue;
                        }

                        if candle_tx.send(Candle::from(binance_kline)).is_err() {
                            info!(
                                "Receiver for Binance Candles has been dropped - closing stream."
                            );
                            return;
                        }
                    }
                    _ => warn!("consume_candles() received BinanceMessage that was not a Candle"),
                }
            }
        });

        // Return normalised Trade stream to consumer
        Ok(UnboundedReceiverStream::new(candle_rx))
    }
}

impl Binance {
    const BASE_URI: &'static str = "wss://stream.binance.com:9443/ws";
    const TRADE_STREAM: &'static str = "@aggTrade";
    const CANDLE_STREAM: &'static str = "@kline_<interval>";

    /// Constructs a new [Binance] [ExchangeClient] instance using the [ClientConfig] provided.
    pub async fn init(cfg: ClientConfig) -> Result<Self, ClientError> {
        // Connect to client WebSocket server
        let ws_conn = connect(&String::from(Binance::BASE_URI)).await?;

        // Construct subscription message channel to subscribe to streams via the ConnectionHandler
        let (subscription_tx, subscription_rx) = mpsc::channel(10);

        // Construct ConnectionHandler
        let connection =
            ConnectionHandler::new(cfg.rate_limit_per_minute, ws_conn, subscription_rx);

        // Manage connection via event loop
        let _ = tokio::spawn(connection.manage());

        Ok(Self { subscription_tx })
    }
}

/// [Binance] Message variants that could be received from Binance WebSocket server.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BinanceMessage {
    Subscription(BinanceSub),
    SubscriptionResponse(BinanceSubResponse),
    Trade(BinanceTrade),
    Kline(BinanceKline),
    OrderBook(BinanceOrderBook),
}

impl StreamIdentifier for BinanceMessage {
    fn get_stream_id(&self) -> Identifier {
        match self {
            BinanceMessage::Trade(trade) => Identifier::Yes(format!(
                "{}@{}",
                trade.symbol.to_lowercase(),
                trade.event_type
            )),
            BinanceMessage::Kline(kline) => Identifier::Yes(format!(
                "{}@{}_{}",
                kline.symbol.to_lowercase(),
                kline.event_type,
                kline.data.interval
            )),
            _ => Identifier::No,
        }
    }
}

/// [Binance] specific subscription message.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct BinanceSub {
    method: String,
    params: Vec<String>,
    id: u64,
}

impl Subscription for BinanceSub {
    fn new(stream_name: String, ticker_pair: String) -> Self {
        Self {
            method: String::from("SUBSCRIBE"),
            params: vec![format!("{}{}", ticker_pair, stream_name)],
            id: 1,
        }
    }
}

impl StreamIdentifier for BinanceSub {
    fn get_stream_id(&self) -> Identifier {
        Identifier::Yes(self.params.get(0).unwrap().clone())
    }
}

/// [Binance] specific subscription response message.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceSubResponse {
    id: u64,
}

/// [Binance] specific Trade message.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceTrade {
    #[serde(rename = "e")]
    event_type: String,
    #[serde(rename = "E", skip_deserializing)]
    event_time: i64,
    #[serde(rename = "s")]
    symbol: String,
    #[serde(rename = "a")]
    trade_id: u64,
    #[serde(rename = "p", deserialize_with = "de_str_to_f64")]
    price: f64,
    #[serde(rename = "q", deserialize_with = "de_str_to_f64")]
    quantity: f64,
    #[serde(rename = "f", skip_deserializing)]
    buyer_order_id: u64,
    #[serde(rename = "l", skip_deserializing)]
    seller_order_id: u64,
    #[serde(rename = "T")]
    trade_time: i64,
    #[serde(rename = "m")]
    buyer_is_market_maker: bool,
    #[serde(rename = "M", skip_deserializing)]
    deprecated: bool,
}

impl From<BinanceTrade> for Trade {
    fn from(binance_trade: BinanceTrade) -> Self {
        let timestamp = DateTime::from_utc(
            NaiveDateTime::from_timestamp(binance_trade.trade_time / 1000, 0),
            Utc,
        );

        let buyer = match binance_trade.buyer_is_market_maker {
            true => BuyerType::MarketMaker,
            false => BuyerType::Taker,
        };

        Self {
            trade_id: binance_trade.trade_id.to_string(),
            timestamp,
            ticker: binance_trade.symbol,
            price: binance_trade.price,
            quantity: binance_trade.quantity,
            buyer,
        }
    }
}

/// [Binance] specific Kline message.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceKline {
    #[serde(rename = "e")]
    event_type: String,
    #[serde(rename = "E", skip_deserializing)]
    event_time: i64, // todo
    #[serde(rename = "s")]
    symbol: String,
    #[serde(rename = "k")]
    data: BinanceKlineData,
}

/// [Binance] Kline data contained within a [BinanceKline].
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceKlineData {
    #[serde(rename = "t")]
    start_time: i64,
    #[serde(rename = "T")]
    end_time: i64,
    #[serde(rename = "s", skip_deserializing)]
    symbol: String,
    #[serde(rename = "i")]
    interval: String,
    #[serde(rename = "f", skip_deserializing)]
    first_trade_id: i64,
    #[serde(rename = "L", skip_deserializing)]
    last_trade_id: i64,
    #[serde(rename = "o", deserialize_with = "de_str_to_f64")]
    open: f64,
    #[serde(rename = "c", deserialize_with = "de_str_to_f64")]
    close: f64,
    #[serde(rename = "h", deserialize_with = "de_str_to_f64")]
    high: f64,
    #[serde(rename = "l", deserialize_with = "de_str_to_f64")]
    low: f64,
    #[serde(rename = "v", deserialize_with = "de_str_to_f64")]
    base_asset_volume: f64,
    #[serde(rename = "n")]
    number_trades: u64,
    #[serde(rename = "x")]
    kline_closed: bool,
    #[serde(rename = "q", deserialize_with = "de_str_to_f64", skip_deserializing)]
    quote_asset_volume: f64,
    #[serde(rename = "V", deserialize_with = "de_str_to_f64", skip_deserializing)]
    taker_buy_base_asset_volume: f64,
    #[serde(rename = "Q", deserialize_with = "de_str_to_f64", skip_deserializing)]
    taker_buy_quote_asset_volume: f64,
    #[serde(rename = "B", skip_deserializing)]
    deprecated: String,
}

impl From<BinanceKline> for Candle {
    fn from(binance_kline: BinanceKline) -> Self {
        let start_timestamp = DateTime::from_utc(
            NaiveDateTime::from_timestamp(binance_kline.data.start_time / 1000, 0),
            Utc,
        );

        let end_timestamp = DateTime::from_utc(
            NaiveDateTime::from_timestamp(binance_kline.data.end_time / 1000, 0),
            Utc,
        );

        Self {
            start_timestamp,
            end_timestamp,
            open: binance_kline.data.open,
            high: binance_kline.data.high,
            low: binance_kline.data.low,
            close: binance_kline.data.close,
            volume: binance_kline.data.base_asset_volume,
            trade_count: binance_kline.data.number_trades,
        }
    }
}

/// [Binance] specific OrderBook snapshot message.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceOrderBook {
    #[serde(rename = "lastUpdateId")]
    pub last_update_id: u64,
    pub bids: Vec<BinanceLevel>,
    pub asks: Vec<BinanceLevel>,
}

/// [Binance] specific Level data structure used to construct a [BinanceOrderBook].
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinanceLevel {
    #[serde(deserialize_with = "de_str_to_f64")]
    pub price: f64,
    #[serde(rename = "quantity")]
    #[serde(deserialize_with = "de_str_to_f64")]
    pub amount: f64,
}