patisson-binance-sdk 0.1.7

Unofficial Rust SDK for the Binance exchange API
Documentation
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
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use crate::{
    Timestamp,
    margin::{
        IsIsolated, MarginLevelStatus, OrderResponseType, OrderSide, OrderStatus, OrderType,
        STPMode, SideEffectType, TimeInForce,
    },
};

#[derive(Debug, PartialEq)]
pub struct Response<T> {
    pub result: T,
    pub headers: Headers,
}

#[derive(Debug, PartialEq)]
pub struct Headers {
    pub retry_after: Option<Timestamp>,
}

// ===== Margin metadata =====

#[derive(Debug, Serialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct GetAllMarginAssetsParams {
    asset: Option<String>,
    recv_window: Option<i64>,
}

impl GetAllMarginAssetsParams {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn asset(mut self, value: impl Into<String>) -> Self {
        self.asset = Some(value.into());
        self
    }

    pub fn recv_window(mut self, value: i64) -> Self {
        self.recv_window = Some(value);
        self
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MarginAsset {
    pub asset_full_name: String,
    pub asset_name: String,
    pub is_borrowable: bool,
    pub is_mortgageable: bool,
    pub user_min_borrow: Decimal,
    pub user_min_repay: Decimal,
}

// ===== Cross margin account =====

#[derive(Debug, Serialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct GetMarginAccountParams {
    recv_window: Option<i64>,
}

impl GetMarginAccountParams {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn recv_window(mut self, value: i64) -> Self {
        self.recv_window = Some(value);
        self
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MarginAccount {
    pub created: bool,
    pub borrow_enabled: bool,
    pub margin_level: Decimal,
    pub collateral_margin_level: Decimal,
    pub total_asset_of_btc: Decimal,
    pub total_liability_of_btc: Decimal,
    pub total_net_asset_of_btc: Decimal,
    pub total_collateral_value_in_usdt: Decimal,
    pub trade_enabled: bool,
    pub transfer_in_enabled: bool,
    pub transfer_out_enabled: bool,
    pub account_type: String,
    pub margin_level_status: MarginLevelStatus,
    pub user_assets: Vec<MarginUserAsset>,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MarginUserAsset {
    pub asset: String,
    pub borrowed: Decimal,
    pub free: Decimal,
    pub interest: Decimal,
    pub locked: Decimal,
    pub net_asset: Decimal,
}

// ===== Margin trading =====

#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderRequest {
    symbol: String,
    is_isolated: Option<IsIsolated>,
    side: OrderSide,
    #[serde(rename = "type")]
    order_type: OrderType,
    quantity: Option<Decimal>,
    quote_order_qty: Option<Decimal>,
    price: Option<Decimal>,
    stop_price: Option<Decimal>,
    /// A unique id among open orders. Automatically generated if not sent.
    new_client_order_id: Option<String>,
    /// Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
    iceberg_qty: Option<Decimal>,
    /// Default ACK; MARKET and LIMIT default to FULL.
    new_order_resp_type: Option<OrderResponseType>,
    side_effect_type: Option<SideEffectType>,
    time_in_force: Option<TimeInForce>,
    self_trade_prevention_mode: Option<STPMode>,
    /// Max 60000.
    recv_window: Option<i64>,
}

impl NewOrderRequest {
    pub fn new(symbol: impl Into<String>, side: OrderSide, order_type: OrderType) -> Self {
        Self {
            symbol: symbol.into(),
            side,
            order_type,
            is_isolated: None,
            quantity: None,
            quote_order_qty: None,
            price: None,
            stop_price: None,
            new_client_order_id: None,
            iceberg_qty: None,
            new_order_resp_type: None,
            side_effect_type: None,
            time_in_force: None,
            self_trade_prevention_mode: None,
            recv_window: None,
        }
    }

    pub fn is_isolated(mut self, value: IsIsolated) -> Self {
        self.is_isolated = Some(value);
        self
    }
    pub fn quantity(mut self, value: Decimal) -> Self {
        self.quantity = Some(value);
        self
    }
    pub fn quote_order_qty(mut self, value: Decimal) -> Self {
        self.quote_order_qty = Some(value);
        self
    }
    pub fn price(mut self, value: Decimal) -> Self {
        self.price = Some(value);
        self
    }
    pub fn stop_price(mut self, value: Decimal) -> Self {
        self.stop_price = Some(value);
        self
    }
    pub fn new_client_order_id(mut self, value: impl Into<String>) -> Self {
        self.new_client_order_id = Some(value.into());
        self
    }
    pub fn iceberg_qty(mut self, value: Decimal) -> Self {
        self.iceberg_qty = Some(value);
        self
    }
    pub fn new_order_resp_type(mut self, value: OrderResponseType) -> Self {
        self.new_order_resp_type = Some(value);
        self
    }
    pub fn side_effect_type(mut self, value: SideEffectType) -> Self {
        self.side_effect_type = Some(value);
        self
    }
    pub fn time_in_force(mut self, value: TimeInForce) -> Self {
        self.time_in_force = Some(value);
        self
    }
    pub fn self_trade_prevention_mode(mut self, value: STPMode) -> Self {
        self.self_trade_prevention_mode = Some(value);
        self
    }
    pub fn recv_window(mut self, value: i64) -> Self {
        self.recv_window = Some(value);
        self
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum NewOrderResponse {
    Full(NewOrderResponseFull),
    Result(NewOrderResponseResult),
    Ack(NewOrderResponseAck),
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderResponseAck {
    pub symbol: String,
    pub order_id: i64,
    pub client_order_id: String,
    pub transact_time: Timestamp,
    pub is_isolated: bool,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderResponseResult {
    pub symbol: String,
    pub order_id: i64,
    pub client_order_id: String,
    pub transact_time: Timestamp,
    pub price: Decimal,
    pub orig_qty: Decimal,
    pub executed_qty: Decimal,
    pub cummulative_quote_qty: Decimal,
    pub status: OrderStatus,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub side: OrderSide,
    pub margin_buy_borrow_amount: Option<Decimal>,
    pub margin_buy_borrow_asset: Option<String>,
    pub is_isolated: bool,
    pub self_trade_prevention_mode: STPMode,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderResponseFull {
    pub symbol: String,
    pub order_id: i64,
    pub client_order_id: String,
    pub transact_time: Timestamp,
    pub price: Decimal,
    pub orig_qty: Decimal,
    pub executed_qty: Decimal,
    pub cummulative_quote_qty: Decimal,
    pub status: OrderStatus,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub side: OrderSide,
    pub fills: Vec<OrderFill>,
    pub margin_buy_borrow_amount: Option<Decimal>,
    pub margin_buy_borrow_asset: Option<String>,
    pub is_isolated: bool,
    pub self_trade_prevention_mode: STPMode,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OrderFill {
    pub price: Decimal,
    pub qty: Decimal,
    pub commission: Decimal,
    pub commission_asset: String,
}

// ===== Query order =====

#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct QueryOrderParams {
    symbol: String,
    is_isolated: Option<IsIsolated>,
    order_id: Option<i64>,
    orig_client_order_id: Option<String>,
    recv_window: Option<i64>,
}

impl QueryOrderParams {
    pub fn new(symbol: impl Into<String>) -> Self {
        Self {
            symbol: symbol.into(),
            is_isolated: None,
            order_id: None,
            orig_client_order_id: None,
            recv_window: None,
        }
    }

    pub fn is_isolated(mut self, value: IsIsolated) -> Self {
        self.is_isolated = Some(value);
        self
    }
    pub fn order_id(mut self, value: i64) -> Self {
        self.order_id = Some(value);
        self
    }
    pub fn orig_client_order_id(mut self, value: impl Into<String>) -> Self {
        self.orig_client_order_id = Some(value.into());
        self
    }
    pub fn recv_window(mut self, value: i64) -> Self {
        self.recv_window = Some(value);
        self
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    pub symbol: String,
    pub order_id: i64,
    pub client_order_id: String,
    pub price: Decimal,
    pub orig_qty: Decimal,
    pub executed_qty: Decimal,
    pub cummulative_quote_qty: Decimal,
    pub status: OrderStatus,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub side: OrderSide,
    pub stop_price: Option<Decimal>,
    pub iceberg_qty: Option<Decimal>,
    pub time: Timestamp,
    pub update_time: Timestamp,
    pub is_working: bool,
    pub is_isolated: bool,
    pub self_trade_prevention_mode: STPMode,
}

// ===== Max borrowable =====

#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GetMaxBorrowableParams {
    asset: String,
    /// Required for isolated margin: the symbol whose isolated account to query.
    isolated_symbol: Option<String>,
    recv_window: Option<i64>,
}

impl GetMaxBorrowableParams {
    pub fn new(asset: impl Into<String>) -> Self {
        Self {
            asset: asset.into(),
            isolated_symbol: None,
            recv_window: None,
        }
    }

    pub fn isolated_symbol(mut self, value: impl Into<String>) -> Self {
        self.isolated_symbol = Some(value.into());
        self
    }
    pub fn recv_window(mut self, value: i64) -> Self {
        self.recv_window = Some(value);
        self
    }
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MaxBorrowable {
    pub amount: Decimal,
    /// Account's current borrow limit for the asset.
    pub borrow_limit: Decimal,
}

// ===== User data stream =====

/// Response from `POST /sapi/v1/userDataStream{,/isolated}`.
///
/// Use the returned `listen_key` to connect to
/// `wss://stream.binance.com:9443/ws/<listen_key>` and consume margin user
/// data events. Keys live for 60 minutes from creation/keepalive — call
/// `keepalive_listen_key` every 30 minutes to extend.
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ListenKey {
    pub listen_key: String,
}

/// Returned by keepalive and close operations on the user data stream
/// (`PUT` / `DELETE`). The body is an empty JSON object `{}`.
#[derive(Debug, Deserialize, PartialEq, Default)]
pub struct EmptyResponse {}

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

    #[test]
    fn deserialize_listen_key() {
        let json =
            r#"{"listenKey":"pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"}"#;
        let parsed: ListenKey = deserialize_json(json).unwrap();
        assert_eq!(parsed.listen_key.len(), 64);
    }

    #[test]
    fn deserialize_empty_response() {
        let json = r#"{}"#;
        let parsed: EmptyResponse = deserialize_json(json).unwrap();
        assert_eq!(parsed, EmptyResponse {});
    }
}