binance-sdk 44.0.1

This is a lightweight library that works as a connector to the Binance public API.
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
/*
 * Binance Derivatives Trading Options REST API
 *
 * OpenAPI Specification for the Binance Derivatives Trading Options REST 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 async_trait::async_trait;
use derive_builder::Builder;
use reqwest;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;

use crate::common::{
    config::ConfigurationRestApi,
    models::{ParamBuildError, RestApiResponse},
    utils::send_request,
};
use crate::derivatives_trading_options::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait AccountApi: Send + Sync {
    async fn account_funding_flow(
        &self,
        params: AccountFundingFlowParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::AccountFundingFlowResponseInner>>>;
    async fn option_margin_account_information(
        &self,
        params: OptionMarginAccountInformationParams,
    ) -> anyhow::Result<RestApiResponse<models::OptionMarginAccountInformationResponse>>;
}

#[derive(Debug, Clone)]
pub struct AccountApiClient {
    configuration: ConfigurationRestApi,
}

impl AccountApiClient {
    pub fn new(configuration: ConfigurationRestApi) -> Self {
        Self { configuration }
    }
}

/// Request parameters for the [`account_funding_flow`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`account_funding_flow`](#method.account_funding_flow).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct AccountFundingFlowParams {
    /// Asset type, only support USDT  as of now
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub currency: String,
    /// Return the recordId and subsequent data, the latest data is returned by default, e.g 100000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub record_id: Option<i64>,
    /// Start Time, e.g 1593511200000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    /// End Time, e.g 1593512200000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Number of result sets returned Default:100 Max:1000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl AccountFundingFlowParams {
    /// Create a builder for [`account_funding_flow`].
    ///
    /// Required parameters:
    ///
    /// * `currency` — Asset type, only support USDT  as of now
    ///
    #[must_use]
    pub fn builder(currency: String) -> AccountFundingFlowParamsBuilder {
        AccountFundingFlowParamsBuilder::default().currency(currency)
    }
}
/// Request parameters for the [`option_margin_account_information`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`option_margin_account_information`](#method.option_margin_account_information).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct OptionMarginAccountInformationParams {
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl OptionMarginAccountInformationParams {
    /// Create a builder for [`option_margin_account_information`].
    ///
    #[must_use]
    pub fn builder() -> OptionMarginAccountInformationParamsBuilder {
        OptionMarginAccountInformationParamsBuilder::default()
    }
}

#[async_trait]
impl AccountApi for AccountApiClient {
    async fn account_funding_flow(
        &self,
        params: AccountFundingFlowParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::AccountFundingFlowResponseInner>>> {
        let AccountFundingFlowParams {
            currency,
            record_id,
            start_time,
            end_time,
            limit,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("currency".to_string(), json!(currency));

        if let Some(rw) = record_id {
            query_params.insert("recordId".to_string(), json!(rw));
        }

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<Vec<models::AccountFundingFlowResponseInner>>(
            &self.configuration,
            "/eapi/v1/bill",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn option_margin_account_information(
        &self,
        params: OptionMarginAccountInformationParams,
    ) -> anyhow::Result<RestApiResponse<models::OptionMarginAccountInformationResponse>> {
        let OptionMarginAccountInformationParams { recv_window } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::OptionMarginAccountInformationResponse>(
            &self.configuration,
            "/eapi/v1/marginAccount",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "derivatives_trading_options"))]
mod tests {
    use super::*;
    use crate::TOKIO_SHARED_RT;
    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
    use async_trait::async_trait;
    use std::collections::HashMap;

    struct DummyRestApiResponse<T> {
        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
        status: u16,
        headers: HashMap<String, String>,
        rate_limits: Option<Vec<RestApiRateLimit>>,
    }

    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
        fn from(dummy: DummyRestApiResponse<T>) -> Self {
            Self {
                data_fn: dummy.inner,
                status: dummy.status,
                headers: dummy.headers,
                rate_limits: dummy.rate_limits,
            }
        }
    }

    struct MockAccountApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl AccountApi for MockAccountApiClient {
        async fn account_funding_flow(
            &self,
            _params: AccountFundingFlowParams,
        ) -> anyhow::Result<RestApiResponse<Vec<models::AccountFundingFlowResponseInner>>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"id":1125899906842624000,"asset":"USDT","amount":"-0.552","type":"FEE","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"100","type":"CONTRACT","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"10000","type":"TRANSFER","createDate":1592448410000}]"#).unwrap();
            let dummy_response: Vec<models::AccountFundingFlowResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::AccountFundingFlowResponseInner>");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn option_margin_account_information(
            &self,
            _params: OptionMarginAccountInformationParams,
        ) -> anyhow::Result<RestApiResponse<models::OptionMarginAccountInformationResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"asset":[{"asset":"USDT","marginBalance":"99998.87365244","equity":"99998.87365244","available":"96883.72734374","initialMargin":"3115.14630870","maintMargin":"0.00000000","unrealizedPNL":"0.00000000","adjustedEquity":"99998.87365244"}],"greek":[{"underlying":"BTCUSDT","delta":"0","theta":"0","gamma":"0","vega":"0"}],"time":1762843368098,"canTrade":true,"canDeposit":true,"canWithdraw":true,"reduceOnly":false,"tradeGroupId":-1}"#).unwrap();
            let dummy_response: models::OptionMarginAccountInformationResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::OptionMarginAccountInformationResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }
    }

    #[test]
    fn account_funding_flow_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: false };

            let params = AccountFundingFlowParams::builder("currency_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"id":1125899906842624000,"asset":"USDT","amount":"-0.552","type":"FEE","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"100","type":"CONTRACT","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"10000","type":"TRANSFER","createDate":1592448410000}]"#).unwrap();
            let expected_response : Vec<models::AccountFundingFlowResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::AccountFundingFlowResponseInner>");

            let resp = client.account_funding_flow(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn account_funding_flow_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: false };

            let params = AccountFundingFlowParams::builder("currency_example".to_string(),).record_id(1).start_time(1623319461670).end_time(1641782889000).limit(100).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"id":1125899906842624000,"asset":"USDT","amount":"-0.552","type":"FEE","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"100","type":"CONTRACT","createDate":1592449456000},{"id":1125899906842624000,"asset":"USDT","amount":"10000","type":"TRANSFER","createDate":1592448410000}]"#).unwrap();
            let expected_response : Vec<models::AccountFundingFlowResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::AccountFundingFlowResponseInner>");

            let resp = client.account_funding_flow(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn account_funding_flow_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: true };

            let params = AccountFundingFlowParams::builder("currency_example".to_string())
                .build()
                .unwrap();

            match client.account_funding_flow(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn option_margin_account_information_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: false };

            let params = OptionMarginAccountInformationParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"asset":[{"asset":"USDT","marginBalance":"99998.87365244","equity":"99998.87365244","available":"96883.72734374","initialMargin":"3115.14630870","maintMargin":"0.00000000","unrealizedPNL":"0.00000000","adjustedEquity":"99998.87365244"}],"greek":[{"underlying":"BTCUSDT","delta":"0","theta":"0","gamma":"0","vega":"0"}],"time":1762843368098,"canTrade":true,"canDeposit":true,"canWithdraw":true,"reduceOnly":false,"tradeGroupId":-1}"#).unwrap();
            let expected_response : models::OptionMarginAccountInformationResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::OptionMarginAccountInformationResponse");

            let resp = client.option_margin_account_information(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn option_margin_account_information_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: false };

            let params = OptionMarginAccountInformationParams::builder().recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"asset":[{"asset":"USDT","marginBalance":"99998.87365244","equity":"99998.87365244","available":"96883.72734374","initialMargin":"3115.14630870","maintMargin":"0.00000000","unrealizedPNL":"0.00000000","adjustedEquity":"99998.87365244"}],"greek":[{"underlying":"BTCUSDT","delta":"0","theta":"0","gamma":"0","vega":"0"}],"time":1762843368098,"canTrade":true,"canDeposit":true,"canWithdraw":true,"reduceOnly":false,"tradeGroupId":-1}"#).unwrap();
            let expected_response : models::OptionMarginAccountInformationResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::OptionMarginAccountInformationResponse");

            let resp = client.option_margin_account_information(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn option_margin_account_information_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockAccountApiClient { force_error: true };

            let params = OptionMarginAccountInformationParams::builder()
                .build()
                .unwrap();

            match client.option_margin_account_information(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }
}