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

/// [`BinanceFuturesUsd`](super::BinanceFuturesUsd) Liquidation order message.
///
/// ### Raw Payload Examples
/// See docs: <https://binance-docs.github.io/apidocs/futures/en/#liquidation-order-streams>
/// ```json
/// {
///     "e": "forceOrder",
///     "E": 1665523974222,
///     "o": {
///         "s": "BTCUSDT",
///         "S": "SELL",
///         "o": "LIMIT",
///         "f": "IOC",
///         "q": "0.009",
///         "p": "18917.15",
///         "ap": "18990.00",
///         "X": "FILLED",
///         "l": "0.009",
///         "z": "0.009",
///         "T": 1665523974217
///     }
/// }
/// ```
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct BinanceLiquidation {
    #[serde(alias = "o")]
    pub order: BinanceLiquidationOrder,
}

/// [`BinanceFuturesUsd`](super::BinanceFuturesUsd) Liquidation order.
///
/// ### Raw Payload Examples
/// ```json
/// {
///     "s": "BTCUSDT",
///     "S": "SELL",
///     "o": "LIMIT",
///     "f": "IOC",
///     "q": "0.009",
///     "p": "18917.15",
///     "ap": "18990.00",
///     "X": "FILLED",
///     "l": "0.009",
///     "z": "0.009",
///     "T": 1665523974217
/// }
/// ```
///
/// See docs: <https://binance-docs.github.io/apidocs/futures/en/#liquidation-order-streams>
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct BinanceLiquidationOrder {
    #[serde(alias = "s", deserialize_with = "de_liquidation_subscription_id")]
    pub subscription_id: SubscriptionId,
    #[serde(alias = "S")]
    pub side: Side,
    #[serde(alias = "p", deserialize_with = "barter_integration::de::de_str")]
    pub price: f64,
    #[serde(alias = "q", deserialize_with = "barter_integration::de::de_str")]
    pub quantity: f64,
    #[serde(
        alias = "T",
        deserialize_with = "barter_integration::de::de_u64_epoch_ms_as_datetime_utc"
    )]
    pub time: DateTime<Utc>,
}

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

impl From<(ExchangeId, Instrument, BinanceLiquidation)> for MarketIter<Liquidation> {
    fn from(
        (exchange_id, instrument, liquidation): (ExchangeId, Instrument, BinanceLiquidation),
    ) -> Self {
        Self(vec![Ok(MarketEvent {
            exchange_time: liquidation.order.time,
            received_time: Utc::now(),
            exchange: Exchange::from(exchange_id),
            instrument,
            kind: Liquidation {
                side: liquidation.order.side,
                price: liquidation.order.price,
                quantity: liquidation.order.quantity,
                time: liquidation.order.time,
            },
        })])
    }
}

/// Deserialize a [`BinanceLiquidationOrder`] "s" (eg/ "BTCUSDT") as the associated
/// [`SubscriptionId`].
///
/// eg/ "forceOrder|BTCUSDT"
pub fn de_liquidation_subscription_id<'de, D>(deserializer: D) -> Result<SubscriptionId, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    Deserialize::deserialize(deserializer).map(|market: String| {
        SubscriptionId::from(format!("{}|{}", BinanceChannel::LIQUIDATIONS.0, market))
    })
}

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

    mod de {
        use super::*;
        use barter_integration::de::datetime_utc_from_epoch_duration;
        use std::time::Duration;

        #[test]
        fn test_binance_liquidation() {
            let input = r#"
            {
                "e": "forceOrder",
                "E": 1665523974222,
                "o": {
                    "s": "BTCUSDT",
                    "S": "SELL",
                    "o": "LIMIT",
                    "f": "IOC",
                    "q": "0.009",
                    "p": "18917.15",
                    "ap": "18990.00",
                    "X": "FILLED",
                    "l": "0.009",
                    "z": "0.009",
                    "T": 1665523974217
                }
            }
            "#;

            assert_eq!(
                serde_json::from_str::<BinanceLiquidation>(input).unwrap(),
                BinanceLiquidation {
                    order: BinanceLiquidationOrder {
                        subscription_id: SubscriptionId::from("@forceOrder|BTCUSDT"),
                        side: Side::Sell,
                        price: 18917.15,
                        quantity: 0.009,
                        time: datetime_utc_from_epoch_duration(Duration::from_millis(
                            1665523974217,
                        )),
                    },
                }
            );
        }
    }
}