kucoin

package module
v1.1.15 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 18 Imported by: 0

README

KuCoin Golang SDK

KuCoin Golang API SDK

CI Tests Go vet CodeQL codecov Go Report Card Go Reference 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. UTA's public market data plus private account/orders/positions/leverage are implemented and tested, alongside Classic Spot (market data + HF order management + the stop-order and OCO-order families + Disconnect Cancel Protocol), a Classic Futures seed set (place/test/query orders, position/margin/position-mode reads — not cancel, and not the full stop/OCO order family), and a Classic Margin seed set (symbols/mark-price/config/risk-limit market data, core order management, stop/OCO orders, borrow/repay/interest — confirmed to be a distinct parallel endpoint family from Classic Spot's, not a shared one), plus a WebSocket layer (bullet-token issuance for all three account/host combinations, plus a generic reconnecting client for both the UTA and Classic wire protocols — see WebSocket examples). Classic Margin's lending-side ("Credit") endpoints and Phase 3 specialty domains are 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 Done — shared infra, UTA Market/Account/Orders, Classic Spot, Classic Futures seed set, and a generic reconnecting WS client (both protocols) are done; Futures market-data endpoints and hand-typed per-channel WS payloads remain open
2 — trading breadth Classic Margin; advanced Spot/Margin orders; UTA positions/leverage; more WS channels Partial — UTA Positions/Leverage, a Classic Margin seed set (market data, order management, stop/OCO orders, borrow/repay/interest), and Classic Spot stop/OCO orders are done; Margin's lending-side ("Credit") endpoints 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
  • clientOid is never auto-generated: PlaceOrder/batch-cancel requests take it as an explicit field, so retry-sensitive workflows stay in your control
  • Local, no-network-call validation for obviously malformed requests (cancel without an ID, a batch over KuCoin's 20-item limit) — see orders.ErrOrderIDOrClientOidRequired / orders.ErrTooManyBatchCancelItems
  • Defensive decoding around two confirmed KuCoin documentation inconsistencies: positions.Position.Value() handles the positionValue/positionMargin field-name conflict, and leverage.LeverageEntry.MarginMode preserves KuCoin's literal (typo'd) ISOLATE value instead of silently coercing it

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, client.Classic.Spot, and client.Classic.Futures — 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: client.UTA.Market.GetKlines and client.Classic.Spot.Market.GetKlines both return [timestamp, ...] arrays, but in different field orders — see the docblocks on uta/market.Kline and classic/spot/market.Kline.

// UTA
ticker, err := client.UTA.Market.GetTickers(ctx, market.TradeTypeSpot, "BTC-USDT")
// Classic Spot
ticker, err := client.Classic.Spot.Market.GetTicker(ctx, "BTC-USDT")

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

Authenticated account data:

overview, err := client.UTA.Account.GetOverview(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println("available margin:", overview.AvailableMargin)

A test-safe order flow with an explicit clientOid (never auto-generated — see Security, risk and legal notice before running this against a funded account):

ref, err := client.UTA.Orders.PlaceOrder(ctx, orders.PlaceOrderRequest{
	TradeType: "SPOT",
	Symbol:    "BTC-USDT",
	Side:      "BUY",
	OrderType: "LIMIT",
	Size:      "0.001",
	SizeUnit:  "BASECCY",
	Price:     "10000", // deliberately far below market so it won't fill
	ClientOid: "my-app-order-0001",
})
if err != nil {
	log.Fatal(err)
}

_, err = client.UTA.Orders.CancelOrder(ctx, orders.CancelOrderRequest{
	TradeType: "SPOT", Symbol: "BTC-USDT", OrderID: ref.OrderID,
})

Classic Spot (a separate, differently-shaped account model — see "UTA versus Classic" above):

spotRef, err := client.Classic.Spot.Orders.PlaceOrder(ctx, classicspotorders.PlaceOrderRequest{
	Type:      "limit",
	Symbol:    "BTC-USDT",
	Side:      "buy",
	Price:     "10000", // deliberately far below market so it won't fill
	Size:      "0.001",
	ClientOid: "my-app-classic-order-0001",
})
if err != nil {
	log.Fatal(err)
}
_, err = client.Classic.Spot.Orders.CancelOrderByID(ctx, spotRef.OrderID, "BTC-USDT")

Classic Spot stop order (a distinct, older order family from HF orders above — /api/v1/stop-order, not /api/v1/hf/orders):

stopRef, err := client.Classic.Spot.Orders.AddStopOrder(ctx, classicspotorders.StopOrderRequest{
	Symbol:    "BTC-USDT",
	Side:      "sell",
	Type:      "limit",
	StopPrice: "45000", // triggers once the last trade price crosses this
	Price:     "44900",
	Size:      "0.001",
	Stop:      "loss", // "loss" (<=) or "entry" (>=)
})
if err != nil {
	log.Fatal(err)
}
_, err = client.Classic.Spot.Orders.CancelStopOrderByID(ctx, stopRef.OrderID)

Classic Spot OCO order (a limit-order leg paired with a stop-limit leg — /api/v3/oco/order; ClientOid is required here, unlike AddStopOrder):

ocoRef, err := client.Classic.Spot.Orders.AddOCOOrder(ctx, classicspotorders.OCOOrderRequest{
	Symbol:     "BTC-USDT",
	Side:       "sell",
	ClientOid:  "my-app-oco-order-0001",
	Price:      "50000", // the limit-order leg
	Size:       "0.001",
	StopPrice:  "45000", // triggers the stop-limit leg
	LimitPrice: "44900",
})
if err != nil {
	log.Fatal(err)
}
// GetOCOOrderByID returns a flat summary; GetOCOOrderDetails returns the two legs.
_, err = client.Classic.Spot.Orders.CancelOCOOrderByID(ctx, ocoRef.OrderID)

Classic Futures (yet another separate host and schema — client.Classic.Futures; seed set only, no cancel endpoint yet):

futuresRef, err := client.Classic.Futures.Orders.PlaceOrder(ctx, classicfuturesorders.PlaceOrderRequest{
	ClientOid: "my-app-futures-order-0001",
	Side:      "buy",
	Symbol:    "XBTUSDTM",
	Price:     "10000", // deliberately far below market so it won't fill
	Size:      1,
})
if err != nil {
	log.Fatal(err)
}
positions, err := client.Classic.Futures.Positions.GetPositionDetails(ctx, "XBTUSDTM")

Classic Margin (client.Classic.Margin; shares Classic Spot's host; tradeType discriminates cross vs isolated on order-listing calls, isIsolated on everything else — see the UTA versus Classic note on this SDK's convention):

marginRef, err := client.Classic.Margin.Orders.PlaceOrder(ctx, classicmarginorders.PlaceOrderRequest{
	ClientOid:  "my-app-margin-order-0001",
	Symbol:     "BTC-USDT",
	Side:       "buy",
	Price:      "10000", // deliberately far below market so it won't fill
	Size:       "0.001",
	IsIsolated: true,
})
if err != nil {
	log.Fatal(err)
}
_, err = client.Classic.Margin.Orders.CancelOrderByID(ctx, marginRef.OrderID, "BTC-USDT")

borrowRef, err := client.Classic.Margin.Debit.Borrow(ctx, classicmargindebit.BorrowRequest{
	Currency: "USDT", Size: "100", TimeInForce: "FOK",
})

Margin has its own parallel stop-order and OCO-order families under /api/v3/hf/margin/stop-order / /api/v3/hf/margin/oco-order — confirmed distinct from Classic Spot's /api/v1/stop-order / /api/v3/oco/order, not shared endpoints. Margin mode is selected via IsIsolated on these two Add calls (not TradeType, which is reserved for the listing endpoints):

marginStopRef, err := client.Classic.Margin.Orders.AddStopOrder(ctx, classicmarginorders.StopOrderRequest{
	Symbol:     "BTC-USDT",
	Side:       "sell",
	Type:       "limit",
	StopPrice:  "45000",
	Price:      "44900",
	Size:       "0.001",
	IsIsolated: true,
})

Cursor pagination:

page, err := client.UTA.Orders.GetOrderHistory(ctx, "SPOT", orders.GetOrderHistoryOptions{PageSize: 50})
for page.LastID != 0 {
	// process page.Items...
	page, err = client.UTA.Orders.GetOrderHistory(ctx, "SPOT", orders.GetOrderHistoryOptions{LastID: page.LastID, PageSize: 50})
	if err != nil {
		break
	}
}

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

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


WebSocket examples

Classic and UTA use two structurally different wire protocols, so there are two client types: websocket/classic and websocket/uta. Both handle reconnect-with-backoff, automatic resubscription, and ping/pong heartbeats; neither is embedded in the REST Client — fetch a token via REST, then hand it to the WS client yourself, so REST and WS lifecycles stay independent.

Classic Spot (public channel, no credentials needed):

import (
	"context"

	kucoin "github.com/tigusigalpa/kucoin-go"
	classicws "github.com/tigusigalpa/kucoin-go/websocket/classic"
)

token, err := client.Classic.Spot.Ws.GetPublicToken(ctx)
if err != nil {
	log.Fatal(err)
}
inst := token.InstanceServers[0]

ws := classicws.NewClient(inst.Endpoint, token.Token)
if err := ws.Connect(ctx); err != nil {
	log.Fatal(err)
}
defer ws.Close()

msgs, err := ws.Subscribe(ctx, "/market/ticker:BTC-USDT", false)
if err != nil {
	log.Fatal(err)
}
for msg := range msgs {
	fmt.Println(msg.Topic, string(msg.Data))
}

UTA (private channel — note KuCoin documents the UTA WebSocket API as pre-release/beta, not for production/live trading):

import utaws "github.com/tigusigalpa/kucoin-go/websocket/uta"

token, err := client.UTA.Ws.GetPrivateToken(ctx)
if err != nil {
	log.Fatal(err)
}

ws := utaws.NewClient(utaws.PrivateWSURL, token.Token)
if err := ws.Connect(ctx); err != nil {
	log.Fatal(err)
}
defer ws.Close()

pushes, err := ws.Subscribe("order", "SPOT", "")
if err != nil {
	log.Fatal(err)
}
for push := range pushes {
	fmt.Println(push.T, string(push.Data))
}

Only a handful of channels are hand-typed as models so far; Message.Data/Push.Data is raw json.RawMessage for everything else — decode it yourself per KuCoin's documented per-channel payload shape. Classic.Futures.Ws works the same way as Classic.Spot.Ws, against the api-futures.kucoin.com host.


Configuration

Option Description Default
WithCredentials(Credentials) API key/secret/passphrase/key-version zero value (public-only)
WithUTABaseURL(string) / WithClassicBaseURL(string) / WithClassicFuturesBaseURL(string) Override REST hosts https://api.kucoin.com / https://api.kucoin.com / https://api-futures.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. PlaceOrder/CancelOrder/BatchModifyMarginMode/etc. and every other POST call fire once — build your own idempotency handling (stable clientOid + a query-before-retry check) if you need retry safety on writes.

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"
	DefaultClassicFuturesBaseURL = "https://api-futures.kucoin.com"
)

Default production REST hosts. UTA and Classic Spot currently share a host; kept as separate options so they can diverge without a breaking change. Classic Futures has always used a distinct host, confirmed across every Futures endpoint.

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

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

SiteTypeGlobal and SiteTypeAustralia re-export KuCoin's supported regional site types.

Variables

View Source
var NewDefaultRetryPolicy = transport.NewDefaultRetryPolicy

NewDefaultRetryPolicy re-exports transport.NewDefaultRetryPolicy.

View Source
var NoRetry = transport.NoRetry

NoRetry re-exports transport.NoRetry.

Functions

This section is empty.

Types

type ClassicServices added in v1.1.6

type ClassicServices struct {
	Spot    SpotServices
	Futures FuturesServices
	Margin  MarginServices
}

ClassicServices groups every implemented Classic (pre-UTA) account-mode service.

type Client

type Client struct {

	// UTA groups every implemented UTA (Unified Trading Account) service.
	UTA UTAServices
	// Classic groups every implemented Classic account-mode service.
	Classic ClassicServices
	// 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
	ClassicFuturesBaseURL 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

Clock re-exports transport.Clock for callers of package kucoin.

type Credentials

type Credentials = transport.Credentials

Credentials re-exports transport.Credentials for callers of package kucoin.

type FuturesServices added in v1.1.6

type FuturesServices struct {
	Orders    *classicfuturesorders.Client
	Positions *classicfuturespositions.Client
	// Ws fetches public/private WebSocket bullet-tokens
	// (POST /api/v1/bullet-public, /api/v1/bullet-private). It does not
	// open a socket itself — pass the returned token/instanceServers to
	// websocket/classic.NewClient.
	Ws *classicfuturesws.Client
}

FuturesServices groups Classic Futures' implemented services (a seed set — Phase 1 scope, not the full Futures API; see docs/ENDPOINTS.md for exactly what's covered).

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

type Logger

type Logger = transport.Logger

Logger re-exports transport.Logger for callers of package kucoin.

type MarginServices added in v1.1.6

type MarginServices struct {
	Market *classicmarginmarket.Client
	Orders *classicmarginorders.Client
	Debit  *classicmargindebit.Client
}

MarginServices groups Classic Margin's implemented services (a seed set covering symbols/mark-price/config/risk-limit market data, core order management, and borrow/repay/interest — not the full Margin API; see docs/ENDPOINTS.md for exactly what's covered). Margin shares Classic Spot's host (api.kucoin.com).

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

type Option

type Option func(*ClientConfig)

Option configures a ClientConfig at construction time.

func WithClassicBaseURL

func WithClassicBaseURL(url string) Option

WithClassicBaseURL overrides the base URL used for Classic Spot and Margin REST requests.

func WithClassicFuturesBaseURL added in v1.1.6

func WithClassicFuturesBaseURL(url string) Option

WithClassicFuturesBaseURL overrides the base URL used for Classic Futures REST requests.

func WithClock

func WithClock(clock Clock) Option

WithClock sets the clock used for request timestamps and retry timing.

func WithCredentials

func WithCredentials(creds Credentials) Option

WithCredentials sets API credentials used for private endpoints.

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

WithHTTPClient sets the HTTP client used for REST requests.

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger used by REST transport.

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

WithSiteType sets the X-SITE-TYPE header sent with requests.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the timeout of the default HTTP client.

func WithUTABaseURL

func WithUTABaseURL(url string) Option

WithUTABaseURL overrides the base URL used for UTA REST requests.

type RetryPolicy

type RetryPolicy = transport.RetryPolicy

RetryPolicy re-exports transport.RetryPolicy for callers of package kucoin.

type SiteType

type SiteType = transport.SiteType

SiteType re-exports transport.SiteType for callers of package kucoin.

type SpotServices added in v1.1.6

type SpotServices struct {
	Market *classicspotmarket.Client
	Orders *classicspotorders.Client
	// Ws fetches public/private WebSocket bullet-tokens
	// (POST /api/v1/bullet-public, /api/v1/bullet-private). It does not
	// open a socket itself — pass the returned token/instanceServers to
	// websocket/classic.NewClient.
	Ws *classicspotws.Client
}

SpotServices groups Classic Spot's implemented services.

Docs: https://www.kucoin.com/docs-new/rest/spot-trading/market-data/get-all-symbols

type UTAServices

type UTAServices struct {
	Market    *market.Client
	Account   *account.Client
	Orders    *orders.Client
	Positions *positions.Client
	Leverage  *leverage.Client
	// Ws fetches the private WebSocket bullet-token
	// (POST /api/v2/bullet-private). It does not open a socket itself —
	// pass the returned token to websocket/uta.NewClient.
	Ws *utaws.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.
classic
futures/orders
Package orders implements a seed set of KuCoin Classic Futures' private order-management endpoints (place/test/query — Phase 1 scope; cancel and the broader stop/OCO order family are not yet implemented).
Package orders implements a seed set of KuCoin Classic Futures' private order-management endpoints (place/test/query — Phase 1 scope; cancel and the broader stop/OCO order family are not yet implemented).
futures/positions
Package positions implements a seed set of KuCoin Classic Futures' private position-related endpoints.
Package positions implements a seed set of KuCoin Classic Futures' private position-related endpoints.
futures/ws
Package ws implements KuCoin Classic Futures' WebSocket token-acquisition endpoints.
Package ws implements KuCoin Classic Futures' WebSocket token-acquisition endpoints.
margin/debit
Package debit implements KuCoin Classic Margin's borrow/repay/interest endpoints (the "Debit" sub-domain) plus leverage modification.
Package debit implements KuCoin Classic Margin's borrow/repay/interest endpoints (the "Debit" sub-domain) plus leverage modification.
margin/market
Package market implements a seed set of KuCoin Classic Margin's public market-data endpoints: symbol specs (cross + isolated), mark price, margin config, and risk limits (cross + isolated).
Package market implements a seed set of KuCoin Classic Margin's public market-data endpoints: symbol specs (cross + isolated), mark price, margin config, and risk limits (cross + isolated).
margin/orders
Package orders implements KuCoin Classic Margin's private order-management endpoints, all under the /api/v3/hf/margin/...
Package orders implements KuCoin Classic Margin's private order-management endpoints, all under the /api/v3/hf/margin/...
spot/market
Package market implements KuCoin Classic Spot's market-data endpoints.
Package market implements KuCoin Classic Spot's market-data endpoints.
spot/orders
Package orders implements KuCoin Classic Spot's private order-management endpoints.
Package orders implements KuCoin Classic Spot's private order-management endpoints.
spot/ws
Package ws implements KuCoin Classic Spot/Margin's WebSocket token-acquisition endpoints.
Package ws implements KuCoin Classic Spot/Margin's WebSocket token-acquisition endpoints.
ws
Package ws holds the token response shape shared by Classic Spot and Classic Futures' WebSocket token-acquisition endpoints.
Package ws holds the token response shape shared by Classic Spot and Classic Futures' WebSocket token-acquisition endpoints.
examples
uta_market command
Command uta_market demonstrates KuCoin UTA public market data.
Command uta_market demonstrates KuCoin UTA public market data.
uta_trading command
Command uta_trading demonstrates authenticated UTA account/order/ position endpoints.
Command uta_trading demonstrates authenticated UTA account/order/ position endpoints.
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
account
Package account implements KuCoin UTA's private account endpoints.
Package account implements KuCoin UTA's private account endpoints.
leverage
Package leverage implements KuCoin UTA's private leverage-management endpoints.
Package leverage implements KuCoin UTA's private leverage-management endpoints.
market
Package market implements KuCoin UTA's public market-data endpoints.
Package market implements KuCoin UTA's public market-data endpoints.
orders
Package orders implements KuCoin UTA's private order-management endpoints.
Package orders implements KuCoin UTA's private order-management endpoints.
positions
Package positions implements KuCoin UTA's private position-management endpoints.
Package positions implements KuCoin UTA's private position-management endpoints.
ws
Package ws implements KuCoin UTA's WebSocket token-acquisition endpoint.
Package ws implements KuCoin UTA's WebSocket token-acquisition endpoint.
websocket
classic
Package classic implements a reconnecting WebSocket client for KuCoin's Classic (Spot/Margin/Futures) WebSocket API.
Package classic implements a reconnecting WebSocket client for KuCoin's Classic (Spot/Margin/Futures) WebSocket API.
uta
Package uta implements a reconnecting WebSocket client for KuCoin's UTA WebSocket API.
Package uta implements a reconnecting WebSocket client for KuCoin's UTA WebSocket API.

Jump to

Keyboard shortcuts

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