A Python client for the KuCoin spot API that talks to the exchange over raw TLS sockets instead of an HTTP library. It writes the HTTP/1.1 requests and a minimal WebSocket client by hand, keeps a pool of pre-connected sockets so the TLS handshake is already done when an order goes out, and keeps balances and order state current from the private WebSocket feed.
Status: not maintained. Written in 2023 against KuCoin's API as it was then (including the
/api/v1/hf/orders high-frequency endpoints). It is kept as a reference implementation; endpoints and
behaviour on KuCoin's side may have changed since.
The point of the library is the order path. A general HTTP client spends time on connection management,
header handling and response parsing that an order request doesn't need, and a cold connection pays a
TLS handshake. KucoinPy builds the request bytes itself, signs them, and writes them to a socket that was
connected earlier. The benchmarks/ directory has the scripts used to compare it with the two common
Python clients (see below).
http.pybuilds the request line and headers by hand, signs each request with HMAC-SHA256 as KuCoin's v2 API keys require, and sends it withsendallon anssl-wrapped socket.- Socket pool.
KucoinPy(...)opensintial_socketsTLS connections (default 10) at startup. A background thread keeps the pool topped up to 20. Each request takes a socket and discards it afterwards; reusing connections caused buffer and closed-socket errors in testing. When the pool is empty, a request waits for the next socket rather than raising. ws.pydoes the WebSocket upgrade handshake and message framing directly on a socket. A listener thread reassembles messages that arrive split across reads.- Reconnects. A ping thread checks the WebSocket at the interval KuCoin asks for. If KuCoin stops answering, the client reconnects and re-subscribes to every channel it was on.
- Hooks.
second_message_handlerreceives every WebSocket message after the built-in handling, andafter_wsruns after each successful reconnect, so calling code can add its own handling without changing the library._shutdown_wsisTruewhile the WebSocket is reconnecting, so callers can tell when the cached state may be stale.
Not on PyPI. Install from source:
pip install git+https://github.com/PrivatePandaCO/KucoinPyDependencies: orjson, requests, and pyloggor for
logging.
from KucoinPy import KucoinPy, Order
kc = KucoinPy(api_key, api_secret, api_passphrase, defaults=None)
kc.order(Order(clientOid="my-id-1", side="buy", symbol="BTC-USDT", type="limit", price="30000", size="0.001"))
print(kc.balance) # kept current from /account/balance
print(kc.orders["my-id-1"]) # updates from /spotMarket/tradeOrdersV2The constructor checks the account balance with the given keys and exits if that fails, so it needs real API credentials.
| Argument | Default | Meaning |
|---|---|---|
kc_api_key, kc_api_secret, kc_api_passphrase |
KuCoin API credentials. | |
defaults |
[] |
Channels to subscribe to at startup, as [(topic, private), ...], e.g. [("/account/balance", True)]. [] subscribes to nothing; None subscribes to /account/balance and /spotMarket/tradeOrdersV2. |
second_message_handler |
None |
Function called with each WebSocket message (parsed JSON) after the built-in handler. |
after_ws |
None |
Function called with no arguments after the WebSocket reconnects. |
logger |
pyloggor(project_root="KucoinPy") |
A pyloggor logger. project_root walks the stack to label each line with its file, which costs about 0.1 ms per call. |
intial_sockets |
10 |
TLS connections to open at startup. Fewer starts faster. |
benchmarks/ holds the latency harness: order latency (server createdAt minus local send time) and
WebSocket latency (local receive time minus the message timestamp on /market/level2:BTC-USDT) for
KucoinPy, python-kucoin and the official
kucoin-python-sdk. See benchmarks/README.md. The results
were not recorded in this repository.
HTTP.recvdoes not honourContent-Length, so large chunked responses are not always split correctly.- Some errors are returned instead of raised.
- Starting the client sets up the REST socket pool even when only the WebSocket is needed.
KucoinOBM uses this client to keep live local orderbooks.
GPL-2.0. See LICENSE.