diff --git a/src/poloniex/api.rs b/src/poloniex/api.rs index f1c147c..f266fee 100644 --- a/src/poloniex/api.rs +++ b/src/poloniex/api.rs @@ -47,6 +47,7 @@ pub struct PoloniexApi { api_key: String, api_secret: String, http_client: Client, + burst: bool, } @@ -69,15 +70,27 @@ impl PoloniexApi { api_key: creds.get("api_key").unwrap_or_default(), api_secret: creds.get("api_secret").unwrap_or_default(), http_client: Client::with_connector(connector), + burst: false, }) } + /// The number of calls in a given period is limited. In order to avoid a ban we limit + /// by default the number of api requests. + /// This function sets or removes the limitation. + /// Burst false implies no block. + /// Burst true implies there is a control over the number of calls allowed to the exchange + pub fn set_burst(&mut self, burst: bool) { + self.burst = burst + } + fn block_or_continue(&self) { - let threshold: u64 = 167; // 6 requests/sec = 1/6*1000 - let offset: u64 = helpers::get_unix_timestamp_ms() as u64 - self.last_request as u64; - if offset < threshold { - let wait_ms = Duration::from_millis(threshold - offset); - thread::sleep(wait_ms); + if ! self.burst { + let threshold: u64 = 167; // 6 requests/sec = 1/6*1000 + let offset: u64 = helpers::get_unix_timestamp_ms() as u64 - self.last_request as u64; + if offset < threshold { + let wait_ms = Duration::from_millis(threshold - offset); + thread::sleep(wait_ms); + } } } @@ -787,3 +800,44 @@ impl PoloniexApi { self.private_query("toggleAutoRenew", ¶ms) } } + + +#[cfg(test)] +mod poloniex_api_tests { + use super::*; + + #[test] + fn should_block_or_not_block_when_enabled_or_disabled() { + let mut api = PoloniexApi { + last_request: helpers::get_unix_timestamp_ms(), + api_key: "".to_string(), + api_secret: "".to_string(), + http_client: Client::new(), + burst: false, + }; + + let mut counter = 0; + loop { + api.set_burst(false); + let start = helpers::get_unix_timestamp_ms(); + api.block_or_continue(); + api.last_request = helpers::get_unix_timestamp_ms(); + + let difference = api.last_request - start; + assert!(difference >= 166); + assert!(difference < 1000); + + + api.set_burst(true); + let start = helpers::get_unix_timestamp_ms(); + api.block_or_continue(); + api.last_request = helpers::get_unix_timestamp_ms(); + + let difference = api.last_request - start; + assert!(difference < 10); + + counter = counter + 1; + if counter >= 3 { break; } + } + } +}