Skip to content

Commit

Permalink
Explain the burst concept in comments for Poloniex
Browse files Browse the repository at this point in the history
  • Loading branch information
ainestal committed Aug 12, 2017
1 parent c513afd commit a002918
Showing 1 changed file with 59 additions and 5 deletions.
64 changes: 59 additions & 5 deletions src/poloniex/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub struct PoloniexApi {
api_key: String,
api_secret: String,
http_client: Client,
burst: bool,
}


Expand All @@ -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);
}
}
}

Expand Down Expand Up @@ -787,3 +800,44 @@ impl PoloniexApi {
self.private_query("toggleAutoRenew", &params)
}
}


#[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; }
}
}
}

0 comments on commit a002918

Please sign in to comment.