๐Ÿ”Œ API ๐ŸŸก Intermediate

KuCoin API Documentation: Complete Guide for Crypto Traders

Master KuCoin API documentation with practical Python examples, authentication setup, WebSocket streams, and futures trading endpoints for automated crypto strategies.

Table of Contents
  1. Understanding the KuCoin API Architecture
  2. Authentication Setup and Your First API Call
  3. Working with the KuCoin Futures API
  4. Real-Time Data with KuCoin WebSocket API
  5. Error Handling and Production Best Practices
  6. KuCoin API Documentation PDF and Offline Access
  7. Frequently Asked Questions
  8. Getting Started with Confidence

KuCoin sits among the top 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 market data for analysis, or automating your portfolio management, the KuCoin API documentation gives you everything you need to interact with the platform programmatically. The catch? The official docs can feel scattered, and some critical details are buried deep. This guide cuts through the noise and gives you a working foundation with real code you can run today.

Understanding the KuCoin API Architecture

The KuCoin API reference is split into three main systems: the Spot/Margin API, the Futures API, and the WebSocket feed. Each has its own base URL, rate limits, and authentication quirks. Unlike Coinbase's unified API or Bitget's simpler structure, KuCoin keeps these fairly separate โ€” so you'll need to understand which endpoint family you're hitting before writing a single line of code.

KuCoin API Endpoint Overview
API TypeBase URLPrimary Use
Spot / Marginhttps://api.kucoin.comTrading, account data, market info
Futureshttps://api-futures.kucoin.comFutures contracts, positions, leverage
WebSocket (Public)wss://ws-api-spot.kucoin.comReal-time tickers, orderbook, trades
WebSocket (Private)wss://ws-api-spot.kucoin.comOrder updates, balance changes
Sandboxhttps://openapi-sandbox.kucoin.comTesting without real funds

The KuCoin API docs recommend starting with the sandbox environment. This is solid advice โ€” you don't want your first authenticated request to accidentally place a real order. The sandbox mirrors the production API with fake balances, so your code will work the same way when you switch to live trading.

KuCoin enforces different rate limits for public and private endpoints. Public endpoints allow 1800 requests per minute, while private (authenticated) endpoints are limited to 1800 per minute per API key. Exceeding these limits results in a 429 status code and a temporary IP ban. Always implement rate limiting in your code.

Authentication Setup and Your First API Call

KuCoin uses HMAC-SHA256 authentication with three credentials: an API key, an API secret, and a passphrase you set during key creation. This is slightly more involved than what you'd find on Bybit or OKX, which only require a key and secret. The passphrase adds an extra layer of security, but it also means one more thing to manage in your configuration.

Here's how to set up authentication and make your first authenticated request using Python. This covers the KuCoin API documentation Python workflow that most traders need โ€” checking account balances.

python
import time
import hmac
import hashlib
import base64
import requests

# Your KuCoin API credentials
API_KEY = "your_api_key_here"
API_SECRET = "your_api_secret_here"
API_PASSPHRASE = "your_passphrase_here"
BASE_URL = "https://api.kucoin.com"

def generate_signature(endpoint: str, method: str, body: str = "") -> dict:
    """Generate authentication headers for KuCoin API."""
    timestamp = str(int(time.time() * 1000))
    str_to_sign = timestamp + method.upper() + endpoint + body
    
    signature = base64.b64encode(
        hmac.new(
            API_SECRET.encode("utf-8"),
            str_to_sign.encode("utf-8"),
            hashlib.sha256
        ).digest()
    ).decode("utf-8")
    
    passphrase = base64.b64encode(
        hmac.new(
            API_SECRET.encode("utf-8"),
            API_PASSPHRASE.encode("utf-8"),
            hashlib.sha256
        ).digest()
    ).decode("utf-8")
    
    return {
        "KC-API-KEY": API_KEY,
        "KC-API-SIGN": signature,
        "KC-API-TIMESTAMP": timestamp,
        "KC-API-PASSPHRASE": passphrase,
        "KC-API-KEY-VERSION": "2",
        "Content-Type": "application/json"
    }

# Fetch account balances
endpoint = "/api/v1/accounts"
headers = generate_signature(endpoint, "GET")
response = requests.get(BASE_URL + endpoint, headers=headers)

if response.status_code == 200:
    data = response.json()
    for account in data["data"]:
        if float(account["balance"]) > 0:
            print(f"{account['currency']}: {account['balance']} ({account['type']})")
else:
    print(f"Error {response.status_code}: {response.json()}")

Note the KC-API-KEY-VERSION header set to "2" โ€” this is for the v2 API signing method where the passphrase is also HMAC-signed. The older v1 method sent the passphrase in plaintext. The KuCoin API reference strongly recommends v2, and you should use it exclusively. If you're coming from the Binance API where signing is simpler, the extra passphrase step catches a lot of people off guard.

Working with the KuCoin Futures API

The KuCoin futures API documentation lives separately from the spot API, and this trips up many developers. The futures endpoints use a different base URL, different contract symbols (like XBTUSDTM instead of BTC-USDT), and have their own authentication flow โ€” though the signing method is identical. If you're building a bot that trades both spot and futures, you'll essentially maintain two API clients.

Here's a practical example of fetching your futures positions and placing a limit order. This is the bread and butter of automated futures trading on KuCoin.

python
FUTURES_URL = "https://api-futures.kucoin.com"

def futures_request(endpoint: str, method: str = "GET", body: str = ""):
    """Make authenticated request to KuCoin Futures API."""
    headers = generate_signature(endpoint, method, body)
    
    if method == "GET":
        resp = requests.get(FUTURES_URL + endpoint, headers=headers)
    elif method == "POST":
        resp = requests.post(FUTURES_URL + endpoint, headers=headers, data=body)
    
    if resp.status_code != 200:
        raise Exception(f"API Error: {resp.status_code} - {resp.text}")
    return resp.json()

# Get current futures positions
positions = futures_request("/api/v1/positions")
for pos in positions["data"]:
    if pos["isOpen"]:
        pnl = float(pos["unrealisedPnl"])
        print(f"{pos['symbol']}: {pos['currentQty']} contracts, PnL: {pnl:.4f}")

# Place a futures limit order
import json

order_data = json.dumps({
    "clientOid": str(int(time.time() * 1000)),
    "symbol": "XBTUSDTM",
    "side": "buy",
    "type": "limit",
    "lever": "5",
    "size": 1,
    "price": "60000",
    "timeInForce": "GTC"
})

result = futures_request("/api/v1/orders", "POST", order_data)
print(f"Order placed: {result['data']['orderId']}")
The 'size' parameter in KuCoin futures represents the number of contracts, not the USDT value. Each XBTUSDTM contract is worth 0.001 BTC. This is different from Binance futures where you specify quantity in base asset. Always check the contract specifications in the KuCoin API docs before placing orders.

Real-Time Data with KuCoin WebSocket API

REST polling is fine for account checks, but for market data you need the KuCoin WebSocket API documentation. WebSocket connections give you real-time orderbook updates, trade streams, and ticker data with minimal latency. This is essential for any strategy that reacts to market movements โ€” from simple price alerts to high-frequency arbitrage between KuCoin and Gate.io.

KuCoin's WebSocket setup requires a token request first โ€” you can't just connect directly. Here's a complete working example that streams live trades for BTC-USDT.

python
import asyncio
import websockets
import json
import requests

async def stream_kucoin_trades():
    """Stream real-time BTC-USDT trades from KuCoin WebSocket."""
    
    # Step 1: Get WebSocket token (public endpoint, no auth needed)
    token_resp = requests.post("https://api.kucoin.com/api/v1/bullet-public")
    token_data = token_resp.json()["data"]
    
    ws_token = token_data["token"]
    ws_endpoint = token_data["instanceServers"][0]["endpoint"]
    ping_interval = token_data["instanceServers"][0]["pingInterval"] / 1000
    
    ws_url = f"{ws_endpoint}?token={ws_token}&connectId={int(time.time()*1000)}"
    
    async with websockets.connect(ws_url) as ws:
        # Wait for welcome message
        welcome = json.loads(await ws.recv())
        print(f"Connected: {welcome['type']}")
        
        # Subscribe to BTC-USDT trade feed
        subscribe_msg = {
            "id": str(int(time.time() * 1000)),
            "type": "subscribe",
            "topic": "/market/match:BTC-USDT",
            "privateChannel": False,
            "response": True
        }
        await ws.send(json.dumps(subscribe_msg))
        
        # Process incoming trades
        while True:
            try:
                msg = json.loads(await asyncio.wait_for(ws.recv(), timeout=ping_interval))
                
                if msg["type"] == "message":
                    trade = msg["data"]
                    side = "BUY " if trade["side"] == "buy" else "SELL"
                    print(f"{side} {trade['size']} BTC @ ${trade['price']}")
                    
            except asyncio.TimeoutError:
                # Send ping to keep connection alive
                await ws.send(json.dumps({"id": str(int(time.time())), "type": "ping"}))

# Run the stream
asyncio.run(stream_kucoin_trades())

The ping mechanism is critical. KuCoin will disconnect you after the ping interval (usually 60 seconds) if you don't send a keepalive. Many developers skip this and wonder why their WebSocket drops after a minute. The code above handles this with the asyncio.wait_for timeout pattern, which is cleaner than running a separate ping task.

For private WebSocket channels โ€” like real-time order fills and balance updates โ€” use the /api/v1/bullet-private endpoint with authentication headers instead of bullet-public. The subscription format is the same, just different topic paths like /spotMarket/tradeOrders.

Error Handling and Production Best Practices

Is KuCoin reliable for API trading? Generally yes โ€” their uptime is solid and the matching engine performs well. But like any exchange, things can go wrong. The KuCoin API returns specific error codes that you need to handle properly. A 200 status doesn't always mean success โ€” KuCoin wraps errors inside a 200 response with a code field that differs from "200000" on failure.

  • Always check the 'code' field in JSON responses โ€” "200000" means success, anything else is an error
  • Handle 429 (rate limit) with exponential backoff, starting at 1 second and doubling up to 60 seconds
  • Implement request timeout of 10-15 seconds โ€” hanging requests are worse than failed ones
  • Log every order placement and fill for reconciliation โ€” don't trust memory, trust logs
  • Use clientOid for order idempotency โ€” if a request times out, you can retry safely without double-ordering
  • Store API credentials in environment variables or a secrets manager, never hardcode them
  • Monitor the KuCoin status page and their Telegram channel for maintenance windows

Is KuCoin trustworthy for running automated strategies? They've been operating since 2017 and handled the 2022 crypto winter without freezing withdrawals, which is more than some competitors can say. Their API has been stable through major market events. That said, never keep more funds on any exchange than your strategy requires โ€” this applies to Binance and OKX just as much as KuCoin.

Platforms like VoiceOfChain can complement your API-based trading by providing real-time market signals. Instead of relying solely on your own indicators, you can pipe external sentiment data and trading signals into your bot's decision logic, adding another layer of confirmation before executing trades.

KuCoin API Documentation PDF and Offline Access

Many traders search for the KuCoin API documentation PDF for offline reference. KuCoin doesn't provide an official PDF download, but their docs site at docs.kucoin.com is well-structured and can be saved as a PDF from your browser. The more practical approach is to use the OpenAPI/Swagger spec they publish โ€” you can import it into Postman or Insomnia and have an interactive reference with pre-built request templates.

The KuCoin API docs also include SDKs for Python, Go, Java, PHP, and Node.js. The official Python SDK (kucoin-python-sdk) wraps all the authentication logic so you don't have to write the HMAC signing yourself. However, many experienced developers prefer raw requests for better control โ€” the SDK can lag behind API changes, and debugging through an abstraction layer is always harder.

For anyone building serious infrastructure, keep a local copy of the endpoint documentation and version it alongside your code. API changes happen, and having a snapshot of what the docs said when you wrote your integration saves hours of debugging when something breaks six months later.

Frequently Asked Questions

Where can I find the official KuCoin API documentation?

The official KuCoin API docs are hosted at docs.kucoin.com, split into Spot, Futures, and WebSocket sections. Each section has its own navigation and endpoint reference. There's no single PDF, but you can export pages from the docs site directly.

Is there a KuCoin API documentation PDF available for download?

KuCoin doesn't offer an official PDF. Your best option is using your browser's print-to-PDF function on docs.kucoin.com, or importing their OpenAPI spec into Postman for an interactive offline reference.

How do I get started with the KuCoin API in Python?

Create API keys in your KuCoin account settings, install the requests library, and implement HMAC-SHA256 signing with your key, secret, and passphrase. Alternatively, install the kucoin-python-sdk package for a higher-level wrapper that handles auth automatically.

Is KuCoin reliable for running automated trading bots?

KuCoin has proven reliable since 2017 with consistent API uptime through major market events. Their rate limits are generous at 1800 requests per minute, and the matching engine handles high-volume periods well. Always use the sandbox for testing before going live.

What's the difference between KuCoin Spot API and Futures API?

They use different base URLs, different symbol formats (BTC-USDT vs XBTUSDTM), and different order parameters. The Futures API includes leverage settings and contract-specific fields like size in contracts rather than coin quantity. Authentication signing is identical for both.

Does KuCoin WebSocket require authentication?

Public channels like trade streams and orderbook data only need a token from the /bullet-public endpoint โ€” no API keys required. Private channels for order updates and balance changes require authentication through /bullet-private with your API credentials.

Getting Started with Confidence

The KuCoin API documentation is comprehensive once you understand its structure. Start with the sandbox, nail your authentication, and build up from simple balance checks to order placement and WebSocket streams. The code examples in this guide are production-ready foundations โ€” extend them with proper logging, error handling, and your own trading logic. Whether you're automating a simple DCA strategy or building a cross-exchange arbitrage system spanning KuCoin, Binance, and Bybit, the API gives you the raw tools. The edge comes from what you build on top of it, and tools like VoiceOfChain for real-time signal integration can help you make smarter decisions at machine speed.