Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection: Implement a mechanism to retry failed HTTP requests for certain status_codes #65

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions krakenex/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import hashlib
import hmac
import base64
import logging

from . import version

Expand Down Expand Up @@ -66,6 +67,8 @@ 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
return

def close(self):
Expand Down Expand Up @@ -109,20 +112,31 @@ def _query(self, urlpath, data, headers=None):
:raises: :py:exc:`requests.HTTPError`: if response status not successful

"""
logger = logging.getLogger()

if data is None:
data = {}
if headers is None:
headers = {}

url = self.uri + urlpath

self.response = self.session.post(url, data = data, headers = headers)

if self.response.status_code not in (200, 201, 202):
self.response.raise_for_status()

return self.response.json()

# 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:
self.response = self.session.post(url, data = data, headers = headers)

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
else:
# Raises stored HTTPError, if one occurred.
self.response.raise_for_status()

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