· 9 years ago · Dec 02, 2016, 05:16 PM
1class RequestExecutor():
2 def post(self, *args, **kwargs):
3 response = requests.post(*args, **kwargs)
4 response.raise_for_status()
5 return response.json()
6
7 def get(self, *args, **kwargs):
8 response = requests.get(*args, **kwargs)
9 response.raise_for_status()
10 return response.json()
11
12class PoloniexApi:
13
14 def __init__(self, api_key, secret_key, limit_rate=True, request_executor=default_executor):
15 self.api_key = api_key
16 self.secret_key = secret_key
17 self.limit_rate = limit_rate
18
19 if self.limit_rate:
20 self.rate_limiter = defaultRateLimiter
21
22 self.request_executor = request_executor
23
24 def public_api_query(self, command, data=None):
25 if data is None:
26 data = dict()
27
28 data['command'] = command
29
30 self._wait_if_needed()
31 response = self.request_executor.get(PoloniexApi.public_url, params=data)
32
33 if isinstance(response, dict) and 'error' in response.keys():
34 raise PoloniexApiError('API error! Reason: {}'.format(response['error']))
35
36 return response
37
38 def _wait_if_needed(self):
39 if self.limit_rate:
40 self.rate_limiter.wait()
41
42class RateLimiter:
43 def __init__(self, call_limit=6, time_frame=1.0):
44 self.callLimit = call_limit
45 self.time_frame = time_frame
46 self.timeBook = []
47
48 def wait(self):
49 now = time.time()
50
51 # if it's our turn
52 if len(self.timeBook) is 0 or (now - self.timeBook[-1]) >= self.time_frame:
53 # add 'now' to the front of 'timeBook', pushing other times back
54 self.timeBook.insert(0, now)
55
56 # 'timeBook' list is longer than 'callLimit'?
57 if len(self.timeBook) > self.callLimit:
58 # remove the oldest time
59 self.timeBook.pop()
60 else:
61 # wait your turn (maxTime - (now - oldest)) = time left to wait
62 time.sleep(self.time_frame-(now - self.timeBook[-1]))
63
64 # add 'now' to the front of 'timeBook', pushing other times back
65 self.timeBook.insert(0, time.time())
66
67 # 'timeBook' list is longer than 'callLimit'?
68 if len(self.timeBook) > self.callLimit:
69 # remove the oldest time
70 self.timeBook.pop()
71
72defaultRateLimiter = RateLimiter()