Skip to content

Commit 2ed5506

Browse files
authored
Merge pull request #66 from doomsplayer/add-order-options
Add order options
2 parents 2697b60 + 5ae1a0d commit 2ed5506

File tree

3 files changed

+127
-149
lines changed

3 files changed

+127
-149
lines changed

src/poloniex/api.rs

+79-103
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! See examples for more informations.
33
44
use hmac::{Hmac, Mac};
5-
use sha2::{Sha512};
5+
use sha2::Sha512;
66

77
use hyper_native_tls::NativeTlsClient;
88
use hyper::Client;
@@ -41,6 +41,36 @@ header! {
4141
(ContentHeader, "Content-Type") => [String]
4242
}
4343

44+
#[derive(Debug, Copy, Clone)]
45+
pub enum PlaceOrderOption {
46+
FillOrKill,
47+
ImmediateOrCancel,
48+
PostOnly,
49+
}
50+
impl PlaceOrderOption {
51+
fn repr(&self) -> &'static str {
52+
match self {
53+
&PlaceOrderOption::FillOrKill => "fillOrKill",
54+
&PlaceOrderOption::ImmediateOrCancel => "immediateOrCancel",
55+
&PlaceOrderOption::PostOnly => "postOnly",
56+
}
57+
}
58+
}
59+
60+
#[derive(Debug, Copy, Clone)]
61+
pub enum MoveOrderOption {
62+
ImmediateOrCancel,
63+
PostOnly,
64+
}
65+
impl MoveOrderOption {
66+
fn repr(&self) -> &'static str {
67+
match self {
68+
&MoveOrderOption::ImmediateOrCancel => "immediateOrCancel",
69+
&MoveOrderOption::PostOnly => "postOnly",
70+
}
71+
}
72+
}
73+
4474
#[derive(Debug)]
4575
pub struct PoloniexApi {
4676
last_request: i64, // unix timestamp in ms, to avoid ban
@@ -50,7 +80,6 @@ pub struct PoloniexApi {
5080
burst: bool,
5181
}
5282

53-
5483
impl PoloniexApi {
5584
/// Create a new PoloniexApi by providing an API key & API secret
5685
pub fn new<C: Credentials>(creds: C) -> Result<PoloniexApi> {
@@ -66,12 +95,12 @@ impl PoloniexApi {
6695
let connector = HttpsConnector::new(ssl);
6796

6897
Ok(PoloniexApi {
69-
last_request: 0,
70-
api_key: creds.get("api_key").unwrap_or_default(),
71-
api_secret: creds.get("api_secret").unwrap_or_default(),
72-
http_client: Client::with_connector(connector),
73-
burst: false,
74-
})
98+
last_request: 0,
99+
api_key: creds.get("api_key").unwrap_or_default(),
100+
api_secret: creds.get("api_secret").unwrap_or_default(),
101+
http_client: Client::with_connector(connector),
102+
burst: false,
103+
})
75104
}
76105

77106
/// The number of calls in a given period is limited. In order to avoid a ban we limit
@@ -84,7 +113,7 @@ impl PoloniexApi {
84113
}
85114

86115
fn block_or_continue(&self) {
87-
if ! self.burst {
116+
if !self.burst {
88117
let threshold: u64 = 167; // 6 requests/sec = 1/6*1000
89118
let offset: u64 = helpers::get_unix_timestamp_ms() as u64 - self.last_request as u64;
90119
if offset < threshold {
@@ -94,14 +123,10 @@ impl PoloniexApi {
94123
}
95124
}
96125

97-
fn public_query(&mut self,
98-
method: &str,
99-
params: &HashMap<&str, &str>)
100-
-> Result<Map<String, Value>> {
126+
fn public_query(&mut self, method: &str, params: &HashMap<&str, &str>) -> Result<Map<String, Value>> {
101127
let mut params = params.clone();
102128
helpers::strip_empties(&mut params);
103-
let url = "https://poloniex.com/public?command=".to_string() + method + "&" +
104-
&helpers::url_encode_hashmap(&params);
129+
let url = "https://poloniex.com/public?command=".to_string() + method + "&" + &helpers::url_encode_hashmap(&params);
105130

106131
self.block_or_continue();
107132
let mut response = match self.http_client.get(&url).send() {
@@ -114,10 +139,7 @@ impl PoloniexApi {
114139
utils::deserialize_json(&buffer)
115140
}
116141

117-
fn private_query(&mut self,
118-
method: &str,
119-
params: &HashMap<&str, &str>)
120-
-> Result<Map<String, Value>> {
142+
fn private_query(&mut self, method: &str, params: &HashMap<&str, &str>) -> Result<Map<String, Value>> {
121143
let unix_timestamp = helpers::get_unix_timestamp_us().to_string();
122144
let mut post_params = params.clone();
123145
post_params.insert("command", method);
@@ -133,15 +155,18 @@ impl PoloniexApi {
133155
let mut custom_header = header::Headers::new();
134156
custom_header.set(KeyHeader(self.api_key.to_owned()));
135157
custom_header.set(SignHeader(sign));
136-
custom_header.set(ContentHeader("application/x-www-form-urlencoded".to_owned()));
158+
custom_header.set(ContentHeader(
159+
"application/x-www-form-urlencoded".to_owned(),
160+
));
137161

138162
self.block_or_continue();
139163

140164
let mut response = match self.http_client
141-
.post("https://poloniex.com/tradingApi")
142-
.body(&post_data)
143-
.headers(custom_header)
144-
.send() {
165+
.post("https://poloniex.com/tradingApi")
166+
.body(&post_data)
167+
.headers(custom_header)
168+
.send()
169+
{
145170
Ok(response) => response,
146171
Err(err) => return Err(ErrorKind::ServiceUnavailable(err.to_string()).into()),
147172
};
@@ -187,10 +212,7 @@ impl PoloniexApi {
187212
/// {"asks":[[0.00007600,1164],[0.00007620,1300], ... ], "bids":[[0.00006901,200],
188213
/// [0.00006900,408], ... ], "isFrozen": 0, "seq": 18849}
189214
/// ```
190-
pub fn return_order_book(&mut self,
191-
currency_pair: &str,
192-
depth: &str)
193-
-> Result<Map<String, Value>> {
215+
pub fn return_order_book(&mut self, currency_pair: &str, depth: &str) -> Result<Map<String, Value>> {
194216
let mut params = HashMap::new();
195217
params.insert("currencyPair", currency_pair);
196218
params.insert("depth", depth);
@@ -205,11 +227,7 @@ impl PoloniexApi {
205227
/// {"date":"2014-02-10 01:19:37","type":"buy","rate":"0.00007600","amount":"655",
206228
/// "total":"0.04978"}, ... ]
207229
/// ```
208-
pub fn return_trade_history(&mut self,
209-
currency_pair: &str,
210-
start: &str,
211-
end: &str)
212-
-> Result<Map<String, Value>> {
230+
pub fn return_trade_history(&mut self, currency_pair: &str, start: &str, end: &str) -> Result<Map<String, Value>> {
213231
let mut params = HashMap::new();
214232
params.insert("currencyPair", currency_pair);
215233
params.insert("start", start);
@@ -223,12 +241,7 @@ impl PoloniexApi {
223241
/// [{"date":1405699200,"high":0.0045388,"low":0.00403001,"open":0.00404545,"close":0.00427592,
224242
/// "volume":44.11655644,"quoteVolume":10259.29079097,"weightedAverage":0.00430015}, ...]
225243
/// ```
226-
pub fn return_chart_data(&mut self,
227-
currency_pair: &str,
228-
start: &str,
229-
end: &str,
230-
period: &str)
231-
-> Result<Map<String, Value>> {
244+
pub fn return_chart_data(&mut self, currency_pair: &str, start: &str, end: &str, period: &str) -> Result<Map<String, Value>> {
232245
let mut params = HashMap::new();
233246
params.insert("currencyPair", currency_pair);
234247
params.insert("start", start);
@@ -334,10 +347,7 @@ impl PoloniexApi {
334347
/// "status":"COMPLETE: 36e483efa6aff9fd53a235177579d98451c4eb237c210e66cd2b9a2d4a988f8e",
335348
/// "ipAddress":"..."}]}
336349
/// ```
337-
pub fn return_deposits_withdrawals(&mut self,
338-
start: &str,
339-
end: &str)
340-
-> Result<Map<String, Value>> {
350+
pub fn return_deposits_withdrawals(&mut self, start: &str, end: &str) -> Result<Map<String, Value>> {
341351
let mut params = HashMap::new();
342352
params.insert("start", start);
343353
params.insert("end", end);
@@ -397,11 +407,7 @@ impl PoloniexApi {
397407
/// "orderNumber": "12603319116", "type": "sell", "category": "marginTrade" }, ... ],
398408
/// "BTC_LTC":[ ... ] ... }
399409
/// ```
400-
pub fn return_private_trade_history(&mut self,
401-
currency_pair: &str,
402-
start: &str,
403-
end: &str)
404-
-> Result<Map<String, Value>> {
410+
pub fn return_private_trade_history(&mut self, currency_pair: &str, start: &str, end: &str) -> Result<Map<String, Value>> {
405411
let mut params = HashMap::new();
406412
params.insert("currencyPair", currency_pair);
407413
params.insert("start", start);
@@ -437,31 +443,29 @@ impl PoloniexApi {
437443
/// "date":"2014-10-18 23:03:21", "rate":"0.00000173","total":"0.00058625","tradeID":"16164",
438444
/// "type":"buy"}]}
439445
/// ```
440-
pub fn buy(&mut self,
441-
currency_pair: &str,
442-
rate: &str,
443-
amount: &str)
444-
-> Result<Map<String, Value>> {
445-
// TODO: "fillOrKill", "immediateOrCancel", "postOnly"
446+
pub fn buy<O>(&mut self, currency_pair: &str, rate: &str, amount: &str, option: O) -> Result<Map<String, Value>>
447+
where
448+
O: Into<Option<PlaceOrderOption>>,
449+
{
446450
let mut params = HashMap::new();
447451
params.insert("currencyPair", currency_pair);
448452
params.insert("rate", rate);
449453
params.insert("amount", amount);
454+
option.into().map(|o| params.insert(o.repr(), "1"));
450455
self.private_query("buy", &params)
451456
}
452457

453458
/// Places a sell order in a given market. Parameters and output are the same as for the buy
454459
/// method.
455-
pub fn sell(&mut self,
456-
currency_pair: &str,
457-
rate: &str,
458-
amount: &str)
459-
-> Result<Map<String, Value>> {
460-
// TODO: "fillOrKill", "immediateOrCancel", "postOnly"
460+
pub fn sell<O>(&mut self, currency_pair: &str, rate: &str, amount: &str, option: O) -> Result<Map<String, Value>>
461+
where
462+
O: Into<Option<PlaceOrderOption>>,
463+
{
461464
let mut params = HashMap::new();
462465
params.insert("currencyPair", currency_pair);
463466
params.insert("rate", rate);
464467
params.insert("amount", amount);
468+
option.into().map(|o| params.insert(o.repr(), "1"));
465469
self.private_query("sell", &params)
466470
}
467471

@@ -486,11 +490,15 @@ impl PoloniexApi {
486490
/// ```json
487491
/// {"success":1,"orderNumber":"239574176","resultingTrades":{"BTC_BTS":[]}}
488492
/// ```
489-
pub fn move_order(&mut self, order_number: &str, rate: &str) -> Result<Map<String, Value>> {
493+
pub fn move_order<O>(&mut self, order_number: &str, rate: &str, option: O) -> Result<Map<String, Value>>
494+
where
495+
O: Into<Option<MoveOrderOption>>,
496+
{
490497
// TODO: add optional parameters
491498
let mut params = HashMap::new();
492499
params.insert("orderNumber", order_number);
493500
params.insert("rate", rate);
501+
option.into().map(|o| params.insert(o.repr(), "1"));
494502
self.private_query("moveOrder", &params)
495503
}
496504

@@ -504,11 +512,7 @@ impl PoloniexApi {
504512
/// ```json
505513
/// {"response":"Withdrew 2398 NXT."}
506514
/// ```
507-
pub fn withdraw(&mut self,
508-
currency: &str,
509-
amount: &str,
510-
address: &str)
511-
-> Result<Map<String, Value>> {
515+
pub fn withdraw(&mut self, currency: &str, amount: &str, address: &str) -> Result<Map<String, Value>> {
512516
let mut params = HashMap::new();
513517
params.insert("currency", currency);
514518
params.insert("amount", amount);
@@ -544,9 +548,7 @@ impl PoloniexApi {
544548
/// "margin":{"BTC":"3.90015637", "DASH":"250.00238240","XMR":"497.12028113"},
545549
/// "lending":{"DASH":"0.01174765","LTC":"11.99936230"}}
546550
/// ```
547-
pub fn return_available_account_balances(&mut self,
548-
account: &str)
549-
-> Result<Map<String, Value>> {
551+
pub fn return_available_account_balances(&mut self, account: &str) -> Result<Map<String, Value>> {
550552
let mut params = HashMap::new();
551553
params.insert("account", account);
552554
self.private_query("returnAvailableAccountBalances", &params)
@@ -576,12 +578,7 @@ impl PoloniexApi {
576578
/// ```json
577579
/// {"success":1,"message":"Transferred 2 BTC from exchange to margin account."}
578580
/// ```
579-
pub fn transfer_balance(&mut self,
580-
currency: &str,
581-
amount: &str,
582-
from_account: &str,
583-
to_account: &str)
584-
-> Result<Map<String, Value>> {
581+
pub fn transfer_balance(&mut self, currency: &str, amount: &str, from_account: &str, to_account: &str) -> Result<Map<String, Value>> {
585582
let mut params = HashMap::new();
586583
params.insert("currency", currency);
587584
params.insert("amount", amount);
@@ -590,7 +587,6 @@ impl PoloniexApi {
590587
self.private_query("transferBalance", &params)
591588
}
592589

593-
594590
/// Returns a summary of your entire margin account. This is the same information you will
595591
/// find in the Margin Account section of the Margin Trading page, under the Markets list.
596592
///
@@ -617,12 +613,7 @@ impl PoloniexApi {
617613
/// "resultingTrades":{"BTC_DASH":[{"amount":"1.00000000","date":"2015-05-10 22:47:05",
618614
/// "rate":"0.01383692","total":"0.01383692","tradeID":"1213556","type":"buy"}]}}
619615
/// ```
620-
pub fn margin_buy(&mut self,
621-
currency_pair: &str,
622-
rate: &str,
623-
amount: &str,
624-
lending_rate: &str)
625-
-> Result<Map<String, Value>> {
616+
pub fn margin_buy(&mut self, currency_pair: &str, rate: &str, amount: &str, lending_rate: &str) -> Result<Map<String, Value>> {
626617
let mut params = HashMap::new();
627618
params.insert("currencyPair", currency_pair);
628619
params.insert("rate", rate);
@@ -643,12 +634,7 @@ impl PoloniexApi {
643634
/// "resultingTrades":{"BTC_DASH":[{"amount":"1.00000000","date":"2015-05-10 22:47:05",
644635
/// "rate":"0.01383692","total":"0.01383692","tradeID":"1213556","type":"sell"}]}}
645636
/// ```
646-
pub fn margin_sell(&mut self,
647-
currency_pair: &str,
648-
rate: &str,
649-
amount: &str,
650-
lending_rate: &str)
651-
-> Result<Map<String, Value>> {
637+
pub fn margin_sell(&mut self, currency_pair: &str, rate: &str, amount: &str, lending_rate: &str) -> Result<Map<String, Value>> {
652638
let mut params = HashMap::new();
653639
params.insert("currencyPair", currency_pair);
654640
params.insert("rate", rate);
@@ -703,13 +689,7 @@ impl PoloniexApi {
703689
/// ```json
704690
/// {"success":1,"message":"Loan order placed.","orderID":10590}
705691
/// ```
706-
pub fn create_loan_offer(&mut self,
707-
currency: &str,
708-
amount: &str,
709-
duration: &str,
710-
auto_renew: &str,
711-
lending_rate: &str)
712-
-> Result<Map<String, Value>> {
692+
pub fn create_loan_offer(&mut self, currency: &str, amount: &str, duration: &str, auto_renew: &str, lending_rate: &str) -> Result<Map<String, Value>> {
713693
let mut params = HashMap::new();
714694
params.insert("currency", currency);
715695
params.insert("amount", amount);
@@ -774,11 +754,7 @@ impl PoloniexApi {
774754
/// "duration": "0.47610000", "interest": "0.00001196", "fee": "-0.00000179",
775755
/// "earned": "0.00001017", "open": "2016-09-28 06:47:26", "close": "2016-09-28 18:13:03" }]
776756
/// ```
777-
pub fn return_lending_history(&mut self,
778-
start: &str,
779-
end: &str,
780-
limit: &str)
781-
-> Result<Map<String, Value>> {
757+
pub fn return_lending_history(&mut self, start: &str, end: &str, limit: &str) -> Result<Map<String, Value>> {
782758
let mut params = HashMap::new();
783759
params.insert("start", start);
784760
params.insert("end", end);
@@ -801,7 +777,6 @@ impl PoloniexApi {
801777
}
802778
}
803779

804-
805780
#[cfg(test)]
806781
mod poloniex_api_tests {
807782
use super::*;
@@ -827,7 +802,6 @@ mod poloniex_api_tests {
827802
assert!(difference >= 166);
828803
assert!(difference < 1000);
829804

830-
831805
api.set_burst(true);
832806
let start = helpers::get_unix_timestamp_ms();
833807
api.block_or_continue();
@@ -837,7 +811,9 @@ mod poloniex_api_tests {
837811
assert!(difference < 10);
838812

839813
counter = counter + 1;
840-
if counter >= 3 { break; }
814+
if counter >= 3 {
815+
break;
816+
}
841817
}
842818
}
843819
}

0 commit comments

Comments
 (0)