KuCoin API Python: Complete Guide to Automated Trading
Learn how to connect to KuCoin's REST and WebSocket APIs using Python. Includes authentication, spot and futures trading examples, and error handling for production bots.
Table of Contents
KuCoin sits among the top exchanges alongside Binance and OKX when it comes to API-friendly infrastructure. The kucoin api python ecosystem is mature enough that you can go from zero to a working trading bot in an afternoon โ if you know where the sharp edges are. This guide covers everything from initial authentication to placing futures orders, with production-ready code you can actually copy into your projects.
Setting Up Your KuCoin API Keys
Before writing a single line of code, you need API credentials. Log into KuCoin, navigate to API Management, and create a new key. You'll get three values: an API key, a secret, and a passphrase. Unlike Binance where you only deal with a key and secret, KuCoin adds the passphrase as an extra authentication layer. Set permissions carefully โ if you're only reading market data, don't enable trading permissions. If you're building a bot, enable trading but disable withdrawals. This is basic security hygiene that applies whether you trade on KuCoin, Bybit, or Gate.io.
pip install python-kucoin python-dotenv
import os
from dotenv import load_dotenv
from kucoin.client import Client
load_dotenv()
client = Client(
api_key=os.getenv('KUCOIN_API_KEY'),
api_secret=os.getenv('KUCOIN_API_SECRET'),
passphrase=os.getenv('KUCOIN_PASSPHRASE'),
sandbox=False # Set True for testing
)
# Verify connection
accounts = client.get_accounts()
for acc in accounts:
if float(acc['balance']) > 0:
print(f"{acc['currency']}: {acc['balance']} ({acc['type']})")
This is the simplest kucoin api python example โ authenticate and list your balances. The python-kucoin library wraps the REST endpoints documented in the kucoin api documentation python section of their developer portal. If you prefer raw HTTP requests, you can use the requests library directly, but the SDK handles signature generation which is the most error-prone part.
Fetching Market Data and Order Books
Market data is the foundation of any trading strategy. Whether you're building a simple price alert or a complex arbitrage system that compares KuCoin prices against Bitget and Coinbase, you start by pulling ticker data and order books.
# Get ticker for BTC-USDT
ticker = client.get_ticker('BTC-USDT')
print(f"Price: {ticker['price']}")
print(f"Best Ask: {ticker['bestAsk']}")
print(f"Best Bid: {ticker['bestBid']}")
# Get full order book (aggregated)
order_book = client.get_order_book('BTC-USDT')
bids = order_book['bids'][:5] # Top 5 bids
asks = order_book['asks'][:5] # Top 5 asks
print("\n--- Order Book (Top 5) ---")
print("BIDS (buyers):")
for price, size in bids:
print(f" {price} | {size} BTC")
print("ASKS (sellers):")
for price, size in asks:
print(f" {price} | {size} BTC")
# Get 1-hour klines for analysis
from datetime import datetime, timedelta
import time
end = int(time.time())
start = int((datetime.now() - timedelta(days=7)).timestamp())
klines = client.get_kline_data(
'BTC-USDT',
kline_type='1hour',
start=start,
end=end
)
print(f"\nFetched {len(klines)} hourly candles")
The kucoin rate limits are reasonable for most use cases โ 30 requests per second for public endpoints and around 10-20 for private ones depending on the endpoint category. Compare that to Binance which uses a weight-based system, or OKX which has per-endpoint limits. For high-frequency strategies, you'll want to use WebSocket streams instead of polling REST endpoints.
Placing Spot and Futures Orders via Python
Reading data is the easy part. Executing trades is where the real work begins. KuCoin supports market, limit, and stop orders on both spot and futures markets. The kucoin futures api python interface uses a separate client because futures and spot are different trading engines โ similar to how Bybit separates its unified and inverse contracts.
import uuid
from kucoin.client import Client
from kucoin_futures.client import FuturesClient
# --- SPOT ORDER ---
def place_spot_order(client, symbol, side, size, price=None):
"""Place a spot order with error handling."""
try:
params = {
'symbol': symbol,
'side': side,
'type': 'market' if price is None else 'limit',
'size': str(size),
'clientOid': str(uuid.uuid4())
}
if price:
params['price'] = str(price)
order = client.create_order(**params)
print(f"Spot order placed: {order['orderId']}")
return order
except Exception as e:
print(f"Spot order failed: {e}")
return None
# Buy 0.001 BTC at market price
place_spot_order(client, 'BTC-USDT', 'buy', 0.001)
# --- FUTURES ORDER ---
futures_client = FuturesClient(
key=os.getenv('KUCOIN_API_KEY'),
secret=os.getenv('KUCOIN_API_SECRET'),
passphrase=os.getenv('KUCOIN_PASSPHRASE')
)
def place_futures_order(fc, symbol, side, leverage, size):
"""Place a futures order with leverage."""
try:
order = fc.create_limit_order(
symbol=symbol,
side=side,
lever=str(leverage),
size=size,
price='', # empty for market
type='market',
clientOid=str(uuid.uuid4())
)
print(f"Futures order placed: {order['orderId']}")
return order
except Exception as e:
print(f"Futures order failed: {e}")
return None
# Long 1 BTC-USDT perpetual contract at 5x leverage
place_futures_order(futures_client, 'XBTUSDTM', 'buy', 5, 1)
WebSocket Streams for Real-Time Data
REST polling burns through rate limits and introduces latency. For any serious trading bot, WebSocket connections are non-negotiable. KuCoin's WebSocket API pushes real-time trades, order book updates, and account notifications. If you're using tools like VoiceOfChain for real-time trading signals, combining those alerts with a WebSocket-connected bot lets you react to market shifts in milliseconds rather than seconds.
import asyncio
from kucoin.ws_client import KucoinWsClient
async def handle_ticker(msg):
"""Process real-time ticker updates."""
data = msg.get('data', {})
price = data.get('price', 'N/A')
symbol = msg.get('topic', '').split(':')[-1]
print(f"{symbol}: ${price}")
async def handle_order_update(msg):
"""Process private order fill notifications."""
data = msg.get('data', {})
status = data.get('status')
if status == 'done':
print(f"Order filled: {data.get('symbol')} "
f"{data.get('side')} {data.get('size')} "
f"@ {data.get('price')}")
async def main():
# Public stream โ no auth needed
ws_public = await KucoinWsClient.create(
None, client, handle_ticker, private=False
)
await ws_public.subscribe('/market/ticker:BTC-USDT,ETH-USDT')
# Private stream โ requires auth
ws_private = await KucoinWsClient.create(
None, client, handle_order_update, private=True
)
await ws_private.subscribe('/spotMarket/tradeOrders')
while True:
await asyncio.sleep(60)
asyncio.run(main())
The WebSocket layer is where the kucoin api documentation python resources become essential reading. Connection management, ping/pong keepalives, and reconnection logic all need careful handling in production. The library handles some of this, but you should still implement your own watchdog that restarts connections if data stops flowing.
Error Handling and Rate Limit Management
A bot that works in testing but crashes in production is worse than no bot at all. KuCoin returns specific error codes that you need to handle โ insufficient balance (400100), order size too small (400760), and rate limits (429000) are the most common ones. Every exchange has its own error taxonomy; Binance uses numeric codes like -1013 for filters, OKX uses string codes, and KuCoin uses six-digit integers.
import time
from functools import wraps
def retry_on_rate_limit(max_retries=3, base_delay=1.0):
"""Decorator that retries on rate limit errors with backoff."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
error_msg = str(e)
# KuCoin rate limit error
if '429' in error_msg or 'Too Many' in error_msg:
delay = base_delay * (2 ** attempt)
print(f"Rate limited. Retry in {delay}s...")
time.sleep(delay)
# Insufficient balance โ no retry
elif '400100' in error_msg:
print(f"Insufficient balance: {e}")
return None
else:
raise
print(f"Max retries ({max_retries}) exceeded.")
return None
return wrapper
return decorator
@retry_on_rate_limit(max_retries=5)
def safe_get_ticker(client, symbol):
return client.get_ticker(symbol)
ticker = safe_get_ticker(client, 'BTC-USDT')
if ticker:
print(f"BTC price: {ticker['price']}")
| Error Code | Meaning | Action |
|---|---|---|
| 200000 | Success | Process response normally |
| 400100 | Insufficient balance | Check funds before retrying |
| 400200 | Order already exists | Use unique clientOid per order |
| 400760 | Order size below minimum | Check symbol's minSize parameter |
| 429000 | Rate limit exceeded | Backoff and retry after delay |
| 500000 | Internal server error | Retry with exponential backoff |
Security Best Practices for KuCoin API Bots
Is KuCoin safe for API trading? The exchange itself has had one major security incident in 2020 but recovered funds and has since upgraded its infrastructure. From your side, the bigger risk is your own code. A misconfigured bot can drain an account faster than any hacker. Here are the non-negotiable security practices for any API trading setup.
- IP whitelist your API keys โ KuCoin allows you to restrict keys to specific IPs, and you should always do this for production bots
- Never enable withdrawal permissions unless your bot absolutely requires them (almost none do)
- Store credentials in environment variables or a secrets manager, never in code repositories
- Set hard position limits in your bot code independent of exchange-side limits
- Use KuCoin's sandbox environment (sandbox.kucoin.com) for all testing before going live
- Monitor your bot's P&L with alerts โ platforms like VoiceOfChain can complement this by providing market context for unusual moves
- Implement a kill switch that cancels all open orders and closes positions if losses exceed a threshold
The kucoin rate for API access is free โ there are no fees for API usage itself, only standard trading fees. KuCoin's maker/taker fee structure starts at 0.1%/0.1% and drops with volume or KCS holdings. Compared to Coinbase Pro's 0.4%/0.6% for small traders, KuCoin is substantially cheaper for API-based strategies where you're doing high volume.
Frequently Asked Questions
Is the KuCoin Python API free to use?
Yes, KuCoin does not charge for API access. You only pay standard trading fees when executing orders. The python-kucoin library is open source and free as well.
Can I trade KuCoin futures with Python?
Absolutely. Install the kucoin-futures-python package and use the FuturesClient class. Futures use different endpoints and a separate client from spot trading, so you'll need to initialize both if your strategy trades across markets.
What are KuCoin's API rate limits?
Public endpoints allow roughly 30 requests per second, while private endpoints are limited to 10-20 requests per second depending on the category. WebSocket connections have a limit of 100 subscriptions per connection. Always implement exponential backoff for rate limit errors.
Is KuCoin safe for running trading bots?
KuCoin has a solid track record since recovering from a 2020 hack and has invested heavily in security infrastructure. The bigger risk is typically on your side โ secure your API keys, whitelist IPs, and never enable withdrawal permissions on bot keys.
How does KuCoin's API compare to Binance or Bybit?
KuCoin's API is well-documented and the Python SDK is mature. Binance has the largest ecosystem of third-party tools, while Bybit offers very fast WebSocket feeds. KuCoin's unique advantage is its wide selection of altcoin pairs that aren't available on larger exchanges.
Can I use the same API key for spot and futures?
Yes, the same API credentials work for both spot and futures endpoints. However, you need separate client instances in Python โ the standard Client for spot and FuturesClient for futures trading.
Wrapping Up
The kucoin api python ecosystem gives you everything you need to build production trading systems โ from simple price monitors to complex multi-market bots. Start with the spot client for market data, graduate to order placement on the sandbox, and only go live when your error handling is bulletproof. Combine programmatic execution with real-time market intelligence from platforms like VoiceOfChain, and you have the foundation for a trading operation that runs while you sleep. The code examples above are starting points โ the real edge comes from the strategy logic you build on top of them.