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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use super::model::{BinanceMessage, BinanceSubResponse};
use crate::{
    model::{subscription::SubKind, MarketEvent},
    ExchangeId, ExchangeTransformer, Subscriber, Subscription, SubscriptionIds, SubscriptionMeta,
};
use barter_integration::{
    error::SocketError, model::SubscriptionId, protocol::websocket::WsMessage, Transformer,
    Validator,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use tokio::sync::mpsc;

/// [`BinanceFuturesUsd`] [`Subscriber`](crate::Subscriber) &
/// [`ExchangeTransformer`](crate::ExchangeTransformer) implementor for the collection
/// of `Futures` data.
#[derive(Clone, Eq, PartialEq, Debug, Deserialize, Serialize)]
pub struct BinanceFuturesUsd {
    pub ids: SubscriptionIds,
}

impl Subscriber for BinanceFuturesUsd {
    type SubResponse = BinanceSubResponse;

    fn base_url() -> &'static str {
        "wss://fstream.binance.com/ws"
    }

    fn build_subscription_meta(
        subscriptions: &[Subscription],
    ) -> Result<SubscriptionMeta, SocketError> {
        // Allocate SubscriptionIds HashMap to track identifiers for each actioned Subscription
        let mut ids = SubscriptionIds(HashMap::with_capacity(subscriptions.len()));

        // Map Barter Subscriptions to BinanceFuturesUsd 'StreamNames'
        let stream_names = subscriptions
            .iter()
            .map(|subscription| {
                // Determine BinanceFuturesUsd specific channel & market for this Barter Subscription
                let (channel, market) = Self::build_channel_meta(subscription)?;

                // Use "channel|market" as the SubscriptionId key in the SubscriptionIds
                // '--> Uppercase market to match incoming exchange event
                // eg/ SubscriptionId("@aggTrade|BTCUSDT")
                ids.insert(
                    BinanceFuturesUsd::subscription_id(channel, &market.to_uppercase()),
                    subscription.clone(),
                );

                // Construct BinanceFuturesUsd 'StreamName' eg/ "btcusdt@aggTrade"
                // '--> Lowercase market because the subscription 'StreamName' must be lowercase
                Ok(format!("{market}{channel}"))
            })
            .collect::<Result<Vec<_>, SocketError>>()?;

        // Use channels to construct a Binance subscription WsMessage
        let subscriptions = Self::subscriptions(stream_names);

        Ok(SubscriptionMeta {
            ids,
            expected_responses: subscriptions.len(),
            subscriptions,
        })
    }
}

impl ExchangeTransformer for BinanceFuturesUsd {
    const EXCHANGE: ExchangeId = ExchangeId::BinanceFuturesUsd;
    fn new(_: mpsc::UnboundedSender<WsMessage>, ids: SubscriptionIds) -> Self {
        Self { ids }
    }
}

impl Transformer<MarketEvent> for BinanceFuturesUsd {
    type Input = BinanceMessage;
    type OutputIter = Vec<Result<MarketEvent, SocketError>>;

    fn transform(&mut self, input: Self::Input) -> Self::OutputIter {
        match input {
            BinanceMessage::Trade(trade) => {
                match self.ids.find_instrument(&trade.subscription_id) {
                    Ok(instrument) => vec![Ok(MarketEvent::from((
                        BinanceFuturesUsd::EXCHANGE,
                        instrument,
                        trade,
                    )))],
                    Err(error) => vec![Err(error)],
                }
            }
            BinanceMessage::OrderBookSnapshot(snapshot) => {
                match self.ids.find_instrument(&snapshot.subscription_id) {
                    Ok(instrument) => vec![Ok(MarketEvent::from((
                        BinanceFuturesUsd::EXCHANGE,
                        instrument,
                        snapshot,
                    )))],
                    Err(error) => vec![Err(error)],
                }
            }
        }
    }
}

impl BinanceFuturesUsd {
    /// [`BinanceFuturesUsd`] aggregated trades channel name.
    ///
    /// See docs: <https://binance-docs.github.io/apidocs/futures/en/#aggregate-trade-streams>
    pub const CHANNEL_TRADES: &'static str = "@aggTrade";

    /// [`BinanceFuturesUsd`] OrderBook channel name. Note that currently additional channel
    /// information for for OrderBook latency (100ms) and depth (20 levels) is included.
    ///
    /// See docs: <https://binance-docs.github.io/apidocs/futures/en/#partial-book-depth-streams>
    pub const CHANNEL_ORDER_BOOK: &'static str = "@depth20@100ms";

    /// Determine the [`BinanceFuturesUsd`] channel metadata associated with an input
    /// Barter [`Subscription`]. This includes the [`BinanceFuturesUsd`] `&str` channel
    /// identifier, and a `String` market identifier. Both are used to build a
    /// [`BinanceFuturesUsd`] subscription payload.
    ///
    /// Example Ok return: Ok("@aggTrade", "btcusdt")
    /// where channel == "@aggTrade" & market == "btcusdt"
    pub fn build_channel_meta(sub: &Subscription) -> Result<(&str, String), SocketError> {
        // Validate provided Subscription InstrumentKind is supported by BinanceFuturesUsd
        let sub = sub.validate()?;

        // Determine the BinanceFuturesUsd channel
        let channel = match &sub.kind {
            SubKind::Trade => Self::CHANNEL_TRADES,
            SubKind::OrderBook => Self::CHANNEL_ORDER_BOOK,
            other => {
                return Err(SocketError::Unsupported {
                    entity: BinanceFuturesUsd::EXCHANGE.as_str(),
                    item: other.to_string(),
                })
            }
        };

        // Determine BinanceFuturesUsd market using the Instrument
        let market = format!("{}{}", sub.instrument.base, sub.instrument.quote);

        Ok((channel, market))
    }

    /// Build a [`BinanceFuturesUsd`] compatible [`SubscriptionId`] using the channel & market
    /// provided. This is used to associate [`BinanceFuturesUsd`] data structures received over
    /// the WebSocket with it's original Barter [`Subscription`].
    ///
    /// eg/ SubscriptionId("@aggTrade|BTCUSDT")
    pub fn subscription_id(channel: &str, market: &str) -> SubscriptionId {
        SubscriptionId::from(format!("{channel}|{market}"))
    }

    /// Build a [`BinanceFuturesUsd`] compatible subscription message using the
    /// 'StreamNames' provided.
    pub fn subscriptions(stream_names: Vec<String>) -> Vec<WsMessage> {
        vec![WsMessage::Text(
            json!({
                "method": "SUBSCRIBE",
                "params": stream_names,
                "id": 1
            })
            .to_string(),
        )]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::exchange::binance::model::BinanceTrade;
    use crate::model::{subscription::Interval, DataKind, PublicTrade};
    use barter_integration::model::{Exchange, Instrument, InstrumentKind, Side};
    use chrono::Utc;

    fn binance_futures_usd(subscriptions: Vec<Subscription>) -> BinanceFuturesUsd {
        let ids = SubscriptionIds(
            subscriptions
                .into_iter()
                .map(|sub| {
                    let subscription_id = match (&sub.kind, &sub.instrument.kind) {
                        (SubKind::Trade, InstrumentKind::FuturePerpetual) => {
                            BinanceFuturesUsd::subscription_id(
                                BinanceFuturesUsd::CHANNEL_TRADES,
                                &format!("{}{}", sub.instrument.base, sub.instrument.quote)
                                    .to_uppercase(),
                            )
                        }
                        (_, _) => {
                            panic!("not supported")
                        }
                    };

                    (subscription_id, sub)
                })
                .collect(),
        );

        BinanceFuturesUsd { ids }
    }

    #[test]
    fn test_build_channel_meta() {
        struct TestCase<'a> {
            input: Subscription,
            expected: Result<(&'a str, String), SocketError>,
        }

        let cases = vec![
            TestCase {
                // TC0: Unsupported InstrumentKind::Spot subscription
                input: Subscription::new(
                    ExchangeId::BinanceFuturesUsd,
                    ("btc", "usdt", InstrumentKind::Spot),
                    SubKind::Trade,
                ),
                expected: Err(SocketError::Unsupported {
                    entity: "",
                    item: "".to_string(),
                }),
            },
            TestCase {
                // TC1: Supported InstrumentKind::FuturePerpetual trades subscription
                input: Subscription::new(
                    ExchangeId::BinanceFuturesUsd,
                    ("btc", "usdt", InstrumentKind::FuturePerpetual),
                    SubKind::Trade,
                ),
                expected: Ok(("@aggTrade", "btcusdt".to_owned())),
            },
            TestCase {
                // TC2: Unsupported InstrumentKind::FuturePerpetual OrderBookL2Delta subscription
                input: Subscription::new(
                    ExchangeId::BinanceFuturesUsd,
                    ("btc", "usdt", InstrumentKind::FuturePerpetual),
                    SubKind::OrderBookL2Delta,
                ),
                expected: Err(SocketError::Unsupported {
                    entity: "",
                    item: "".to_string(),
                }),
            },
            TestCase {
                // TC3: Unsupported InstrumentKind::FuturePerpetual candle subscription
                input: Subscription::new(
                    ExchangeId::BinanceFuturesUsd,
                    ("btc", "usdt", InstrumentKind::FuturePerpetual),
                    SubKind::Candle(Interval::Minute5),
                ),
                expected: Err(SocketError::Unsupported {
                    entity: "",
                    item: "".to_string(),
                }),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let actual = BinanceFuturesUsd::build_channel_meta(&test.input);
            match (actual, test.expected) {
                (Ok(actual), Ok(expected)) => {
                    assert_eq!(actual, expected, "TC{} failed", index)
                }
                (Err(_), Err(_)) => {
                    // Test passed
                }
                (actual, expected) => {
                    // Test failed
                    panic!("TC{index} failed because actual != expected. \nActual: {actual:?}\nExpected: {expected:?}\n");
                }
            }
        }
    }

    #[test]
    fn test_binance_transform() {
        let mut transformer = binance_futures_usd(vec![Subscription::from((
            ExchangeId::BinanceFuturesUsd,
            "btc",
            "usdt",
            InstrumentKind::FuturePerpetual,
            SubKind::Trade,
        ))]);

        let time = Utc::now();

        struct TestCase {
            input: BinanceMessage,
            expected: Vec<Result<MarketEvent, SocketError>>,
        }

        let cases = vec![
            TestCase {
                // TC0: BinanceMessage with unknown SubscriptionId
                input: BinanceMessage::Trade(BinanceTrade {
                    subscription_id: SubscriptionId::from("unknown"),
                    time,
                    id: 0,
                    price: 1000.0,
                    quantity: 1.0,
                    side: Side::Buy,
                }),
                expected: vec![Err(SocketError::Unidentifiable(SubscriptionId::from(
                    "unknown",
                )))],
            },
            TestCase {
                // TC1: BinanceMessage FuturePerpetual trade w/ known SubscriptionId
                input: BinanceMessage::Trade(BinanceTrade {
                    subscription_id: SubscriptionId::from("@aggTrade|BTCUSDT"),
                    time,
                    id: 0,
                    price: 1000.0,
                    quantity: 1.0,
                    side: Side::Buy,
                }),
                expected: vec![Ok(MarketEvent {
                    exchange_time: time,
                    received_time: time,
                    exchange: Exchange::from(ExchangeId::BinanceFuturesUsd),
                    instrument: Instrument::from(("btc", "usdt", InstrumentKind::FuturePerpetual)),
                    kind: DataKind::Trade(PublicTrade {
                        id: "0".to_string(),
                        price: 1000.0,
                        quantity: 1.0,
                        side: Side::Buy,
                    }),
                })],
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let actual = transformer.transform(test.input);
            assert_eq!(
                actual.len(),
                test.expected.len(),
                "TestCase {} failed at vector length assert_eq with actual: {:?}",
                index,
                actual
            );

            for (vector_index, (actual, expected)) in actual
                .into_iter()
                .zip(test.expected.into_iter())
                .enumerate()
            {
                match (actual, expected) {
                    (Ok(actual), Ok(expected)) => {
                        // Scrub Utc::now() timestamps to allow comparison
                        let actual = MarketEvent {
                            received_time: time,
                            ..actual
                        };
                        assert_eq!(
                            actual, expected,
                            "TC{} failed at vector index {}",
                            index, vector_index
                        )
                    }
                    (Err(_), Err(_)) => {
                        // Test passed
                    }
                    (actual, expected) => {
                        // Test failed
                        panic!("TC{index} failed at vector index {vector_index} because actual != expected. \nActual: {actual:?}\nExpected: {expected:?}\n");
                    }
                }
            }
        }
    }
}