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.
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.
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.
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.
Never hardcode API keys in your source files. Use environment variables or a .env file excluded from version control. A leaked KuCoin API key with withdrawal permissions can drain your account in seconds.
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.
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.
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)
Always test orders on KuCoin's sandbox environment first. Set sandbox=True in the client constructor and use sandbox API keys from sandbox.kucoin.com. Production mistakes with the futures API can be expensive.
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.
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 |
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.
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.
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.