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)
}
}
Output:
Index ¶
- Constants
- Variables
- func FuturesCandlesChannel(coin, interval string) (string, error)
- func FuturesOrderBookChannel(coin string) (string, error)
- func FuturesTradesChannel(coin string) (string, error)
- func IsLocalHost(host string) bool
- func NewClientOrderID() string
- func Operations() map[OperationID]OperationInfo
- func Ptr[T any](v T) *T
- type APIError
- type APIKey
- type APIKeyAuthenticator
- func (a *APIKeyAuthenticator) Authenticate(req *http.Request, _ []byte) error
- func (a APIKeyAuthenticator) GoString() string
- func (a APIKeyAuthenticator) KeyHint() string
- func (a *APIKeyAuthenticator) Kind() string
- func (a APIKeyAuthenticator) LogValue() slog.Value
- func (a *APIKeyAuthenticator) Redact(text string) string
- func (a APIKeyAuthenticator) String() string
- type APIScope
- type AccountId
- type AccountMismatchError
- type AccountService
- func (s *AccountService) APIKeys(ctx context.Context, opts ...CallOption) ([]APIKey, error)
- func (s *AccountService) AllLedger(ctx context.Context, params *GetLedgerParams, opts ...IterOption) iter.Seq2[LedgerEntry, error]
- func (s *AccountService) AllNotifications(ctx context.Context, params *ListNotificationsParams, opts ...IterOption) iter.Seq2[Notification, error]
- func (s *AccountService) Balance(ctx context.Context, asset string, opts ...CallOption) (Balance, error)
- func (s *AccountService) Balances(ctx context.Context, opts ...CallOption) ([]Balance, error)
- func (s *AccountService) ID(ctx context.Context, opts ...CallOption) (string, error)
- func (s *AccountService) Ledger(ctx context.Context, params *GetLedgerParams, opts ...CallOption) (*Page[LedgerEntry], error)
- func (s *AccountService) Notifications(ctx context.Context, params *ListNotificationsParams, opts ...CallOption) (*Page[Notification], error)
- func (s *AccountService) SubAccountBalances(ctx context.Context, id string, opts ...CallOption) ([]Balance, error)
- func (s *AccountService) SubAccounts(ctx context.Context, opts ...CallOption) ([]SubAccount, error)
- type Amount
- type Asset
- type AssetNetwork
- type AssetsService
- type AuthChange
- type AuthChangeReason
- type AuthResult
- type Authenticator
- type Balance
- type BatchCancelResult
- type BatchOrder
- type BatchOrderItem
- type BatchOrderOutcome
- type BatchOrderRequest
- type BatchOrderResult
- type BatchOutcome
- type BatchPlaceError
- type BatchPlaceResult
- type BookLevel
- type BookSnapshot
- type CallOption
- type CancelAllAfter
- type CancelAllAfterRequest
- type CancelAllOptions
- type CancelAllRequest
- type CancelAllResult
- type CancelAllSummary
- type CancelBatch
- type CancelBatchItem
- type CancelBatchRequest
- type CancelBatchResult
- type CancelEntryOutcome
- type CancelFailure
- type Candle
- type CandleInterval
- type CandlesParamsdeprecated
- type Client
- func (c *Client) BaseURL() string
- func (c *Client) Config(ctx context.Context, opts ...CallOption) (ExchangeConfig, error)
- func (c *Client) GoString() string
- func (c *Client) HasCredentials() bool
- func (c *Client) RateLimit() (state RateLimitState, ok bool)
- func (c *Client) String() string
- func (c *Client) Time(ctx context.Context, opts ...CallOption) (ServerTime, error)
- func (c *Client) UserAgent() string
- func (c *Client) WebSocket(opts WSOptions) (*WebSocket, error)
- type CloseInfo
- type ConfigError
- type ConnectionError
- type Deposit
- type DepositAddress
- type DepositAddressParams
- type DepositID
- type DepositStatus
- type ErrorBody
- type ErrorCode
- type Event
- type ExchangeConfig
- type ExitPoolRequest
- type ExitPoolResult
- type ExportParams
- type ExportsService
- func (s *ExportsService) Deposits(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)
- func (s *ExportsService) Ledger(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)
- func (s *ExportsService) Orders(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)
- func (s *ExportsService) Trades(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)
- func (s *ExportsService) Withdrawals(ctx context.Context, params *ExportParams, opts ...CallOption) (string, error)
- type FeeSchedule
- type FeesService
- type Fill
- type FillsParamsdeprecated
- type Funding
- type FundingParamsdeprecated
- type FuturesBook
- type FuturesBookUpdate
- type FuturesCandle
- type FuturesCandleUpdate
- type FuturesCandles
- type FuturesCandlesParams
- type FuturesFill
- type FuturesFills
- type FuturesFillsParams
- type FuturesFunding
- type FuturesFundingParams
- type FuturesMarket
- type FuturesMarkets
- type FuturesMids
- type FuturesOpenOrders
- type FuturesOrderbookParams
- type FuturesOrdersUpdate
- type FuturesPositions
- type FuturesPositionsUpdate
- type FuturesPublicTrade
- type FuturesService
- func (s *FuturesService) AllFills(ctx context.Context, opts ...IterOption) iter.Seq2[FuturesFill, error]
- func (s *FuturesService) AllFunding(ctx context.Context, opts ...IterOption) iter.Seq2[Funding, error]
- func (s *FuturesService) Candles(ctx context.Context, coin string, params FuturesCandlesParams, ...) (FuturesCandles, error)
- func (s *FuturesService) Fills(ctx context.Context, cursor string, opts ...CallOption) (FuturesFills, error)
- func (s *FuturesService) Funding(ctx context.Context, cursor string, opts ...CallOption) (FuturesFunding, error)
- func (s *FuturesService) Market(ctx context.Context, coin string, opts ...CallOption) (FuturesMarket, error)
- func (s *FuturesService) Markets(ctx context.Context, opts ...CallOption) (FuturesMarkets, error)
- func (s *FuturesService) OpenOrders(ctx context.Context, opts ...CallOption) (FuturesOpenOrders, error)
- func (s *FuturesService) OrderBook(ctx context.Context, coin string, depth int, opts ...CallOption) (FuturesBook, error)
- func (s *FuturesService) Positions(ctx context.Context, opts ...CallOption) (FuturesPositions, error)
- func (s *FuturesService) Trades(ctx context.Context, coin string, limit int, opts ...CallOption) (FuturesTrades, error)
- type FuturesStatus
- type FuturesTrades
- type FuturesTradesParams
- type FuturesTradesUpdate
- type FuturesTransferID
- type GetCandlesParams
- type GetLedgerParams
- type GetMarketTradesParams
- type GetOrderBookParams
- type HMACAuthenticator
- func (a *HMACAuthenticator) Authenticate(req *http.Request, body []byte) error
- func (a *HMACAuthenticator) ClockOffset() time.Duration
- func (a *HMACAuthenticator) GoString() string
- func (a *HMACAuthenticator) Kind() string
- func (a *HMACAuthenticator) LogValue() slog.Value
- func (a *HMACAuthenticator) Redact(text string) string
- func (a *HMACAuthenticator) SignWebSocketChallenge(connectionID, challenge string) (keyID, signature string)
- func (a *HMACAuthenticator) String() string
- type HeldIncoming
- type InvalidAmountError
- type IterOption
- type JoinPoolRequest
- type JoinPoolResult
- type LedgerEntry
- type LedgerEntryKind
- type LedgerReference
- type LedgerReferenceType
- type Level
- type LiquidityRole
- type ListDepositsParams
- type ListNotificationsParams
- type ListOpenOrdersParams
- type ListWithdrawalsParams
- type LiveBalances
- type LiveBalancesOptions
- type LiveOrderBook
- type LiveOrderBookOptions
- type MaintenanceReason
- type MaintenanceState
- type Market
- type MarketStatus
- type MarketsService
- func (s *MarketsService) AllTrades(ctx context.Context, symbol string, params *GetMarketTradesParams, ...) iter.Seq2[PublicTrade, error]
- func (s *MarketsService) Candles(ctx context.Context, symbol string, params GetCandlesParams, ...) ([]Candle, error)
- func (s *MarketsService) Get(ctx context.Context, symbol string, opts ...CallOption) (Market, error)
- func (s *MarketsService) List(ctx context.Context, opts ...CallOption) ([]Market, error)
- func (s *MarketsService) OrderBook(ctx context.Context, symbol string, params *GetOrderBookParams, ...) (OrderBook, error)
- func (s *MarketsService) Trades(ctx context.Context, symbol string, params *GetMarketTradesParams, ...) (*Page[PublicTrade], error)
- type Network
- type NetworksService
- type Notification
- type NotificationKind
- type OpenOrder
- type OperationID
- type OperationInfo
- type Options
- type Order
- type OrderBook
- type OrderBookUpdate
- type OrderHistoryParams
- type OrderID
- type OrderSide
- type OrderStateUnknownError
- type OrderStatus
- type OrderType
- type OrderbookParamsdeprecated
- type Page
- type PasswordRules
- type PerpMarket
- type PlaceOrderRequest
- type PlaceOrderResponse
- type PlaceOrderResult
- type PlaceOrdersItem
- type Pool
- type PoolID
- type PoolStatus
- type PoolsService
- func (s *PoolsService) Exit(ctx context.Context, symbol string, req ExitPoolRequest, opts ...CallOption) (ExitPoolResult, error)
- func (s *PoolsService) Get(ctx context.Context, symbol string, opts ...CallOption) (Pool, error)
- func (s *PoolsService) Join(ctx context.Context, symbol string, req JoinPoolRequest, opts ...CallOption) (JoinPoolResult, error)
- func (s *PoolsService) List(ctx context.Context, opts ...CallOption) ([]Pool, error)
- type Position
- type Positions
- type PublicTrade
- type RateLimitState
- type ResyncReason
- type RetryInfo
- type SequenceGap
- type ServerTime
- type SessionRevoked
- type SortDirection
- type SubAccount
- type SubscribeRefusal
- type SubscribeResult
- type TimeInForce
- type TradeHistoryParams
- type TradeID
- type TradesParamsdeprecated
- type TradingService
- func (s *TradingService) AllOrderHistory(ctx context.Context, params *OrderHistoryParams, opts ...IterOption) iter.Seq2[Order, error]
- func (s *TradingService) AllTrades(ctx context.Context, params *TradeHistoryParams, opts ...IterOption) iter.Seq2[Fill, error]
- func (s *TradingService) CancelAll(ctx context.Context, symbol string, opts ...CallOption) (CancelAllResult, error)
- func (s *TradingService) CancelAllAfter(ctx context.Context, symbol string, timeout time.Duration, opts ...CallOption) (CancelAllAfter, error)
- func (s *TradingService) CancelAllAfterMarkets(ctx context.Context, timeout time.Duration, opts ...CallOption) (CancelAllAfter, error)
- func (s *TradingService) CancelAllMarkets(ctx context.Context, opts ...CallOption) (CancelAllResult, error)
- func (s *TradingService) CancelAllUntilDone(ctx context.Context, o CancelAllOptions, opts ...CallOption) (CancelAllSummary, error)
- func (s *TradingService) CancelOrder(ctx context.Context, orderID string, opts ...CallOption) (Order, error)
- func (s *TradingService) CancelOrderByClientID(ctx context.Context, clientOrderID string, opts ...CallOption) (Order, error)
- func (s *TradingService) CancelOrders(ctx context.Context, entries []CancelBatchItem, opts ...CallOption) (BatchCancelResult, error)
- func (s *TradingService) OpenOrders(ctx context.Context, params *ListOpenOrdersParams, opts ...CallOption) ([]Order, error)
- func (s *TradingService) Order(ctx context.Context, orderID string, opts ...CallOption) (Order, error)
- func (s *TradingService) OrderByClientID(ctx context.Context, clientOrderID string, opts ...CallOption) (Order, error)
- func (s *TradingService) OrderHistory(ctx context.Context, params *OrderHistoryParams, opts ...CallOption) (*Page[Order], error)
- func (s *TradingService) PlaceOrder(ctx context.Context, order PlaceOrderRequest, opts ...CallOption) (PlaceOrderResult, error)
- func (s *TradingService) PlaceOrders(ctx context.Context, symbol string, orders []PlaceOrdersItem, ...) (BatchPlaceResult, error)
- func (s *TradingService) Trades(ctx context.Context, params *TradeHistoryParams, opts ...CallOption) (*Page[Fill], error)
- type TriggerDirection
- type UserID
- type WSClock
- type WSError
- type WSHandlers
- type WSKeySigner
- type WSOptions
- type WSTimer
- type WalletService
- func (s *WalletService) AllDeposits(ctx context.Context, params *ListDepositsParams, opts ...IterOption) iter.Seq2[Deposit, error]
- func (s *WalletService) AllWithdrawals(ctx context.Context, params *ListWithdrawalsParams, opts ...IterOption) iter.Seq2[Withdrawal, error]
- func (s *WalletService) Deposit(ctx context.Context, depositID string, opts ...CallOption) (Deposit, error)
- func (s *WalletService) DepositAddress(ctx context.Context, params DepositAddressParams, opts ...CallOption) (DepositAddress, error)
- func (s *WalletService) Deposits(ctx context.Context, params *ListDepositsParams, opts ...CallOption) (*Page[Deposit], error)
- func (s *WalletService) Withdrawal(ctx context.Context, withdrawalID string, opts ...CallOption) (Withdrawal, error)
- func (s *WalletService) WithdrawalAddresses(ctx context.Context, opts ...CallOption) ([]WithdrawalAddress, error)
- func (s *WalletService) Withdrawals(ctx context.Context, params *ListWithdrawalsParams, opts ...CallOption) (*Page[Withdrawal], error)
- type WebSocket
- func (w *WebSocket) Auth(ctx context.Context, token string) (AuthResult, error)
- func (w *WebSocket) AuthKey(ctx context.Context) (AuthResult, error)
- func (w *WebSocket) Channels() []string
- func (w *WebSocket) Close() error
- func (w *WebSocket) Connect(ctx context.Context) (Welcome, error)
- func (w *WebSocket) Connected() bool
- func (w *WebSocket) HasToken() bool
- func (w *WebSocket) LiveBalances(ctx context.Context, opts LiveBalancesOptions) (*LiveBalances, error)
- func (w *WebSocket) OrderBook(ctx context.Context, symbol string, opts LiveOrderBookOptions) (*LiveOrderBook, error)
- func (w *WebSocket) PendingChannels() []string
- func (w *WebSocket) Ping(ctx context.Context) (time.Duration, error)
- func (w *WebSocket) Subscribe(ctx context.Context, channels ...string) (SubscribeResult, error)
- func (w *WebSocket) URL() string
- func (w *WebSocket) Unsubscribe(ctx context.Context, channels ...string) error
- func (w *WebSocket) UserID() string
- func (w *WebSocket) Welcome() (Welcome, bool)
- type Welcome
- type Withdrawal
- type WithdrawalAddress
- type WithdrawalHistoryEntry
- type WithdrawalID
- type WithdrawalStatus
Examples ¶
Constants ¶
const ( MaxBatchOrders = 20 // orders in one PlaceOrders call MaxCancelOrders = 50 // entries in one CancelOrders call )
Batch limits.
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.
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.
const ( CancelStoppedDone = "done" CancelStoppedMaxRounds = "max_rounds" CancelStoppedTimeBudget = "time_budget" )
Reasons CancelAllUntilDone stopped.
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).
const DefaultBaseURL = "https://api.cexy.io"
DefaultBaseURL is the production API.
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).
const DefaultWebSocketURL = "wss://api.cexy.io/api/v1/ws"
DefaultWebSocketURL is the production WebSocket endpoint.
const MaxClockOffset = time.Hour
MaxClockOffset is the furthest the client clock may be corrected after SIGNATURE_EXPIRED.
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.
const NoMinimum time.Duration = -1
NoMinimum, as LiveBalancesOptions.MinSnapshotInterval, disables the minimum time between snapshots (the other SDKs spell this 0).
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).
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.
const SpecVersion = "1.0.0"
SpecVersion is the info.version of the openapi.sdk.json this SDK was generated from.
const SupportedProtocolVersion = 1
SupportedProtocolVersion is the WebSocket protocol version this SDK was written for.
const UserAgent = "cexy-go/" + Version
UserAgent is the default User-Agent product token.
const Version = "0.1.0-dev.16"
Version is the SDK version (a test keeps it in step with CHANGELOG.md).
const WSBookDepth = 50
WSBookDepth is how many levels per side the WebSocket book carries. REST levels deeper than this are never used.
Variables ¶
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.
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.
var FuturesCandleIntervals = []string{"1m", "5m", "15m", "1h", "4h", "1d"}
FuturesCandleIntervals are the intervals FuturesCandlesChannel accepts.
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 ¶
FuturesCandlesChannel returns "futures.candles:{coin}:{interval}" (event futures.candle.update, data FuturesCandleUpdate). interval is one of FuturesCandleIntervals.
func FuturesOrderBookChannel ¶
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 ¶
FuturesTradesChannel returns "futures.trades:{coin}" (event futures.trades.new, data FuturesTradesUpdate).
func IsLocalHost ¶
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.
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) Is ¶
Is reports whether the error belongs to category target (ErrNotFound, ErrRateLimited, ...).
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.
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 ¶
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.
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 ¶
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.
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.
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 (*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) HasCredentials ¶
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) Time ¶
func (c *Client) Time(ctx context.Context, opts ...CallOption) (ServerTime, error)
Time returns the server clock. Compare it with yours to detect skew.
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" CodeDepositDisabled ErrorCode = "DEPOSIT_DISABLED" CodeWithdrawalDisabled ErrorCode = "WITHDRAWAL_DISABLED" CodeSelfTradeBlocked ErrorCode = "SELF_TRADE_BLOCKED" CodeLimitExceeded ErrorCode = "LIMIT_EXCEEDED" CodeRateLimited ErrorCode = "RATE_LIMITED" CodeInternal ErrorCode = "INTERNAL" 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).
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 {
}
ExitPoolRequest: Removes liquidity from a pool.
type ExitPoolResult ¶
type ExitPoolResult struct {
BaseReturned Amount `json:"base_returned"`
QuoteReturned Amount `json:"quote_returned"`
}
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) 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 ¶
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"`
}
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 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" MaintenanceReasonDepositsDisabled MaintenanceReason = "deposits_disabled" MaintenanceReasonWithdrawalsDisabled MaintenanceReason = "withdrawals_disabled" )
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.
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.
type OrderStateUnknownError ¶
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.
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"`
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 ¶
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 ¶
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.
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 ¶
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)
}
}
Output:
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)
}
}
Output:
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 ¶
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.
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 ¶
NewWebSocket checks the options. Call Connect to open the connection.
func (*WebSocket) Auth ¶
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 ¶
Channels returns the channels currently held (restored after every reconnect).
func (*WebSocket) Connect ¶
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) HasToken ¶
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()
}
Output:
func (*WebSocket) PendingChannels ¶
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) Subscribe ¶
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) Unsubscribe ¶
Unsubscribe unsubscribes and returns on the unsubscribed acknowledgement (or after AckTimeout without one); it fails on an error frame with the request id.
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" )