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
use super::BinanceChannel;
use crate::{
    event::{MarketEvent, MarketIter},
    exchange::{ExchangeId, ExchangeSub},
    subscription::trade::PublicTrade,
    Identifier,
};
use barter_integration::model::{instrument::Instrument, Exchange, Side, SubscriptionId};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Binance real-time trade message.
///
/// Note:
/// For [`BinanceFuturesUsd`](super::futures::BinanceFuturesUsd) this real-time stream is
/// undocumented.
///
/// See discord: <https://discord.com/channels/910237311332151317/923160222711812126/975712874582388757>
///
/// ### Raw Payload Examples
/// See docs: <https://binance-docs.github.io/apidocs/spot/en/#trade-streams>
/// #### Spot Side::Buy Trade
/// ```json
/// {
///     "e":"trade",
///     "E":1649324825173,
///     "s":"ETHUSDT",
///     "t":1000000000,
///     "p":"10000.19",
///     "q":"0.239000",
///     "b":10108767791,
///     "a":10108764858,
///     "T":1749354825200,
///     "m":false,
///     "M":true
/// }
/// ```
///
/// #### FuturePerpetual Side::Sell Trade
/// ```json
/// {
///     "e": "trade",
///     "E": 1649839266194,
///     "T": 1749354825200,
///     "s": "ETHUSDT",
///     "t": 1000000000,
///     "p":"10000.19",
///     "q":"0.239000",
///     "X": "MARKET",
///     "m": true
/// }
/// ```
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct BinanceTrade {
    #[serde(alias = "s", deserialize_with = "de_trade_subscription_id")]
    pub subscription_id: SubscriptionId,
    #[serde(
        alias = "T",
        deserialize_with = "barter_integration::de::de_u64_epoch_ms_as_datetime_utc"
    )]
    pub time: DateTime<Utc>,
    #[serde(alias = "t")]
    pub id: u64,
    #[serde(alias = "p", deserialize_with = "barter_integration::de::de_str")]
    pub price: f64,
    #[serde(alias = "q", deserialize_with = "barter_integration::de::de_str")]
    pub amount: f64,
    #[serde(alias = "m", deserialize_with = "de_side_from_buyer_is_maker")]
    pub side: Side,
}

impl Identifier<Option<SubscriptionId>> for BinanceTrade {
    fn id(&self) -> Option<SubscriptionId> {
        Some(self.subscription_id.clone())
    }
}

impl From<(ExchangeId, Instrument, BinanceTrade)> for MarketIter<PublicTrade> {
    fn from((exchange_id, instrument, trade): (ExchangeId, Instrument, BinanceTrade)) -> Self {
        Self(vec![Ok(MarketEvent {
            exchange_time: trade.time,
            received_time: Utc::now(),
            exchange: Exchange::from(exchange_id),
            instrument,
            kind: PublicTrade {
                id: trade.id.to_string(),
                price: trade.price,
                amount: trade.amount,
                side: trade.side,
            },
        })])
    }
}

/// Deserialize a [`BinanceTrade`] "s" (eg/ "BTCUSDT") as the associated [`SubscriptionId`]
/// (eg/ "@trade|BTCUSDT").
pub fn de_trade_subscription_id<'de, D>(deserializer: D) -> Result<SubscriptionId, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    <&str as Deserialize>::deserialize(deserializer)
        .map(|market| ExchangeSub::from((BinanceChannel::TRADES, market)).id())
}

/// Deserialize a [`BinanceTrade`] "buyer_is_maker" boolean field to a Barter [`Side`].
///
/// Variants:
/// buyer_is_maker => Side::Sell
/// !buyer_is_maker => Side::Buy
pub fn de_side_from_buyer_is_maker<'de, D>(deserializer: D) -> Result<Side, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    Deserialize::deserialize(deserializer).map(|buyer_is_maker| {
        if buyer_is_maker {
            Side::Sell
        } else {
            Side::Buy
        }
    })
}

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

    mod de {
        use super::*;
        use barter_integration::{de::datetime_utc_from_epoch_duration, error::SocketError};
        use serde::de::Error;
        use std::time::Duration;

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

            let tests = vec![
                TestCase {
                    // TC0: Spot trade valid
                    input: r#"
                    {
                        "e":"trade","E":1649324825173,"s":"ETHUSDT","t":1000000000,
                        "p":"10000.19","q":"0.239000","b":10108767791,"a":10108764858,
                        "T":1749354825200,"m":false,"M":true
                    }
                    "#,
                    expected: Ok(BinanceTrade {
                        subscription_id: SubscriptionId::from("@trade|ETHUSDT"),
                        time: datetime_utc_from_epoch_duration(Duration::from_millis(
                            1749354825200,
                        )),
                        id: 1000000000,
                        price: 10000.19,
                        amount: 0.239000,
                        side: Side::Buy,
                    }),
                },
                TestCase {
                    // TC1: Spot trade malformed w/ "yes" is_buyer_maker field
                    input: r#"{
                        "e":"trade","E":1649324825173,"s":"ETHUSDT","t":1000000000,
                        "p":"10000.19000000","q":"0.239000","b":10108767791,"a":10108764858,
                        "T":1649324825173,"m":"yes","M":true
                    }"#,
                    expected: Err(SocketError::Deserialise {
                        error: serde_json::Error::custom(""),
                        payload: "".to_owned(),
                    }),
                },
                TestCase {
                    // TC2: FuturePerpetual trade w/ type MARKET
                    input: r#"
                    {
                        "e": "trade","E": 1649839266194,"T": 1749354825200,"s": "ETHUSDT",
                        "t": 1000000000,"p":"10000.19","q":"0.239000","X": "MARKET","m": true
                    }
                    "#,
                    expected: Ok(BinanceTrade {
                        subscription_id: SubscriptionId::from("@trade|ETHUSDT"),
                        time: datetime_utc_from_epoch_duration(Duration::from_millis(
                            1749354825200,
                        )),
                        id: 1000000000,
                        price: 10000.19,
                        amount: 0.239000,
                        side: Side::Sell,
                    }),
                },
                TestCase {
                    // TC3: FuturePerpetual trade w/ type LIQUIDATION
                    input: r#"
                    {
                        "e": "trade","E": 1649839266194,"T": 1749354825200,"s": "ETHUSDT",
                        "t": 1000000000,"p":"10000.19","q":"0.239000","X": "LIQUIDATION","m": false
                    }
                    "#,
                    expected: Ok(BinanceTrade {
                        subscription_id: SubscriptionId::from("@trade|ETHUSDT"),
                        time: datetime_utc_from_epoch_duration(Duration::from_millis(
                            1749354825200,
                        )),
                        id: 1000000000,
                        price: 10000.19,
                        amount: 0.239000,
                        side: Side::Buy,
                    }),
                },
                TestCase {
                    // TC4: FuturePerpetual trade w/ type LIQUIDATION
                    input: r#"{
                        "e": "trade","E": 1649839266194,"T": 1749354825200,"s": "ETHUSDT",
                        "t": 1000000000,"p":"10000.19","q":"0.239000","X": "INSURANCE_FUND","m": false
                    }"#,
                    expected: Ok(BinanceTrade {
                        subscription_id: SubscriptionId::from("@trade|ETHUSDT"),
                        time: datetime_utc_from_epoch_duration(Duration::from_millis(
                            1749354825200,
                        )),
                        id: 1000000000,
                        price: 10000.19,
                        amount: 0.239000,
                        side: Side::Buy,
                    }),
                },
            ];

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