KuCoin API: Complete Guide for Automated Crypto Trading
Learn how to set up and use the KuCoin API for automated trading, including authentication, Python examples, futures endpoints, and rate limit management.
Table of Contents
- Why the KuCoin API Matters for Serious Traders
- Setting Up Your KuCoin API Key
- Authentication and Your First API Call in Python
- Working with KuCoin API Futures and Funding Rates
- Understanding KuCoin API Rate Limits
- Building a Simple Trading Bot with Error Handling
- Frequently Asked Questions
- Wrapping Up
Why the KuCoin API Matters for Serious Traders
KuCoin sits among the top-tier exchanges alongside Binance, Bybit, and OKX โ and its API is one of the more developer-friendly options out there. Whether you're building a trading bot, pulling funding rate data, or automating your portfolio rebalancing, the KuCoin API gives you programmatic access to spot markets, futures, margin trading, and account management. If you've ever stared at charts for hours waiting for a setup to trigger, automation through the API is the logical next step.
The KuCoin API documentation is well-structured and covers REST and WebSocket endpoints for both spot and futures markets. Unlike some exchanges where the docs feel like an afterthought, KuCoin's API docs are genuinely usable โ complete with request examples, error codes, and rate limit details. That said, there are gotchas that the documentation glosses over, and that's exactly what this guide covers.
Setting Up Your KuCoin API Key
Before writing a single line of code, you need to generate your KuCoin API key. Head to your KuCoin account settings, navigate to API Management, and create a new key. You'll get three pieces of information: the API key, the API secret, and the KuCoin API passphrase. That passphrase is unique to KuCoin โ most exchanges like Binance or Coinbase only require a key and secret pair. The passphrase adds an extra layer of security, but it also means your authentication code will look slightly different from what you're used to.
When creating the key, you'll choose permissions: General (read-only account info), Trade (place and cancel orders), and Transfer (withdrawals). For most bot development, you want General + Trade. Only enable Transfer if your bot genuinely needs to move funds between accounts, and even then, restrict withdrawal addresses via KuCoin's whitelist feature.
# Store credentials as environment variables
export KUCOIN_API_KEY="your_api_key_here"
export KUCOIN_API_SECRET="your_api_secret_here"
export KUCOIN_API_PASSPHRASE="your_passphrase_here"
Authentication and Your First API Call in Python
The KuCoin API uses HMAC-SHA256 signatures for authentication. Every authenticated request requires a timestamp, a signature generated from your secret, and your passphrase (also signed in API v2). The kucoin-python library handles all of this for you, but understanding the raw process matters when things break at 3 AM and your bot is stuck.
Here's how to set up authentication and fetch your account balances using the official KuCoin API Python client:
import os
from kucoin.client import Client
# Load credentials from environment
api_key = os.environ['KUCOIN_API_KEY']
api_secret = os.environ['KUCOIN_API_SECRET']
api_passphrase = os.environ['KUCOIN_API_PASSPHRASE']
client = Client(api_key, api_secret, api_passphrase)
# Fetch account balances
accounts = client.get_accounts()
for account in accounts:
if float(account['balance']) > 0:
print(f"{account['currency']}: {account['balance']} ({account['type']})")
# Get BTC-USDT ticker
ticker = client.get_ticker('BTC-USDT')
print(f"BTC Price: {ticker['price']}")
print(f"24h Volume: {ticker['vol']}")
If you prefer working with raw HTTP requests โ which gives you more control and fewer dependency headaches โ here's how to sign requests manually:
import hashlib
import hmac
import base64
import time
import requests
import os
API_KEY = os.environ['KUCOIN_API_KEY']
API_SECRET = os.environ['KUCOIN_API_SECRET']
API_PASSPHRASE = os.environ['KUCOIN_API_PASSPHRASE']
BASE_URL = 'https://api.kucoin.com'
def kucoin_request(method, endpoint, body=''):
now = str(int(time.time() * 1000))
str_to_sign = now + method.upper() + endpoint + body
signature = base64.b64encode(
hmac.new(API_SECRET.encode(), str_to_sign.encode(), hashlib.sha256).digest()
).decode()
# API v2: passphrase is also signed
passphrase = base64.b64encode(
hmac.new(API_SECRET.encode(), API_PASSPHRASE.encode(), hashlib.sha256).digest()
).decode()
headers = {
'KC-API-KEY': API_KEY,
'KC-API-SIGN': signature,
'KC-API-TIMESTAMP': now,
'KC-API-PASSPHRASE': passphrase,
'KC-API-KEY-VERSION': '2',
'Content-Type': 'application/json'
}
resp = requests.request(method, BASE_URL + endpoint, headers=headers)
data = resp.json()
if data.get('code') != '200000':
raise Exception(f"API Error {data['code']}: {data.get('msg')}")
return data['data']
# Example: get order book for ETH-USDT
orderbook = kucoin_request('GET', '/api/v1/market/orderbook/level2_20?symbol=ETH-USDT')
print(f"Best bid: {orderbook['bids'][0]}")
print(f"Best ask: {orderbook['asks'][0]}")
Working with KuCoin API Futures and Funding Rates
KuCoin's futures API lives on a separate base URL (api-futures.kucoin.com) with its own set of endpoints. This catches many developers off guard โ your spot API key works for futures too, but you need to point your requests at the right host. The KuCoin API docs cover futures endpoints in a separate section, so make sure you're reading the right page.
One of the most useful futures endpoints is the KuCoin API funding rate data. Funding rates are critical for perpetual futures traders โ they tell you whether longs or shorts are paying the premium. When funding rates spike, it often signals overcrowded positioning. Tools like VoiceOfChain track these signals across multiple exchanges in real time, but having direct API access lets you build custom alerts and strategies around funding rate extremes.
import requests
FUTURES_URL = 'https://api-futures.kucoin.com'
# Get current funding rate for BTC perpetual (public endpoint, no auth needed)
resp = requests.get(f'{FUTURES_URL}/api/v1/funding-rate/XBTUSDTM/current')
data = resp.json()['data']
print(f"Symbol: {data['symbol']}")
print(f"Current funding rate: {float(data['value']) * 100:.4f}%")
print(f"Predicted rate: {float(data['predictedValue']) * 100:.4f}%")
# Get active futures contracts list
resp = requests.get(f'{FUTURES_URL}/api/v1/contracts/active')
contracts = resp.json()['data']
for contract in contracts[:5]:
print(f"{contract['symbol']}: tick={contract['tickSize']}, "
f"multiplier={contract['multiplier']}")
Compare this to how Bybit and OKX handle funding rates โ the data structure is similar, but KuCoin uses 'value' and 'predictedValue' fields while others use different naming conventions. If you're building a cross-exchange funding rate monitor, normalize these field names early or you'll end up with a debugging nightmare.
Understanding KuCoin API Rate Limits
The KuCoin API rate limit system is weight-based, and it's more generous than you might expect โ but it can still trip you up during high-frequency operations. The KuCoin API limits are applied per API key and vary by endpoint type. Most public endpoints allow around 100 requests per 10 seconds, while private (authenticated) endpoints vary between 30-100 requests per 10 seconds depending on the specific call.
| Endpoint Type | Rate Limit | Window |
|---|---|---|
| Public market data | 100 requests | 10 seconds |
| Private (spot orders) | 45 requests | 3 seconds |
| Private (account info) | 30 requests | 3 seconds |
| Futures orders | 30 requests | 3 seconds |
| WebSocket connections | 30 per minute | Per IP |
When you hit the rate limit, KuCoin returns a 429 status code with error code 429000. Your bot needs to handle this gracefully. Here's a pattern that works well โ exponential backoff with jitter prevents the thundering herd problem when multiple bot instances hit limits simultaneously:
- Always check the response code before processing data โ don't assume success
- Implement a request queue that respects the rate window rather than retrying blindly
- Use WebSocket streams for real-time data instead of polling REST endpoints
- Cache frequently accessed data like symbol info that rarely changes
- On Binance the limits work differently (IP-based weights), so don't copy patterns directly
For strategies that need real-time order book or trade data, the WebSocket API is the correct approach. KuCoin's WebSocket supports both public channels (tickers, order books, trades) and private channels (order updates, balance changes). You'll need to request a WebSocket token from the REST API first, then connect using the returned endpoint and token.
Building a Simple Trading Bot with Error Handling
Let's put it all together. Below is a practical example that monitors a price level and places a limit buy order when triggered. This is the kind of automation that separates traders who sleep well from those who set phone alarms at 4 AM. Platforms like Gate.io and Bitget also offer similar API capabilities, but KuCoin's sandbox environment makes it particularly good for testing before risking real capital.
import os
import time
import logging
from kucoin.client import Client
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('kucoin_bot')
client = Client(
os.environ['KUCOIN_API_KEY'],
os.environ['KUCOIN_API_SECRET'],
os.environ['KUCOIN_API_PASSPHRASE']
)
SYMBOL = 'BTC-USDT'
BUY_PRICE = '62000' # trigger price
BUY_SIZE = '0.001' # BTC amount
def check_and_trade():
try:
ticker = client.get_ticker(SYMBOL)
current_price = float(ticker['price'])
log.info(f'{SYMBOL} price: {current_price}')
if current_price <= float(BUY_PRICE):
order = client.create_limit_order(
symbol=SYMBOL,
side='buy',
price=BUY_PRICE,
size=BUY_SIZE
)
log.info(f'Order placed! ID: {order["orderId"]}')
return True
except Exception as e:
error_msg = str(e)
if '429000' in error_msg:
log.warning('Rate limited โ backing off 10s')
time.sleep(10)
elif '400100' in error_msg:
log.error('Insufficient balance')
return True # stop the loop
else:
log.error(f'Unexpected error: {e}')
return False
log.info(f'Monitoring {SYMBOL}, buy trigger at ${BUY_PRICE}')
while True:
if check_and_trade():
break
time.sleep(5) # check every 5 seconds
Frequently Asked Questions
How do I get my KuCoin API passphrase if I forgot it?
The KuCoin API passphrase is set by you when creating the API key โ KuCoin does not store or display it after creation. If you've lost it, you need to delete the existing API key and create a new one with a new passphrase. Store it in a password manager immediately.
Can I use the same KuCoin API key for spot and futures trading?
Yes, the same API key works for both spot and futures endpoints. However, the base URLs are different: api.kucoin.com for spot and api-futures.kucoin.com for futures. Make sure your key has Trade permissions enabled for the markets you intend to use.
What are the KuCoin API rate limits for placing orders?
KuCoin allows approximately 45 order-related requests per 3-second window for spot and 30 per 3 seconds for futures. Exceeding these limits returns a 429 error. Use WebSocket private channels for order status updates instead of polling the REST API.
Is the KuCoin Python library officially maintained?
The kucoin-python package on PyPI is a community-maintained SDK. While it works well for most use cases, it can lag behind API updates. For production bots, consider using raw HTTP requests with the signing logic shown above โ it gives you full control and zero dependency on third-party maintenance.
How does KuCoin API compare to Binance API for bot development?
Both are capable, but they differ in structure. KuCoin uses a passphrase in addition to key and secret, has separate futures endpoints, and uses different rate limit schemes. Binance uses IP-based weight limits and a single base URL. KuCoin's sandbox environment is better for testing, while Binance has a larger ecosystem of community libraries.
Can I access KuCoin funding rate data without authentication?
Yes, the funding rate endpoint is public and requires no API key. You can fetch current and predicted funding rates for any perpetual contract with a simple GET request to the futures API. This makes it easy to build funding rate dashboards or integrate the data into signal platforms like VoiceOfChain.
Wrapping Up
The KuCoin API is a solid choice for automated trading โ the documentation is clear, the sandbox environment lets you test safely, and the endpoint coverage spans spot, futures, margin, and lending. The main things to remember: always sign your passphrase with API v2, use separate base URLs for spot and futures, and respect the rate limits by leveraging WebSocket streams for real-time data instead of hammering REST endpoints.
Start with the sandbox, get your authentication working, and build from there. The code examples in this guide are production-ready patterns โ adapt them to your strategy, add proper logging, and never deploy a bot without a kill switch. If you're monitoring funding rates or sentiment signals across KuCoin and other exchanges, tools like VoiceOfChain can complement your API setup by surfacing actionable data you might otherwise miss.