barter_data/exchange/bitmex/
trade.rs

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
use crate::{
    event::{MarketEvent, MarketIter},
    exchange::{bitmex::message::BitmexMessage, ExchangeId},
    subscription::trade::PublicTrade,
};
use barter_integration::model::{Exchange, Side};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Terse type alias for an [`BitmexTrade`](BitmexTradeInner) real-time trades WebSocket message.
pub type BitmexTrade = BitmexMessage<BitmexTradeInner>;

/// ### Raw Payload Examples
/// See docs: <https://www.bitmex.com/app/wsAPI#Response-Format>
/// #### Trade payload
/// ```json
/// {
///     "table": "trade",
///     "action": "insert",
///     "data": [
///         {
///             "timestamp": "2023-02-18T09:27:59.701Z",
///             "symbol": "XBTUSD",
///             "side": "Sell",
///             "size": 200,
///             "price": 24564.5,
///             "tickDirection": "MinusTick",
///             "trdMatchID": "31e50cb7-e005-a44e-f354-86e88dff52eb",
///             "grossValue": 814184,
///             "homeNotional": 0.00814184,
///             "foreignNotional": 200,
///             "trdType": "Regular"
///         }
///     ]
/// }
///```
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct BitmexTradeInner {
    pub timestamp: DateTime<Utc>,

    pub symbol: String,

    pub side: Side,
    #[serde(rename = "size")]
    pub amount: f64,
    pub price: f64,

    #[serde(rename = "trdMatchID")]
    pub id: String,
}

impl<InstrumentKey: Clone> From<(ExchangeId, InstrumentKey, BitmexTrade)>
    for MarketIter<InstrumentKey, PublicTrade>
{
    fn from((exchange_id, instrument, trades): (ExchangeId, InstrumentKey, BitmexTrade)) -> Self {
        Self(
            trades
                .data
                .into_iter()
                .map(|trade| {
                    Ok(MarketEvent {
                        time_exchange: trade.timestamp,
                        time_received: Utc::now(),
                        exchange: Exchange::from(exchange_id),
                        instrument: instrument.clone(),
                        kind: PublicTrade {
                            id: trade.id,
                            price: trade.price,
                            amount: trade.amount,
                            side: trade.side,
                        },
                    })
                })
                .collect(),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod de {
        use super::*;
        use barter_integration::error::SocketError;
        use chrono::{Duration, TimeZone};

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

            let tests = vec![
                // TC0: input BitmexTrade is deserialised
                TestCase {
                    input: r#"
                    {
                        "timestamp": "2023-02-18T09:27:59.701Z",
                        "symbol": "XBTUSD",
                        "side": "Sell",
                        "size": 200,
                        "price": 24564.5,
                        "tickDirection": "MinusTick",
                        "trdMatchID": "31e50cb7-e005-a44e-f354-86e88dff52eb",
                        "grossValue": 814184,
                        "homeNotional": 0.00814184,
                        "foreignNotional": 200,
                        "trdType": "Regular"
                    }
                    "#,
                    expected: Ok(BitmexTradeInner {
                        timestamp: Utc.with_ymd_and_hms(2023, 2, 18, 9, 27, 59).unwrap()
                            + Duration::milliseconds(701),
                        symbol: "XBTUSD".to_string(),
                        side: Side::Sell,
                        amount: 200.0,
                        price: 24564.5,
                        id: "31e50cb7-e005-a44e-f354-86e88dff52eb".to_string(),
                    }),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                let actual = serde_json::from_str::<BitmexTradeInner>(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_bitmex_trade_payload() {
            struct TestCase {
                input: &'static str,
                expected: Result<BitmexTrade, SocketError>,
            }

            let tests = vec![
                // TC0: input BitmexTradePayload is deserialised
                TestCase {
                    input: r#"
                    {
                        "table": "trade",
                        "action": "insert",
                        "data": [
                            {
                                "timestamp": "2023-02-18T09:27:59.701Z",
                                "symbol": "XBTUSD",
                                "side": "Sell",
                                "size": 200,
                                "price": 24564.5,
                                "tickDirection": "MinusTick",
                                "trdMatchID": "31e50cb7-e005-a44e-f354-86e88dff52eb",
                                "grossValue": 814184,
                                "homeNotional": 0.00814184,
                                "foreignNotional": 200,
                                "trdType": "Regular"
                            }
                        ]
                    }
                    "#,
                    expected: Ok(BitmexTrade {
                        table: "trade".to_string(),
                        data: vec![BitmexTradeInner {
                            timestamp: Utc.with_ymd_and_hms(2023, 2, 18, 9, 27, 59).unwrap()
                                + Duration::milliseconds(701),
                            symbol: "XBTUSD".to_string(),
                            side: Side::Sell,
                            amount: 200.0,
                            price: 24564.5,
                            id: "31e50cb7-e005-a44e-f354-86e88dff52eb".to_string(),
                        }],
                    }),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                let actual = serde_json::from_str::<BitmexTrade>(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");
                    }
                }
            }
        }
    }
}