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
use time;
use std;
use std::str;
use hmac::{Hmac, Mac, MacResult};
use sha2::Sha512;
use generic_array::typenum::U64;
use serde;
use reqwest::{Client, Proxy};
use reqwest::header::Headers;

use error::{ BittrexError, BittrexErrorType };
use values::*;

const API_URL: &str = "https://bittrex.com/api/v1.1";

pub type Result<T> = std::result::Result<T, BittrexError>;

pub struct BittrexClient {
    api_url: String,
    api_key: String,
    api_secret: String,
    http_proxy: Option<String>,
    https_proxy: Option<String>
}

impl BittrexClient {
    pub fn new(api_key: String, api_secret: String) -> Self {
        BittrexClient { api_url: API_URL.to_string(), api_key: api_key, api_secret: api_secret, http_proxy: None, https_proxy: None }
    }

    pub fn new_override_api_url(api_key: String, api_secret: String, api_url: String) -> Self {
        BittrexClient { api_url: api_url, api_key: api_key, api_secret: api_secret, http_proxy: None, https_proxy: None }
    }

    pub fn new_with_proxy(api_key: String, api_secret: String, http_proxy: Option<String>, https_proxy: Option<String>) -> Self {
        BittrexClient { api_url: API_URL.to_string(), api_key: api_key, api_secret: api_secret, http_proxy: http_proxy, https_proxy: https_proxy }
    }

    /// Returns all available market data
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let markets = bittrex_client.get_markets().unwrap();
    /// ```
    pub fn get_markets(&self) -> Result<Vec<BittrexMarket>> {
        let markets = self.call_public_api::<BittrexAPIVecResult<BittrexMarket>>(&format!("{}/public/getmarkets", self.api_url))?;
        self.check_return_vec_response(markets)
    }

    /// Returns all available currencies
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let currencies = bittrex_client.get_currencies().unwrap();
    /// ```
    pub fn get_currencies(&self) -> Result<Vec<BittrexCurrency>> {
        let currencies = self.call_public_api::<BittrexAPIVecResult<BittrexCurrency>>(&format!("{}/public/getcurrencies", self.api_url))?;
        self.check_return_vec_response(currencies)
    }

    /// Returns ticker by market name
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let ticker = bittrex_client.get_ticker("BTC-LTC").unwrap();
    /// ```
    pub fn get_ticker(&self, market: &str) -> Result<BittrexTicker> {
        let ticker = self.call_public_api::<BittrexAPIResult<BittrexTicker>>(&format!("{}/public/getticker?market={}", self.api_url, market))?;
        self.check_return_single_response(ticker)        
    }

    /// Returns all market summaries
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let summaries = bittrex_client.get_market_summaries().unwrap();
    /// ```
    pub fn get_market_summaries(&self) -> Result<Vec<BittrexMarketSummary>> {
        let summaries = self.call_public_api::<BittrexAPIVecResult<BittrexMarketSummary>>(&format!("{}/public/getmarketsummaries", self.api_url))?;
        self.check_return_vec_response(summaries)
    }

    /// Returns market summary by market name
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let summary = bittrex_client.get_market_summary("BTC-LTC").unwrap();
    /// ```
    pub fn get_market_summary(&self, market: &str) -> Result<BittrexMarketSummary> {
        let summary = self.call_public_api::<BittrexAPIVecResult<BittrexMarketSummary>>(&format!("{}/public/getmarketsummary?market={}", self.api_url, market))?;
        self.check_return_single_vec_response(summary)
    }

    /// Returns the order book of the given market.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    /// use bittrex_api::values::BittrexOrderType;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let order_book = bittrex_client.get_order_book("BTC-LTC", BittrexOrderType::Both).unwrap();
    /// ```
    pub fn get_order_book(&self, market: &str, book_type: BittrexOrderType) -> Result<BittrexPublicOrderBook> {
        let order_book = self.call_public_api::<BittrexAPIResult<BittrexPublicOrderBook>>(&format!("{}/public/getorderbook?market={}&type={}", self.api_url, market, book_type))?;
        self.check_return_single_response(order_book)
    }

    /// Returns the market history of the given market.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let market_history = bittrex_client.get_market_history("BTC-LTC").unwrap();
    /// ```
    pub fn get_market_history(&self, market: &str) -> Result<Vec<BittrexTrade>> {
        let market_history = self.call_public_api::<BittrexAPIVecResult<BittrexTrade>>(&format!("{}/public/getmarkethistory?market={}", self.api_url, market))?;
        self.check_return_vec_response(market_history)
    }

    /// Returns the open orders of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let open_orders = bittrex_client.get_open_orders().unwrap();
    /// ```
    pub fn get_open_orders(&self) -> Result<Vec<BittrexOpenOrder>> {
        let open_orders = self.call_private_api::<BittrexAPIVecResult<BittrexOpenOrder>>(&format!("{}/market/getopenorders?", self.api_url))?;
        self.check_return_vec_response(open_orders)
    }

    /// Returns the open orders of the given market and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let open_orders = bittrex_client.get_open_orders_by_market("BTC-LTC").unwrap();
    /// ```
    pub fn get_open_orders_by_market(&self, market: &str) -> Result<Vec<BittrexOpenOrder>> {
        let open_orders = self.call_private_api::<BittrexAPIVecResult<BittrexOpenOrder>>(&format!("{}/market/getopenorders?market={}", self.api_url, market))?;
        self.check_return_vec_response(open_orders)
    }

    /// Returns the order given by the order_id.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let order = bittrex_client.get_order("ORDERID").unwrap();
    /// ```
    pub fn get_order(&self, order_id: &str) -> Result<BittrexOrder> {
        let order = self.call_private_api::<BittrexAPIResult<BittrexOrder>>(&format!("{}/account/getorder?uuid={}", self.api_url, order_id))?;
        self.check_return_single_response(order)
    }

    /// Returns the order history of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let order_history = bittrex_client.get_order_history().unwrap();
    /// ```
    pub fn get_order_history(&self) -> Result<Vec<BittrexHistoryOrder>> {
        let order_history = self.call_private_api::<BittrexAPIVecResult<BittrexHistoryOrder>>(&format!("{}/account/getorderhistory?", self.api_url))?;
        self.check_return_vec_response(order_history)
    }

    /// Returns the order history of the given market and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let order_history = bittrex_client.get_order_history_by_market("BTC-LTC").unwrap();
    /// ```
    pub fn get_order_history_by_market(&self, market: &str) -> Result<Vec<BittrexHistoryOrder>> {
        let order_history = self.call_private_api::<BittrexAPIVecResult<BittrexHistoryOrder>>(&format!("{}/account/getorderhistory?market={}", self.api_url, market))?;
        self.check_return_vec_response(order_history)
    }

    /// Returns the withdrawal history of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let withdrawal_history = bittrex_client.get_withdrawal_history().unwrap();
    /// ```
    pub fn get_withdrawal_history(&self) -> Result<Vec<BittrexTransaction>> {
        let withdrawal_history = self.call_private_api::<BittrexAPIVecResult<BittrexTransaction>>(&format!("{}/account/getwithdrawalhistory?", self.api_url))?;
        self.check_return_vec_response(withdrawal_history)
    }

    /// Returns the withdrawal history of the given market and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let withdrawal_history = bittrex_client.get_withdrawal_history_by_currency("BTC-LTC").unwrap();
    /// ```
    pub fn get_withdrawal_history_by_currency(&self, currency: &str) -> Result<Vec<BittrexTransaction>> {
        let withdrawal_history = self.call_private_api::<BittrexAPIVecResult<BittrexTransaction>>(&format!("{}/account/getwithdrawalhistory?currency={}", self.api_url, currency))?;
        self.check_return_vec_response(withdrawal_history)
    }

    /// Returns the deposit history of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let deposit_history = bittrex_client.get_deposit_history().unwrap();
    /// ```
    pub fn get_deposit_history(&self) -> Result<Vec<BittrexTransaction>> {
        let deposit_history = self.call_private_api::<BittrexAPIVecResult<BittrexTransaction>>(&format!("{}/account/getdeposithistory?", self.api_url))?;
        self.check_return_vec_response(deposit_history)
    }

    /// Returns the deposit history of the given currency and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let deposit_history = bittrex_client.get_deposit_history_by_currency("BTC").unwrap();
    /// ```
    pub fn get_deposit_history_by_currency(&self, currency: &str) -> Result<Vec<BittrexTransaction>> {
        let deposit_history = self.call_private_api::<BittrexAPIVecResult<BittrexTransaction>>(&format!("{}/account/getdeposithistory?currency={}", self.api_url, currency))?;
        self.check_return_vec_response(deposit_history)
    }

    /// Returns the balances of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let balances = bittrex_client.get_balances().unwrap();
    /// ```
    pub fn get_balances(&self) -> Result<Vec<BittrexBalance>> {
        let balances = self.call_private_api::<BittrexAPIVecResult<BittrexBalance>>(&format!("{}/account/getbalances?", self.api_url))?;
        self.check_return_vec_response(balances)
    }

    /// Returns the balance of the given currency and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let balance = bittrex_client.get_balance("BTC").unwrap();
    /// ```
    pub fn get_balance(&self, currency: &str) -> Result<BittrexBalance> {
        let balance = self.call_private_api::<BittrexAPIResult<BittrexBalance>>(&format!("{}/account/getbalance?currency={}", self.api_url, currency))?;
        self.check_return_single_response(balance)
    }

    /// Returns the deposit address of the given currency and of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let deposit_history = bittrex_client.get_deposit_address("BTC").unwrap();
    /// ```
    pub fn get_deposit_address(&self, currency: &str) -> Result<BittrexAddress> {
        let deposit_address = self.call_private_api::<BittrexAPIResult<BittrexAddress>>(&format!("{}/account/getdepositaddress?currency={}", self.api_url, currency))?;
        self.check_return_single_response(deposit_address)
    }

    /// Withdraws tokens of the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let withdraw_uuid = bittrex_client.withdraw("BTC", 1.5, "BITCOINADDRESS", "").unwrap();
    /// ```
    pub fn withdraw(&self, currency: &str, quantity: f64, address: &str, payment_id: &str) -> Result<BittrexUuid> {
        let withdraw = self.call_private_api::<BittrexAPIResult<BittrexUuid>>(&format!("{}/account/withdraw?currency={}&quantity={}&address={}&paymentid={}", self.api_url, currency, quantity, address, payment_id))?;
        self.check_return_single_response(withdraw)
    }

    /// Places a buy order on the given market for the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let buy_uuid = bittrex_client.buy_limit("BTC-LTC", 1.5, 0.00023).unwrap();
    /// ```
    pub fn buy_limit(&self, market: &str, quantity: f64, rate: f64) -> Result<BittrexUuid> {
        let buy_limit = self.call_private_api::<BittrexAPIResult<BittrexUuid>>(&format!("{}/market/buylimit?market={}&quantity={}&rate={}", self.api_url, market, quantity, rate))?;
        self.check_return_single_response(buy_limit)
    }

    /// Places a sell order on the given market for the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// let sell_uuid = bittrex_client.sell_limit("BTC-LTC", 1.5, 0.00023).unwrap();
    /// ```
    pub fn sell_limit(&self, market: &str, quantity: f64, rate: f64) -> Result<BittrexUuid> {
        let sell_limit = self.call_private_api::<BittrexAPIResult<BittrexUuid>>(&format!("{}/market/selllimit?market={}&quantity={}&rate={}", self.api_url, market, quantity, rate))?;
        self.check_return_single_response(sell_limit)
    }

    /// Cancels an order for the user given by the api_key and api_secret.
    ///
    /// # Examples
    /// 
    /// ```rust,no_run
    /// use bittrex_api::BittrexClient;
    ///
    /// let bittrex_client = BittrexClient::new("APIKEY".to_string(), "APISECRET".to_string());
    /// bittrex_client.cancel_order("ORDERID").unwrap();
    /// ```
    pub fn cancel_order(&self, order_id: &str) -> Result<()> {
        self.call_private_api::<BittrexAPIResult<()>>(&format!("{}/market/cancel?uuid={}", self.api_url, order_id))?;
        Ok(())
    }

    fn call_public_api<T>(&self, url: &str) -> Result<T> where for<'de> T: serde::Deserialize<'de> {
        let client = self.get_client()?;
        let mut resp = client.get(url)?.send()?;
        let result : T = resp.json()?;
        
        Ok(result)
    }

    fn call_private_api<T>(&self, url: &str) -> Result<T> where for<'de> T: serde::Deserialize<'de> {
        let url_with_key = format!("{}&apikey={}&nonce={}", url, self.api_key, time::precise_time_ns());
        let hmac = self.sign_call(&url_with_key);
        
        let mut headers = Headers::new();
        headers.set_raw("apisign", self.to_hex_string(hmac.code()));

        let client = self.get_client()?;
        let mut resp = client.get(&url_with_key)?.headers(headers).send()?;
        let result : T = resp.json()?;
        
        Ok(result)
    }

    fn sign_call(&self, msg: &str) -> MacResult<U64> {
        let mut hmac = Hmac::<Sha512>::new(self.api_secret.as_bytes());
        hmac.input(msg.as_bytes());
        
        MacResult::from_slice(hmac.result().code())
    }

    fn get_client(&self) -> Result<Client> {
        let mut client_builder = Client::builder()?;

        if let Some(ref http_proxy) = self.http_proxy {
            client_builder.proxy(Proxy::http(http_proxy)?);
        }

        if let Some(ref https_proxy) = self.https_proxy {
            client_builder.proxy(Proxy::https(https_proxy)?);
        }
        
        Ok(client_builder.build()?)
    }

    fn check_return_single_response<T>(&self, bittrex_api_result: BittrexAPIResult<T>) -> Result<T> {
        if bittrex_api_result.success {
            return Ok(bittrex_api_result.result.expect("Result should exist!"));
        }
        Err(BittrexError { error_type: BittrexErrorType::APIError, message: bittrex_api_result.message })
    }

    fn check_return_vec_response<T>(&self, bittrex_api_result: BittrexAPIVecResult<T>) -> Result<Vec<T>> {
        if bittrex_api_result.success {
            return Ok(bittrex_api_result.result.expect("Result should exist!"));
        }
        Err(BittrexError { error_type: BittrexErrorType::APIError, message: bittrex_api_result.message })
    }

    fn check_return_single_vec_response<T>(&self, bittrex_api_result: BittrexAPIVecResult<T>) -> Result<T> {
        if bittrex_api_result.success {
            let mut result = bittrex_api_result.result.expect("Result should exist!");
            return match result.len() {
                1 => Ok(result.remove(0)),
                0 => Err(BittrexError { error_type: BittrexErrorType::NoResults, message: "Maybe check your parameters?".to_string() }),
                _ => Err(BittrexError { error_type: BittrexErrorType::APIError, message: "Multiple results found! Maybe check your parameters?".to_string() })
            }
        }
        Err(BittrexError { error_type: BittrexErrorType::APIError, message: bittrex_api_result.message })
    }

    fn to_hex_string(&self, bytes: &[u8]) -> String {
        let strs: Vec<String> = bytes.iter()
                                    .map(|b| format!("{:02X}", b))
                                    .collect();
        strs.join("")
    }
}