Skip to content

Commit

Permalink
api: rework _query() retries code with suggestions from PR #65.
Browse files Browse the repository at this point in the history
  • Loading branch information
veox committed Sep 13, 2018
1 parent 756fcb7 commit afd6eb6
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions krakenex/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,13 @@ def __init__(self, key='', secret=''):
'User-Agent': 'krakenex/' + version.__version__ + ' (+' + version.__url__ + ')'
})
self.response = None
# How many times we try to recover from bad HTTP connection situation
self.bad_http_connection_retries = 3

# retry-on-failure configuration
self.retries = 1
self.cooldown = 15
self.successcodes = [200, 201, 202]
self.retrycodes = [504, 520]

return

def close(self):
Expand Down Expand Up @@ -121,23 +126,24 @@ def _query(self, urlpath, data, headers=None):

url = self.uri + urlpath

# Retries mechanism for certain HTTP codes.
# Kraken is behind CloudFlare which adds to network requests instability during peaks
# Careful! Sometimes service returns error code but actuallu executes a request
# needs investigation if this can cause a multiple buys/sells (don't think so as there is nonce in each request )
attempt = 1
while attempt<=self.bad_http_connection_retries:
attempt = 0
while attempt < self.retries:
logger.debug('Posting query: nonce %d, attempt %d.', data['nonce'], attempt)
self.response = self.session.post(url, data = data, headers = headers)
status = self.response.status_code

if self.response.status_code in (200, 201, 202):
return self.response.json()
elif self.response.status_code in (504, 520) and attempt<self.bad_http_connection_retries:
logger.debug("HTTP Error. Status Code %d. Attempting to reconnect (attempt: %d)", self.response.status_code, attempt)
attempt = attempt + 1
if status in self.successcodes:
break
elif status in self.retrycodes and attempt < self.retries:
logger.debug('HTTP error %d', status)
logger.debug('Sleeping for %d seconds', self.cooldown)
time.sleep(self.cooldown)
attempt += 1
else:
# Raises stored HTTPError, if one occurred.
self.response.raise_for_status()

return self.response.json()

def query_public(self, method, data=None):
""" Performs an API query that does not require a valid key/secret pair.
Expand Down

0 comments on commit afd6eb6

Please sign in to comment.