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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::{
    model::{
        subscription::{SubKind, Subscription, SubscriptionIds, SubscriptionMeta},
        MarketEvent,
    },
    ExchangeId, ExchangeTransformer, Subscriber,
};
use barter_integration::{
    error::SocketError,
    model::{InstrumentKind, SubscriptionId},
    protocol::websocket::WsMessage,
    Transformer, Validator,
};
use model::{FtxMessage, FtxSubResponse};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashMap;
use tokio::sync::mpsc;

/// [`Ftx`] specific data structures.
pub mod model;

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

impl Subscriber for Ftx {
    type SubResponse = FtxSubResponse;

    fn base_url() -> &'static str {
        "wss://ftx.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 Ftx subscriptions
        let subscriptions = subscriptions
            .iter()
            .map(|subscription| {
                // Determine the Ftx 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
                // eg/ SubscriptionId("trades|BTC/USDT")
                ids.insert(Ftx::subscription_id(channel, &market), subscription.clone());

                // Construct Ftx specific subscription message
                Ok(Self::subscription(channel, &market))
            })
            .collect::<Result<Vec<_>, SocketError>>()?;

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

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

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

    fn transform(&mut self, input: Self::Input) -> Self::OutputIter {
        match input {
            FtxMessage::Trades {
                subscription_id,
                trades,
            } => {
                let instrument = match self.ids.find_instrument(&subscription_id) {
                    Ok(instrument) => instrument,
                    Err(error) => return vec![Err(error)],
                };

                trades
                    .into_iter()
                    .map(|trade| {
                        Ok(MarketEvent::from((
                            Ftx::EXCHANGE,
                            instrument.clone(),
                            trade,
                        )))
                    })
                    .collect()
            }
        }
    }
}

impl Ftx {
    /// [`Ftx`] trades channel name.
    ///
    /// See docs: <https://docs.ftx.com/#trades>
    pub const CHANNEL_TRADES: &'static str = "trades";

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

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

        // Determine Ftx market using the Instrument
        let market = match &sub.instrument.kind {
            InstrumentKind::Spot => format!("{}/{}", sub.instrument.base, sub.instrument.quote),
            InstrumentKind::FuturePerpetual => format!("{}-PERP", sub.instrument.base),
        };

        Ok((channel, market.to_uppercase()))
    }

    /// Build a [`Ftx`] compatible subscription message using the channel & market provided.
    pub fn subscription(channel: &str, market: &str) -> WsMessage {
        WsMessage::Text(
            json!({
                "op": "subscribe",
                "channel": channel,
                "market": market,
            })
            .to_string(),
        )
    }

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

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

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

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

        Ftx { ids }
    }

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

        let cases = vec![
            TestCase {
                // TC0: Supported InstrumentKind::Spot trades subscription
                input: Subscription::new(
                    ExchangeId::Ftx,
                    ("btc", "usdt", InstrumentKind::Spot),
                    SubKind::Trade,
                ),
                expected: Ok(("trades", "BTC/USDT".to_owned())),
            },
            TestCase {
                // TC1: Supported InstrumentKind::FuturePerpetual trades subscription
                input: Subscription::new(
                    ExchangeId::Ftx,
                    ("btc", "usdt", InstrumentKind::FuturePerpetual),
                    SubKind::Trade,
                ),
                expected: Ok(("trades", "BTC-PERP".to_owned())),
            },
            TestCase {
                // TC2: Unsupported InstrumentKind::FuturePerpetual candle subscription
                input: Subscription::new(
                    ExchangeId::Ftx,
                    ("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 = Ftx::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_ftx_transform() {
        let mut transformer = ftx(vec![
            Subscription::from((
                ExchangeId::Ftx,
                "btc",
                "usdt",
                InstrumentKind::Spot,
                SubKind::Trade,
            )),
            Subscription::from((
                ExchangeId::Ftx,
                "btc",
                "usdt",
                InstrumentKind::FuturePerpetual,
                SubKind::Trade,
            )),
        ]);

        let time = Utc::now();

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

        let cases = vec![
            TestCase {
                // TC0: FtxMessage with unknown SubscriptionId
                input: FtxMessage::Trades {
                    subscription_id: SubscriptionId::from("unknown"),
                    trades: vec![],
                },
                expected: vec![Err(SocketError::Unidentifiable(SubscriptionId::from(
                    "unknown",
                )))],
            },
            TestCase {
                // TC1: FtxMessage Spot trades w/ known SubscriptionId
                input: FtxMessage::Trades {
                    subscription_id: SubscriptionId::from("trades|BTC/USDT"),
                    trades: vec![
                        FtxTrade {
                            id: 1,
                            price: 1.0,
                            size: 1.0,
                            side: Side::Buy,
                            time: time,
                        },
                        FtxTrade {
                            id: 2,
                            price: 1.0,
                            size: 1.0,
                            side: Side::Sell,
                            time: time,
                        },
                    ],
                },
                expected: vec![
                    Ok(MarketEvent {
                        exchange_time: time,
                        received_time: time,
                        exchange: Exchange::from(ExchangeId::Ftx),
                        instrument: Instrument::from(("btc", "usdt", InstrumentKind::Spot)),
                        kind: DataKind::Trade(PublicTrade {
                            id: "1".to_string(),
                            price: 1.0,
                            quantity: 1.0,
                            side: Side::Buy,
                        }),
                    }),
                    Ok(MarketEvent {
                        exchange_time: time,
                        received_time: time,
                        exchange: Exchange::from(ExchangeId::Ftx),
                        instrument: Instrument::from(("btc", "usdt", InstrumentKind::Spot)),
                        kind: DataKind::Trade(PublicTrade {
                            id: "2".to_string(),
                            price: 1.0,
                            quantity: 1.0,
                            side: Side::Sell,
                        }),
                    }),
                ],
            },
            TestCase {
                // TC2: FtxMessage FuturePerpetual trades w/ known SubscriptionId
                input: FtxMessage::Trades {
                    subscription_id: SubscriptionId::from("trades|BTC-PERP"),
                    trades: vec![
                        FtxTrade {
                            id: 1,
                            price: 1.0,
                            size: 1.0,
                            side: Side::Buy,
                            time: time,
                        },
                        FtxTrade {
                            id: 2,
                            price: 1.0,
                            size: 1.0,
                            side: Side::Sell,
                            time: time,
                        },
                    ],
                },
                expected: vec![
                    Ok(MarketEvent {
                        exchange_time: time,
                        received_time: time,
                        exchange: Exchange::from(ExchangeId::Ftx),
                        instrument: Instrument::from((
                            "btc",
                            "usdt",
                            InstrumentKind::FuturePerpetual,
                        )),
                        kind: DataKind::Trade(PublicTrade {
                            id: "1".to_string(),
                            price: 1.0,
                            quantity: 1.0,
                            side: Side::Buy,
                        }),
                    }),
                    Ok(MarketEvent {
                        exchange_time: time,
                        received_time: time,
                        exchange: Exchange::from(ExchangeId::Ftx),
                        instrument: Instrument::from((
                            "btc",
                            "usdt",
                            InstrumentKind::FuturePerpetual,
                        )),
                        kind: DataKind::Trade(PublicTrade {
                            id: "2".to_string(),
                            price: 1.0,
                            quantity: 1.0,
                            side: Side::Sell,
                        }),
                    }),
                ],
            },
        ];

        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");
                    }
                }
            }
        }
    }
}