0

api_secret etc. not left blank in run code. only to hide it here. get output : {'code': '400005', 'msg': 'Invalid KC-API-SIGN'} it works for other POST orders, eg. buy/sell.

def borrow_margin(currency, amount):
    api_key = ****************
    api_secret = ****************
    api_passphrase = ****************
    url = 'https://api.kucoin.com/api/v1/margin/borrow'

    order = {'currency':currency,'type':'FOK','size':amount}
    order_json = json.dumps(order)

    now = int(time.time() * 1000)
    str_to_sign = str(now) + 'POST' + '/api/v1/margin/borrow' + order_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"
    }

    req = requests.request('post', url, headers=headers).json()
    print(req)


borrow_margin('USDT', 50.0)

output : {'code': '400005', 'msg': 'Invalid KC-API-SIGN'}

2 Answers2

0

should be : req = requests.request('POST', url=url, headers=headers, data=order_json).json()

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 24 '23 at 09:58
0

This one was a head-scratcher for me as well. here is my current (working) code for the futures API: how to get account info, how to open position, and how to close position.

Clarification regarding KC_place_order(curr, side, amount): *The argument 'curr' refers to the trading pair you are using: e.g. a string value like 'FTM-USDT', 'ETH-USDT' etc. *'side' is a string value for long or short position: e.g. 'buy' or 'sell' *'amount' is a float value for the quantity of the currency you like to trade.

Code is not perfect, I know, but it's working. Code will be slightly different for the spot API btw: ask me if anyone would like me to post that as well.

Good luck! =)

    import time
    import base64
    import hmac
    import hashlib
    import requests
    import json
    import uuid
    import datetime
    from dateutil import parser
    import pandas as pd
    import numpy as np
    import os

def get_equity_account(): 

    client0id = uuid.uuid4().hex
    client0id = str(client0id)
    api_key = "your api_key"
    api_secret = "your api_secret"
    api_passphrase = "your api_passphrase"

    #Get account equity in USDT
    url = 'https://api-futures.kucoin.com/api/v1/account-overview?currency=USDT'
    now = int(time.time() * 1000)
    data = {"clientOid": client0id,'currency':'FTM'}
    data_json = json.dumps(data)
    str_to_sign = str(now) + 'GET' + '/api/v1/account-overview?currency=USDT' + 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" # specifying content type or using json=data in request
    }
    response = requests.request('GET', url, headers=headers, data=data_json)
    # print(response.status_code)
    # pprint(response.json())
    # print(response.json()['data']['accountEquity'])
    equity = float(response.json()['data']['accountEquity'])
    return equity

    # server message example: 
    #     {'code': '200000',
    #  'data': {'accountEquity': 19834.517194515,
    #           'availableBalance': 19834.517194515,
    #           'currency': 'USDT',
    #           'frozenFunds': 0,
    #           'marginBalance': 19834.517194515,
    #           'orderMargin': 0.0,
    #           'positionMargin': 0,
    #           'unrealisedPNL': 0}}


def KC_place_order(curr, side, amount):

    leverage = '< float with whatever leverage you prefer >'

    # curr_URL = curr.replace('-', '') + 'M' - only for futures trading. Original curr string for spot
    curr_replace = curr.replace('-','_')
    curr_URL = curr.replace('-', '') + 'M'
    curr_equity_symbol = curr.replace('-USDT', '')
    client0id = uuid.uuid4().hex
    client0id = str(client0id)
    api_key = "your api_key"
    api_secret = "your api_secret"
    api_passphrase = "your api_passphrase"
    url = 'https://api-futures.kucoin.com/api/v1/orders'
    now = int(time.time() * 1000)
    data = {"clientOid": client0id, "symbol": curr_URL, "side": side, "type": "market", 'leverage': leverage, "size": amount} #how to set stop loss? Check dev docs!
    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" # specifying content type or using json=data in request
        }
    response = requests.request('POST', url, headers=headers, data=data_json)
    print(response.status_code)
    print(response.json())

    #"closeOrder": True,
    #"side": "sell"
    #'leverage': 5
    #data = {"clientOid": client0id,"symbol": "FTMUSDTM", "side": "buy", "type": "market",'leverage': '5', "size": 10}
    #KC_place_order(curr, side, amount, equity_deal)
    return response

def KC_close_position(curr):

    #get equity of a certain currency
    #sell the enirety of that equity
    curr_URL = curr.replace('-', '') + 'M'
    curr_replace = curr.replace('-','_')
    curr_equity_symbol = curr.replace('-USDT', '')

    client0id = uuid.uuid4().hex
    client0id = str(client0id)
    api_key = "your api_key"
    api_secret = "your api_secret"
    api_passphrase = "your api_passphrase"
    url = 'https://api-futures.kucoin.com/api/v1/orders'
    now = int(time.time() * 1000)
    data = {"clientOid": client0id,"symbol": curr_URL, "type": "market", "closeOrder": True,} 
    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" # specifying content type or using json=data in request
    }
    response = requests.request('POST', url, headers=headers, data=data_json)
    print(response.status_code)
    print(response.json())


    return response