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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//!
//! # Wex API
//!
//! API implementation for the [Wex](https://wex.nz/) market-place.
//!
//! **Please Donate**
//!
//! + **BTC:** 17voJDvueb7iZtcLRrLtq3dfQYBaSi2GsU
//! + **ETC:** 0x7bC5Ff6Bc22B4C6Af135493E6a8a11A62D209ae5
//! + **XMR:** 49S4VziJ9v2CSkH6mP9km5SGeo3uxhG41bVYDQdwXQZzRF6mG7B4Fqv2aNEYHmQmPfJcYEnwNK1cAGLHMMmKaUWg25rHnkm
//!
//! **Wex API Documentation:**
//!
//! + https://wex.nz/api/3/docs
//! + https://wex.nz/tapi/docs
//!
//! ## Example
//!
//! ```rust
//! extern crate wex;
//!
//! fn main() {
//!    let account = wex::Account {
//!         key: String::from("<your-key>"),
//!         secret: String::from("<your-secret>"),
//!     };
//!
//!     println!("{:?}", wex::info());
//!     println!("{:?}", wex::get_info(&account));
//!
//!     // currency pair chain :)
//!
//!     let info = wex::info().expect("could not optain wex pairs");
//!     let pairs: Vec<&String> = info.pairs.keys().collect();
//!     let mut pairchain = pairs.iter().fold(
//!         String::new(),
//!         |data, item| data + item + "-",
//!     );
//!     pairchain.pop(); // remove last `-`
//!
//!     // ticker all pairs at once :D
//!     let ticks = wex::ticker(&pairchain).expect("could not ticker");
//! }
//! ```
//!
extern crate crypto;
extern crate curl;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha2::Sha512;
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write;
use std::io::Read;
use curl::easy::{Easy, List};


///
/// Representing a key secret pair from Wex.
///
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Account {
    pub key: String,
    pub secret: String,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct TickPair {
    /// 24h maximum price.
    pub high: f64,
    /// 24h minimum price.
    pub low: f64,
    /// 24h average price.
    pub avg: f64,
    /// trade volume.
    pub vol: f64,
    /// trade volume in currency.
    pub vol_cur: f64,
    /// the price of the last trade.
    pub last: f64,
    /// buy price.
    pub buy: f64,
    /// sell price.
    pub sell: f64,
    /// last update of cache.
    pub updated: i64,
}

pub type Tick = HashMap<String, TickPair>;

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Depth {
    pub asks: Vec<Vec<f64>>,
    pub bids: Vec<Vec<f64>>,
}

pub type Depths = HashMap<String, Depth>;

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum PublicTradeKind {
    Ask,
    Bid,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct PublicTrade {
    /// ask – Sell, bid – Buy.
    #[serde(rename = "type")]
    kind: PublicTradeKind,
    /// Buy price/Sell price
    price: f64,
    /// the amount of asset bought/sold.
    amount: f64,
    /// trade ID.
    tid: u32,
    /// UNIX time of the trade.
    timestamp: i64,
}

pub type PublicTrades = HashMap<String, Vec<PublicTrade>>;

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct InfoPair {
    pub decimal_places: u32,
    pub min_price: f64,
    pub max_price: f64,
    pub min_amount: f64,
    pub hidden: u32,
    pub fee: f64,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Info {
    pub server_time: i64,
    pub pairs: HashMap<String, InfoPair>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct WexResult<T> {
    success: u8,
    #[serde(rename = "return")]
    result: Option<T>,
    error: Option<String>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct FundRights {
    pub info: u8,
    pub trade: u8,
    pub withdraw: u8,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct FundInfo {
    /// Your account balance available for trading. Doesn’t include funds on your open orders.
    pub funds: HashMap<String, f64>,
    /// The privileges of the current API key. At this time the privilege to withdraw is not used anywhere.
    pub rights: FundRights,
    /// Deprecated, is equal to 0.
    pub transaction_count: u32,
    /// The number of your open orders.
    pub open_orders: u32,
    /// Server time (MSK).
    pub server_time: i64,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct TradeResult {
    /// The amount of currency bought/sold.
    pub received: f64,
    /// The remaining amount of currency to be bought/sold (and the initial order amount).
    pub remains: f64,
    /// Is equal to 0 if the request was fully “matched” by the opposite orders, otherwise the ID of the executed order will be returned.
    pub order_id: u64,
    /// Balance after the request.
    pub funds: HashMap<String, f64>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum OrderType {
    Sell,
    Buy,
}


macro_rules! enum_number {
    ($name:ident { $($variant:ident = $value:expr, )* }) => {
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        pub enum $name {
            $($variant = $value,)*
        }

        impl ::serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where S: ::serde::Serializer
            {
                // Serialize the enum as a u64.
                serializer.serialize_u64(*self as u64)
            }
        }

        impl<'de> ::serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where D: ::serde::Deserializer<'de>
            {
                struct Visitor;

                impl<'de> ::serde::de::Visitor<'de> for Visitor {
                    type Value = $name;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("positive integer")
                    }

                    fn visit_u64<E>(self, value: u64) -> Result<$name, E>
                        where E: ::serde::de::Error
                    {
                        // Rust does not come with a simple way of converting a
                        // number to an enum, so use a big `match`.
                        match value {
                            $( $value => Ok($name::$variant), )*
                            _ => Err(E::custom(
                                format!("unknown {} value: {}",
                                stringify!($name), value))),
                        }
                    }
                }

                // Deserialize the enum from a u64.
                deserializer.deserialize_u64(Visitor)
            }
        }
    }
}

enum_number!(OrderStatus {
    Active = 0,
    ExecutedOrder = 1,
    Canceled = 2,
    PartiallyExecuted = 3,
});

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct ActiveOrder {
    /// The pair on which the order was created.
    pair: String,
    ///  Order type, buy/sell.
    #[serde(rename = "type")]
    kind: OrderType,
    /// The amount of currency to be bought/sold.
    amount: f64,
    /// Sell/Buy price.
    rate: f64,
    /// The time when the order was created.
    timestamp_created: i64,
    /// Deprecated, is always equal to 0.
    status: OrderStatus,
}

pub type ActiveOrders = HashMap<String, ActiveOrder>;


#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct OrderInfo {
    /// The pair on which the order was created.
    pair: String,
    ///  Order type, buy/sell.
    #[serde(rename = "type")]
    kind: OrderType,
    /// The initial amount at the time of order creation.
    start_amount: f64,
    /// The remaining amount of currency to be bought/sold.
    amount: f64,
    /// Sell/Buy price.
    rate: f64,
    /// The time when the order was created.
    timestamp_created: i64,
    /// Deprecated, is always equal to 0.
    status: OrderStatus,
}

pub type OrderInfos = HashMap<String, ActiveOrder>;

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct CancelResult {
    /// The ID of canceled order.
    order_id: String,
    /// Balance upon request.
    funds: HashMap<String, f64>,
}


pub enum TradeHistorySorting {
    Asc,
    Desc,
}

pub struct HistoryQuery {
    /// trade ID, from which the display starts 	numerical 	0
    from: Option<u64>,
    /// the number of trades for display 	numerical 	1000
    count: Option<u64>,
    /// trade ID, from which the display starts 	numerical 	0
    from_id: Option<u64>,
    /// trade ID on which the display ends 	numerical 	∞
    end_id: Option<u64>,
    /// Sorting. Defaults: DESC.
    order: Option<TradeHistorySorting>,
    /// the time to start the display 	UNIX time 	0
    since: Option<i64>,
    /// the time to end the display 	UNIX time 	∞
    end: Option<i64>,
    /// pair to be displayed 	btc_usd (example) 	all pairs
    pair: Option<String>,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct TradeHistoryEntry {
    /// The pair on which the trade was executed.
    pair: String,
    /// Trade type, buy/sell.
    kind: OrderType,
    /// The amount of currency was bought/sold.
    amount: f64,
    /// Sell/Buy price.
    rate: f64,
    /// Order ID.
    order_id: u64,
    /// Is equal to 1 if order_id is your order, otherwise is equal to 0.
    is_your_order: u8,
    /// Trade execution time.
    timestamp: i64,
}

type TradeHistory = HashMap<String, TradeHistoryEntry>;

#[derive(Deserialize, Serialize, Clone, Debug)]
pub enum TransactionType {
    Deposit = 1,
    Withdrawl = 2,
    Credit = 4,
    Debit = 5,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub enum TransactionStatus {
    Canceled = 0,
    Waiting = 1,
    Successful = 2,
    NotConfirmed = 3,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct TransactionHistoryEntry {
    #[serde(rename = "type")]
    kind: TransactionType,
    amount: f64,
    currency: String,
    desc: String,
    status: TransactionStatus,
    timestamp: i64,
}

pub type TransactionHistory = HashMap<String, TransactionHistoryEntry>;

fn public(url: &str) -> Result<Vec<u8>, String> {
    let mut easy = Easy::new();
    let mut dst = Vec::new();

    easy.url(&format!("https://wex.nz/api/3/{}", url)).unwrap();

    let result = {
        let mut transfer = easy.transfer();
        transfer
            .write_function(|data| {
                dst.extend_from_slice(data);
                Ok(data.len())
            })
            .unwrap();

        transfer.perform()
    };

    result.map_err(|e| format!("{:?}", e)).and_then(
        |_x| Ok(dst),
    )
}

///
/// This method provides all the information about currently active pairs.
///
pub fn info() -> Result<Info, String> {
    public("info").and_then(|data| {
        serde_json::from_slice(&data).map_err(|e| format!("{:?}", e))
    })
}

///
/// This method provides all the information about currently active pairs
///
/// # Arguments
///
/// + `pair` - A string of market pairs.
///
/// # Examples
///
/// ```rust
/// // get ticks for btc_usd and btc_eur
/// wex::ticker("btc_usd-btc_eur")
///     .map(|ticks| {
///         print!("{:?}", ticks.get("btc_usd").unwrap())
///     })
/// ```
///
pub fn ticker(pair: &str) -> Result<Tick, String> {
    public(&format!("ticker/{}", pair)).and_then(|data| {
        serde_json::from_slice(&data).map_err(|e| format!("{:?}", e))
    })
}

///
/// This method provides the information about active orders on the pair.
///
/// # Arguments
///
/// + `pair` - A string of market pairs.
/// + `limit` - Which indicates how many orders should be displayed (150 by default).
///
pub fn depth(pair: &str, limit: Option<u32>) -> Result<Depths, String> {
    let mut url = format!("depth/{}", pair);

    if let Some(l) = limit {
        url = format!("{}?limit={}", url, l);
    }

    public(&url).and_then(|data| {
        serde_json::from_slice(&data).map_err(|e| format!("{:?}", e))
    })
}

///
/// This method provides the information about the last trades.
///
/// # Arguments
///
/// + `pair` - A string of market pairs.
/// + `limit` - Which indicates how many orders should be displayed (150 by default).
///
pub fn trades(pair: &str, limit: Option<u32>) -> Result<PublicTrades, String> {
    let mut url = format!("trades/{}", pair);

    if let Some(l) = limit {
        url = format!("{}?limit={}", url, l);
    }

    public(&url).and_then(|data| {
        serde_json::from_slice(&data).map_err(|e| format!("{:?}", e))
    })
}

// // ---

fn private(account: &Account, params: &mut HashMap<String, String>) -> Result<Vec<u8>, String> {
    let mut dst = Vec::new();
    let mut easy = Easy::new();

    easy.url("https://wex.nz/tapi").unwrap();
    easy.post(true).unwrap();

    let timestamp = ::std::time::UNIX_EPOCH.elapsed().unwrap();
    let nonce = format!("{}", timestamp.as_secs());

    params.insert("nonce".to_owned(), nonce);

    let mut body = params.iter().fold(
        String::new(),
        |data, item| data + item.0 + "=" + item.1 + "&",
    );
    body.pop();
    let mut body_bytes = body.as_bytes();

    let mut hmac = Hmac::new(Sha512::new(), account.secret.as_bytes());

    hmac.input(body_bytes);

    easy.post_field_size(body_bytes.len() as u64).unwrap();

    let mut list = List::new();
    let sign = hmac.result();

    let mut hex = String::new();
    for byte in sign.code() {
        write!(&mut hex, "{:02x}", byte).expect("could not create hmac hex");
    }
    list.append("Content-Type: application/x-www-form-urlencoded")
        .unwrap();
    list.append(&format!("Key: {}", account.key)).unwrap();
    list.append(&format!("Sign: {}", hex)).unwrap();

    easy.http_headers(list).unwrap();

    let result = {
        let mut transfer = easy.transfer();

        transfer
            .read_function(|buf| Ok(body_bytes.read(buf).unwrap_or(0)))
            .unwrap();

        transfer
            .write_function(|data| {
                dst.extend_from_slice(data);
                Ok(data.len())
            })
            .unwrap();

        transfer.perform()
    };

    result.map_err(|e| format!("{:?}", e)).and_then(
        |_x| Ok(dst),
    )
}

///
/// Returns information about the user’s current balance,
/// API-key privileges, the number of open orders and Server Time.
/// To use this method you need a privilege of the key info.
///
pub fn get_info(account: &Account) -> Result<FundInfo, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "getInfo".to_owned());

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<FundInfo>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// Create orders.
///
/// You can only create limit orders using this method, but you can emulate market orders using rate parameters.
/// E.g. using rate=0.1 you can sell at the best market price.
/// Each pair has a different limit on the minimum / maximum amounts, the minimum amount and the number of digits after the decimal point.
/// All limitations can be obtained using the info method in PublicAPI v3.
///
pub fn trade(
    account: &Account,
    pair: &str,
    kind: OrderType,
    rate: &str,
    amount: &str,
) -> Result<TradeResult, String> {
    let mut params = HashMap::new();

    let kind_str = match kind {
        OrderType::Buy => String::from("buy"),
        OrderType::Sell => String::from("sell"),
    };

    params.insert("method".to_owned(), "Trade".to_owned());
    params.insert("pair".to_owned(), String::from(pair));
    params.insert("type".to_owned(), kind_str);
    params.insert("rate".to_owned(), String::from(rate));
    params.insert("amount".to_owned(), String::from(amount));

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<TradeResult>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// Returns the list of your active orders.
/// If the order disappears from the list, it was either executed or canceled.
///
pub fn active_orders(account: &Account, pair: Option<&str>) -> Result<ActiveOrders, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "ActiveOrders".to_owned());

    if let Some(p) = pair {
        params.insert("pair".to_owned(), String::from(p));
    }

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}\n{}", e, String::from_utf8(r).unwrap()))
            .and_then(|result: WexResult<ActiveOrders>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// Returns the information on particular order.
///
pub fn order_info(account: &Account, order_id: &str) -> Result<OrderInfos, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "OrderInfo".to_owned());
    params.insert("order_id".to_owned(), String::from(order_id));

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<OrderInfos>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// This method is used for order cancelation.
///
pub fn cancel_order(account: &Account, order_id: &str) -> Result<CancelResult, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "CancelOrder".to_owned());
    params.insert("order_id".to_owned(), String::from(order_id));

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<CancelResult>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// Returns trade history.
///
/// When using parameters since or end, the order parameter automatically assumes the value ASC.
/// When using the since parameter the maximum time that can displayed is 1 week.
///
pub fn trade_history(account: &Account, cfg: Option<HistoryQuery>) -> Result<TradeHistory, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "TradeHistory".to_owned());

    if let Some(p) = cfg {
        if let Some(from) = p.from {
            params.insert("from".to_owned(), format!("{}", from));
        }

        if let Some(count) = p.count {
            params.insert("count".to_owned(), format!("{}", count));
        }

        if let Some(from_id) = p.from_id {
            params.insert("from_id".to_owned(), format!("{}", from_id));
        }

        if let Some(end_id) = p.end_id {
            params.insert("end_id".to_owned(), format!("{}", end_id));
        }

        if let Some(order) = p.order {
            match order {
                TradeHistorySorting::Asc => params.insert("order".to_owned(), "asc".to_owned()),
                TradeHistorySorting::Desc => params.insert("order".to_owned(), "desc".to_owned()),
            };
        }

        if let Some(since) = p.since {
            params.insert("since".to_owned(), format!("{}", since));
        }

        if let Some(end) = p.end {
            params.insert("end".to_owned(), format!("{}", end));
        }

        if let Some(pair) = p.pair {
            params.insert("pair".to_owned(), pair);
        }
    }

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<TradeHistory>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// Returns the history of transactions.
///
pub fn trans_history(
    account: &Account,
    cfg: Option<HistoryQuery>,
) -> Result<TransactionHistory, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "TransHistory".to_owned());

    if let Some(p) = cfg {
        if let Some(from) = p.from {
            params.insert("from".to_owned(), format!("{}", from));
        }

        if let Some(count) = p.count {
            params.insert("count".to_owned(), format!("{}", count));
        }

        if let Some(from_id) = p.from_id {
            params.insert("from_id".to_owned(), format!("{}", from_id));
        }

        if let Some(end_id) = p.end_id {
            params.insert("end_id".to_owned(), format!("{}", end_id));
        }

        if let Some(order) = p.order {
            match order {
                TradeHistorySorting::Asc => params.insert("order".to_owned(), "asc".to_owned()),
                TradeHistorySorting::Desc => params.insert("order".to_owned(), "desc".to_owned()),
            };
        }

        if let Some(since) = p.since {
            params.insert("since".to_owned(), format!("{}", since));
        }

        if let Some(end) = p.end {
            params.insert("end".to_owned(), format!("{}", end));
        }

        if let Some(pair) = p.pair {
            params.insert("pair".to_owned(), pair);
        }
    }

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<TransactionHistory>| if result.success ==
                1
            {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}

///
/// This method can be used to retrieve the address for depositing crypto-currency.
///
/// To use this method, you need the info key privilege.
///
/// At present, this method does not generate new adresses.
/// If you have never deposited in a particular crypto-currency and try to retrive a deposit address,
/// your request will return an error, because this address has not been generated yet.
///
pub fn coin_deposit_address(account: &Account, coin_name: &str) -> Result<CancelResult, String> {
    let mut params = HashMap::new();

    params.insert("method".to_owned(), "CoinDepositAddress".to_owned());
    params.insert("coinName".to_owned(), String::from(coin_name));

    private(account, &mut params).and_then(|r| {
        serde_json::from_slice(&r)
            .map_err(|e| format!("{:?}", e))
            .and_then(|result: WexResult<CancelResult>| if result.success == 1 {
                Ok(result.result.unwrap())
            } else {
                Err(result.error.unwrap())
            })
    })
}