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
//!
//! The Binance HTTP adapter.
//!

pub mod error;
pub mod response;

use hmac::Hmac;
use hmac::Mac;
use hmac::NewMac;
use reqwest::Method;
use reqwest::Url;
use sha2::Sha256;

use crate::data::account::get::request::Query as AccountGetQuery;
use crate::data::account::get::response::Response as AccountGetResponse;
use crate::data::depth::get::request::Query as DepthGetQuery;
use crate::data::depth::get::response::Response as DepthGetResponse;
use crate::data::exchange_info::get::response::Response as ExchangeInfoGetResponse;
use crate::data::klines::get::request::Query as KlinesGetQuery;
use crate::data::klines::get::response::Response as KlinesGetResponse;
use crate::data::open_orders::delete::request::Query as OpenOrdersDeleteQuery;
use crate::data::open_orders::delete::response::Response as OpenOrdersDeleteResponse;
use crate::data::open_orders::get::request::Query as OpenOrdersGetQuery;
use crate::data::open_orders::get::response::Response as OpenOrdersGetResponse;
use crate::data::order::delete::request::Query as OrderDeleteQuery;
use crate::data::order::delete::response::Response as OrderDeleteResponse;
use crate::data::order::get::request::Query as OrderGetQuery;
use crate::data::order::get::response::Response as OrderGetResponse;
use crate::data::order::post::request::Query as OrderPostQuery;
use crate::data::order::post::response::Response as OrderPostResponse;
use crate::data::time::get::response::Response as TimeGetResponse;

use self::error::Error;
use self::response::Response;

///
/// The Binance HTTP client.
///
#[derive(Debug, Clone)]
pub struct Client {
    /// The inner HTTP client.
    inner: reqwest::Client,
    /// The Binance authorization API key.
    api_key: Option<String>,
    /// The Binance authorization secret key.
    secret_key: Option<String>,
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

type Result<T> = ::std::result::Result<T, Error>;

impl Client {
    /// The Binance API base URL.
    const BASE_URL: &'static str = "https://api.binance.com";

    ///
    /// Creates an unauthorized client instance.
    ///
    pub fn new() -> Self {
        Self {
            inner: reqwest::Client::new(),
            api_key: None,
            secret_key: None,
        }
    }

    ///
    /// Creates an authorized client instance.
    ///
    pub fn new_with_auth(api_key: String, secret_key: String) -> Self {
        Self {
            inner: reqwest::Client::new(),
            api_key: Some(api_key),
            secret_key: Some(secret_key),
        }
    }

    ///
    /// Test connectivity to the Rest API.
    ///
    pub fn ping(&self) -> Result<()> {
        self.execute::<()>(Method::GET, "/api/v3/ping".to_owned())
    }

    ///
    /// Test connectivity to the Rest API and get the current server time.
    ///
    pub fn time(&self) -> Result<TimeGetResponse> {
        self.execute::<TimeGetResponse>(Method::GET, "/api/v3/time".to_owned())
    }

    ///
    /// Current exchange trading rules and symbol information.
    ///
    pub fn exchange_info(&self) -> Result<ExchangeInfoGetResponse> {
        self.execute::<ExchangeInfoGetResponse>(Method::GET, "/api/v3/exchangeInfo".to_owned())
    }

    ///
    /// Kline/candlestick bars for a symbol.
    /// Klines are uniquely identified by their open time.
    ///
    pub fn klines(&self, request: KlinesGetQuery) -> Result<KlinesGetResponse> {
        self.execute::<KlinesGetResponse>(
            Method::GET,
            format!("/api/v3/klines?{}", request.to_string()),
        )
    }

    ///
    /// The real-time market depth.
    ///
    pub fn depth(&self, request: DepthGetQuery) -> Result<DepthGetResponse> {
        self.execute::<DepthGetResponse>(
            Method::GET,
            format!("/api/v3/depth?{}", request.to_string()),
        )
    }

    ///
    /// Get the account info and balances.
    ///
    pub fn account_get(&self, request: AccountGetQuery) -> Result<AccountGetResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<AccountGetResponse>(
            Method::GET,
            format!("/api/v3/account?{}", params),
        )
    }

    ///
    /// Get the account open orders.
    ///
    pub fn open_orders_get(&self, request: OpenOrdersGetQuery) -> Result<OpenOrdersGetResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OpenOrdersGetResponse>(
            Method::GET,
            format!("/api/v3/openOrders?{}", params),
        )
    }

    ///
    /// Delete the account open orders.
    ///
    pub fn open_orders_delete(
        &self,
        request: OpenOrdersDeleteQuery,
    ) -> Result<OpenOrdersDeleteResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OpenOrdersDeleteResponse>(
            Method::DELETE,
            format!("/api/v3/openOrders?{}", params),
        )
    }

    ///
    /// Check an order's status.
    ///
    pub fn order_get(&self, request: OrderGetQuery) -> Result<OrderGetResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OrderGetResponse>(Method::GET, format!("/api/v3/order?{}", params))
    }

    ///
    /// Send in a new order.
    ///
    pub fn order_post(&self, request: OrderPostQuery) -> Result<OrderPostResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OrderPostResponse>(Method::POST, format!("/api/v3/order?{}", params))
    }

    ///
    /// Cancel an active order.
    ///
    pub fn order_delete(&self, request: OrderDeleteQuery) -> Result<OrderDeleteResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OrderDeleteResponse>(
            Method::DELETE,
            format!("/api/v3/order?{}", params),
        )
    }

    ///
    /// Test new order creation and signature/recvWindow long.
    /// Creates and validates a new order but does not send it into the matching engine.
    ///
    pub fn order_post_test(&self, request: OrderPostQuery) -> Result<OrderPostResponse> {
        let secret_key = self
            .secret_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let mut params = request.to_string();
        params += &format!("&signature={}", Self::signature(&params, secret_key));

        self.execute_signed::<OrderPostResponse>(
            Method::POST,
            format!("/api/v3/order/test?{}", params),
        )
    }

    ///
    /// Executes an unauthorized request.
    ///
    fn execute<T>(&self, method: Method, url: String) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let url = Self::BASE_URL.to_owned() + url.as_str();

        let response = self
            .inner
            .execute(
                self.inner
                    .request(
                        method,
                        Url::parse(&url).map_err(|error| Error::UrlParsing(error, url))?,
                    )
                    .build()
                    .map_err(Error::RequestBuilding)?,
            )
            .map_err(Error::RequestExecution)?
            .text()
            .map_err(Error::ResponseReading)?;
        let response: Response<T> = serde_json::from_str(response.as_str())
            .map_err(|error| Error::ResponseParsing(error, response))?;

        match response {
            Response::Ok(response) => Ok(response),
            Response::Error(error) => Err(Error::ResponseError(error)),
        }
    }

    ///
    /// Executes an authorized request.
    ///
    fn execute_signed<T>(&self, method: Method, url: String) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let api_key = self
            .api_key
            .as_ref()
            .ok_or(Error::AuthorizationKeysMissing)?;

        let url = Self::BASE_URL.to_owned() + url.as_str();

        let response = self
            .inner
            .execute(
                self.inner
                    .request(
                        method,
                        Url::parse(&url).map_err(|error| Error::UrlParsing(error, url))?,
                    )
                    .header("X-MBX-APIKEY", api_key.to_owned())
                    .build()
                    .map_err(Error::RequestBuilding)?,
            )
            .map_err(Error::RequestExecution)?
            .text()
            .map_err(Error::ResponseReading)?;
        let response: Response<T> = serde_json::from_str(response.as_str())
            .map_err(|error| Error::ResponseParsing(error, response))?;

        match response {
            Response::Ok(response) => Ok(response),
            Response::Error(error) => Err(Error::ResponseError(error)),
        }
    }

    ///
    /// Generates an HMAC signature for authorized requests.
    ///
    fn signature(params: &str, secret_key: &str) -> String {
        hex::encode(
            {
                let mut hmac: Hmac<Sha256> =
                    Hmac::new_varkey(secret_key.as_bytes()).expect(crate::panic::HMAC_ALWAYS_VALID);
                hmac.update(params.as_bytes());
                hmac.finalize().into_bytes()
            }
            .to_vec(),
        )
    }
}