KuCoin API Docs: Complete Guide for Algorithmic Traders
Master the KuCoin API documentation with practical Python examples, authentication setup, and real endpoint walkthroughs for spot and futures trading.
Master the KuCoin API documentation with practical Python examples, authentication setup, and real endpoint walkthroughs for spot and futures trading.
KuCoin sits among the top global exchanges alongside Binance, OKX, and Bybit — and its API is one of the more developer-friendly options available. The KuCoin API docs cover everything from market data feeds to order management, making it a solid foundation for anyone building automated trading systems. Whether you're pulling price data into a spreadsheet or running a full-blown market-making bot, the KuCoin API documentation gives you the endpoints and WebSocket channels to get the job done.
What makes the KuCoin exchange API docs stand out is the separation between spot, futures, and margin trading interfaces. Each has its own base URL, its own set of endpoints, and its own rate limits. This modular approach means you can build a spot-only bot without worrying about futures complexity — or tap into the KuCoin futures API docs when you're ready to trade perpetual contracts with leverage.
Before diving into the API, make sure you have a KuCoin account with API key creation enabled. You'll need three credentials: an API key, an API secret, and a passphrase you set during key creation. Never share these or commit them to version control.
Every private endpoint in the KuCoin API reference requires HMAC-SHA256 signed requests. The signing process uses your API secret to hash a combination of the timestamp, HTTP method, request path, and body. Here's a complete Python authentication setup that you can reuse across all your KuCoin API calls:
import hmac
import hashlib
import base64
import time
import requests
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'
API_PASSPHRASE = 'your_passphrase'
BASE_URL = 'https://api.kucoin.com'
def get_headers(method: str, endpoint: str, body: str = '') -> dict:
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()
passphrase = base64.b64encode(
hmac.new(
API_SECRET.encode(), API_PASSPHRASE.encode(), hashlib.sha256
).digest()
).decode()
return {
'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'
}
# Fetch account balances
endpoint = '/api/v1/accounts'
headers = get_headers('GET', endpoint)
response = requests.get(BASE_URL + endpoint, headers=headers)
data = response.json()
if data['code'] == '200000':
for account in data['data']:
if float(account['balance']) > 0:
print(f"{account['currency']}: {account['balance']}")
else:
print(f"Error: {data['msg']}")
Notice the KC-API-KEY-VERSION header set to '2' — this is critical. Version 2 requires the passphrase to be HMAC-signed as well, not sent in plaintext. The KuCoin API documentation python examples sometimes show version 1, but version 2 is more secure and recommended for all new integrations. If you're coming from the Binance API, you'll notice KuCoin adds the passphrase as an extra security layer that Binance doesn't require.
The KuCoin spot API docs and the KuCoin futures API docs use different base URLs and slightly different endpoint structures. This is where many developers trip up — calling a spot endpoint on the futures base URL returns confusing errors.
| API Type | Base URL | Common Endpoints |
|---|---|---|
| Spot / Margin | https://api.kucoin.com | /api/v1/market/orderbook, /api/v1/orders |
| Futures | https://api-futures.kucoin.com | /api/v1/ticker, /api/v1/orders |
| WebSocket (Spot) | wss://ws-api-spot.kucoin.com | Market streams, order updates |
| WebSocket (Futures) | wss://ws-api-futures.kucoin.com | Position updates, mark price |
Here's how to pull the order book for BTC-USDT on spot and compare it with the futures contract — a technique useful for basis trading strategies. Platforms like Bybit and OKX offer similar dual-endpoint architectures, so once you learn this pattern on KuCoin, migrating your code is straightforward:
import requests
# Spot order book (public — no auth needed)
spot_url = 'https://api.kucoin.com/api/v1/market/orderbook/level2_20'
spot_resp = requests.get(spot_url, params={'symbol': 'BTC-USDT'}).json()
# Futures ticker (public)
futures_url = 'https://api-futures.kucoin.com/api/v1/ticker'
futures_resp = requests.get(futures_url, params={'symbol': 'XBTUSDTM'}).json()
if spot_resp['code'] == '200000' and futures_resp['code'] == '200000':
spot_best_ask = float(spot_resp['data']['asks'][0][0])
futures_price = float(futures_resp['data']['price'])
basis = futures_price - spot_best_ask
basis_pct = (basis / spot_best_ask) * 100
print(f"Spot ask: ${spot_best_ask:,.2f}")
print(f"Futures: ${futures_price:,.2f}")
print(f"Basis: ${basis:,.2f} ({basis_pct:.3f}%)")
else:
print('API error — check response codes')
Futures symbols on KuCoin use a different naming convention. BTC-USDT on spot becomes XBTUSDTM for USDT-margined perpetual futures. Always check the KuCoin futures API docs for the correct symbol format before making requests.
The KuCoin API reference defines rate limits per endpoint group. Public market data endpoints allow roughly 30 requests per second, while private endpoints like order placement are capped at around 9 requests per second. Exceeding these limits returns a 429 status code, and repeated violations can lead to temporary IP bans.
Robust error handling separates a production-grade bot from a hobby script. Here's a pattern that handles the most common failure modes — rate limits, network timeouts, and API-level errors:
import time
import requests
from requests.exceptions import Timeout, ConnectionError
def safe_request(method, url, max_retries=3, **kwargs):
"""KuCoin API request with retry logic and rate limit handling."""
kwargs.setdefault('timeout', 10)
for attempt in range(max_retries):
try:
resp = requests.request(method, url, **kwargs)
data = resp.json()
# KuCoin uses '200000' as success code
if data.get('code') == '200000':
return data['data']
# Rate limited
if data.get('code') == '429000':
wait = 2 ** attempt
print(f"Rate limited. Waiting {wait}s...")
time.sleep(wait)
continue
# Other API errors
print(f"API error {data.get('code')}: {data.get('msg')}")
return None
except Timeout:
print(f"Timeout on attempt {attempt + 1}")
time.sleep(1)
except ConnectionError:
print(f"Connection failed on attempt {attempt + 1}")
time.sleep(2)
print("Max retries reached")
return None
# Usage
orderbook = safe_request(
'GET',
'https://api.kucoin.com/api/v1/market/orderbook/level2_20',
params={'symbol': 'ETH-USDT'}
)
if orderbook:
print(f"Best bid: {orderbook['bids'][0][0]}")
Compare this to how you'd handle errors on Binance — the pattern is similar, but KuCoin wraps everything in a 'code' field inside the JSON body rather than using HTTP status codes alone. Gate.io follows a similar convention, so if you build a multi-exchange bot, you'll want an abstraction layer that normalizes these differences.
REST endpoints are fine for account management and order placement, but for real-time market data, you need WebSockets. The KuCoin API documentation covers both public and private WebSocket channels. Public channels stream order book updates, trades, and ticker data. Private channels push order fills, balance changes, and margin calls.
To connect, you first request a temporary WebSocket token from the REST API, then use it to establish the connection. This token-based approach is unique to KuCoin — on Bybit or OKX, you authenticate the WebSocket connection directly with your API key.
For traders who want actionable signals without building the entire infrastructure themselves, platforms like VoiceOfChain aggregate real-time data from multiple exchanges — including KuCoin — and deliver trading signals that would otherwise require significant API development work. It's a practical shortcut when you need cross-exchange intelligence but don't have time to build and maintain WebSocket connections to every platform.
That said, if you're building custom strategies, there's no substitute for direct API access. The KuCoin spot API docs list over 20 WebSocket topics for spot markets alone, from individual trade streams to full Level 3 order book feeds. The depth of data available rivals what you'd find on Coinbase's Advanced Trade API.
A question that comes up constantly: is KuCoin allowed in the US? The short answer is complicated. KuCoin is not registered with US regulators, and in 2023 the DOJ charged the exchange with operating an unlicensed money transmitting business. While many US-based traders have historically used KuCoin, doing so carries regulatory risk.
Is KuCoin available in New York? Specifically no — New York's BitLicense requirements make it one of the strictest states for crypto exchange access. KuCoin does not hold a BitLicense, and New York residents are explicitly restricted. If you're based in the US and need API access to a compliant exchange, Coinbase Advanced Trade or Kraken are your safest bets. Their APIs are well-documented and offer similar functionality for spot trading.
For international traders with no such restrictions, the KuCoin API remains one of the most feature-rich options available. The KuCoin API documentation PDF used to be available as a downloadable reference, but the exchange has since moved to a fully interactive online documentation portal that stays current with API changes — a better approach than static PDFs that go stale.
The KuCoin API docs provide a comprehensive toolkit for building everything from simple price trackers to sophisticated trading bots. The authentication flow takes some effort to set up correctly, but once you have the signing logic in place, the rest is straightforward endpoint calls. Start with public endpoints to validate your setup, move to authenticated calls for account data, and graduate to WebSockets when you need real-time performance.
Whether you're comparing order books across KuCoin and Binance for arbitrage, building a futures scalping bot, or just pulling historical data for backtesting — the API gives you the raw materials. The code examples in this guide should get you from zero to making authenticated requests in under an hour. From there, the KuCoin API reference is your roadmap to every endpoint the exchange offers.