Hyperliquid
Simple and easy way to access the Hyperliquid API using Javascript/Typescript
Install / Use
/learn @nomeida/HyperliquidREADME
Hyperliquid API SDK
Typescript SDK to more easily interact with Hyperliquid's API
All info on the Hyperliquid API can be found here: HyperLiquid API Documentation
Features
- Complete API coverage for both REST and WebSocket endpoints
- TypeScript support with comprehensive type definitions
- Browser and Node.js compatibility
- Automatic handling of trailing zeros in price and size fields
- Rate limiting support
- Comprehensive error handling
Installation
Choose your preferred installation method:
Package Managers
# npm
npm i --save hyperliquid
# yarn
yarn add hyperliquid
# pnpm
pnpm add hyperliquid
# bun
bun i hyperliquid
Node.js Version Requirements for WebSocket Functionality
This 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:
npm install ws
Direct Web Usage
<!-- Global bundle (UMD) - Use this with script tags -->
<script src="https://unpkg.com/hyperliquid/dist/browser.global.js"></script>
<!-- ESM bundle - Use this with ES modules -->
<script type="module">
import { Hyperliquid } from 'https://unpkg.com/hyperliquid/dist/browser.js';
</script>
The SDK provides two browser bundles:
browser.global.js: UMD bundle that exposes the SDK globally asHyperliquidSDK. Use this with regular<script>tags.browser.js: ESM bundle for use with ES modules (import/export syntax).
For Browser usage, see Browser Usage Guide.
Usage
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'.
If you don't do this you will be unable to use some of the SDK methods successfully. If you are using your own Private Key then it's not necessary as the SDK can derive your wallet address from the Private key.
const { Hyperliquid } = require('hyperliquid');
const sdk = new Hyperliquid({
enableWs: true, // boolean (OPTIONAL) - Enable/disable WebSocket functionality, defaults to true
privateKey: <private_key - string>,
testnet: <testnet - boolean (OPTIONAL)>,
walletAddress: <walletAddress - string (Required if you are using an API Agent Wallet, otherwise not necessary)>,
vaultAddress: <vaultAddress - string (OPTIONAL)>,
maxReconnectAttempts: <number (OPTIONAL)>, // Default is 5, controls WebSocket reconnection attempts
disableAssetMapRefresh: <boolean (OPTIONAL)>, // Default is false, set to true to disable automatic asset map refresh
assetMapRefreshIntervalMs: <number (OPTIONAL)> // Default is 60000 (1 minute), controls how often asset maps are refreshed
});
// Use the SDK methods
sdk.info.getAllMids().then(allMids => {
console.log(allMids);
});
Note: You don't have to provide your private key, but it is required if you want to
use the exchange API to place, cancel or modify orders or access your accounts assets.
WebSocket functionality is enabled by default but can be disabled by setting enableWs: false in the constructor options.
Key Features
Rate Limiting
The SDK implements Hyperliquid's token bucket rate limiting system:
- 100 tokens maximum capacity
- 10 tokens per second refill rate
- Automatic handling of rate limits with proper backoff
The SDK will automatically wait when rate limits are reached, ensuring your API calls succeed without overwhelming the server.
WebSocket Management
The SDK provides robust WebSocket connection handling:
- Automatic reconnection with exponential backoff
- Ping/pong heartbeat mechanism to detect stale connections
- Subscription limit tracking (maximum 1000 subscriptions per IP)
- Proper cleanup of subscriptions when no longer needed
Secure Nonce Generation
For authenticated requests, the SDK uses a secure nonce generation system:
- Monotonically increasing timestamps
- Handles multiple requests in the same millisecond
- Ensures compliance with Hyperliquid's nonce requirements
Asset Map Refresh Management
The SDK automatically maintains asset maps for symbol conversion between internal names (e.g., BTC-PERP) and exchange names (e.g., BTC). By default, these maps are refreshed every 60 seconds to stay up-to-date with new assets.
For users running multiple SDK instances or experiencing rate limiting issues, you can disable automatic refresh:
const sdk = new Hyperliquid({
privateKey: 'your-private-key',
testnet: false,
enableWs: false,
disableAssetMapRefresh: true, // Prevents automatic refresh calls
});
// If you need asset maps, refresh manually when needed:
await sdk.refreshAssetMapsNow();
Configuration options:
disableAssetMapRefresh: true- Completely disables automatic asset map refreshassetMapRefreshIntervalMs: 300000- Sets refresh interval to 5 minutes instead of 1 minute
Runtime control methods:
// Check if refresh is enabled
console.log(sdk.isAssetMapRefreshEnabled());
// Disable refresh at runtime
sdk.disableAssetMapRefresh();
// Enable refresh at runtime
sdk.enableAssetMapRefresh();
// Change refresh interval
sdk.setAssetMapRefreshInterval(300000); // 5 minutes
// Manual refresh
await sdk.refreshAssetMapsNow();
When to disable asset map refresh:
- Running multiple SDK instances from the same IP
- Only using the SDK for order placement/cancellation without symbol conversion
- Experiencing rate limiting issues (HTTP 429 errors)
- Using external price oracles and don't need real-time asset metadata
Symbol Naming Convention
Instead 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:
- For perpetuals:
<coin>-PERP(e.g., BTC-PERP, ETH-PERP) - For spot:
<coin>-SPOT(e.g., PURR-SPOT, BTC-SPOT)
This convention makes it easier to distinguish between spot and perpetual markets.
Examples
Exchange API Methods
// Place an order
sdk.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);
});
// Reserve additional actions for rate limits
// This costs 0.0005 USDC per request instead of trading to increase rate limits
sdk.exchange
.reserveRequestWeight(1)
.then(result => {
console.log('Reserved additional actions:', result);
})
.catch(error => {
console.error('Error reserving actions:', 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);
});
// Cancel an order
sdk.exchange
.cancelOrder({
coin: 'BTC-PERP',
o: 123456, // order ID
})
.then(cancelOrderResult => {
console.log(cancelOrderResult);
})
.catch(error => {
console.error('Error cancelling order:', error);
});
// Transfer between perpetual and spot accounts
sdk.exchange
.transferBetweenSpotAndPerp(100, true) // Transfer 100 USDC from spot to perp
.then(transferResult => {
console.log(transferResult);
})
.catch(error => {
console.error('Error transferring funds:', error);
});
// Transfer spot tokens to another address
// IMPORTANT: Token format must be "TOKEN_NAME:TOKEN_ADDRESS"
sdk.exchange
.spotTransfer(
'0x1234567890123456789012345678901234567890', // destination address
'PURR:0xeb62eee3685fc4c43992febcd9e75443', // token format: "NAME:ADDRESS"
'1.0' // amount as string
)
.then(transferResult => {
console.log(transferResult);
})
.catch(error => {
console.error('Error transferring spot tokens:', error);
});
📋 Token Format Requirements
Spot Token Format
When using spotTransfer or other spot token operations, the token parameter must follow the format:
"TOKEN_NAME:TOKEN_ADDRESS"
Examples:
"PURR:0xeb62eee3685fc4c43992febcd9e75443"- PURR token"USDC:0xaf88d065e77c8cc2239327c5edb3a432268e5831"- USDC token
How to get token addresses:
- Use the
sdk.info.spot.getSpotMeta()method to get all available spot tokens - Each token object contains the
tokenIdfield which is the address to use - Format:
"${token.name}:${token.tokenId}"
Common mistakes:
- ❌
"PURR-SPOT"- Incorrect format - ❌
"PURR"- Missing address - ❌
"0xeb62eee3685fc4c43992febcd9e75443"- Missing token name - ✅
"PURR:0xeb62eee3685fc4c43992febcd9e75443"- Correct format Transfer spot tokens to another address // IMPORTANT: Token format must be "TOKEN_NAME:TOKEN_ADDRESS" sdk.exchange .spotTransfer( '0x1234567890123456789012345678901234567890', // destination address 'PURR:0xeb62eee3685fc4c43992febcd9e75443', // token format: "NAME:ADDRESS" '1.0' // amount as string ) .then(transferResult => { console.log(transferResult); }) .catch(error => { console.error('Error transferring spot tokens:', error); });
## 📋 Token Forma
