Skip to content

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

KucoinPy

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.

Why raw sockets

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).

How it works

  • http.py builds the request line and headers by hand, signs each request with HMAC-SHA256 as KuCoin's v2 API keys require, and sends it with sendall on an ssl-wrapped socket.
  • Socket pool. KucoinPy(...) opens intial_sockets TLS 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.py does 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_handler receives every WebSocket message after the built-in handling, and after_ws runs after each successful reconnect, so calling code can add its own handling without changing the library. _shutdown_ws is True while the WebSocket is reconnecting, so callers can tell when the cached state may be stale.

Install

Not on PyPI. Install from source:

pip install git+https://github.com/PrivatePandaCO/KucoinPy

Dependencies: orjson, requests, and pyloggor for logging.

Usage

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/tradeOrdersV2

The constructor checks the account balance with the given keys and exits if that fails, so it needs real API credentials.

Constructor arguments

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

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.

Known issues

  • HTTP.recv does not honour Content-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.

Related

KucoinOBM uses this client to keep live local orderbooks.

License

GPL-2.0. See LICENSE.

About

KuCoin API client over raw TLS sockets: hand-written HTTP/1.1 and a minimal WebSocket. Not maintained.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages