make an order kucoin API in python

2k Views Asked by At
import requests, json, time


url = 'https://api.kucoin.com/api/v1/orders'

headers = {
    "KC-API-KEY": '',
    "KC-API-PASSPHRASE": '',
    "clientOid": "AAA",
    "side": "sell",
    "symbol": "BTC-USDT",
    "type": "market",
    "size": "0.001",
    
}
response = requests.post(url, headers=headers)
print(response.status_code)
print(response.json())

I am trying to place an order but it isn't working. Am I missing some parameters?

Error:

{'code': '400001', 'msg': 'Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE'}
3

There are 3 best solutions below

1
On

try removing the spaces from : data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}

0
On

Did you consider using wrapped library like Python-kucoin ? https://python-kucoin.readthedocs.io/en/stable/index.html

it is really great and will definitely help you. Have a look to the documentation

from kucoin.client import Client

api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'

client = Client(api_key, api_secret, api_passphrase)

# place a market buy order
order = client.create_market_order('BTC-USDT', Client.SIDE_BUY, size=0.001)
0
On

According to the official docs, all private request must contain the following headers:

  • KC-API-KEY
  • KC-API-SIGN
  • KC-API-TIMESTAMP
  • KC-API-PASSPHRASE
  • KC-API-VERSION

Here is an example of the endpoint to place a order limit:

import base64, hmac, hashlib, json

# constants
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
API_PASSPHRASE = "YOUR_API_PASSPHRASE"

url = "https://api.kucoin.com/api/v1/orders"

now = int(time.time() * 1000)

data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}
data_json = json.dumps(data)

str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json

signature = base64.b64encode(hmac.new(API_SECRET.encode(
    'utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())

passphrase = base64.b64encode(hmac.new(API_SECRET.encode(
    'utf-8'), API_PASSPHRASE.encode('utf-8'), hashlib.sha256).digest())

headers = {
    "KC-API-SIGN": signature,
    "KC-API-TIMESTAMP": str(now),
    "KC-API-KEY": API_KEY,
    "KC-API-PASSPHRASE": passphrase,
    "KC-API-KEY-VERSION": "2",
    "Content-Type": "application/json"
}

try:
    res = requests.post(
        url, headers=headers, data=data_json).json()

    print(res)

except Exception as err:
    print(err)

Hope it will help.