cexy

package module
v0.1.0-dev.16 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cexy-go

The official Go SDK for the CEXY.io REST and WebSocket API.

  • Typed models generated from the public OpenAPI spec (cexy-api-spec).
  • Safe by default: retries with backoff, order placement designed to avoid duplicate orders (via client_order_id), a client-side rate limiter, and no HTTP redirects followed.
  • A WebSocket client with heartbeat, reconnect and a live order book that applies the sync rules for you.
  • context.Context on every call, range-over-func iterators (iter.Seq2) for pagination, one dependency (coder/websocket).
  • Go 1.26 or newer.

Status: 0.x, pre-release. The API is not yet frozen. It stays 0.x until the exchange ships HMAC request signing, which will change how credentials are sent.

Install

go get github.com/cexyio/cexy-go@v0.1.0-dev.16
import cexy "github.com/cexyio/cexy-go"

Quick start: public data

ctx := context.Background()
c, err := cexy.New(cexy.Options{}) // no key needed for market data
if err != nil {
	log.Fatal(err)
}

markets, err := c.Markets.List(ctx)
btc, err := c.Markets.Get(ctx, "BTC/USDT")
book, err := c.Markets.OrderBook(ctx, "BTC/USDT", &cexy.GetOrderBookParams{Depth: cexy.Ptr(10)})
candles, err := c.Markets.Candles(ctx, "BTC/USDT", cexy.GetCandlesParams{Interval: cexy.CandleInterval1h, Limit: cexy.Ptr(24)})
now, err := c.Time(ctx)

Also: Assets.List/Get, Networks.List, Fees.List, Config, Pools.List/Get, Markets.Trades. Optional parameters are pointers; cexy.Ptr(v) makes one.

Quick start: your account

c, err := cexy.New(cexy.Options{
	APIKey:    os.Getenv("CEXY_API_KEY"),    // ak_your_key_here
	APISecret: os.Getenv("CEXY_API_SECRET"), // your_secret_here
})

balances, err := c.Account.Balances(ctx)
// A sub-account's balances (parent account only; same shape, incl. HeldIncoming):
subBalances, err := c.Account.SubAccountBalances(ctx, "sub-account-id")
open, err := c.Trading.OpenOrders(ctx, &cexy.ListOpenOrdersParams{Symbol: cexy.Ptr("BTC/USDT")})

placed, err := c.Trading.PlaceOrder(ctx, cexy.PlaceOrderRequest{
	Symbol:   "BTC/USDT",
	Side:     cexy.OrderSideBuy,
	Type:     cexy.OrderTypeLimit,
	Price:    cexy.Ptr(cexy.Amount("60000.00")), // decimal STRINGS, never floats
	Quantity: cexy.Ptr(cexy.Amount("0.0010")),
})
_, err = c.Trading.CancelOrder(ctx, placed.Order.ID)
_, err = c.Trading.CancelAll(ctx, "BTC/USDT") // CancelAllMarkets(ctx) = every market, explicitly

CancelAll requires a symbol: the server treats a missing symbol as "every market", so that is a separate method, CancelAllMarkets. The server allows cancel-all 30 times a minute per account. Cancel-all also cancels stop orders that have not triggered yet (status pending_trigger) and releases their reservations, so nothing fires into the market after the call.

Dead-man switch

CancelAllAfter arms a timer: if you do not arm again before it runs out, the server cancels the open orders in scope. timeout of 0 disarms.

// Arm every ~2 s with a 10 s timeout. Time the local deadline from when the call started.
res, err := c.Trading.CancelAllAfter(ctx, "BTC/USDT", 10*time.Second) // CancelAllAfterMarkets(ctx, d) = every market
_, err = c.Trading.CancelAllAfter(ctx, "BTC/USDT", 0)                 // disarm this market only

A blank symbol is refused (use CancelAllAfterMarkets), and so is a timeout that is negative, below 1 ms or not a whole number of milliseconds; the server checks the 5 s to 10 min range. Per-market and all-markets switches are separate. A fired switch is cleared: arm again before quoting. Never compare the local clock with Deadline. After a retried arm, disarm once more if the switch must be off; no endpoint reads it. A house account placing an order without an armed switch gets ErrDeadManNotArmed (DEAD_MAN_NOT_ARMED, 409, not retried): stop quoting.

One cancel-all call handles at most 500 orders. Each order it handled is in exactly one of Cancelled, AlreadyClosed (it closed on its own first; not an error) and Failed, with the reason in Failures (INVALID_STATE means an order taken off the book that cannot be cancelled yet; a pending order is cancelled at once by the server). HasMore means there are more. To repeat until nothing is left, use CancelAllUntilDone:

sum, err := c.Trading.CancelAllUntilDone(ctx, cexy.CancelAllOptions{Symbol: "BTC/USDT"}) // or AllMarkets: true
// sum.Cancelled, sum.AlreadyClosed, sum.Failed + sum.Failures, sum.Rounds, sum.Stopped

It calls again while HasMore is set or a failure code is SERVICE_UNAVAILABLE, MARKET_UNAVAILABLE or CONCURRENT_MODIFICATION. INVALID_STATE is returned, not retried. Each round is exactly one HTTP request (the loop owns the retries), so it never sends more than MaxRounds requests (default 20). After a round with no progress it waits 1, 2, 4, 8, then 15 s. A round that fails with a retryable error counts as a round: after a 429 it waits the server's Retry-After exactly, after other retryable errors the next back-off step. It never takes a wait that would reach TimeBudget (default 120 s): it stops with Stopped: "time_budget" and LastErrorCode set. A market that stays down returns only when the time budget ends. A non-retryable error is returned with the summary so far. Rounds are merged by order id: the latest state wins.

Give both APIKey and APISecret, or neither: New returns a *ConfigError for only one.

Service Methods Scope
Markets List, Get, OrderBook, Trades, AllTrades, Candles public
Assets, Networks, Fees, Pools List, Get / List / List / List, Get public
Time, Config (on Client) public
Account Balances, Balance, Ledger, Notifications, SubAccounts, SubAccountBalances, APIKeys (+ All… iterators) read
Exports Deposits, Ledger, Orders, Trades, Withdrawals (CSV text) read
Wallet Deposits, Deposit, Withdrawals, Withdrawal, WithdrawalAddresses, DepositAddress (+ iterators) read
Trading OpenOrders, Order, OrderByClientID, OrderHistory, Trades (+ iterators) read
Trading PlaceOrder, CancelOrder, CancelAll, CancelAllMarkets, CancelAllUntilDone, CancelAllAfter, CancelAllAfterMarkets trade
Pools Join, Exit trade

Wallet.DepositAddress creates the address on the first call for that asset and network (later calls return the same one). Always use the memo too when one is returned.

There are no withdrawal or transfer methods: API keys cannot withdraw or transfer funds.

Held incoming transfers

Balance.HeldIncoming lists incoming internal transfers still held, each with TransferID, Amount and AvailableAt. Their sum is already included in Locked, so never add it to Locked or Total again. There are at most 100 entries, soonest AvailableAt first (millisecond precision), with no sender identity. An entry disappears once the transfer is released (the amount moves to Available) or cancelled by the exchange. It is never nil: an empty slice when none, including from servers that predate the field.

Batch orders

Place up to 20 orders in one market with one request, or cancel up to 50:

res, err := c.Trading.PlaceOrders(ctx, "BTC/USDT", []cexy.PlaceOrdersItem{
	{Side: cexy.OrderSideBuy, Type: cexy.OrderTypeLimit, Price: cexy.Ptr(cexy.Amount("64000")), Quantity: cexy.Ptr(cexy.Amount("0.01"))},
	{Side: cexy.OrderSideSell, Type: cexy.OrderTypeLimit, Price: cexy.Ptr(cexy.Amount("66000")), Quantity: cexy.Ptr(cexy.Amount("0.01"))},
})
if err != nil {
	return err
}
for _, o := range res.Results { // request order
	fmt.Println(o.Index, o.ClientOrderID, o.Outcome, o.OrderID, o.Status, o.Error)
}

_, err = c.Trading.CancelOrders(ctx, []cexy.CancelBatchItem{{OrderID: cexy.Ptr("...")}, {ClientOrderID: cexy.Ptr("...")}})
_, err = c.Trading.CancelOrderByClientID(ctx, "my-id-1")
  • Each order is placed (or cancelled) on its own: the batch is not atomic, and one refusal does not stop the rest. Each result's Outcome is OutcomePlaced (or OutcomeCancelled), OutcomeFailed with Error, OutcomeRecovered or OutcomeUnknown (below). The counts on the result are computed from the results.
  • Every order carries a client_order_id; one (a UUID) is generated for each order without one. Your own ids must be 1 to 64 characters of A-Z a-z 0-9 _ - . :, not . or .., distinct within the batch, and unique per account across all markets.
  • If you need to reconcile, supply and save your own client_order_ids before the call (cexy.NewClientOrderID() makes one). That is the only protection if your process dies mid-call.
  • Retries: the request body is built once; a retry after a lost answer (a timeout, or any 5xx except 501 and 503) resends it unchanged, and the server refuses every id it already placed, so nothing is placed twice. Such an order comes back as OutcomeRecovered with its OrderID and Status. A rejected status means the server refused it for funds and its id is spent: do not place it again under that id. OutcomeUnknown means its state could not be read; it was not placed again (look it up with Trading.OrderByClientID). A cancel that a retry finds already closed is looked up and comes back as OutcomeRecovered with its current status. An order refused with an order id in its details (MARKET_UNAVAILABLE when the market stopped while matching) exists, so it is OutcomeRecovered too, and an item INTERNAL error is looked up once.
  • A recovered order counts as placed unless its status is rejected, even one that ended cancelled with nothing filled: read Status before acting on it.
  • res.Unknown > 0: some orders' state could not be read. Look each one up with Trading.OrderByClientID before placing anything again.
  • Errors: once the body is built, every failure of PlaceOrders is a *cexy.BatchPlaceError with ClientOrderIDs (every id sent, in order, generated ones included) and MaybePlaced. The cause is wrapped: errors.As finds the *APIError or *ConnectionError, and errors.Is finds context.Canceled or cexy.ErrBadResponse (a 2xx without usable results, which the server acted on). Reconcile with Trading.OrderByClientID when MaybePlaced is true.
  • A 400 (bad request), 403 (account may not trade), 404 (no such market) or 429 (spent budget, waited out and resent) refuses the attempt it answers, which placed nothing. An earlier attempt of the same call whose answer was lost may still have placed orders: then MaybePlaced is true. A batch larger than the key's whole budget is a 400 with a number in Details["limit"]: send fewer at a time. The SDK never splits a batch.
Market buys by total

A market buy can name a budget, quote_quantity, instead of a quantity: "spend at most this much of the quote asset".

_, err := c.Trading.PlaceOrder(ctx, cexy.PlaceOrderRequest{
	Symbol:        "BTC/USDT",
	Side:          cexy.OrderSideBuy,
	Type:          cexy.OrderTypeMarket,
	QuoteQuantity: cexy.Ptr(cexy.Amount("50.00")),
})
  • The taker fee is inside the budget: filled_quote_quantity + fee_paid <= quote_quantity, always. A stop-market buy by total reserves exactly the budget.
  • The budget must be at least the market's min_notional. It may have at most the market's price decimals. More decimals are refused with 400 PRECISION_EXCEEDED, never rounded. Trailing zeros are fine.
  • How it ends: filled, with no status_reason, when the budget was used (what is left cannot buy one lot at the last fill price). The last WebSocket frame is then order.filled. Otherwise it ends cancelled with a status_reason, for example Insufficient liquidity to fill the remainder (fills, but the book ran out) or Budget exhausted (no fill; the budget cannot buy one lot).
  • After a server restart mid-order, a budget order can end cancelled with Interrupted; the unfilled remainder was cancelled. Its fills stand and the rest is released: treat it like any partial fill.
  • Reading one: quantity and remaining_quantity are 0 for a budget order. Progress is filled_quote_quantity + fee_paid against quote_quantity. Never divide by quantity.
  • A budget bounds the money spent, not the price paid. On a thin book a market buy can fill far from the last price.

Amounts

Every amount is an exact decimal string (cexy.Amount("0.00150000")), in responses and requests. Floats cannot hold most decimals exactly. The SDK checks every amount field before sending and returns an *InvalidAmountError for anything but a plain decimal (no exponents, no spaces). Do arithmetic with a decimal package such as github.com/shopspring/decimal:

total := decimal.RequireFromString(string(*order.Price)).Mul(decimal.RequireFromString(string(order.Quantity)))

Errors

Every API failure is an *cexy.APIError with Status, Code, Message, Details, Fields, RequestID, Retryable and RetryAfter. Branch on Code, never on Message. Match the category with errors.Is:

Sentinel When
ErrAuthentication 401: missing or invalid credentials
ErrForbidden 403: the key lacks a scope (FORBIDDEN), or the route is session-only (API_KEY_NOT_ALLOWED); also matches 451
ErrJurisdictionBlocked 451: JURISDICTION_BLOCKED (not available in the caller's jurisdiction)
ErrValidation 400: see Fields
ErrNotFound 404
ErrConflict 409: ALREADY_EXISTS, IDEMPOTENCY_KEY_CONFLICT, CONCURRENT_MODIFICATION
ErrUnprocessable 422: INSUFFICIENT_FUNDS, MARKET_UNAVAILABLE, ...
ErrRateLimited 429, with RetryAfter
ErrServer 5xx
(none) a code this SDK version does not know yet: check Code

Local problems are *ConfigError, *InvalidAmountError, *ConnectionError (with Timeout for the per-attempt timeout) and *OrderStateUnknownError. A cancelled context returns ctx.Err(). ErrorCode is an open string type with a constant for every known code (cexy.CodeInsufficientFunds, ...): keep a default branch, because new codes can appear.

_, err := c.Trading.PlaceOrder(ctx, order)
var apiErr *cexy.APIError
switch {
case errors.As(err, &apiErr) && apiErr.Code == cexy.CodeInsufficientFunds:
	log.Println("not enough funds:", apiErr.Details)
case errors.Is(err, cexy.ErrRateLimited):
	log.Println("slow down for", apiErr.RetryAfter)
case err != nil:
	return err
}

Retries and idempotency

  • Timeout per attempt: Options.Timeout (default 10 s). Retries: Options.MaxRetries (default 3; NoRetries turns them off), exponential backoff with full jitter.
  • Retried: connection errors, timeouts and responses with retryable: true (and 409 CONCURRENT_MODIFICATION). A 4xx is never retried except 429 and 409 CONCURRENT_MODIFICATION, whatever its body says.
  • After a 429 with a wait hint, the client-side rate limiter holds every other request of the client for that wait (at most 120 s), not only the retried one. A key that keeps sending through its own limit counts against its IP's failed-key limit (120 a minute) and can lock out every other key on that IP. Market makers: run the cancel/risk key from its own egress IP; a separate key on the same IP is not isolated.
  • A 429 waits Retry-After / details.retry_after_seconds (plus up to 250 ms of jitter). Server wait hints are untrusted: unparseable or absurd values are ignored, and a hint above cexy.MaxServerWait (120 s) is not waited. The call fails at once with the rate-limit APIError, whose RetryAfter still holds the server's value. The client-side rate limiter never blocks longer than MaxServerWait because of a server hint.
  • GETs retry freely.
  • Idempotency-Key is sent only on pool join and exit, the only endpoints that honour it. Orders, order cancels, cancel-all and cancel-all-after send none.
  • Orders: safety rests on client_order_id. PlaceOrder always sends a client_order_id (a UUID if you do not set one); it is unique per account and a repeat is refused before any funds move. After an ambiguous failure (connection error, timeout, 5xx) the SDK first looks the order up by that id. If the order exists it is returned with Recovered: true; only if it does not exist is it sent again, with the same id. If even the lookup fails you get *OrderStateUnknownError: check Trading.OrderByClientID before placing the order again.
  • Cancels: CancelOrder is retried like a read: on connection errors, timeouts and retryable responses (such as a 503, a 429, or a 409 CONCURRENT_MODIFICATION). If a retry gets INVALID_STATE, the first attempt already cancelled the order, so the SDK fetches and returns it. Cancel-all is naturally repeatable and is retried the same way (a retry reports only what it cancelled).
  • Pool join and exit send a generated Idempotency-Key, reused on every retry; the server honours it there, so they execute once. A 409 CONCURRENT_MODIFICATION (the same key still in flight) is retried with the same key. cexy.WithIdempotencyKey(k) sets it yourself (ignored on other calls).
  • Options.OnRetry lets you log retries.

Every method takes a context and optional CallOptions: cexy.WithTimeout(d), cexy.WithMaxRetries(n), cexy.WithIdempotencyKey(k).

Pagination

Histories use opaque cursors. Each listing returns one page (Items, HasMore, NextCursor), and an All… method returns an iterator that fetches pages lazily:

for order, err := range c.Trading.AllOrderHistory(ctx, &cexy.OrderHistoryParams{Symbol: cexy.Ptr("BTC/USDT")}) {
	if err != nil {
		return err
	}
	fmt.Println(order.ID, order.Status)
}
// cap the total: c.Account.AllLedger(ctx, nil, cexy.WithMaxItems(500))

Futures data (read only)

c.Futures reads futures market data and the account's own futures data. Nothing here places or changes anything. Markets are named by coin ("BTC"), not by spot symbol.

mk, err := c.Futures.Markets(ctx)                  // every listed market and its figures
m, err := c.Futures.Market(ctx, "BTC")
book, err := c.Futures.OrderBook(ctx, "BTC", 10)   // levels a side, 1 to 20 (0: the default, 20)
cs, err := c.Futures.Candles(ctx, "BTC", cexy.FuturesCandlesParams{Interval: "1h"}) // 500 candles; Before: an older window
tr, err := c.Futures.Trades(ctx, "BTC", 50)        // recent public trades, at most 100 (0: the default, 50)

Every market response carries AsOf and Stale. For books and trades Stale is the live feed's health, not the data's age: a quiet book can be unchanged and current. When nothing usable is cached the API answers 503 SERVICE_UNAVAILABLE (retryable, with Retry-After), which the client retries like any other retryable error.

With an API key (read scope), the account's own data:

pos, err := c.Futures.Positions(ctx)    // margin summary and open positions
oo, err := c.Futures.OpenOrders(ctx)
if !pos.HasAccount {
	// no futures account: the reads succeed and hold nothing
}
for f, err := range c.Futures.AllFills(ctx) { // newest first, 30 days back
	if err != nil {
		return err
	}
	fmt.Println(f.ID, f.Coin, f.Side, f.Price, f.Size)
}
// funding payments: c.Futures.AllFunding(ctx); one page: c.Futures.Fills(ctx, cursor)

Fills and funding are paged by an opaque cursor: pass NextCursor back exactly as given ("" for the newest page) until it is nil. A page may be short, even empty, and still have a next cursor. AllFills and AllFunding do this for you. While the futures provider is busy the server answers an empty page that hands back the cursor it was given, or a 503 with details.reason futures_data_unavailable: the iterator waits (the server's Retry-After, else details.retry_after_seconds, else the client's backoff; reported to Options.OnRetry) and asks again, at most cexy.WithMaxBusyRetries(n) times in a row (3 by default; independent of the client's retry count, so a client with NoRetries still rides out a busy provider), then yields a retryable *cexy.APIError with code cexy.CodePagingStalled (PAGING_STALLED, made by the SDK, Status 0; after a 503, errors.Unwrap gives it). The rows already yielded are not the whole history: resume later from Details["cursor"]. A page with rows that hands back the cursor it was sent is a server error: its rows are yielded, then a non-retryable cexy.CodePagingCursorRepeated (PAGING_CURSOR_REPEATED) error ends the iteration. Without a futures account the iterators end at once with no rows.

Rate limits

The client has a token-bucket limiter: 100 requests a minute without a key (the server allows 120 a minute per IP for anonymous calls) and 300 a minute with an API key (the server allows 600 a minute per key). Cancel-all is limited separately to 30 a minute per account. It adapts downwards to X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset (seconds until the window resets), and pauses after a 429. Change it with Options.RequestsPerMinute, or turn it off with DisableRateLimit. The limiter belongs to one Client, which is safe for concurrent use: share it.

Batches and order budgets. A batch of N orders or cancel entries takes N tokens from the client's limiter, as the server counts it. A market maker's key also has an order budget of 50 placements a second (per key and per account); cancels never count against it. A 429 whose Details["limit"] is "order_actions" holds only placements (PlaceOrder, PlaceOrders) for its wait: reads and cancels keep going. Set Options.OrderActionsPerSecond to 50 to keep placements under that budget locally instead of being refused (off by default).

WebSocket

ws, err := c.WebSocket(cexy.WSOptions{ // wss://api.cexy.io/api/v1/ws
	Handlers: cexy.WSHandlers{
		OnEvent: func(e cexy.Event) {
			if e.Type == "ticker.update" {
				fmt.Println(e.Channel, string(e.Data))
			}
		},
		OnReconnected: func(cexy.Welcome) { log.Println("reconnected and re-subscribed") },
		OnResync:      func(cexy.ResyncReason) { /* refetch anything you derive from events */ },
	},
})
if _, err := ws.Connect(ctx); err != nil {
	log.Fatal(err)
}
defer ws.Close()
_, err = ws.Subscribe(ctx, "ticker:BTC/USDT", "trades:BTC/USDT")

book, err := ws.OrderBook(ctx, "BTC/USDT", cexy.LiveOrderBookOptions{
	OnUpdate: func(b cexy.BookSnapshot) {
		bid, _, ask, _ := b.Best()
		fmt.Println(bid.Price, ask.Price, b.Stale)
	},
})

Handlers run one at a time on a dedicated goroutine, in frame order, so they may call Subscribe, Auth and the other methods. Keep them quick: frames queue up while a handler runs.

What the client does for you:

  • Sends {"op":"ping"} every 30 s (required: the server closes idle connections) and accepts the server's unsolicited pongs. No frame for 75 s means a dead connection and a reconnect.
  • Reconnects with exponential backoff and full jitter, then re-authenticates and re-subscribes everything.
  • Correlates every request with its acknowledgement by id: Auth returns on authenticated (and fails on an error with its id, or on timeout), Subscribe on subscribed, Unsubscribe on unsubscribed, Ping on pong.
  • Guards locally: at most 100 subscriptions (extras are returned in Refused) and 200 messages a minute.
  • Warns once if the server speaks a newer protocol_version, and ignores unknown event types.

Order-book rules (applied by ws.OrderBook; follow them if you build your own):

  1. Subscribe to orderbook:{symbol} first, then take the REST snapshot (its sequence is S).
  2. Drop updates with sequence <= S.
  3. Every update carries the complete top 50 of both sides ("full": true) and replaces the previous state. There are no deltas. Never merge REST levels deeper than 50 into WebSocket state.
  4. A sequence gap marks the book stale until the next update, which heals it. There is no forced resync.
  5. Sequences reset when the server restarts: take a fresh snapshot after every reconnect.
  6. An error frame CONCURRENT_MODIFICATION with a null id means messages were dropped: resync every book and channel (the client calls OnResync).

Private channels (orders, balances, deposits, withdrawals, account) need ws.Auth(ctx, token) with a session access token (it returns the user_id from authenticated), or ws.AuthKey(ctx) with an API key (see Request signing). If the session is revoked, the client calls OnAuthLost; public channels keep working.

The server ends private subscriptions, without any frame, when Auth succeeds as another user, when an Auth fails (any error signs the connection out), or when this connection's own session is revoked (session.revoked with current: true). The client calls OnAuthChanged (Reason: AuthUserChanged, AuthFailed or AuthSessionRevoked, plus the Dropped channels) and re-subscribes those channels itself: at once for another user, after the next successful Auth otherwise, followed by OnResync(ResyncReauth) (refetch private state).

The server can also sign a connection out by itself: signed_out (a planned server frame; this SDK already handles it). Reason expired gives OnAuthChanged with AuthTokenExpired, reason revoked gives AuthSessionRevoked plus OnAuthLost, and any other reason gives AuthSignedOut with the raw value in Code. Call Auth again with the fresh token on every token refresh; that keeps the private subscriptions.

Missed private events. Every private frame carries a per-connection Sequence. When numbers are skipped (after a short reorder window, WSOptions.ReorderWindow, default 250 ms), the client calls OnSequenceGap and OnResync(ResyncSequenceGap): refetch that channel's state over REST. balances.resync, deposits.resync and withdrawals.resync (the last two planned) call OnResync with ResyncBalancesResync, ResyncDepositsResync or ResyncWithdrawalsResync.

Request signing

Every private request is signed (Auth: "hmac", the default since v0.1.0-dev.9). The API is switching off the old mode that sent the secret in X-API-Secret, and refuses it with SIGNATURE_REQUIRED:

client, err := cexy.New(cexy.Options{APIKey: key, APISecret: secret}) // signs requests; same as Auth: "hmac"

The secret never leaves your process: every private request is signed (X-API-Key, X-API-Timestamp, X-API-Nonce, X-API-Signature), every retry with a fresh timestamp and nonce. A key issued before signing existed fails with KEY_NOT_SIGNABLE: create a new API key. ws.AuthKey(ctx) authenticates a WebSocket with the same key.

The signed timestamp must be at most 30 s behind and 5 s ahead of the server clock: keep the system clock synchronised (NTP). After SIGNATURE_EXPIRED the client adopts the server clock (at most 1 h away) and resends once. For a few seconds after the API's replay-protection store restarts, it may answer 503 SERVICE_UNAVAILABLE (nonce_store_warming); reads are retried after Retry-After.

Futures channels
book, _ := cexy.FuturesOrderBookChannel("BTC")        // "futures.orderbook:BTC"
candles, _ := cexy.FuturesCandlesChannel("BTC", "1m") // "futures.candles:BTC:1m"
_, err := ws.Subscribe(ctx, cexy.FuturesMidsChannel, book, candles)
// in OnEvent:
switch ev.Type {
case "futures.orderbook.update":
	var b cexy.FuturesBookUpdate // the complete book: replace yours
	_ = ev.Decode(&b)
case "futures.mids": // cexy.FuturesMids, the full set
case "futures.trades.new": // cexy.FuturesTradesUpdate
case "futures.candle.update": // cexy.FuturesCandleUpdate
case "futures.status": // cexy.FuturesStatus: live or degraded
}

The helpers check the coin (1 to 20 ASCII letters or digits, sent exactly as given: BTC and btc differ) and the interval (1m, 5m, 15m, 1h, 4h, 1d) and return a *cexy.ConfigError before anything is sent. Public futures channels send nothing on subscribe: seed them from c.Futures over REST. Book levels are {price, size} objects ([]cexy.Level), not the spot [price, quantity] arrays.

cexy.FuturesAccountChannel (futures.account, private) sends futures.positions (cexy.FuturesPositionsUpdate) and futures.orders (cexy.FuturesOrdersUpdate) in full on subscribe and on change. Subscribed before Auth or AuthKey, it is held (ws.PendingChannels()) and subscribed once the connection is authenticated.

futures.resync (data {}) is delivered to OnEvent and to OnFuturesResync(channel): data on that channel may have been missed, refetch it over REST. On futures.account the server's poller has stopped, so the client also unsubscribes and subscribes again by itself; if the server refuses (for example NOT_FOUND "No futures account"), the error is reported (OnServerError, OnError) and the channel is no longer held (an UNAUTHENTICATED refusal keeps it pending until the next auth).

A refused futures subscribe (RATE_LIMITED, NOT_FOUND, VALIDATION_FAILED, SERVICE_UNAVAILABLE) is returned by Subscribe and is not retried. WebSocket error frames carry no retry hint: wait yourself (the server means 60 s) before trying again.

Subscribe refusals work the same for every channel. SubscribeResult.Added lists the channels the server accepted and SubscribeResult.RefusedByServer the refused ones, each with its error frame; only the accepted channels are held. Subscribe returns an error only when every channel sent was refused, or when no answer came (TIMEOUT, a dropped connection). When the client re-subscribes by itself (after a reconnect or a re-auth), a private channel refused with UNAUTHENTICATED waits for the next successful auth (ws.PendingChannels()); any other refusal drops the channel. Each is reported to OnError as a *cexy.SubscribeRefusal (errors.As also finds its *cexy.WSError).

The client pings at least every 60 s: the server closes connections silent for 90 s. A PingInterval above 60 s is a *cexy.ConfigError from NewWebSocket / Client.WebSocket.

Live balances
ws, _ := c.WebSocket(cexy.WSOptions{}) // c has an API key
ws.Connect(ctx)
ws.Auth(ctx, sessionToken)
lb, err := ws.LiveBalances(ctx, cexy.LiveBalancesOptions{
	OnUpdate: func(asset string, b *cexy.Balance) { /* b == nil: removed */ },
})
usdt, ok := lb.Get("USDT")
_ = lb.Stale()     // true while a refetch is pending
_ = lb.LastError() // *cexy.AccountMismatchError: nothing merged

LiveBalances subscribes balances, takes a REST snapshot and applies newer balance.updated events (only when their sequence is greater than the one it holds; a total of 0 removes the row). It refetches by itself on a missed event, balances.resync, CONCURRENT_MODIFICATION, a reconnect or an account change, at most every MinSnapshotInterval (default 2 s; cexy.NoMinimum for none, since 0 selects the default), and never because a balance's own sequence skipped values. At the start and after every account change it checks that the REST key's account (Account.ID) is the WebSocket's authenticated user: otherwise nothing is merged. With your own Snapshot, also pass its owner (OwnerID or AccountID); without one, LiveBalances returns a *ConfigError.

Security

  • API keys cannot withdraw or transfer funds, whatever their scopes.
  • Use a read-only key unless you need to trade, and restrict keys to your IPs (allowed_ips).
  • Credentials are sent only on private endpoints and never in URLs: the key id and a signature (X-API-Key, X-API-Timestamp, X-API-Nonce, X-API-Signature). The secret itself is never sent.
  • The SDK never follows HTTP redirects, so credentials and orders are never re-sent to another URL. A 3xx response becomes an *APIError with code UNEXPECTED_REDIRECT (errors.Is(err, cexy.ErrUnexpectedRedirect)); it is not retried. The SDK uses its own copy of Options.HTTPClient and leaves yours unchanged.
  • Only https:// base URLs and wss:// WebSocket URLs are accepted. AllowInsecure permits http:// / ws:// solely for localhost, 127.0.0.1 or ::1 (local test servers).
  • The SDK redacts the secret from fmt output (%v, %+v, %#v), log/slog and error messages, including anything the server echoes back in APIError.Details and Fields: nested values and object keys too.
  • Keep keys in environment variables or a secret manager, not in code.

Report vulnerabilities as described in SECURITY.md.

Trading risk

  • Orders are real and irreversible once filled. Test your code with a read-only key and small amounts first, and add your own limits (maximum order size, allowed markets) before automating trades.
  • Retries and the client_order_id lookup are designed to avoid duplicate orders, but when a failure is ambiguous and even the lookup fails you get *OrderStateUnknownError: check the order before placing it again.
  • Markets move between reading data and placing an order; prices and balances you read may be stale.
  • This SDK is provided under the MIT licence, without warranty. Nothing in it is investment advice.

For tool builders

cexy.Operations() returns the table of the 40 operations (method, path, auth and scope). The package also exports every model type, the error types, the Authenticator interface (HMAC signing will plug in here) and Options.UserAgentSuffix to identify your tool.

Development

pip install pyyaml
python3 tools/generate.py          # regenerate models_gen.go and operations_gen.go from ../cexy-api-spec
python3 tools/generate.py --check  # CI: the generated files match the spec
go vet ./... && go test -race ./...
CEXY_LIVE_TESTS=1 go test -run TestLive ./...   # optional: anonymous GETs against api.cexy.io

Tests read the shared conformance cases from a cexy-api-spec checkout next to this repo (override with CEXY_API_SPEC; CEXY_REQUIRE_SPEC=1 fails instead of skipping when it is missing).

License

MIT, see LICENSE.

Documentation

Overview

Package cexy is the Go client for the CEXY.io REST and WebSocket API.

Public market data needs no credentials:

c, err := cexy.New(cexy.Options{})
markets, err := c.Markets.List(ctx)

Account, wallet reads and trading need an API key:

c, err := cexy.New(cexy.Options{APIKey: key, APISecret: secret})
balances, err := c.Account.Balances(ctx)

Amounts are decimal strings (Amount), never floats. API errors are *APIError values; match their category with errors.Is (for example ErrRateLimited) and branch on APIError.Code, never on the message.

API keys can never withdraw or transfer funds, and this package has no such methods.

Example
package main

import (
	"context"
	"fmt"
	"log"

	cexy "github.com/cexyio/cexy-go"
)

func main() {
	ctx := context.Background()
	c, err := cexy.New(cexy.Options{})
	if err != nil {
		log.Fatal(err)
	}
	markets, err := c.Markets.List(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, m := range markets {
		fmt.Println(m.Symbol)
	}
}

Index

Examples

Constants

View Source
const (
	MaxBatchOrders  = 20 // orders in one PlaceOrders call
	MaxCancelOrders = 50 // entries in one CancelOrders call
)

Batch limits.

View Source
const (
	DefaultRPMAnonymous = 100
	DefaultRPMWithKey   = 300
)

Default client-side rate limits. The server allows about 120 requests a minute per IP without credentials and 600 a minute per API key; these keep a margin.

View Source
const (
	OpCandles    = OpFuturesCandles
	OpFills      = OpFuturesFills
	OpFunding    = OpFuturesFunding
	OpMarket     = OpFuturesMarket
	OpMarkets    = OpFuturesMarkets
	OpOpenOrders = OpFuturesOpenOrders
	OpOrderbook  = OpFuturesOrderbook
	OpPositions  = OpFuturesPositions
	OpTrades     = OpFuturesTrades
)

Deprecated: the futures operation ids now start with futures_; use the OpFutures* constants.

View Source
const (
	CancelStoppedDone       = "done"
	CancelStoppedMaxRounds  = "max_rounds"
	CancelStoppedTimeBudget = "time_budget"
)

Reasons CancelAllUntilDone stopped.

View Source
const (
	// FuturesMidsChannel: every futures coin's mid price (event futures.mids, data FuturesMids).
	FuturesMidsChannel = "futures.mids"
	// FuturesStatusChannel: the server's futures market-data connection going live or degraded
	// (event futures.status, data FuturesStatus). Nothing is sent on subscribe.
	FuturesStatusChannel = "futures.status"
	// FuturesAccountChannel: the account's futures positions and open orders, in full on
	// subscribe and on change (events futures.positions and futures.orders). Private.
	FuturesAccountChannel = "futures.account"
)

Futures WebSocket channels (conformance/ws/futures.json). Public: FuturesMidsChannel, FuturesOrderBookChannel, FuturesTradesChannel, FuturesCandlesChannel, FuturesStatusChannel. Private: FuturesAccountChannel (held until Auth or AuthKey succeeds).

Public futures channels send nothing on subscribe: seed from REST (Client.Futures). Books, mids, positions and orders frames are full replacements; trades and candles are not replayed. Public futures channels are not gap-tracked. A refused futures subscribe (RATE_LIMITED, NOT_FOUND, VALIDATION_FAILED, SERVICE_UNAVAILABLE) is returned by Subscribe and not retried: WebSocket error frames carry no retry hint, so back off yourself (the server means 60 s).

View Source
const DefaultBaseURL = "https://api.cexy.io"

DefaultBaseURL is the production API.

View Source
const DefaultMaxBusyRetries = 3

DefaultMaxBusyRetries is how many times in a row AllFills and AllFunding ask again for a page while the futures provider is busy (see WithMaxBusyRetries).

View Source
const DefaultWebSocketURL = "wss://api.cexy.io/api/v1/ws"

DefaultWebSocketURL is the production WebSocket endpoint.

View Source
const MaxClockOffset = time.Hour

MaxClockOffset is the furthest the client clock may be corrected after SIGNATURE_EXPIRED.

View Source
const MaxServerWait = 120 * time.Second

MaxServerWait is the longest the SDK waits because of a server hint (Retry-After, details.retry_after_seconds, X-RateLimit-Reset). A longer hint is not waited: the call fails at once with the rate-limit error, whose RetryAfter still holds the server's value, and the client-side rate limiter blocks for at most this long.

View Source
const NoMinimum time.Duration = -1

NoMinimum, as LiveBalancesOptions.MinSnapshotInterval, disables the minimum time between snapshots (the other SDKs spell this 0).

View Source
const NoReorderWindow time.Duration = -1

NoReorderWindow, as WSOptions.ReorderWindow, reports a sequence gap at once instead of waiting for a swapped frame (0 selects the default).

View Source
const SigningScheme = "CEXY-HMAC-SHA256-v1"

SigningScheme is the request-signing scheme: the default (Options.Auth "hmac"). The API refuses the old secret header with SIGNATURE_REQUIRED.

View Source
const SpecVersion = "1.0.0"

SpecVersion is the info.version of the openapi.sdk.json this SDK was generated from.

View Source
const SupportedProtocolVersion = 1

SupportedProtocolVersion is the WebSocket protocol version this SDK was written for.

View Source
const UserAgent = "cexy-go/" + Version

UserAgent is the default User-Agent product token.

View Source
const Version = "0.1.0-dev.16"

Version is the SDK version (a test keeps it in step with CHANGELOG.md).

View Source
const WSBookDepth = 50

WSBookDepth is how many levels per side the WebSocket book carries. REST levels deeper than this are never used.

Variables

View Source
var (
	ErrValidation          = errors.New("cexy: validation failed")            // 400
	ErrAuthentication      = errors.New("cexy: authentication failed")        // 401
	ErrForbidden           = errors.New("cexy: forbidden")                    // 403 (and 451)
	ErrJurisdictionBlocked = errors.New("cexy: blocked in this jurisdiction") // 451 JURISDICTION_BLOCKED
	ErrNotFound            = errors.New("cexy: not found")                    // 404
	ErrConflict            = errors.New("cexy: conflict")                     // 409
	ErrDeadManNotArmed     = errors.New("cexy: dead-man switch not armed")    // 409 DEAD_MAN_NOT_ARMED
	ErrUnprocessable       = errors.New("cexy: refused by a business rule")   // 422
	ErrRateLimited         = errors.New("cexy: rate limited")                 // 429
	ErrServer              = errors.New("cexy: server error")                 // 5xx
	ErrUnexpectedRedirect  = errors.New("cexy: unexpected redirect")          // 3xx (never followed)
)

Error categories. An *APIError matches at most one of them with errors.Is, except that ErrJurisdictionBlocked also matches ErrForbidden and ErrDeadManNotArmed also matches ErrConflict. An error with a code this SDK does not know matches none of them: check APIError.Code instead.

View Source
var ErrBadResponse = errors.New("cexy: unusable response")

ErrBadResponse matches an error for a 2xx answer the SDK could not use: not JSON, without "data", undecodable, or (for a batch) results that do not match the request. The server acted on such a request.

View Source
var FuturesCandleIntervals = []string{"1m", "5m", "15m", "1h", "4h", "1d"}

FuturesCandleIntervals are the intervals FuturesCandlesChannel accepts.

View Source
var PrivateChannels = map[string]bool{"orders": true, "balances": true, "deposits": true, "withdrawals": true, "account": true,
	FuturesAccountChannel: true}

PrivateChannels need Auth with a session access token, or AuthKey.

Functions

func FuturesCandlesChannel

func FuturesCandlesChannel(coin, interval string) (string, error)

FuturesCandlesChannel returns "futures.candles:{coin}:{interval}" (event futures.candle.update, data FuturesCandleUpdate). interval is one of FuturesCandleIntervals.

func FuturesOrderBookChannel

func FuturesOrderBookChannel(coin string) (string, error)

FuturesOrderBookChannel returns "futures.orderbook:{coin}" (event futures.orderbook.update, data FuturesBookUpdate). The coin is sent exactly as given: it is case-sensitive ("BTC", "kPEPE").

func FuturesTradesChannel

func FuturesTradesChannel(coin string) (string, error)

FuturesTradesChannel returns "futures.trades:{coin}" (event futures.trades.new, data FuturesTradesUpdate).

func IsLocalHost

func IsLocalHost(host string) bool

IsLocalHost reports whether host is a loopback name or address, the only hosts where plain-text transport may be allowed.

func NewClientOrderID

func NewClientOrderID() string

NewClientOrderID returns a new client order id (a random UUID), as PlaceOrder and PlaceOrders generate for an order without one. Create and save ids with it before a call when you must be able to reconcile after any failure.

func Operations

func Operations() map[OperationID]OperationInfo

Operations returns the SDK surface: the 55 operations with their method, path, auth and required key scope.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v, for optional fields: cexy.Ptr(cexy.Amount("0.5")).

Types

type APIError

type APIError struct {
	// HTTP status; 0 for an error made by the SDK itself (CodePagingStalled).
	Status int
	// Machine-readable code. A code missing from errors.yaml is passed through unchanged;
	// a response without the envelope (a proxy error page) gets "HTTP_<status>".
	Code ErrorCode
	// Human-readable, may change between releases. Credentials are redacted from it.
	Message string
	// Structured context: string, int64 or bool values.
	Details map[string]any
	// Per-field validation messages (400).
	Fields map[string]string
	// Quote it in support requests. Empty when the server sent none.
	RequestID string
	// Whether an identical retry could succeed.
	Retryable bool
	// How long the server asked to wait (Retry-After or details.retry_after_seconds); 0 if
	// it gave no hint.
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

APIError is an error response from the API (the {"error": {...}} envelope).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether the error belongs to category target (ErrNotFound, ErrRateLimited, ...).

func (*APIError) Known

func (e *APIError) Known() bool

Known reports whether Code is listed in errors.yaml.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the error behind an SDK-made error: for CodePagingStalled after busy 503 answers, the last 503 (its Details["reason"] stays reachable). Nil otherwise.

type APIKey

type APIKey struct {
	// Permitted source addresses. Empty means unrestricted.
	AllowedIPs []string `json:"allowed_ips"`
	// When it was created.
	CreatedAt time.Time `json:"created_at"`
	// When it stops working.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// Opaque key identifier, used to revoke it.
	ID string `json:"id"`
	// The public key id, sent as `X-API-Key`.
	KeyID string `json:"key_id"`
	// Human label.
	Label string `json:"label"`
	// When it was last used, if ever.
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// Its rate-limit tier: `default`, or `mm` for a market maker's key, which only the exchange sets.
	RateTier string `json:"rate_tier"`
	// Whether it has been revoked.
	Revoked bool `json:"revoked"`
	// Granted scopes.
	Scopes []APIScope `json:"scopes"`
}

APIKey: An existing key. Never carries the secret.

type APIKeyAuthenticator

type APIKeyAuthenticator struct {
	// contains filtered or unexported fields
}

APIKeyAuthenticator is the old scheme (Options.Auth "headers"): X-API-Key and X-API-Secret headers on every private request. The API is switching it off (SIGNATURE_REQUIRED); the default is request signing (HMACAuthenticator).

Its String, GoString and LogValue methods never reveal the secret.

func NewAPIKeyAuthenticator

func NewAPIKeyAuthenticator(apiKey, apiSecret string) (*APIKeyAuthenticator, error)

NewAPIKeyAuthenticator checks the pair and returns the authenticator.

func (*APIKeyAuthenticator) Authenticate

func (a *APIKeyAuthenticator) Authenticate(req *http.Request, _ []byte) error

Authenticate sets the two headers. Credentials never go into the URL.

func (APIKeyAuthenticator) GoString

func (a APIKeyAuthenticator) GoString() string

GoString keeps %#v from printing the fields.

func (APIKeyAuthenticator) KeyHint

func (a APIKeyAuthenticator) KeyHint() string

KeyHint is a non-secret hint for logs: the first characters of the key id.

func (*APIKeyAuthenticator) Kind

func (a *APIKeyAuthenticator) Kind() string

Kind returns "api-key".

func (APIKeyAuthenticator) LogValue

func (a APIKeyAuthenticator) LogValue() slog.Value

LogValue keeps log/slog from printing the fields.

func (*APIKeyAuthenticator) Redact

func (a *APIKeyAuthenticator) Redact(text string) string

Redact replaces the secret and the key id in text.

func (APIKeyAuthenticator) String

func (a APIKeyAuthenticator) String() string

String never reveals the secret. Value receivers make both APIKeyAuthenticator and *APIKeyAuthenticator redact in fmt and log/slog.

type APIScope

type APIScope string

APIScope: Scope attached to an API key.

Scopes narrow what an API key may do. They apply to API keys only: a signed-in session carries none and is not limited by them.

The type is open: values added to the API later decode without error.

const (
	APIScopeRead  APIScope = "read"
	APIScopeTrade APIScope = "trade"
)

type AccountId

type AccountId struct {
	// Account id: the same hex as the realtime `authenticated` reply's `user_id`.
	UserID string `json:"user_id"`
}

AccountId: The id of the account a credential belongs to, and nothing else.

type AccountMismatchError

type AccountMismatchError struct {
	WebSocketUserID string
	SnapshotUserID  string
}

AccountMismatchError: the snapshot source belongs to another account than the WebSocket session.

func (*AccountMismatchError) Code

func (e *AccountMismatchError) Code() string

Code returns "ACCOUNT_MISMATCH" (the same code as the other SDKs).

func (*AccountMismatchError) Error

func (e *AccountMismatchError) Error() string

type AccountService

type AccountService struct {
	// contains filtered or unexported fields
}

AccountService: balances, ledger, notifications, sub-accounts and API keys.

func (*AccountService) APIKeys

func (s *AccountService) APIKeys(ctx context.Context, opts ...CallOption) ([]APIKey, error)

APIKeys returns your API keys (metadata only; secrets are never returned).

func (*AccountService) AllLedger

func (s *AccountService) AllLedger(ctx context.Context, params *GetLedgerParams, opts ...IterOption) iter.Seq2[LedgerEntry, error]

AllLedger iterates over every ledger entry.

func (*AccountService) AllNotifications

func (s *AccountService) AllNotifications(ctx context.Context, params *ListNotificationsParams, opts ...IterOption) iter.Seq2[Notification, error]

AllNotifications iterates over every notification.

func (*AccountService) Balance

func (s *AccountService) Balance(ctx context.Context, asset string, opts ...CallOption) (Balance, error)

Balance returns the balance of one asset. See Balances for HeldIncoming.

func (*AccountService) Balances

func (s *AccountService) Balances(ctx context.Context, opts ...CallOption) ([]Balance, error)

Balances returns every balance.

Balance.HeldIncoming lists incoming internal transfers still held. Their sum is ALREADY INCLUDED in Locked: never add them to Locked or Total again. At most 100 entries, soonest AvailableAt first (millisecond precision), with no sender identity. An entry disappears once the transfer is released (its amount moves to Available) or cancelled by the exchange. HeldIncoming is never nil: a server that omits the field decodes as an empty slice.

func (*AccountService) ID

func (s *AccountService) ID(ctx context.Context, opts ...CallOption) (string, error)

ID returns the id of the account this API key belongs to (the same hex as the WebSocket's authenticated user id). WebSocket.LiveBalances uses it to check that REST snapshots and WebSocket events belong to the same account.

func (*AccountService) Ledger

func (s *AccountService) Ledger(ctx context.Context, params *GetLedgerParams, opts ...CallOption) (*Page[LedgerEntry], error)

Ledger returns one page of ledger entries.

func (*AccountService) Notifications

func (s *AccountService) Notifications(ctx context.Context, params *ListNotificationsParams, opts ...CallOption) (*Page[Notification], error)

Notifications returns one page of notifications.

func (*AccountService) SubAccountBalances

func (s *AccountService) SubAccountBalances(ctx context.Context, id string, opts ...CallOption) ([]Balance, error)

SubAccountBalances returns a sub-account's balances, read by its PARENT account: the same shape as Balances (zero balances omitted), including HeldIncoming, whose sum is already inside Locked; HeldIncoming is never nil. The server currently returns them ordered by asset symbol; don't rely on the order. An id that is not one of the caller's sub-accounts (or a call made with the sub-account's own key) returns an *APIError matching ErrNotFound, and it is not retried; a sub-account's own key reads its balances with Balances. A malformed id gets 400 (ErrValidation); a key without the read scope gets 403 FORBIDDEN (ErrForbidden). id must be non-empty and not "." or ".." (a *ConfigError before any request); it is sent as one URL path segment.

func (*AccountService) SubAccounts

func (s *AccountService) SubAccounts(ctx context.Context, opts ...CallOption) ([]SubAccount, error)

SubAccounts returns the sub-accounts.

type Amount

type Amount string

Amount is an exact decimal amount as a string, such as "0.00150000". The API never uses JSON numbers for money. Do arithmetic with a decimal package (for example github.com/shopspring/decimal or math/big), never with float64.

func (Amount) String

func (a Amount) String() string

String returns the decimal text.

func (Amount) Valid

func (a Amount) Valid() bool

Valid reports whether a is a plain decimal string: digits, an optional "." and sign.

type Asset

type Asset struct {
	// Accounting precision: the decimal places the exchange records internally.
	//
	// Use this for arithmetic. For rendering, use `display_decimals`.
	Decimals int `json:"decimals"`
	// Decimal places to show in a user interface.
	//
	// Always less than or equal to `decimals`. Rounding for display is presentation only and must never be fed back into a request.
	DisplayDecimals int `json:"display_decimals"`
	// Identifier for a client-bundled icon, when no logo URL is set.
	IconKey *string `json:"icon_key,omitempty"`
	// Logo URL, when the operator has configured one.
	LogoURL *string `json:"logo_url,omitempty"`
	// How old this asset's price may be before it is refused, in seconds.
	//
	// The global default unless an operator set an override for this asset. Exposed beside the flag because the flag alone cannot explain itself: an asset that is not stale after a week and one that is not stale after an hour look identical without it.
	MaxPriceAgeSecs int64 `json:"max_price_age_secs"`
	// Display name.
	Name string `json:"name"`
	// Networks this asset can be deposited to or withdrawn from.
	Networks []AssetNetwork `json:"networks"`
	// Operator note, e.g. why deposits are paused.
	Notice *string `json:"notice,omitempty"`
	// Uppercase ticker.
	Symbol string `json:"symbol"`
	// Whether the asset may appear in markets.
	TradingEnabled bool   `json:"trading_enabled"`
	UsdPrice       Amount `json:"usd_price"`
	// Whether that price is too old to compute with.
	//
	// When true, the exchange refuses to derive anything from it: daily limits and auto-approval fail closed rather than guess, and a stored USD value is recorded as absent rather than as a confident wrong figure.
	UsdPriceStale bool `json:"usd_price_stale"`
	// When that price was last set.
	//
	// Exposed because the price is typed in by an operator and refreshed by nothing — there is no feed. Without the timestamp a caller cannot tell a price set an hour ago from one set last month, and both look equally authoritative.
	UsdPriceUpdatedAt time.Time `json:"usd_price_updated_at"`
	// Project website.
	WebsiteURL *string `json:"website_url,omitempty"`
}

Asset: A tradable asset.

type AssetNetwork

type AssetNetwork struct {
	// Contract address or chain asset id, for a token.
	ContractAddress *string `json:"contract_address,omitempty"`
	// Confirmations before a deposit is credited.
	DepositConfirmations int `json:"deposit_confirmations"`
	// Whether deposits are accepted.
	DepositEnabled bool              `json:"deposit_enabled"`
	Maintenance    *MaintenanceState `json:"maintenance,omitempty"`
	MaxWithdrawal  *Amount           `json:"max_withdrawal,omitempty"`
	// What to call the memo field in a UI.
	MemoLabel *string `json:"memo_label,omitempty"`
	// Whether a memo is mandatory.
	MemoRequired bool `json:"memo_required"`
	// Whether the network uses a memo / destination tag.
	MemoSupported bool   `json:"memo_supported"`
	MinDeposit    Amount `json:"min_deposit"`
	MinWithdrawal Amount `json:"min_withdrawal"`
	// Network code.
	Network string `json:"network"`
	// Network display name.
	NetworkName string `json:"network_name"`
	// Operator note.
	Notice *string `json:"notice,omitempty"`
	// How the asset exists on this chain.
	TokenKind string `json:"token_kind"`
	// Decimal places a withdrawal amount is truncated to.
	WithdrawalDecimals int `json:"withdrawal_decimals"`
	// Whether withdrawals are accepted.
	WithdrawalEnabled bool   `json:"withdrawal_enabled"`
	WithdrawalFee     Amount `json:"withdrawal_fee"`
	// Asset the withdrawal fee is charged in.
	WithdrawalFeeAsset string `json:"withdrawal_fee_asset"`
}

AssetNetwork: An asset's policy on one network.

type AssetsService

type AssetsService struct {
	// contains filtered or unexported fields
}

AssetsService: the asset catalogue.

func (*AssetsService) Get

func (s *AssetsService) Get(ctx context.Context, symbol string, opts ...CallOption) (Asset, error)

Get returns one asset.

func (*AssetsService) List

func (s *AssetsService) List(ctx context.Context, opts ...CallOption) ([]Asset, error)

List returns every asset.

type AuthChange

type AuthChange struct {
	Reason AuthChangeReason
	// The user of the last successful auth on this connection, or empty.
	PreviousUserID string
	// The new user (AuthUserChanged), otherwise empty: the connection is signed out.
	UserID string
	// The server's error code (AuthFailed), or the raw signed_out reason (AuthSignedOut).
	Code string
	// Private channels the server dropped. They are re-subscribed automatically: at once for
	// AuthUserChanged, after the next successful Auth otherwise (then OnResync(ResyncReauth)).
	Dropped []string
}

AuthChange is passed to OnAuthChanged.

type AuthChangeReason

type AuthChangeReason string

AuthChangeReason says why the server ended the connection's private subscriptions.

const (
	// AuthUserChanged: Auth succeeded as a different user.
	AuthUserChanged AuthChangeReason = "user_changed"
	// AuthFailed: an Auth failed; the server signs the connection out on any auth error.
	AuthFailed AuthChangeReason = "auth_failed"
	// AuthSessionRevoked: this connection's own session was revoked (session.revoked with
	// current true, or the signed_out frame with reason "revoked").
	AuthSessionRevoked AuthChangeReason = "session_revoked"
	// AuthTokenExpired: the signed_out frame with reason "expired". Re-send Auth on every token
	// refresh to avoid it.
	AuthTokenExpired AuthChangeReason = "token_expired"
	// AuthKeyRevoked: the API key was revoked or deleted (key authentication).
	AuthKeyRevoked AuthChangeReason = "key_revoked"
	// AuthKeyExpired: the API key expired (key authentication).
	AuthKeyExpired AuthChangeReason = "key_expired"
	// AuthSignedOut: a server sign-out with a reason this SDK does not know (raw value in Code).
	// The set of reasons may grow.
	AuthSignedOut AuthChangeReason = "signed_out"
)

type AuthResult

type AuthResult struct {
	// From the authenticated acknowledgement; empty when queued.
	UserID string
	// How the connection is authenticated ("api_key" or "session"), when the server says.
	Auth string
	// True when not connected: the token is kept and sent (and acknowledged) on connect.
	Queued bool
}

AuthResult is what Auth did.

type Authenticator

type Authenticator interface {
	// Kind is a short, non-secret description such as "api-key".
	Kind() string
	Authenticate(req *http.Request, body []byte) error
	// Redact removes any secret material from text (used on error messages).
	Redact(text string) string
}

Authenticator adds credentials to requests for operations that need an API key.

Authenticate is called once per attempt (retries included), so a future signing scheme can put a fresh timestamp and nonce on each attempt. It is never called for public operations. body is the exact JSON that will be sent, or nil.

type Balance

type Balance struct {
	// Asset symbol.
	Asset     string `json:"asset"`
	Available Amount `json:"available"`
	// Internal transfers to this account still held, soonest released first; empty when none. Their sum is part of `locked`. Shows at most 100.
	HeldIncoming []HeldIncoming `json:"held_incoming"`
	Locked       Amount         `json:"locked"`
	Pending      Amount         `json:"pending"`
	// This balance's sequence: it rises with every change to it, and `balance.updated` carries the same number as `data.sequence`. Apply an event only if its sequence is greater than the one this snapshot holds. 0 for a balance never touched.
	Sequence int64  `json:"sequence"`
	Total    Amount `json:"total"`
}

Balance: A balance in one asset.

type BatchCancelResult

type BatchCancelResult struct {
	Results   []CancelEntryOutcome
	Cancelled int
	Failed    int
	Unknown   int
}

BatchCancelResult is what CancelOrders did. Cancelled counts entries now cancelled (recovered ones whose status is cancelled included), Failed the rest whose state is known, Unknown those whose state could not be read.

type BatchOrder

type BatchOrder struct {
	// How many were refused.
	Failed int `json:"failed"`
	// How many were accepted.
	Placed int `json:"placed"`
	// One per order sent, in the same order.
	Results []BatchOrderResult `json:"results"`
}

BatchOrder: What a batch did: one result per order, in the order sent.

type BatchOrderItem

type BatchOrderItem struct {
	// Your own identifier, unique per account. Required: a retry of the batch is answered `ALREADY_EXISTS` for every order it already placed, so nothing is placed twice.
	ClientOrderID    string            `json:"client_order_id"`
	Price            *Amount           `json:"price,omitempty"`
	Quantity         *Amount           `json:"quantity,omitempty"`
	QuoteQuantity    *Amount           `json:"quote_quantity,omitempty"`
	Side             OrderSide         `json:"side"`
	StopPrice        *Amount           `json:"stop_price,omitempty"`
	TimeInForce      *TimeInForce      `json:"time_in_force,omitempty"`
	TriggerDirection *TriggerDirection `json:"trigger_direction,omitempty"`
	Type             OrderType         `json:"type"`
}

BatchOrderItem: One order of a batch: an order as for `POST /trading/orders`, without the symbol, and with `client_order_id` required.

type BatchOrderOutcome

type BatchOrderOutcome struct {
	Index         int
	ClientOrderID string
	Outcome       BatchOutcome
	OrderID       string
	Status        OrderStatus
	Order         *Order
	Fills         []Fill
	Error         *ErrorBody
}

BatchOrderOutcome is one order of PlaceOrders, in request order.

A recovered order's Status may be OrderStatusRejected: the server refused it for funds, its client_order_id is spent, and it must not be placed again under that id. Order is set for a placed order, and for a recovered one only when the SDK had to look it up.

type BatchOrderRequest

type BatchOrderRequest struct {
	// The orders, 1 to 20, placed one after another in this order.
	Orders []BatchOrderItem `json:"orders"`
	// The market every order is placed in.
	Symbol string `json:"symbol"`
}

BatchOrderRequest: Places up to 20 orders in one market (Phase 0 B2).

type BatchOrderResult

type BatchOrderResult struct {
	// Its `client_order_id`, as sent.
	ClientOrderID string     `json:"client_order_id"`
	Error         *ErrorBody `json:"error,omitempty"`
	// Fills produced on entry, oldest first; empty when refused.
	Fills []Fill `json:"fills"`
	// Its position in the request, from 0.
	Index int    `json:"index"`
	Order *Order `json:"order,omitempty"`
}

BatchOrderResult: One order's outcome in a batch: exactly one of `order` and `error` is set.

type BatchOutcome

type BatchOutcome string

BatchOutcome is what became of one order or entry of a batch call.

const (
	// OutcomePlaced: PlaceOrders placed it now; Order and Fills are set.
	OutcomePlaced BatchOutcome = "placed"
	// OutcomeCancelled: CancelOrders cancelled it now; Order is the cancelled order.
	OutcomeCancelled BatchOutcome = "cancelled"
	// OutcomeFailed: refused; Error says why. ALREADY_EXISTS here means the client_order_id was
	// used before this call.
	OutcomeFailed BatchOutcome = "failed"
	// OutcomeRecovered: an earlier attempt of this call acted on it and its answer was lost, so
	// the retry was refused (ALREADY_EXISTS for a placement, INVALID_STATE for a cancel).
	// OrderID and Status say what became of it.
	OutcomeRecovered BatchOutcome = "recovered"
	// OutcomeUnknown: as recovered, but its state could not be read. A placement was not placed
	// again: look it up with Trading.OrderByClientID.
	OutcomeUnknown BatchOutcome = "unknown"
)

type BatchPlaceError

type BatchPlaceError struct {
	ClientOrderIDs []string
	MaybePlaced    bool
	Err            error
}

BatchPlaceError is returned by Trading.PlaceOrders when it fails after building its request body. ClientOrderIDs are the ids of every order in the body, in request order, the generated ones included: look them up with Trading.OrderByClientID before placing any of them again. MaybePlaced is false only when every attempt was a definite refusal (429, 501, 503, another 4xx, or a connection that was never made); then nothing was placed. Err is the cause: errors.As and errors.Is see through to it (*APIError, *ConnectionError, context.Canceled, ErrBadResponse).

func (*BatchPlaceError) Error

func (e *BatchPlaceError) Error() string

func (*BatchPlaceError) Unwrap

func (e *BatchPlaceError) Unwrap() error

type BatchPlaceResult

type BatchPlaceResult struct {
	Results []BatchOrderOutcome
	Placed  int
	Failed  int
	Unknown int
}

BatchPlaceResult is what PlaceOrders did. The counts are computed from Results, never copied from the server (whose counts describe only the last attempt): Placed counts placed and recovered orders that were not rejected, Failed the refused ones (a recovered rejected one included), Unknown those whose state could not be read.

type BookLevel

type BookLevel struct {
	Price, Quantity Amount
}

BookLevel is one [price, quantity] level of an order book.

func Levels

func Levels(raw [][]Amount) []BookLevel

Levels converts the raw [price, quantity] pairs of an order book side. Malformed entries (fewer than two values) are skipped.

type BookSnapshot

type BookSnapshot struct {
	Symbol     string
	Bids, Asks []BookLevel
	// Sequence of the last applied snapshot or update on the current connection; valid when
	// HasSequence.
	Sequence    int64
	HasSequence bool
	// True after a sequence gap, until the next in-order update.
	Stale bool
	// False while waiting for a snapshot (after a reconnect or a resync).
	Synced bool
}

BookSnapshot is a copy of a LiveOrderBook's state. Levels are best first, at most 50 a side.

func (BookSnapshot) Best

func (b BookSnapshot) Best() (bid BookLevel, bidOK bool, ask BookLevel, askOK bool)

Best returns the best bid and ask; ok is false for an empty side.

type CallOption

type CallOption func(*callOptions)

CallOption changes one call: WithTimeout, WithMaxRetries, WithIdempotencyKey.

func WithIdempotencyKey

func WithIdempotencyKey(key string) CallOption

WithIdempotencyKey sets the Idempotency-Key of a pool join or exit (generated when absent), the only endpoints that honour it; set it yourself to make a retry across process restarts safe there. It is ignored on every other call: no Idempotency-Key is sent on orders or cancels, whose safety comes from client_order_id (see Trading.PlaceOrder).

func WithMaxRetries

func WithMaxRetries(n int) CallOption

WithMaxRetries overrides the client's MaxRetries for this call (0 disables retries).

func WithTimeout

func WithTimeout(d time.Duration) CallOption

WithTimeout overrides the client's per-attempt timeout for this call.

type CancelAllAfter

type CancelAllAfter struct {
	// Whether a deadline is now armed for this scope. `false` after a disarm.
	Armed bool `json:"armed"`
	// When the orders are cancelled unless armed again. `null` when disarmed.
	Deadline *time.Time `json:"deadline,omitempty"`
	// The server's time after the deadline was stored, to measure the deadline against.
	ServerTime time.Time `json:"server_time"`
	// The market it covers, or `null` for every market.
	Symbol *string `json:"symbol,omitempty"`
	// The timeout asked for, in milliseconds.
	TimeoutMs int64 `json:"timeout_ms"`
}

CancelAllAfter: The dead-man switch, as just set.

type CancelAllAfterRequest

type CancelAllAfterRequest struct {
	// One market's orders only. Omitted or `null`, the switch covers every market; an empty string is refused (400). A per-market switch and the all-markets switch are separate: each fires on its own.
	Symbol *string `json:"symbol,omitempty"`
	// Milliseconds from now after which the open orders in scope are cancelled, unless the switch is armed again first: from 5000 to 600000. `0` disarms.
	TimeoutMs int64 `json:"timeout_ms"`
}

CancelAllAfterRequest: Arms, re-arms or disarms the dead-man switch.

type CancelAllOptions

type CancelAllOptions struct {
	Symbol     string        // one market, such as "BTC/USDT"
	AllMarkets bool          // every market
	MaxRounds  int           // calls at most; default 20
	TimeBudget time.Duration // stop before a wait would reach this; default 120 s
}

CancelAllOptions selects the target of CancelAllUntilDone and bounds its loop. Exactly one of Symbol and AllMarkets must be set, so an account-wide cancel is always explicit.

type CancelAllRequest

type CancelAllRequest struct {
	// Limit the cancellation to one market. Omitted or `null`, every market's open orders are cancelled.
	Symbol *string `json:"symbol,omitempty"`
}

CancelAllRequest: Cancels every open order, optionally within one market.

type CancelAllResult

type CancelAllResult struct {
	// Orders that closed on their own (filled, rejected, cancelled elsewhere) before this call reached them. Nothing was done to them, and they are not failures.
	AlreadyClosed []string `json:"already_closed"`
	// Orders cancelled.
	Cancelled []string `json:"cancelled"`
	// Orders that could not be cancelled in this call. Check `failures` for why, then refresh or call again.
	Failed []string `json:"failed"`
	// Why each order in `failed` could not be cancelled.
	Failures []CancelFailure `json:"failures"`
	// More open orders exist than one call handles (500). Call again.
	HasMore bool `json:"has_more"`
}

CancelAllResult: What a bulk cancellation achieved.

Every order the call handled is in exactly one of `cancelled`, `already_closed` and `failed`.

type CancelAllSummary

type CancelAllSummary struct {
	Cancelled     []string
	AlreadyClosed []string
	Failed        []string        // still failed after the last round
	Failures      []CancelFailure // the latest reason for each order in Failed
	HasMore       bool            // the last successful round's has_more
	Rounds        int             // HTTP requests sent (one per round)
	Stopped       string          // CancelStoppedDone, CancelStoppedMaxRounds or CancelStoppedTimeBudget
	LastErrorCode string          // set when the last round was a retryable error (e.g. RATE_LIMITED)
}

CancelAllSummary merges the rounds of CancelAllUntilDone by order id; an order's latest state wins (an order that failed in one round and was cancelled in a later one is only in Cancelled).

type CancelBatch

type CancelBatch struct {
	// How many were cancelled.
	Cancelled int `json:"cancelled"`
	// How many were not.
	Failed int `json:"failed"`
	// One per entry sent, in the same order.
	Results []CancelBatchResult `json:"results"`
}

CancelBatch: What a batch cancel did: one result per entry, in the order sent.

type CancelBatchItem

type CancelBatchItem struct {
	// Your identifier for it.
	ClientOrderID *string `json:"client_order_id,omitempty"`
	// The order's id.
	OrderID *string `json:"order_id,omitempty"`
}

CancelBatchItem: One order to cancel: exactly one of `order_id` and `client_order_id`.

type CancelBatchRequest

type CancelBatchRequest struct {
	// The orders, 1 to 50, cancelled one after another in this order.
	Orders []CancelBatchItem `json:"orders"`
}

CancelBatchRequest: Cancels up to 50 orders, each named by its id or by your own (Phase 0 B2).

type CancelBatchResult

type CancelBatchResult struct {
	// The client order id, as sent.
	ClientOrderID *string    `json:"client_order_id,omitempty"`
	Error         *ErrorBody `json:"error,omitempty"`
	// Its position in the request, from 0.
	Index int    `json:"index"`
	Order *Order `json:"order,omitempty"`
	// The order id, as sent.
	OrderID *string `json:"order_id,omitempty"`
}

CancelBatchResult: One entry's outcome in a batch cancel: exactly one of `order` and `error` is set.

type CancelEntryOutcome

type CancelEntryOutcome struct {
	Index         int
	Outcome       BatchOutcome
	OrderID       string
	ClientOrderID string
	Status        OrderStatus
	Order         *Order
	Error         *ErrorBody
}

CancelEntryOutcome is one entry of CancelOrders, in request order. OrderID and ClientOrderID are as sent (OrderID is the order's id once it is known). A recovered entry's Status says cancelled or, for example, filled.

type CancelFailure

type CancelFailure struct {
	// The error code of the attempt, as in any error response: e.g. `MARKET_UNAVAILABLE` for an order whose market is restarting, or `CONCURRENT_MODIFICATION`.
	Code string `json:"code"`
	// Its message.
	Message string `json:"message"`
	// The order.
	OrderID string `json:"order_id"`
}

CancelFailure: Why one order could not be cancelled.

type Candle

type Candle struct {
	Close Amount `json:"close"`
	High  Amount `json:"high"`
	Low   Amount `json:"low"`
	Open  Amount `json:"open"`
	// Bucket start.
	OpenTime    time.Time `json:"open_time"`
	QuoteVolume Amount    `json:"quote_volume"`
	// Number of trades.
	TradeCount int64  `json:"trade_count"`
	Volume     Amount `json:"volume"`
}

Candle: An OHLCV bucket.

type CandleInterval

type CandleInterval string

CandleInterval: Candle/kline intervals for market data.

The type is open: values added to the API later decode without error.

const (
	CandleInterval1m  CandleInterval = "1m"
	CandleInterval5m  CandleInterval = "5m"
	CandleInterval15m CandleInterval = "15m"
	CandleInterval30m CandleInterval = "30m"
	CandleInterval1h  CandleInterval = "1h"
	CandleInterval4h  CandleInterval = "4h"
	CandleInterval1d  CandleInterval = "1d"
	CandleInterval1w  CandleInterval = "1w"
)

type CandlesParams deprecated

type CandlesParams = FuturesCandlesParams

Deprecated: use FuturesCandlesParams.

type Client

type Client struct {
	Markets  *MarketsService
	Assets   *AssetsService
	Networks *NetworksService
	Fees     *FeesService
	Pools    *PoolsService
	Account  *AccountService
	Exports  *ExportsService
	Wallet   *WalletService
	Trading  *TradingService
	Futures  *FuturesService
	// contains filtered or unexported fields
}

Client is the CEXY.io REST client. It is safe for concurrent use.

func New

func New(opts Options) (*Client, error)

New checks the options and returns a client. It sends nothing.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the API base URL.

func (*Client) Config

func (c *Client) Config(ctx context.Context, opts ...CallOption) (ExchangeConfig, error)

Config returns the public exchange configuration (maintenance state, page sizes, ...).

func (*Client) GoString

func (c *Client) GoString() string

GoString keeps %#v from printing the credentials.

func (*Client) HasCredentials

func (c *Client) HasCredentials() bool

HasCredentials reports whether private endpoints are available.

func (*Client) RateLimit

func (c *Client) RateLimit() (state RateLimitState, ok bool)

RateLimit returns the client-side rate limiter state; ok is false when it is disabled.

func (*Client) String

func (c *Client) String() string

func (*Client) Time

func (c *Client) Time(ctx context.Context, opts ...CallOption) (ServerTime, error)

Time returns the server clock. Compare it with yours to detect skew.

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent returns the User-Agent the client sends.

func (*Client) WebSocket

func (c *Client) WebSocket(opts WSOptions) (*WebSocket, error)

WebSocket returns a WebSocket client for the same deployment, wired to this client for order-book snapshots. An empty opts.URL is derived from BaseURL.

type CloseInfo

type CloseInfo struct {
	Code          int
	Reason        string
	WillReconnect bool
}

CloseInfo describes a closed connection.

type ConfigError

type ConfigError struct{ Msg string }

ConfigError is an invalid client configuration or call, detected before anything is sent.

func (*ConfigError) Error

func (e *ConfigError) Error() string

type ConnectionError

type ConnectionError struct {
	Method, Path string
	// True when the per-attempt timeout expired.
	Timeout bool
	Err     error
	// contains filtered or unexported fields
}

ConnectionError means the request produced no HTTP response (DNS, TLS, connection reset, or the per-attempt timeout). It is always retryable.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type Deposit

type Deposit struct {
	// Address that received it.
	Address string `json:"address"`
	Amount  Amount `json:"amount"`
	// Asset symbol.
	Asset string `json:"asset"`
	// Confirmations observed.
	Confirmations int `json:"confirmations"`
	// When it was credited.
	CreditedAt *time.Time `json:"credited_at,omitempty"`
	// Explorer link, when the network has one configured.
	ExplorerURL *string `json:"explorer_url,omitempty"`
	// When it was first observed.
	FirstSeenAt time.Time `json:"first_seen_at"`
	// Deposit id.
	ID string `json:"id"`
	// Memo, if any.
	Memo *string `json:"memo,omitempty"`
	// Network code.
	Network string `json:"network"`
	// Operator note, e.g. why it was reversed.
	Note *string `json:"note,omitempty"`
	// Position within the transaction. Distinguishes two outputs of one transaction.
	OutputIndex int `json:"output_index"`
	// Confirmations required to credit.
	RequiredConfirmations int           `json:"required_confirmations"`
	Status                DepositStatus `json:"status"`
	// Transaction hash.
	Txid string `json:"txid"`
}

Deposit: A deposit.

type DepositAddress

type DepositAddress struct {
	// The address to send to.
	Address string `json:"address"`
	// Asset symbol.
	Asset string `json:"asset"`
	// When the address was issued.
	CreatedAt time.Time `json:"created_at"`
	// Confirmations before the deposit is credited.
	DepositConfirmations int `json:"deposit_confirmations"`
	// Memo / destination tag. **Required when present** — a deposit without it may be unrecoverable.
	Memo *string `json:"memo,omitempty"`
	// What to call the memo field in a UI.
	MemoLabel  *string `json:"memo_label,omitempty"`
	MinDeposit Amount  `json:"min_deposit"`
	// Network code.
	Network string `json:"network"`
}

DepositAddress: A deposit address.

type DepositAddressParams

type DepositAddressParams struct {
	// Asset symbol.
	//
	// Required.
	Asset string
	// Network code.
	//
	// Required.
	Network string
}

DepositAddressParams holds the query parameters of deposit_address. Nil pointers are not sent.

type DepositID

type DepositID = string

DepositID: Unique identifier of a deposit.

An alias of string: its format is not checked, so a future format keeps working.

type DepositStatus

type DepositStatus string

DepositStatus: Lifecycle of an incoming blockchain deposit.

The type is open: values added to the API later decode without error.

const (
	DepositStatusDetected     DepositStatus = "detected"
	DepositStatusCredited     DepositStatus = "credited"
	DepositStatusReversed     DepositStatus = "reversed"
	DepositStatusOrphaned     DepositStatus = "orphaned"
	DepositStatusBelowMinimum DepositStatus = "below_minimum"
	DepositStatusUnderReview  DepositStatus = "under_review"
	DepositStatusInternal     DepositStatus = "internal"
)

type ErrorBody

type ErrorBody struct {
	Code ErrorCode `json:"code"`
	// Structured context, when available.
	Details map[string]any `json:"details,omitempty"`
	// Per-field validation messages, keyed by request field name.
	//
	// Present only on validation failures. Render each message beside its input.
	Fields map[string]string `json:"fields,omitempty"`
	// Human-readable description. May change between releases.
	Message string `json:"message"`
	// Correlates this response with server logs. Quote it in support requests.
	RequestID *string `json:"request_id,omitempty"`
	// Whether an identical retry could succeed.
	Retryable bool `json:"retryable"`
}

ErrorBody: The `error` object as it appears on the wire.

type ErrorCode

type ErrorCode string

ErrorCode is the machine-readable error.code of an API error. Branch on it, never on the message. The type is open: codes added to the API later arrive unchanged.

const (
	CodeValidationFailed       ErrorCode = "VALIDATION_FAILED"
	CodeMalformedRequest       ErrorCode = "MALFORMED_REQUEST"
	CodeInvalidCursor          ErrorCode = "INVALID_CURSOR"
	CodePrecisionExceeded      ErrorCode = "PRECISION_EXCEEDED"
	CodeBelowMinimum           ErrorCode = "BELOW_MINIMUM"
	CodeAboveMaximum           ErrorCode = "ABOVE_MAXIMUM"
	CodeInvalidAddress         ErrorCode = "INVALID_ADDRESS"
	CodeMemoRequired           ErrorCode = "MEMO_REQUIRED"
	CodeUnauthenticated        ErrorCode = "UNAUTHENTICATED"
	CodeInvalidCredentials     ErrorCode = "INVALID_CREDENTIALS"
	CodeTokenExpired           ErrorCode = "TOKEN_EXPIRED"
	CodeSessionRevoked         ErrorCode = "SESSION_REVOKED"
	CodeTwoFactorRequired      ErrorCode = "TWO_FACTOR_REQUIRED"
	CodeTwoFactorInvalid       ErrorCode = "TWO_FACTOR_INVALID"
	CodeFreshTwoFactorRequired ErrorCode = "FRESH_TWO_FACTOR_REQUIRED"
	CodeForbidden              ErrorCode = "FORBIDDEN"
	CodeAPIKeyNotAllowed       ErrorCode = "API_KEY_NOT_ALLOWED"
	CodeKeyNotSignable         ErrorCode = "KEY_NOT_SIGNABLE"
	CodeSignatureExpired       ErrorCode = "SIGNATURE_EXPIRED"
	CodeNonceReused            ErrorCode = "NONCE_REUSED"
	CodeSignatureRequired      ErrorCode = "SIGNATURE_REQUIRED"
	CodeFuturesRestricted      ErrorCode = "FUTURES_RESTRICTED"
	CodeAccountFrozen          ErrorCode = "ACCOUNT_FROZEN"
	CodeAccountOnHold          ErrorCode = "ACCOUNT_ON_HOLD"
	CodeEmailNotVerified       ErrorCode = "EMAIL_NOT_VERIFIED"
	CodeRegionBlocked          ErrorCode = "REGION_BLOCKED"
	CodeJurisdictionBlocked    ErrorCode = "JURISDICTION_BLOCKED"
	CodeNotFound               ErrorCode = "NOT_FOUND"
	CodeMethodNotAllowed       ErrorCode = "METHOD_NOT_ALLOWED"
	CodeAlreadyExists          ErrorCode = "ALREADY_EXISTS"
	CodeInvalidState           ErrorCode = "INVALID_STATE"
	CodeIdempotencyKeyConflict ErrorCode = "IDEMPOTENCY_KEY_CONFLICT"
	CodeWindowOpen             ErrorCode = "WINDOW_OPEN"
	CodeEvidenceContradicts    ErrorCode = "EVIDENCE_CONTRADICTS"
	CodeAmountMismatch         ErrorCode = "AMOUNT_MISMATCH"
	CodeConcurrentModification ErrorCode = "CONCURRENT_MODIFICATION"
	CodeDeadManNotArmed        ErrorCode = "DEAD_MAN_NOT_ARMED"
	CodeInsufficientFunds      ErrorCode = "INSUFFICIENT_FUNDS"
	CodeInsufficientFeeFunds   ErrorCode = "INSUFFICIENT_FEE_FUNDS"
	CodeMarketUnavailable      ErrorCode = "MARKET_UNAVAILABLE"
	CodeDepositDisabled        ErrorCode = "DEPOSIT_DISABLED"
	CodeWithdrawalDisabled     ErrorCode = "WITHDRAWAL_DISABLED"
	CodeSelfTradeBlocked       ErrorCode = "SELF_TRADE_BLOCKED"
	CodeLimitExceeded          ErrorCode = "LIMIT_EXCEEDED"
	CodePriceUnavailable       ErrorCode = "PRICE_UNAVAILABLE"
	CodeRateLimited            ErrorCode = "RATE_LIMITED"
	CodeInternal               ErrorCode = "INTERNAL"
	CodeServiceUnavailable     ErrorCode = "SERVICE_UNAVAILABLE"
	CodeUnderMaintenance       ErrorCode = "UNDER_MAINTENANCE"
	CodeEngineOverloaded       ErrorCode = "ENGINE_OVERLOADED"
)

Every error code the API is known to return (errors.yaml).

const CodePagingCursorRepeated ErrorCode = "PAGING_CURSOR_REPEATED"

CodePagingCursorRepeated is the code of the *APIError that AllFills and AllFunding yield after a page WITH rows handed back the cursor just sent: a server error, since paging on would repeat rows forever. Made by the SDK (Status 0), not retryable. Details["cursor"] is that cursor.

const CodePagingStalled ErrorCode = "PAGING_STALLED"

CodePagingStalled is the code of the *APIError that AllFills and AllFunding yield when the futures provider stays busy: an empty page handed back the cursor just sent, or a 503 with details.reason futures_data_unavailable, more times in a row than WithMaxBusyRetries allows (Unwrap is the last 503 in the second case). It is made by the SDK, not sent by the API (Status 0). It is retryable: the rows yielded so far are not the whole history; resume later from Details["cursor"] (a string) with Fills or Funding.

const CodeUnexpectedRedirect ErrorCode = "UNEXPECTED_REDIRECT"

CodeUnexpectedRedirect is the code of the *APIError for a 3xx response. The SDK never follows redirects, so that credentials and orders are never re-sent to another URL.

type Event

type Event struct {
	Type    string `json:"type"`
	Channel string `json:"channel"`
	// Per channel, +1 per update. Resets per connection and when the server restarts.
	Sequence  *int64          `json:"sequence,omitempty"`
	Timestamp string          `json:"timestamp,omitempty"`
	Data      json.RawMessage `json:"data"`
}

Event is a channel event such as ticker.update, orderbook.update or order.filled. Decode Data with Decode. Unknown event types are ignored (they may be added without notice).

func (Event) Decode

func (e Event) Decode(v any) error

Decode unmarshals Data into v (for example *OrderBookUpdate or *Order).

type ExchangeConfig

type ExchangeConfig struct {
	// Candle intervals the API serves.
	CandleIntervals []CandleInterval `json:"candle_intervals"`
	// Default page size for paginated endpoints.
	DefaultPageSize int `json:"default_page_size"`
	// Whether registration verifies the email address with an emailed code before the authenticator step. Lets a signup form show the right number of steps up front.
	EmailVerificationRequired bool `json:"email_verification_required"`
	// Feature flags a frontend may use to hide unavailable functionality.
	//
	// Presentation only. The backend enforces every rule independently.
	Features map[string]bool `json:"features"`
	// Message to show while in maintenance.
	MaintenanceMessage *string `json:"maintenance_message,omitempty"`
	// Whether the exchange is in maintenance mode.
	MaintenanceMode bool `json:"maintenance_mode"`
	// Maximum page size.
	MaxPageSize int `json:"max_page_size"`
	// Display name.
	Name          string        `json:"name"`
	PasswordRules PasswordRules `json:"password_rules"`
	// Whether new registrations are accepted.
	RegistrationEnabled bool `json:"registration_enabled"`
	// Support contact.
	SupportURL *string `json:"support_url,omitempty"`
	// Seconds a verified two-factor code authorises sensitive actions for.
	TwoFactorFreshnessSeconds int64 `json:"two_factor_freshness_seconds"`
	// Where to open the realtime connection, relative to this API's origin.
	WebsocketPath string `json:"websocket_path"`
	// The realtime protocol version this server speaks.
	WebsocketProtocolVersion int `json:"websocket_protocol_version"`
}

ExchangeConfig: Public exchange configuration.

Everything a frontend needs to render itself without a deploy: branding, limits, supported intervals, and whether the exchange is in maintenance.

type ExitPoolRequest

type ExitPoolRequest struct {
	Shares Amount `json:"shares"`
}

ExitPoolRequest: Removes liquidity from a pool.

type ExitPoolResult

type ExitPoolResult struct {
	BaseReturned  Amount `json:"base_returned"`
	QuoteReturned Amount `json:"quote_returned"`
	SharesBurned  Amount `json:"shares_burned"`
	SharesHeld    Amount `json:"shares_held"`
}

ExitPoolResult: What an exit produced.

type ExportParams

type ExportParams struct {
	// Start of the period, inclusive. Defaults to 30 days ago.
	From *time.Time
	// End of the period, inclusive. Defaults to now.
	To *time.Time
}

ExportParams holds the query parameters of export_deposits, export_ledger, export_orders, export_trades, export_withdrawals. Nil pointers are not sent.

type ExportsService

type ExportsService struct {
	// contains filtered or unexported fields
}

ExportsService: CSV exports. Each method returns the CSV text.

func (*ExportsService) Deposits

func (s *ExportsService) Deposits(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)

Deposits exports deposits as CSV.

func (*ExportsService) Ledger

func (s *ExportsService) Ledger(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)

Ledger exports the ledger as CSV.

func (*ExportsService) Orders

func (s *ExportsService) Orders(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)

Orders exports orders as CSV.

func (*ExportsService) Trades

func (s *ExportsService) Trades(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)

Trades exports your trades as CSV.

func (*ExportsService) Withdrawals

func (s *ExportsService) Withdrawals(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)

Withdrawals exports withdrawals as CSV.

type FeeSchedule

type FeeSchedule struct {
	// Human label.
	Label string `json:"label"`
	// Maker rate, as a percentage.
	MakerFeePercent string `json:"maker_fee_percent"`
	Min30dVolumeUsd Amount `json:"min_30d_volume_usd"`
	// Taker rate, as a percentage.
	TakerFeePercent string `json:"taker_fee_percent"`
	// Tier index.
	Tier int `json:"tier"`
}

FeeSchedule: A fee tier.

type FeesService

type FeesService struct {
	// contains filtered or unexported fields
}

FeesService: fee schedules.

func (*FeesService) List

func (s *FeesService) List(ctx context.Context, opts ...CallOption) ([]FeeSchedule, error)

List returns the fee schedules (maker and taker rates by tier).

type Fill

type Fill struct {
	Fee Amount `json:"fee"`
	// Asset the fee was charged in.
	FeeAsset string `json:"fee_asset"`
	// The caller's order.
	OrderID       string        `json:"order_id"`
	Price         Amount        `json:"price"`
	Quantity      Amount        `json:"quantity"`
	QuoteQuantity Amount        `json:"quote_quantity"`
	Role          LiquidityRole `json:"role"`
	Side          OrderSide     `json:"side"`
	// Market symbol.
	Symbol string `json:"symbol"`
	// When it executed.
	Timestamp time.Time `json:"timestamp"`
	// Trade id.
	TradeID string `json:"trade_id"`
}

Fill: One of the caller's executions.

type FillsParams deprecated

type FillsParams = FuturesFillsParams

Deprecated: use FuturesFillsParams.

type Funding

type Funding struct {
	Amount Amount `json:"amount"`
	// Coin.
	Coin         string `json:"coin"`
	PositionSize Amount `json:"position_size"`
	Rate         Amount `json:"rate"`
	// When, unix milliseconds.
	Time int64 `json:"time"`
}

Funding: One funding payment.

type FundingParams deprecated

type FundingParams = FuturesFundingParams

Deprecated: use FuturesFundingParams.

type FuturesBook

type FuturesBook struct {
	// When the provider last sent it.
	AsOf time.Time `json:"as_of"`
	// Asks, best first.
	Asks []Level `json:"asks"`
	// Bids, best first.
	Bids []Level `json:"bids"`
	// Coin.
	Coin string `json:"coin"`
	// The live feed is not healthy: the book may be out of date.
	Stale bool `json:"stale"`
}

FuturesBook: A futures market's book.

type FuturesBookUpdate

type FuturesBookUpdate struct {
	Coin string `json:"coin"`
	Full bool   `json:"full"`
	// Best first. Levels are {price, size} objects.
	Bids []Level   `json:"bids"`
	Asks []Level   `json:"asks"`
	AsOf time.Time `json:"as_of"`
}

FuturesBookUpdate is the data of futures.orderbook.update: the complete book (Full is always true). It replaces the previous one; a level absent from it is gone.

type FuturesCandle

type FuturesCandle struct {
	Close Amount `json:"close"`
	// Close time, unix milliseconds.
	CloseTime int64  `json:"close_time"`
	High      Amount `json:"high"`
	Low       Amount `json:"low"`
	Open      Amount `json:"open"`
	// Open time, unix milliseconds.
	OpenTime int64 `json:"open_time"`
	// Number of trades.
	Trades int64  `json:"trades"`
	Volume Amount `json:"volume"`
}

FuturesCandle: One candle.

type FuturesCandleUpdate

type FuturesCandleUpdate struct {
	Coin     string        `json:"coin"`
	Interval string        `json:"interval"`
	Candle   FuturesCandle `json:"candle"`
}

FuturesCandleUpdate is the data of futures.candle.update: the current (possibly open) candle. Candle.OpenTime tells an update of the current bar from a new bar.

type FuturesCandles

type FuturesCandles struct {
	// When read.
	AsOf time.Time `json:"as_of"`
	// Candles, oldest first.
	Candles []FuturesCandle `json:"candles"`
	// Coin.
	Coin string `json:"coin"`
	// Interval.
	Interval string `json:"interval"`
	// Older than it should be.
	Stale bool `json:"stale"`
}

FuturesCandles: A futures market's candles.

type FuturesCandlesParams

type FuturesCandlesParams struct {
	// `1m`, `5m`, `15m`, `1h`, `4h` or `1d`.
	//
	// Required.
	Interval string
	// Unix milliseconds: the window of 500 candles holding this time. Absent: the latest 500.
	Before *int64
}

FuturesCandlesParams holds the query parameters of futures_candles. Nil pointers are not sent.

type FuturesFill

type FuturesFill struct {
	ClosedPnl Amount `json:"closed_pnl"`
	// Coin.
	Coin string `json:"coin"`
	// The provider's description of the fill's effect (`Open Long`, `Close Short`, ...).
	Direction string `json:"direction"`
	// Our id for it.
	ID string `json:"id"`
	// Our id for its order.
	OrderID string `json:"order_id"`
	Price   Amount `json:"price"`
	// `buy` or `sell`.
	Side string `json:"side"`
	Size Amount `json:"size"`
	// Whether this fill took liquidity.
	Taker bool `json:"taker"`
	// When, unix milliseconds.
	Time int64 `json:"time"`
}

FuturesFill: One fill.

type FuturesFills

type FuturesFills struct {
	// Newest first; fills sharing a millisecond in a fixed order. A page may be short of 100 and still be followed by more.
	Fills []FuturesFill `json:"fills"`
	// Whether the account has a futures account.
	HasAccount bool `json:"has_account"`
	// Pass as `cursor` for older fills, exactly as given; `null` at the end (30 days back). Opaque: it may carry more than a time.
	NextCursor *string `json:"next_cursor,omitempty"`
}

FuturesFills: A page of the account's fills.

type FuturesFillsParams

type FuturesFillsParams struct {
	// The `next_cursor` of the previous page, as given; absent for the newest. A unix time in milliseconds is also accepted: rows older than it.
	Cursor *string
}

FuturesFillsParams holds the query parameters of futures_fills. Nil pointers are not sent.

type FuturesFunding

type FuturesFunding struct {
	// Newest first.
	Funding []Funding `json:"funding"`
	// Whether the account has a futures account.
	HasAccount bool `json:"has_account"`
	// Pass as `cursor` for older payments, exactly as given; `null` at the end (30 days back). Opaque.
	NextCursor *string `json:"next_cursor,omitempty"`
}

FuturesFunding: A page of the account's funding payments.

type FuturesFundingParams

type FuturesFundingParams struct {
	// The `next_cursor` of the previous page, as given; absent for the newest. A unix time in milliseconds is also accepted: rows older than it.
	Cursor *string
}

FuturesFundingParams holds the query parameters of futures_funding. Nil pointers are not sent.

type FuturesMarket

type FuturesMarket struct {
	// When this data was read.
	AsOf   time.Time  `json:"as_of"`
	Market PerpMarket `json:"market"`
	// Older than it should be.
	Stale bool `json:"stale"`
}

FuturesMarket: One futures market.

type FuturesMarkets

type FuturesMarkets struct {
	// When this data was read from the futures provider.
	AsOf time.Time `json:"as_of"`
	// The markets, in the provider's order. Delisted markets are not included.
	Markets []PerpMarket `json:"markets"`
	// The data is older than it should be: the provider could not be read just now.
	Stale bool `json:"stale"`
}

FuturesMarkets: Every listed futures market.

type FuturesMids

type FuturesMids struct {
	Mids map[string]Amount `json:"mids"`
	// When the server published the frame.
	AsOf time.Time `json:"as_of"`
}

FuturesMids is the data of futures.mids: the full set of mids, every coin each time.

type FuturesOpenOrders

type FuturesOpenOrders struct {
	// When read.
	AsOf *time.Time `json:"as_of,omitempty"`
	// Whether the account has a futures account.
	HasAccount bool `json:"has_account"`
	// The open orders.
	Orders []OpenOrder `json:"orders"`
	// Older than it should be.
	Stale bool `json:"stale"`
}

FuturesOpenOrders: The account's open orders.

type FuturesOrderbookParams

type FuturesOrderbookParams struct {
	// Levels per side, 1 to 20 (default 20).
	Depth *int
}

FuturesOrderbookParams holds the query parameters of futures_orderbook. Nil pointers are not sent.

type FuturesOrdersUpdate

type FuturesOrdersUpdate struct {
	Orders []OpenOrder `json:"orders"`
	AsOf   time.Time   `json:"as_of"`
	Stale  bool        `json:"stale"`
}

FuturesOrdersUpdate is the data of futures.orders on futures.account: every open order, in full. Replace your local list.

type FuturesPositions

type FuturesPositions struct {
	// When read.
	AsOf *time.Time `json:"as_of,omitempty"`
	// Whether the account has a futures account. Without one, nothing else is meaningful.
	HasAccount bool       `json:"has_account"`
	Positions  *Positions `json:"positions,omitempty"`
	// Older than it should be.
	Stale bool `json:"stale"`
}

FuturesPositions: The account's positions.

type FuturesPositionsUpdate

type FuturesPositionsUpdate struct {
	Positions Positions `json:"positions"`
	AsOf      time.Time `json:"as_of"`
	// Served from an older read.
	Stale bool `json:"stale"`
}

FuturesPositionsUpdate is the data of futures.positions on futures.account: the margin summary and every open position, in full.

type FuturesPublicTrade

type FuturesPublicTrade struct {
	Price Amount `json:"price"`
	// `buy` or `sell`: the taker's side.
	Side string `json:"side"`
	Size Amount `json:"size"`
	// When, unix milliseconds.
	Time int64 `json:"time"`
}

FuturesPublicTrade: A public trade, with nothing that identifies the parties.

type FuturesService

type FuturesService struct {
	// contains filtered or unexported fields
}

FuturesService: futures data, read only. Markets, OrderBook, Candles and Trades are public; Positions, OpenOrders, Fills and Funding need an API key with the read scope. Every market response carries AsOf and Stale (for books and trades, Stale is the live feed's health, not the data's age). When nothing usable is cached the API answers 503 SERVICE_UNAVAILABLE (retryable, with Retry-After), which the client retries like any other.

Without a futures account the account reads succeed with HasAccount false.

func (*FuturesService) AllFills

func (s *FuturesService) AllFills(ctx context.Context, opts ...IterOption) iter.Seq2[FuturesFill, error]

AllFills iterates over the account's fills, newest first, fetching pages as needed. It ends at the last page, or at once (no rows) when the account has no futures account.

While the futures provider is busy the server answers an empty page that hands back the cursor it was given, or a 503 whose details.reason is "futures_data_unavailable" (also on the first request). The iterator waits and asks again for the same cursor, at most WithMaxBusyRetries times in a row (default 3, one count for both kinds, reset by a page that advances; independent of the client's retry count, which does not apply to that 503). The wait is the Retry-After header, else details.retry_after_seconds, taken exactly (a hint above MaxServerWait fails at once with the 503), else the client's backoff; it is reported to Options.OnRetry. Then it yields a retryable *APIError with code CodePagingStalled, whose Unwrap is the last 503 when the last busy answer was one. Any other retryable error (a 503 without that reason, 502, 429) is retried by the client's normal retry policy. A page with rows that hands back the cursor it was given is a server error: its rows are yielded, then a non-retryable *APIError with code CodePagingCursorRepeated. Both carry Details["cursor"], which resumes the listing through Fills.

func (*FuturesService) AllFunding

func (s *FuturesService) AllFunding(ctx context.Context, opts ...IterOption) iter.Seq2[Funding, error]

AllFunding iterates over the account's funding payments, newest first, like AllFills.

func (*FuturesService) Candles

func (s *FuturesService) Candles(ctx context.Context, coin string, params FuturesCandlesParams, opts ...CallOption) (FuturesCandles, error)

Candles returns 500 candles of a futures market, oldest first: the latest, or the window holding params.Before (unix milliseconds). params.Interval is required (1m, 5m, 15m, 1h, 4h or 1d).

func (*FuturesService) Fills

func (s *FuturesService) Fills(ctx context.Context, cursor string, opts ...CallOption) (FuturesFills, error)

Fills returns one page of the account's fills, newest first, 30 days back. Pass "" for the newest page, then each NextCursor exactly as given until it is nil. A page may be short, even empty, and still have a NextCursor. AllFills does the paging.

func (*FuturesService) Funding

func (s *FuturesService) Funding(ctx context.Context, cursor string, opts ...CallOption) (FuturesFunding, error)

Funding returns one page of the account's funding payments, paged like Fills.

func (*FuturesService) Market

func (s *FuturesService) Market(ctx context.Context, coin string, opts ...CallOption) (FuturesMarket, error)

Market returns one futures market, for example "BTC" (the coin name, not a spot symbol).

func (*FuturesService) Markets

func (s *FuturesService) Markets(ctx context.Context, opts ...CallOption) (FuturesMarkets, error)

Markets returns every listed futures market and its current figures.

func (*FuturesService) OpenOrders

func (s *FuturesService) OpenOrders(ctx context.Context, opts ...CallOption) (FuturesOpenOrders, error)

OpenOrders returns the account's open futures orders.

func (*FuturesService) OrderBook

func (s *FuturesService) OrderBook(ctx context.Context, coin string, depth int, opts ...CallOption) (FuturesBook, error)

OrderBook returns a futures market's book, depth levels a side (1 to 20; 0 sends no depth and the server's default, 20, applies).

func (*FuturesService) Positions

func (s *FuturesService) Positions(ctx context.Context, opts ...CallOption) (FuturesPositions, error)

Positions returns the account's margin summary and open positions.

func (*FuturesService) Trades

func (s *FuturesService) Trades(ctx context.Context, coin string, limit int, opts ...CallOption) (FuturesTrades, error)

Trades returns a futures market's recent public trades, newest first: limit of them (1 to 100; 0 sends no limit and the server's default, 50, applies).

type FuturesStatus

type FuturesStatus struct {
	// "live" or "degraded" (what is served may be out of date).
	State string    `json:"state"`
	Since time.Time `json:"since"`
}

FuturesStatus is the data of futures.status, sent on a transition only.

type FuturesTrades

type FuturesTrades struct {
	// Coin.
	Coin string `json:"coin"`
	// The live feed is not healthy, or was only just opened: trades may be missing.
	Stale bool `json:"stale"`
	// Newest first.
	Trades []FuturesPublicTrade `json:"trades"`
}

FuturesTrades: A futures market's recent public trades.

type FuturesTradesParams

type FuturesTradesParams struct {
	// 1 to 100 (default 50).
	Limit *int
}

FuturesTradesParams holds the query parameters of futures_trades. Nil pointers are not sent.

type FuturesTradesUpdate

type FuturesTradesUpdate struct {
	Coin   string               `json:"coin"`
	Trades []FuturesPublicTrade `json:"trades"`
}

FuturesTradesUpdate is the data of futures.trades.new: one or more public trades.

type FuturesTransferID

type FuturesTransferID = string

FuturesTransferID: Unique identifier of a futures collateral transfer.

An alias of string: its format is not checked, so a future format keeps working.

type GetCandlesParams

type GetCandlesParams struct {
	// Bucket width.
	//
	// Required.
	Interval CandleInterval
	// Earliest bucket to return.
	StartTime *time.Time
	// Latest bucket to return.
	EndTime *time.Time
	// Maximum buckets. Capped server-side.
	Limit *int
}

GetCandlesParams holds the query parameters of get_candles. Nil pointers are not sent.

type GetLedgerParams

type GetLedgerParams struct {
	// Limit to one asset.
	Asset *string
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

GetLedgerParams holds the query parameters of get_ledger. Nil pointers are not sent.

type GetMarketTradesParams

type GetMarketTradesParams struct {
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

GetMarketTradesParams holds the query parameters of get_market_trades. Nil pointers are not sent.

type GetOrderBookParams

type GetOrderBookParams struct {
	// Price levels per side. Capped server-side.
	Depth *int
}

GetOrderBookParams holds the query parameters of get_order_book. Nil pointers are not sent.

type HMACAuthenticator

type HMACAuthenticator struct {
	// contains filtered or unexported fields
}

HMACAuthenticator signs every private request (see SigningScheme). Only X-API-Key, X-API-Timestamp, X-API-Nonce and X-API-Signature are sent: the secret never leaves the process. Authenticate runs once per attempt, so every retry is signed with a fresh timestamp and nonce. The HMAC key is the UTF-8 bytes of the secret string as issued.

Its String, GoString and LogValue methods never reveal the secret.

func NewHMACAuthenticator

func NewHMACAuthenticator(apiKey, apiSecret string) (*HMACAuthenticator, error)

NewHMACAuthenticator checks the pair and returns the authenticator.

func (*HMACAuthenticator) Authenticate

func (a *HMACAuthenticator) Authenticate(req *http.Request, body []byte) error

Authenticate signs what is on the wire: the escaped path and raw query of req.URL (exactly the request line Go sends) and the exact body bytes.

func (*HMACAuthenticator) ClockOffset

func (a *HMACAuthenticator) ClockOffset() time.Duration

ClockOffset is the correction applied to the local clock after SIGNATURE_EXPIRED.

func (*HMACAuthenticator) GoString

func (a *HMACAuthenticator) GoString() string

GoString keeps %#v from printing the fields.

func (*HMACAuthenticator) Kind

func (a *HMACAuthenticator) Kind() string

Kind returns "hmac".

func (*HMACAuthenticator) LogValue

func (a *HMACAuthenticator) LogValue() slog.Value

LogValue keeps log/slog from printing the fields.

func (*HMACAuthenticator) Redact

func (a *HMACAuthenticator) Redact(text string) string

Redact replaces the secret and the key id in text.

func (*HMACAuthenticator) SignWebSocketChallenge

func (a *HMACAuthenticator) SignWebSocketChallenge(connectionID, challenge string) (keyID, signature string)

SignWebSocketChallenge returns the key id and the signature for a WebSocket auth_key.

func (*HMACAuthenticator) String

func (a *HMACAuthenticator) String() string

type HeldIncoming

type HeldIncoming struct {
	Amount Amount `json:"amount"`
	// When it becomes available, unless an operator cancels it before then.
	AvailableAt time.Time `json:"available_at"`
	// The transfer.
	TransferID string `json:"transfer_id"`
}

HeldIncoming: An internal transfer credited to `locked` and not yet available.

type InvalidAmountError

type InvalidAmountError struct {
	Field string
	Msg   string
}

InvalidAmountError is a malformed decimal string in an amount field, detected before sending.

func (*InvalidAmountError) Error

func (e *InvalidAmountError) Error() string

type IterOption

type IterOption func(*iterOptions)

IterOption configures an iterator: WithMaxItems, WithMaxBusyRetries, WithCallOptions.

func WithCallOptions

func WithCallOptions(opts ...CallOption) IterOption

WithCallOptions applies call options (timeout, retries) to every page request.

func WithMaxBusyRetries

func WithMaxBusyRetries(n int) IterOption

WithMaxBusyRetries sets how many times in a row Futures.AllFills and Futures.AllFunding ask again for a page while the futures provider is busy (an empty page with the same cursor, or a 503 futures_data_unavailable), before they yield PAGING_STALLED. Default DefaultMaxBusyRetries (3). It is independent of the client's retry count: a client with NoRetries still rides out a busy provider. 0 gives up at the first busy answer.

func WithMaxItems

func WithMaxItems(n int) IterOption

WithMaxItems stops the iterator after n items in total.

type JoinPoolRequest

type JoinPoolRequest struct {
	BaseAmount               Amount  `json:"base_amount"`
	MaxRatioDeviationPercent *Amount `json:"max_ratio_deviation_percent,omitempty"`
	QuoteAmount              Amount  `json:"quote_amount"`
}

JoinPoolRequest: Adds liquidity to a pool.

type JoinPoolResult

type JoinPoolResult struct {
	BaseDeposited  Amount `json:"base_deposited"`
	QuoteDeposited Amount `json:"quote_deposited"`
	SharesHeld     Amount `json:"shares_held"`
	SharesMinted   Amount `json:"shares_minted"`
}

JoinPoolResult: What a join produced.

type LedgerEntry

type LedgerEntry struct {
	// Asset symbol.
	Asset          string `json:"asset"`
	AvailableAfter Amount `json:"available_after"`
	AvailableDelta Amount `json:"available_delta"`
	// When it was applied.
	CreatedAt time.Time `json:"created_at"`
	// Entry id.
	ID           string          `json:"id"`
	Kind         LedgerEntryKind `json:"kind"`
	LockedDelta  Amount          `json:"locked_delta"`
	PendingDelta Amount          `json:"pending_delta"`
	Reference    LedgerReference `json:"reference"`
	// Position in this account's history for this asset.
	Sequence int64 `json:"sequence"`
}

LedgerEntry: One entry from the account's ledger.

type LedgerEntryKind

type LedgerEntryKind string

LedgerEntryKind: What a ledger entry records.

The type is open: values added to the API later decode without error.

const (
	LedgerEntryKindDeposit                   LedgerEntryKind = "deposit"
	LedgerEntryKindDepositReversal           LedgerEntryKind = "deposit_reversal"
	LedgerEntryKindWithdrawalDebit           LedgerEntryKind = "withdrawal_debit"
	LedgerEntryKindWithdrawalFee             LedgerEntryKind = "withdrawal_fee"
	LedgerEntryKindWithdrawalFeeReserve      LedgerEntryKind = "withdrawal_fee_reserve"
	LedgerEntryKindWithdrawalRelease         LedgerEntryKind = "withdrawal_release"
	LedgerEntryKindWithdrawalFeeRelease      LedgerEntryKind = "withdrawal_fee_release"
	LedgerEntryKindOrderReserve              LedgerEntryKind = "order_reserve"
	LedgerEntryKindWithdrawalReserve         LedgerEntryKind = "withdrawal_reserve"
	LedgerEntryKindOrderRelease              LedgerEntryKind = "order_release"
	LedgerEntryKindTradeDebit                LedgerEntryKind = "trade_debit"
	LedgerEntryKindTradeCredit               LedgerEntryKind = "trade_credit"
	LedgerEntryKindTradeFee                  LedgerEntryKind = "trade_fee"
	LedgerEntryKindTransferOut               LedgerEntryKind = "transfer_out"
	LedgerEntryKindTransferIn                LedgerEntryKind = "transfer_in"
	LedgerEntryKindTransferInHeld            LedgerEntryKind = "transfer_in_held"
	LedgerEntryKindTransferRelease           LedgerEntryKind = "transfer_release"
	LedgerEntryKindTransferReversal          LedgerEntryKind = "transfer_reversal"
	LedgerEntryKindAdjustmentCredit          LedgerEntryKind = "adjustment_credit"
	LedgerEntryKindAdjustmentDebit           LedgerEntryKind = "adjustment_debit"
	LedgerEntryKindRebate                    LedgerEntryKind = "rebate"
	LedgerEntryKindPoolJoin                  LedgerEntryKind = "pool_join"
	LedgerEntryKindPoolExit                  LedgerEntryKind = "pool_exit"
	LedgerEntryKindFuturesTransferReserve    LedgerEntryKind = "futures_transfer_reserve"
	LedgerEntryKindFuturesTransferRelease    LedgerEntryKind = "futures_transfer_release"
	LedgerEntryKindFuturesCollateralSent     LedgerEntryKind = "futures_collateral_sent"
	LedgerEntryKindFuturesCollateralReturned LedgerEntryKind = "futures_collateral_returned"
	LedgerEntryKindWithdrawalRefund          LedgerEntryKind = "withdrawal_refund"
)

type LedgerReference

type LedgerReference struct {
	Type LedgerReferenceType `json:"type"`
	// Short machine-readable cause.
	//
	// Set for type system.
	Cause *string `json:"cause,omitempty"`
	// Set for type transfer.
	CounterpartyUserID *UserID `json:"counterparty_user_id,omitempty"`
	// Set for type deposit.
	DepositID *DepositID `json:"deposit_id,omitempty"`
	// Set for type futures_transfer.
	FuturesTransferID *FuturesTransferID `json:"futures_transfer_id,omitempty"`
	// Set for type adjustment.
	OperatorUserID *UserID `json:"operator_user_id,omitempty"`
	// Set for type order, trade.
	OrderID *OrderID `json:"order_id,omitempty"`
	// Set for type pool.
	PoolID *PoolID `json:"pool_id,omitempty"`
	// Set for type trade.
	TradeID *TradeID `json:"trade_id,omitempty"`
	// Shared reference linking both halves.
	//
	// Set for type transfer.
	TransferRef *string `json:"transfer_ref,omitempty"`
	// Set for type withdrawal.
	WithdrawalID *WithdrawalID `json:"withdrawal_id,omitempty"`
	// Raw is the object as received (nil for values built in code).
	Raw json.RawMessage `json:"-"`
}

LedgerReference: What caused a ledger entry: one kind of cause per variant, told apart by `type`.

Type says which variant it is; only that variant's fields are set. A type added to the API later decodes without error: Type holds it and Raw the whole object.

func (LedgerReference) Known

func (r LedgerReference) Known() bool

Known reports whether Type is one this SDK version knows.

func (*LedgerReference) UnmarshalJSON

func (r *LedgerReference) UnmarshalJSON(b []byte) error

UnmarshalJSON keeps the raw object and never fails on an unknown variant.

type LedgerReferenceType

type LedgerReferenceType string

LedgerReferenceType tells the variants of LedgerReference apart. The type is open.

const (
	// A blockchain deposit.
	LedgerReferenceTypeDeposit LedgerReferenceType = "deposit"
	// A withdrawal request.
	LedgerReferenceTypeWithdrawal LedgerReferenceType = "withdrawal"
	// An order reservation or release.
	LedgerReferenceTypeOrder LedgerReferenceType = "order"
	// A trade settlement.
	LedgerReferenceTypeTrade LedgerReferenceType = "trade"
	// An internal transfer between accounts.
	LedgerReferenceTypeTransfer LedgerReferenceType = "transfer"
	// A manual operator adjustment. Always accompanied by an audit event.
	LedgerReferenceTypeAdjustment LedgerReferenceType = "adjustment"
	// A liquidity pool join or exit.
	LedgerReferenceTypePool LedgerReferenceType = "pool"
	// A movement of collateral to or from a futures account.
	//
	// Every entry a transfer produces carries the same one, so the reservation, the release and the completion can be read back as one event — which is what an operator resolving an ambiguous transfer needs.
	LedgerReferenceTypeFuturesTransfer LedgerReferenceType = "futures_transfer"
	// A system-originated credit with no user counterparty (rebate, promotion).
	LedgerReferenceTypeSystem LedgerReferenceType = "system"
)

type Level

type Level struct {
	Price Amount `json:"price"`
	Size  Amount `json:"size"`
}

Level: One price level.

type LiquidityRole

type LiquidityRole string

LiquidityRole: Whether a fill added liquidity (maker) or removed it (taker).

The type is open: values added to the API later decode without error.

const (
	LiquidityRoleMaker LiquidityRole = "maker"
	LiquidityRoleTaker LiquidityRole = "taker"
)

type ListDepositsParams

type ListDepositsParams struct {
	// Limit to one asset.
	Asset *string
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

ListDepositsParams holds the query parameters of list_deposits. Nil pointers are not sent.

type ListNotificationsParams

type ListNotificationsParams struct {
	// Return only notices that have not been read.
	UnreadOnly *bool
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

ListNotificationsParams holds the query parameters of list_notifications. Nil pointers are not sent.

type ListOpenOrdersParams

type ListOpenOrdersParams struct {
	// Limit to one market.
	Symbol *string
	// Limit to one status.
	Status *OrderStatus
}

ListOpenOrdersParams holds the query parameters of list_open_orders. Nil pointers are not sent.

type ListWithdrawalsParams

type ListWithdrawalsParams struct {
	// Limit to one asset.
	Asset *string
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

ListWithdrawalsParams holds the query parameters of list_withdrawals. Nil pointers are not sent.

type LiveBalances

type LiveBalances struct {
	// contains filtered or unexported fields
}

LiveBalances holds the live balances of the authenticated account, fed by the balances channel and REST snapshots. Create it with WebSocket.LiveBalances after Auth. It is safe for concurrent use.

An event applies only if its data.sequence is greater than the stored one for that asset; a total of 0 removes the row (a snapshot row at or below that sequence cannot bring it back). A new snapshot is taken on a frame gap, balances.resync, CONCURRENT_MODIFICATION, a reconnect and after an account change, never because data.sequence skipped values. At the start and after every account change the snapshot source's owner is checked against the WebSocket user.

func (*LiveBalances) All

func (lb *LiveBalances) All() []Balance

All returns copies of every non-zero balance.

func (*LiveBalances) Close

func (lb *LiveBalances) Close()

Close stops following (unsubscribes balances unless something else on this socket needs it).

func (*LiveBalances) Get

func (lb *LiveBalances) Get(asset string) (Balance, bool)

Get returns a copy of one asset's balance.

func (*LiveBalances) LastError

func (lb *LiveBalances) LastError() error

LastError returns the last error (also passed to OnError; the first owner check can fail before the caller holds the LiveBalances). An *AccountMismatchError means nothing was merged. The next snapshot clears it.

func (*LiveBalances) Stale

func (lb *LiveBalances) Stale() bool

Stale is true until the first snapshot, and from every refetch trigger until the next snapshot is applied.

type LiveBalancesOptions

type LiveBalancesOptions struct {
	// Where snapshots come from. Default: the Client's Account.Balances (use Client.WebSocket).
	// It must return the balances of the same account the WebSocket is authenticated as.
	Snapshot func(ctx context.Context) ([]Balance, error)
	// The user id the snapshot source belongs to, compared with the WebSocket's authenticated user
	// at the start and after every account change. Default: the Client's Account.ID (GET /api/v1/account/id).
	OwnerID func(ctx context.Context) (string, error)
	// A fixed owner user id instead of OwnerID.
	AccountID string
	// Minimum time between successful snapshots (the API key's rate limit is shared). NOTE: 0
	// selects the default, 2 s (Go cannot tell unset from zero); use NoMinimum for none.
	MinSnapshotInterval time.Duration
	// Retry delay after a failed snapshot or owner lookup. Default 1 s (doubles up to 30 s).
	RetryDelay time.Duration
	// Called (on its own goroutine, one at a time) when one asset changes; nil balance: the row
	// was removed because its total reached 0. Callbacks queue up to 256 deep; while the queue is
	// full, further notifications are dropped with a warning (the state itself stays correct: read
	// it with Get and All).
	OnUpdate func(asset string, b *Balance)
	// Called after a snapshot was applied.
	OnSnapshot func(reason string)
	// ACCOUNT_MISMATCH (*AccountMismatchError: nothing merged), or a failed snapshot or owner
	// lookup (retried with backoff).
	OnError func(error)
}

LiveBalancesOptions configures WebSocket.LiveBalances.

type LiveOrderBook

type LiveOrderBook struct {
	// contains filtered or unexported fields
}

LiveOrderBook is a local order book fed by the orderbook:{symbol} channel. Create it with WebSocket.OrderBook. It is safe for concurrent use.

func (*LiveOrderBook) Close

func (b *LiveOrderBook) Close()

Close stops following the book and unsubscribes.

func (*LiveOrderBook) Snapshot

func (b *LiveOrderBook) Snapshot() BookSnapshot

Snapshot returns a copy of the current state.

func (*LiveOrderBook) Symbol

func (b *LiveOrderBook) Symbol() string

Symbol returns the market symbol.

type LiveOrderBookOptions

type LiveOrderBookOptions struct {
	// The book changed (a snapshot or an update was applied).
	OnUpdate func(BookSnapshot)
	// A sequence gap: the book is stale until the next update replaces it.
	OnStale func(expected, received int64)
	// The update after a gap arrived in order; the book is current again.
	OnHealed func()
	// A fresh REST snapshot is being taken (reconnect, CONCURRENT_MODIFICATION).
	OnResync func()
	// A snapshot failed; it is retried with backoff.
	OnError func(error)
	// Delay before retrying a failed snapshot. Default 1 s, doubling up to 30 s.
	SnapshotRetryDelay time.Duration
}

LiveOrderBookOptions are optional callbacks for a LiveOrderBook. They run on the WebSocket's handler goroutine, in order.

type MaintenanceReason

type MaintenanceReason string

MaintenanceReason: Machine-readable reasons a capability is unavailable.

The type is open: values added to the API later decode without error.

const (
	MaintenanceReasonExchangeMaintenance MaintenanceReason = "exchange_maintenance"
	MaintenanceReasonNetworkUnavailable  MaintenanceReason = "network_unavailable"
	MaintenanceReasonDepositsDisabled    MaintenanceReason = "deposits_disabled"
	MaintenanceReasonWithdrawalsDisabled MaintenanceReason = "withdrawals_disabled"
	MaintenanceReasonAssetUnavailable    MaintenanceReason = "asset_unavailable"
)

type MaintenanceState

type MaintenanceState struct {
	// Operator-supplied explanation, when there is one.
	Message *string           `json:"message,omitempty"`
	Reason  MaintenanceReason `json:"reason"`
}

MaintenanceState: Why a capability is currently unavailable.

type Market

type Market struct {
	// Base asset symbol.
	BaseAsset        string `json:"base_asset"`
	BestAsk          Amount `json:"best_ask"`
	BestBid          Amount `json:"best_bid"`
	Change24hPercent Amount `json:"change_24h_percent"`
	High24h          Amount `json:"high_24h"`
	LastPrice        Amount `json:"last_price"`
	// Time of the most recent trade.
	LastTradeAt *time.Time `json:"last_trade_at,omitempty"`
	LotSize     Amount     `json:"lot_size"`
	Low24h      Amount     `json:"low_24h"`
	MaxQuantity *Amount    `json:"max_quantity,omitempty"`
	MinNotional Amount     `json:"min_notional"`
	MinQuantity Amount     `json:"min_quantity"`
	// Decimal places a price may carry.
	PriceDecimals int `json:"price_decimals"`
	// Decimal places a quantity may carry.
	QuantityDecimals int `json:"quantity_decimals"`
	// Quote asset symbol.
	QuoteAsset     string       `json:"quote_asset"`
	QuoteVolume24h Amount       `json:"quote_volume_24h"`
	Status         MarketStatus `json:"status"`
	// Order types this market accepts.
	SupportedOrderTypes []OrderType `json:"supported_order_types"`
	// Time-in-force options this market accepts.
	SupportedTimeInForce []TimeInForce `json:"supported_time_in_force"`
	// `BASE/QUOTE`.
	Symbol   string `json:"symbol"`
	TickSize Amount `json:"tick_size"`
	// When trading opens, for a market not yet live.
	TradingStartsAt *time.Time `json:"trading_starts_at,omitempty"`
	Volume24h       Amount     `json:"volume_24h"`
}

Market: A tradable market and its current ticker.

type MarketStatus

type MarketStatus string

MarketStatus: Trading availability of a market.

The type is open: values added to the API later decode without error.

const (
	MarketStatusActive     MarketStatus = "active"
	MarketStatusPaused     MarketStatus = "paused"
	MarketStatusSellOnly   MarketStatus = "sell_only"
	MarketStatusPreTrading MarketStatus = "pre_trading"
	MarketStatusDelisted   MarketStatus = "delisted"
)

type MarketsService

type MarketsService struct {
	// contains filtered or unexported fields
}

MarketsService: markets, tickers, order books, public trades and candles.

func (*MarketsService) AllTrades

func (s *MarketsService) AllTrades(ctx context.Context, symbol string, params *GetMarketTradesParams, opts ...IterOption) iter.Seq2[PublicTrade, error]

AllTrades iterates over every public trade, fetching pages as needed.

func (*MarketsService) Candles

func (s *MarketsService) Candles(ctx context.Context, symbol string, params GetCandlesParams, opts ...CallOption) ([]Candle, error)

Candles returns OHLCV candles. params.Interval is required.

func (*MarketsService) Get

func (s *MarketsService) Get(ctx context.Context, symbol string, opts ...CallOption) (Market, error)

Get returns one market, for example "BTC/USDT".

func (*MarketsService) List

func (s *MarketsService) List(ctx context.Context, opts ...CallOption) ([]Market, error)

List returns every market with its current ticker.

func (*MarketsService) OrderBook

func (s *MarketsService) OrderBook(ctx context.Context, symbol string, params *GetOrderBookParams, opts ...CallOption) (OrderBook, error)

OrderBook returns an order-book snapshot aggregated by price, with the realtime sequence it is current as of. To follow a book live, use WebSocket.OrderBook, which applies the sync rules.

func (*MarketsService) Trades

func (s *MarketsService) Trades(ctx context.Context, symbol string, params *GetMarketTradesParams, opts ...CallOption) (*Page[PublicTrade], error)

Trades returns one page of recent public trades.

type Network

type Network struct {
	// Typical seconds between blocks, for estimating confirmation time.
	AverageBlockSeconds int `json:"average_block_seconds"`
	// Stable code.
	Code string `json:"code"`
	// Whether deposits on this network are actually being detected.
	//
	// False means either half of the pipeline is down: the last scan pass failed — a refused block range, a rate limit, a node that answers but will not serve logs — or finality could not be established, so deposits are being held rather than credited.
	//
	// Deposits sent now will be credited late, whenever the chain recovers, rather than lost. This is the field a status page should use to say deposits are degraded; `reachable` only says the node replies, which it may well do while yielding nothing.
	DepositsOperational bool `json:"deposits_operational"`
	// Template for an address explorer link. `{address}` is substituted.
	ExplorerAddressURLTemplate *string `json:"explorer_address_url_template,omitempty"`
	// Template for a transaction explorer link. `{txid}` is substituted.
	//
	// Absent when the operator has configured none; render no link rather than guessing a URL.
	ExplorerTxURLTemplate *string `json:"explorer_tx_url_template,omitempty"`
	// Whether the network is operational.
	IsActive bool `json:"is_active"`
	// Display name.
	Name string `json:"name"`
	// Whether the node answers at all.
	//
	// Narrower than it sounds, and deliberately so: a reachable node can still be failing to yield deposits. Do not render this alone as "network up".
	Reachable bool `json:"reachable"`
}

Network: A blockchain network.

type NetworksService

type NetworksService struct {
	// contains filtered or unexported fields
}

NetworksService: blockchain networks.

func (*NetworksService) List

func (s *NetworksService) List(ctx context.Context, opts ...CallOption) ([]Network, error)

List returns every network.

type Notification

type Notification struct {
	// One or two sentences.
	Body string `json:"body"`
	// When it was created.
	CreatedAt time.Time `json:"created_at"`
	// Notice id.
	ID   string           `json:"id"`
	Kind NotificationKind `json:"kind"`
	// Whether it has been read.
	Read bool `json:"read"`
	// The referenced resource's opaque id, for linking.
	ResourceID *string `json:"resource_id,omitempty"`
	// What it refers to: `deposit`, `withdrawal`, `order`.
	ResourceType *string `json:"resource_type,omitempty"`
	// Short heading.
	Title string `json:"title"`
}

Notification: An in-app notice.

type NotificationKind

type NotificationKind string

NotificationKind: What a notice is about.

A closed enum so a client can render each kind deliberately — an icon, a colour, a link — rather than pattern-matching on prose that may be reworded.

The type is open: values added to the API later decode without error.

const (
	NotificationKindDepositDetected     NotificationKind = "deposit_detected"
	NotificationKindDepositCredited     NotificationKind = "deposit_credited"
	NotificationKindWithdrawalRequested NotificationKind = "withdrawal_requested"
	NotificationKindWithdrawalSent      NotificationKind = "withdrawal_sent"
	NotificationKindWithdrawalCompleted NotificationKind = "withdrawal_completed"
	NotificationKindWithdrawalFailed    NotificationKind = "withdrawal_failed"
	NotificationKindOrderFilled         NotificationKind = "order_filled"
	NotificationKindOrderClosed         NotificationKind = "order_closed"
	NotificationKindSecurity            NotificationKind = "security"
	NotificationKindListingDecision     NotificationKind = "listing_decision"
	NotificationKindAnnouncement        NotificationKind = "announcement"
)

type OpenOrder

type OpenOrder struct {
	// Coin.
	Coin string `json:"coin"`
	// Our id for it, stable across reads.
	ID string `json:"id"`
	// The order type as the provider names it (`Limit`, `Stop Market`, ...).
	OrderType    string `json:"order_type"`
	OriginalSize Amount `json:"original_size"`
	// When placed, unix milliseconds.
	PlacedAt int64  `json:"placed_at"`
	Price    Amount `json:"price"`
	// Whether it may only reduce a position.
	ReduceOnly bool `json:"reduce_only"`
	// `buy` or `sell`.
	Side         string  `json:"side"`
	Size         Amount  `json:"size"`
	TriggerPrice *Amount `json:"trigger_price,omitempty"`
}

OpenOrder: One open order.

type OperationID

type OperationID string

OperationID names one operation of the SDK surface.

const (
	OpCancelAll               OperationID = "cancel_all"
	OpCancelAllAfter          OperationID = "cancel_all_after"
	OpCancelBatch             OperationID = "cancel_batch"
	OpCancelOrder             OperationID = "cancel_order"
	OpCancelOrderByClientID   OperationID = "cancel_order_by_client_id"
	OpDepositAddress          OperationID = "deposit_address"
	OpExchangeConfig          OperationID = "exchange_config"
	OpExitPool                OperationID = "exit_pool"
	OpExportDeposits          OperationID = "export_deposits"
	OpExportLedger            OperationID = "export_ledger"
	OpExportOrders            OperationID = "export_orders"
	OpExportTrades            OperationID = "export_trades"
	OpExportWithdrawals       OperationID = "export_withdrawals"
	OpFuturesCandles          OperationID = "futures_candles"
	OpFuturesFills            OperationID = "futures_fills"
	OpFuturesFunding          OperationID = "futures_funding"
	OpFuturesMarket           OperationID = "futures_market"
	OpFuturesMarkets          OperationID = "futures_markets"
	OpFuturesOpenOrders       OperationID = "futures_open_orders"
	OpFuturesOrderbook        OperationID = "futures_orderbook"
	OpFuturesPositions        OperationID = "futures_positions"
	OpFuturesTrades           OperationID = "futures_trades"
	OpGetAccountID            OperationID = "get_account_id"
	OpGetAsset                OperationID = "get_asset"
	OpGetBalance              OperationID = "get_balance"
	OpGetCandles              OperationID = "get_candles"
	OpGetDeposit              OperationID = "get_deposit"
	OpGetLedger               OperationID = "get_ledger"
	OpGetMarket               OperationID = "get_market"
	OpGetMarketTrades         OperationID = "get_market_trades"
	OpGetOrder                OperationID = "get_order"
	OpGetOrderBook            OperationID = "get_order_book"
	OpGetOrderByClientID      OperationID = "get_order_by_client_id"
	OpGetPool                 OperationID = "get_pool"
	OpGetWithdrawal           OperationID = "get_withdrawal"
	OpJoinPool                OperationID = "join_pool"
	OpListAPIKeys             OperationID = "list_api_keys"
	OpListAssets              OperationID = "list_assets"
	OpListBalances            OperationID = "list_balances"
	OpListDeposits            OperationID = "list_deposits"
	OpListFeeSchedules        OperationID = "list_fee_schedules"
	OpListMarkets             OperationID = "list_markets"
	OpListNetworks            OperationID = "list_networks"
	OpListNotifications       OperationID = "list_notifications"
	OpListOpenOrders          OperationID = "list_open_orders"
	OpListPools               OperationID = "list_pools"
	OpListSubAccounts         OperationID = "list_sub_accounts"
	OpListWithdrawalAddresses OperationID = "list_withdrawal_addresses"
	OpListWithdrawals         OperationID = "list_withdrawals"
	OpOrderHistory            OperationID = "order_history"
	OpPlaceBatch              OperationID = "place_batch"
	OpPlaceOrder              OperationID = "place_order"
	OpServerTime              OperationID = "server_time"
	OpSubAccountBalances      OperationID = "sub_account_balances"
	OpTradeHistory            OperationID = "trade_history"
)

type OperationInfo

type OperationInfo struct {
	Method, Path string
	Auth         string // "none" or "api_key"
	Scope        string // "", "read" or "trade"
}

OperationInfo describes one operation of the SDK surface.

type Options

type Options struct {
	// API key id (ak_…). Give it together with APISecret, or not at all.
	APIKey string
	// API key secret. Never logged, never put in a URL.
	APISecret string
	// How APIKey/APISecret authenticate: "hmac" (default, "" too): every private request is
	// signed and the secret never leaves the process; a key issued before signing existed fails
	// with KEY_NOT_SIGNABLE (no fallback). "headers": X-API-Key + X-API-Secret, which the API is
	// switching off (SIGNATURE_REQUIRED); kept only for servers that still accept it.
	Auth string
	// A custom credentials scheme. Mutually exclusive with APIKey/APISecret.
	Authenticator Authenticator
	// Default DefaultBaseURL. Must be https:// (see AllowInsecure).
	BaseURL string
	// Allow plain http:// (and ws:// for WebSocket), but ONLY for a loopback host
	// (localhost, 127.0.0.1, ::1), for example a local test server.
	AllowInsecure bool
	// Per-attempt timeout. Default 10 s.
	Timeout time.Duration
	// Retries after the first attempt for retryable failures. Default 3; use NoRetries for 0.
	MaxRetries int
	// Set to disable retries (MaxRetries 0 means "default").
	NoRetries bool
	// Default: an http.Client without a timeout of its own (Timeout applies per attempt).
	// The SDK uses a copy with redirects disabled; the client you pass is not modified.
	HTTPClient *http.Client
	// Client-side rate limit in requests per minute. Default DefaultRPMAnonymous without
	// credentials and DefaultRPMWithKey with them. It adapts downwards to the server's
	// X-RateLimit-* headers.
	RequestsPerMinute int
	// Disables the client-side rate limiter, and with it the hold that a 429 sets.
	DisableRateLimit bool
	// A client-side budget for placements, in order actions a second: PlaceOrder takes 1 and
	// PlaceOrders takes one per order; cancels never take any. 0 (the default) turns it off.
	// A market maker's key has 50 a second on the server: set 50 to wait locally instead of
	// being refused.
	OrderActionsPerSecond float64
	// Appended to the User-Agent: "my-bot/1.2" gives "cexy-go/<Version> my-bot/1.2".
	UserAgentSuffix string
	// Called before each retry (for logging or metrics). Never receives credentials.
	OnRetry func(RetryInfo)
	// contains filtered or unexported fields
}

Options configures a Client. The zero value gives an anonymous client for public data.

func (Options) GoString

func (o Options) GoString() string

GoString keeps %#v from printing APISecret.

func (Options) String

func (o Options) String() string

String keeps fmt (%v, %+v) from printing APISecret.

type Order

type Order struct {
	AveragePrice *Amount `json:"average_price,omitempty"`
	// Your identifier, if you supplied one.
	ClientOrderID *string `json:"client_order_id,omitempty"`
	// When it reached a terminal state.
	ClosedAt *time.Time `json:"closed_at,omitempty"`
	// When it was placed.
	CreatedAt time.Time `json:"created_at"`
	// Asset the fees were charged in.
	FeeAsset            *string `json:"fee_asset,omitempty"`
	FeePaid             Amount  `json:"fee_paid"`
	FilledQuantity      Amount  `json:"filled_quantity"`
	FilledQuoteQuantity Amount  `json:"filled_quote_quantity"`
	// Order id.
	ID                string      `json:"id"`
	Price             *Amount     `json:"price,omitempty"`
	Quantity          Amount      `json:"quantity"`
	QuoteQuantity     *Amount     `json:"quote_quantity,omitempty"`
	RemainingQuantity Amount      `json:"remaining_quantity"`
	ReservedRemaining Amount      `json:"reserved_remaining"`
	Side              OrderSide   `json:"side"`
	Status            OrderStatus `json:"status"`
	// Why the order was rejected or cancelled.
	StatusReason *string `json:"status_reason,omitempty"`
	StopPrice    *Amount `json:"stop_price,omitempty"`
	// Market symbol.
	Symbol           string            `json:"symbol"`
	TimeInForce      TimeInForce       `json:"time_in_force"`
	TriggerDirection *TriggerDirection `json:"trigger_direction,omitempty"`
	// When the trigger fired, if it has.
	TriggeredAt *time.Time `json:"triggered_at,omitempty"`
	Type        OrderType  `json:"type"`
	// When it last changed.
	UpdatedAt time.Time `json:"updated_at"`
}

Order: An order.

type OrderBook

type OrderBook struct {
	// Asks, best first.
	Asks [][]Amount `json:"asks"`
	// Bids, best first, as `[price, quantity]` pairs.
	Bids [][]Amount `json:"bids"`
	// The realtime sequence this snapshot is current as of.
	//
	// Each `orderbook.update` on the `orderbook:{symbol}` websocket channel carries both sides of the top 50 levels in full (`data.full` is always `true`) and replaces the previous state; there are no deltas to buffer. Ignore an update whose `sequence` is at or below the one you hold. A gap only means a book was missed: the next update replaces it whole.
	Sequence int64 `json:"sequence"`
	// Market symbol.
	Symbol string `json:"symbol"`
	// When this snapshot was taken.
	Timestamp time.Time `json:"timestamp"`
}

OrderBook: One side of the order book, aggregated by price.

type OrderBookUpdate

type OrderBookUpdate struct {
	Symbol string     `json:"symbol"`
	Full   bool       `json:"full"`
	Bids   [][]Amount `json:"bids"`
	Asks   [][]Amount `json:"asks"`
}

OrderBookUpdate is the data of orderbook.update: always the complete top 50 levels of both sides (Full is always true). It replaces the previous book; there are no deltas.

type OrderHistoryParams

type OrderHistoryParams struct {
	// Limit to one market.
	Symbol *string
	// Limit to one status.
	Status *OrderStatus
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

OrderHistoryParams holds the query parameters of order_history. Nil pointers are not sent.

type OrderID

type OrderID = string

OrderID: Unique identifier of an order.

An alias of string: its format is not checked, so a future format keeps working.

type OrderSide

type OrderSide string

OrderSide: Which side of a market an order takes.

The type is open: values added to the API later decode without error.

const (
	OrderSideBuy  OrderSide = "buy"
	OrderSideSell OrderSide = "sell"
)

type OrderStateUnknownError

type OrderStateUnknownError struct {
	ClientOrderID string
	Err           error
}

OrderStateUnknownError means PlaceOrder failed ambiguously (network error or 5xx) and the lookup by client_order_id failed too, so it is unknown whether the order exists. Check Trading.OrderByClientID(ClientOrderID) before placing it again.

func (*OrderStateUnknownError) Error

func (e *OrderStateUnknownError) Error() string

func (*OrderStateUnknownError) Unwrap

func (e *OrderStateUnknownError) Unwrap() error

type OrderStatus

type OrderStatus string

OrderStatus: Lifecycle of an order.

The type is open: values added to the API later decode without error.

const (
	OrderStatusPending         OrderStatus = "pending"
	OrderStatusOpen            OrderStatus = "open"
	OrderStatusPartiallyFilled OrderStatus = "partially_filled"
	OrderStatusFilled          OrderStatus = "filled"
	OrderStatusCancelled       OrderStatus = "cancelled"
	OrderStatusRejected        OrderStatus = "rejected"
	OrderStatusPendingTrigger  OrderStatus = "pending_trigger"
	OrderStatusExpired         OrderStatus = "expired"
)

type OrderType

type OrderType string

OrderType: Order types the matching engine accepts.

The type is open: values added to the API later decode without error.

const (
	OrderTypeLimit      OrderType = "limit"
	OrderTypeMarket     OrderType = "market"
	OrderTypeStopLimit  OrderType = "stop_limit"
	OrderTypeStopMarket OrderType = "stop_market"
)

type OrderbookParams deprecated

type OrderbookParams = FuturesOrderbookParams

Deprecated: use FuturesOrderbookParams.

type Page

type Page[T any] struct {
	Items   []T  `json:"items"`
	HasMore bool `json:"has_more"`
	// Pass it back as Cursor to get the next page. Nil on the last page.
	NextCursor *string `json:"next_cursor,omitempty"`
}

Page is one page of a cursor-paginated listing.

type PasswordRules

type PasswordRules struct {
	// Whether the password may contain the account's email address.
	AllowsEmailSubstring bool `json:"allows_email_substring"`
	// A short description of any further rules, for display beside the input.
	Description string `json:"description"`
	// Maximum length in characters.
	MaxLength int `json:"max_length"`
	// Minimum length in characters.
	MinLength int `json:"min_length"`
}

PasswordRules: Password constraints, published so a form can validate locally.

type PerpMarket

type PerpMarket struct {
	// The provider's coin name, e.g. `BTC` or `kPEPE`.
	Coin        string `json:"coin"`
	FundingRate Amount `json:"funding_rate"`
	MarkPrice   Amount `json:"mark_price"`
	// The highest leverage allowed.
	MaxLeverage  int     `json:"max_leverage"`
	MidPrice     *Amount `json:"mid_price,omitempty"`
	OpenInterest Amount  `json:"open_interest"`
	OraclePrice  Amount  `json:"oracle_price"`
	Price24hAgo  Amount  `json:"price_24h_ago"`
	// Decimal places a size may have.
	SizeDecimals int    `json:"size_decimals"`
	Volume24h    Amount `json:"volume_24h"`
}

PerpMarket: One listed perpetual market and its current figures.

type PlaceOrderRequest

type PlaceOrderRequest struct {
	// Your own identifier. Unique per account.
	ClientOrderID *string   `json:"client_order_id,omitempty"`
	Price         *Amount   `json:"price,omitempty"`
	Quantity      *Amount   `json:"quantity,omitempty"`
	QuoteQuantity *Amount   `json:"quote_quantity,omitempty"`
	Side          OrderSide `json:"side"`
	StopPrice     *Amount   `json:"stop_price,omitempty"`
	// Market symbol.
	Symbol           string            `json:"symbol"`
	TimeInForce      *TimeInForce      `json:"time_in_force,omitempty"`
	TriggerDirection *TriggerDirection `json:"trigger_direction,omitempty"`
	Type             OrderType         `json:"type"`
}

PlaceOrderRequest: Places an order.

Set `client_order_id` to make a retry safe: it is unique per account, so a repeat is refused before any funds move, and `GET /trading/orders/by-client-id/{client_order_id}` recovers the outcome. `Idempotency-Key` is not honoured for orders.

type PlaceOrderResponse

type PlaceOrderResponse struct {
	// Fills produced on entry, oldest first.
	Fills []Fill `json:"fills"`
	Order Order  `json:"order"`
}

PlaceOrderResponse: The result of placing an order, including anything it executed immediately.

type PlaceOrderResult

type PlaceOrderResult struct {
	PlaceOrderResponse
	// The client_order_id that was sent (generated when you did not set one).
	ClientOrderID string
	// True when the POST failed ambiguously and the order was then found by ClientOrderID.
	// Fills is empty then; use Trades for the executions.
	Recovered bool
}

PlaceOrderResult is what PlaceOrder returns.

type PlaceOrdersItem

type PlaceOrdersItem struct {
	ClientOrderID    *string           `json:"client_order_id,omitempty"`
	Side             OrderSide         `json:"side"`
	Type             OrderType         `json:"type"`
	Quantity         *Amount           `json:"quantity,omitempty"`
	Price            *Amount           `json:"price,omitempty"`
	QuoteQuantity    *Amount           `json:"quote_quantity,omitempty"`
	StopPrice        *Amount           `json:"stop_price,omitempty"`
	TimeInForce      *TimeInForce      `json:"time_in_force,omitempty"`
	TriggerDirection *TriggerDirection `json:"trigger_direction,omitempty"`
}

PlaceOrdersItem is one order of PlaceOrders: a PlaceOrderRequest without the symbol. A nil ClientOrderID is generated (a UUID); one you set must be 1 to 64 characters of A-Z a-z 0-9 _ - . : (an empty one is refused).

type Pool

type Pool struct {
	BaseReserve Amount `json:"base_reserve"`
	// When the pool was created.
	CreatedAt time.Time `json:"created_at"`
	// The pool's fee, in percent, priced into every quote it rests.
	FeePercent string `json:"fee_percent"`
	// Identifier.
	ID string `json:"id"`
	// Ladder steps per side.
	LadderSteps       int        `json:"ladder_steps"`
	Price             *Amount    `json:"price,omitempty"`
	QuoteReserve      Amount     `json:"quote_reserve"`
	SharesOutstanding Amount     `json:"shares_outstanding"`
	Status            PoolStatus `json:"status"`
	// Market the pool quotes.
	Symbol string `json:"symbol"`
}

Pool: A pool as a client sees it.

Reserves are the custody account's balances, so they include liquidity currently locked in resting orders. `price` is the curve's mid, which sits between the pool's own best bid and ask by exactly its fee — it is not a traded price.

type PoolID

type PoolID = string

PoolID: Unique identifier of a liquidity pool.

An alias of string: its format is not checked, so a future format keeps working.

type PoolStatus

type PoolStatus string

PoolStatus: Whether a pool quotes, and whether it accepts new liquidity.

The type is open: values added to the API later decode without error.

const (
	PoolStatusActive  PoolStatus = "active"
	PoolStatusPaused  PoolStatus = "paused"
	PoolStatusClosing PoolStatus = "closing"
)

type PoolsService

type PoolsService struct {
	// contains filtered or unexported fields
}

PoolsService: liquidity pools. Join and Exit need an API key with the trade scope.

func (*PoolsService) Exit

func (s *PoolsService) Exit(ctx context.Context, symbol string, req ExitPoolRequest, opts ...CallOption) (ExitPoolResult, error)

Exit removes liquidity. The Idempotency-Key makes retries safe.

func (*PoolsService) Get

func (s *PoolsService) Get(ctx context.Context, symbol string, opts ...CallOption) (Pool, error)

Get returns one pool.

func (*PoolsService) Join

func (s *PoolsService) Join(ctx context.Context, symbol string, req JoinPoolRequest, opts ...CallOption) (JoinPoolResult, error)

Join adds liquidity. Amounts are decimal strings. The Idempotency-Key (generated, or set with WithIdempotencyKey) makes retries safe.

func (*PoolsService) List

func (s *PoolsService) List(ctx context.Context, opts ...CallOption) ([]Pool, error)

List returns every pool.

type Position

type Position struct {
	// Coin.
	Coin             string  `json:"coin"`
	EntryPrice       *Amount `json:"entry_price,omitempty"`
	FundingSinceOpen Amount  `json:"funding_since_open"`
	// Leverage.
	Leverage int `json:"leverage"`
	// `cross` or `isolated`.
	LeverageType     string  `json:"leverage_type"`
	LiquidationPrice *Amount `json:"liquidation_price,omitempty"`
	MarginUsed       Amount  `json:"margin_used"`
	PositionValue    Amount  `json:"position_value"`
	ReturnOnEquity   Amount  `json:"return_on_equity"`
	Size             Amount  `json:"size"`
	UnrealizedPnl    Amount  `json:"unrealized_pnl"`
}

Position: One open position.

type Positions

type Positions struct {
	AccountValue      Amount `json:"account_value"`
	MaintenanceMargin Amount `json:"maintenance_margin"`
	MarginUsed        Amount `json:"margin_used"`
	// The open positions.
	Positions     []Position `json:"positions"`
	TotalNotional Amount     `json:"total_notional"`
}

Positions: A margin summary and the open positions.

type PublicTrade

type PublicTrade struct {
	// Trade id.
	ID       string `json:"id"`
	Price    Amount `json:"price"`
	Quantity Amount `json:"quantity"`
	// Gapless per-market sequence.
	Sequence int64     `json:"sequence"`
	Side     OrderSide `json:"side"`
	// When it executed.
	Timestamp time.Time `json:"timestamp"`
}

PublicTrade: A public trade.

Deliberately anonymous: no account identifiers, and no indication of which side was the resting order beyond the aggressor direction.

type RateLimitState

type RateLimitState struct {
	RequestsPerMinute float64
	Tokens            float64
	BlockedUntil      time.Time
}

RateLimitState is a snapshot of the client-side rate limiter.

type ResyncReason

type ResyncReason string

ResyncReason says why state may have been missed.

const (
	ResyncConcurrentModification ResyncReason = "concurrent_modification"
	ResyncReconnect              ResyncReason = "reconnect"
	// ResyncReauth: private channels were re-subscribed after the server signed the
	// connection out or switched it to another account; refetch private state through REST.
	ResyncReauth ResyncReason = "reauth"
	// ResyncSequenceGap: a private channel skipped sequence numbers (see OnSequenceGap).
	ResyncSequenceGap ResyncReason = "sequence_gap"
	// ResyncBalancesResync: balances.resync, the server could not resume its balance change stream.
	ResyncBalancesResync ResyncReason = "balances_resync"
	// ResyncDepositsResync: deposits.resync: refetch the deposit list.
	ResyncDepositsResync ResyncReason = "deposits_resync"
	// ResyncWithdrawalsResync: withdrawals.resync: refetch the withdrawal list.
	ResyncWithdrawalsResync ResyncReason = "withdrawals_resync"
)

type RetryInfo

type RetryInfo struct {
	Operation      OperationID
	Method, Path   string
	Attempt        int // 1 for the first retry
	Delay          time.Duration
	Err            error
	IdempotencyKey string
}

RetryInfo is passed to Options.OnRetry before the SDK waits and retries. It never holds credentials.

type SequenceGap

type SequenceGap struct {
	Channel  string
	Expected int64
	Received int64
}

SequenceGap is passed to OnSequenceGap.

type ServerTime

type ServerTime struct {
	// Current time in milliseconds since the Unix epoch.
	EpochMs int64 `json:"epoch_ms"`
	// Current time as RFC 3339 with an explicit UTC offset.
	Iso string `json:"iso"`
}

ServerTime: The server's clock.

Two-factor codes are time-based, so a client can compare its own clock against this before a skewed clock gets a correct code rejected.

func (ServerTime) Time

func (t ServerTime) Time() (time.Time, error)

Time parses the server's RFC 3339 time.

type SessionRevoked

type SessionRevoked struct {
	SessionID *string `json:"session_id"`
	Reason    string  `json:"reason"`
	Current   bool    `json:"current"`
}

SessionRevoked is the data of session.revoked on the account channel.

type SortDirection

type SortDirection string

SortDirection: Sort direction for a paginated listing.

The type is open: values added to the API later decode without error.

const (
	SortDirectionAsc  SortDirection = "asc"
	SortDirectionDesc SortDirection = "desc"
)

type SubAccount

type SubAccount struct {
	// Always `false`. A sub-account has no withdrawal path — stated explicitly so a client does not have to infer it.
	CanWithdraw bool `json:"can_withdraw"`
	// When it was created.
	CreatedAt time.Time `json:"created_at"`
	// Opaque identifier. Use it to transfer funds and to issue API keys.
	ID string `json:"id"`
	// Whether it may trade.
	IsActive bool `json:"is_active"`
	// The label given at creation.
	Label string `json:"label"`
}

SubAccount: A sub-account.

type SubscribeRefusal

type SubscribeRefusal struct {
	Channel string
	Err     *WSError
}

SubscribeRefusal is a channel the server refused (an error frame with the subscribe's id). It is also the error OnError reports when an automatic re-subscribe (after a reconnect, a re-auth or futures.resync on futures.account) is refused; errors.As finds the *WSError in it.

func (*SubscribeRefusal) Error

func (r *SubscribeRefusal) Error() string

func (*SubscribeRefusal) Unwrap

func (r *SubscribeRefusal) Unwrap() error

type SubscribeResult

type SubscribeResult struct {
	// Channels the server confirmed as newly added.
	Added []string
	// Channels refused locally because the subscription cap was reached.
	Refused []string
	// Channels already held (nothing was sent for them).
	AlreadySubscribed []string
	// Channels the server refused, each with its error frame. They are not held and not retried.
	RefusedByServer []SubscribeRefusal
}

SubscribeResult is what Subscribe did.

type TimeInForce

type TimeInForce string

TimeInForce: How long an order remains eligible to match.

The type is open: values added to the API later decode without error.

const (
	TimeInForceGtc      TimeInForce = "gtc"
	TimeInForceIoc      TimeInForce = "ioc"
	TimeInForceFok      TimeInForce = "fok"
	TimeInForcePostOnly TimeInForce = "post_only"
)

type TradeHistoryParams

type TradeHistoryParams struct {
	// Limit to one market.
	Symbol *string
	// Opaque cursor from a previous response's `next_cursor`. Omit for the first page.
	Cursor *string
	// Maximum items to return. Clamped to `MAX_LIMIT`.
	Limit *int
	// Sort direction. Defaults to newest-first.
	Direction *SortDirection
}

TradeHistoryParams holds the query parameters of trade_history. Nil pointers are not sent.

type TradeID

type TradeID = string

TradeID: Unique identifier of a trade.

An alias of string: its format is not checked, so a future format keeps working.

type TradesParams deprecated

type TradesParams = FuturesTradesParams

Deprecated: use FuturesTradesParams.

type TradingService

type TradingService struct {
	// contains filtered or unexported fields
}

TradingService: orders and your trades. Placing and cancelling need the trade scope.

func (*TradingService) AllOrderHistory

func (s *TradingService) AllOrderHistory(ctx context.Context, params *OrderHistoryParams, opts ...IterOption) iter.Seq2[Order, error]

AllOrderHistory iterates over every past order.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	cexy "github.com/cexyio/cexy-go"
)

func main() {
	ctx := context.Background()
	c, _ := cexy.New(cexy.Options{APIKey: os.Getenv("CEXY_API_KEY"), APISecret: os.Getenv("CEXY_API_SECRET")})
	for order, err := range c.Trading.AllOrderHistory(ctx, &cexy.OrderHistoryParams{Symbol: cexy.Ptr("BTC/USDT")},
		cexy.WithMaxItems(500)) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(order.ID, order.Status)
	}
}

func (*TradingService) AllTrades

func (s *TradingService) AllTrades(ctx context.Context, params *TradeHistoryParams, opts ...IterOption) iter.Seq2[Fill, error]

AllTrades iterates over every execution.

func (*TradingService) CancelAll

func (s *TradingService) CancelAll(ctx context.Context, symbol string, opts ...CallOption) (CancelAllResult, error)

CancelAll cancels every open order in one market, such as "BTC/USDT", in one request, including stop orders that have not triggered yet (status pending_trigger). An empty symbol is an error, so an account-wide cancel never happens by accident; use CancelAllMarkets for that. An unknown symbol is an APIError matching ErrNotFound.

One call handles at most 500 orders. Every order it handled is in exactly one of Cancelled, AlreadyClosed (it closed on its own first: not a failure) and Failed (with the reason in Failures; INVALID_STATE means an order taken off the book that cannot be cancelled yet). A pending order is cancelled at once by the server. HasMore means there are more: call again, or use CancelAllUntilDone.

The server limits cancel-all to 30 calls a minute per account (ErrRateLimited, retried after the server's wait by the normal retry policy). It is naturally repeatable, so it is retried after connection errors; a retry reports only what that retry did. No Idempotency-Key is sent: the server does not honour one here.

func (*TradingService) CancelAllAfter

func (s *TradingService) CancelAllAfter(ctx context.Context, symbol string, timeout time.Duration, opts ...CallOption) (CancelAllAfter, error)

CancelAllAfter arms, re-arms or disarms the dead-man switch for one market, such as "BTC/USDT": if it is not armed again within timeout, the server cancels every open order in that market. A timeout of exactly 0 disarms the switch. An empty or blank symbol is a ConfigError (the server would read it as "every market"); use CancelAllAfterMarkets for that.

timeout must be a whole number of milliseconds: a negative one, a non-zero one below 1 ms and a fractional one are a ConfigError, so a non-zero timeout never turns into 0 (which would disarm). The SDK checks nothing else: the server owns the range (5000 to 600000 ms, else ErrValidation).

A market maker should arm about every 2 seconds with a 10 second timeout. Take the local deadline from the moment the call started (not when it returned) and never compare the local clock with the returned Deadline: use ServerTime to measure it. When the switch fires it is cleared, so quoting again needs a new arm. The per-market switch and the all-markets switch are separate and each fires on its own. A disarm (0) only switches off the scope it names.

Repeating an arm is harmless, so it is retried after connection errors like CancelAll. An arm still in flight can land after a later disarm and re-arm it: if the switch must be off, disarm once more after any retried arm. No endpoint reads the switch.

A house account that places an order without an armed switch gets DEAD_MAN_NOT_ARMED (ErrDeadManNotArmed, also ErrConflict, never retryable) from PlaceOrder: stop quoting, arm, and do not retry the placement blindly.

func (*TradingService) CancelAllAfterMarkets

func (s *TradingService) CancelAllAfterMarkets(ctx context.Context, timeout time.Duration, opts ...CallOption) (CancelAllAfter, error)

CancelAllAfterMarkets is CancelAllAfter for the all-markets switch: it sends an explicit "symbol": null. It is separate from the per-market switches. See CancelAllAfter.

func (*TradingService) CancelAllMarkets

func (s *TradingService) CancelAllMarkets(ctx context.Context, opts ...CallOption) (CancelAllResult, error)

CancelAllMarkets cancels every open order in EVERY market, in one request. See CancelAll.

func (*TradingService) CancelAllUntilDone

func (s *TradingService) CancelAllUntilDone(ctx context.Context, o CancelAllOptions, opts ...CallOption) (CancelAllSummary, error)

CancelAllUntilDone repeats cancel-all until nothing is left to do: while HasMore is set, or while a failure code is SERVICE_UNAVAILABLE, MARKET_UNAVAILABLE or CONCURRENT_MODIFICATION. INVALID_STATE (an order taken off the book that cannot be cancelled yet) is not retried: it is returned in the summary. A pending order is cancelled at once by the server.

Each round is exactly one HTTP request: the loop owns the retries, so it never sends more than MaxRounds requests. After a round with no progress (nothing cancelled or already closed) it waits 1, 2, 4, 8, then 15 s before the next call; any progress resets the wait. A round that fails with a retryable error counts as a round without progress: after a 429 the loop waits the server's Retry-After exactly (without advancing the back-off), after any other retryable error the next back-off step. It never takes a wait that would bring the elapsed time to or past TimeBudget, or a server wait above MaxServerWait: it stops with CancelStoppedTimeBudget (and LastErrorCode when the last round failed). It also stops after MaxRounds requests. A market that stays down (MARKET_UNAVAILABLE) makes the loop return only when the time budget ends. Failure codes other than SERVICE_UNAVAILABLE, MARKET_UNAVAILABLE and CONCURRENT_MODIFICATION are returned in the summary, never retried.

A non-retryable error (or a cancelled ctx) is returned with the summary so far.

func (*TradingService) CancelOrder

func (s *TradingService) CancelOrder(ctx context.Context, orderID string, opts ...CallOption) (Order, error)

CancelOrder cancels one order (needs the trade scope). It is retried on connection errors and retryable responses. If a RETRY gets INVALID_STATE (the order is no longer open, typically because the first attempt did cancel it), the cancel is treated as done and the order is fetched and returned. INVALID_STATE on the first attempt is returned as an error (for example, the order was already filled).

func (*TradingService) CancelOrderByClientID

func (s *TradingService) CancelOrderByClientID(ctx context.Context, clientOrderID string, opts ...CallOption) (Order, error)

CancelOrderByClientID cancels one order named by your client_order_id (needs the trade scope). It is retried like CancelOrder: if a RETRY gets INVALID_STATE, the order is fetched by client_order_id and returned (check its Status). The id is sent percent-encoded as one path segment.

func (*TradingService) CancelOrders

func (s *TradingService) CancelOrders(ctx context.Context, entries []CancelBatchItem, opts ...CallOption) (BatchCancelResult, error)

CancelOrders cancels 1 to 50 orders (needs the trade scope), each named by exactly one of OrderID and ClientOrderID, one after another in order; a failure does not stop the rest.

It is retried like CancelOrder: after a lost answer, an entry refused with INVALID_STATE (an earlier attempt may have cancelled it) is looked up once and comes back OutcomeRecovered with its current Status, or OutcomeUnknown if the lookup fails. Results are in request order. A 2xx answer that is not usable (no data, undecodable, or results whose count, index, order id or client order id do not match the entries) is an error matching ErrBadResponse.

func (*TradingService) OpenOrders

func (s *TradingService) OpenOrders(ctx context.Context, params *ListOpenOrdersParams, opts ...CallOption) ([]Order, error)

OpenOrders returns open orders, optionally filtered by market or status.

func (*TradingService) Order

func (s *TradingService) Order(ctx context.Context, orderID string, opts ...CallOption) (Order, error)

Order returns one order.

func (*TradingService) OrderByClientID

func (s *TradingService) OrderByClientID(ctx context.Context, clientOrderID string, opts ...CallOption) (Order, error)

OrderByClientID returns the order with your client_order_id.

func (*TradingService) OrderHistory

func (s *TradingService) OrderHistory(ctx context.Context, params *OrderHistoryParams, opts ...CallOption) (*Page[Order], error)

OrderHistory returns one page of past orders.

func (*TradingService) PlaceOrder

func (s *TradingService) PlaceOrder(ctx context.Context, order PlaceOrderRequest, opts ...CallOption) (PlaceOrderResult, error)

PlaceOrder places a REAL order (needs the trade scope). Amounts are decimal strings.

Retry safety rests on client_order_id (a UUID is generated when absent): it is unique per account, and the server refuses a repeat before any funds move. No Idempotency-Key is sent: the server does not honour one on orders. After an ambiguous failure (connection error, timeout or 5xx) the SDK first looks the order up by client_order_id and returns it if it exists (Recovered); only if it does not exist is the order sent again, with the same client_order_id, so a late first attempt makes the resend fail as a duplicate, which the lookup resolves again. It returns *OrderStateUnknownError when even the lookup fails.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	cexy "github.com/cexyio/cexy-go"
)

func main() {
	ctx := context.Background()
	c, err := cexy.New(cexy.Options{APIKey: os.Getenv("CEXY_API_KEY"), APISecret: os.Getenv("CEXY_API_SECRET")})
	if err != nil {
		log.Fatal(err)
	}
	placed, err := c.Trading.PlaceOrder(ctx, cexy.PlaceOrderRequest{
		Symbol:   "BTC/USDT",
		Side:     cexy.OrderSideBuy,
		Type:     cexy.OrderTypeLimit,
		Price:    cexy.Ptr(cexy.Amount("60000.00")),
		Quantity: cexy.Ptr(cexy.Amount("0.0010")),
	})
	var apiErr *cexy.APIError
	switch {
	case errors.As(err, &apiErr) && apiErr.Code == cexy.CodeInsufficientFunds:
		log.Println("not enough funds:", apiErr.Details)
	case err != nil:
		log.Fatal(err)
	default:
		fmt.Println(placed.Order.ID, placed.ClientOrderID, placed.Recovered)
	}
}

func (*TradingService) PlaceOrders

func (s *TradingService) PlaceOrders(ctx context.Context, symbol string, orders []PlaceOrdersItem, opts ...CallOption) (BatchPlaceResult, error)

PlaceOrders places 1 to 20 REAL orders in one market (needs the trade scope), each on its own and in order: the batch is not atomic, and one refusal does not stop the rest. Amounts are decimal strings.

A ClientOrderID (a UUID) is generated for each order without one (nil); your own ids must be 1 to 64 characters of A-Z a-z 0-9 _ - . :, not "." or "..", and distinct within the batch (a *ConfigError before anything is sent). The ids sent are in the results. To reconcile after any failure, even a process crash, create and save your own ids first (NewClientOrderID).

Retry safety: the body, ids included, is built once and every retry resends it unchanged. The server refuses an id it already placed, so nothing is placed twice: after a lost answer (a connection error after sending, or any 5xx except 501 and 503) such an order comes back OutcomeRecovered with its OrderID and Status, read from the refusal's details or, when they are missing, looked up once by client_order_id (OutcomeUnknown if that fails). An item refused with an order id in its details (MARKET_UNAVAILABLE when the market stopped while matching, for example) exists, so it comes back OutcomeRecovered too; an item INTERNAL error is looked up once. Results are in request order. Res.Unknown > 0 means some orders' state could not be read: look them up with Trading.OrderByClientID before placing anything again.

Errors: once the body is built, every failure is a *BatchPlaceError with all the ids sent and MaybePlaced (false only if no attempt can have been acted on). A refusal of the whole batch (400, 403, 404) is not retried; it placed nothing in that attempt, but an earlier ambiguous attempt may have. A batch larger than the key's whole budget (400 with a number in Details["limit"]) must be split by the caller. A 429 is waited out and the same body resent.

func (*TradingService) Trades

func (s *TradingService) Trades(ctx context.Context, params *TradeHistoryParams, opts ...CallOption) (*Page[Fill], error)

Trades returns one page of your executions.

type TriggerDirection

type TriggerDirection string

TriggerDirection: Which way the price must move for a stop to fire.

Explicit rather than inferred from the side, because the inference is ambiguous: a sell stop below the market is a stop-loss, and a sell stop above it is a take-profit. Both are legitimate, and guessing wrong means an order that fires at exactly the wrong moment — which is the one thing a protective order must never do.

The type is open: values added to the API later decode without error.

const (
	TriggerDirectionAbove TriggerDirection = "above"
	TriggerDirectionBelow TriggerDirection = "below"
)

type UserID

type UserID = string

UserID: Unique identifier of a user account.

An alias of string: its format is not checked, so a future format keeps working.

type WSClock

type WSClock interface {
	Now() time.Time
	AfterFunc(d time.Duration, f func()) WSTimer
}

WSClock is a TEST-ONLY time source for the reorder-window timer and LiveBalances scheduling (minimum snapshot interval, retry backoff). Socket timeouts always use the real clock. Leave WSOptions.Clock nil in production.

type WSError

type WSError struct {
	Code    string
	Message string
	// True when it came from a server error frame (not a local guard or a disconnect).
	FromServer bool
	// Channel is the channel a server error frame names (a refused subscribe); empty when the
	// frame has none and for local errors.
	Channel string
	// Details is the frame's "details" object; empty when absent or not an object.
	Details map[string]any
	// RetryAfter is details.retry_after_seconds when it is a non-negative number; 0 otherwise.
	// The client does not retry on it by itself.
	RetryAfter time.Duration
}

WSError is a WebSocket protocol error, a server error frame (FromServer), or a local guard.

func (*WSError) Error

func (e *WSError) Error() string

type WSHandlers

type WSHandlers struct {
	OnWelcome func(Welcome)
	// Every known event (ticker.update, orderbook.update, order.*, ...).
	OnEvent        func(Event)
	OnSubscribed   func(channels []string)
	OnUnsubscribed func(channels []string)
	// The authenticated acknowledgement (after Auth or the automatic re-auth on reconnect).
	OnAuthenticated func(userID string)
	// id is empty for the server's own pongs.
	OnPong func(id string)
	// An error frame from the server.
	OnServerError func(*WSError)
	// Transport problems and failed automatic re-subscriptions or re-authentications.
	OnError        func(error)
	OnClose        func(CloseInfo)
	OnReconnecting func(attempt int, delay time.Duration)
	// Reconnected, re-authenticated (if a token was held) and re-subscribed.
	OnReconnected func(Welcome)
	// State may have been missed: refetch anything you keep from private or public channels.
	OnResync func(ResyncReason)
	// session.revoked arrived for this connection's own session (current true): private
	// channels are dead. The socket stays open and public channels keep working. Call Auth with
	// a new token to restore private channels.
	OnAuthLost func(Event)
	// The server ended this connection's private subscriptions: Auth succeeded as another
	// user, an Auth failed, or this connection's own session was revoked.
	OnAuthChanged func(AuthChange)
	// A private channel skipped sequence numbers on this connection (after the reorder window):
	// events were lost. Followed by OnResync(ResyncSequenceGap); refetch that channel's state.
	OnSequenceGap func(SequenceGap)
	// futures.resync arrived on channel: data on it may have been missed; refetch it over REST
	// (the event itself also goes to OnEvent). Public futures channels stay subscribed. For
	// futures.account the client then unsubscribes and subscribes again by itself (the server's
	// poller stopped); a refusal of that subscribe is reported (OnServerError, and OnError as a
	// *SubscribeRefusal): UNAUTHENTICATED puts it back to pending, any other code drops it.
	OnFuturesResync func(channel string)
}

WSHandlers are optional callbacks. They run one at a time on a dedicated goroutine, in frame order, so they may call Subscribe, Auth and the other methods. Keep them quick: frames queue up while a handler runs.

type WSKeySigner

type WSKeySigner interface {
	SignWebSocketChallenge(connectionID, challenge string) (keyID, signature string)
}

WSKeySigner signs a WebSocket auth_key challenge (an *HMACAuthenticator fits).

type WSOptions

type WSOptions struct {
	// Default DefaultWebSocketURL. Must be wss:// (see AllowInsecure).
	URL string
	// Allow ws://, but ONLY for localhost, 127.0.0.1 or ::1 (local test servers).
	AllowInsecure bool
	// Client ping cadence, required by the server (it closes connections silent for 90 s).
	// Default 30 s; at most 60 s (NewWebSocket refuses a longer one with a *ConfigError).
	PingInterval time.Duration
	// Reconnect when no frame arrives for this long. Default 75 s.
	LivenessTimeout time.Duration
	// Default 10 s.
	WelcomeTimeout time.Duration
	// How long Subscribe, Unsubscribe, Auth and Ping wait for the acknowledgement. Default 5 s.
	AckTimeout time.Duration
	// Disables automatic reconnection.
	NoReconnect bool
	// Reconnect backoff: full jitter from ReconnectBaseDelay (default 1 s), doubling up to
	// ReconnectMaxDelay (default 30 s). MaxReconnectAttempts 0 means unlimited.
	ReconnectBaseDelay   time.Duration
	ReconnectMaxDelay    time.Duration
	MaxReconnectAttempts int
	// Local subscription cap. Default 100 (the server's limit).
	MaxSubscriptions int
	// Local cap on client messages per fixed minute. Default 200 (the server closes above 240).
	MaxMessagesPerMinute int
	// Sent as the User-Agent of the handshake. Client.WebSocket sets the SDK's.
	UserAgent string
	// Used for the handshake. Default http.DefaultClient. The SDK uses a copy with redirects
	// disabled; the client you pass is not modified.
	HTTPClient *http.Client
	// Default slog.Default().
	Logger   *slog.Logger
	Handlers WSHandlers
	// Private channels with several publishers (orders, account) can deliver two adjacent frames
	// swapped: a missing sequence number gets this long to arrive before it counts as a gap.
	// 0 selects the default, 250 ms; NoReorderWindow reports a gap at once.
	ReorderWindow time.Duration
	// TEST-ONLY: see WSClock.
	Clock WSClock
	// Signs AuthKey challenges (API-key authentication). Client.WebSocket sets it when
	// the client uses Auth "hmac".
	KeySigner WSKeySigner
	// contains filtered or unexported fields
}

WSOptions configures a WebSocket.

type WSTimer

type WSTimer interface{ Stop() bool }

WSTimer is a stoppable timer (a *time.Timer fits).

type WalletService

type WalletService struct {
	// contains filtered or unexported fields
}

WalletService: wallet reads. API keys can never withdraw or transfer; there are no such methods.

func (*WalletService) AllDeposits

func (s *WalletService) AllDeposits(ctx context.Context, params *ListDepositsParams, opts ...IterOption) iter.Seq2[Deposit, error]

AllDeposits iterates over every deposit.

func (*WalletService) AllWithdrawals

func (s *WalletService) AllWithdrawals(ctx context.Context, params *ListWithdrawalsParams, opts ...IterOption) iter.Seq2[Withdrawal, error]

AllWithdrawals iterates over every withdrawal.

func (*WalletService) Deposit

func (s *WalletService) Deposit(ctx context.Context, depositID string, opts ...CallOption) (Deposit, error)

Deposit returns one deposit.

func (*WalletService) DepositAddress

func (s *WalletService) DepositAddress(ctx context.Context, params DepositAddressParams, opts ...CallOption) (DepositAddress, error)

DepositAddress returns your deposit address for an asset on a network.

Side effect: the first call for an asset and network CREATES the address, and it is permanent; later calls return the same address. Always send the memo too when the response has one, or the deposit may be unrecoverable.

func (*WalletService) Deposits

func (s *WalletService) Deposits(ctx context.Context, params *ListDepositsParams, opts ...CallOption) (*Page[Deposit], error)

Deposits returns one page of deposits.

func (*WalletService) Withdrawal

func (s *WalletService) Withdrawal(ctx context.Context, withdrawalID string, opts ...CallOption) (Withdrawal, error)

Withdrawal returns one withdrawal.

func (*WalletService) WithdrawalAddresses

func (s *WalletService) WithdrawalAddresses(ctx context.Context, opts ...CallOption) ([]WithdrawalAddress, error)

WithdrawalAddresses returns the saved withdrawal addresses.

func (*WalletService) Withdrawals

func (s *WalletService) Withdrawals(ctx context.Context, params *ListWithdrawalsParams, opts ...CallOption) (*Page[Withdrawal], error)

Withdrawals returns one page of withdrawals.

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

WebSocket is the CEXY.io WebSocket client: heartbeat, liveness, subscriptions with local limits, automatic reconnect with re-auth and re-subscribe, and live order books. It is safe for concurrent use.

Private channels need Auth with a session access token, or AuthKey with an API key (on a client that signs requests: Options.Auth "hmac", the default).

func NewWebSocket

func NewWebSocket(opts WSOptions) (*WebSocket, error)

NewWebSocket checks the options. Call Connect to open the connection.

func (*WebSocket) Auth

func (w *WebSocket) Auth(ctx context.Context, token string) (AuthResult, error)

Auth authenticates private channels with a session access token. It returns on the server's authenticated acknowledgement; it fails on an error frame with the request id (the token is then forgotten) or when no acknowledgement arrives within AckTimeout. The token is kept in memory and re-sent after each reconnect. When not connected, the token is queued and Queued is true. (For an API key, use AuthKey.)

func (*WebSocket) AuthKey

func (w *WebSocket) AuthKey(ctx context.Context) (AuthResult, error)

AuthKey authenticates with the client's API key. It signs the server's single-use challenge; the secret never leaves the process. After a reconnect it signs the new connection's challenge automatically. A refused auth_key stops the automatic re-auth (the server closes the socket after 5 failures). It needs WSOptions.KeySigner (Client.WebSocket sets it when the client uses Auth "hmac").

func (*WebSocket) Channels

func (w *WebSocket) Channels() []string

Channels returns the channels currently held (restored after every reconnect).

func (*WebSocket) Close

func (w *WebSocket) Close() error

Close closes the connection for good (no reconnect).

func (*WebSocket) Connect

func (w *WebSocket) Connect(ctx context.Context) (Welcome, error)

Connect opens the connection and returns the server's welcome frame. After it succeeds, dropped connections are reopened automatically until Close (unless NoReconnect).

func (*WebSocket) Connected

func (w *WebSocket) Connected() bool

Connected reports whether the connection is open and welcomed.

func (*WebSocket) HasToken

func (w *WebSocket) HasToken() bool

HasToken reports whether a session token is kept for automatic re-authentication. A refused token and a revoked session are forgotten.

func (*WebSocket) LiveBalances

func (w *WebSocket) LiveBalances(ctx context.Context, opts LiveBalancesOptions) (*LiveBalances, error)

LiveBalances subscribes balances and returns a LiveBalances that follows them. Call Auth first.

func (*WebSocket) OrderBook

func (w *WebSocket) OrderBook(ctx context.Context, symbol string, opts LiveOrderBookOptions) (*LiveOrderBook, error)

OrderBook returns a live order book for symbol that follows the sync rules: subscribe first, then take a REST snapshot (sequence S); drop updates with sequence <= S; each update replaces the top 50 levels; a gap marks the book stale until the next update; a fresh snapshot after every reconnect and after CONCURRENT_MODIFICATION. It returns after the first snapshot. It needs a WebSocket made by Client.WebSocket.

Example
package main

import (
	"context"
	"fmt"
	"log"

	cexy "github.com/cexyio/cexy-go"
)

func main() {
	ctx := context.Background()
	c, _ := cexy.New(cexy.Options{})
	ws, err := c.WebSocket(cexy.WSOptions{Handlers: cexy.WSHandlers{
		OnResync: func(cexy.ResyncReason) { log.Println("resync: refetch derived state") },
	}})
	if err != nil {
		log.Fatal(err)
	}
	if _, err := ws.Connect(ctx); err != nil {
		log.Fatal(err)
	}
	defer ws.Close()
	book, err := ws.OrderBook(ctx, "BTC/USDT", cexy.LiveOrderBookOptions{
		OnUpdate: func(b cexy.BookSnapshot) {
			bid, _, ask, _ := b.Best()
			fmt.Println(bid.Price, ask.Price, b.Stale)
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer book.Close()
}

func (*WebSocket) PendingChannels

func (w *WebSocket) PendingChannels() []string

PendingChannels returns the private channels held until the next successful Auth or AuthKey: futures.account subscribed while signed out, and private channels dropped by a sign-out.

func (*WebSocket) Ping

func (w *WebSocket) Ping(ctx context.Context) (time.Duration, error)

Ping sends a ping with an id and returns the round-trip time.

func (*WebSocket) Subscribe

func (w *WebSocket) Subscribe(ctx context.Context, channels ...string) (SubscribeResult, error)

Subscribe subscribes to channels such as "ticker:BTC/USDT" and "trades:BTC/USDT", and returns when the server confirms. Channels beyond MaxSubscriptions are refused locally. When not connected, channels are queued and subscribed on connect.

Channels the server refuses are listed in RefusedByServer with their error frames; they are not held and not retried. The error is non-nil only when every channel sent was refused (the first refusal), or when no answer came within AckTimeout (TIMEOUT; the channels stay held and are re-subscribed after a reconnect) or the connection dropped. After a reconnect or a re-auth, the client re-subscribes by itself: a private channel refused with UNAUTHENTICATED waits for the next successful auth (PendingChannels); any other refusal drops the channel. Each such refusal goes to OnError as a *SubscribeRefusal.

func (*WebSocket) URL

func (w *WebSocket) URL() string

URL returns the WebSocket URL.

func (*WebSocket) Unsubscribe

func (w *WebSocket) Unsubscribe(ctx context.Context, channels ...string) error

Unsubscribe unsubscribes and returns on the unsubscribed acknowledgement (or after AckTimeout without one); it fails on an error frame with the request id.

func (*WebSocket) UserID

func (w *WebSocket) UserID() string

UserID is the user of the last successful Auth on the current connection ("" when signed out).

func (*WebSocket) Welcome

func (w *WebSocket) Welcome() (Welcome, bool)

Welcome returns the last welcome frame; ok is false before the first connection.

type Welcome

type Welcome struct {
	ProtocolVersion int `json:"protocol_version"`
	// The server's own pong cadence (30), not a client deadline.
	HeartbeatIntervalSeconds int    `json:"heartbeat_interval_seconds"`
	MaxSubscriptions         int    `json:"max_subscriptions"`
	ConnectionID             string `json:"connection_id"`
	// Single-use challenge for AuthKey (API-key authentication).
	Challenge string `json:"challenge,omitempty"`
}

Welcome is the server's first frame on every connection.

type Withdrawal

type Withdrawal struct {
	// Destination.
	Address string `json:"address"`
	Amount  Amount `json:"amount"`
	// Asset symbol.
	Asset string `json:"asset"`
	// When it was broadcast.
	BroadcastAt *time.Time `json:"broadcast_at,omitempty"`
	// Whether the account holder may still cancel it.
	Cancellable bool `json:"cancellable"`
	// When it confirmed to the required depth.
	CompletedAt *time.Time `json:"completed_at,omitempty"`
	// Confirmations observed.
	Confirmations int `json:"confirmations"`
	// When it was requested.
	CreatedAt time.Time `json:"created_at"`
	// Explorer link, when available.
	ExplorerURL *string `json:"explorer_url,omitempty"`
	Fee         Amount  `json:"fee"`
	// Asset the fee was charged in.
	FeeAsset string `json:"fee_asset"`
	// Transitions this withdrawal has been through.
	History []WithdrawalHistoryEntry `json:"history"`
	// Withdrawal id.
	ID string `json:"id"`
	// Memo, if any.
	Memo *string `json:"memo,omitempty"`
	// Network code.
	Network string           `json:"network"`
	Status  WithdrawalStatus `json:"status"`
	// Transaction hash, once broadcast.
	Txid *string `json:"txid,omitempty"`
}

Withdrawal: A withdrawal.

type WithdrawalAddress

type WithdrawalAddress struct {
	// The address.
	Address string `json:"address"`
	// Asset, when restricted to one.
	Asset *string `json:"asset,omitempty"`
	// When it was saved.
	CreatedAt time.Time `json:"created_at"`
	// Address-book entry id.
	ID string `json:"id"`
	// Your label.
	Label string `json:"label"`
	// When it was last withdrawn to.
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// Memo, if any.
	Memo *string `json:"memo,omitempty"`
	// Network code.
	Network string `json:"network"`
	// Whether ownership has been confirmed.
	Verified bool `json:"verified"`
}

WithdrawalAddress: A saved withdrawal address.

type WithdrawalHistoryEntry

type WithdrawalHistoryEntry struct {
	// When.
	At time.Time `json:"at"`
	// Why, where a reason applies.
	Reason *string          `json:"reason,omitempty"`
	Status WithdrawalStatus `json:"status"`
}

WithdrawalHistoryEntry: One transition in a withdrawal's life.

type WithdrawalID

type WithdrawalID = string

WithdrawalID: Unique identifier of a withdrawal.

An alias of string: its format is not checked, so a future format keeps working.

type WithdrawalStatus

type WithdrawalStatus string

WithdrawalStatus: Lifecycle of an outgoing withdrawal.

`pending_approval` waits for an operator to approve the withdrawal. `broadcast_unknown` means the transaction may have been sent: the funds stay debited until it is resolved against the chain.

The type is open: values added to the API later decode without error.

const (
	WithdrawalStatusRequested        WithdrawalStatus = "requested"
	WithdrawalStatusPendingApproval  WithdrawalStatus = "pending_approval"
	WithdrawalStatusApproved         WithdrawalStatus = "approved"
	WithdrawalStatusProcessing       WithdrawalStatus = "processing"
	WithdrawalStatusBroadcast        WithdrawalStatus = "broadcast"
	WithdrawalStatusCompleted        WithdrawalStatus = "completed"
	WithdrawalStatusRejected         WithdrawalStatus = "rejected"
	WithdrawalStatusCancelled        WithdrawalStatus = "cancelled"
	WithdrawalStatusFailed           WithdrawalStatus = "failed"
	WithdrawalStatusBroadcastUnknown WithdrawalStatus = "broadcast_unknown"
	WithdrawalStatusReverted         WithdrawalStatus = "reverted"
)

Jump to

Keyboard shortcuts

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