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.
- Account
Id - 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 examplerust_decimal), never withf64. - ApiError
- An error response from the API.
- ApiKey
- An existing key. Never carries the secret.
- ApiKey
Authenticator - The old scheme (
AuthScheme::Headers):X-API-KeyandX-API-Secretheaders on every private request. The API is switching it off (SIGNATURE_REQUIRED); the default is request signing (crate::HmacAuthenticator). - Asset
- A tradable asset.
- Asset
Network - An asset’s policy on one network.
- Assets
- The asset catalogue.
- Auth
Change - Carried by
WsEvent::AuthChanged. - Auth
Request - One request an
Authenticatoradds credentials to. - Auth
Result - What
WebSocket::authdid. - Balance
- A balance in one asset.
- Batch
Cancel Result - What
crate::Trading::cancel_ordersdid.cancelledcounts entries now cancelled (recovered ones included),failedthe rest that have a known state,unknownthose that do not. - Batch
Order - What a batch did: one result per order, in the order sent.
- Batch
Order Input - One order for
crate::Trading::place_orders: the fields of acrate::PlaceOrderRequestwithout the symbol. Amounts are decimal strings. - Batch
Order Item - One order of a batch: an order as for
POST /trading/orders, without the symbol, and withclient_order_idrequired. - Batch
Order Outcome - One order of
crate::Trading::place_orders, in request order. - Batch
Order Request - Places up to 20 orders in one market (Phase 0 B2).
- Batch
Order Result - One order’s outcome in a batch: exactly one of
orderanderroris set. - Batch
Place Result - What
crate::Trading::place_ordersdid. The counts are computed fromresults:placedcounts placed and recovered orders that were not rejected,failedthe refused ones (a recoveredrejectedincluded),unknownthose whose state could not be read. - Book
Level - One
[price, quantity]level of an order book. - Book
Snapshot - A copy of a
LiveOrderBook’s state. Levels are best first, at most 50 a side. - Call
Options - Per-call overrides: see
Client::with_options. - Cancel
AllAfter - The dead-man switch, as just set.
- Cancel
AllAfter Request - Arms, re-arms or disarms the dead-man switch.
- Cancel
AllOptions - Target and bounds of
Trading::cancel_all_until_done. - Cancel
AllRequest - Cancels every open order, optionally within one market.
- Cancel
AllResult - What a bulk cancellation achieved.
- Cancel
AllSummary - The rounds of
cancel_all_until_donemerged 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 incancelled). - Cancel
Batch - What a batch cancel did: one result per entry, in the order sent.
- Cancel
Batch Item - One order to cancel: exactly one of
order_idandclient_order_id. - Cancel
Batch Request - Cancels up to 50 orders, each named by its id or by your own (Phase 0 B2).
- Cancel
Batch Result - One entry’s outcome in a batch cancel: exactly one of
orderanderroris set. - Cancel
Entry Outcome - One entry of
crate::Trading::cancel_orders, in request order. - Cancel
Failure - 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.
- Client
Options - Configures a
Client. The default gives an anonymous client for public data. - Close
Info - A closed connection.
- Connection
Error - The request produced no HTTP response.
- Deposit
- A deposit.
- Deposit
Address - A deposit address.
- Deposit
Address Params - Query parameters of
deposit_address.Noneis not sent. - Error
Body - The
errorobject of one item in a batch result (crate::BatchOrderResult,crate::CancelBatchResult), as the server sent it. A whole response’s error is anApiErrorinstead. - Exchange
Config - Public exchange configuration.
- Exit
Pool Request - Removes liquidity from a pool.
- Exit
Pool Result - What an exit produced.
- Export
Params - Query parameters of
export_deposits,export_ledger,export_orders,export_trades,export_withdrawals.Noneis 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.
- Futures
Book - A futures market’s book.
- Futures
Book Update - The data of
futures.orderbook.update: the complete book (fullis always true), replacing the previous one. Levels are{price, size}objects, best first. - Futures
Candle - One candle.
- Futures
Candle Update - The data of
futures.candle.update: the current (possibly still open) candle. - Futures
Candles - A futures market’s candles.
- Futures
Candles Params - Query parameters of
futures_candles.Noneis not sent. - Futures
Channel - Futures channel names. A coin is sent exactly as given: it is case-sensitive (as
GET /api/v1/futures/marketslists it) and must be 1 to 20 ASCII letters or digits. A bad coin or interval is anError::Configand nothing is sent. - Futures
Fill - One fill.
- Futures
Fills - A page of the account’s fills.
- Futures
Fills Params - Query parameters of
futures_fills.Noneis not sent. - Futures
Funding - A page of the account’s funding payments.
- Futures
Funding Params - Query parameters of
futures_funding.Noneis not sent. - Futures
Market - One futures market.
- Futures
Markets - Every listed futures market.
- Futures
Mids - The data of
futures.mids: every coin’s mid price, the full set each time (not a diff). - Futures
Open Orders - The account’s open orders.
- Futures
Orderbook Params - Query parameters of
futures_orderbook.Noneis not sent. - Futures
Orders Update - The data of
futures.ordersonfutures.account: every open order, in full. - Futures
Positions - The account’s positions.
- Futures
Positions Update - The data of
futures.positionsonfutures.account: the full state. - Futures
Public Trade - A public trade, with nothing that identifies the parties.
- Futures
Status - The data of
futures.status, sent on a transition only. - Futures
Trades - A futures market’s recent public trades.
- Futures
Trades Params - Query parameters of
futures_trades.Noneis not sent. - Futures
Trades Update - The data of
futures.trades.new: one or more public trades. - GetCandles
Params - Query parameters of
get_candles.Noneis not sent. - GetLedger
Params - Query parameters of
get_ledger.Noneis not sent. - GetMarket
Trades Params - Query parameters of
get_market_trades.Noneis not sent. - GetOrder
Book Params - Query parameters of
get_order_book.Noneis not sent. - Held
Incoming - An internal transfer credited to
lockedand not yet available. - Hmac
Authenticator - Signs every private request (see
SIGNING_SCHEME). The secret never leaves the process: onlyX-API-Key,X-API-Timestamp,X-API-NonceandX-API-Signatureare sent. Called once per attempt, so every retry has a fresh timestamp and nonce. - Join
Pool Request - Adds liquidity to a pool.
- Join
Pool Result - What a join produced.
- Ledger
Entry - One entry from the account’s ledger.
- Ledger
Reference Adjustment - A manual operator adjustment. Always accompanied by an audit event.
- Ledger
Reference Deposit - A blockchain deposit.
- Ledger
Reference Futures Transfer - A movement of collateral to or from a futures account.
- Ledger
Reference Order - An order reservation or release.
- Ledger
Reference Pool - A liquidity pool join or exit.
- Ledger
Reference System - A system-originated credit with no user counterparty (rebate, promotion).
- Ledger
Reference Trade - A trade settlement.
- Ledger
Reference Transfer - An internal transfer between accounts.
- Ledger
Reference Withdrawal - A withdrawal request.
- Level
- One price level.
- List
Deposits Params - Query parameters of
list_deposits.Noneis not sent. - List
Notifications Params - Query parameters of
list_notifications.Noneis not sent. - List
Open Orders Params - Query parameters of
list_open_orders.Noneis not sent. - List
Withdrawals Params - Query parameters of
list_withdrawals.Noneis not sent. - Live
Balances - Live balances of the authenticated account, fed by the
balanceschannel and REST snapshots. Create it withWebSocket::live_balancesafterauth. Cloning is cheap. - Live
Balances Options - Configures
WebSocket::live_balances. - Live
Order Book - A local order book fed by the
orderbook:{symbol}channel. Create it withcrate::WebSocket::order_book. Cloning is cheap; clones share the book. Changes are reported asWsEvent::Bookevents. - Maintenance
State - 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.
- Open
Order - One open order.
- Operation
Info - Method, path, authentication and required API-key scope of an operation.
- Order
- An order.
- Order
Book - One side of the order book, aggregated by price.
- Order
Book Update - The data of
orderbook.update: always the complete top 50 levels of both sides (fullis always true). It replaces the previous book; there are no deltas. - Order
History Params - Query parameters of
order_history.Noneis not sent. - Page
- One page of a cursor-paginated listing.
- Password
Rules - Password constraints, published so a form can validate locally.
- Perp
Market - One listed perpetual market and its current figures.
- Place
Order Request - Places an order.
- Place
Order Response - The result of placing an order, including anything it executed immediately.
- Place
Order Result - What
Trading::place_orderreturns. - 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.
- Public
Trade - A public trade.
- Rate
Limit State - A snapshot of the client-side rate limiter.
- Retry
Info - Passed to
ClientOptions::on_retrybefore the SDK waits and retries. It never holds credentials. - Sequence
Gap - Carried by
WsEvent::SequenceGap. - Server
Time - The server’s clock.
- Session
Revoked - The data of
session.revokedon the account channel. - SubAccount
- A sub-account.
- Subscribe
Result - What
WebSocket::subscribedid. - Trade
History Params - Query parameters of
trade_history.Noneis 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.
- Withdrawal
Address - A saved withdrawal address.
- Withdrawal
History Entry - 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.updateororder.filled. DecodedatawithWsFrame::decode. Unknown event types are ignored (they may be added without notice). - WsOptions
- Configures a
WebSocket.
Enums§
- ApiScope
- Scope attached to an API key.
- Auth
Change Reason - Why the server ended the connection’s private subscriptions.
- Auth
Scheme - How a
Clientsendsapi_keyandapi_secret. - Balances
Event - A
LiveBalanceschanged state (read fromcrate::WsEventsasWsEvent::Balances). - Book
Event - A live order book changed state.
- Cancel
AllStop - Why
cancel_all_until_donestopped. - Cancel
AllTarget - What
cancel_all_until_donecancels. There is no default, so an account-wide cancel is always explicit. - Cancel
Outcome - What became of one entry of
crate::Trading::cancel_orders. - Candle
Interval - Candle/kline intervals for market data.
- Deposit
Status - Lifecycle of an incoming blockchain deposit.
- Error
- Every error the SDK returns.
- Error
Category - The category of an API error. An error matches at most one, except that
JurisdictionBlockedalso matchesForbidden. An error with a code this SDK does not know matches none: checkApiError::codeinstead. - Error
Code - Stable, machine-readable error identifiers.
- Ledger
Entry Kind - What a ledger entry records.
- Ledger
Reference - What caused a ledger entry: one kind of cause per variant, told apart by
type. - Liquidity
Role - Whether a fill added liquidity (maker) or removed it (taker).
- Maintenance
Reason - Machine-readable reasons a capability is unavailable.
- Market
Status - Trading availability of a market.
- Notification
Kind - What a notice is about.
- Operation
Id - One operation of the SDK surface.
- Order
Side - Which side of a market an order takes.
- Order
Status - Lifecycle of an order.
- Order
Type - Order types the matching engine accepts.
- Place
Outcome - What became of one order of
crate::Trading::place_orders. - Pool
Status - Whether a pool quotes, and whether it accepts new liquidity.
- Resync
Reason - Why state may have been missed.
- Sort
Direction - Sort direction for a paginated listing.
- Time
InForce - How long an order remains eligible to match.
- Trigger
Direction - Which way the price must move for a stop to fire.
- Withdrawal
Status - 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_fillsandFutures::all_fundingask again for the same cursor while the provider is busy, unlessFutures::with_max_busy_retriessays 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_orderscall takes. - MAX_
CANCEL_ ENTRIES - The most entries one
crate::Trading::cancel_orderscall 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_intervalis 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) orWebSocket::auth_key. - SIGNING_
SCHEME - The signing scheme, the first line of every canonical request.
- SPEC_
VERSION - The
info.versionof 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
LiveBalancesscheduling (minimum snapshot interval, retry backoff). Socket timeouts always use the real clock. LeaveWsOptions::clockunset in production. - WsTimer
- A stoppable timer from a
WsClock.
Functions§
- is_
local_ host - Whether
hostis 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), asplace_orderandplace_ordersgenerate 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§
- Balance
Snapshot Fn - Where snapshots come from.
- Candles
Params Deprecated - Renamed to
FuturesCandlesParams. - Deposit
Id - Unique identifier of a deposit.
- Fills
Params Deprecated - Renamed to
FuturesFillsParams. - Funding
Params Deprecated - Renamed to
FuturesFundingParams. - Futures
Transfer Id - Unique identifier of a futures collateral transfer.
- Item
Stream - Every item of a listing, fetched page by page as it is consumed. Use it with
futures_util::StreamExt(next().await) orTryStreamExt(try_collect). - OnRetry
- A retry callback: see
ClientOptions::on_retry. - OrderId
- Unique identifier of an order.
- Orderbook
Params Deprecated - Renamed to
FuturesOrderbookParams. - Owner
IdFn - Where the snapshot source’s owner user id comes from.
- PoolId
- Unique identifier of a liquidity pool.
- Result
Resultwith this crate’sError.- TradeId
- Unique identifier of a trade.
- Trades
Params Deprecated - Renamed to
FuturesTradesParams. - UserId
- Unique identifier of a user account.
- Withdrawal
Id - Unique identifier of a withdrawal.
- WsEvents
- The receiving end of the event channel.