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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
* Binance Derivatives Trading COIN Futures WebSocket API
*
* OpenAPI Specification for the Binance Derivatives Trading COIN Futures WebSocket API
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#![allow(unused_imports)]
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::{collections::BTreeMap, sync::Arc};
use crate::common::config::ConfigurationWebsocketApi;
use crate::common::models::WebsocketApiResponse;
use crate::common::utils::random_string;
use crate::common::websocket::{
Subscription, WebsocketApi as WebsocketApiBase, WebsocketBase, WebsocketMessageSendOptions,
WebsocketStream, create_stream_handler,
};
use crate::errors::WebsocketError;
use crate::models::{WebsocketEvent, WebsocketMode};
mod apis;
mod handle;
mod models;
pub use apis::*;
pub use handle::*;
pub use models::*;
const HAS_TIME_UNIT: bool = false;
#[derive(Clone)]
pub struct WebsocketApi {
websocket_api_base: Arc<WebsocketApiBase>,
account_api_client: AccountApiClient,
trade_api_client: TradeApiClient,
user_data_streams_api_client: UserDataStreamsApiClient,
}
impl WebsocketApi {
pub(crate) async fn connect(
config: ConfigurationWebsocketApi,
mode: Option<WebsocketMode>,
) -> anyhow::Result<Self> {
let mut cfg = config;
if let Some(m) = mode {
cfg.mode = m;
}
if !HAS_TIME_UNIT {
cfg.time_unit = None;
}
let websocket_api_base = WebsocketApiBase::new(cfg, vec![]);
websocket_api_base.clone().connect().await?;
Ok(Self {
websocket_api_base: websocket_api_base.clone(),
account_api_client: AccountApiClient::new(websocket_api_base.clone()),
trade_api_client: TradeApiClient::new(websocket_api_base.clone()),
user_data_streams_api_client: UserDataStreamsApiClient::new(websocket_api_base.clone()),
})
}
/// Subscribes to WebSocket events with a provided callback function.
///
/// # Arguments
///
/// * `callback` - A mutable function that will be called when a WebSocket event is received.
/// The callback takes a `WebsocketEvent` as its parameter.
///
/// # Returns
///
/// A `Subscription` that can be used to manage the event subscription.
///
/// # Examples
///
///
/// let subscription = `websocket_api.subscribe_on_ws_events(|event`| {
/// // Handle WebSocket event
/// });
///
pub fn subscribe_on_ws_events<F>(&self, callback: F) -> Subscription
where
F: FnMut(WebsocketEvent) + Send + 'static,
{
let base = Arc::clone(&self.websocket_api_base);
base.common.events.subscribe(callback)
}
/// Unsubscribes from WebSocket events using the provided `Subscription`.
///
/// # Arguments
///
/// * `subscription` - The `Subscription` to unsubscribe from WebSocket events.
///
/// # Examples
///
///
/// let subscription = `websocket_api.subscribe_on_ws_events(|event`| {
/// // Handle WebSocket event
/// });
/// `websocket_api.unsubscribe_from_ws_events(subscription)`;
///
pub fn unsubscribe_from_ws_events(&self, subscription: Subscription) {
subscription.unsubscribe();
}
/// Disconnects the WebSocket connection.
///
/// # Returns
///
/// A `Result` indicating whether the disconnection was successful.
/// Returns an error if the disconnection fails.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the connection fails.
///
/// # Examples
///
///
/// let result = `websocket_api.disconnect().await`;
///
pub async fn disconnect(&self) -> anyhow::Result<()> {
self.websocket_api_base
.disconnect()
.await
.map_err(anyhow::Error::msg)
}
/// Sends a ping message to the WebSocket server to check the connection status.
///
/// # Examples
///
///
/// `websocket_api.ping_server().await`;
///
///
/// This method sends a lightweight ping request to verify the WebSocket connection is still active.
pub async fn ping_server(&self) {
self.websocket_api_base.ping_server().await;
}
/// Checks if the WebSocket connection is currently active.
///
/// # Returns
///
/// A `bool` indicating whether the WebSocket connection is established and active.
///
/// # Examples
///
///
/// let `is_active` = `websocket_api.is_connected().await`;
/// if `is_active` {
/// // WebSocket connection is active
/// }
///
///
/// This method provides a way to check the current status of the WebSocket connection.
pub async fn is_connected(&self) -> bool {
self.websocket_api_base.is_connected().await
}
/// Sends an unsigned WebSocket message with the specified method and payload.
///
/// # Type Parameters
///
/// * `R` - The response type to deserialize the message into.
///
/// # Arguments
///
/// * `method` - The WebSocket method to invoke.
/// * `payload` - A map of key-value pairs representing the message payload.
///
/// # Returns
///
/// A `Result` containing the deserialized response or a `WebsocketError`.
///
/// # Errors
///
/// Returns a `WebsocketError` if the WebSocket connection fails or the response cannot be deserialized.
///
/// # Examples
///
///
/// let response = `websocket_api.send_message::`<ResponseType>("`method_name`", payload).await;
///
pub async fn send_message<R: DeserializeOwned + Send + Sync + 'static>(
&self,
method: &str,
payload: BTreeMap<String, Value>,
) -> Result<WebsocketApiResponse<R>, WebsocketError> {
self.websocket_api_base
.send_message::<R>(method, payload, WebsocketMessageSendOptions::new())
.await?
.into_iter()
.next()
.ok_or(WebsocketError::NoResponse)
}
/// Sends a signed WebSocket message with the specified method and payload.
///
/// # Type Parameters
///
/// * `R` - The response type to deserialize the message into.
///
/// # Arguments
///
/// * `method` - The WebSocket method to invoke.
/// * `payload` - A map of key-value pairs representing the message payload.
///
/// # Returns
///
/// A `Result` containing the deserialized response or a `WebsocketError`.
///
/// # Errors
///
/// Returns a `WebsocketError` if the WebSocket connection fails or the response cannot be deserialized.
///
/// # Examples
///
///
/// let response = `websocket_api.send_signed_message::`<ResponseType>("`method_name`", payload).await;
///
pub async fn send_signed_message<R: DeserializeOwned + Send + Sync + 'static>(
&self,
method: &str,
payload: BTreeMap<String, Value>,
) -> Result<WebsocketApiResponse<R>, WebsocketError> {
self.websocket_api_base
.send_message::<R>(method, payload, WebsocketMessageSendOptions::new().signed())
.await?
.into_iter()
.next()
.ok_or(WebsocketError::NoResponse)
}
/// Account `Information(USER_DATA)`
///
/// Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.
///
/// Weight: 5
///
/// # Arguments
///
/// - `params`: [`AccountInformationParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::AccountInformationResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/account/websocket-api/Account-Information).
///
pub async fn account_information(
&self,
params: AccountInformationParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::AccountInformationResponseResult>>> {
self.account_api_client.account_information(params).await
}
/// Futures Account `Balance(USER_DATA)`
///
/// Query account balance info
///
/// Weight: 5
///
/// # Arguments
///
/// - `params`: [`FuturesAccountBalanceParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Vec<models::FuturesAccountBalanceResponseResultInner>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/account/websocket-api/Futures-Account-Balance).
///
pub async fn futures_account_balance(
&self,
params: FuturesAccountBalanceParams,
) -> anyhow::Result<WebsocketApiResponse<Vec<models::FuturesAccountBalanceResponseResultInner>>>
{
self.account_api_client
.futures_account_balance(params)
.await
}
/// Cancel Order (TRADE)
///
/// Cancel an active order.
///
/// * Either `orderId` or `origClientOrderId` must be sent.
///
/// Weight: 1
///
/// # Arguments
///
/// - `params`: [`CancelOrderParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::CancelOrderResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Cancel-Order).
///
pub async fn cancel_order(
&self,
params: CancelOrderParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::CancelOrderResponseResult>>> {
self.trade_api_client.cancel_order(params).await
}
/// Modify Order (TRADE)
///
/// Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue
///
/// * Either `orderId` or `origClientOrderId` must be sent, and the `orderId` will prevail if both are sent.
/// * Both `quantity` and `price` must be sent, which is different from dapi modify order endpoint.
/// * When the new `quantity` or `price` doesn't satisfy `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE`, amendment will be rejected and the order will stay as it is.
/// * However the order will be cancelled by the amendment in the following situations:
/// * when the order is in partially filled status and the new `quantity` <= `executedQty`
/// * When the order is `GTX` and the new price will cause it to be executed immediately
/// * One order can only be modfied for less than 10000 times
///
/// Weight: 1 on 10s order rate limit(X-MBX-ORDER-COUNT-10S);
/// 1 on 1min order rate limit(X-MBX-ORDER-COUNT-1M);
/// 1 on IP rate limit(x-mbx-used-weight-1m)
///
/// # Arguments
///
/// - `params`: [`ModifyOrderParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::ModifyOrderResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Modify-Order).
///
pub async fn modify_order(
&self,
params: ModifyOrderParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::ModifyOrderResponseResult>>> {
self.trade_api_client.modify_order(params).await
}
/// New Order(TRADE)
///
/// Send in a new order.
///
/// * Order with type `STOP`, parameter `timeInForce` can be sent ( default `GTC`).
/// * Order with type `TAKE_PROFIT`, parameter `timeInForce` can be sent ( default `GTC`).
/// * Condition orders will be triggered when:
/// * If parameter `priceProtect` is sent as true:
/// * when price reaches the `stopPrice`,the difference rate between "`MARK_PRICE`" and "`CONTRACT_PRICE`" cannot be larger than the "triggerProtect" of the symbol
/// * "triggerProtect" of a symbol can be got from `GET /dapi/v1/exchangeInfo`
/// * `STOP`, `STOP_MARKET`:
/// * BUY: latest price ("`MARK_PRICE`" or "`CONTRACT_PRICE`") >= `stopPrice`
/// * SELL: latest price ("`MARK_PRICE`" or "`CONTRACT_PRICE`") <= `stopPrice`
/// * `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`:
/// * BUY: latest price ("`MARK_PRICE`" or "`CONTRACT_PRICE`") <= `stopPrice`
/// * SELL: latest price ("`MARK_PRICE`" or "`CONTRACT_PRICE`") >= `stopPrice`
/// * `TRAILING_STOP_MARKET`:
/// * BUY: the lowest price after order placed <= `activationPrice`, and the latest price >= the lowest price * (1 + `callbackRate`)
/// * SELL: the highest price after order placed >= `activationPrice`, and the latest price <= the highest price * (1 - `callbackRate`)
/// * For `TRAILING_STOP_MARKET`, if you got such error code.
/// * BUY: `activationPrice` should be smaller than latest price.
/// * SELL: `activationPrice` should be larger than latest price.
/// * If `newOrderRespType` is sent as `RESULT`:
/// * `MARKET` order: the final FILLED result of the order will be return directly.
/// * `LIMIT` order with special `timeInForce`: the final status result of the order(FILLED or EXPIRED) will be returned directly.
/// * `STOP_MARKET`, `TAKE_PROFIT_MARKET` with `closePosition=true`:
/// * Follow the same rules for condition orders.
/// * If triggered,**close all** current long position(if `SELL`) or current short position(if `BUY`).
/// * Cannot be used with `quantity` parameter
/// * Cannot be used with `reduceOnly` parameter
/// * In Hedge Mode, cannot be used with `BUY` orders in `LONG` position side. and cannot be used with `SELL` orders in `SHORT` position side
///
/// Weight: 0
///
/// # Arguments
///
/// - `params`: [`NewOrderParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::NewOrderResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/New-Order).
///
pub async fn new_order(
&self,
params: NewOrderParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::NewOrderResponseResult>>> {
self.trade_api_client.new_order(params).await
}
/// Position `Information(USER_DATA)`
///
/// Get current position information.
///
/// * Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and accuracy needs.
///
/// Weight: 5
///
/// # Arguments
///
/// - `params`: [`PositionInformationParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Vec<models::PositionInformationResponseResultInner>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Position-Information).
///
pub async fn position_information(
&self,
params: PositionInformationParams,
) -> anyhow::Result<WebsocketApiResponse<Vec<models::PositionInformationResponseResultInner>>>
{
self.trade_api_client.position_information(params).await
}
/// Query Order (`USER_DATA`)
///
/// Check an order's status.
///
/// * These orders will not be found:
/// * order status is `CANCELED` or `EXPIRED` **AND** order has NO filled trade **AND** created time + 3 days < current time
/// * order create time + 90 days < current time
///
/// * Either `orderId` or `origClientOrderId` must be sent.
/// * `orderId` is self-increment for each specific `symbol`
///
/// Weight: 1
///
/// # Arguments
///
/// - `params`: [`QueryOrderParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::QueryOrderResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/websocket-api/Query-Order).
///
pub async fn query_order(
&self,
params: QueryOrderParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::QueryOrderResponseResult>>> {
self.trade_api_client.query_order(params).await
}
/// Close User Data Stream (`USER_STREAM`)
///
/// Close out a user data stream.
///
/// Weight: 1
///
/// # Arguments
///
/// - `params`: [`CloseUserDataStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<serde_json::Value>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Close-User-Data-Stream-Wsp).
///
pub async fn close_user_data_stream(
&self,
params: CloseUserDataStreamParams,
) -> anyhow::Result<WebsocketApiResponse<serde_json::Value>> {
self.user_data_streams_api_client
.close_user_data_stream(params)
.await
}
/// Keepalive User Data Stream (`USER_STREAM`)
///
/// Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 60 minutes.
///
/// Weight: 1
///
/// # Arguments
///
/// - `params`: [`KeepaliveUserDataStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::KeepaliveUserDataStreamResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Keepalive-User-Data-Stream-Wsp).
///
pub async fn keepalive_user_data_stream(
&self,
params: KeepaliveUserDataStreamParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::KeepaliveUserDataStreamResponseResult>>>
{
self.user_data_streams_api_client
.keepalive_user_data_stream(params)
.await
}
/// Start User Data Stream (`USER_STREAM`)
///
/// Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes.
///
/// Weight: 1
///
/// # Arguments
///
/// - `params`: [`StartUserDataStreamParams`]
/// The parameters for this operation.
///
/// # Returns
///
/// [`WebsocketApiResponse<Box<models::StartUserDataStreamResponseResult>>`] on success.
///
/// # Errors
///
/// Returns an [`anyhow::Error`] if the WebSocket request fails, if parameters are invalid, or if parsing the response fails.
///
///
/// For full API details, see the [Binance API Documentation](https://developers.binance.com/docs/derivatives/coin-margined-futures/user-data-streams/Start-User-Data-Stream-Wsp).
///
pub async fn start_user_data_stream(
&self,
params: StartUserDataStreamParams,
) -> anyhow::Result<WebsocketApiResponse<Box<models::StartUserDataStreamResponseResult>>> {
self.user_data_streams_api_client
.start_user_data_stream(params)
.await
}
}