Sumtinlazy
Sumtinlazy

Reputation: 347

Unsure how to authenticate my api key Kucoin

I am learning how to use the Kucoin and am having trouble with the authenticating myself to the API server.

I am trying to load all of the active orders however keep getting a 401 error.

The Kucoin API documentation states that I need to add this:

{
    "KC-API-KEY": "59c5ecfe18497f5394ded813",  
    "KC-API-NONCE" : 1506219855000   //Client timestamp (exact to 
milliseconds), before using the calibration time, the server does not 
accept calls with a time difference of more than 3 seconds
    "KC-API-SIGNATURE" : 
"fd83147802c361575bbe72fef32ba90dcb364d388d05cb909c1a6e832f6ca3ac"   
//signature after client encryption
}

as a parameter to headers of request. I am unsure what this means. Any help will be appreciated.

Upvotes: 3

Views: 2793

Answers (2)

blackraven
blackraven

Reputation: 5627

Here are my working codes in Python 3:

import requests
import json
import hmac
import hashlib
import base64
from urllib.parse import urlencode
import time

api_key = 'xxxxx'
api_secret = 'xx-xxx-xx'
api_passphrase = 'xxx'   #note that this is *not* trading password
base_uri = 'https://api.kucoin.com'

def get_headers(method, endpoint):
    now = int(time.time() * 1000)
    str_to_sign = str(now) + method + endpoint
    signature = base64.b64encode(hmac.new(api_secret.encode(), str_to_sign.encode(), hashlib.sha256).digest()).decode()
    passphrase = base64.b64encode(hmac.new(api_secret.encode(), api_passphrase.encode(), hashlib.sha256).digest()).decode()
    return {'KC-API-KEY': api_key,
            'KC-API-KEY-VERSION': '2',
            'KC-API-PASSPHRASE': passphrase,
            'KC-API-SIGN': signature,
            'KC-API-TIMESTAMP': str(now)
    }

#List Accounts
method = 'GET'
endpoint = '/api/v1/accounts'
response = requests.request(method, base_uri+endpoint, headers=get_headers(method,endpoint))
print(response.status_code)
print(response.json())

Output

200
{'code': '200000', 'data': [{'available': blah,blah,blah  }]}

Upvotes: 1

Sam McHardy
Sam McHardy

Reputation: 126

Creating the header can be a little tricky.

For the nonce value, or any millisecond timestamp value, I've found the best way to generate this is like this

import time
int(time.time() * 1000)

The signature requires you to order the parameters alphabetically in a query string format, combine that with the path and nonce and then hash the string using sha256 with your secret key.

If you'd like to implement it yourself feel free to copy the code from here, it's split over a few functions and should be quite readable https://github.com/sammchardy/python-kucoin/blob/0ece729c406056a428a57853345c9931d449be02/kucoin/client.py#L117

Or alternatively you may be best off just using that library. (Note: I'm the author and maintainer of python-kucoin)

Upvotes: 1

Related Questions