Hyperliquid SDK for Rust
The simplest way to trade on Hyperliquid. One line to place orders, zero ceremony.
use HyperliquidSDK;
async
That's it. No build-sign-send ceremony. No manual hash signing. No nonce tracking. Just trading.
Community SDK — Not affiliated with Hyperliquid Foundation.
Installation
Add to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
That's it. Everything is included: trading, Info API, WebSocket streaming, gRPC streaming, HyperCore, and EVM.
Quick Start
Endpoint Flexibility
The SDK automatically handles any endpoint format you provide:
// All of these work - the SDK extracts the token and routes correctly
let endpoint = "https://x.quiknode.pro/TOKEN";
let endpoint = "https://x.quiknode.pro/TOKEN/";
let endpoint = "https://x.quiknode.pro/TOKEN/info";
let endpoint = "https://x.quiknode.pro/TOKEN/hypercore";
let endpoint = "https://x.quiknode.pro/TOKEN/evm";
Just pass your endpoint - the SDK handles the rest.
You can create a Hyperliquid endpoint on Quicknode to get access to the data APIs.
1. Set your private key
2. Start trading
use ;
async
Data APIs
Query Hyperliquid data with clean, simple interfaces.
Info API
50+ methods for account state, positions, market data, and metadata.
let info = sdk.info;
// Market data
info.all_mids.await?; // All mid prices
info.l2_book.await?; // Order book
info.recent_trades.await?; // Recent trades
info.candles.await?; // OHLCV candles
info.funding_history.await?; // Funding history
info.predicted_fundings.await?; // Predicted funding rates
// Metadata
info.meta.await?; // Exchange metadata
info.spot_meta.await?; // Spot metadata
info.exchange_status.await?; // Exchange status
info.perp_dexs.await?; // Perpetual DEX info
info.max_market_order_ntls.await?; // Max market order notionals
// User data
info.clearinghouse_state.await?; // Positions & margin
info.spot_clearinghouse_state.await?; // Spot balances
info.open_orders.await?; // Open orders
info.frontend_open_orders.await?; // Enhanced open orders
info.order_status.await?; // Specific order status
info.historical_orders.await?; // Order history
info.user_fills.await?; // Trade history
info.user_fills_by_time.await?; // Fills by time range
info.user_funding.await?; // Funding payments
info.user_fees.await?; // Fee structure
info.user_rate_limit.await?; // Rate limit status
info.user_role.await?; // Account type
info.portfolio.await?; // Portfolio history
info.sub_accounts.await?; // Sub-accounts
info.extra_agents.await?; // API keys/agents
// TWAP
info.user_twap_slice_fills.await?; // TWAP slice fills
// Batch queries
info.batch_clearinghouse_states.await?;
// Vaults
info.vault_summaries.await?; // All vault summaries
info.vault_details.await?; // Specific vault
info.user_vault_equities.await?; // User's vault equities
info.leading_vaults.await?; // Vaults user leads
// Delegation/Staking
info.delegations.await?; // Active delegations
info.delegator_summary.await?; // Delegation summary
info.delegator_history.await?; // Delegation history
info.delegator_rewards.await?; // Delegation rewards
// Tokens
info.token_details.await?; // Token details
info.spot_deploy_state.await?; // Spot deployment state
// Other
info.referral.await?; // Referral info
info.max_builder_fee.await?; // Builder fee limits
info.approved_builders.await?; // Approved builders
info.liquidatable.await?; // Liquidatable positions
HyperCore API
Block data, trading operations, and real-time data via JSON-RPC.
let core = sdk.core;
// Block data
core.latest_block_number.await?; // Latest block
core.get_block.await?; // Get specific block
core.get_batch_blocks.await?; // Get block range
core.latest_blocks.await?; // Latest blocks
// Recent data
core.latest_trades.await?; // Recent trades (all coins)
core.latest_trades.await?; // Recent BTC trades
core.latest_orders.await?; // Recent order events
core.latest_book_updates.await?; // Recent book updates
// Discovery
core.list_dexes.await?; // All DEXes
core.list_markets.await?; // All markets
core.list_markets.await?; // Markets by DEX
// Order queries
core.open_orders.await?; // User's open orders
core.order_status.await?; // Specific order status
core.preflight.await?; // Validate order before signing
// Order building (for manual signing)
core.build_order.await?;
core.build_cancel.await?;
core.build_modify.await?;
core.build_approve_builder_fee.await?;
core.build_revoke_builder_fee.await?;
// Send signed actions
core.send_order.await?;
core.send_cancel.await?;
core.send_modify.await?;
core.send_approval.await?;
core.send_revocation.await?;
// Builder fees
core.get_max_builder_fee.await?;
// Subscriptions
core.subscribe.await?;
core.unsubscribe.await?;
EVM (Ethereum JSON-RPC)
50+ Ethereum JSON-RPC methods for Hyperliquid's EVM chain (chain ID 999 mainnet, 998 testnet).
let evm = sdk.evm;
// Chain info
evm.block_number.await?; // Latest block
evm.chain_id.await?; // 999 mainnet, 998 testnet
evm.gas_price.await?; // Current gas price
evm.max_priority_fee_per_gas.await?; // Priority fee
evm.net_version.await?; // Network version
evm.syncing.await?; // Sync status
// Accounts
evm.get_balance.await?; // Account balance
evm.get_transaction_count.await?; // Nonce
evm.get_code.await?; // Contract code
evm.get_storage_at.await?; // Storage value
// Transactions
evm.call.await?;
evm.estimate_gas.await?;
evm.send_raw_transaction.await?;
evm.get_transaction_by_hash.await?;
evm.get_transaction_receipt.await?;
// Blocks
evm.get_block_by_number.await?;
evm.get_block_by_hash.await?;
evm.get_block_receipts.await?;
evm.get_block_transaction_count_by_number.await?;
evm.get_block_transaction_count_by_hash.await?;
evm.get_transaction_by_block_number_and_index.await?;
evm.get_transaction_by_block_hash_and_index.await?;
// Logs
evm.get_logs.await?;
// Fees
evm.fee_history.await?;
// Debug/Trace (use .with_debug(true))
let evm = sdk.evm.with_debug;
evm.debug_trace_transaction.await?;
evm.trace_transaction.await?;
evm.trace_block.await?;
Real-Time Streaming
WebSocket Streaming
20+ subscription types for real-time data with automatic reconnection.
use Stream;
let mut stream = new
.on_open
.on_error
.on_reconnect;
// Subscribe to trades
stream.trades;
// Subscribe to book updates
stream.book_updates;
// Subscribe to orders (your orders)
stream.orders;
// Run in background
stream.start?;
// ... do other work ...
stream.stop?;
// Or run blocking
stream.run?;
Available WebSocket Streams:
Market Data:
trades(coins, callback)— Executed tradesbook_updates(coins, callback)— Order book changesl2_book(coin, callback)— L2 order book snapshotsall_mids(callback)— All mid price updatescandle(coin, interval, callback)— Candlestick databbo(coin, callback)— Best bid/offer updatesactive_asset_ctx(coin, callback)— Asset context (pricing, volume)
User Data:
orders(coins, callback, users)— Order lifecycle eventsopen_orders(user, callback)— User's open ordersorder_updates(user, callback)— Order status changesuser_events(user, callback)— All user eventsuser_fills(user, callback)— Trade fillsuser_fundings(user, callback)— Funding paymentsuser_non_funding_ledger(user, callback)— Ledger changesclearinghouse_state(user, callback)— Position updatesactive_asset_data(user, coin, callback)— Trading parameters
TWAP:
twap(coins, callback)— TWAP executiontwap_states(user, callback)— TWAP algorithm statesuser_twap_slice_fills(user, callback)— TWAP slice fillsuser_twap_history(user, callback)— TWAP history
System:
events(callback)— System events (funding, liquidations)notification(user, callback)— User notificationsweb_data_3(user, callback)— Aggregate user infowriter_actions(user, callback)— Writer actions
gRPC Streaming (High Performance)
Lower latency streaming via gRPC for high-frequency applications.
use GRPCStream;
let mut stream = new?;
// Subscribe to trades
stream.trades;
// Subscribe to L2 order book (aggregated by price level)
stream.l2_book;
// Subscribe to L4 order book (CRITICAL: individual orders with order IDs)
stream.l4_book;
// Subscribe to blocks
stream.blocks;
// Run in background
stream.start?;
// ... do other work ...
stream.stop?;
// Or run blocking
stream.run?;
The SDK automatically connects to port 10000 with your token.
Available gRPC Streams:
| Method | Parameters | Description |
|---|---|---|
trades(coins, callback) |
coins: &[&str] |
Executed trades with price, size, direction |
orders(coins, callback, users) |
coins: &[&str], users: Option<&[&str]> |
Order lifecycle events |
book_updates(coins, callback) |
coins: &[&str] |
Order book changes (deltas) |
l2_book(coin, callback, n_sig_figs) |
coin: &str, n_sig_figs: Option<u8> (3-5) |
L2 order book (aggregated by price) |
l4_book(coin, callback) |
coin: &str |
L4 order book (individual orders) |
blocks(callback) |
- | Block data |
twap(coins, callback) |
coins: &[&str] |
TWAP execution updates |
events(callback) |
- | System events (funding, liquidations) |
writer_actions(callback) |
- | Writer actions |
L4 Order Book (Critical for Trading)
L4 order book shows every individual order with its order ID. This is essential for:
- Market Making: Know your exact queue position
- Order Flow Analysis: Detect large orders and icebergs
- Optimal Execution: See exactly what you're crossing
- HFT: Lower latency than WebSocket
use GRPCStream;
let mut stream = new?;
stream.l4_book;
stream.run?;
L2 vs L4 Comparison
| Feature | L2 Book | L4 Book |
|---|---|---|
| Aggregation | By price level | Individual orders |
| Order IDs | No | Yes |
| Queue Position | Unknown | Visible |
| Bandwidth | Lower | Higher |
| Protocol | WebSocket or gRPC | gRPC only |
| Use Case | Price monitoring | Market making, HFT |
EVM WebSocket Streaming (eth_subscribe)
use EVMStream;
let mut evm_stream = sdk.evm_stream;
// Subscribe to new block headers
evm_stream.new_heads;
// Subscribe to contract logs
evm_stream.logs;
// Subscribe to pending transactions
evm_stream.new_pending_transactions;
evm_stream.start?;
Trading Features
One-Line Orders
// Market orders
sdk.market_buy.await.size.await?;
sdk.market_sell.await.notional.await?;
// Limit orders
sdk.buy.await?;
sdk.sell.await?;
// Perp trader aliases
sdk.long.await?;
sdk.short.await?;
Fluent Order Builder
use Order;
let order = sdk.order.await?;
Order Management
// Place, modify, cancel
let order = sdk.buy.await?;
order.modify.await?;
order.cancel.await?;
// Cancel all
sdk.cancel_all.await?;
sdk.cancel_all.await?; // Just BTC orders
// Dead-man's switch
sdk.schedule_cancel.await?;
Position Management
sdk.close_position.await?; // Close entire position
Querying Open Orders by Trading Pair
// Get all open orders
let result = sdk.open_orders.await?;
let orders = result.as_array.unwrap;
println!;
// Order fields: coin, limitPx (price), sz (size), side, oid, timestamp,
// orderType, tif, cloid, reduceOnly
for order in orders
// Filter by trading pair
for order in orders
// For enhanced data (triggers, children), use frontend_open_orders()
let addr = format!;
let enhanced = sdk.info.frontend_open_orders.await?;
Partial Position Close by Percentage
close_position() closes the entire position. To close a percentage, read the current size and place a reduce-only market order for the desired amount:
async
// Close 50% of BTC position
close_percentage.await?;
Batch Cancel with Partial Failure Handling
Cancel all orders for an asset in one call:
// Cancel all orders for a specific asset
sdk.cancel_all.await?;
// Cancel by client order ID (for CLOID-tracked orders)
sdk.cancel_by_cloid.await?;
Or cancel selectively with per-order error handling:
use Error;
// Get open orders
let result = sdk.open_orders.await?;
let orders = result.as_array.unwrap;
// Cancel specific orders with per-order error handling
let mut failures = Vecnew;
for order in orders
if !failures.is_empty
Resilient Order Placement
Use client order IDs (CLOIDs) for idempotent orders and categorize errors for retry logic:
use ;
use ErrorCode;
use Duration;
// Set a CLOID for idempotency — the exchange rejects duplicates
let order = sdk.order.await?;
// Error categories:
// Transient (retry): Error::RateLimited, Error::ApiError { code: ErrorCode::InvalidNonce, .. }
// Permanent (fail): Error::GeoBlocked, Error::ApiError { code: ErrorCode::InsufficientMargin, .. },
// Error::ValidationError(..), Error::SigningError(..), Error::ApiError { code: ErrorCode::MaxOrdersExceeded, .. }
// Already done: Error::ApiError { code: ErrorCode::DuplicateOrder, .. }
async
// Timeout configuration on SDK constructor
let sdk = new
.private_key
.timeout
.build.await?;
Leverage & Margin
// Update leverage
sdk.update_leverage.await?; // 10x cross
sdk.update_leverage.await?; // 5x isolated
// Isolated margin management
sdk.update_isolated_margin.await?; // Add margin to long
sdk.update_isolated_margin.await?; // Remove from short
sdk.top_up_isolated_only_margin.await?; // Special maintenance mode
Trigger Orders (Stop Loss / Take Profit)
use ;
// Stop loss (market order when triggered)
sdk.stop_loss.await?;
// Stop loss (limit order when triggered)
let trigger = stop_loss
.size
.trigger_price
.limit;
sdk.trigger_order.await?;
// Take profit
sdk.take_profit.await?;
// Buy-side (closing shorts)
let trigger = stop_loss
.size
.trigger_price
.side
.market;
sdk.trigger_order.await?;
TWAP Orders
// Time-weighted average price order
let result = sdk.twap_order.await?;
let twap_id = result.as_u64.unwrap;
// Cancel TWAP
sdk.twap_cancel.await?;
Transfers
// Internal transfers
sdk.transfer_spot_to_perp.await?;
sdk.transfer_perp_to_spot.await?;
// External transfers
sdk.transfer_usd.await?;
sdk.transfer_spot.await?;
sdk.send_asset.await?;
// Withdraw to L1 (Arbitrum)
sdk.withdraw.await?;
Vaults
let hlp_vault = "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303";
sdk.vault_deposit.await?;
sdk.vault_withdraw.await?;
Staking
// Stake/unstake HYPE
sdk.stake.await?;
sdk.unstake.await?; // 7-day queue
// Delegate to validators
sdk.delegate.await?;
sdk.undelegate.await?;
Builder Fee
// Check approval
let status = sdk.approval_status.await?;
// Approve builder fee
sdk.approve_builder_fee.await?;
// Revoke
sdk.revoke_builder_fee.await?;
Agent/API Key Management
// Approve an agent to trade on your behalf
sdk.approve_agent.await?;
Account Abstraction
// Set abstraction mode
sdk.set_abstraction.await?;
sdk.set_abstraction.await?;
sdk.set_abstraction.await?;
// As an agent
sdk.agent_set_abstraction.await?;
Advanced Transfers
// Send asset between DEXs
sdk.send_asset.await?;
// Send to EVM with data
sdk.send_to_evm_with_data.await?;
Additional Operations
// Cancel by client order ID
sdk.cancel_by_cloid.await?;
// Reserve rate limit capacity
sdk.reserve_request_weight.await?;
// No-op (consume nonce)
sdk.noop.await?;
// Preflight validation
sdk.preflight.await?;
// Refresh markets cache
sdk.refresh_markets.await?;
Error Handling
All errors are typed with specific error codes and guidance.
use Error;
use ErrorCode;
match sdk.market_buy.await.notional.await
Available Error Types:
Error::ApiError— Base API error with code and messageError::BuildError— Order building failedError::SendError— Transaction send failedError::ApprovalRequired— Builder fee approval neededError::ValidationError— Invalid parametersError::SignatureError— Signature verification failedError::NoPosition— No position to closeError::OrderNotFound— Order not foundError::GeoBlocked— Region blockedError::InsufficientMargin— Not enough marginError::LeverageError— Invalid leverageError::RateLimited— Rate limitedError::MaxOrders— Too many ordersError::ReduceOnlyError— Reduce-only constraintError::DuplicateOrder— Duplicate orderError::UserNotFound— User not foundError::MustDeposit— Deposit requiredError::InvalidNonce— Invalid nonce
API Reference
HyperliquidSDK (Trading)
new
.endpoint // Endpoint URL
.private_key // Falls back to PRIVATE_KEY env var
.auto_approve // Auto-approve builder fee (default: true)
.max_fee // Max fee for auto-approval
.slippage // Default slippage for market orders (3%)
.timeout // Request timeout in seconds
.build
.await?;
Info (Account & Metadata)
new;
HyperCore (Blocks & Trades)
new;
EVM (Ethereum JSON-RPC)
EVMnew;
EVMnew.with_debug; // Enable debug/trace methods
Stream (WebSocket)
new
.on_error // Error callback
.on_close // Close callback
.on_open // Open callback
.on_reconnect; // Reconnect callback
GRPCStream (gRPC)
new?; // Token extracted from endpoint
EVMStream (EVM WebSocket)
new;
Environment Variables
| Variable | Description |
|---|---|
PRIVATE_KEY |
Your Ethereum private key (hex, with or without 0x) |
ENDPOINT |
Endpoint URL |
Performance
The SDK is designed for high performance:
- Zero-copy where possible
- Connection pooling via reqwest
- Lock-free data structures (DashMap)
- Efficient MessagePack serialization
- Lazy initialization of sub-clients
Examples
See the hyperliquid-examples repository for 44 complete, runnable examples covering trading, streaming, market data, and more.
Disclaimer
This is an unofficial community SDK. It is not affiliated with Hyperliquid Foundation or Hyperliquid Labs.
Use at your own risk. Always review transactions before signing.
License
MIT License - see LICENSE for details.