### Initialize InfoClient for Market Data Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Creates an info client for querying market data and user state. Supports optional automatic WebSocket reconnection. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient}; #[tokio::main] async fn main() { // Standard client let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)) .await .expect("Failed to create info client"); // Client with automatic WebSocket reconnection let info_client_reconnect = InfoClient::with_reconnect(None, Some(BaseUrl::Mainnet)) .await .expect("Failed to create reconnecting info client"); println!("Info clients created successfully"); } ``` -------------------------------- ### Place Take Profit and Stop Loss Orders Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Demonstrates how to place take profit and stop loss orders. Ensure `reduce_only` is set to true for closing existing positions. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{ BaseUrl, ClientOrder, ClientOrderRequest, ClientTrigger, ExchangeClient, }; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Take profit order let take_profit = ClientOrderRequest { asset: "ETH".to_string(), is_buy: false, // Sell to close long reduce_only: true, limit_px: 2000.0, sz: 0.01, cloid: None, order_type: ClientOrder::Trigger(ClientTrigger { trigger_px: 2000.0, is_market: true, // Execute as market order when triggered tpsl: "tp".to_string(), // "tp" for take profit, "sl" for stop loss }), }; let response = exchange_client.order(take_profit, None).await.unwrap(); println!("Take profit order: {:?}", response); // Stop loss order let stop_loss = ClientOrderRequest { asset: "ETH".to_string(), is_buy: false, reduce_only: true, limit_px: 1700.0, sz: 0.01, cloid: None, order_type: ClientOrder::Trigger(ClientTrigger { trigger_px: 1700.0, is_market: true, tpsl: "sl".to_string(), }), }; let response = exchange_client.order(stop_loss, None).await.unwrap(); println!("Stop loss order: {:?}", response); } ``` -------------------------------- ### Subscribe to Real-time Market Data via WebSocket Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Establish a WebSocket connection using `InfoClient` to subscribe to real-time market data, such as all mid prices. Requires setting up an MPSC channel for message handling and handling potential connection losses. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient, Message, Subscription}; use tokio::sync::mpsc::unbounded_channel; #[tokio::main] async fn main() { let mut info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let (sender, mut receiver) = unbounded_channel(); // Subscribe to all mid prices let sub_id = info_client .subscribe(Subscription::AllMids, sender.clone()) .await .unwrap(); println!("Subscribed with ID: {}", sub_id); // Process messages while let Some(msg) = receiver.recv().await { match msg { Message::AllMids(all_mids) => { let mids = &all_mids.data.mids; if let Some(eth_price) = mids.get("ETH") { println!("ETH mid price: {}", eth_price); } } Message::NoData => { println!("Connection lost, waiting for reconnect..."); } _ => {} } } } ``` -------------------------------- ### Query Market Data with InfoClient Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Use InfoClient to fetch perpetual and spot market metadata, mid prices, L2 order book snapshots, recent trades, and historical candle data. Ensure necessary imports and async runtime are set up. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient}; #[tokio::main] async fn main() { let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); // Get perpetual market metadata let meta = info_client.meta().await.unwrap(); for asset in &meta.universe { println!("Asset: {} - Max leverage: {}x, Size decimals: {}", asset.name, asset.max_leverage, asset.sz_decimals); } // Get spot market metadata let spot_meta = info_client.spot_meta().await.unwrap(); println!("Spot tokens: {:?}", spot_meta.tokens); // Get all mid prices let mids = info_client.all_mids().await.unwrap(); for (asset, price) in &mids { println!("{}: ${}", asset, price); } // Get L2 order book snapshot let l2 = info_client.l2_snapshot("ETH".to_string()).await.unwrap(); println!("ETH L2 book - Bids: {:?}, Asks: {:?}", l2.levels.get(0), l2.levels.get(1)); // Get recent trades let trades = info_client.recent_trades("ETH".to_string()).await.unwrap(); for trade in trades.iter().take(5) { println!("Trade: {} {} @ {} at {}", trade.side, trade.sz, trade.px, trade.time); } // Get candle data let start = 1690540602225u64; let end = 1690569402225u64; let candles = info_client .candles_snapshot("ETH".to_string(), "1h".to_string(), start, end) .await .unwrap(); for candle in &candles { println!("Candle: O:{} H:{} L:{} C:{} V:{}", candle.open, candle.high, candle.low, candle.close, candle.vlm); } } ``` -------------------------------- ### Initialize ExchangeClient for Trading Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Creates a new exchange client for executing trades using an Ethereum wallet. Supports mainnet, testnet, or localhost environments. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { // Parse private key into a wallet signer let wallet: PrivateKeySigner = "your_private_key_hex" .parse() .expect("Failed to parse private key"); // Create exchange client for testnet let exchange_client = ExchangeClient::new( None, // Optional reqwest::Client wallet, // Wallet for signing Some(BaseUrl::Testnet), // BaseUrl::Mainnet, Testnet, or Localhost None, // Optional pre-fetched Meta None, // Optional vault address ) .await .expect("Failed to create exchange client"); println!("Exchange client created successfully"); } ``` -------------------------------- ### Query User State and Positions Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Use `InfoClient` to retrieve user account details, including margin, positions, token balances, and fee rates. Requires user's address. ```rust use alloy::primitives::Address; use hyperliquid_rust_sdk::{BaseUrl, InfoClient}; #[tokio::main] async fn main() { let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let user: Address = "0xc64cc00b46101bd40aa1c3121195e85c0b0918d8".parse().unwrap(); // Get user clearinghouse state (positions, margin) let user_state = info_client.user_state(user).await.unwrap(); println!("Account value: {}", user_state.margin_summary.account_value); println!("Withdrawable: {}", user_state.withdrawable); for position in &user_state.asset_positions { println!("Position: {} - Size: {}, Entry: {}, PnL: {}", position.position.coin, position.position.szi, position.position.entry_px.as_deref().unwrap_or("N/A"), position.position.unrealized_pnl); } // Batch query multiple users let users = vec![user]; let states = info_client.user_states(users).await.unwrap(); println!("Batch states: {:?}", states); // Get spot token balances let balances = info_client.user_token_balances(user).await.unwrap(); for balance in &balances.balances { println!("Token: {} - Total: {}", balance.coin, balance.total); } // Get user fee rates let fees = info_client.user_fees(user).await.unwrap(); println!("Maker rate: {}, Taker rate: {}", fees.fee_schedule.add, fees.fee_schedule.taker); } ``` -------------------------------- ### Open and Close Market Orders in Rust Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Demonstrates opening a long market position and closing the entire position for a given asset. Configurable slippage tolerance can be provided. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{ BaseUrl, ExchangeClient, ExchangeDataStatus, ExchangeResponseStatus, MarketOrderParams, MarketCloseParams, }; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Open a market long position let market_open_params = MarketOrderParams { asset: "ETH", is_buy: true, sz: 0.01, px: None, // Optional price override (uses mid price if None) slippage: Some(0.01), // 1% slippage tolerance (default 5%) cloid: None, wallet: None, // Uses exchange client's wallet if None }; let response = exchange_client.market_open(market_open_params).await.unwrap(); println!("Market open response: {:?}", response); // Close the entire position let market_close_params = MarketCloseParams { asset: "ETH", sz: None, // None closes entire position px: None, slippage: Some(0.01), cloid: None, wallet: None, }; let response = exchange_client.market_close(market_close_params).await.unwrap(); println!("Market close response: {:?}", response); } ``` -------------------------------- ### Add Hyperliquid Rust SDK to Cargo.toml Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Add the SDK dependency to your project's Cargo.toml file to include it in your build. ```toml [dependencies] hyperliquid_rust_sdk = "0.6.0" ``` -------------------------------- ### Place a Limit Order on Hyperliquid Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Places a limit order for a specified asset with a given price and size. Handles different order statuses like Filled, Resting, or Error. ```rust use std::{thread::sleep, time::Duration}; use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{ BaseUrl, ClientLimit, ClientOrder, ClientOrderRequest, ExchangeClient, ExchangeDataStatus, ExchangeResponseStatus, }; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Create a limit buy order for ETH let order = ClientOrderRequest { asset: "ETH".to_string(), is_buy: true, reduce_only: false, limit_px: 1800.0, // Price in USD sz: 0.01, // Size in ETH cloid: None, // Optional client order ID (UUID) order_type: ClientOrder::Limit(ClientLimit { tif: "Gtc".to_string(), // Good-til-cancelled, "Ioc" (immediate-or-cancel), or "Alo" (add liquidity only) }), }; let response = exchange_client.order(order, None).await.unwrap(); match response { ExchangeResponseStatus::Ok(exchange_response) => { let status = exchange_response.data.unwrap().statuses[0].clone(); match status { ExchangeDataStatus::Filled(order) => { println!("Order filled! OID: {}, Avg price: {}, Size: {}", order.oid, order.avg_px, order.total_sz); } ExchangeDataStatus::Resting(order) => { println!("Order resting on book. OID: {}", order.oid); } ExchangeDataStatus::Error(e) => println!("Order error: {}", e), _ => println!("Other status: {:?}", status), } } ExchangeResponseStatus::Err(e) => println!("Exchange error: {}", e), } } ``` -------------------------------- ### Basic Market Making Strategy Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Implements a basic market making strategy by continuously quoting buy and sell orders around the current market price. It adjusts quotes based on price movements and maintains a target liquidity. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{MarketMaker, MarketMakerInput}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let input = MarketMakerInput { asset: "ETH".to_string(), target_liquidity: 1.0, // Amount to quote on each side half_spread: 10, // 10 bps = 0.1% half spread max_bps_diff: 5, // Requote if price moves 5 bps max_absolute_position_size: 5.0, // Max position in ETH decimals: 2, // Price decimals wallet, }; let mut market_maker = MarketMaker::new(input).await; // Start market making (runs indefinitely) market_maker.start().await; } ``` -------------------------------- ### Approve Agent for Delegated Trading Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Generates a new agent private key and approves it to trade on behalf of the main account using the `ExchangeClient`. Requires a private key for the main account to sign the approval transaction. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Approve a new random agent wallet let (agent_private_key, response) = exchange_client.approve_agent(None).await.unwrap(); println!("Agent private key: 0x{}", hex::encode(agent_private_key)); println!("Approval response: {:?}", response); // The agent can now trade using the returned private key let agent_wallet: PrivateKeySigner = hex::encode(agent_private_key).parse().unwrap(); println!("Agent address: {:?}", agent_wallet.address()); } ``` -------------------------------- ### Modify Orders in Rust Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Demonstrates how to modify an existing order by updating its price and size, and how to perform a bulk modification of multiple orders. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{ BaseUrl, ClientLimit, ClientModifyRequest, ClientOrder, ClientOrderRequest, ExchangeClient, }; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); let modify_request = ClientModifyRequest { oid: 123456789, // Existing order ID to modify order: ClientOrderRequest { asset: "ETH".to_string(), is_buy: true, reduce_only: false, limit_px: 1850.0, // New price sz: 0.02, // New size cloid: None, order_type: ClientOrder::Limit(ClientLimit { tif: "Gtc".to_string(), }), }, }; let response = exchange_client.modify(modify_request, None).await.unwrap(); println!("Modify response: {:?}", response); // Bulk modify multiple orders let modifies = vec![modify_request]; let response = exchange_client.bulk_modify(modifies, None).await.unwrap(); println!("Bulk modify response: {:?}", response); } ``` -------------------------------- ### Query Open and Historical Orders Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Retrieve open orders, query specific orders by OID, and fetch historical trades using `InfoClient`. Requires user's address. ```rust use alloy::primitives::Address; use hyperliquid_rust_sdk::{BaseUrl, InfoClient}; #[tokio::main] async fn main() { let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let user: Address = "0xc64cc00b46101bd40aa1c3121195e85c0b0918d8".parse().unwrap(); // Get all open orders let open_orders = info_client.open_orders(user).await.unwrap(); for order in &open_orders { println!("Open order: {} {} {} @ {} (OID: {})", order.side, order.sz, order.coin, order.limit_px, order.oid); } // Query specific order by OID let order_status = info_client.query_order_by_oid(user, 26342632321).await.unwrap(); println!("Order status: {}", order_status.status); if let Some(order) = order_status.order { println!("Order details: {:?}", order); } // Get historical orders let historical = info_client.historical_orders(user).await.unwrap(); println!("Historical orders count: {}", historical.len()); // Get user fills (trade history) let fills = info_client.user_fills(user).await.unwrap(); for fill in fills.iter().take(5) { println!("Fill: {} {} {} @ {} - PnL: {}", fill.side, fill.sz, fill.coin, fill.px, fill.closed_pnl); } } ``` -------------------------------- ### Subscribe to L2 Order Book Stream Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Connects to the L2 order book stream for a specified asset (e.g., ETH) and prints the best bid and ask. Includes logic to unsubscribe after a set duration. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient, Message, Subscription}; use tokio::{spawn, sync::mpsc::unbounded_channel, time::{sleep, Duration}}; #[tokio::main] async fn main() { let mut info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let (sender, mut receiver) = unbounded_channel(); let subscription_id = info_client .subscribe( Subscription::L2Book { coin: "ETH".to_string() }, sender, ) .await .unwrap(); // Unsubscribe after 30 seconds spawn(async move { sleep(Duration::from_secs(30)).await; println!("Unsubscribing..."); info_client.unsubscribe(subscription_id).await.unwrap(); }); while let Some(Message::L2Book(l2_book)) = receiver.recv().await { let data = &l2_book.data; println!("L2 Book for {} at time {}", data.coin, data.time); if let Some(bids) = data.levels.get(0) { println!(" Best bid: {:?}", bids.first()); } if let Some(asks) = data.levels.get(1) { println!(" Best ask: {:?}", asks.first()); } } } ``` -------------------------------- ### Set Referral Code and Query Referral State Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Sets a referral code for the user's account and queries the current referral state, including cumulative volume, unclaimed rewards, and who referred the user. ```rust use alloy::signers::local::PrivateKeySigner; use alloy::primitives::Address; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient, InfoClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let address = wallet.address(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); // Set referrer code let response = exchange_client .set_referrer("REFERRAL_CODE".to_string(), None) .await .unwrap(); println!("Set referrer: {:?}", response); // Query referral state let referral = info_client.query_referral_state(address).await.unwrap(); println!("Cumulative volume: {}", referral.cum_vlm); println!("Unclaimed rewards: {}", referral.unclaimed_rewards); println!("Claimed rewards: {}", referral.claimed_rewards); if let Some(referred_by) = referral.referred_by { println!("Referred by: {:?}", referred_by); } } ``` -------------------------------- ### Retrieve Funding Rate History Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Fetch historical funding rates for a specific asset or retrieve a user's funding payment history. Requires an `InfoClient` instance and time range parameters. ```rust use alloy::primitives::Address; use hyperliquid_rust_sdk::{BaseUrl, InfoClient}; #[tokio::main] async fn main() { let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let user: Address = "0xc64cc00b46101bd40aa1c3121195e85c0b0918d8".parse().unwrap(); let start_time = 1690540602225u64; let end_time = 1690569402225u64; // Get funding rate history for an asset let funding_history = info_client .funding_history("ETH".to_string(), start_time, Some(end_time)) .await .unwrap(); for funding in &funding_history { println!("Funding rate: {} at {} - Premium: {}", funding.funding_rate, funding.time, funding.premium); } // Get user's funding payments let user_funding = info_client .user_funding_history(user, start_time, Some(end_time)) .await .unwrap(); for payment in &user_funding { println!("Funding payment: {:?} at {}", payment.delta, payment.time); } } ``` -------------------------------- ### Market Data Queries Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Retrieve market metadata, prices, order books, and historical data for perpetual and spot markets. ```APIDOC ## Market Data Queries Retrieves market metadata, prices, order books, and historical data. ### Get Perpetual Market Metadata **Endpoint:** `/meta` **Method:** GET **Description:** Fetches metadata for all perpetual markets, including leverage and size decimals. ### Get Spot Market Metadata **Endpoint:** `/spot_meta` **Method:** GET **Description:** Retrieves metadata for available spot tokens. ### Get All Mid Prices **Endpoint:** `/all_mids` **Method:** GET **Description:** Fetches the current mid-price for all listed assets. ### Get L2 Order Book Snapshot **Endpoint:** `/l2_snapshot` **Method:** GET **Parameters:** - **asset** (string) - Required - The trading asset (e.g., "ETH"). **Description:** Retrieves the Level 2 order book snapshot for a given asset. ### Get Recent Trades **Endpoint:** `/recent_trades` **Method:** GET **Parameters:** - **asset** (string) - Required - The trading asset (e.g., "ETH"). **Description:** Fetches a list of recent trades for a specified asset. ### Get Candle Data **Endpoint:** `/candles_snapshot` **Method:** GET **Parameters:** - **asset** (string) - Required - The trading asset (e.g., "ETH"). - **interval** (string) - Required - The candle interval (e.g., "1h", "1d"). - **start** (u64) - Required - The start timestamp in milliseconds. - **end** (u64) - Required - The end timestamp in milliseconds. **Description:** Retrieves historical candle data for a given asset and interval within a specified time range. ``` -------------------------------- ### WebSocket Subscriptions Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Subscribe to real-time market data and user events via WebSocket. ```APIDOC ## WebSocket Subscriptions Subscribes to real-time market data and user events via WebSocket. ### Subscribe to Market Data **Method:** WebSocket **Description:** Establishes a WebSocket connection to receive real-time market data updates. **Subscriptions Available:** - `Subscription::AllMids`: Subscribe to all mid prices. - Other subscription types may be available (refer to SDK documentation for a complete list). **Message Handling:** Messages received via WebSocket are of type `Message`. Common variants include: - `Message::AllMids(AllMidsData)`: Contains real-time mid-price data. - `Message::NoData`: Indicates a connection loss, requiring reconnection. **Example Usage:** 1. Create an `InfoClient`. 2. Create an unbounded channel for sending and receiving messages. 3. Call `info_client.subscribe()` with the desired `Subscription` and sender. 4. Process incoming `Message` variants from the receiver. ``` -------------------------------- ### Subscribe to User Events Stream Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Listens for real-time user-specific events, such as trade fills and position updates, for a given Ethereum address. Requires the `alloy` crate for address manipulation. ```rust use alloy::primitives::address; use hyperliquid_rust_sdk::{BaseUrl, InfoClient, Message, Subscription, UserData}; use tokio::sync::mpsc::unbounded_channel; #[tokio::main] async fn main() { let mut info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let user = address!("0xc64cc00b46101bd40aa1c3121195e85c0b0918d8"); let (sender, mut receiver) = unbounded_channel(); info_client .subscribe(Subscription::UserEvents { user }, sender) .await .unwrap(); while let Some(Message::User(user_event)) = receiver.recv().await { match user_event.data { UserData::Fills(fills) => { for fill in fills { println!("Fill: {} {} {} @ {}", fill.side, fill.sz, fill.coin, fill.px); } } _ => println!("User event: {:?}", user_event.data), } } } ``` -------------------------------- ### Update Leverage and Margin Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Configures leverage and manages isolated margin for positions. Use `is_cross: false` for isolated margin and `true` for cross margin. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient, InfoClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let address = wallet.address(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); let info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); // Update leverage (5x isolated margin) let response = exchange_client .update_leverage( 5, // Leverage multiplier "ETH", // Asset false, // is_cross: false = isolated, true = cross margin None, // Optional wallet override ) .await .unwrap(); println!("Update leverage response: {:?}", response); // Add isolated margin to position let response = exchange_client .update_isolated_margin( 1.0, // Amount in USD to add (negative to remove) "ETH", None, ) .await .unwrap(); println!("Update margin response: {:?}", response); // Verify changes let user_state = info_client.user_state(address).await.unwrap(); println!("User state: {:?}", user_state); } ``` -------------------------------- ### Schedule Order Cancellation and Claim Rewards Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Schedules automatic cancellation of all open orders at a specified time and claims available referral rewards. The scheduled cancellation can also be unscheduled by passing `None`. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Schedule cancel all orders at a specific time let cancel_time = 1700000000000u64; // Unix timestamp in milliseconds let response = exchange_client .schedule_cancel(Some(cancel_time), None) .await .unwrap(); println!("Schedule cancel: {:?}", response); // Cancel the scheduled cancel (pass None) let response = exchange_client.schedule_cancel(None, None).await.unwrap(); println!("Cancel scheduled cancel: {:?}", response); // Claim referral rewards let response = exchange_client.claim_rewards(None).await.unwrap(); println!("Claim rewards: {:?}", response); } ``` -------------------------------- ### Subscribe to Candle Stream Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Subscribes to real-time candlestick data for a given asset and interval (e.g., ETH, 1m) for technical analysis. Displays the open, high, low, and close prices for each candle. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient, Message, Subscription}; use tokio::sync::mpsc::unbounded_channel; #[tokio::main] async fn main() { let mut info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let (sender, mut receiver) = unbounded_channel(); info_client .subscribe( Subscription::Candle { coin: "ETH".to_string(), interval: "1m".to_string(), // 1m, 5m, 15m, 1h, 4h, 1d }, sender, ) .await .unwrap(); while let Some(Message::Candle(candle)) = receiver.recv().await { let data = &candle.data; println!("Candle {}: O:{} H:{} L:{} C:{}", data.coin, data.open, data.high, data.low, data.close); } } ``` -------------------------------- ### Subscribe to Trades Stream Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Fetches real-time trade data for a specific asset (e.g., ETH) from the WebSocket stream. Prints details of each trade including side, size, coin, price, and timestamp. ```rust use hyperliquid_rust_sdk::{BaseUrl, InfoClient, Message, Subscription}; use tokio::sync::mpsc::unbounded_channel; #[tokio::main] async fn main() { let mut info_client = InfoClient::new(None, Some(BaseUrl::Testnet)).await.unwrap(); let (sender, mut receiver) = unbounded_channel(); info_client .subscribe(Subscription::Trades { coin: "ETH".to_string() }, sender) .await .unwrap(); while let Some(Message::Trades(trades)) = receiver.recv().await { for trade in &trades.data { println!("Trade: {} {} {} @ {} ({})", trade.side, trade.sz, trade.coin, trade.px, trade.time); } } } ``` -------------------------------- ### Transfer USDC and Spot Tokens Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Facilitates transfers of USDC and other spot tokens to specified addresses. For `class_transfer`, `to_perp: true` moves assets from spot to perpetuals, and `false` moves from perpetuals to spot. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Transfer USDC to another address let response = exchange_client .usdc_transfer( "10", // Amount as string "0x0D1d9635D0640821d15e323ac8AdADfA9c111414", // Destination address None, ) .await .unwrap(); println!("USDC transfer: {:?}", response); // Transfer spot tokens let response = exchange_client .spot_transfer( "100", // Amount "0x0D1d9635D0640821d15e323ac8AdADfA9c111414", // Destination "PURR:0xc4bf3f870c0e9465323c0b6ed28096c2", // Token identifier None, ) .await .unwrap(); println!("Spot transfer: {:?}", response); // Transfer between perp and spot accounts let response = exchange_client .class_transfer( 100.0, // USDC amount true, // to_perp: true = spot to perp, false = perp to spot None, ) .await .unwrap(); println!("Class transfer: {:?}", response); } ``` -------------------------------- ### Funding Rate History Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Retrieve funding rate data for assets and user funding payments. ```APIDOC ## Funding Rate History Retrieves funding rate data for assets and user funding payments. ### Get Funding Rate History for an Asset **Endpoint:** `/funding_history` **Method:** GET **Parameters:** - **asset** (string) - Required - The trading asset (e.g., "ETH"). - **start_time** (u64) - Required - The start timestamp in milliseconds. - **end_time** (u64) - Optional - The end timestamp in milliseconds. **Description:** Fetches the historical funding rates for a specified asset within a given time range. ### Get User's Funding Payments **Endpoint:** `/user_funding_history` **Method:** GET **Parameters:** - **user_address** (Address) - Required - The user's Ethereum address. - **start_time** (u64) - Required - The start timestamp in milliseconds. - **end_time** (u64) - Optional - The end timestamp in milliseconds. **Description:** Retrieves the funding payment history for a specific user's address within a given time range. ``` -------------------------------- ### Withdraw Funds from Hyperliquid Bridge Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Demonstrates how to withdraw USDC from Hyperliquid to an external address using the `withdraw_from_bridge` function. Ensure your private key and destination address are correctly configured. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Withdraw USDC through bridge let response = exchange_client .withdraw_from_bridge( "100", // Amount as string "0x0D1d9635D0640821d15e323ac8AdADfA9c111414", // Destination address None, ) .await .unwrap(); println!("Bridge withdrawal: {:?}", response); } ``` -------------------------------- ### Deposit and Withdraw from Vaults Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Use `vault_transfer` to deposit or withdraw funds from a specified vault. Amounts are in raw units. ```rust use alloy::signers::local::PrivateKeySigner; use alloy::primitives::Address; use hyperliquid_rust_sdk::{BaseUrl, ExchangeClient}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let vault_address: Address = "0x1234567890123456789012345678901234567890".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Deposit to vault let response = exchange_client .vault_transfer( true, // is_deposit 1_000_000, // Amount in raw units (1 USDC = 1_000_000) Some(vault_address), None, ) .await .unwrap(); println!("Vault deposit: {:?}", response); // Withdraw from vault let response = exchange_client .vault_transfer(false, 500_000, Some(vault_address), None) .await .unwrap(); println!("Vault withdrawal: {:?}", response); } ``` -------------------------------- ### Cancel Orders by ID or Cloid in Rust Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Shows how to cancel single orders using their order ID or client order ID (cloid), and how to perform a bulk cancellation of multiple orders. ```rust use alloy::signers::local::PrivateKeySigner; use hyperliquid_rust_sdk::{ BaseUrl, ClientCancelRequest, ClientCancelRequestCloid, ExchangeClient, }; use uuid::Uuid; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); // Cancel by order ID let cancel_request = ClientCancelRequest { asset: "ETH".to_string(), oid: 123456789, // Order ID from order response }; let response = exchange_client.cancel(cancel_request, None).await.unwrap(); println!("Cancel response: {:?}", response); // Cancel by client order ID let cloid = Uuid::parse_str("1e60610f-0b3d-4205-97c8-8c1fed2ad5ee").unwrap(); let cancel_by_cloid = ClientCancelRequestCloid { asset: "ETH".to_string(), cloid, }; let response = exchange_client.cancel_by_cloid(cancel_by_cloid, None).await.unwrap(); println!("Cancel by cloid response: {:?}", response); // Bulk cancel multiple orders let cancels = vec![ ClientCancelRequest { asset: "ETH".to_string(), oid: 111 }, ClientCancelRequest { asset: "BTC".to_string(), oid: 222 }, ]; let response = exchange_client.bulk_cancel(cancels, None).await.unwrap(); println!("Bulk cancel response: {:?}", response); } ``` -------------------------------- ### Approve Builder Fee for Order Routing Source: https://context7.com/hyperliquid-dex/hyperliquid-rust-sdk/llms.txt Approves a builder address to receive a specified fee percentage for routing orders. This is useful for setting up fee-sharing agreements with order routers. ```rust use alloy::signers::local::PrivateKeySigner; use alloy::primitives::address; use hyperliquid_rust_sdk::{BaseUrl, BuilderInfo, ExchangeClient, MarketOrderParams}; #[tokio::main] async fn main() { let wallet: PrivateKeySigner = "your_private_key_hex".parse().unwrap(); let exchange_client = ExchangeClient::new(None, wallet, Some(BaseUrl::Testnet), None, None) .await .unwrap(); let builder = address!("0x1234567890123456789012345678901234567890"); // Approve builder to charge up to 0.1% fee let response = exchange_client .approve_builder_fee(builder, "0.001%".to_string(), None) .await .unwrap(); println!("Builder fee approval: {:?}", response); // Place order through builder let builder_info = BuilderInfo { builder: format!("{:?}", builder), fee: "0.0005%".to_string(), // 0.05% fee for this order }; let params = MarketOrderParams { asset: "ETH", is_buy: true, sz: 0.01, px: None, slippage: Some(0.01), cloid: None, wallet: None, }; let response = exchange_client .market_open_with_builder(params, builder_info) .await .unwrap(); println!("Order with builder: {:?}", response); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.