Kucoin API error 401: Unauthorized -- Invalid API Key

187 Views Asked by At

I'm trying to automate some trading orders on Kucoin API for spot market. This how is my current code looks like:

import os
import hmac
import time
import json
import base64
import hashlib
import requests


kucoin_api = os.environ['kucoin_api']
api_key = os.environ['api_key']
api_secret_key = os.environ['api_secret_key']
check_price_endpoint = os.environ['check_price_endpoint']
open_trade_endpoint = os.environ['open_trade_endpoint']
get_coin_balance_endpoint = os.environ['get_coin_balance_endpoint']
api_passphrase = os.environ['api_passphrase']


def get_courrent_price(trading_pair):
    timestamp = int(time.time() * 1000)
    params = {
        'symbol': trading_pair
    }
    signature = create_kucoin_signature(api_secret_key, check_price_endpoint, timestamp, params=params)
    headers = {
        'KC-API-KEY': api_key,
        'KC-API-TIMESTAMP': str(timestamp),
        'KC-API-SIGN': signature
    }
    response = requests.get(kucoin_api + check_price_endpoint, headers=headers, params=params)
    price = float(json.loads(response.text)['data']['price']) if response.status_code == 200 else 0
    return price


def get_courrent_balance(currency=None, account_type=None):
    timestamp = int(time.time() * 1000)
    params = {
        'currency': currency,
        'type': 'trade',
    }
    signature = create_kucoin_signature(api_secret_key, get_coin_balance_endpoint, timestamp, params=params)
    passphrase = base64.b64encode(hmac.new(api_key.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
    headers = {
        'KC-API-KEY': api_key,
        'KC-API-TIMESTAMP': str(timestamp),
        'KC-API-SIGN': signature,
        'KC-API-PASSPHRASE': passphrase,
        'KC-API-KEY-VERSION': '2',
    }
    response = requests.get(kucoin_api + get_coin_balance_endpoint, headers=headers, params=params)
    return 


def create_kucoin_signature(api_secret_key, endpoint, timestamp, params=None):
    data = endpoint + '/' + str(timestamp)
    if params:
        sorted_params = sorted(params.items())
        data += '/' + '/'.join([f"{k}-{v}" for k, v in sorted_params])

    signature = hmac.new(api_secret_key.encode(), data.encode(), hashlib.sha256).hexdigest()
    return signature

The request for my get_courrent_price function it's correct and return the current coin pair price, but the get_courrent_balance(currency='BTC') return a request.status_code = 401, which means:

Unauthorized -- Invalid API Key.

I don't understand this since I'm using the same API Key for both functions, even delete and create the API 3 times and checked multiple times that the values are correct.

Can anyone please help me with this issue?

0

There are 0 best solutions below