A Rust library for interacting with the OKX cryptocurrency exchange API. Provides both REST and WebSocket clients for accessing real-time order book data.
- π Async/Await - Built on Tokio for high-performance async I/O
- π REST API Client - Fetch order book snapshots via HTTP
- π WebSocket Client - Real-time order book updates via WebSocket
- π‘οΈ Type-Safe - Strongly typed order book data structures
- β‘ Error Handling - Comprehensive error types with
thiserror - β Well-Tested - Unit and integration tests included
Add this to your Cargo.toml:
[dependencies]
okx_connector = "0.1.0"
tokio = { version = "1", features = ["full"] }use okx_connector::OKXRestClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create REST client
let client = OKXRestClient::new("https://www.okx.com")?;
// Fetch order book for BTC-USDT
let orderbook = client.get_order_book("BTC-USDT").await?;
println!("Timestamp: {}", orderbook.ts);
println!("Top ask: {:?}", orderbook.asks.first());
println!("Top bid: {:?}", orderbook.bids.first());
Ok(())
}use okx_connector::OKXWebSocketClient;
use tokio::sync::mpsc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create WebSocket client
let ws_client = OKXWebSocketClient::new("wss://ws.okx.com:8443/ws/v5/public");
// Create channel for receiving messages
let (tx, mut rx) = mpsc::channel(100);
// Subscribe to order book updates
tokio::spawn(async move {
ws_client.subscribe_to_order_book("BTC-USDT", tx).await
});
// Process incoming messages
while let Some(message) = rx.recv().await {
println!("Received: {}", message);
}
Ok(())
}REST API client for fetching order book snapshots.
Methods:
new(base_url: &str) -> Result<Self, OKXClientError>- Create a new REST clientget_order_book(symbol: &str) -> Result<Orderbook, OKXClientError>- Fetch order book for a symbol
WebSocket client for real-time order book updates.
Methods:
new(url: &str) -> Self- Create a new WebSocket clientsubscribe_to_order_book(symbol: &str, tx: mpsc::Sender<String>) -> Result<(), WebSocketError>- Subscribe to order book updates
Order book data structure with asks and bids.
Fields:
asks: Vec<(f64, f64)>- Ask orders (price, amount), sorted ascending by pricebids: Vec<(f64, f64)>- Bid orders (price, amount), sorted descending by pricets: u64- Timestamp in milliseconds
Methods:
from_snapshot(data: &str) -> Result<Self, OrderbookError>- Parse from JSON snapshotapply_update(update: &str) -> Result<(), OrderbookError>- Apply incremental update
The repository includes an example that demonstrates both REST and WebSocket functionality:
# Run with defaults (BTC-USDT)
cargo run --example okx_demo
# Run with custom symbol
cargo run --example okx_demo -- --symbol ETH-USDT
# Show more updates
cargo run --example okx_demo -- --update-count 20
# Using environment variables
OKX_SYMBOL=ETH-USDT cargo run --example okx_demo
# View all options
cargo run --example okx_demo -- --helpThe example uses clap for configuration and can be configured via command-line arguments or environment variables:
| Option | Short | Environment Variable | Default | Description |
|---|---|---|---|---|
--rest-url |
-r |
OKX_REST_URL |
https://www.okx.com |
REST API base URL |
--ws-url |
-w |
OKX_WS_URL |
wss://ws.okx.com:8443/ws/v5/public |
WebSocket URL |
--symbol |
-s |
OKX_SYMBOL |
BTC-USDT |
Trading symbol |
--update-count |
-u |
OKX_UPDATE_COUNT |
10 |
Number of updates to display |
--help |
-h |
- | - | Show help message |
--version |
-V |
- | - | Show version |
Run the test suite:
# Run all tests
cargo test
# Run tests with output
cargo test -- --nocapture
# Run specific test
cargo test test_get_order_book- Rust 1.90 or higher
- Cargo
# Debug build
cargo build
# Release build
cargo build --release# Run clippy linter
cargo clippy --all-targets --all-features -- -D warnings
# Format code
cargo fmt
# Check formatting
cargo fmt -- --checkokx_connector/
βββ examples/
β βββ okx_demo.rs # Example demonstrating REST and WebSocket
βββ src/
β βββ client/
β β βββ mod.rs
β β βββ rest_client.rs # REST API client
β β βββ websocket_client.rs # WebSocket client
β βββ models/
β β βββ mod.rs
β β βββ orderbook.rs # Orderbook data structure
β βββ utils/
β β βββ mod.rs
β β βββ helpers.rs # Utility functions
β βββ lib.rs # Library root
βββ Cargo.toml
βββ README.md
- Base URL:
https://www.okx.com - Endpoint:
/api/v5/market/books?instId={symbol} - Example:
https://www.okx.com/api/v5/market/books?instId=BTC-USDT
- URL:
wss://ws.okx.com:8443/ws/v5/public - Channel:
books - Subscribe Message:
{ "op": "subscribe", "args": [{ "channel": "books", "instId": "BTC-USDT" }] }
The library uses custom error types for better error handling:
OKXClientError- REST client errors (network, parsing, etc.)WebSocketError- WebSocket connection errorsOrderbookError- Order book parsing and validation errors
All errors implement std::error::Error and can be easily propagated using the ? operator.
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with Tokio for async runtime
- Uses reqwest for HTTP client
- Uses tokio-tungstenite for WebSocket client