### Install Hyperliquid SDK with bun Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Install the Hyperliquid SDK using bun. A fast JavaScript runtime and toolkit. ```bash bun i hyperliquid ``` -------------------------------- ### Install Hyperliquid SDK with npm Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Install the Hyperliquid SDK using npm. This is the primary method for Node.js projects. ```bash npm i --save hyperliquid ``` -------------------------------- ### Minimal Code Example for Bug Reproduction Source: https://github.com/nomeida/hyperliquid/blob/main/bug_report_template.md Provide a minimal, copy-pasteable code example that demonstrates the bug. Keep the example as small as possible while still showing the issue. ```javascript // Minimal code example that reproduces the issue // Please make this as small as possible while still demonstrating the bug ``` -------------------------------- ### Install Hyperliquid SDK with yarn Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Install the Hyperliquid SDK using yarn. An alternative package manager for Node.js projects. ```bash yarn add hyperliquid ``` -------------------------------- ### Install Hyperliquid SDK with pnpm Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Install the Hyperliquid SDK using pnpm. Another popular package manager for Node.js. ```bash pnpm add hyperliquid ``` -------------------------------- ### Fetch All Mids using SDK Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Example of using an SDK method to fetch all Mids. This demonstrates basic interaction with the SDK after initialization. ```typescript // Use the SDK methods sdk.info.getAllMids().then(allMids => { console.log(allMids); }); ``` -------------------------------- ### Get User Funding Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches user funding history for a given address and time range. Start time is required, end time is optional. ```javascript sdk.info.perpetuals.getUserFunding(address, parseInt(startTime), parseInt(endTime)) ``` -------------------------------- ### Install ws package for older Node.js versions Source: https://github.com/nomeida/hyperliquid/blob/main/README.md If using a Node.js version older than 22, install the 'ws' package to enable WebSocket functionality. ```bash npm install ws ``` -------------------------------- ### Initialize and Connect Hyperliquid SDK Source: https://github.com/nomeida/hyperliquid/blob/main/BROWSER.md This example demonstrates initializing the Hyperliquid SDK, connecting to the API, fetching market data, and subscribing to real-time price updates. Ensure `connect()` is called before other operations. ```javascript async function init() { const sdk = new Hyperliquid({ testnet: true, enableWs: true }); // Connect to the API await sdk.connect(); // Get market data const assets = await sdk.info.getAllAssets(); console.log('Available assets:', assets); // Subscribe to real-time updates sdk.subscriptions.subscribeToAllMids((data) => { console.log('Price update:', data); }); // Clean up when done // sdk.disconnect(); } ``` -------------------------------- ### Get All Assets Source: https://context7.com/nomeida/hyperliquid/llms.txt Retrieves arrays of all available perpetual and spot symbols. ```APIDOC ## `sdk.custom.getAllAssets()` Returns arrays of all available perpetual and spot symbols in the SDK's naming format. ### Response - **perp** (array) - Array of perpetual market symbols. - **spot** (array) - Array of spot market symbols. ### Request Example ```typescript const { perp, spot } = await sdk.custom.getAllAssets(); console.log(`Perp markets: ${perp.length}`); // e.g. ['BTC-PERP', 'ETH-PERP', ...] console.log(`Spot markets: ${spot.length}`); // e.g. ['PURR-SPOT', 'BTC-SPOT', ...] ``` ``` -------------------------------- ### Initialize Hyperliquid SDK Source: https://context7.com/nomeida/hyperliquid/llms.txt Constructs the SDK instance. Private key is optional for read-only access. `enableWs` controls WebSocket setup. Call `sdk.connect()` to establish WebSocket connections and initialize symbol maps. Use `sdk.disconnect()` for graceful teardown. ```typescript import { Hyperliquid } from 'hyperliquid'; // Read-only (no private key) const sdk = new Hyperliquid({ enableWs: false }); // Authenticated with WebSocket enabled const sdk = new Hyperliquid({ privateKey: '0xYOUR_PRIVATE_KEY', testnet: false, // true → testnet enableWs: true, // default true walletAddress: '0x...', // required only for API Agent wallets vaultAddress: '0x...', // optional: trade on behalf of a vault maxReconnectAttempts: 5, disableAssetMapRefresh: false, assetMapRefreshIntervalMs: 60000, }); await sdk.connect(); // establishes WebSocket + initializes symbol maps console.log(sdk.isAuthenticated()); // true console.log(sdk.isWebSocketConnected()); // true sdk.disconnect(); // graceful teardown ``` -------------------------------- ### REST API: Get All Assets Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves a list of all available assets on the Hyperliquid platform. No parameters are required. ```javascript 'Get All Assets': { method: async () => await sdk.custom.getAllAssets(), params: [] } ``` -------------------------------- ### Get Spot Metadata (TypeScript) Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Retrieves metadata for spot markets. Ensure you have initialized the SDK before calling this method. ```typescript sdk.info.spot .getSpotMeta() .then(spotMeta => { console.log(spotMeta); }) .catch(error => { console.error('Error getting spot metadata:', error); }); ``` -------------------------------- ### Get Candle Snapshot Data Source: https://context7.com/nomeida/hyperliquid/llms.txt Fetches OHLCV (Open, High, Low, Close, Volume) candle data for a given symbol, interval, and time range. The data includes timestamp (`t`), start time (`T`), symbol (`s`), interval (`i`), open (`o`), close (`c`), high (`h`), low (`l`), volume (`v`), and number of trades (`n`). ```typescript const now = Date.now(); const candles = await sdk.info.getCandleSnapshot( 'ETH-PERP', '1h', now - 24 * 60 * 60 * 1000, // 24 h ago now ); // candles: Array<{ t, T, s, i, o, c, h, l, v, n }> candles.forEach(c => console.log(`${new Date(c.t).toISOString()} close=${c.c}`)); ``` -------------------------------- ### Get User Open Positions Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches the open positions for a given user address. Requires the user's wallet address. ```javascript sdk.info.perpetuals.getUserPositions(address) ``` -------------------------------- ### Get Spot Metadata and Asset Contexts Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves metadata for spot markets along with their asset contexts. This function takes no parameters. ```javascript sdk.info.spot.getSpotMetaAndAssetCtxs() ``` -------------------------------- ### Get Spot Deployment State Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves the deployment state of the spot market for a given address. Requires the user's wallet address. ```javascript sdk.info.spot.getSpotDeployState(address) ``` -------------------------------- ### Get Spot Market Metadata Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves metadata for all spot markets. This function requires no arguments. ```javascript sdk.info.spot.getSpotMeta() ``` -------------------------------- ### Retrieve All Available Assets Source: https://context7.com/nomeida/hyperliquid/llms.txt Get lists of all available perpetual and spot trading symbols supported by the SDK using `getAllAssets`. The output is formatted in the SDK's standard naming convention. ```typescript const { perp, spot } = await sdk.custom.getAllAssets(); console.log(`Perp markets: ${perp.length}`); // e.g. ['BTC-PERP', 'ETH-PERP', ...] console.log(`Spot markets: ${spot.length}`); // e.g. ['PURR-SPOT', 'BTC-SPOT', ...] ``` -------------------------------- ### Get User Open Orders Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Fetches the open orders for a specific user address. Replace 'user_address_here' with the actual wallet address. ```typescript // Get user open orders sdk.info .getUserOpenOrders('user_address_here') .then(userOpenOrders => { console.log(userOpenOrders); }) .catch(error => { console.error('Error getting user open orders:', error); }); ``` -------------------------------- ### Get Token Details Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches detailed information for a specific token. Requires the token's ID. ```javascript sdk.info.spot.getTokenDetails(tokenId) ``` -------------------------------- ### Initiate Off-Chain Withdrawal Source: https://context7.com/nomeida/hyperliquid/llms.txt Start an off-chain bridge withdrawal to an Arbitrum address using `initiateWithdrawal`. This transaction has a $1 fee. ```typescript await sdk.exchange.initiateWithdrawal('0xARBITRUM_ADDRESS', 500); ``` -------------------------------- ### sdk.info.getUserRateLimit(user) Source: https://context7.com/nomeida/hyperliquid/llms.txt Gets the current rate limit status for a user, showing used and total request allowances. ```APIDOC ## `sdk.info.getUserRateLimit(user)` ### Description Returns the current rate-limit state for a user (cumulative volume and weight used). ### Parameters #### Path Parameters - **user** (string) - Required - The user's address. ### Request Example ```typescript const rl = await sdk.info.getUserRateLimit('0xUSER'); console.log(`Requests used: ${rl.nRequestsUsed} / ${rl.nRequestsLimit}`); ``` ``` -------------------------------- ### Get User Open Orders Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves a list of open orders for a specified user address. Requires the user's wallet address. ```javascript sdk.info.perpetuals.getUserOpenOrders(address) ``` -------------------------------- ### REST API: Get Delegator Summary Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches a summary of delegation data for a user. Requires the user's wallet address. ```javascript 'Get Delegator Summary': { method: async (address) => await sdk.info.getDelegatorSummary(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### REST API: Get User Open Orders Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches all open orders for a given user address. Requires the user's wallet address. ```javascript 'Get User Open Orders': { method: async (address) => await sdk.info.getUserOpenOrders(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### REST API: Perpetuals - Get Meta And Asset Contexts Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches both perpetual futures metadata and asset context information. This method requires no parameters. ```javascript 'Get Meta And Asset Contexts': { method: async () => await sdk.info.perpetuals.getMetaAndAssetCtxs(), params: [] } ``` -------------------------------- ### Get Spot Clearinghouse State (TypeScript) Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Fetches the clearinghouse state for a specific user's spot account. Requires the user's address as input. ```typescript sdk.info.spot .getSpotClearinghouseState('user_address_here') .then(spotClearinghouseState => { console.log(spotClearinghouseState); }) .catch(error => { console.error('Error getting spot clearinghouse state:', error); }); ``` -------------------------------- ### Initialize SDK and Set Up State Variables Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Initializes the SDK and sets up state variables for managing subscriptions and UI behavior like auto-scrolling. ```javascript let sdk = null; let activeSubscriptions = new Map(); let isAutoScrollEnabled = true; let isUserScrolling = false; let scrollTimeout; ``` -------------------------------- ### Get Funding History Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches the funding history for a specific symbol within a given time range. Start time is required, end time is optional. ```javascript sdk.info.perpetuals.getFundingHistory(symbol, parseInt(startTime), parseInt(endTime)) ``` -------------------------------- ### Get User Non-Funding Ledger Updates Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves non-funding ledger updates for a user. Requires address and a time range (start and optional end time). ```javascript sdk.info.perpetuals.getUserNonFundingLedgerUpdates(address, parseInt(startTime), parseInt(endTime)) ``` -------------------------------- ### Get Funding History for Perpetual Source: https://context7.com/nomeida/hyperliquid/llms.txt Fetches historical funding rate data for a specified perpetual. The start time is typically set to a past date to retrieve recent history. ```typescript const history = await sdk.info.perpetuals.getFundingHistory( 'BTC-PERP', Date.now() - 7 * 24 * 60 * 60 * 1000 ); history.forEach(h => console.log(`${new Date(h.time).toISOString()} rate=${h.fundingRate}`)); ``` -------------------------------- ### Initialize Hyperliquid SDK Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Initializes the Hyperliquid SDK with configuration options such as environment (testnet/mainnet), private key, and wallet address. Connects to the SDK and logs the initialization status. ```javascript async function initializeSDK() { try { const privateKey = document.getElementById('privateKey').value; const walletAddress = document.getElementById('walletAddress').value; const environment = document.getElementById('environment').value; const config = { testnet: environment === 'testnet', enableWs: true }; if (privateKey) config.privateKey = privateKey; if (walletAddress) config.walletAddress = walletAddress; sdk = new HyperliquidSDK.Hyperliquid(config); await sdk.connect(); log('SDK initialized successfully'); populateMethods(); checkCompatibility(); } catch (error) { log(error.message, 'error'); } } ``` -------------------------------- ### Initialization Source: https://context7.com/nomeida/hyperliquid/llms.txt Constructs the SDK. Private key is optional. Call `sdk.connect()` before using WebSocket features or when you need explicit initialization. ```APIDOC ## Initialization — `new Hyperliquid(config)` Constructs the SDK. Private key is optional (omit for read-only). Pass `enableWs: false` to skip WebSocket setup. Call `sdk.connect()` before using WebSocket features or when you need explicit initialization. ```typescript import { Hyperliquid } from 'hyperliquid'; // Read-only (no private key) const sdk = new Hyperliquid({ enableWs: false }); // Authenticated with WebSocket enabled const sdk = new Hyperliquid({ privateKey: '0xYOUR_PRIVATE_KEY', testnet: false, // true → testnet enableWs: true, // default true walletAddress: '0x...', // required only for API Agent wallets vaultAddress: '0x...', // optional: trade on behalf of a vault maxReconnectAttempts: 5, disableAssetMapRefresh: false, assetMapRefreshIntervalMs: 60000, }); await sdk.connect(); // establishes WebSocket + initializes symbol maps console.log(sdk.isAuthenticated()); // true console.log(sdk.isWebSocketConnected()); // true sdk.disconnect(); // graceful teardown ``` ``` -------------------------------- ### REST API: Get User Fills By Time Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves user fills within a specified time range. Requires address, start time, and end time in milliseconds. ```javascript 'Get User Fills By Time': { method: async (address, startTime, endTime) => await sdk.info.getUserFillsByTime(address, parseInt(startTime), parseInt(endTime)), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' }, { name: 'startTime', type: 'number', placeholder: 'Start timestamp (ms)' }, { name: 'endTime', type: 'number', placeholder: 'End timestamp (ms)' } ] } ``` -------------------------------- ### REST API: Get Candle Snapshot Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches historical candlestick data for a given symbol and interval within a time range. Requires symbol, interval, start time, and end time. ```javascript 'Get Candle Snapshot': { method: async (symbol, interval, startTime, endTime) => await sdk.info.getCandleSnapshot(symbol, interval, parseInt(startTime), parseInt(endTime)), params: [ { name: 'symbol', type: 'text', placeholder: 'e.g. BTC-PERP' }, { name: 'interval', type: 'text', placeholder: 'e.g. 1m, 5m, 1h' }, { name: 'startTime', type: 'number', placeholder: 'Start timestamp (ms)' }, { name: 'endTime', type: 'number', placeholder: 'End timestamp (ms)' } ] } ``` -------------------------------- ### Get Paginated User Order History by Time Range Source: https://context7.com/nomeida/hyperliquid/llms.txt Retrieves paginated order history for a user within a specified time range. The example shows how to fetch orders from the last 24 hours. ```typescript const orderHistory = await sdk.info.getUserOrderHistory( '0xUSER', Date.now() - 24 * 60 * 60 * 1000 // last 24 h ); console.log(`Orders in last 24 h: ${orderHistory.length}`); ``` -------------------------------- ### Initialize Hyperliquid SDK Client Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Instantiate the Hyperliquid SDK client. Provide configuration options such as enabling WebSockets, your private key, testnet status, and wallet address if using an API Agent Wallet. The SDK can derive the wallet address from the private key if not provided. ```typescript const { Hyperliquid } = require('hyperliquid'); const sdk = new Hyperliquid({ enableWs: true, // boolean (OPTIONAL) - Enable/disable WebSocket functionality, defaults to true privateKey: , testnet: , walletAddress: , vaultAddress: , maxReconnectAttempts: , // Default is 5, controls WebSocket reconnection attempts disableAssetMapRefresh: , // Default is false, set to true to disable automatic asset map refresh assetMapRefreshIntervalMs: // Default is 60000 (1 minute), controls how often asset maps are refreshed }); ``` -------------------------------- ### WebSocket: Initialize and Connect Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Initializes the Hyperliquid SDK with WebSocket enabled and establishes a connection. Private keys can be passed for authenticated access. ```javascript const { Hyperliquid } = require('hyperliquid'); async function testWebSocketSubscriptions() { // 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'); // ... other subscriptions ... // Keep the script running await new Promise(() => {}); } catch (error) { console.error('Error:', error); } } ``` -------------------------------- ### Basic WebSocket POST Usage Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Demonstrates how to connect to the WebSocket, place an order, cancel all orders, and perform a transfer between spot and perp accounts. ```APIDOC ## Basic WebSocket POST Usage ### Description This example shows how to initialize the Hyperliquid SDK with WebSocket enabled, connect to the server, and then execute several common exchange operations using WebSocket POST requests. ### Methods Demonstrated - `sdk.connect()` - `sdk.wsPayloads.placeOrder(orderParams)` - `sdk.wsPayloads.cancelAllOrders()` - `sdk.wsPayloads.transferBetweenSpotAndPerp(amount, toPerp)` - `sdk.disconnect()` ### Request Example ```typescript const { Hyperliquid } = require('hyperliquid'); async function testWebSocketPostRequests() { const sdk = new Hyperliquid({ enableWs: true, privateKey: 'your_private_key', // Required for exchange methods testnet: false, // Set to true for testnet }); try { await sdk.connect(); console.log('Connected to WebSocket'); await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for connection // Place Order const orderResponse = await sdk.wsPayloads.placeOrder({ coin: 'BTC-PERP', is_buy: true, sz: '0.001', limit_px: '50000', order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, }); console.log('Place Order Response:', orderResponse); // Cancel All Orders const cancelAllResponse = await sdk.wsPayloads.cancelAllOrders(); console.log('Cancel All Orders Response:', cancelAllResponse); // Transfer Between Spot and Perp const transferResponse = await sdk.wsPayloads.transferBetweenSpotAndPerp(1.0, true); console.log('Transfer Response:', transferResponse); } catch (error) { console.error('Error:', error); } finally { sdk.disconnect(); } } testWebSocketPostRequests(); ``` ``` -------------------------------- ### sdk.info.spot.getSpotMeta() Source: https://context7.com/nomeida/hyperliquid/llms.txt Fetches metadata for all available spot markets, including token details. ```APIDOC ## `sdk.info.spot.getSpotMeta()` ### Description Returns spot market metadata including all tokens and their tokenIds. ### Request Example ```typescript const spotMeta = await sdk.info.spot.getSpotMeta(); spotMeta.tokens.forEach(t => console.log(`${t.name} | tokenId=${t.tokenId} | szDecimals=${t.szDecimals}`) ); // Find a token for later use in spotTransfer: const purr = spotMeta.tokens.find(t => t.name === 'PURR'); const tokenFormat = `${purr.name}:${purr.tokenId}`; // "PURR:0xeb62eee..." ``` ``` -------------------------------- ### Asset Map Refresh Management Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Demonstrates how to initialize the SDK with automatic asset map refresh disabled and how to manually refresh asset maps. ```APIDOC ## Initialize SDK with Disabled Asset Map Refresh ### Description Initializes the Hyperliquid SDK, disabling the automatic refresh of asset maps. This is useful for users running multiple SDK instances or experiencing rate limiting issues. ### Code Example ```typescript const sdk = new Hyperliquid({ privateKey: 'your-private-key', testnet: false, enableWs: false, disableAssetMapRefresh: true, // Prevents automatic refresh calls }); // To refresh asset maps manually when needed: await sdk.refreshAssetMapsNow(); ``` ``` -------------------------------- ### Get Predicted Fundings Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves predicted funding rates. This function does not require any parameters. ```javascript sdk.info.perpetuals.getPredictedFundings() ``` -------------------------------- ### Sub-Account Management: Create and Transfer Funds Source: https://context7.com/nomeida/hyperliquid/llms.txt Create new sub-accounts and transfer funds between your main account and sub-accounts. Use `subAccountTransfer` for perpetuals and `subAccountSpotTransfer` for spot tokens. ```typescript const sub = await sdk.exchange.createSubAccount('bot-1'); console.log(`Sub-account address: ${sub.response.data.subAccountUser}`); // Transfer 100 USDC perp to sub-account (isDeposit = true means sending to sub) await sdk.exchange.subAccountTransfer(sub.response.data.subAccountUser, true, 100); // Transfer spot token (token index) to sub-account await sdk.exchange.subAccountSpotTransfer(sub.response.data.subAccountUser, true, 0, '50'); ``` -------------------------------- ### REST API: Get All Mids Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches all Mid-price data. This method does not require any parameters. ```javascript 'Get All Mids': { method: async () => await sdk.info.getAllMids(), params: [] } ``` -------------------------------- ### sdk.info.getAllMids() Source: https://context7.com/nomeida/hyperliquid/llms.txt Returns the mid-prices for every tradable asset keyed by the SDK's human-readable symbol names (`BTC-PERP`, `PURR-SPOT`, etc.). ```APIDOC ## `sdk.info.getAllMids()` Returns the mid-prices for every tradable asset keyed by the SDK's human-readable symbol names (`BTC-PERP`, `PURR-SPOT`, etc.). ```typescript const mids = await sdk.info.getAllMids(); // { 'BTC-PERP': 67432.5, 'ETH-PERP': 3521.1, 'PURR-SPOT': 0.1942, ... } console.log(`BTC mid price: ${mids['BTC-PERP']}`); ``` ``` -------------------------------- ### Get Perpetual Market Info Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves metadata for perpetual markets. No specific parameters are required. ```javascript sdk.info.perpetuals.getPerpetualsMeta() ``` -------------------------------- ### Subscribe to Best Bid/Offer (BBO) Source: https://context7.com/nomeida/hyperliquid/llms.txt Streams BBO updates for a given coin, offering lower overhead than a full L2 book. Requires the coin symbol. ```typescript await sdk.subscriptions.subscribeToBbo('BTC-PERP', bbo => { console.log(`BBO — bid: ${bbo.bbo[0]?.px} ask: ${bbo.bbo[1]?.px}`); }); ``` -------------------------------- ### Generate and Execute Custom WebSocket Payloads Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Demonstrates how to generate a custom WebSocket payload for placing an order and then execute it. This is useful for advanced users who need more control over the payload structure. Ensure the SDK is initialized and connected. ```typescript // Generate a custom payload const customPayload = await sdk.wsPayloads.generatePayload('placeOrder', { orders: [ { coin: 'ETH-PERP', is_buy: true, sz: '0.1', limit_px: '3000', order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, }, ], }); // Execute the custom payload const response = await sdk.wsPayloads.executeCustomMethod('placeOrder', { orders: [ { coin: 'ETH-PERP', is_buy: true, sz: '0.1', limit_px: '3000', order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, }, ], }); ``` -------------------------------- ### Include Hyperliquid SDK via Script Tag Source: https://github.com/nomeida/hyperliquid/blob/main/BROWSER.md Use this method to include the Hyperliquid SDK directly in your HTML for browser environments. It initializes the SDK with testnet and WebSocket support enabled. ```html ``` -------------------------------- ### Get All Mids Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Retrieves all mid-prices for available trading pairs. This method is part of the general info endpoints. ```typescript // Get all mids sdk.info .getAllMids() .then(allMids => { console.log(allMids); }) .catch(error => { console.error('Error getting all mids:', error); }); ``` -------------------------------- ### Include Hyperliquid SDK via ESM bundle Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Use the ESM bundle with a script tag for direct web usage with ES modules. Import the `Hyperliquid` class. ```html ``` -------------------------------- ### Runtime Asset Map Refresh Control Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Provides examples of controlling asset map refresh behavior at runtime. ```APIDOC ## Runtime Asset Map Refresh Control ### Description Methods to control and query the state of automatic asset map refresh at runtime. ### Methods - `isAssetMapRefreshEnabled()`: Checks if automatic refresh is currently enabled. - `disableAssetMapRefresh()`: Disables automatic asset map refresh. - `enableAssetMapRefresh()`: Enables automatic asset map refresh. - `setAssetMapRefreshInterval(intervalMs: number)`: Sets the interval for automatic refresh in milliseconds. - `refreshAssetMapsNow()`: Manually triggers an asset map refresh. ### Code Examples ```typescript // Check if refresh is enabled console.log(sdk.isAssetMapRefreshEnabled()); // Disable refresh at runtime sdk.disableAssetMapRefresh(); // Enable refresh at runtime sdk.enableAssetMapRefresh(); // Change refresh interval to 5 minutes sdk.setAssetMapRefreshInterval(300000); // Manual refresh await sdk.refreshAssetMapsNow(); ``` ``` -------------------------------- ### Place Order via WebSocket Source: https://context7.com/nomeida/hyperliquid/llms.txt Executes exchange actions, such as placing orders, via the WebSocket connection for reduced latency. Requires an active WebSocket connection and a provided private key. ```APIDOC ## `sdk.wsPayloads.placeOrder(orderParams)` — WebSocket POST Trading Executes exchange actions over the WebSocket connection for lower latency than HTTP. Requires WebSocket to be connected and a private key provided. ```typescript await sdk.connect(); // Place order via WebSocket POST const orderResp = await sdk.wsPayloads.placeOrder({ coin: 'BTC-PERP', is_buy: true, sz: '0.001', limit_px: '50000', order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, }); console.log('WS order:', orderResp); // Cancel via WebSocket POST const cancelResp = await sdk.wsPayloads.cancelOrder({ coin: 'BTC-PERP', o: 123456 }); // Transfer via WebSocket POST await sdk.wsPayloads.transferBetweenSpotAndPerp(100, true); // Market open via WebSocket POST (uses custom ops internally) await sdk.wsPayloads.marketOpen('ETH-PERP', true, 0.05, undefined, 0.02); // Place TWAP via WebSocket POST await sdk.wsPayloads.placeTwapOrder({ coin: 'BTC-PERP', is_buy: true, sz: 0.1, reduce_only: false, minutes: 30, randomize: true, }); sdk.disconnect(); ``` ``` -------------------------------- ### sdk.info.getUserOpenOrders(user) Source: https://context7.com/nomeida/hyperliquid/llms.txt Fetches all open orders for a wallet address. ```APIDOC ## `sdk.info.getUserOpenOrders(user)` Fetches all open orders for a wallet address. ```typescript const orders = await sdk.info.getUserOpenOrders('0xYOUR_ADDRESS'); orders.forEach(o => console.log(`${o.coin} | oid=${o.oid} | side=${o.side} | px=${o.limitPx} | sz=${o.sz}`) ); ``` ``` -------------------------------- ### REST API: Perpetuals - Get Meta Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves metadata for perpetual futures trading. This method requires no parameters. ```javascript 'Get Meta': { method: async () => await sdk.info.perpetuals.getMeta(), params: [] } ``` -------------------------------- ### Get All Tradable Assets (TypeScript) Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Retrieves a list of all assets that can be traded on the platform. This is a custom method provided by the SDK. ```typescript const allAssets = sdk.custom.getAllAssets(); console.log(allAssets); ``` -------------------------------- ### Include Hyperliquid SDK via UMD bundle Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Use the UMD bundle with a script tag for direct web usage in HTML. The SDK will be exposed globally as `HyperliquidSDK`. ```html ``` -------------------------------- ### sdk.exchange.placeOrder(orderRequest) Source: https://context7.com/nomeida/hyperliquid/llms.txt Places one or more orders on the exchange. Handles symbol resolution, signing, and submission. ```APIDOC ## `sdk.exchange.placeOrder(orderRequest)` ### Description Places a single or multiple orders. Automatically removes trailing zeros from prices and sizes, resolves symbols, signs, and submits. ### Parameters #### Request Body - **orderRequest** (object) - Required - The details of the order(s) to place. - **coin** (string) - Required - The trading pair (e.g., 'BTC-PERP'). - **is_buy** (boolean) - Required - True for buy orders, false for sell orders. - **sz** (number) - Required - The size of the order. - **limit_px** (number) - Optional - The limit price for limit orders. - **order_type** (object) - Required - The type of order. - **limit** (object) - For limit orders. - **tif** (string) - Time in Force (e.g., 'Gtc'). - **trigger** (object) - For trigger orders. - **isMarket** (boolean) - True if the trigger order is a market order. - **triggerPx** (number) - The price at which the trigger order should be activated. - **tpsl** (string) - 'tp' for take profit, 'sl' for stop loss. - **reduce_only** (boolean) - Optional - If true, the order will only reduce existing positions. - **orders** (array) - Optional - For placing multiple orders. - **grouping** (string) - Optional - Specifies how multiple orders should be grouped (e.g., 'normalTpsl'). - **builder** (object) - Optional - Information for builder fees. - **address** (string) - Required - The builder's address. - **fee** (number) - Required - The fee percentage. ### Request Example ```typescript // Single limit order const result = await sdk.exchange.placeOrder({ coin: 'BTC-PERP', is_buy: true, sz: 0.001, limit_px: 50000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, }); console.log(result.response.data.statuses); // ['resting'] // Bulk order with grouping and builder fee const bulk = await sdk.exchange.placeOrder({ orders: [ { coin: 'ETH-PERP', is_buy: true, sz: 0.1, limit_px: 3000, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }, { coin: 'ETH-PERP', is_buy: false, sz: 0.1, limit_px: 3500, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false }, ], grouping: 'normalTpsl', builder: { address: '0xBUILDER', fee: 1 }, }); // Trigger (TP/SL) order await sdk.exchange.placeOrder({ coin: 'BTC-PERP', is_buy: false, sz: 0.001, limit_px: 45000, order_type: { trigger: { isMarket: true, triggerPx: 45000, tpsl: 'sl' } }, reduce_only: true, }); ``` ``` -------------------------------- ### Get L2 Order Book Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Retrieves the Level 2 order book for a specified trading pair, such as 'BTC-PERP'. ```typescript // Get L2 order book sdk.info .getL2Book('BTC-PERP') .then(l2Book => { console.log(l2Book); }) .catch(error => { console.error('Error getting L2 book:', error); }); ``` -------------------------------- ### Spot API Methods Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Methods for interacting with spot markets, including retrieving metadata and token details. ```APIDOC ## Get Spot Meta ### Description Retrieves metadata for spot markets. ### Method `getSpotMeta()` ### Response #### Success Response (200) - **spotMeta** (object) - Spot market metadata. ## Get Spot Clearinghouse State ### Description Retrieves the spot clearinghouse state for a given address. ### Method `getSpotClearinghouseState(address)` ### Parameters #### Path Parameters - **address** (text) - Required - The wallet address. ### Response #### Success Response (200) - **clearinghouseState** (object) - Spot clearinghouse state. ## Get Spot Meta And Asset Contexts ### Description Retrieves spot market metadata and asset contexts. ### Method `getSpotMetaAndAssetCtxs()` ### Response #### Success Response (200) - **metaAndContexts** (object) - Spot metadata and asset contexts. ## Get Token Details ### Description Retrieves details for a specific token. ### Method `getTokenDetails(tokenId)` ### Parameters #### Path Parameters - **tokenId** (text) - Required - The ID of the token. ### Response #### Success Response (200) - **tokenDetails** (object) - Details of the token. ## Get Spot Deploy State ### Description Retrieves the deployment state of spot markets for a given address. ### Method `getSpotDeployState(address)` ### Parameters #### Path Parameters - **address** (text) - Required - The wallet address. ### Response #### Success Response (200) - **deployState** (object) - Spot deployment state. ``` -------------------------------- ### REST API: Get Delegator Rewards Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches delegation rewards for a user. Requires the user's wallet address. ```javascript 'Get Delegator Rewards': { method: async (address) => await sdk.info.getDelegatorRewards(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### REST API: Get Delegator History Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves the delegation history for a user. Requires the user's wallet address. ```javascript 'Get Delegator History': { method: async (address) => await sdk.info.getDelegatorHistory(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### Initialize SDK Connection (TypeScript) Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Explicitly initializes the SDK connection. This is typically only needed if the SDK throws an error indicating it requires initialization. ```typescript await sdk.connect(); ``` -------------------------------- ### REST API: Get User Role Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches the role of a user on the platform. Requires the user's wallet address. ```javascript 'Get User Role': { method: async (address) => await sdk.info.getUserRole(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### Get Perpetuals Metadata (TypeScript) Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Retrieves metadata for perpetual futures markets. This method is part of the perpetuals info endpoint. ```typescript sdk.info.perpetuals .getMeta() .then(perpsMeta => { console.log(perpsMeta); }) .catch(error => { console.error('Error getting perpetuals metadata:', error); }); ``` -------------------------------- ### Populate REST and WebSocket Methods Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Organizes and displays available REST and WebSocket methods in separate containers. It categorizes REST methods into predefined sections like 'Info API' and 'Exchange API'. ```javascript function populateMethods() { const restContainer = document.getElementById('restMethods'); const wsContainer = document.getElementById('wsMethods'); restContainer.innerHTML = ''; wsContainer.innerHTML = ''; function createSectionHeader(text) { const header = document.createElement('h3'); header.style.marginTop = '20px'; header.style.marginBottom = '10px'; header.style.borderBottom = '1px solid #ddd'; header.style.paddingBottom = '5px'; header.textContent = text; return header; } const sections = [ { title: 'Info API - General', methods: {} }, { title: 'Info API - Perpetuals', methods: {} }, { title: 'Info API - Spot', methods: {} }, { title: 'Exchange API', methods: {} }, { title: 'Custom Operations', methods: {} } ]; Object.entries(restMethods).forEach(([name, info]) => { if (name === 'Cancel All Orders' || name === 'Market Open' || name === 'Market Close' || name === 'Close All Positions' || name === 'Get All Assets') { sections[4].methods[name] = info; } else if (name.startsWith('Place Order') || name.startsWith('Cancel Order') || name.startsWith('Modify') || name.startsWith('Update') || name.startsWith('USD Transfer') || name.startsWith('Spot Transfer') || name.startsWith('Initiate') || name.startsWith('Transfer Between') || name.startsWith('Schedule') || name.startsWith('Vault Transfer') || name.startsWith('Set Referrer') || name.startsWith('Modify User') || name.startsWith('Place TWAP') || name.startsWith('Cancel TWAP') || name.startsWith('Approve')) { sections[3].methods[name] = info; } else if (name.startsWith('Get Spot') || name.startsWith('Get Token')) { sections[2].methods[name] = info; } else if (name === 'Get Meta' || name === 'Get Meta And Asset Contexts' || name === 'Get Clearinghouse State' || name === 'Get User Funding' || name === 'Get User Non-Funding Ledger Updates' || name === 'Get Funding History' || name === 'Get Predicted Fundings' || name === 'Get Perps At Open Interest Cap') { sections[1].methods[name] = info; } else { sections[0].methods[name] = info; } }); sections.forEach(section => { if (Object.keys(section.methods).length > 0) { restContainer.appendChild(createSectionHeader(section.title)); Object.entries(section.methods).forEach(([name, info]) => { restContainer.appendChild(createMethodButton(name, info, false)); }); } }); wsContainer.appendChild(createSectionHeader('WebSocket Subscriptions')); Object.entries(wsMethods).forEach(([name, info]) => { wsContainer.appendChild(createMethodButton(name, info, true)); }); } ``` -------------------------------- ### General Info Methods Source: https://github.com/nomeida/hyperliquid/blob/main/README.md Methods for retrieving general information from the Hyperliquid API. ```APIDOC ## General Info Methods ### getAllMids #### Description Retrieves all available mids (market information). #### Method `sdk.info.getAllMids()` #### Response - **allMids** - An object containing all mids data. ### getUserOpenOrders #### Description Retrieves the open orders for a specific user. #### Method `sdk.info.getUserOpenOrders(user_address)` #### Parameters - **user_address** (string) - The address of the user whose open orders are to be retrieved. #### Response - **userOpenOrders** - An object containing the user's open orders. ### getL2Book #### Description Retrieves the Level 2 order book for a given trading pair. #### Method `sdk.info.getL2Book(trading_pair)` #### Parameters - **trading_pair** (string) - The trading pair for which to retrieve the order book (e.g., 'BTC-PERP'). #### Response - **l2Book** - An object containing the L2 order book data. ### Request Example (getAllMids) ```typescript sdk.info .getAllMids() .then(allMids => { console.log(allMids); }) .catch(error => { console.error('Error getting all mids:', error); }); ``` ### Request Example (getUserOpenOrders) ```typescript sdk.info .getUserOpenOrders('user_address_here') .then(userOpenOrders => { console.log(userOpenOrders); }) .catch(error => { console.error('Error getting user open orders:', error); }); ``` ### Request Example (getL2Book) ```typescript sdk.info .getL2Book('BTC-PERP') .then(l2Book => { console.log(l2Book); }) .catch(error => { console.error('Error getting L2 book:', error); }); ``` ``` -------------------------------- ### Get Perps At Open Interest Cap Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Fetches perpetual market data related to the open interest cap. No parameters are needed. ```javascript sdk.info.perpetuals.getPerpsAtOpenInterestCap() ``` -------------------------------- ### sdk.info.perpetuals.getFundingHistory(coin, startTime, endTime?) Source: https://context7.com/nomeida/hyperliquid/llms.txt Fetches historical funding rate data for a specified perpetual contract. ```APIDOC ## `sdk.info.perpetuals.getFundingHistory(coin, startTime, endTime?)` ### Description Retrieves historical funding rate data for a perpetual. ### Parameters #### Path Parameters - **coin** (string) - Required - The perpetual contract symbol (e.g., 'BTC-PERP'). - **startTime** (number) - Required - The start of the time range in milliseconds. - **endTime** (number) - Optional - The end of the time range in milliseconds. Defaults to current time. ### Request Example ```typescript const history = await sdk.info.perpetuals.getFundingHistory( 'BTC-PERP', Date.now() - 7 * 24 * 60 * 60 * 1000 ); history.forEach(h => console.log(`${new Date(h.time).toISOString()} rate=${h.fundingRate}`)); ``` ``` -------------------------------- ### Get All Mid-Prices Source: https://context7.com/nomeida/hyperliquid/llms.txt Retrieves the mid-prices for all tradable assets, keyed by human-readable symbols like `BTC-PERP`. Useful for quick market overview. ```typescript const mids = await sdk.info.getAllMids(); // { 'BTC-PERP': 67432.5, 'ETH-PERP': 3521.1, 'PURR-SPOT': 0.1942, ... } console.log(`BTC mid price: ${mids['BTC-PERP']}`); ``` -------------------------------- ### sdk.exchange.initiateWithdrawal Source: https://context7.com/nomeida/hyperliquid/llms.txt Initiates an off-chain bridge withdrawal to an Arbitrum address. Costs $1 in fees. ```APIDOC ## `sdk.exchange.initiateWithdrawal(destination, amount)` Initiates an off-chain bridge withdrawal to an Arbitrum address. Costs $1 in fees. ### Parameters - **destination** (string) - The Arbitrum address for the withdrawal. - **amount** (number) - The amount of USDC to withdraw. ### Request Example ```typescript await sdk.exchange.initiateWithdrawal('0xARBITRUM_ADDRESS', 500); ``` ``` -------------------------------- ### REST API: Get Delegations Source: https://github.com/nomeida/hyperliquid/blob/main/examples/browser-test.html Retrieves delegation information for a given user address. Requires the user's wallet address. ```javascript 'Get Delegations': { method: async (address) => await sdk.info.getDelegations(address), params: [ { name: 'address', type: 'text', placeholder: 'Enter wallet address' } ] } ``` -------------------------------- ### Subscribe to User Fills Source: https://context7.com/nomeida/hyperliquid/llms.txt Pushes real-time fill (execution) notifications for a wallet address. ```APIDOC ## `sdk.subscriptions.subscribeToUserFills(user, callback)` Pushes real-time fill (execution) notifications for a wallet address. ### Parameters - **user** (string) - The wallet address to track. - **callback** (function) - A function that receives fill data. - `data.fills` is an array of fill objects, each with `coin`, `side`, `sz` (size), `px` (price), and `fee` properties. ### Request Example ```typescript await sdk.subscriptions.subscribeToUserFills('0xUSER', data => { data.fills.forEach(f => console.log(`Fill: ${f.coin} ${f.side} ${f.sz} @ ${f.px} fee=${f.fee}`) ); }); ``` ```