ccxt-rust 0.1.0

Cryptocurrency exchange trading library in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# <center> CCXT-Rust </center>
___

[![Rust](https://img.shields.io/badge/rust-1.91%2B-orange.svg)](https://www.rust-lang.org/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Rust CI](https://github.com/Praying/ccxt-rust/actions/workflows/rust.yml/badge.svg)](https://github.com/Praying/ccxt-rust/actions/workflows/rust.yml)
[![Security Audit](https://github.com/Praying/ccxt-rust/actions/workflows/rust.yml/badge.svg)](https://github.com/Praying/ccxt-rust/actions/workflows/rust.yml)
[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://docs.rs/ccxt-rust)

A professional-grade Rust implementation of the CCXT (CryptoCurrency eXchange Trading) library, providing unified, type-safe access to Major cryptocurrency exchanges with high-performance async operations.

[English]README.md | [็ฎ€ไฝ“ไธญๆ–‡]README_CN.md

## ๐ŸŽฏ Supported Exchanges

| Exchange | Public API (Market Data) | Private API (Trading) | WebSocket |
|----------|--------------------------|-----------------------|-----------|
| **Binance** | โœ… | โœ… | โœ… |
| **Bitget** | โœ… | โœ… | โœ… |
| **Hyperliquid** | โœ… | โœ… | โœ… |
| **OKX** | โœ… | โœ… | โœ… |
| **Bybit** | โœ… | โœ… | โœ… |

> **Legend**: โœ… Supported, ๐Ÿšง In Progress, ๐Ÿ”„ Planned

## ๐ŸŒŸ Features

### Core Capabilities
- **โœ… Type-Safe Trading Operations** - Leverage Rust's strong type system for compile-time safety
- **โœ… Async/Await Architecture** - Built on Tokio for efficient, non-blocking I/O operations
- **โœ… Precise Financial Calculations** - Using `rust_decimal` for accurate monetary computations
- **โœ… Comprehensive Error Handling** - Structured error types with full context propagation
- **โœ… REST API Support** - Complete REST API implementation for exchange operations
- **โœ… WebSocket Real-Time Data** - Live market data streaming with automatic reconnection
- **โœ… Multi-Exchange Support** - Unified interface across multiple cryptocurrency exchanges

### Advanced Features
- **Market Data Operations**
  - Fetch tickers, order books, and OHLCV data
  - Real-time market data streaming via WebSocket
  - Advanced market data with depth and aggregation

- **Order Management**
  - Create, cancel, and modify orders
  - Support for market, limit, and conditional orders
  - OCO (One-Cancels-Other) order support
  - Batch order operations

- **Account Management**
  - Balance inquiries and account information
  - Deposit and withdrawal operations
  - Transaction history and ledger access
  - Fee management and calculation

- **Trading Features**
  - Spot trading
  - Margin trading (cross and isolated)
  - Futures trading with position management
  - Leverage and margin management

- **WebSocket Features**
  - Real-time order book updates
  - Live trade streaming
  - Account balance updates
  - Order status updates
  - Position updates for futures

## ๐Ÿ—๏ธ Architecture

The project follows a clean, modular workspace architecture with a unified Exchange trait:

```
ccxt-rust/
โ”œโ”€โ”€ ccxt-core/              # Core types, traits, and error handling
โ”‚   โ”œโ”€โ”€ types/              # Market, Order, Trade, Ticker, etc.
โ”‚   โ”œโ”€โ”€ exchange.rs         # Unified Exchange trait (NEW)
โ”‚   โ”œโ”€โ”€ ws_exchange.rs      # WebSocket Exchange trait (NEW)
โ”‚   โ”œโ”€โ”€ error.rs            # Comprehensive error types
โ”‚   โ””โ”€โ”€ base_exchange.rs    # Base exchange functionality
โ”œโ”€โ”€ ccxt-exchanges/         # Exchange-specific implementations
โ”‚   โ”œโ”€โ”€ exchange.rs         # Re-exports from ccxt-core (deprecated)
โ”‚   โ””โ”€โ”€ binance/            # Binance exchange implementation
โ”‚       โ”œโ”€โ”€ mod.rs          # Main Binance struct
โ”‚       โ”œโ”€โ”€ builder.rs      # BinanceBuilder (NEW)
โ”‚       โ”œโ”€โ”€ exchange_impl.rs # Exchange trait implementation
โ”‚       โ”œโ”€โ”€ ws_exchange_impl.rs # WsExchange trait implementation
โ”‚       โ”œโ”€โ”€ rest.rs         # REST API client
โ”‚       โ”œโ”€โ”€ ws.rs           # WebSocket client
โ”‚       โ”œโ”€โ”€ parser.rs       # Response parsing
โ”‚       โ””โ”€โ”€ auth.rs         # Authentication
โ”œโ”€โ”€ examples/               # Comprehensive usage examples
โ”œโ”€โ”€ tests/                  # Integration tests
โ””โ”€โ”€ docs/                   # Detailed documentation
```

### Unified Exchange Trait

The `Exchange` trait in `ccxt-core` provides a unified interface for all exchanges:

```rust
use ccxt_core::exchange::{Exchange, ExchangeCapabilities, BoxedExchange};

// Use any exchange through the unified interface
async fn fetch_price(exchange: &dyn Exchange, symbol: &str) -> Result<Decimal, Error> {
    // Check capability before calling
    if !exchange.capabilities().fetch_ticker {
        return Err(Error::not_implemented("fetch_ticker"));
    }
    
    let ticker = exchange.fetch_ticker(symbol).await?;
    ticker.last.ok_or_else(|| Error::invalid_response("No last price"))
}

// Use multiple exchanges polymorphically
async fn compare_prices(exchanges: &[BoxedExchange], symbol: &str) {
    for exchange in exchanges {
        println!("{}: {:?}", exchange.name(), fetch_price(exchange.as_ref(), symbol).await);
    }
}
```

### WebSocket Streaming

The `WsExchange` trait provides real-time data streaming:

```rust
use ccxt_core::ws_exchange::{WsExchange, FullExchange};
use futures::StreamExt;

async fn watch_market(exchange: &dyn WsExchange, symbol: &str) {
    exchange.ws_connect().await.unwrap();
    
    let mut stream = exchange.watch_ticker(symbol).await.unwrap();
    while let Some(Ok(ticker)) = stream.next().await {
        println!("Price: {:?}", ticker.last);
    }
}
```

## ๐Ÿš€ Quick Start

### Prerequisites

- Rust 1.91+ or later
- Cargo (latest stable)

### Installation

Add via command line:

```bash
cargo add ccxt-rust
```

Or add to your `Cargo.toml`:

```toml
[dependencies]
ccxt-core = { path = "ccxt-core" }
ccxt-exchanges = { path = "ccxt-exchanges" }
tokio = { version = "1.35", features = ["full"] }
rust_decimal = "1.39"
futures = "0.3"
```

### Basic Usage with Builder Pattern

```rust
use ccxt_exchanges::binance::Binance;
use ccxt_core::exchange::Exchange;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize exchange using the builder pattern (recommended)
    let exchange = Binance::builder()
        .api_key("your_api_key")
        .secret("your_secret")
        .sandbox(false)  // Use production API
        .build()?;

    // Fetch ticker through the unified Exchange trait
    let ticker = exchange.fetch_ticker("BTC/USDT").await?;
    println!("BTC/USDT Price: {:?}", ticker.last);

    // Fetch order book
    let orderbook = exchange.fetch_order_book("BTC/USDT", Some(10)).await?;
    if let Some(best_bid) = orderbook.bids.first() {
        println!("Best bid: {}", best_bid.price);
    }
    if let Some(best_ask) = orderbook.asks.first() {
        println!("Best ask: {}", best_ask.price);
    }

    // Place an order (requires API credentials)
    use ccxt_core::types::{OrderType, OrderSide};
    use rust_decimal_macros::dec;
    
    let order = exchange.create_order(
        "BTC/USDT",
        OrderType::Limit,
        OrderSide::Buy,
        dec!(0.001),
        Some(dec!(40000)),
    ).await?;
    println!("Order placed: {}", order.id);

    Ok(())
}
```

### Using Exchanges Polymorphically

```rust
use ccxt_core::exchange::{Exchange, BoxedExchange};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create exchange as a trait object
    let exchange: BoxedExchange = Box::new(
        ccxt_exchanges::binance::Binance::builder().build()?
    );
    
    // Use through the unified interface
    println!("Exchange: {} ({})", exchange.name(), exchange.id());
    println!("Capabilities: {:?}", exchange.capabilities());
    
    // Check capabilities before calling methods
    if exchange.capabilities().fetch_ticker {
        let ticker = exchange.fetch_ticker("BTC/USDT").await?;
        println!("Price: {:?}", ticker.last);
    }
    
    Ok(())
}
```

### WebSocket Streaming

```rust
use ccxt_exchanges::binance::Binance;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize exchange
    let exchange = Binance::builder().build()?;
    
    // Create WebSocket client
    let ws_client = exchange.create_ws();
    ws_client.connect().await?;

    // Subscribe to real-time trades
    let mut stream = ws_client.watch_trades("BTC/USDT").await?;
    
    while let Some(trade_result) = stream.next().await {
        match trade_result {
            Ok(trade) => println!("Trade: {} @ {}", trade.amount, trade.price),
            Err(e) => eprintln!("Error: {}", e),
        }
    }

    Ok(())
}
```

## ๐Ÿ“š Examples

The project includes comprehensive examples covering all major features:

- **`basic_usage.rs`** - Getting started with the library
- **`binance_market_data_example.rs`** - Market data operations
- **`binance_order_management_example.rs`** - Order creation and management
- **`binance_account_example.rs`** - Account operations
- **`binance_margin_example.rs`** - Margin trading
- **`binance_futures_example.rs`** - Futures trading
- **`binance_ws_example.rs`** - WebSocket streaming
- **`binance_conditional_orders_example.rs`** - Conditional orders
- **`binance_deposit_withdrawal_example.rs`** - Deposit/withdrawal operations

Run any example:

```bash
cargo run --example basic_usage
cargo run --example binance_ws_example
```



## ๐Ÿšฉ Feature Flags

Optimize your build by selecting only the features you need in `Cargo.toml`:

- **`default`**: Enables `rest`, `websocket`, and `rustls-tls`.
- **`rest`**: Enables REST API support.
- **`websocket`**: Enables WebSocket support.
- **`rustls-tls`**: Uses `rustls` for TLS (default, recommended).
- **`native-tls`**: Uses platform-native TLS (OpenSSL/Schannel/Secure Transport).
- **`compression`**: Enables GZIP compression for HTTP requests.
- **`full`**: Enables all features.

## ๐Ÿ”ง Configuration

### Environment Variables

Create a `.env` file from the template:

```bash
cp .env.example .env
```

Key configuration options:

```bash
# API Credentials
BINANCE_API_KEY=your_api_key_here
BINANCE_SECRET=your_secret_here

# Testing
ENABLE_PRIVATE_TESTS=false
ENABLE_INTEGRATION_TESTS=false
USE_MOCK_DATA=true
TEST_SYMBOL=BTC/USDT

# Logging
RUST_LOG=info
```

## ๐Ÿงช Testing

```bash
# Run all tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific test suite
cargo test -p ccxt-core
cargo test -p ccxt-exchanges

# Run integration tests
cargo test --test binance_integration_test

# Run with live API (requires credentials)
ENABLE_INTEGRATION_TESTS=true cargo test
```

## ๐Ÿ“– Documentation

- **[API Documentation]docs/** - Detailed API reference
- **[Testing Guide]docs/TESTING.md** - Comprehensive testing documentation
- **[Implementation Plans]docs/** - Feature implementation roadmaps
- **[Comparison Analysis]docs/GO_RUST_COMPARISON_ANALYSIS.md** - Go vs Rust implementation

Generate local documentation:

```bash
cargo doc --open
```


## ๐Ÿ› ๏ธ Development

### Building

```bash
# Debug build
cargo build

# Release build (optimized)
cargo build --release

# Build specific package
cargo build -p ccxt-core
cargo build -p ccxt-exchanges
```

### Code Quality

```bash
# Format code
cargo fmt

# Run linter
cargo clippy --all-targets --all-features

# Strict linting (no warnings)
cargo clippy --all-targets --all-features -- -D warnings

# Check compilation
cargo check --all-features
```

## ๐Ÿ” Security

- **Never commit API keys or secrets** - Always use environment variables
- **Secure credential storage** - Use system keychains or encrypted vaults
- **Rate limiting** - Built-in rate limiting to prevent API bans
- **Input validation** - All inputs are validated before API calls
- **HTTPS only** - All communications use TLS encryption

## ๐Ÿค Contributing

Contributions are welcome! Please follow these guidelines:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Follow Rust best practices and project conventions
4. Add tests for new features
5. Ensure all tests pass (`cargo test`)
6. Run formatting and linting (`cargo fmt && cargo clippy`)
7. Commit your changes (`git commit -m 'Add amazing feature'`)
8. Push to the branch (`git push origin feature/amazing-feature`)
9. Open a Pull Request

### Development Conventions

- **Code Style**: Rust 2024 edition, 100-character line width
- **Testing**: Minimum 80% test coverage
- **Documentation**: All public APIs must have documentation
- **Error Handling**: Use `thiserror` for custom errors, `anyhow` for context

## ๐Ÿ“Š Performance

Built for high performance:
- **Async I/O**: Non-blocking operations using Tokio
- **Zero-copy parsing**: Efficient JSON deserialization
- **Connection pooling**: Reused HTTP connections
- **Optimized builds**: LTO and single codegen unit for releases
- **Benchmarks**: Criterion-based performance benchmarks

## ๐Ÿ› Troubleshooting

### Common Issues

1. **Compilation errors**
   - Ensure Rust 1.91+ is installed: `rustc --version`
   - Update dependencies: `cargo update`
   - Clean build: `cargo clean && cargo build`

2. **API authentication failures**
   - Verify API keys in `.env` file
   - Check API key permissions on exchange
   - Ensure system clock is synchronized

3. **Rate limiting**
   - Reduce request frequency
   - Use WebSocket for real-time data
   - Check exchange-specific rate limits

For more help, see [documentation](docs/) or open an issue.

## ๐Ÿ“ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Inspired by the original [CCXT]https://github.com/ccxt/ccxt library
- Built with amazing Rust ecosystem libraries
- Community contributors and testers

## ๐Ÿ“ž Contact & Support

- **Issues**: [GitHub Issues]https://github.com/Praying/ccxt-rust/issues
- **Discussions**: [GitHub Discussions]https://github.com/Praying/ccxt-rust/discussions
- **Documentation**: [Project Docs]docs/

---

**Status**: ๐Ÿšง Active Development | **Version**: 0.1.0-alpha | **Updated**: 2025-12

โš ๏ธ **Note**: This library is under active development. APIs may change before v1.0. Not recommended for production use yet.