cexy (Rust)
The official Rust SDK for the CEXY.io REST and WebSocket API.
- Typed models generated from the public OpenAPI spec (cexy-api-spec).
- Safe by default: retries with backoff, order placement designed to avoid duplicate orders (via
client_order_id), a client-side rate limiter, and no HTTP redirects followed. - A WebSocket client with heartbeat, reconnect and a live order book that applies the sync rules for you.
- Async on tokio, with reqwest and tokio-tungstenite over rustls (the
ringprovider and thewebpki-rootsMozilla root store, for REST and WebSocket alike). No OpenSSL, no system trust store, no C toolchain needed to build. - Rust 1.94 or newer.
Status: 0.x, pre-release. The API is not yet frozen. It stays 0.x until the exchange ships HMAC request signing, which will change how credentials are sent.
Install
[]
= "=0.1.0-dev.2"
= { = "1", = ["macros", "rt-multi-thread"] }
Cargo never picks a pre-release (a version with -dev.N) on its own: name it explicitly. The
exact requirement above (=0.1.0-dev.2) is the safest way; move it by hand for each new pre-release.
Quick start: public data
use ;
async
Quick start: your account
use ;
# async
Placing and cancelling need a key with the trade scope; everything else needs read.
Cancel-all
One cancel_all call handles at most 500 orders. Every order it handled is in exactly one of
cancelled, already_closed (it closed on its own first: not a failure) and failed (the reason is
in failures; INVALID_STATE means the order was still being placed). has_more means there are
more. An unknown symbol is a NotFound error, and the server allows 30 cancel-all calls a minute.
cancel_all_until_done repeats the call until nothing is left: while has_more is set or orders are
still being placed. Each round is exactly one HTTP request (the loop does its own retrying, so it
never sends more than max_rounds requests). It backs off 1, 2, 4, 8, then 15 s after rounds without
progress or with a retryable error (a 503, a network failure), waits a 429's Retry-After exactly,
stops after max_rounds (default 20) or before a wait would reach time_budget (default 120 s; that
wait is not taken, and last_error_code says why), and merges the rounds by order id. A
non-retryable error returns Error::CancelAllInterrupted with the summary so far. The target is
explicit:
# async
Amounts
Every amount is an exact decimal string (Amount::new("0.00150000")?), in responses and requests.
Floats cannot hold most decimals exactly. Amount::new accepts only plain decimals (no exponents, no
spaces), and the SDK checks every amount field again before sending (Error::InvalidAmount). Do
arithmetic with a decimal crate such as rust_decimal:
#
Errors
Every API failure is Error::Api(ApiError) with status, code, message, details, fields,
request_id, retryable and retry_after. Branch on code, never on message. Match the category
with err.is(ErrorCategory::…):
| Category | When |
|---|---|
Authentication |
401: missing or invalid credentials |
Forbidden |
403: the key lacks a scope (FORBIDDEN), or the route is session-only (API_KEY_NOT_ALLOWED); also matches 451 |
JurisdictionBlocked |
451: JURISDICTION_BLOCKED (not available in the caller's jurisdiction) |
Validation |
400: see fields |
NotFound |
404 |
Conflict |
409: ALREADY_EXISTS, IDEMPOTENCY_KEY_CONFLICT, CONCURRENT_MODIFICATION |
Unprocessable |
422: INSUFFICIENT_FUNDS, MARKET_UNAVAILABLE, ... |
RateLimited |
429, with retry_after |
Server |
5xx |
UnexpectedRedirect |
3xx: code UNEXPECTED_REDIRECT, set by the SDK (see Security) |
| (none) | a code this SDK version does not know yet: check code |
Local problems are Error::Config, Error::InvalidAmount, Error::Connection (with timeout for
the per-attempt timeout), Error::OrderStateUnknown and Error::CancelAllInterrupted. ErrorCode
is an open enum: codes added to the API later arrive as ErrorCode::Other(String), so keep a
wildcard arm.
# async
Retries and idempotency
- Timeout per attempt:
ClientOptions::timeout(default 10 s). Retries:max_retries(default 3;Some(0)turns them off), exponential backoff with full jitter, capped at 10 s. - Retried: connection errors, timeouts and responses with
retryable: true. - A 429 waits at least
Retry-After/details.retry_after_seconds. - GETs retry freely.
- Orders: safety rests on
client_order_id, not onIdempotency-Key(the server does not honour that header on orders, order cancels or cancel-all, so the SDK sends it only on pool join and exit).place_orderalways sends aclient_order_id(a UUID if you do not set one); it is unique per account and a repeat is refused before any funds move. After an ambiguous failure (connection error, timeout, 5xx) the SDK first looks the order up by that id. If the order exists it is returned withrecovered: true; only if it does not exist is it sent again, with the same id. If even the lookup fails, or the order was accepted but its response could not be decoded, you getError::OrderStateUnknownwith theclient_order_id: checkorder_by_client_idbefore placing the order again. - Cancels:
cancel_orderretries connection errors; if a retry getsINVALID_STATE, the first attempt most likely cancelled the order, so the SDK fetches and returns it. Check the returnedstatus: it is usuallycancelled, but can befilledif the order traded before the cancel landed. Cancel-all is naturally repeatable and is retried the same way (a retry reports only what it cancelled); it sends noIdempotency-Key.cancel_all_until_donedoes its own retrying instead (one request per round, see above). - Server waits are bounded. A
Retry-After(ordetails.retry_after_seconds) up to 120 s (MAX_SERVER_WAIT) is honoured; a longer one is not waited: the call fails at once with the rate-limit error, whoseretry_afterstill says what the server asked. Unreadable values are ignored, andX-RateLimit-*headers never make the client-side limiter wait longer than 120 s. - Pool join and exit send a generated
Idempotency-Key, reused on every retry; the server honours it there, so they execute once. A 409CONCURRENT_MODIFICATION(the same key still in flight) is retried with the same key. Set it yourself withCallOptions::idempotency_key. ClientOptions::on_retrylets you log retries.
Per-call overrides: client.with_options(CallOptions { timeout: Some(..), max_retries: Some(..), idempotency_key: Some(..) })
returns a client that shares everything else with the original.
Pagination
Histories use opaque cursors. Each listing returns one Page (items, has_more, next_cursor), and
an all_… method returns a stream that fetches pages lazily:
# async
Rate limits
The client has a token-bucket limiter: 100 requests a minute without a key (the server allows
120 a minute per IP for anonymous calls) and 300 a minute with an API key (the server allows 600 a
minute per key). Cancel-all is limited separately to 30 a minute per account. It adapts downwards to
X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset (seconds until the window resets),
and pauses after a 429. Change it with requests_per_minute, or turn it off with disable_rate_limit.
The limiter belongs to one Client; clones share it, so clone the client rather than creating new ones.
WebSocket
# async
Everything the client reports arrives, in order, on the event channel from ws.events(). Read it
continuously: when its buffer (event_buffer, default 10 000) is full, new events are dropped and
counted in ws.dropped_events(). Live order books keep updating either way (book.snapshot()).
What the client does for you:
- Sends
{"op":"ping"}every 30 s (required: the server closes idle connections) and accepts the server's unsolicited pongs. No frame from the server for 75 s (liveness_timeout; the client's own pings do not count) means a dead connection and a reconnect. - Reconnects with exponential backoff and full jitter, then re-authenticates and re-subscribes everything.
- Correlates every request with its acknowledgement by
id:authreturns onauthenticated(and fails on anerrorwith its id, or on timeout),subscribeonsubscribed,unsubscribeonunsubscribed,pingonpong. - Guards locally: at most 100 subscriptions (extras are returned in
refused) and 200 messages a minute. - Warns once (
WsEvent::Warning) if the server speaks anotherprotocol_version, and ignores unknown event types.
Order-book rules (applied by ws.order_book; follow them if you build your own):
- Subscribe to
orderbook:{symbol}first, then take the REST snapshot (itssequenceis S). - Drop updates with
sequence <= S. - Every update carries the complete top 50 of both sides (
"full": true) and replaces the previous state. There are no deltas. Never merge REST levels deeper than 50 into WebSocket state. - A sequence gap marks the book stale until the next update, which heals it. There is no forced resync.
- Sequences reset when the server restarts: take a fresh snapshot after every reconnect.
- An
errorframeCONCURRENT_MODIFICATIONwith a nullidmeans messages were dropped: resync every book and channel (the client emitsWsEvent::Resync).
While a snapshot is missing (for example, the REST call keeps failing), LiveOrderBook keeps at most
the newest 256 updates to replay; older ones are dropped (book.dropped_updates(), with one
WsEvent::Warning). Nothing is lost, since every update is a complete top 50.
Private channels (orders, balances, deposits, withdrawals, account) need
ws.auth(token) with a session access token (it returns the user_id from authenticated).
API-key authentication on the WebSocket is not available yet: with an API key, use public channels
and poll REST for private state. If the session is revoked, the client emits WsEvent::AuthLost;
public channels keep working.
Security
- API keys cannot withdraw or transfer funds, whatever their scopes.
- Use a read-only key unless you need to trade, and restrict keys to your IPs (
allowed_ips). - Credentials go only in the
X-API-Key/X-API-Secretheaders and only on private endpoints; never in URLs. - The SDK never follows HTTP redirects, so credentials and orders are never re-sent to another URL.
A 3xx response becomes an API error with code
UNEXPECTED_REDIRECT(categoryUnexpectedRedirect); it is not retried. The WebSocket handshake does not follow redirects either. - The SDK always builds its own HTTP client, and there is no option to pass your own
reqwest::Client: redirects cannot be disabled on a client the SDK did not create, so a caller's client could leak the credentials. UseClientOptions(timeout, retries, rate limit, User-Agent) to tune it. - Only
https://base URLs andwss://WebSocket URLs are accepted.allow_insecurepermitshttp:///ws://solely forlocalhost,127.0.0.1or::1(local test servers). - The SDK redacts the secret from
Debug/Displayoutput and error messages, including values the server echoes back inApiError::details(at any depth, object keys included),fieldsandrequest_id. - WebSocket URLs must not carry credentials (
user:pass@), a query string or a fragment. - Live tests (
tests/live.rs: public REST reads and one unauthenticated WebSocket connection) run only withCEXY_LIVE_TESTS=1, never in CI. - Keep keys in environment variables or a secret manager, not in code.
Report vulnerabilities as described in SECURITY.md.
Trading risk
- Orders are real and irreversible once filled. Test your code with a read-only key and small amounts first, and add your own limits (maximum order size, allowed markets) before automating trades.
- Retries and the
client_order_idlookup are designed to avoid duplicate orders, but when a failure is ambiguous and even the lookup fails you getError::OrderStateUnknown: check the order before placing it again. - Markets move between reading data and placing an order; prices and balances you read may be stale.
- This SDK is provided under the MIT licence, without warranty. Nothing in it is investment advice.
For tool builders
OperationId::ALL and OperationId::info() describe the 40 operations (method, path, auth and scope).
The crate also exports every model type, the error types, the Authenticator trait (HMAC signing will
plug in here) and ClientOptions::user_agent_suffix to identify your tool.
Development
&& &&
CEXY_LIVE_TESTS=1
Tests read the shared conformance cases from a cexy-api-spec checkout next to this repo
(override with CEXY_API_SPEC; CEXY_REQUIRE_SPEC=1 fails instead of skipping when it is missing).
License
MIT, see LICENSE.