I have a problem when I send an order to kucoin exchange with the API.
"code":"429000","msg":"Too Many Requests"
It seems that my code sends too many requests to Kucoin, my IP address exceed the rate limit (the request rate limit is 30 times/3s).
It happen when I create only one order, when I create an order, I only have 3 requests:
get Wallet balance:
def get_usdt_balance():
try:
acc_balance = exchange.fetch_balance()
return acc_balance['USDT']['free']
except Exception as e:
print("an exception occured - {}".format(e))
return False
get the contract size of a symbol:
def get_contractSize(symbol):
contractsize= exchange.market(symbol)['contractSize']
return contractsize
create an order
def order(side, quantity, symbol):
i = 0
while i < 10:
i += 1
try:
params = {'leverage': 15}
order = exchange.create_order(
symbol=symbol,
side=side,
type='market',
amount=quantity,
params=params)
except Exception as e:
print("an exception occured - {}".format(e))
print ('- Retry n°',i,'...')
time.sleep(11)
continue
else:
print ("ORDER EXECUTED")
print(f"sending order {side} - {symbol}")
i == 0
return order
As you can see in the last request, I should set up a "retry if fail" because the 429 error always come, the code wait 11 seconds, and retry, sometime it should retry 6 times to work. So I'll lose more than one minute retrying, (its a scalping strategy I cannot wait that much) for only one order (3 requests) for only one account.
So how can we explain that the code exceed the request rate limit with only 3 requests?
As of March 8, 2023, it seems that Kucoin is doing a bit better in terms of 429-Too Many Requests. The best you can do is just retrying after 100ms. I haven't found any other way. Those errors are very annoying and random.
pip install retrying
from retrying import retry
def retry_on_429_too_many_requests(e):
if '429' in str(e):
logger.warning(f'Retry on 429: {str(e)}.')
return True
return False
@retry(stop_max_attempt_number=9, wait_fixed=100, retry_on_exception=retry_on_429_too_many_requests)
def request_to_kucoin(*args, **kwargs):
pass # make a request to Kucoin.
a bit improved algorithm of @Philippe Remy solution with less often notifications:
begin
result = @http.send(method, u, headers)
if result.code == "429"
sleep 100
raise Retry
end
rescue Retry
handle_retries retries += 1, url, data
retry
end
def handle_retries retries, url, data
debug_data = {retries: retries, url: url, data: data}
if retries % 10 == 0
puts "Retry more than 10 times", debug_data
end
raise "Too much http retries" if retries % 50 == 0
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With