kucoin

package module
v1.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 4 Imported by: 0

README

KuCoin Go SDK

KuCoin Golang API SDK

Go Version License

An idiomatic Go client for KuCoin's UTA (Unified Trading Account) and Classic (Spot/Margin/Futures) REST and WebSocket APIs, written from scratch against KuCoin's current docs-new documentation — not a wrapper around the official Universal SDK.

Package: a matching PHP/Laravel SDK is available at tigusigalpa/kucoin-php.


Why this exists

KuCoin's official Universal SDK is generated code that tries to cover every language and every account model at once, and it shows: inconsistent naming, loosely typed fields, and error handling that varies by endpoint. This project takes the opposite approach — hand-written, one endpoint at a time, with a single consistent shape for requests, responses, and errors across the whole SDK. The trade-off is honest: coverage grows slower, but what's there is tested, typed, and documented against KuCoin's real docs rather than against generator templates.

If you need full API coverage today, use the official SDK. If you want a smaller, carefully built Go client and can wait for coverage to grow (or want to contribute an endpoint yourself), this is for you.


Status

This is an early, honest checkpoint, not a finished library. Only UTA public market data is implemented and tested so far. Everything else described in this project's roadmap — UTA Account/Orders/Positions/Leverage/Transfers, Classic Spot/Margin/Futures trading, and every WebSocket channel — is not yet implemented. See docs/ENDPOINTS.md for the exact, generated list of what's covered, with a direct KuCoin documentation link per method.

Phase Scope Status
1 — reliable core Shared HTTP/auth/error/retry infra; UTA market/account/orders; Classic Spot market/orders; Classic Futures market/order/position; UTA + Classic WS core channels Partial — shared infra + UTA Market done; the rest is not started
2 — trading breadth Classic Margin; advanced Spot/Margin orders; UTA positions/leverage; more WS channels Not started
3 — specialty domains Account/funding/subaccounts/deposits/withdrawals, Earn, VIP Lending, Convert, Broker, Affiliate, Copy Trading Not started

We'd rather ship a small, correct surface than a large, half-tested one. If your use case needs something from Phase 2 or 3, please open an issue — real demand is what decides what gets built next.


What's inside (so far)

  • context.Context as the first parameter of every network call
  • An injectable *http.Client, Clock, and Logger
  • Strings for every price/quantity/PnL/fee field — no float rounding errors
  • Independent HMAC-SHA256 signer (KC-API-SIGN and the HMAC-signed KC-API-PASSPHRASE), verified against known-answer fixture vectors
  • A shared transport.Executor: response envelope decoding, ResponseMeta (HTTP status, KuCoin business code/message, request ID, gw-ratelimit-*, x-in-time/x-out-time), and a typed error hierarchy (errors.Is/errors.As)
  • A conservative retry policy — GET requests only, exponential backoff with jitter, bounded max-elapsed time; POST/DELETE (place/cancel/amend orders, transfers, withdrawals) are never auto-retried
  • A manifest-driven docs/ENDPOINTS.md, regenerated by go run ./internal/gendocs from internal/endpoints.yaml; CI fails if they drift apart

Install

go get github.com/tigusigalpa/kucoin-go

Requires Go 1.22 or newer.


Quick start

Public market data works with zero credentials — a good way to try the SDK before deciding whether to trust it with real keys:

package main

import (
	"context"
	"fmt"
	"log"

	kucoin "github.com/tigusigalpa/kucoin-go"
	"github.com/tigusigalpa/kucoin-go/uta/market"
)

func main() {
	client := kucoin.NewClient()

	tickers, err := client.UTA.Market.GetTickers(context.Background(), market.TradeTypeSpot, "BTC-USDT")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(tickers.List[0].LastPrice)
}

Runnable example: examples/uta_market.


Credentials and security

Read KC-API-KEY/KC-API-SECRET/KC-API-PASSPHRASE from environment variables or your own secret store — never hardcode them:

client := kucoin.NewClient(kucoin.WithCredentials(kucoin.Credentials{
	APIKey:        os.Getenv("KUCOIN_API_KEY"),
	APISecret:     os.Getenv("KUCOIN_API_SECRET"),
	APIPassphrase: os.Getenv("KUCOIN_API_PASSPHRASE"),
	APIKeyVersion: os.Getenv("KUCOIN_API_KEY_VERSION"), // per-key metadata, not a constant
}))
  • Create keys with the minimum permission needed (read-only for market/account calls).
  • Restrict the key to specific IPs where KuCoin allows it.
  • This library never logs KC-API-KEY, KC-API-SIGN, KC-API-PASSPHRASE, or full private request bodies.
  • It never places live trading, transfer, or withdrawal calls in its own tests, examples, or CI.

See SECURITY.md to report a vulnerability.


UTA versus Classic

KuCoin exposes two distinct account models with different permissions, hosts, and data shapes. This SDK keeps them as explicit, separate service roots — client.UTA today, client.Classic once implemented — rather than merging them into one type, since doing so would misrepresent which fields/permissions actually apply. Do not assume a UTA and a Classic response for "the same" concept (e.g. a kline) share a struct — see the field-order note on market.Kline.

If you're not sure which model your account uses: UTA is KuCoin's newer, unified margin/futures/spot account; Classic is the older, separately-funded Spot/Margin/Futures setup. Check your KuCoin account settings if you're unsure — the two are not interchangeable at the API level.


REST examples

Market data (public, no credentials):

book, err := client.UTA.Market.GetOrderBook(ctx, market.TradeTypeSpot, "BTC-USDT", market.GetOrderBookOptions{Limit: 20})

Error and rate-limit inspection:

_, err := client.UTA.Market.GetTickers(ctx, market.TradeTypeSpot, "BTC-USDT")
if errors.Is(err, transport.ErrRateLimited) {
	// back off
}
var kucoinErr *transport.KucoinError
if errors.As(err, &kucoinErr) {
	fmt.Println(kucoinErr.HTTPStatus, kucoinErr.Code, kucoinErr.Message)
}

Authenticated account/order examples aren't shown here because that domain isn't implemented yet — see Status above.


WebSocket examples

Not yet implemented. No WebSocket client exists in this checkpoint. Token acquisition, subscription ACKs, heartbeat, reconnect/re-subscribe, and typed message dispatch are all planned for a later phase — see CONTRIBUTING.md.


Configuration

Option Description Default
WithCredentials(Credentials) API key/secret/passphrase/key-version zero value (public-only)
WithUTABaseURL(string) / WithClassicBaseURL(string) Override REST hosts https://api.kucoin.com
WithHTTPClient(*http.Client) Inject a custom HTTP client &http.Client{Timeout: 15s}
WithTimeout(time.Duration) Timeout for the internally built HTTP client 15s
WithSiteType(SiteType) X-SITE-TYPE header (global/australia) global
WithEnableNS(bool) Send kc-enable-ns: true for nanosecond response timing false
WithClock(Clock) Inject a clock (tests, clock-skew correction) system clock
WithLogger(Logger) Structured logger (never logs credentials) no-op
WithRetryPolicy(*RetryPolicy) Override the default GET-only retry policy NewDefaultRetryPolicy()

Endpoint reference

Full, generated coverage map with direct KuCoin doc links: docs/ENDPOINTS.md. Source manifest: internal/endpoints.yaml. Official docs map: KuCoin llms.txt.

Before wiring up a new integration, it's worth skimming this file — it tells you at a glance whether the endpoint you need already exists, or whether you'd be the first to ask for it.


A few practical tips

  1. Use strings for money. Every numeric financial field in this SDK is a string. Reach for math/big.Rat or a decimal library when doing arithmetic; avoid strconv.ParseFloat where precision matters.
  2. Check docs/ENDPOINTS.md before assuming coverage. This is an in-progress SDK — don't assume a method exists just because the equivalent REST endpoint is documented by KuCoin.
  3. Pass contexts with deadlines. Especially relevant once trading endpoints land — a slow request can outlive its usefulness.
  4. Check errors by type. Use errors.Is for sentinel errors like transport.ErrRateLimited and errors.As for *transport.KucoinError instead of matching on error strings.
  5. Watch the retry policy. Only GET requests are retried automatically. Once order/transfer endpoints ship, treat every write call as "fires once" unless you add your own idempotency handling.

Testing and development

go test ./...              # unit tests (offline, httptest-backed, no credentials required)
go vet ./...
go run ./internal/gendocs  # regenerate docs/ENDPOINTS.md after editing the manifest

No test, example, or CI job in this repository places a live trading, transfer, or withdrawal call.


Compatibility and migration

Pre-1.0: breaking changes may happen between minor versions while Phase 1 is being built out; see CHANGELOG.md. This library is not a drop-in replacement for the official KuCoin Universal SDK — method names, types, and error handling are intentionally different (see the design notes in this README and CONTRIBUTING.md).


This is an unofficial, community-maintained client. It is provided as is, with no warranty. Nothing here is financial advice. You are solely responsible for complying with the laws and regulations of your jurisdiction and for the safety of your API credentials and funds. Always test against a small amount / read-only permissions before trusting new code with a funded account.


Contributing and roadmap

See CONTRIBUTING.md for the workflow and the phase-by-phase roadmap. Contributions that add a missing endpoint, tighten test coverage, or improve documentation accuracy are especially welcome — a good first contribution is usually a single UTA or Classic REST endpoint with its fixtures and a docs/ENDPOINTS.md entry.


Getting help

  • Found a bug or missing endpoint you need? Open an issue.
  • Found a security issue? Please follow SECURITY.md instead of opening a public issue.
  • General questions about scope or roadmap are welcome as issues too — this project is small enough that direct feedback shapes what gets built next.

License

MIT. See LICENSE.

Author

Igor Sazonov — @tigusigalpa — sovletig@gmail.com


Not affiliated with KuCoin. This is an early checkpoint — verify coverage in docs/ENDPOINTS.md before relying on any endpoint.

Documentation

Overview

Package kucoin is an idiomatic Go client for KuCoin's UTA (Unified Trading Account) and Classic (Spot/Margin/Futures) REST and WebSocket APIs.

UTA and Classic are exposed as explicit, separate service roots (Client.UTA / Client.Classic) rather than a merged type — they are different account models with different permissions and data shapes, and treating them as interchangeable would be misleading.

Docs: https://www.kucoin.com/docs-new/introduction

Index

Constants

View Source
const (
	DefaultUTABaseURL     = "https://api.kucoin.com"
	DefaultClassicBaseURL = "https://api.kucoin.com"
)

Default production REST host. UTA and Classic currently share a host; kept as two options so they can diverge without a breaking change.

Docs: https://www.kucoin.com/docs-new/rest/ua/introduction Docs: https://www.kucoin.com/docs-new/rest/spot-trading/introduction

View Source
const (
	SiteTypeGlobal    = transport.SiteTypeGlobal
	SiteTypeAustralia = transport.SiteTypeAustralia
)

Variables

View Source
var (
	NewDefaultRetryPolicy = transport.NewDefaultRetryPolicy
	NoRetry               = transport.NoRetry
)

Functions

This section is empty.

Types

type Client

type Client struct {

	// UTA groups every implemented UTA (Unified Trading Account) service.
	UTA UTAServices
	// contains filtered or unexported fields
}

Client is the SDK entry point. Construct with NewClient. Public endpoints (e.g. Client.UTA.Market) work with zero-value Credentials; private endpoints return ErrCredentialsRequired locally if none are configured.

func NewClient

func NewClient(opts ...Option) *Client

NewClient builds a fully wired Client. It performs no network I/O.

type ClientConfig

type ClientConfig struct {
	Credentials Credentials

	UTABaseURL     string
	ClassicBaseURL string

	HTTPClient *http.Client
	Timeout    time.Duration

	SiteType SiteType
	EnableNS bool

	Clock  Clock
	Logger Logger

	RetryPolicy *RetryPolicy
}

ClientConfig holds every configurable knob of a Client. Zero value is usable; NewClient fills in defaults for unset fields.

type Clock

type Clock = transport.Clock

Re-exported from package transport so callers only need to import package kucoin for the common case.

type Credentials

type Credentials = transport.Credentials

Re-exported from package transport so callers only need to import package kucoin for the common case.

type Logger

type Logger = transport.Logger

Re-exported from package transport so callers only need to import package kucoin for the common case.

type Option

type Option func(*ClientConfig)

Option configures a ClientConfig at construction time.

func WithClassicBaseURL

func WithClassicBaseURL(url string) Option

func WithClock

func WithClock(clock Clock) Option

func WithCredentials

func WithCredentials(creds Credentials) Option

func WithEnableNS

func WithEnableNS(enabled bool) Option

WithEnableNS sends "kc-enable-ns: true", requesting nanosecond-precision x-in-time/x-out-time response headers.

Docs: https://www.kucoin.com/docs-new/authentication

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

func WithLogger

func WithLogger(logger Logger) Option

func WithRetryPolicy

func WithRetryPolicy(policy *RetryPolicy) Option

WithRetryPolicy overrides the default conservative retry policy (GET requests only; see transport.RetryPolicy).

func WithSiteType

func WithSiteType(siteType SiteType) Option

func WithTimeout

func WithTimeout(d time.Duration) Option

func WithUTABaseURL

func WithUTABaseURL(url string) Option

type RetryPolicy

type RetryPolicy = transport.RetryPolicy

Re-exported from package transport so callers only need to import package kucoin for the common case.

type SiteType

type SiteType = transport.SiteType

Re-exported from package transport so callers only need to import package kucoin for the common case.

type UTAServices

type UTAServices struct {
	Market *market.Client
}

UTAServices groups every implemented UTA (Unified Trading Account) service.

Docs: https://www.kucoin.com/docs-new/rest/ua/introduction

Directories

Path Synopsis
Package auth implements KuCoin's HMAC-SHA256 request-signing scheme.
Package auth implements KuCoin's HMAC-SHA256 request-signing scheme.
examples
uta_market command
Command uta_market demonstrates KuCoin UTA public market data.
Command uta_market demonstrates KuCoin UTA public market data.
internal
gendocs command
Command gendocs regenerates docs/ENDPOINTS.md from internal/endpoints.yaml, the single source of truth for endpoint coverage.
Command gendocs regenerates docs/ENDPOINTS.md from internal/endpoints.yaml, the single source of truth for endpoint coverage.
Package transport implements the shared HTTP request executor, response metadata capture, and error hierarchy used by every KuCoin service.
Package transport implements the shared HTTP request executor, response metadata capture, and error hierarchy used by every KuCoin service.
uta
market
Package market implements KuCoin UTA's public market-data endpoints.
Package market implements KuCoin UTA's public market-data endpoints.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL