Skip to main content

Crate cexy

Crate cexy 

Source
Expand description

The official Rust SDK for the CEXY.io exchange API: REST and WebSocket.

  • Typed models generated from the public OpenAPI spec (cexy-api-spec).
  • Safe by default: retries with backoff, order placement designed to avoid duplicates (via client_order_id), a client-side rate limiter, and HTTP redirects are never followed.
  • A WebSocket client with heartbeat, reconnect and a live order book.
let client = cexy::Client::new(cexy::ClientOptions::default())?;
let markets = client.markets().list().await?;
let now = client.time().await?;
println!("{} markets, server time {}", markets.len(), now.iso);

Amounts are decimal strings (Amount), never floating point. API keys cannot withdraw or transfer funds, whatever their scopes.

Structs§

Account
Balances, ledger, notifications, sub-accounts and API keys.
AccountId
The id of the account a credential belongs to, and nothing else.
Amount
An exact decimal amount as a string, such as "0.00150000". The API never uses JSON numbers for money. Do arithmetic with a decimal crate (for example rust_decimal), never with f64.
ApiError
An error response from the API.
ApiKey
An existing key. Never carries the secret.
ApiKeyAuthenticator
The old scheme (AuthScheme::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 (crate::HmacAuthenticator).
Asset
A tradable asset.
AssetNetwork
An asset’s policy on one network.
Assets
The asset catalogue.
AuthChange
Carried by WsEvent::AuthChanged.
AuthRequest
One request an Authenticator adds credentials to.
AuthResult
What WebSocket::auth did.
Balance
A balance in one asset.
BatchCancelResult
What crate::Trading::cancel_orders did. cancelled counts entries now cancelled (recovered ones included), failed the rest that have a known state, unknown those that do not.
BatchOrder
What a batch did: one result per order, in the order sent.
BatchOrderInput
One order for crate::Trading::place_orders: the fields of a crate::PlaceOrderRequest without the symbol. Amounts are decimal strings.
BatchOrderItem
One order of a batch: an order as for POST /trading/orders, without the symbol, and with client_order_id required.
BatchOrderOutcome
One order of crate::Trading::place_orders, in request order.
BatchOrderRequest
Places up to 20 orders in one market (Phase 0 B2).
BatchOrderResult
One order’s outcome in a batch: exactly one of order and error is set.
BatchPlaceResult
What crate::Trading::place_orders did. The counts are computed from results: placed counts placed and recovered orders that were not rejected, failed the refused ones (a recovered rejected included), unknown those whose state could not be read.
BookLevel
One [price, quantity] level of an order book.
BookSnapshot
A copy of a LiveOrderBook’s state. Levels are best first, at most 50 a side.
CallOptions
Per-call overrides: see Client::with_options.
CancelAllAfter
The dead-man switch, as just set.
CancelAllAfterRequest
Arms, re-arms or disarms the dead-man switch.
CancelAllOptions
Target and bounds of Trading::cancel_all_until_done.
CancelAllRequest
Cancels every open order, optionally within one market.
CancelAllResult
What a bulk cancellation achieved.
CancelAllSummary
The rounds of cancel_all_until_done merged 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).
CancelBatch
What a batch cancel did: one result per entry, in the order sent.
CancelBatchItem
One order to cancel: exactly one of order_id and client_order_id.
CancelBatchRequest
Cancels up to 50 orders, each named by its id or by your own (Phase 0 B2).
CancelBatchResult
One entry’s outcome in a batch cancel: exactly one of order and error is set.
CancelEntryOutcome
One entry of crate::Trading::cancel_orders, in request order.
CancelFailure
Why one order could not be cancelled.
Candle
An OHLCV bucket.
Client
The CEXY.io REST client. Cloning is cheap and clones share the connection pool and the rate limiter. Use one client per API key.
ClientOptions
Configures a Client. The default gives an anonymous client for public data.
CloseInfo
A closed connection.
ConnectionError
The request produced no HTTP response.
Deposit
A deposit.
DepositAddress
A deposit address.
DepositAddressParams
Query parameters of deposit_address. None is not sent.
ErrorBody
The error object of one item in a batch result (crate::BatchOrderResult, crate::CancelBatchResult), as the server sent it. A whole response’s error is an ApiError instead.
ExchangeConfig
Public exchange configuration.
ExitPoolRequest
Removes liquidity from a pool.
ExitPoolResult
What an exit produced.
ExportParams
Query parameters of export_deposits, export_ledger, export_orders, export_trades, export_withdrawals. None is not sent.
Exports
CSV exports. Each method returns the CSV text.
FeeSchedule
A fee tier.
Fees
Fee schedules.
Fill
One of the caller’s executions.
Funding
One funding payment.
Futures
Futures market data (public) and the account’s own futures data (API key with the read scope). Read only: nothing here places orders or moves funds.
FuturesBook
A futures market’s book.
FuturesBookUpdate
The data of futures.orderbook.update: the complete book (full is always true), replacing the previous one. Levels are {price, size} objects, best first.
FuturesCandle
One candle.
FuturesCandleUpdate
The data of futures.candle.update: the current (possibly still open) candle.
FuturesCandles
A futures market’s candles.
FuturesCandlesParams
Query parameters of futures_candles. None is not sent.
FuturesChannel
Futures channel names. A coin is sent exactly as given: it is case-sensitive (as GET /api/v1/futures/markets lists it) and must be 1 to 20 ASCII letters or digits. A bad coin or interval is an Error::Config and nothing is sent.
FuturesFill
One fill.
FuturesFills
A page of the account’s fills.
FuturesFillsParams
Query parameters of futures_fills. None is not sent.
FuturesFunding
A page of the account’s funding payments.
FuturesFundingParams
Query parameters of futures_funding. None is not sent.
FuturesMarket
One futures market.
FuturesMarkets
Every listed futures market.
FuturesMids
The data of futures.mids: every coin’s mid price, the full set each time (not a diff).
FuturesOpenOrders
The account’s open orders.
FuturesOrderbookParams
Query parameters of futures_orderbook. None is not sent.
FuturesOrdersUpdate
The data of futures.orders on futures.account: every open order, in full.
FuturesPositions
The account’s positions.
FuturesPositionsUpdate
The data of futures.positions on futures.account: the full state.
FuturesPublicTrade
A public trade, with nothing that identifies the parties.
FuturesStatus
The data of futures.status, sent on a transition only.
FuturesTrades
A futures market’s recent public trades.
FuturesTradesParams
Query parameters of futures_trades. None is not sent.
FuturesTradesUpdate
The data of futures.trades.new: one or more public trades.
GetCandlesParams
Query parameters of get_candles. None is not sent.
GetLedgerParams
Query parameters of get_ledger. None is not sent.
GetMarketTradesParams
Query parameters of get_market_trades. None is not sent.
GetOrderBookParams
Query parameters of get_order_book. None is not sent.
HeldIncoming
An internal transfer credited to locked and not yet available.
HmacAuthenticator
Signs every private request (see SIGNING_SCHEME). The secret never leaves the process: only X-API-Key, X-API-Timestamp, X-API-Nonce and X-API-Signature are sent. Called once per attempt, so every retry has a fresh timestamp and nonce.
JoinPoolRequest
Adds liquidity to a pool.
JoinPoolResult
What a join produced.
LedgerEntry
One entry from the account’s ledger.
LedgerReferenceAdjustment
A manual operator adjustment. Always accompanied by an audit event.
LedgerReferenceDeposit
A blockchain deposit.
LedgerReferenceFuturesTransfer
A movement of collateral to or from a futures account.
LedgerReferenceOrder
An order reservation or release.
LedgerReferencePool
A liquidity pool join or exit.
LedgerReferenceSystem
A system-originated credit with no user counterparty (rebate, promotion).
LedgerReferenceTrade
A trade settlement.
LedgerReferenceTransfer
An internal transfer between accounts.
LedgerReferenceWithdrawal
A withdrawal request.
Level
One price level.
ListDepositsParams
Query parameters of list_deposits. None is not sent.
ListNotificationsParams
Query parameters of list_notifications. None is not sent.
ListOpenOrdersParams
Query parameters of list_open_orders. None is not sent.
ListWithdrawalsParams
Query parameters of list_withdrawals. None is not sent.
LiveBalances
Live balances of the authenticated account, fed by the balances channel and REST snapshots. Create it with WebSocket::live_balances after auth. Cloning is cheap.
LiveBalancesOptions
Configures WebSocket::live_balances.
LiveOrderBook
A local order book fed by the orderbook:{symbol} channel. Create it with crate::WebSocket::order_book. Cloning is cheap; clones share the book. Changes are reported as WsEvent::Book events.
MaintenanceState
Why a capability is currently unavailable.
Market
A tradable market and its current ticker.
Markets
Markets, tickers, order books, public trades and candles.
Network
A blockchain network.
Networks
Blockchain networks.
Notification
An in-app notice.
OpenOrder
One open order.
OperationInfo
Method, path, authentication and required API-key scope of an operation.
Order
An order.
OrderBook
One side of the order book, aggregated by price.
OrderBookUpdate
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.
OrderHistoryParams
Query parameters of order_history. None is not sent.
Page
One page of a cursor-paginated listing.
PasswordRules
Password constraints, published so a form can validate locally.
PerpMarket
One listed perpetual market and its current figures.
PlaceOrderRequest
Places an order.
PlaceOrderResponse
The result of placing an order, including anything it executed immediately.
PlaceOrderResult
What Trading::place_order returns.
Pool
A pool as a client sees it.
Pools
Liquidity pools. Join and exit need an API key with the trade scope.
Position
One open position.
Positions
A margin summary and the open positions.
PublicTrade
A public trade.
RateLimitState
A snapshot of the client-side rate limiter.
RetryInfo
Passed to ClientOptions::on_retry before the SDK waits and retries. It never holds credentials.
SequenceGap
Carried by WsEvent::SequenceGap.
ServerTime
The server’s clock.
SessionRevoked
The data of session.revoked on the account channel.
SubAccount
A sub-account.
SubscribeResult
What WebSocket::subscribe did.
TradeHistoryParams
Query parameters of trade_history. None is not sent.
Trading
Orders and your trades. Placing and cancelling need the trade scope.
Wallet
Wallet reads. API keys can never withdraw or transfer; there are no such methods.
WebSocket
The CEXY.io WebSocket client. Cloning is cheap; clones share the connection.
Welcome
The server’s first frame on every connection.
Withdrawal
A withdrawal.
WithdrawalAddress
A saved withdrawal address.
WithdrawalHistoryEntry
One transition in a withdrawal’s life.
WsError
A WebSocket protocol error, a server error frame (from_server), or a local guard.
WsFrame
A channel event such as ticker.update, orderbook.update or order.filled. Decode data with WsFrame::decode. Unknown event types are ignored (they may be added without notice).
WsOptions
Configures a WebSocket.

Enums§

ApiScope
Scope attached to an API key.
AuthChangeReason
Why the server ended the connection’s private subscriptions.
AuthScheme
How a Client sends api_key and api_secret.
BalancesEvent
A LiveBalances changed state (read from crate::WsEvents as WsEvent::Balances).
BookEvent
A live order book changed state.
CancelAllStop
Why cancel_all_until_done stopped.
CancelAllTarget
What cancel_all_until_done cancels. There is no default, so an account-wide cancel is always explicit.
CancelOutcome
What became of one entry of crate::Trading::cancel_orders.
CandleInterval
Candle/kline intervals for market data.
DepositStatus
Lifecycle of an incoming blockchain deposit.
Error
Every error the SDK returns.
ErrorCategory
The category of an API error. An error matches at most one, except that JurisdictionBlocked also matches Forbidden. An error with a code this SDK does not know matches none: check ApiError::code instead.
ErrorCode
Stable, machine-readable error identifiers.
LedgerEntryKind
What a ledger entry records.
LedgerReference
What caused a ledger entry: one kind of cause per variant, told apart by type.
LiquidityRole
Whether a fill added liquidity (maker) or removed it (taker).
MaintenanceReason
Machine-readable reasons a capability is unavailable.
MarketStatus
Trading availability of a market.
NotificationKind
What a notice is about.
OperationId
One operation of the SDK surface.
OrderSide
Which side of a market an order takes.
OrderStatus
Lifecycle of an order.
OrderType
Order types the matching engine accepts.
PlaceOutcome
What became of one order of crate::Trading::place_orders.
PoolStatus
Whether a pool quotes, and whether it accepts new liquidity.
ResyncReason
Why state may have been missed.
SortDirection
Sort direction for a paginated listing.
TimeInForce
How long an order remains eligible to match.
TriggerDirection
Which way the price must move for a stop to fire.
WithdrawalStatus
Lifecycle of an outgoing withdrawal.
WsEvent
Everything the WebSocket reports, in order. Read them from WebSocket::events.

Constants§

DEFAULT_BASE_URL
The production API.
DEFAULT_MAX_BUSY_RETRIES
How many times Futures::all_fills and Futures::all_funding ask again for the same cursor while the provider is busy, unless Futures::with_max_busy_retries says otherwise.
DEFAULT_RPM_ANONYMOUS
Default client-side limit without credentials (the server allows about 120 a minute per IP).
DEFAULT_RPM_WITH_KEY
Default client-side limit with an API key (the server allows about 600 a minute per key).
DEFAULT_WEBSOCKET_URL
The production WebSocket endpoint.
FUTURES_ACCOUNT_CHANNEL
The private futures channel: the account’s positions and open orders.
FUTURES_INTERVALS
The candle intervals of futures.candles:{coin}:{interval} (exact, case-sensitive).
MAX_BATCH_ORDERS
The most orders one crate::Trading::place_orders call takes.
MAX_CANCEL_ENTRIES
The most entries one crate::Trading::cancel_orders call takes.
MAX_CLOCK_OFFSET
The furthest the client clock may be corrected after SIGNATURE_EXPIRED; beyond it the request fails with a clock error.
MAX_PING_INTERVAL
The longest client ping interval: the server closes a connection whose client is silent for 90 to 120 s. A longer WsOptions::ping_interval is a configuration error.
MAX_SERVER_WAIT
The longest wait the SDK accepts from a server hint (Retry-After, details.retry_after_seconds, X-RateLimit-Reset). A longer hint is not waited: the call fails with the error, and the client-side limiter never blocks longer than this.
PAGING_CURSOR_REPEATED
The code of Error::PagingCursorRepeated.
PAGING_STALLED
The code of Error::PagingStalled.
PRIVATE_CHANNELS
Channels that need WebSocket::auth (session access token) or WebSocket::auth_key.
SIGNING_SCHEME
The signing scheme, the first line of every canonical request.
SPEC_VERSION
The info.version of the SDK spec this crate was generated from.
SUPPORTED_PROTOCOL_VERSION
The WebSocket protocol version this SDK was written for.
USER_AGENT
Default User-Agent product token: cexy-rust/<VERSION>.
VERSION
SDK version.
WS_BOOK_DEPTH
How many levels per side the WebSocket book carries. REST levels deeper than this are never used.

Traits§

Authenticator
Adds credentials to requests for operations that need an API key.
WsClock
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 unset in production.
WsTimer
A stoppable timer from a WsClock.

Functions§

is_local_host
Whether host is a loopback name or address, the only hosts where plain-text transport may be allowed.
levels
Converts the raw [price, quantity] pairs of an order-book side. Entries with fewer than two values are skipped.
new_client_order_id
A new client_order_id (a UUID v4), as place_order and place_orders generate for an order without one. Create and save your ids with it before the call when you need to reconcile after an error: a dropped future returns nothing.

Type Aliases§

BalanceSnapshotFn
Where snapshots come from.
CandlesParamsDeprecated
Renamed to FuturesCandlesParams.
DepositId
Unique identifier of a deposit.
FillsParamsDeprecated
Renamed to FuturesFillsParams.
FundingParamsDeprecated
Renamed to FuturesFundingParams.
FuturesTransferId
Unique identifier of a futures collateral transfer.
ItemStream
Every item of a listing, fetched page by page as it is consumed. Use it with futures_util::StreamExt (next().await) or TryStreamExt (try_collect).
OnRetry
A retry callback: see ClientOptions::on_retry.
OrderId
Unique identifier of an order.
OrderbookParamsDeprecated
Renamed to FuturesOrderbookParams.
OwnerIdFn
Where the snapshot source’s owner user id comes from.
PoolId
Unique identifier of a liquidity pool.
Result
Result with this crate’s Error.
TradeId
Unique identifier of a trade.
TradesParamsDeprecated
Renamed to FuturesTradesParams.
UserId
Unique identifier of a user account.
WithdrawalId
Unique identifier of a withdrawal.
WsEvents
The receiving end of the event channel.