Crate ccxt_rust

Crate ccxt_rust 

Source
Expand description

§CCXT Rust

CCXT Rust is a professional-grade trading toolkit that brings the CCXT unified exchange interface to native Rust projects. It wraps REST and WebSocket APIs for major cryptocurrency exchanges under a single, strongly typed abstraction.

§Features

  • Async first: Powered by tokio with ergonomic async/await APIs for every call
  • Unified types: Shared Exchange trait and strongly typed market/order models
  • Performance oriented: Zero-cost abstractions with rust_decimal for precise math
  • Live data: WebSocket clients with automatic reconnection and streamed order books
  • Extensible: Builder patterns and configuration hooks for custom environments

§Installation

[dependencies]
ccxt-rust = { version = "0.1", features = ["full"] }

Alternatively depend on the workspace members directly when developing inside the repo.

§Quick Start

use ccxt_exchanges::binance::Binance;
use ccxt_rust::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    // Prefer testnet when experimenting to avoid hitting live balances.
    let exchange = Binance::builder()
        .sandbox(true)
        .build()?;

    if exchange.capabilities().fetch_ticker() {
        let ticker = exchange.fetch_ticker("BTC/USDT", ()).await?;
        println!("Last price: {:?}", ticker.last);
    }

    Ok(())
}

§Further Reading

See the repository README and the examples/ folder for advanced scenarios covering authenticated calls, streaming data, and multi-exchange orchestration.

Modules§

account
Account configuration type definitions.
balance
Balance type definitions
bid_ask
Bid-ask (best bid and ask prices) type definitions.
currency
Currency type definitions
default_type
Default type configuration for exchange operations Default Type Definitions for Exchange Configuration
endpoint
Endpoint type for public/private API distinction Endpoint type definitions for exchange API routing
fee
Fee-related type definitions
financial
Financial types with enhanced type safety (Price, Amount, Cost) Financial calculation type definitions.
funding_rate
Funding rate type definitions
ledger
Ledger entry types and related structures Ledger entry type definitions.
margin
Margin trading related types
mark_price
Mark price type definitions.
market
Market type definitions
market_data
Futures market data type definitions.
ohlcv
OHLCV (candlestick) data type definitions.
ohlcv_request
OHLCV request types with Builder pattern OHLCV request types with Builder pattern.
order
Order type definitions
order_request
Order request types with Builder pattern using typestate Order request types with Builder pattern using typestate.
orderbook
Orderbook type definitions
params
Parameter types for trait methods with builder pattern support Parameter types for trait methods with builder pattern support.
position
Position type definitions for futures trading.
prelude
Prelude module for convenient imports
risk
Risk management and position risk types Risk management type definitions.
symbol
Symbol types for unified symbol format Symbol Type Definitions for Unified Symbol Format
ticker
Ticker type definitions
ticker_params
Strongly typed parameter builder for ticker requests.
trade
Trade type definitions
transaction
Transaction types for deposits and withdrawals
transfer
Transfer-related type definitions.

Structs§

AccountConfig
Account configuration information.
AggTrade
Aggregated trade data structure.
Amount
Amount type (zero-cost wrapper).
BackoffConfig
Exponential backoff configuration for reconnection.
BackoffStrategy
Calculates retry delay with exponential backoff and jitter.
Balance
Balance structure containing all currency balances
BalanceEntry
Balance entry for a single currency
BalanceParams
Parameters for fetching account balance.
BaseExchange
Base exchange implementation
BatchCancelResult
Batch cancel order result.
BatchOrderRequest
Batch order request payload used by create_orders.
BatchOrderResult
Batch order result.
BatchOrderUpdate
Batch order update request payload used by edit_orders.
BidAsk
Best bid and ask prices data structure.
Binance
Binance exchange structure.
BinanceBuilder
Builder for creating Binance exchange instances.
Bitget
Bitget exchange structure.
BitgetBuilder
Builder for creating Bitget exchange instances.
BorrowInterest
Borrow interest record
BorrowRate
Borrow rate information for margin trading
BorrowRateHistory
Borrow rate history record
Bybit
Bybit exchange structure.
BybitBuilder
Builder for creating Bybit exchange instances.
CancelAllOrdersResult
Cancel-all orders result payload.
CancelReplaceResponse
Cancel and replace order response.
CancellationToken
A token which can be used to signal a cancellation request to one or more tasks.
CommissionRate
Commission rate information.
Cost
Cost type (zero-cost wrapper).
Currency
Currency structure representing a tradable asset
CurrencyNetwork
Currency network/chain information
Decimal
Decimal represents a 128 bit representation of a fixed-precision decimal number. The finite set of values of type Decimal are of the form m / 10e, where m is an integer such that -296 < m < 296, and e is an integer between 0 and 28 inclusive.
DepositAddress
Deposit address information for receiving funds.
DepositWithdrawFee
Deposit and withdrawal fee information.
ExchangeCapabilities
Exchange capabilities configuration
ExchangeConfig
Exchange configuration
ExchangeConfigBuilder
Builder for ExchangeConfig
ExpiryDate
Represents a futures contract expiry date in YYMMDD format
Fee
Fee information
FeeFundingRate
Funding rate structure.
FeeFundingRateHistory
Funding rate history structure.
FeeTradingFee
Trading fee structure.
FundingFee
Personal funding fee record.
FundingHistory
Funding fee history record.
FundingRate
Funding rate information.
FundingRateHistory
Funding rate history record.
HttpClient
HTTP client with retry and rate limiting support
HttpConfig
HTTP request configuration
HyperLiquid
HyperLiquid exchange structure.
HyperLiquidBuilder
Builder for creating HyperLiquid exchange instances.
IndexPrice
Index price information.
IsolatedBorrowRate
Isolated borrow rate information for margin trading
LastPrice
Latest price information.
LedgerEntry
Ledger entry structure.
Leverage
Leverage configuration for a trading symbol.
LeverageParams
Parameters for setting leverage.
LeverageTier
Leverage tier structure.
Liquidation
Liquidation order information.
LogConfig
Log configuration.
MarginAdjustment
Margin adjustment record (transfers between spot and margin accounts)
MarginLoan
Margin loan record
MarginRepay
Margin repayment record
MarkPrice
Mark price data structure.
Market
Market structure representing a trading pair
MarketBidAsk
Best bid/ask price information (book ticker).
MarketCache
Market data cache structure
MarketLimits
Market limits for order parameters
MarketPrecision
Market precision settings
MaxBorrowable
Maximum borrowable amount information.
MaxLeverage
Maximum available leverage information.
MaxTransferable
Maximum transferable amount information.
MinMax
Min/Max range for limits
MultiTierRateLimiter
Multi-tier rate limiter for exchanges with multiple rate limit tiers
NetworkInfo
Blockchain network information.
NextFundingRate
Next funding rate information.
OHLCV
OHLCV data structure (candlestick data).
OcoOrder
OCO (One-Cancels-the-Other) order.
OcoOrderInfo
OCO order info for a single order.
Ohlcv
OHLCV (Open, High, Low, Close, Volume) candlestick data
OhlcvParams
Parameters for fetching OHLCV (candlestick) data.
OhlcvRequest
OHLCV request configuration built via builder pattern.
OhlcvRequestBuilder
Builder for OhlcvRequest with validation.
Okx
OKX exchange structure.
OkxBuilder
Builder for creating OKX exchange instances.
OpenInterest
Open interest data representing the total number of outstanding derivative contracts.
OpenInterestHistory
Historical open interest data.
Order
Order structure
OrderBook
Complete order book structure
OrderBookDelta
Orderbook delta update message
OrderBookEntry
Order book entry (price level)
OrderBookParams
Parameters for fetching order book data.
OrderParams
Parameters for creating orders.
OrderReport
OCO order report with detailed status.
OrderRequest
Order request configuration built via builder pattern.
OrderRequestBuilder
Builder for OrderRequest with typestate pattern for required fields.
ParsedSymbol
Represents a parsed unified symbol with all components
Position
Trading position information.
PremiumIndex
Premium index information.
Price
Price type (zero-cost wrapper).
RateLimiter
Rate limiter using token bucket algorithm
RateLimiterConfig
Rate limiter configuration
RetryConfig
Retry configuration.
RetryStrategy
Retry strategy.
ServerTime
Server time information.
Stats24hr
24-hour statistics data.
Subscription
WebSocket subscription metadata.
SubscriptionManager
Subscription manager with capacity limits.
SymbolFormatter
Symbol formatter for converting ParsedSymbol to unified symbol strings
SymbolParser
Symbol parser for unified symbol strings
Ticker
Ticker data structure
TickerParams
Strongly typed parameters accepted by ticker endpoints.
TickerParamsBuilder
Convenience builder for TickerParams.
Trade
Trade data structure
TradingFee
Trading fee information.
TradingLimits
Trading limits for a market
Transaction
Transaction record for deposits and withdrawals.
TransactionFee
Transaction fee information.
Transfer
Transfer record between accounts.
TransferParams
Parameters for transferring funds between accounts.
WithdrawParams
Parameters for withdrawing funds.
WsClient
Async WebSocket client for exchange streaming APIs.
WsConfig
WebSocket connection configuration.
WsError
Extended WebSocket error with classification.
WsStats
WebSocket connection statistics (lock-free).
WsStatsSnapshot
Immutable snapshot of WebSocket connection statistics.

Enums§

AccountType
Account type for balance queries and transfers.
ContractType
Contract settlement type for derivatives
CountingMode
Precision counting mode.
DefaultSubType
Contract settlement type for derivatives
DefaultType
Default market type for exchange operations
DefaultTypeError
Error type for DefaultType parsing
DigestFormat
Output encoding format for cryptographic digests.
EndpointType
Endpoint type enum for distinguishing between public and private API endpoints.
Error
The primary error type for the ccxt-rust library.
HashAlgorithm
Supported cryptographic hash algorithms.
LedgerDirection
Ledger entry direction.
LedgerEntryType
Ledger entry type (CCXT standardized types).
LogFormat
Log format.
LogLevel
Log level.
MarginType
Margin type for futures positions.
MarketType
Market type enumeration
OrderSide
Order side (buy or sell)
OrderStatus
Order status
OrderType
Order type
PaddingMode
Output padding mode.
PositionSide
Position side for dual-side position mode.
PrecisionMode
Precision mode for currency operations
PriceType
Price type for OHLCV data (futures-specific).
RetryStrategyType
Retry strategy type.
RoundingMode
Rounding mode for precision calculations.
SymbolError
Symbol-related errors
SymbolMarketType
Market type derived from symbol structure
TakerOrMaker
Whether a trade is maker or taker
TimeInForce
Time in force - order validity duration
Timeframe
Timeframe enum for OHLCV data
TransactionStatus
Transaction processing status.
TransactionType
Transaction type for deposits and withdrawals.
TransferType
Transfer type for inter-account transfers.
WsConnectionState
WebSocket connection state.
WsErrorKind
WebSocket error classification.
WsEvent
WebSocket connection event types.
WsMessage
WebSocket message types for exchange communication.

Constants§

DEFAULT_MAX_SUBSCRIPTIONS
Default maximum number of subscriptions.
DEFAULT_SHUTDOWN_TIMEOUT
Default shutdown timeout in milliseconds.
VERSION
Library version

Traits§

ContextExt
Extension trait for ergonomic error context attachment.
Deserialize
A data structure that can be deserialized from any data format supported by Serde.
ErrorContextDeprecated
Helper trait for adding context to errors (legacy alias for ContextExt).
Exchange
Core Exchange trait - the unified interface for all exchanges
ExchangeExt
Extension trait providing access to modular sub-traits from Exchange.
FullExchange
Combined trait for exchanges that support both REST and WebSocket
IntoTickerParams
Trait for values convertible into TickerParams.
Serialize
A data structure that can be serialized into any data format supported by Serde.
WsExchange
WebSocket exchange trait for real-time data streaming

Functions§

base64_to_base64url
Converts standard Base64 to Base64 URL format.
base64url_decode
Decodes a Base64 URL-encoded string.
decimal_to_precision
Formats a decimal to a specific precision with configurable rounding and counting modes.
eddsa_sign
Generates an EdDSA signature using Ed25519.
hash
Computes a cryptographic hash (one-way, keyless).
hmac_sign
Generates an HMAC signature for a message.
init_logging
Initializes the logging system.
iso8601
Converts a timestamp in milliseconds to an ISO 8601 formatted string
jwt_sign
Generates a JWT (JSON Web Token).
microseconds
Returns the current time in microseconds since the Unix epoch
milliseconds
Returns the current time in milliseconds since the Unix epoch
number_to_string
Converts a decimal number to string, handling scientific notation.
parse_date
Parses a date string and returns the timestamp in milliseconds since Unix epoch
parse_iso8601
Parses an ISO 8601 date string and returns the timestamp in milliseconds
precision_from_string
Extracts precision (number of decimal places) from a string representation.
resolve_market_type
Resolves the effective market type for an API call
seconds
Returns the current time in seconds since the Unix epoch
try_init_logging
Attempts to initialize the logging system, ignoring duplicate initialization errors.
ymd
Alias for yyyymmdd function
ymdhms
Formats a timestamp as “yyyy-MM-dd HH:mm:ss”
yymmdd
Formats a timestamp as “yy-MM-dd”
yyyymmdd
Formats a timestamp as “yyyy-MM-dd”

Type Aliases§

ArcExchange
Type alias for an Arc-wrapped Exchange trait object
BoxedExchange
Type alias for a boxed Exchange trait object
MarginMode
Margin mode for futures trading.
MessageStream
WebSocket message stream type
OrderBookSide
Order book side (bids or asks)
Result
Result type alias for all CCXT operations.
Symbol
Type alias for trading symbols (e.g., “BTC/USDT”)
Timestamp
Type alias for timestamps (milliseconds since Unix epoch)

Derive Macros§

Deserialize
Serialize