I have been coding in Python the Kucoin API and I have gotten to a point at which I am stuck. The error I get is as follows:
API request failed with status code 401
Error response: {"code":"400005","msg":"Invalid KC-API-SIGN"}
Here is my full code, my API key, secret key and passphrase are hidden for obvious reasons.
import requests
import json
import hmac
import hashlib
import time
# Replace with your KuCoin API key, secret, and passphrase
api_key = 'API_Key'
api_secret = 'SECRET'
api_passphrase = 'PASSPHRASE'
# Replace with your trading parameters
symbol = 'XRP-USDT'
quantity = 31.1022642448
risk_percent = 15
# KuCoin API endpoints
base_url = 'https://api.kucoin.com'
create_order_url = '/api/v1/orders'
historical_klines_url = '/api/v1/market/candles'
ticker_url = '/api/v1/market/orderbook/level1'
account_url = '/api/v1/accounts'
# Function to create a request header with authentication
def create_headers(method, endpoint, timestamp, data=''):
str_to_sign = f'{method.upper()} {endpoint}{timestamp}{data}'
signature = hmac.new(api_secret.encode(), str_to_sign.encode(), hashlib.sha256).hexdigest()
headers = {
'KC-API-KEY': api_key,
'KC-API-TIMESTAMP': str(timestamp),
'KC-API-PASSPHRASE': api_passphrase,
'KC-API-SIGN': signature,
'Content-Type': 'application/json'
}
return headers
# Function to get the current price
def get_current_price(symbol):
endpoint = f'{ticker_url}?symbol={symbol}'
response = requests.get(f'{base_url}{endpoint}')
return float(response.json()['price'])
response = None
# Function to get the account balance
def get_account_balance():
global response # Use the global keyword to indicate that we are referring to the global variable
try:
endpoint = account_url
timestamp = int(time.time() * 1000)
headers = create_headers('GET', endpoint, timestamp)
response = requests.get(f'{base_url}{endpoint}', headers=headers)
if response.status_code == 200:
# Successful response
return float(response.json()[0]['balance'])
else:
# Print the error details
print(f"API request failed with status code {response.status_code}")
print(f"Error response: {response.text}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
# Function to get historical klines (candlestick data) from KuCoin
def get_historical_klines(symbol, interval, limit=100):
endpoint = f'{historical_klines_url}?symbol={symbol}&interval={interval}&limit={limit}'
response = requests.get(f'{base_url}{endpoint}')
return response.json()['data']['candles']
# Function to calculate the Supertrend value (more complex example)
def calculate_supertrend(data, atr_length, multiplier):
high_prices = [float(entry[2]) for entry in data]
low_prices = [float(entry[3]) for entry in data]
close_prices = [float(entry[4]) for entry in data]
# Calculate True Range (TR)
tr = [max(high_prices[i] - low_prices[i], abs(high_prices[i] - close_prices[i - 1]), abs(low_prices[i] - close_prices[i - 1])) for i in range(1, len(data))]
# Calculate Average True Range (ATR)
atr = sum(tr[-atr_length:]) / atr_length
# Calculate the Supertrend direction (1 for up, -1 for down)
supertrend_direction = 1 if close_prices[-1] > close_prices[-2] else -1
# Calculate the Supertrend value
supertrend = close_prices[-1] + supertrend_direction * multiplier * atr
return supertrend
# Function to place a market order
def place_market_order(symbol, side, quantity):
endpoint = create_order_url
timestamp = int(time.time() * 1000)
data = {
'symbol': symbol,
'side': side,
'type': 'MARKET',
'quantity': quantity,
}
headers = create_headers('POST', endpoint, timestamp, json.dumps(data))
response = requests.post(f'{base_url}{endpoint}', headers=headers, data=json.dumps(data))
return response.json()
# Main trading logic
while True:
try:
# Get account balance
equity = get_account_balance()
# Get historical klines data from KuCoin
historical_data = get_historical_klines(symbol, '1hour', limit=10)
# Get the current price
current_price = get_current_price(symbol)
# Calculate Supertrend value
supertrend_value = calculate_supertrend(historical_data, 10, 3.0)
# Buy condition
if current_price > supertrend_value:
position_size = equity * risk_percent / supertrend_value
order_response = place_market_order(symbol, 'buy', position_size)
print(f"Buy order executed: {order_response}")
# Sell condition
elif current_price < supertrend_value:
position_size = equity * risk_percent / supertrend_value
order_response = place_market_order(symbol, 'sell', position_size)
print(f"Sell order executed: {order_response}")
time.sleep(60) # Adjust the sleep interval based on your trading frequency
except Exception as e:
print(f"An error occurred: {e}")
if response is not None:
print(f"Error response: {response.text}")
I have been looking around for a fix for my problem but nothing seems to work as of now. I looked at the documentation and it says they error 401 means that the API key is wrong, however I can confirm it is 100% correct.