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.
Table of Contents
- Why the KuCoin API Matters for Serious Traders
- Authentication Setup and Your First API Call
- Working with Spot and Futures Endpoints
- Rate Limits, Error Handling, and Best Practices
- Building a Real-Time Data Pipeline with WebSockets
- US Access: Legal Considerations and Alternatives
- Frequently Asked Questions
- Wrapping Up
Why the KuCoin API Matters for Serious Traders
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.
Authentication Setup and Your First API Call
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.
Working with Spot and Futures Endpoints
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')
Rate Limits, Error Handling, and Best Practices
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.
- Always check the 'code' field in KuCoin responses โ HTTP 200 doesn't mean success
- Use exponential backoff for rate limit errors, not fixed delays
- Set explicit timeouts on every request โ hanging connections kill bots silently
- Log every failed request with full context for post-mortem debugging
- Monitor your API key usage in the KuCoin dashboard to catch anomalies early
Building a Real-Time Data Pipeline with WebSockets
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.
US Access: Legal Considerations and Alternatives
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.
Frequently Asked Questions
Where can I find the official KuCoin API documentation?
The official KuCoin API docs are available at docs.kucoin.com. The documentation is split into sections for spot, futures, and margin trading, each with its own set of endpoints, examples, and rate limit specifications.
Is there a KuCoin API documentation PDF available for download?
KuCoin no longer provides a standalone PDF version of their API documentation. The online docs at docs.kucoin.com are the authoritative source and are updated in real time as the API evolves. You can use browser print-to-PDF if you need an offline copy.
What Python library should I use for the KuCoin API?
The official kucoin-python-sdk is available on PyPI. For simpler projects, many traders use raw requests with custom signing as shown in this guide โ it gives you full control. The ccxt library also supports KuCoin and lets you write code that works across Binance, OKX, and other exchanges with minimal changes.
Is KuCoin allowed in the US for API trading?
KuCoin is not registered with US financial regulators, and the DOJ has taken legal action against the exchange. While API access is technically possible from the US, using it carries legal and regulatory risk. US-based traders should consider Coinbase or Kraken for compliant API access.
What are KuCoin API rate limits for trading bots?
KuCoin enforces rate limits per endpoint group. Spot order placement is limited to approximately 9 requests per second, while public market data allows around 30 requests per second. Exceeding these limits triggers a 429000 error code. Use exponential backoff and request batching to stay within limits.
How do KuCoin futures API endpoints differ from spot?
KuCoin futures use a separate base URL (api-futures.kucoin.com) and different symbol conventions โ for example, XBTUSDTM instead of BTC-USDT. The authentication method is the same, but futures endpoints include additional fields for leverage, margin mode, and position management.
Wrapping Up
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.