High-performance Rust implementation of the Paradex SDK for decentralized derivatives trading
Complete Rust implementation of the Paradex SDK, built with Rust's performance and type safety.
use paradex_rs::{Paradex, Environment, Order, OrderSide, OrderType};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize client
let paradex = Paradex::with_l1_credentials(
Environment::Testnet,
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"0x1234..."
).await?;
// Fetch markets
let markets = paradex.api_client().lock().unwrap()
.fetch_markets().await?;
// Create and submit order
let mut order = Order::builder()
.market("BTC-USD-PERP")
.side(OrderSide::Buy)
.order_type(OrderType::Limit)
.size("0.1")
.price("50000")
.build()?;
paradex.account().unwrap().lock().unwrap().sign_order(&mut order)?;
let result = paradex.api_client().lock().unwrap()
.submit_order(&order).await?;
println!("Order submitted: {}", result.id);
Ok(())
}Add to your Cargo.toml:
[dependencies]
paradex-rs = "0.1"
tokio = { version = "1", features = ["full"] }-
Account Management
- L1 to L2 key derivation from Ethereum
- Stark key generation
- Account address computation
- Subkey support for L2-only authentication
-
Message Signing
- Order signing (EIP-712 on Starknet)
- Authentication & onboarding signing
- Block trade & offer signing
- Fullnode RPC message signing
-
REST API (50+ endpoints)
- Public: Markets, orderbook, trades, funding
- Private: Account, orders, positions, fills
- Batch operations (submit, cancel)
- Block trades (10+ endpoints)
-
WebSocket (15+ channels)
- Real-time market data (BBO, trades, orderbook)
- Account updates (orders, fills, positions)
- Auto-reconnect & ping/pong
- Type-safe callback system
-
Authentication
- JWT token management
- Auto-refresh (4-minute interval)
- Onboarding flow
use paradex_rs::{Paradex, Environment};
let paradex = Paradex::new(Environment::Testnet)?;
// Fetch markets
let markets = paradex.api_client().lock().unwrap()
.fetch_markets().await?;
// Get orderbook
let orderbook = paradex.api_client().lock().unwrap()
.fetch_orderbook("BTC-USD-PERP", Some(10)).await?;
// Get BBO (best bid/offer)
let bbo = paradex.api_client().lock().unwrap()
.fetch_bbo("BTC-USD-PERP").await?;// Initialize with L1 credentials (derives L2 key)
let paradex = Paradex::with_l1_credentials(
Environment::Testnet,
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"0x1234567890abcdef..."
).await?;
// Or use L2 key directly
let paradex = Paradex::with_l2_credentials(
Environment::Testnet,
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"0xabcdef1234567890..."
).await?;
// Fetch account summary
let summary = paradex.api_client().lock().unwrap()
.fetch_account_summary().await?;use paradex_rs::{Order, OrderSide, OrderType, OrderInstruction};
// Create order
let mut order = Order::builder()
.market("BTC-USD-PERP")
.side(OrderSide::Buy)
.order_type(OrderType::Limit)
.size("0.1")
.price("50000")
.instruction(OrderInstruction::PostOnly)
.client_id("my-order-123")
.build()?;
// Sign order
paradex.account().unwrap().lock().unwrap()
.sign_order(&mut order)?;
// Submit order
let result = paradex.api_client().lock().unwrap()
.submit_order(&order).await?;
// Cancel order
paradex.api_client().lock().unwrap()
.cancel_order(&result.id).await?;// Submit multiple orders at once
let orders = vec![order1, order2, order3];
let result = paradex.api_client().lock().unwrap()
.submit_orders_batch(&orders).await?;
// Cancel multiple orders
paradex.api_client().lock().unwrap()
.cancel_orders_batch(Some(&order_ids), None).await?;use paradex_rs::WebSocketChannel;
let ws = paradex.ws_client();
ws.lock().unwrap().connect().await?;
// Subscribe to BBO
ws.lock().unwrap().subscribe(
WebSocketChannel::BBO,
Some("BTC-USD-PERP"),
|message| Box::pin(async move {
println!("BBO Update: {:?}", message);
})
).await?;
// Subscribe to trades
ws.lock().unwrap().subscribe(
WebSocketChannel::Trades,
Some("BTC-USD-PERP"),
|message| Box::pin(async move {
println!("Trade: {:?}", message);
})
).await?;
// Subscribe to private order updates
ws.lock().unwrap().subscribe(
WebSocketChannel::Orders,
Some("BTC-USD-PERP"),
|message| Box::pin(async move {
println!("Order Update: {:?}", message);
})
).await?;use paradex_rs::ParadexSubkey;
// No L1 credentials needed
let paradex = ParadexSubkey::new(
Environment::Testnet,
"0xabcdef...", // L2 private key
"0x123456..." // L2 address
).await?;
// Full API access with subkey
let positions = paradex.api_client().lock().unwrap()
.fetch_positions().await?;use paradex_rs::{BlockTradeRequest, BlockExecuteRequest};
// Create block trade
let block_trade = BlockTradeRequest {
markets: vec!["BTC-USD-PERP".to_string()],
required_signers: vec!["0x123...".to_string()],
signature: "...".to_string(),
signature_timestamp: 1234567890,
};
let result = paradex.api_client().lock().unwrap()
.create_block_trade(&block_trade).await?;
// Execute block trade
let execution = BlockExecuteRequest {
offer_ids: vec!["offer123".to_string()],
};
paradex.api_client().lock().unwrap()
.execute_block_trade(&result.block_id, &execution).await?;System & Markets (Public)
fetch_system_config()- System configurationfetch_system_state()- System statusfetch_system_time()- Server timefetch_markets()- All marketsfetch_markets_summary()- Market summariesfetch_klines()- OHLCV candlestick datafetch_orderbook()- Order bookfetch_bbo()- Best bid/offerfetch_trades()- Public tradesfetch_funding_data()- Funding datafetch_insurance_fund()- Insurance fund info
Account (Private)
fetch_account_summary()- Account summaryfetch_account_profile()- Profile datafetch_account_info()- Account infofetch_subaccounts()- Sub-accounts listfetch_balances()- All balancesfetch_positions()- All positions
Orders (Private)
fetch_orders()- Open ordersfetch_orders_history()- Order historyfetch_order()- Get order by IDfetch_order_by_client_id()- Get order by client IDsubmit_order()- Submit single ordersubmit_orders_batch()- Submit multiple ordersmodify_order()- Modify existing ordercancel_order()- Cancel ordercancel_order_by_client_id()- Cancel by client IDcancel_all_orders()- Cancel all orderscancel_orders_batch()- Cancel multiple orders
Trading History (Private)
fetch_fills()- Fill historyfetch_tradebusts()- Tradebust historyfetch_funding_payments()- Funding paymentsfetch_transactions()- Transaction historyfetch_transfers()- Transfer historyfetch_liquidations()- Liquidation historyfetch_points_data()- Points program data
Block Trades (Private)
list_block_trades()- List all block tradescreate_block_trade()- Create new block tradeget_block_trade()- Get block trade detailscancel_block_trade()- Cancel block tradeexecute_block_trade()- Execute block tradeget_block_trade_offers()- Get all offerscreate_block_trade_offer()- Create offerget_block_trade_offer()- Get specific offercancel_block_trade_offer()- Cancel offerexecute_block_trade_offer()- Execute offer
Public Channels
BBO- Best bid/offer updatesTrades- Trade updatesOrderBook- Orderbook snapshotsMarketsSummary- Market summary updatesFundingData- Funding data updatesFundingRateComparison- Funding rate comparison
Private Channels (require auth)
Account- Account updatesBalanceEvents- Balance event updatesOrders- Order updatesFills- Fill updatesPositions- Position updatesFundingPayments- Funding payment updatesTradebusts- Tradebust notificationsTransactions- Transaction updatesTransfers- Transfer updates
paradex-rs/
βββ src/
β βββ lib.rs # Main entry point
β βββ environment.rs # Environment config
β βββ constants.rs # Constants
β βββ error.rs # Error types
β βββ subkey.rs # Subkey support
β βββ types/ # Type definitions
β β βββ models.rs # API models
β β βββ order.rs # Order types
β β βββ block_trades.rs # Block trade types
β βββ account/ # Account management
β β βββ account.rs # Main account
β β βββ key_derivation.rs # Key derivation
β β βββ signing.rs # Message signing
β β βββ block_trades_signing.rs # Block trade signing
β βββ message/ # Message builders
β β βββ typed_data.rs # EIP-712 structures
β β βββ order.rs # Order messages
β β βββ auth.rs # Auth messages
β β βββ onboarding.rs # Onboarding messages
β β βββ block_trades.rs # Block trade messages
β βββ api/ # API clients
β β βββ client.rs # REST API (50+ endpoints)
β β βββ http_client.rs # HTTP wrapper
β β βββ auth.rs # Authentication
β β βββ block_trades.rs # Block trades API
β β βββ ws_client.rs # WebSocket facade
β β βββ ws_client_impl.rs # WebSocket implementation
β βββ utils/ # Utilities
β βββ mod.rs # Helper functions
βββ examples/ # Examples
βββ basic_api_usage.rs # Public API
βββ order_management.rs # Orders
βββ fetch_account_data.rs # Account data
βββ complete_workflow.rs # Full workflow
βββ websocket_realtime.rs # WebSocket
# Public API (no auth required)
cargo run --example basic_api_usage
# Order management (requires credentials)
cargo run --example order_management
# Complete workflow
cargo run --example complete_workflow
# WebSocket real-time data
cargo run --example websocket_realtime# Run all tests
cargo test
# Run with logging
RUST_LOG=debug cargo test -- --nocapture
# Build documentation
cargo doc --open| Feature | Python SDK | Rust SDK |
|---|---|---|
| Core | ||
| Environment config | β | β |
| Error handling | β | β |
| Account | ||
| L1 key derivation | β | β |
| L2 key management | β | β |
| Subkey support | β | β |
| Message signing | β | β |
| REST API | ||
| 50+ endpoints | β | β |
| Batch operations | β | β |
| Block trades (10 endpoints) | β | β |
| WebSocket | ||
| 15+ channels | β | β |
| Auto-reconnect | β | β |
| Callbacks | β | β |
| Auth | ||
| JWT management | β | β |
| Auto-refresh | β | β |
| Overall | 100% | 100% |
- Migration Guide - Python β Rust transition
- Examples - Working code samples
- Paradex Docs - Official API docs
// With custom timeouts and settings
let paradex = Paradex::new(Environment::Testnet)?;
// Manual auth refresh
paradex.refresh_auth_if_needed().await?;// Compile-time type checking
let order = Order::builder()
.market("BTC-USD-PERP")
.side(OrderSide::Buy) // Enum, not string
.order_type(OrderType::Limit)
.size("0.1")
.build()?; // Returns Resultuse paradex_rs::ParadexError;
match paradex.api_client().lock().unwrap().fetch_markets().await {
Ok(markets) => println!("Got {} markets", markets.results.len()),
Err(ParadexError::ApiError { status, message }) => {
eprintln!("API error {}: {}", status, message);
}
Err(e) => eprintln!("Error: {}", e),
}let paradex = Paradex::with_l1_credentials(
Environment::Testnet,
"0xYourEthAddress",
"0xYourEthPrivateKey"
).await?;let paradex = Paradex::with_l2_credentials(
Environment::Testnet,
"0xYourEthAddress",
"0xYourL2PrivateKey"
).await?;let paradex = ParadexSubkey::new(
Environment::Testnet,
"0xYourL2PrivateKey",
"0xYourL2Address"
).await?;- Type Safety - Compile-time guarantees, no runtime surprises
- Performance - Zero-cost abstractions, minimal allocations
- Memory Safety - No garbage collector, predictable performance
- Concurrency - Safe concurrent operations with Tokio
- Reliability - Strong error handling, no exceptions
Contributions welcome! Areas for enhancement:
- Additional examples and tutorials
- Performance optimizations
- Extended test coverage
- Documentation improvements
MIT License
This SDK is provided as-is. Always test thoroughly on testnet before using in production. Not affiliated with or endorsed by Paradex.
Built with β€οΈ in Rust