{"_id":"@allenchuang/hyperliquid","name":"@allenchuang/hyperliquid","dist-tags":{"latest":"1.7.6"},"versions":{"1.7.6":{"name":"@allenchuang/hyperliquid","version":"1.7.6","description":"SDK for Hyperliquid API","main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","browser":"./dist/browser.js","require":"./dist/index.js","import":"./dist/index.mjs"}},"browser":{"./dist/index.js":"./dist/browser.js"},"sideEffects":false,"scripts":{"prebuild":"npm run format","build":"tsup","test":"jest","prepare":"husky install && npm run build","test:node":"node examples/node-test.js","test:browser":"npx serve -s . -p 3000","test:all":"npm run build && npm run test:node && echo '\nTo test in browser, run: npm run test:browser and visit http://localhost:3000/examples/browser-test.html'","format":"prettier --write \"src/**/*.{ts,tsx,js,jsx}\"","format:check":"prettier --check \"src/**/*.{ts,tsx,js,jsx}\"","format:all":"prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"","postinstall":"husky install"},"keywords":["hyperliquid","api","sdk","rest","websocket","trading","crypto","blockchain","arbitrum","dex"],"author":{"name":"Nomeida"},"license":"MIT","dependencies":{"@msgpack/msgpack":"^3.0.0-beta2","axios":"^1.7.2","ethers":"^6.13.2"},"devDependencies":{"@types/jest":"^29.0.0","husky":"^9.1.7","jest":"^29.0.0","lint-staged":"^15.5.1","prettier":"^3.5.3","serve":"^14.0.0","tsup":"^8.0.0","typescript":"^5.0.0"},"directories":{"test":"tests"},"repository":{"type":"git","url":"git+https://github.com/nomeida/hyperliquid-api.git"},"engines":{"node":">=16.0.0"},"lint-staged":{"*.{ts,tsx,js,jsx}":["prettier --write"],"*.{json,md}":["prettier --write"]},"_id":"@allenchuang/hyperliquid@1.7.6","gitHead":"f8aea4602c56ab949b7d1f697357dd334a41f836","bugs":{"url":"https://github.com/nomeida/hyperliquid-api/issues"},"homepage":"https://github.com/nomeida/hyperliquid-api#readme","_nodeVersion":"20.6.1","_npmVersion":"9.8.1","dist":{"integrity":"sha512-DL8df3vJYYAraT6KVKe7TI/p4nEKRK8bRufVkzFQVe0mYPNaFObBswWdXLV/0qXcNze7gzejNTh95yEoKsfYJA==","shasum":"99cb7458ddc22287d8112c828c09510137a62c71","tarball":"https://registry.npmjs.org/@allenchuang/hyperliquid/-/hyperliquid-1.7.6.tgz","fileCount":29,"unpackedSize":3513914,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQCpTlABhqr46vGDp9nrukP185O93GLYhwvmF2fHLB3UlQIhAITzksNvcBFMAdQ7GN8cfd+D5jrKrPnjxU5GB65EM7+H"}]},"_npmUser":{"name":"allenchuang","email":"mr.allenchuang@gmail.com"},"maintainers":[{"name":"allenchuang","email":"mr.allenchuang@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/hyperliquid_1.7.6_1749471916809_0.08817282497772871"},"_hasShrinkwrap":false}},"time":{"created":"2025-06-09T12:25:16.734Z","1.7.6":"2025-06-09T12:25:17.064Z","modified":"2025-06-09T12:25:17.326Z"},"maintainers":[{"name":"allenchuang","email":"mr.allenchuang@gmail.com"}],"description":"SDK for Hyperliquid API","homepage":"https://github.com/nomeida/hyperliquid-api#readme","keywords":["hyperliquid","api","sdk","rest","websocket","trading","crypto","blockchain","arbitrum","dex"],"repository":{"type":"git","url":"git+https://github.com/nomeida/hyperliquid-api.git"},"author":{"name":"Nomeida"},"bugs":{"url":"https://github.com/nomeida/hyperliquid-api/issues"},"license":"MIT","readme":"# Hyperliquid API SDK\n\nTypescript SDK to more easily interact with Hyperliquid's API\n\nAll info on the Hyperliquid API can be found here: [HyperLiquid API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs)\n\n## Features\n\n- Complete API coverage for both REST and WebSocket endpoints\n- TypeScript support with comprehensive type definitions\n- Browser and Node.js compatibility\n- Automatic handling of trailing zeros in price and size fields\n- Rate limiting support\n- Comprehensive error handling\n\n## Installation\n\nChoose your preferred installation method:\n\n### Package Managers\n\n```bash\n# npm\nnpm i --save hyperliquid\n\n# yarn\nyarn add hyperliquid\n\n# pnpm\npnpm add hyperliquid\n\n# bun\nbun i hyperliquid\n```\n\n### Node.js Version Requirements for WebSocket Functionality\n\nThis SDK uses native WebSocket implementation which requires Node.js version 22 or higher. If you're using an earlier version of Node.js, you'll need to install the `ws` package to use the WebSocket functionality:\n\n```bash\nnpm install ws\n```\n\n### Direct Web Usage\n\n```html\n<!-- Global bundle (UMD) - Use this with script tags -->\n<script src=\"https://unpkg.com/hyperliquid/dist/browser.global.js\"></script>\n\n<!-- ESM bundle - Use this with ES modules -->\n<script type=\"module\">\n  import { Hyperliquid } from \"https://unpkg.com/hyperliquid/dist/browser.js\";\n</script>\n\n```\n\nThe SDK provides two browser bundles:\n- `browser.global.js`: UMD bundle that exposes the SDK globally as `HyperliquidSDK`. Use this with regular `<script>` tags.\n- `browser.js`: ESM bundle for use with ES modules (import/export syntax).\n\nFor Browser usage, see [Browser Usage Guide](/BROWSER.md).\n\n## Usage\n\n**API Agent Wallet Usage:** If you are using API Agent wallets everything works as normal but you need to add your actual account's wallet address in the Hyperliquid object field 'walletAddress'.\n\nIf you don't do this you will be unable to use some of the SDK methods successfully. If you are using\nyour own Private Key then it's not necessary as the SDK can derive your wallet address from the Private key.\n```typescript\nconst { Hyperliquid } = require('hyperliquid');\n\nconst sdk = new Hyperliquid({\n  enableWs: true, // boolean (OPTIONAL) - Enable/disable WebSocket functionality, defaults to true\n  privateKey: <private_key - string>,\n  testnet: <testnet - boolean (OPTIONAL)>,\n  walletAddress: <walletAddress - string (Required if you are using an API Agent Wallet, otherwise not necessary)>,\n  vaultAddress: <vaultAddress - string (OPTIONAL)>,\n  maxReconnectAttempts: <number (OPTIONAL)> // Default is 5, controls WebSocket reconnection attempts\n});\n\n// Use the SDK methods\nsdk.info.getAllMids().then(allMids => {\n  console.log(allMids);\n});\n```\n**Note:** You don't have to provide your private key, but it is required if you want to\nuse the exchange API to place, cancel or modify orders or access your accounts assets.\nWebSocket functionality is enabled by default but can be disabled by setting `enableWs: false` in the constructor options.\n\n## Key Features\n\n### Rate Limiting\n\nThe SDK implements Hyperliquid's token bucket rate limiting system:\n- 100 tokens maximum capacity\n- 10 tokens per second refill rate\n- Automatic handling of rate limits with proper backoff\n\nThe SDK will automatically wait when rate limits are reached, ensuring your API calls succeed without overwhelming the server.\n\n### WebSocket Management\n\nThe SDK provides robust WebSocket connection handling:\n- Automatic reconnection with exponential backoff\n- Ping/pong heartbeat mechanism to detect stale connections\n- Subscription limit tracking (maximum 1000 subscriptions per IP)\n- Proper cleanup of subscriptions when no longer needed\n\n### Secure Nonce Generation\n\nFor authenticated requests, the SDK uses a secure nonce generation system:\n- Monotonically increasing timestamps\n- Handles multiple requests in the same millisecond\n- Ensures compliance with Hyperliquid's nonce requirements\n\n## Symbol Naming Convention\n\nInstead of using native symbols (which can be confusing, like @1, @4, @5 for spot and only the coin name for perps), we've implemented a more intuitive naming system:\n\n- For perpetuals: `<coin>-PERP` (e.g., BTC-PERP, ETH-PERP)\n- For spot: `<coin>-SPOT` (e.g., PURR-SPOT, BTC-SPOT)\n\nThis convention makes it easier to distinguish between spot and perpetual markets.\n\n## Examples\n\n### Exchange API Methods\n\n```typescript\n// Place an order\nsdk.exchange.placeOrder({\n  coin: 'BTC-PERP',\n  is_buy: true,\n  sz: 1,\n  limit_px: 30000,\n  order_type: { limit: { tif: 'Gtc' } },\n  reduce_only: false,\n  vaultAddress: '0x...' // optional\n}).then(placeOrderResult => {\n  console.log(placeOrderResult);\n}).catch(error => {\n  console.error('Error placing order:', error);\n});\n\n// Reserve additional actions for rate limits\n// This costs 0.0005 USDC per request instead of trading to increase rate limits\nsdk.exchange.reserveRequestWeight(1).then(result => {\n  console.log('Reserved additional actions:', result);\n}).catch(error => {\n  console.error('Error reserving actions:', error);\n});\n\n// Multiple orders can be passed as an array or order objects\n// The grouping, vaultAddress and builder properties are optional\n// Grouping determines how multiple orders are treated by the exchange endpoint in terms\n// of transaction priority, execution and dependency. Defaults to 'na' if not specified.\nsdk.exchange.placeOrder({\n  orders: [{\n    coin: 'BTC-PERP',\n    is_buy: true,\n    sz: 1,\n    limit_px: 30000,\n    order_type: { limit: { tif: 'Gtc' } },\n    reduce_only: false\n  }],\n  vaultAddress: '0x...',\n  grouping: 'normalTpsl',\n  builder: {\n    address: '0x...',\n    fee: 999,\n  }\n}).then(placeOrderResult => {\n  console.log(placeOrderResult);\n}).catch(error => {\n  console.error('Error placing order:', error);\n});\n\n// Cancel an order\nsdk.exchange.cancelOrder({\n  coin: 'BTC-PERP',\n  o: 123456 // order ID\n}).then(cancelOrderResult => {\n  console.log(cancelOrderResult);\n}).catch(error => {\n  console.error('Error cancelling order:', error);\n});\n\n// Transfer between perpetual and spot accounts\nsdk.exchange.transferBetweenSpotAndPerp(100, true) // Transfer 100 USDC from spot to perp\n  .then(transferResult => {\n    console.log(transferResult);\n  }).catch(error => {\n    console.error('Error transferring funds:', error);\n  });\n```\nAll methods supported can be found here: [Hyperliquid Exchange Endpoint API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint)\n\n### General Info Methods\n\n```typescript\n// Get all mids\nsdk.info.getAllMids().then(allMids => {\n  console.log(allMids);\n}).catch(error => {\n  console.error('Error getting all mids:', error);\n});\n\n// Get user open orders\nsdk.info.getUserOpenOrders('user_address_here').then(userOpenOrders => {\n  console.log(userOpenOrders);\n}).catch(error => {\n  console.error('Error getting user open orders:', error);\n});\n\n// Get L2 order book\nsdk.info.getL2Book('BTC-PERP').then(l2Book => {\n  console.log(l2Book);\n}).catch(error => {\n  console.error('Error getting L2 book:', error);\n});\n```\n\nAll methods supported can be found here: [Hyperliquid Info Endpoint API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint)\n\n### WebSocket Methods\n\n#### WebSocket Subscriptions\n\n```typescript\nconst { Hyperliquid } = require('hyperliquid');\n\nasync function testWebSocketSubscriptions() {\n    // Create a new Hyperliquid instance\n    // You can pass a privateKey in the options if you need authenticated access\n    const sdk = new Hyperliquid({ enableWs: true });\n\n    try {\n        // Connect to the WebSocket\n        await sdk.connect();\n        console.log('Connected to WebSocket');\n\n        // Subscribe to get latest prices for all coins\n        sdk.subscriptions.subscribeToAllMids((data) => {\n            console.log('Received trades data:', data);\n        });\n\n        // Get updates anytime the user gets new fills\n        sdk.subscriptions.subscribeToUserFills(\"<wallet_address_here>\", (data) => {\n            console.log('Received user fills data:', data);\n        });\n\n        // Get updates on 1 minute ETH-PERP candles\n        sdk.subscriptions.subscribeToCandle(\"BTC-PERP\", \"1m\", (data) => {\n            console.log('Received candle data:', data);\n        });\n\n        // Keep the script running\n        await new Promise(() => {});\n    } catch (error) {\n        console.error('Error:', error);\n    }\n}\n\ntestWebSocketSubscriptions();\n```\n\n#### WebSocket POST Requests\n\nYou can also use WebSocket to send POST requests instead of using HTTP. This is useful for high-frequency trading or when you need to minimize latency.\n\n```typescript\nconst { Hyperliquid } = require('hyperliquid');\n\nasync function testWebSocketPostRequests() {\n    // Create a new Hyperliquid instance\n    const sdk = new Hyperliquid({\n        enableWs: true,\n        // Include privateKey for authorized requests\n        privateKey: 'your_private_key' // Optional, only needed for authorized requests\n    });\n\n    try {\n        // Connect to the WebSocket\n        await sdk.connect();\n        console.log('Connected to WebSocket');\n\n        // Wait a moment to ensure connection is fully established\n        await new Promise(resolve => setTimeout(resolve, 1000));\n\n        // Example 1: Unauthorized POST request (info endpoint)\n        const l2BookResponse = await sdk.subscriptions.postRequest('info', {\n            type: 'l2Book',\n            coin: 'BTC'\n        });\n        console.log('L2 Book Response:', l2BookResponse);\n\n        // Example 2: Authorized POST request (exchange endpoint)\n        // Only works if privateKey is provided\n        if (sdk.isAuthenticated()) {\n            // Generate order payload\n            const orderPayload = await sdk.exchange.getOrderPayload({\n                coin: 'BTC',\n                is_buy: true,\n                sz: '0.001',\n                limit_px: '50000', // Far from market price for safety\n                order_type: { limit: { tif: 'Gtc' } },\n                reduce_only: false\n            });\n\n            // Send the order via WebSocket\n            const orderResponse = await sdk.subscriptions.postRequest('action', orderPayload);\n            console.log('Place Order Response:', orderResponse);\n\n            // Cancel all orders\n            const cancelAllPayload = await sdk.exchange.getCancelAllPayload();\n            const cancelAllResponse = await sdk.subscriptions.postRequest('action', cancelAllPayload);\n            console.log('Cancel All Orders Response:', cancelAllResponse);\n        }\n    } catch (error) {\n        console.error('Error:', error);\n    } finally {\n        // Disconnect WebSocket when done\n        sdk.disconnect();\n    }\n}\n\ntestWebSocketPostRequests();\n```\n\n**Notes:**\n- The WebSocket connection must be fully established before sending POST requests. It's recommended to add a short delay after connecting before sending the first request.\n- For authorized requests, the SDK will use the wallet address as the vault address if no vault address is explicitly provided. If you're using a specific vault, make sure to provide the vault address when initializing the SDK.\n\n## Automatic Handling of Trailing Zeros\n\nThe Hyperliquid API requires that price (`p`) and size (`s`) fields do not contain trailing zeros. For example:\n- `12345.0` should be `12345`\n- `0.123450` should be `0.12345`\n\nThis SDK automatically handles this requirement for you in all relevant methods. When you use methods like `placeOrder`, `modifyOrder`, or `batchModifyOrders`, the SDK will automatically remove trailing zeros from price and size values.\n\nYou can also use string values for price and size fields, which will be properly formatted:\n\n```typescript\n// Both of these will work correctly\nawait sdk.exchange.placeOrder({\n  coin: \"BTC-PERP\",\n  is_buy: true,\n  sz: \"1.0000\",  // Will be automatically converted to \"1\"\n  limit_px: \"50000.00\",  // Will be automatically converted to \"50000\"\n  reduce_only: false,\n  order_type: { limit: { tif: 'Gtc' } }\n});\n\nawait sdk.exchange.placeOrder({\n  coin: \"BTC-PERP\",\n  is_buy: true,\n  sz: 1,  // Numeric values also work\n  limit_px: 50000,\n  reduce_only: false,\n  order_type: { limit: { tif: 'Gtc' } }\n});\n```\n\nIf you're using the low-level `signL1Action` function directly, the SDK will also automatically normalize the action object to remove trailing zeros.\n\n### Spot Info Methods\n\n```typescript\n//Get spot metadata\nsdk.info.spot.getSpotMeta().then(spotMeta => {\n  console.log(spotMeta);\n}).catch(error => {\n  console.error('Error getting spot metadata:', error);\n});\n\n// Get spot clearinghouse state\nsdk.info.spot.getSpotClearinghouseState('user_address_here').then(spotClearinghouseState => {\n  console.log(spotClearinghouseState);\n}).catch(error => {\n  console.error('Error getting spot clearinghouse state:', error);\n});\n```\nAll methods supported can be found here: [Hyperliquid Spot Info Endpoint API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot)\n\n### Perpetuals Info Methods\n\n```typescript\n// Get perpetuals metadata\nsdk.info.perpetuals.getMeta().then(perpsMeta => {\n  console.log(perpsMeta);\n}).catch(error => {\n  console.error('Error getting perpetuals metadata:', error);\n});\n\n// Get user's perpetuals account summary\nsdk.info.perpetuals.getClearinghouseState('user_address_here').then(clearinghouseState => {\n  console.log(clearinghouseState);\n}).catch(error => {\n  console.error('Error getting clearinghouse state:', error);\n});\n```\nAll methods supported can be found here: [Hyperliquid Perpetuals Info Endpoint API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals)\n\n### Custom Methods\n\n```typescript\n// Cancel all orders\nsdk.custom.cancelAllOrders().then(cancelAllResult => {\n  console.log(cancelAllResult);\n}).catch(error => {\n  console.error('Error cancelling all orders:', error);\n});\n\n// Cancel all orders for a specific symbol\nsdk.custom.cancelAllOrders('BTC-PERP').then(cancelAllBTCResult => {\n  console.log(cancelAllBTCResult);\n}).catch(error => {\n  console.error('Error cancelling all BTC-PERP orders:', error);\n});\n\n// Get all tradable assets\nconst allAssets = sdk.custom.getAllAssets();\nconsole.log(allAssets);\n```\nAll Custom methods are listed above. These are custom methods that are not part of the official Hyperliquid API. As more are added we will add examples for them here.\n\n## WebSocket Subscription Limits\n\nThe Hyperliquid API imposes a limit of 1000 WebSocket subscriptions per IP address. The SDK automatically tracks and manages these subscriptions to prevent exceeding this limit. If you attempt to create more than 1000 subscriptions, the SDK will throw an error.\n\nTo manage your subscriptions effectively:\n- Unsubscribe from feeds you no longer need\n- Reuse existing subscriptions where possible\n- Monitor your subscription count with `sdk.ws.getSubscriptionCount()`\n\n## Initialization\n\nIn most cases the SDK will automatically initialize itself when required. However, in some cases you may need to explicitly initialize the SDK. You can use this method to initialize the SDK:\n\n```typescript\nawait sdk.connect();\n```\n\np.s. You only need to worry about this if the SDK throws you an error telling you that it needs to be initialized.\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=nomeida/hyperliquid&type=Date)](https://star-history.com/#nomeida/hyperliquid&Date)\n\n## Documentation\n\nFor more detailed documentation on all available methods and their parameters, please refer to the [official Hyperliquid API documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/).\n\n## Disclaimer\nIf you don't have an existing referral and use this SDK then your referral will be set by the SDK. This gives you a 4% discount on fees and gives me a percentage of the fees you pay so that I can keep working on and maintaining the SDK. You get a 4% fee discount & an easy-to-use SDK and in return I get some compensation for maintaining it, win-win\n\n*p.s. All referral commissions from this SDK will go towards buying HYPE and other HL-related coins, so it will function as an extension of the assistance fund essentially*\n\n## Reporting Issues\n\nIf you encounter any issues with the SDK, please use the bug report template when creating a new issue on GitHub. This helps us gather all the necessary information to diagnose and fix the problem efficiently.\n\nTo report a bug:\n1. Go to the [Issues tab](https://github.com/nomeida/hyperliquid/issues)\n2. Click \"New Issue\"\n3. Select the \"Bug Report\" template\n4. Fill in all the requested information, including:\n   - Description of the issue\n   - Steps to reproduce\n   - Expected behavior\n   - Actual behavior\n   - Environment details (OS, Node.js version, etc.)\n   - Any relevant logs or screenshots\n\nUsing the bug report template ensures we have all the necessary information to address your issue quickly and effectively.\n\n## License\n\nMIT\n","readmeFilename":"README.md","_rev":"1-29e3d1ef94ccbdbb3d869950cbfd9c22"}