KuCoin API – An Introductory Guide

10 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on April 3, 2023

kucoin guide

Table of contents:

  1. What is KuCoin API?
  2. What is KuCoin?
  3. What can I trade on KuCoin?
  4. Is KuCoin free?
  5. What are KuCoin Shares (KCS)?
  6. Why should I use KuCoin?
  7. Why shouldn’t I use the KuCoin?
  8. What are the alternatives to using KuCoin?
  9. What clients are available for the KuCoin API?
  10. How to get started with KuCoin API?
  11. How to get ticker info with KuCoin API?
  12. How to get Price Data on KuCoin API?
  13. How to get historical data with KuCoin API?
  14. How to access technical indicators such as the 20 SMA with the KuCoin API?
  15. How to get Order Book data with KuCoin API?
  16. What types of orders does KuCoin support?
  17. How to execute a trade on ETH when BTC hits a certain price with the KuCoin API?
  18. How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the KuCoin API?
  19. How to cancel orders with KuCoin API?
  20. Full code

What is Kucoin API?

KuCoin API is a method that allows us to automatically trade cryptocurrencies on KuCoin via code.

Link: https://www.kucoin.com

What is KuCoin?

KuCoin is an online cryptocurrency exchange platform that allows its users to trade a variety of cryptocurrency spot, perpetuals and futures assets.

What can I trade on KuCoin?

As KuCoin is a cryptocurrency platform you can trade a decent amount of coins (over 200) and the most notable ones are BTC, ETH, XRP, LTC, LUNA, EOS, and more.

Moreover, KuCoin supports buying cryptocurrencies with fiat (USD, EUR, CAD, GBP, and more) with their P2P fiat trade, Fast Buy Service, or with a credit or debit card.

Is KuCoin free?

Yes, setting up an account on KuCoin is free, easy, and fast.

When it comes to the trading fees KuCoin is known for its low fee rates. Mainly, there are 13 (0-12) trading fee tiers that you can climb in two ways which are the following:

  • Having a bigger monthly trading volume
  • Staking their own cryptocurrency

For example, in the spot trading fee schedule on tier 0, the Maker/Taker fees are set to 0.1% with a 24h withdrawal amount in BTC set to 200.

On tier 7 the Maker fee ends up being 0% while the Taker fee goes down to 0.05% and the withdrawal limit goes up to 500. For a more detailed look on the Spot and Futures market fees proceed to the following website:

https://www.kucoin.com/vip/level?lang=en_US

KuCoin’s rival when it comes to the low fees is Binance as the two exchanges have similar fee levels. KuCoin might pull up an upper hand as it has the KuCoin Shares that allow for staking.

What are KuCoin Shares (KCS)?

KuCoin Shares (KCS) are native KuCoin tokens that offer special things like trading discounts, unlock more trading pairs, daily crypto dividends, perks, offers, and more. You can stake your KCS to unlock these special perks.

KCS can be bought or obtained through referral links.

Why should I use KuCoin?

  • KuCoin is free
  • Has low fees
  • Easy to use
  • Beginner-friendly
  • Has a decent amount of cryptos
  • Has a mobile app
  • Allows Staking
  • Can buy crypto with fiat

Why shouldn’t I use KuCoin?

  • KuCoin has a lower trading volume when compared to other exchanges
  • KuCoin has been hacked in 2020 with about $280 million worth of assets stolen
  • Can experience API delays on days with high traffic
  • Experiences bad server latency

Is KuCoin available in my country?

KuCoin is available in all countries for unverified accounts. The information about available countries will be provided upon the completion of the KYC regulation that verifies the account.

Sadly, there is no documentation on the full list of restricted countries when it comes to KuCoin and far as I’ve seen they weren’t open about it.

What are the alternatives to using KuCoin?

KuCoin can be replaced with other applications that can be more suitable for you needs. Here is the list:

What clients are available for the KuCoin API?

When it comes to the available official SDK of KuCoin they are the following:

How to get started with KuCoin API?

In order to get started with KuCoin and explore their offerings and API usage, we will need to go over to their website and create an account. In order to do this, go to the following link and hit sign-up:

https://www.kucoin.com/

After that, you will be taken to a new page where you will first need to provide your email to obtain a verification code. Upon completion, you can set up your password and referral code (if you have one).

Have in mind that you can provide your phone number, instead of an email, for the verification process.

Welcome to KuCoin! In order to obtain the API key go to the big white circle in the upper right corner and select the API Management option.

When there, you will be required to complete an SMS or Google Verification process and a Trading password setup. To do this, just click on the green “Edit” words that will take you to the right steps.

After you have completed the verification process and set your trading password go back to the API Management tab and hit the “Create API” button.

When there, you will name your API, create a secret passphrase for it, and give it the permissions you want. For this guide, I’ll give it the General and Trade permissions. You can also restrict the API to an IP address.

After that, be sure to save your API Key and API Secret to a secure place. The API Secret won’t be showable anymore after you close the API information pop-up.

Now that the API Key is ready, we can freely explore what the KuCoin API has to offer. We will start with the public endpoints and finish with two trading scenarios.

Be sure to install the KuCoin Python library with the following command:

pip install kucoin-python

Have in mind that the API request limit is set to 1800 calls per minute.

How to get ticker info with KuCoin API?

Tickers can be obtained from KuCoin in several ways by utilizing the python library. Let us set up the client and check what the market list is composed of:

import pandas as pd
from kucoin.client import Market
client = Market(url='https://api.kucoin.com')

symbols = client.get_market_list()
symbols
['USDS', 'BTC', 'KCS', 'ALTS', 'DeFi', 'NFT', 'Polkadot']

This shows us the main categories but what we really want is the list of all available tickers. We will request them and arrange the data into a pandas data frame for a better observation.

tickers = client.get_all_tickers()
tickers = pd.DataFrame(tickers['ticker'])
tickers.set_index('symbol', inplace=True)
tickers.head().T

There are 577 pairs in total.

As some of you may have experienced by now, the Python library isn’t optimized for speed and you can easily get a connection timeout. Take note that KuCoin has some delay when too much trading starts going on.

Thus, we will switch to using the regular request method and get a list of available currencies.

import requests
import json
import datetime
url = 'https://api.kucoin.com'
currencies = requests.get(url + '/api/v1/currencies')
currencies = currencies.json()
currencies = pd.DataFrame(currencies['data'])
currencies.set_index('currency', inplace=True)
print('There are {} currencies'.format(len(currencies)))
currencies.head().T

How to get Price Data on KuCoin API?

In order to obtain Price Data on KuCoin issue the following request:

ticker = requests.get(url + '/api/v1/market/orderbook/level1?symbol=BTC-USDT').json()
ticker['data']
{'time': 1615475368927,
 'sequence': '1614104704724',
 'price': '56977.4',
 'size': '0.001',
 'bestBid': '56971.5',
 'bestBidSize': '0.00009434',
 'bestAsk': '56971.6',
 'bestAskSize': '0.00017804'}

If you want to see how a certain asset performed in a 24-hour interval do the following:

ticker_24h = requests.get(url + '/api/v1/market/stats?symbol=BTC-USDT').json()
ticker_24h['data']
{'time': 1615475556056,
 'symbol': 'BTC-U5DT',
 'buy': '56998.3',
 'sell': '57000',
 'changeRate': '0.013',
 'changePrice': '736.7',
 'high': '57364',
 'low': '54238',
 'vol': '3712.3667572',
 'volValue.: '208342804.860257668',
 'last': '57000',
 'averagePrice': '54559.31856369',
 'takerFeeRate': '0.001',
 'makerFeeRate': '0.001',
 'takerCoefficient': '1',
 'makerCoefficient': '1'} 

To get the fiat price for a specific asset write the following code:

fiat = requests.get(url + '/api/v1/prices?base=USD').json()
fiat['data']
{'LOKI': '1.01001475',
 'DFI': '3.74945229',
 'IOTX': '0.03639693',
 'MC': '0.0167',
 'FRONT': '2.13320120',
 'MXEU: '0.01922177',
 'TFD': '0.06198852',
 'DOCK': '0.09895415',
 'SUSD': '1.02366360',
 'REVV': '0.22804950',
 'STX': '1.13057958',
 'OLT': '0.01097026',
 'DENT': '0.00207008',
 'AION': '0.18767166',
 'NPXS.: '0.00230893',
 'TFL': '0.31107999',
 'XNS': '0.00056870',
 'GMB': '0.00070519',
 'DGB': '0.06198852', 

How to get historical data with KuCoin API?

In order to obtain historical data from KuCoin we must utilize the correct endpoint and arrange the data into a pandas data frame for a better look. We will also convert the timestamp to a readable format.

history = requests.get(url + '/api/v1/market/histories?symbol=BTC-USDT')
history = history.json()
history = pd.DataFrame(history['data'])
history['time'] = pd.to_datetime(history['time'])
history.set_index('time', inplace=True)
history

Now let us obtain the candles for our symbol, clean up the response and arrange the data.

kline = requests.get(url + '/api/v1/market/candles?type=1min&symbol=BTC-USDT&startAt=1566703297&endAt=1566789757')
kline = kline.json()
kline = pd.DataFrame(kline['data'])
kline = kline.rename({0:"Time",1:"Open",
                2:"Close",3:"High",4:"Low",5:"Amount",6:"Volume"}, axis='columns')
kline.set_index('Time', inplace=True)
kline.head()

How to access technical indicators such as the 20 SMA with the KuCoin API?

To calculate the 20SMA we can do a simple pandas transformation. Let us proceed and do the transformation on the closing prices of the previous example.

kline['20 SMA'] = kline.Close.rolling(20).mean()
kline.tail()

How to get Order Book data with KuCoin API?

Order Book data on KuCoin has 3 different endpoints and they are the following:

Part Order Book (aggregated) – as the name suggests, this order book only bids and asks up to a certain level which you can set in your request (e.g. level_100 return 100 instances)

Full Order Book (aggregated) – this endpoint returns an order book with full depth and it is most often used by advanced traders. As it noticeably uses the KuCoin server resources it has a strict frequency control.

Full Order Book (atomic) – this endpoint provides level 3 order book data for a specified pair. The data is not aggregated and every instance is a single order, hence the name atomic. This endpoint is also under strict frequency control.

For this article, we will obtain the Part Order Book with 20 levels. Then, we shall clean up the response by creating 2 separate data frames for bids and asks. I’ll also show you how to merge them for a better observation.

orderbook = requests.get(url + '/api/v1/market/orderbook/level2_20?symbol=BTC-USDT')
orderbook = orderbook.json()
orderbook
bids = pd.DataFrame(orderbook['data']['bids'])
asks = pd.DataFrame(orderbook['data']['asks'])

df = pd.merge(bids, asks, left_index=True, right_index=True)
df = df.rename({"0_x":"Bid Price","1_x":"Bid Amount",
                "0_y":"Ask Price","1_y":"Ask Amount"}, axis='columns')
df.head()

What types of orders does KuCoin support?

KuCoin supports 3 types of orders and those are spot, margin, stop and bulk orders. Let us go briefly over the stop and bulk order as the first two are widely known by people that don’t even have their foot in the field.

A stop order is where you specify the amount of cryptos at the last traded price or pre-specified limit price once the order has traded at or through a pre-specified stop price. The order is then executed by the highest price first.

On the other hand, the bulk order allows you to execute 5 orders at the same time. The orders must be limit orders of the same symbol.

As now we know what kind of orders KuCoin offers, let us go ahead and explore two simple trading scenarios.

How to execute a trade on ETH when BTC hits a certain price with the KuCoin API?

In the first example, I will show you how to properly and securely launch orders with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price (e.g. $57200).

In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping around.

When the price is executed we will wait for a few seconds and then check if the order was really filled. This additional step is very important to have in your trading strategies as the exchange server may encounter some troubles.

Now that we have the main idea in mind it is time to set up the trade foundation. We will set up the trading client and add the API Key, API Secret, and API Passphrase variables.

from kucoin.client import Trade
from kucoin.client import Market
import pandas as pd
from time import sleep

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

m_client = Market(url='https://api.kucoin.com')
client = Trade(api_key, api_secret, api_passphrase, is_sandbox=True)

Before we build the main loop that will check if the trading requirement is satisfied let us cover the parameters that you can pass when executing an order.

  • clientOid – this is a unique order id that is created by you so the order can be identified
  • side – buy or sell
  • symbol – symbol code
  • type – (optional) limit or market (default is set to limit)
  • remark – (optional) remark for the order
  • stp – (optional) self trade prevention, CN, CO, DC, or CB
  • tradeType – (optional) TRADE = Spot Trade, MARGIN_TRADE = Margin Trade. Default is set to trade.

Now for the main part of our script:

while True:
    try:
        btc = m_client.get_ticker('BTC-USDT')
        print('The price of BTC at {} is:'.format(pd.Timestamp.now()), btc['price'])
    except Exception as e:
        print(f'Error obtaining BTC data: {e}')
        
    if float(btc['bestAsk']) < 57200.00:
        continue
        
    elif float(btc['bestAsk']) >= 57200.00: 
        try:
            order = client.create_market_order('ETH-USDT', 'buy', size='5')
            print()
        except Exception as e:
            print(f'Error placing order: {e}')
            
        sleep(2)
        
        try:
            check = client.get_order_details(orderId=order['orderId'])
            print(check)
        except Excpetion as e:
            print(f'Error while checking order status: {e}')
            
        if check['isActive'] == true:
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
            
        else:
            print('Order was canceled {}'.format(pd.Timestamp.now()))
            break

How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the KuCoin API?

Great! But what about if we want to calculate the percentage move between two currencies and then launch an order? Well, our next example will take care of that!

The main task will be to execute an ETH trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain the prices of the two cryptos and calculate the percentage change between the two.

If the percentage change is less than 5%, the program will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.

After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Now that the logic is set, it is time to code it out:

while True:
    try:
        btc_old = m_client.get_ticker('BTC-USDT')
        print('The price of BTC at {} is:'.format(pd.Timestamp.now()), btc_old['price'])
    except Exception as e:
        print(f'Error obtaining BTC data: {e}')
    
    sleep(300)
    
    try:
        btc_new = m_client.get_ticker('BTC-USDT')
        print('The price of BTC at {} is:'.format(pd.Timestamp.now()), btc_new['price'])
    except Exception as e:
        print(f'Error obtaining BTC data: {e}')    
    
    percent = (((float(btc_new['bestAsk']) - float(btc_old['bestAsk'])) * 100) / float(btc_old['bestAsk']))
    
    if percent < 5:
        print('The trade requirement was not satisfied. The percentage move is at ',percent)
        continue
        
    elif percent >= 5:
        try:
            order = client.create_market_order('ETH-USDT', 'buy', size='5')
            print()
        except Exception as e:
            print(f'Error placing order: {e}')
            
        sleep(2)
        
        try:
            check = client.get_order_details(orderId=order['orderId'])
            print(check)
        except Excpetion as e:
            print(f'Error while checking order status: {e}')
            
        if check['isActive'] == true:
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break
            
        else:
            print('Order was canceled {}'.format(pd.Timestamp.now()))
            break

How to cancel orders with KuCoin API?

If you want to cancel an order on KuCoin you can easily use the following API request:

client.cancel_order(orderId)

Full code

GitHub Link

Igor Radovanovic

One Reply to “KuCoin API – An Introductory Guide”

Comments are closed.