### Install Hyperliquid SDK Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Installs the Hyperliquid SDK using npm. This is the first step to integrate the SDK into your project. ```bash npm install --save hyperliquid ``` -------------------------------- ### Set Up WebSocket Subscriptions with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Provides a comprehensive example of setting up WebSocket subscriptions for real-time data feeds. This includes subscribing to mid prices, L2 order book updates, trade feeds, candle updates, user fills, order updates, and general user events. The example also shows how to unsubscribe and disconnect. ```typescript import { Hyperliquid } from 'hyperliquid'; async function setupWebSocket() { const sdk = new Hyperliquid({ enableWs: true }); await sdk.connect(); // Subscribe to all mid prices sdk.subscriptions.subscribeToAllMids((data) => { console.log('Price update:', data); // Output: { 'BTC-PERP': 45123.5, 'ETH-PERP': 3001.25, ... } }); // Subscribe to L2 order book updates sdk.subscriptions.subscribeToL2Book('BTC-PERP', (data) => { console.log('Order book update:', data.coin, data.levels); }); // Subscribe to trade feed sdk.subscriptions.subscribeToTrades('ETH-PERP', (trades) => { trades.forEach(trade => { console.log(`Trade: ${trade.side} ${trade.sz} @ ${trade.px}`); }); }); // Subscribe to candle updates sdk.subscriptions.subscribeToCandle('BTC-PERP', '1m', (candle) => { console.log('New candle:', candle); }); // Subscribe to user fills sdk.subscriptions.subscribeToUserFills('0xYourAddress', (fill) => { console.log('New fill:', fill); }); // Subscribe to order updates sdk.subscriptions.subscribeToOrderUpdates('0xYourAddress', (orders) => { console.log('Order updates:', orders); }); // Subscribe to user events (positions, liquidations, etc) sdk.subscriptions.subscribeToUserEvents('0xYourAddress', (event) => { console.log('User event:', event); }); // Unsubscribe when done await sdk.subscriptions.unsubscribeFromAllMids(); await sdk.subscriptions.unsubscribeFromL2Book('BTC-PERP'); // Disconnect WebSocket sdk.disconnect(); } setupWebSocket(); ``` -------------------------------- ### Place Limit Order on Hyperliquid Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Provides examples for placing single and multiple limit orders using the Hyperliquid SDK. It shows how to specify order details such as coin, side, size, price, order type (e.g., 'Gtc'), and optional client order IDs (CLOID). The multi-order example includes grouping and builder fee configurations. ```typescript // Place a single limit order const orderRequest = { coin: 'BTC-PERP', is_buy: true, sz: 0.1, limit_px: 45000, order_type: { limit: { tif: 'Gtc' } }, // Good-til-cancelled reduce_only: false, cloid: '0x1234567890abcdef1234567890abcdef' // Optional client order ID }; try { const response = await sdk.exchange.placeOrder(orderRequest); console.log('Order placed:', response); // Output: { status: 'ok', response: { type: 'order', data: { statuses: [{ resting: { oid: 123456 } }] } } } } catch (error) { console.error('Order failed:', error.message); } // Place multiple orders atomically const multiOrderRequest = { orders: [ { coin: 'BTC-PERP', is_buy: true, sz: 0.1, limit_px: 45000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }, { coin: 'ETH-PERP', is_buy: false, sz: 1.0, limit_px: 3100, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false } ], grouping: 'normalTpsl', // Order execution grouping builder: { address: '0xBuilderAddress', fee: 999 // Builder fee in basis points } }; const multiResponse = await sdk.exchange.placeOrder(multiOrderRequest); ``` -------------------------------- ### Connect and Subscribe via WebSocket Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Demonstrates how to initialize the Hyperliquid SDK, connect to WebSocket, and subscribe to various data streams including all mid prices, user fills, and candle data for a specified symbol. Ensure the 'hyperliquid' package is installed. ```typescript const { Hyperliquid } = require('hyperliquid'); async function testWebSocket() { // Create a new Hyperliquid instance // You can pass a privateKey in the options if you need authenticated access const sdk = new Hyperliquid({ enableWs: true }); try { // Connect to the WebSocket await sdk.connect(); console.log('Connected to WebSocket'); // Subscribe to get latest prices for all coins sdk.subscriptions.subscribeToAllMids((data) => { console.log('Received trades data:', data); }); // Get updates anytime the user gets new fills sdk.subscriptions.subscribeToUserFills("", (data) => { console.log('Received user fills data:', data); }); // Get updates on 1 minute ETH-PERP candles sdk.subscriptions.subscribeToCandle("BTC-PERP", "1m", (data) => { console.log('Received candle data:', data); }); // Keep the script running await new Promise(() => {}); } catch (error) { console.error('Error:', error); } } testWebSocket(); ``` -------------------------------- ### Query Account Information with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Provides examples for retrieving various account details, including perpetuals and spot account states, open orders, and trade history (fills). It demonstrates fetching data for a specific user address and querying fills within a defined time range. The outputs include margin summaries, asset positions, balances, and order details. ```typescript const userAddress = '0xYourWalletAddress'; // Get perpetuals account state const perpState = await sdk.info.perpetuals.getClearinghouseState(userAddress); console.log('Account value:', perpState.marginSummary.accountValue); console.log('Positions:', perpState.assetPositions); /* Output: { marginSummary: { accountValue: '10000.50', totalNtlPos: '5000', totalRawUsd: '10500' }, assetPositions: [ { position: { coin: 'BTC-PERP', szi: '0.1', leverage: { value: 5 }, unrealizedPnl: '50.25' } } ] } */ // Get spot account state const spotState = await sdk.info.spot.getSpotClearinghouseState(userAddress); console.log('Spot balances:', spotState.balances); // Get open orders const openOrders = await sdk.info.getUserOpenOrders(userAddress); console.log('Open orders:', openOrders); /* Output: [ { coin: 'BTC-PERP', oid: 123456, side: 'B', limitPx: '45000', sz: '0.1', timestamp: 1234567890000 } ] */ // Get user fills (trade history) const fills = await sdk.info.getUserFills(userAddress); console.log('Recent trades:', fills); // Get fills within a time range const startTime = Date.now() - 86400000; // 24 hours ago const endTime = Date.now(); const fillsInRange = await sdk.info.getUserFillsByTime(userAddress, startTime, endTime); ``` -------------------------------- ### Get User Open Orders with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Fetches a list of all currently open orders for a specified user address. Requires the user's wallet address as input. ```typescript // Get user open orderssdk.info.getUserOpenOrders('user_address_here').then(userOpenOrders => { console.log(userOpenOrders); }).catch(error => { console.error('Error getting user open orders:', error); }); ``` -------------------------------- ### Query Market Data with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Illustrates how to access real-time and historical market data, including mid prices, order book depth, and candle data for various intervals. It also covers fetching metadata for perpetual and spot markets, and listing all available assets. The examples include sample outputs for clarity. ```typescript // Get current mid prices for all assets const allMids = await sdk.info.getAllMids(); console.log('BTC price:', allMids['BTC-PERP']); // Get L2 order book depth const l2Book = await sdk.info.getL2Book('BTC-PERP'); console.log('Order book:', l2Book); /* Output: { coin: 'BTC-PERP', levels: [ [{ px: '45000', sz: '1.5', n: 3 }], // Bids [{ px: '45001', sz: '2.0', n: 5 }] // Asks ], time: 1234567890000 } */ // Get historical candles const candleData = await sdk.info.getCandleSnapshot( 'BTC-PERP', '1h', // interval: '1m', '5m', '15m', '1h', '4h', '1d' Date.now() - 86400000, // startTime (24h ago) Date.now() // endTime ); console.log('Candles:', candleData); /* Output: [ { t: 1234567890000, T: 1234571490000, s: 'BTC-PERP', i: '1h', o: '44500', h: '45200', l: '44300', c: '45000', v: '1234.56', n: 523 } ] */ // Get perpetuals metadata const perpMeta = await sdk.info.perpetuals.getMeta(); console.log('Available perpetuals:', perpMeta.universe); // Get spot metadata const spotMeta = await sdk.info.spot.getSpotMeta(); console.log('Available spot assets:', spotMeta.tokens); // Get all available assets const allAssets = await sdk.custom.getAllAssets(); console.log('Perpetuals:', allAssets.perp); console.log('Spot:', allAssets.spot); ``` -------------------------------- ### Get All Mids with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Retrieves all available market indifference prices (MIDs) from the Hyperliquid API. This method is useful for getting an overview of current market prices. ```typescript // Get all midssdk.info.getAllMids().then(allMids => { console.log(allMids); }).catch(error => { console.error('Error getting all mids:', error); }); ``` -------------------------------- ### Execute Custom Trading Actions Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Provides examples of custom methods in the Hyperliquid SDK for cancelling all orders (globally or for a specific symbol) and retrieving a list of all tradable assets. These are not part of the standard API. ```typescript // Cancel all orders sdk.custom.cancelAllOrders().then(cancelAllResult => { console.log(cancelAllResult); }).catch(error => { console.error('Error cancelling all orders:', error); }); // Cancel all orders for a specific symbol sdk.custom.cancelAllOrders('BTC-PERP').then(cancelAllBTCResult => { console.log(cancelAllBTCResult); }).catch(error => { console.error('Error cancelling all BTC-PERP orders:', error); }); // Get all tradable assets const allAssets = sdk.custom.getAllAssets(); console.log(allAssets); ``` -------------------------------- ### Query Vault and Sub-Account Information with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt This TypeScript example demonstrates how to query vault details and sub-account information using the Hyperliquid SDK. It covers fetching vault details for a specific address, retrieving a user's vault equities, listing sub-accounts, checking user role information, and obtaining delegation details. ```typescript // Get vault details const vaultDetails = await sdk.info.getVaultDetails( '0xVaultAddress', '0xOptionalUserAddress' // Include to get user-specific vault info ); console.log('Vault details:', vaultDetails); // Get user's vault equities const vaultEquities = await sdk.info.getUserVaultEquities('0xUserAddress'); console.log('Vault positions:', vaultEquities); // Get sub-accounts const subAccounts = await sdk.info.getSubAccounts('0xUserAddress'); console.log('Sub-accounts:', subAccounts); // Get user role information const userRole = await sdk.info.getUserRole('0xUserAddress'); console.log('User role:', userRole); // Get delegation information const delegations = await sdk.info.getDelegations('0xUserAddress'); console.log('Delegations:', delegations); ``` -------------------------------- ### Get L2 Order Book with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Retrieves the Level 2 order book for a specific trading pair. This provides a detailed view of buy and sell orders at different price levels. ```typescript // Get L2 order booksdk.info.getL2Book('BTC-PERP').then(l2Book => { console.log(l2Book); }).catch(error => { console.error('Error getting L2 book:', error); }); ``` -------------------------------- ### Place and Cancel TWAP Orders with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Shows how to place Time-Weighted Average Price (TWAP) orders to spread trades over time, reducing market impact. It also includes an example of cancelling a TWAP order and retrieving TWAP slice fill history. Key parameters for placing orders include coin, size, duration, and randomization. ```typescript // Place a TWAP order const twapOrderResponse = await sdk.exchange.placeTwapOrder({ coin: 'BTC-PERP', is_buy: true, sz: 1.0, reduce_only: false, minutes: 30, // Duration to spread order over randomize: true // Randomize slice timing }); console.log('TWAP order placed:', twapOrderResponse); const twapId = twapOrderResponse.response.data.status.running.twapId; // Cancel a TWAP order const cancelTwapResponse = await sdk.exchange.cancelTwapOrder({ coin: 'BTC-PERP', twap_id: twapId }); console.log('TWAP order cancelled:', cancelTwapResponse); // Get TWAP slice fills history const twapSliceFills = await sdk.info.getUserTwapSliceFills(userAddress); console.log('TWAP fills:', twapSliceFills); ``` -------------------------------- ### Query Funding Rates and History with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt This TypeScript code snippet shows how to retrieve funding rate data for perpetual contracts using the Hyperliquid SDK. It includes functions to get user funding payments, historical funding rates for specific assets, predicted funding rates, and perpetuals currently at their open interest cap. ```typescript const userAddress = '0xYourAddress'; // Get user funding payments const startTime = Date.now() - 86400000; // 24 hours ago const userFunding = await sdk.info.perpetuals.getUserFunding( userAddress, startTime ); console.log('Funding payments:', userFunding); // Get historical funding rates for an asset const fundingHistory = await sdk.info.perpetuals.getFundingHistory( 'BTC-PERP', startTime, Date.now() ); console.log('Funding rate history:', fundingHistory); // Get predicted funding rates const predictedFundings = await sdk.info.perpetuals.getPredictedFundings(); console.log('Predicted fundings:', predictedFundings); // Get perpetuals at open interest cap const capsReached = await sdk.info.perpetuals.getPerpsAtOpenInterestCap(); console.log('Assets at OI cap:', capsReached); ``` -------------------------------- ### Cancel Orders on Hyperliquid Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Illustrates how to cancel orders on Hyperliquid using the SDK. Examples include canceling a single order by its ID, canceling multiple orders by ID, canceling an order by its client order ID (CLOID), and using custom methods to cancel all open orders or all orders for a specific symbol. ```typescript // Cancel a single order by order ID const cancelRequest = { coin: 'BTC-PERP', o: 123456 // Order ID from place order response }; try { const cancelResponse = await sdk.exchange.cancelOrder(cancelRequest); console.log('Order cancelled:', cancelResponse); // Output: { status: 'ok', response: { type: 'cancel', data: { statuses: ['success'] } } } } catch (error) { console.error('Cancel failed:', error.message); } // Cancel multiple orders const multiCancelRequests = [ { coin: 'BTC-PERP', o: 123456 }, { coin: 'ETH-PERP', o: 123457 } ]; await sdk.exchange.cancelOrder(multiCancelRequests); // Cancel by client order ID (CLOID) await sdk.exchange.cancelOrderByCloid('BTC-PERP', '0x1234567890abcdef1234567890abcdef'); // Cancel all open orders (custom method) await sdk.custom.cancelAllOrders(); // Cancel all orders for a specific symbol await sdk.custom.cancelAllOrders('BTC-PERP'); ``` -------------------------------- ### Initialize Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Demonstrates how to initialize the Hyperliquid SDK for both authenticated trading and read-only operations. It covers setting up private keys, testnet/mainnet environments, WebSocket connections, and wallet/vault addresses. The connection must be explicitly awaited for WebSocket and symbol conversion to initialize. ```typescript import { Hyperliquid } from 'hyperliquid'; // Initialize with private key for authenticated operations const sdk = new Hyperliquid({ privateKey: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', testnet: false, enableWs: true, walletAddress: '0xYourWalletAddress', // Required for API Agent wallets vaultAddress: '0xYourVaultAddress' // Optional, for vault operations }); // Initialize for read-only operations (no private key) const readOnlySdk = new Hyperliquid({ testnet: false, enableWs: true }); // Explicitly connect to initialize WebSocket and symbol conversion await sdk.connect(); // Query market data without authentication const allMids = await readOnlySdk.info.getAllMids(); console.log(allMids); // Output: { 'BTC-PERP': 45000.5, 'ETH-PERP': 3000.25, 'PURR-SPOT': 0.00123, ... } ``` -------------------------------- ### Retrieve Spot Market Information Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Shows how to fetch metadata and clearinghouse state for spot markets using the Hyperliquid SDK. Requires the SDK to be initialized and connected. ```typescript //Get spot metadata sdk.info.spot.getSpotMeta().then(spotMeta => { console.log(spotMeta); }).catch(error => { console.error('Error getting spot metadata:', error); }); // Get spot clearinghouse state sdk.info.spot.getSpotClearinghouseState('user_address_here').then(spotClearinghouseState => { console.log(spotClearinghouseState); }).catch(error => { console.error('Error getting spot clearinghouse state:', error); }); ``` -------------------------------- ### SDK Initialization Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Initializes the Hyperliquid SDK with configuration options for authentication and network selection. The SDK can be initialized for authenticated operations using a private key or for read-only operations. ```APIDOC ## SDK Initialization ### Description Initialize the Hyperliquid SDK with configuration options for authentication and network selection. ### Method `new Hyperliquid(config)` ### Parameters #### Constructor Parameters - **config** (object) - Required - Configuration object for the SDK. - **privateKey** (string) - Optional - Private key for authenticated operations. - **testnet** (boolean) - Required - Set to true for testnet, false for mainnet. - **enableWs** (boolean) - Required - Enable WebSocket connections for real-time data. - **walletAddress** (string) - Optional - Wallet address, required for API Agent wallets. - **vaultAddress** (string) - Optional - Vault address for vault operations. ### Initialization Examples ```typescript import { Hyperliquid } from 'hyperliquid'; // Initialize with private key for authenticated operations const sdk = new Hyperliquid({ privateKey: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', testnet: false, enableWs: true, walletAddress: '0xYourWalletAddress', // Required for API Agent wallets vaultAddress: '0xYourVaultAddress' // Optional, for vault operations }); // Initialize for read-only operations (no private key) const readOnlySdk = new Hyperliquid({ testnet: false, enableWs: true }); // Explicitly connect to initialize WebSocket and symbol conversion await sdk.connect(); // Query market data without authentication const allMids = await readOnlySdk.info.getAllMids(); console.log(allMids); // Output: { 'BTC-PERP': 45000.5, 'ETH-PERP': 3000.25, 'PURR-SPOT': 0.00123, ... } ``` ``` -------------------------------- ### Retrieve Perpetual Market Information Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Demonstrates fetching metadata and account summary for perpetual markets via the Hyperliquid SDK. Ensure the SDK is initialized and authenticated if necessary. ```typescript // Get perpetuals metadata sdk.info.perpetuals.getMeta().then(perpsMeta => { console.log(perpsMeta); }).catch(error => { console.error('Error getting perpetuals metadata:', error); }); // Get user's perpetuals account summary sdk.info.perpetuals.getClearinghouseState('user_address_here').then(clearinghouseState => { console.log(clearinghouseState); }).catch(error => { console.error('Error getting clearinghouse state:', error); }); ``` -------------------------------- ### Place Orders with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Demonstrates placing single and multiple orders using the Hyperliquid SDK. Supports specifying order details like coin, side, size, price, and order type. Multiple orders can be batched with optional grouping and builder configurations. ```typescript // Place an ordersdk.exchange.placeOrder({ coin: 'BTC-PERP', is_buy: true, sz: 1, limit_px: 30000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, vaultAddress: '0x...' // optional }).then(placeOrderResult => { console.log(placeOrderResult); }).catch(error => { console.error('Error placing order:', error); }); // Multiple orders can be passed as an array or order objects // The grouping, vaultAddress and builder properties are optional // Grouping determines how multiple orders are treated by the exchange endpoint in terms // of transaction priority, execution and dependency. Defaults to 'na' if not specified.sdk.exchange.placeOrder({ orders: [{ coin: 'BTC-PERP', is_buy: true, sz: 1, limit_px: 30000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }], vaultAddress: '0x...', grouping: 'normalTpsl', builder: { address: '0x...', fee: 999, } }).then(placeOrderResult => { console.log(placeOrderResult); }).catch(error => { console.error('Error placing order:', error); }); ``` -------------------------------- ### Initialize Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Initializes the Hyperliquid SDK instance with various configuration options. Supports WebSocket functionality, private keys for authenticated actions, testnet environments, and wallet/vault addresses. ```typescript const { Hyperliquid } = require('hyperliquid'); const sdk = new Hyperliquid({ enableWs: true, // boolean (OPTIONAL) - Enable/disable WebSocket functionality, defaults to true privateKey: , testnet: , walletAddress: , vaultAddress: }); // Use the SDK methodssdk.info.getAllMids().then(allMids => { console.log(allMids); }); ``` -------------------------------- ### Initialize Hyperliquid SDK Connection Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Illustrates the explicit initialization method for the Hyperliquid SDK using `sdk.connect()`. This is typically only needed if the SDK encounters an initialization error. ```typescript await sdk.connect(); ``` -------------------------------- ### Place Limit Order Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Allows users to create and submit limit orders to buy or sell an asset at a specified price. Supports placing single orders or multiple orders atomically. ```APIDOC ## Place Limit Order ### Description Create and submit a limit order to buy or sell an asset at a specified price. Supports placing single orders or multiple orders atomically. ### Method `sdk.exchange.placeOrder(orderRequest)` ### Parameters #### Request Body (Single Order) - **orderRequest** (object) - Required - Details of the order to be placed. - **coin** (string) - Required - The trading pair symbol (e.g., 'BTC-PERP', 'PURR-SPOT'). - **is_buy** (boolean) - Required - True for buy order, false for sell order. - **sz** (number) - Required - The size of the order. - **limit_px** (number) - Required - The limit price for the order. - **order_type** (object) - Required - Type of order. Use `{ limit: { tif: 'Gtc' } }` for Good-til-cancelled. - **reduce_only** (boolean) - Required - If true, the order will only reduce existing positions. - **cloid** (string) - Optional - Client order ID for tracking. #### Request Body (Multiple Orders) - **orderRequest** (object) - Required - Object containing multiple orders and grouping options. - **orders** (array) - Required - An array of order objects. - **grouping** (string) - Required - How to group order executions (e.g., 'normalTpsl'). - **builder** (object) - Required - Information about the order builder. - **address** (string) - Required - The address of the builder. - **fee** (number) - Required - The builder fee in basis points. ### Request Example ```typescript // Place a single limit order const orderRequest = { coin: 'BTC-PERP', is_buy: true, sz: 0.1, limit_px: 45000, order_type: { limit: { tif: 'Gtc' } }, // Good-til-cancelled reduce_only: false, cloid: '0x1234567890abcdef1234567890abcdef' // Optional client order ID }; try { const response = await sdk.exchange.placeOrder(orderRequest); console.log('Order placed:', response); // Output: { status: 'ok', response: { type: 'order', data: { statuses: [{ resting: { oid: 123456 } }] } } } } catch (error) { console.error('Order failed:', error.message); } // Place multiple orders atomically const multiOrderRequest = { orders: [ { coin: 'BTC-PERP', is_buy: true, sz: 0.1, limit_px: 45000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }, { coin: 'ETH-PERP', is_buy: false, sz: 1.0, limit_px: 3100, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false } ], grouping: 'normalTpsl', // Order execution grouping builder: { address: '0xBuilderAddress', fee: 999 // Builder fee in basis points } }; const multiResponse = await sdk.exchange.placeOrder(multiOrderRequest); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation ('ok'). - **response** (object) - The result of the order placement. - **type** (string) - The type of response ('order'). - **data** (object) - Order-specific data. - **statuses** (array) - An array of statuses for the placed orders. - **resting** (object) - Information about resting orders. - **oid** (number) - The order ID of the resting order. #### Response Example ```json { "status": "ok", "response": { "type": "order", "data": { "statuses": [ { "resting": { "oid": 123456 } } ] } } } ``` ``` -------------------------------- ### Manage Advanced Trading Features with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt This snippet demonstrates how to utilize advanced trading features in the Hyperliquid SDK, including scheduling automatic order cancellations, setting referral codes, approving API agents and builder fees, and managing EVM transaction block sizes. It also shows how to check the authentication status. ```typescript // Schedule automatic order cancellation const scheduleCancelResponse = await sdk.exchange.scheduleCancel( Date.now() + 3600000 // Cancel all orders in 1 hour (null to disable) ); // Set referral code (done automatically on first order, but can be changed) await sdk.exchange.setReferrer('YOUR_REFERRAL_CODE'); // Approve an API agent wallet await sdk.exchange.approveAgent({ agentAddress: '0xAgentWalletAddress', agentName: 'TradingBot1' // Optional name for identification }); // Approve builder fees await sdk.exchange.approveBuilderFee({ maxFeeRate: '0.001%', // Maximum fee rate builder: '0xBuilderAddress' }); // Switch block size for EVM transactions await sdk.exchange.switchBlocks( true // usingBigBlocks: true for large blocks, false for standard ); // Check if authenticated const isAuth = sdk.isAuthenticated(); console.log('Authenticated:', isAuth); ``` -------------------------------- ### Execute Market Orders with Custom Operations in Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Shows how to execute market orders for opening and closing positions, including closing all positions, using the custom operations API. This method allows for configurable slippage and provides options for partial or full position closure. It includes error handling for failed operations. ```typescript // Open a market position try { const marketOpenResponse = await sdk.custom.marketOpen( 'BTC-PERP', true, // is_buy 0.1, // size 45000, // optional reference price 0.05, // slippage (5%) '0xOptionalCLOID' ); console.log('Market order executed:', marketOpenResponse); } catch (error) { console.error('Market open failed:', error.message); } // Close a specific position await sdk.custom.marketClose( 'ETH-PERP', 1.0, // optional size (defaults to full position) undefined, // optional reference price 0.05 // slippage ); // Close all open positions const closeResults = await sdk.custom.closeAllPositions(0.05); console.log(`Closed ${closeResults.length} positions`); ``` -------------------------------- ### Handle Errors and Authentication with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt This TypeScript code snippet illustrates how to implement error handling for common issues in the Hyperliquid SDK, such as authentication failures and rate limiting. It also shows how to retrieve the status of a specific order for debugging purposes. ```typescript import { Hyperliquid } from 'hyperliquid'; try { const sdk = new Hyperliquid({ privateKey: 'invalid_key', testnet: false }); // This will throw AuthenticationError await sdk.exchange.placeOrder({ coin: 'BTC-PERP', is_buy: true, sz: 0.1, limit_px: 45000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }); } catch (error) { if (error.name === 'AuthenticationError') { console.error('Authentication failed:', error.message); } else { console.error('Order error:', error.message); } } // Handle rate limiting try { for (let i = 0; i < 100; i++) { await sdk.info.getAllMids(); } } catch (error) { console.error('Rate limit exceeded:', error.message); } // Get order status for debugging const orderStatus = await sdk.info.getOrderStatus( '0xUserAddress', 123456 // order ID or CLOID ); console.log('Order status:', orderStatus); ``` -------------------------------- ### Manage Leverage and Margin with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Demonstrates how to update leverage settings (isolated or cross) and manage isolated margin for specific perpetual contracts. This includes adding or removing notional value to a position. Ensure correct contract symbols and margin values are used. ```typescript async function manageLeverageAndMargin() { // Update leverage mode and value try { const leverageResponse = await sdk.exchange.updateLeverage( 'BTC-PERP', 'isolated', // 'isolated' or 'cross' 10 // leverage multiplier ); console.log('Leverage updated:', leverageResponse); } catch (error) { console.error('Leverage update failed:', error.message); } // Add or remove isolated margin const marginResponse = await sdk.exchange.updateIsolatedMargin( 'BTC-PERP', true, // is_buy (position side) 100 // notional value to add/remove (negative to remove) ); console.log('Margin adjusted:', marginResponse); } ``` -------------------------------- ### Perform Fund Transfers with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Illustrates various fund transfer operations, including internal transfers between spot and perpetual wallets, external transfers to other wallets (without bridge fees), and initiating withdrawals to L1. Note that L1 withdrawals incur a bridge fee. Also covers depositing to and withdrawing from vaults. ```typescript // Transfer USDC between perp and spot wallets (internal) const transferResponse = await sdk.exchange.transferBetweenSpotAndPerp( 100, // amount in USDC true // toPerp: true = spot to perp, false = perp to spot ); console.log('Transfer complete:', transferResponse); // Transfer USDC to another wallet (no bridge fee) const usdTransferResponse = await sdk.exchange.usdTransfer( '0xRecipientAddress', 50, // amount in USDC Date.now() // nonce ); // Transfer spot tokens to another wallet const spotTransferResponse = await sdk.exchange.spotTransfer( '0xRecipientAddress', 'PURR-SPOT', '100.5', // amount as string Date.now() // nonce ); // Withdraw USDC to L1 (incurs $1 bridge fee) const withdrawalResponse = await sdk.exchange.initiateWithdrawal( '0xRecipientAddress', 100 // amount in USDC ); console.log('Withdrawal initiated:', withdrawalResponse); // Vault transfers (deposit/withdraw from vault) const vaultTransferResponse = await sdk.exchange.vaultTransfer( '0xVaultAddress', true, // isDeposit: true = deposit, false = withdraw 500 // amount in USD ); ``` -------------------------------- ### Transfer Funds between Spot and Perp with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Enables transferring funds between spot and perpetual accounts on Hyperliquid. The function takes the amount and a boolean indicating the direction of the transfer. ```typescript // Transfer between perpetual and spot accountssdk.exchange.transferBetweenSpotAndPerp(100, true) // Transfer 100 USDC from spot to perp .then(transferResult => { console.log(transferResult); }).catch(error => { console.error('Error transferring funds:', error); }); ``` -------------------------------- ### Modify Existing Orders with Hyperliquid SDK Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Demonstrates how to modify single and batch orders using the Hyperliquid SDK. This allows updating order parameters like size and price without needing to cancel and replace orders, improving efficiency. It handles potential errors during the modification process. ```typescript const oid = 123456; const modifiedOrder = { coin: 'BTC-PERP', is_buy: true, sz: 0.15, // Changed size limit_px: 44500, // Changed price order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }; try { const modifyResponse = await sdk.exchange.modifyOrder(oid, modifiedOrder); console.log('Order modified:', modifyResponse); } catch (error) { console.error('Modify failed:', error.message); } const batchModifies = [ { oid: 123456, order: { coin: 'BTC-PERP', is_buy: true, sz: 0.15, limit_px: 44500, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false } }, { oid: 123457, order: { coin: 'ETH-PERP', is_buy: false, sz: 1.5, limit_px: 3050, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false } } ]; const batchResponse = await sdk.exchange.batchModifyOrders(batchModifies); ``` -------------------------------- ### Cancel Order with Hyperliquid SDK (TypeScript) Source: https://github.com/liqd-labs/hyperliquid-sdk/blob/main/README.md Shows how to cancel an existing order using the Hyperliquid SDK. Requires the order ID and the corresponding coin symbol. ```typescript // Cancel an ordersdk.exchange.cancelOrder({ coin: 'BTC-PERP', o: 123456 // order ID }).then(cancelOrderResult => { console.log(cancelOrderResult); }).catch(error => { console.error('Error cancelling order:', error); }); ``` -------------------------------- ### Cancel Orders Source: https://context7.com/liqd-labs/hyperliquid-sdk/llms.txt Allows users to cancel existing orders by providing the order ID or client order ID. Supports cancelling single or multiple orders, and has custom methods for cancelling all orders. ```APIDOC ## Cancel Orders ### Description Cancel existing orders by order ID or client order ID. Supports cancelling single or multiple orders, and has custom methods for cancelling all orders. ### Method `sdk.exchange.cancelOrder(cancelRequest)` `sdk.exchange.cancelOrderByCloid(coin, cloid)` `sdk.custom.cancelAllOrders(coin?)` ### Parameters #### Request Body (Single Order Cancellation) - **cancelRequest** (object) - Required - Details for cancelling a single order. - **coin** (string) - Required - The trading pair symbol. - **o** (number) - Required - The order ID to cancel. #### Request Body (Multiple Orders Cancellation) - **cancelRequest** (array) - Required - An array of objects, each specifying a coin and order ID to cancel. - **coin** (string) - Required - The trading pair symbol. - **o** (number) - Required - The order ID to cancel. #### Parameters (Cancel by CLOID) - **coin** (string) - Required - The trading pair symbol. - **cloid** (string) - Required - The client order ID to cancel. #### Parameters (Cancel All Orders) - **coin** (string) - Optional - If provided, cancels all orders for this specific symbol. If omitted, cancels all open orders across all symbols. ### Request Example ```typescript // Cancel a single order by order ID const cancelRequest = { coin: 'BTC-PERP', o: 123456 // Order ID from place order response }; try { const cancelResponse = await sdk.exchange.cancelOrder(cancelRequest); console.log('Order cancelled:', cancelResponse); // Output: { status: 'ok', response: { type: 'cancel', data: { statuses: ['success'] } } } } catch (error) { console.error('Cancel failed:', error.message); } // Cancel multiple orders const multiCancelRequests = [ { coin: 'BTC-PERP', o: 123456 }, { coin: 'ETH-PERP', o: 123457 } ]; await sdk.exchange.cancelOrder(multiCancelRequests); // Cancel by client order ID (CLOID) await sdk.exchange.cancelOrderByCloid('BTC-PERP', '0x1234567890abcdef1234567890abcdef'); // Cancel all open orders (custom method) await sdk.custom.cancelAllOrders(); // Cancel all orders for a specific symbol await sdk.custom.cancelAllOrders('BTC-PERP'); ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation ('ok'). - **response** (object) - The result of the order cancellation. - **type** (string) - The type of response ('cancel'). - **data** (object) - Cancellation-specific data. - **statuses** (array) - An array of cancellation statuses (e.g., ['success']). #### Response Example ```json { "status": "ok", "response": { "type": "cancel", "data": { "statuses": ["success"] } } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.