Skip to content

Commit afd6eb6

Browse files
committed
api: rework _query() retries code with suggestions from PR #65.
1 parent 756fcb7 commit afd6eb6

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

krakenex/api.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,13 @@ def __init__(self, key='', secret=''):
6767
'User-Agent': 'krakenex/' + version.__version__ + ' (+' + version.__url__ + ')'
6868
})
6969
self.response = None
70-
# How many times we try to recover from bad HTTP connection situation
71-
self.bad_http_connection_retries = 3
70+
71+
# retry-on-failure configuration
72+
self.retries = 1
73+
self.cooldown = 15
74+
self.successcodes = [200, 201, 202]
75+
self.retrycodes = [504, 520]
76+
7277
return
7378

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

122127
url = self.uri + urlpath
123128

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

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

145+
return self.response.json()
146+
141147
def query_public(self, method, data=None):
142148
""" Performs an API query that does not require a valid key/secret pair.
143149

0 commit comments

Comments
 (0)