Hyperliquid JavaScript SDK
Use @siebly/hyperliquid-api to read Hyperliquid market data, manage orders, and consume streams from Node.js. JavaScript and TypeScript use the same clients; request and response types are included.
Choose a client
- RestClient
- Market data, account state, orders, transfers, staking, vaults, subaccounts, HIP-3, and other Info and Exchange operations
- WebsocketClient
- Public market data and address-scoped account subscriptions
- WebsocketAPIClient
- Awaitable Info and signed Exchange requests over the WebSocket POST protocol
Make a first public request
In a Node.js project, install the package once. The REST and WebSocket API examples below use .mjs files so Node.js can run their imports directly.
npm install @siebly/hyperliquid-api
REST walkthrough
Read public BTC perpetual data with RestClient. These public requests require no credentials.
Save the code as rest-public.mjs and run:
node rest-public.mjs
import { RestClient } from '@siebly/hyperliquid-api'; const client = new RestClient(); async function main() { try { const status = await client.getExchangeStatus(); console.log('Exchange status:', status); } catch (error) { console.error('Exchange-status request failed:', error); } try { const mids = await client.getAllMids(); console.log('BTC midpoint:', mids.BTC); } catch (error) { console.error('Midpoint request failed:', error); } try { const metadata = await client.getPerpMetadata(); const btc = metadata.universe.find((asset) => asset.name === 'BTC'); console.log('BTC perpetual metadata:', btc); } catch (error) { console.error('Perpetual metadata request failed:', error); } try { const orderBook = await client.getOrderBook({ coin: 'BTC', }); console.log('Best bid:', orderBook?.levels[0][0]); console.log('Best ask:', orderBook?.levels[1][0]); } catch (error) { console.error('Order-book request failed:', error); } try { const candles = await client.getCandles({ coin: 'BTC', interval: '1h', startTime: Date.now() - 24 * 60 * 60 * 1000, }); console.log('Latest hourly candle:', candles.at(-1)); } catch (error) { console.error('Candle request failed:', error); } try { const trades = await client.getRecentTrades({ coin: 'BTC', }); console.log('Most recent trade:', trades[0]); } catch (error) { console.error('Recent-trade request failed:', error); }} main();Expected response
Market values change on each run. These are the fields to check in the logged output.
| Field | Expected result |
|---|---|
| BTC midpoint / metadata | A decimal-string midpoint and a perpetual asset object from universe. |
| Best bid / Best ask | Objects with decimal-string px and sz, plus order count n. |
| Latest hourly candle / Most recent trade | A candle object with millisecond t and T, OHLC and volume strings; a trade with coin, px, sz, and side. |
import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api';
// or
// import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api';
/**
* Public market-data subscriptions.
*
* Listen for data with on('message') and acknowledgements with on('response').
* Every event includes the connection's wsKey.
*
* npx tsx examples/Websocket/ws-public.ts
*/
const logger = {
...DefaultLogger,
// Uncomment to log connection lifecycle events:
trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params),
};
const wsClient = new WebsocketClient(
{
// testnet: true,
},
logger,
);
wsClient.on('open', (data) => {
console.log('ws connection opened:', data.wsKey);
});
wsClient.on('reconnecting', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
wsClient.on('exception', ({ event, data, wsKey }) => {
console.error('ws exception:', wsKey, event ?? data);
});
wsClient.on('close', ({ wsKey }) => {
console.log('ws closed:', wsKey);
});
wsClient.on('response', (event) => {
console.log('ws response:', event.wsKey, event.channel, event.data);
});
wsClient.on('message', (event) => {
switch (event.channel) {
case 'allMids':
console.log('allMids BTC:', event.data.mids.BTC);
break;
case 'l2Book':
console.log(
'Order book:',
event.wsKey,
event.data.coin,
event.data.levels,
);
break;
case 'trades':
console.log('Trades:', event.wsKey, event.data);
break;
default:
console.log(
`Market update (unhandled in switch case: "${event.channel}"):`,
event.wsKey,
event.channel,
event.data,
);
}
});
async function main() {
try {
await wsClient.subscribe([
{ type: 'allMids' },
{ type: 'l2Book', coin: 'ETH' },
{ type: 'trades', coin: 'BTC' },
{ type: 'candle', coin: 'ETH', interval: '1m' },
{ type: 'bbo', coin: 'ETH' },
{ type: 'activeAssetCtx', coin: 'BTC' },
// Native Spot universe names pass through without metadata requests.
{ type: 'trades', coin: 'PURR/USDC' },
]);
// For a readable alias, resolve it explicitly before subscribing:
// const coin = await wsClient.nameToCoin('HYPE/USDC');
// await wsClient.subscribe({ type: 'trades', coin });
} catch (error) {
console.error('subscribe failed:', error);
}
}
main();WebSocket API walkthrough
Read public midpoints through the WebSocket API without a signer. The result maps asset names to decimal-string prices. Close the connection after the request finishes.
Save the code as ws-api-public.mjs and run:
node ws-api-public.mjs
import { WebsocketAPIClient } from '@siebly/hyperliquid-api';
const wsApi = new WebsocketAPIClient();
try {
const mids = await wsApi.getAllMids();
console.log('BTC midpoint:', mids.BTC);
} finally {
wsApi.getWSClient().closeAll();
}Hyperliquid API JavaScript Tutorial
A practical JavaScript guide to using @siebly/hyperliquid-api for Hyperliquid market data, account state, perpetual and Spot orders, WebSocket streams, WebSocket API requests, Testnet, proxies, and recovery.
Your app / service
bot, dashboard, worker
@siebly/hyperliquid-api
RestClient, WebsocketClient, WebsocketAPIClient
Hyperliquid APIs
Info requests, signed Exchange actions, streaming subscriptions, and WebSocket POST requests
Common Hyperliquid implementation tasks
Start from the behavior you need, not just from REST or WebSocket as a transport. Market-data driven systems should be event driven. Backfill via the REST API once and let WebSockets passively stream new data to you, as it becomes available.
REST API hydration or backfill
Start from the REST API quickstart and endpoint reference, then normalize exchange-specific IDs, timestamps, symbols, and product scope.
Open endpoint referenceWebSocket consumer
Start from the WebSocket quickstart that matches the task boundary, verify subscription acknowledgement semantics, and keep reconnect handling explicit.
Open WebSocket quickstartAgent prompt recipe
Use the AI prompt generator when the task combines REST API hydration, live streams, in-memory state, operational outputs, or strategy code.
Build an agent promptFor coding agents
Give these files to an agent before implementation so it can find the package, examples, task guidance, and safety rules from the normal SDK-page flow.
AI prompt framework
Prompt generator and task recipes for exchange API projects.
llms.txt
Compact discovery file for agents choosing where to start.
llms-full.txt
Full route and implementation guidance index for machine readers.
SDK catalog
Machine-readable package, docs, examples, and task guidance.
Agent skill
Reusable workflow rules for coding agents using exchange APIs.
Endpoint Function Reference
Endpoint maps
Each REST client is a JavaScript class, which provides functions individually mapped to each endpoint available in the exchange's API offering.
The following table shows all methods available in each REST client, whether the method requires authentication (automatically handled if a private key or signer is provided), as well as the exact endpoint each method is connected to.
Hyperliquid exposes two HTTP paths: POST /info and POST /exchange. The value in parentheses is the request type field from the official docs (for example allMids, order, usdSend). Search this table for that type name to find the SDK function.
This can be used to easily find which method to call, once you have found which endpoint you're looking to use.
All REST clients are in the src folder. For usage examples, make sure to check the examples folder.
List of clients:
If anything is missing or wrong, please open an issue or let us know in our Node.js Traders telegram group!
How to use table
Table consists of 4 parts:
- Function name
- AUTH
- HTTP Method
- Endpoint
Function name is the name of the function that can be called through the SDK. Check examples folder in the repo for more help on how to use them!
AUTH is a boolean value that indicates if the function requires authentication - which means you need to pass your private key or a signer to the SDK. Public Info calls work with new RestClient(). Account Info, L1 actions, and user-signed actions need credentials.
HTTP Method shows HTTP method that the function uses to call the endpoint. Hyperliquid uses POST for both Info and Exchange.
Endpoint is the path plus Hyperliquid type. Best way to find exact function you need is to search for the official type (or /info / /exchange) in this table and find corresponding function name.
RestClient.ts
This table includes all endpoints from the official Exchange API docs and corresponding SDK functions for each endpoint that are found in RestClient.ts.
WebsocketAPIClient extends RestClient and exposes the same methods over Hyperliquid's WebSocket POST protocol (info / action).
| Function | AUTH | HTTP Method | Endpoint |
|---|---|---|---|
| getAllMids() | POST | /info (allMids) | |
| getActiveAssetData() | 🔐 | POST | /info (activeAssetData) |
| getAllBorrowLendReserveStates() | POST | /info (allBorrowLendReserveStates) | |
| getAllPerpMetadata() | POST | /info (allPerpMetas) | |
| getApprovedBuilders() | 🔐 | POST | /info (approvedBuilders) |
| getBorrowLendReserveState() | POST | /info (borrowLendReserveState) | |
| getUserBorrowLendState() | 🔐 | POST | /info (borrowLendUserState) |
| getCandles() | POST | /info (candleSnapshot) | |
| getPerpAccountSummary() | 🔐 | POST | /info (clearinghouseState) |
| getStakingDelegations() | 🔐 | POST | /info (delegations) |
| getStakingHistory() | 🔐 | POST | /info (delegatorHistory) |
| getStakingRewards() | 🔐 | POST | /info (delegatorRewards) |
| getStakingSummary() | 🔐 | POST | /info (delegatorSummary) |
| getExchangeStatus() | POST | /info (exchangeStatus) | |
| getExtraAgents() | 🔐 | POST | /info (extraAgents) |
| getFrontendOpenOrders() | 🔐 | POST | /info (frontendOpenOrders) |
| getFundingHistory() | POST | /info (fundingHistory) | |
| getGossipPriorityAuctionStatus() | POST | /info (gossipPriorityAuctionStatus) | |
| getGossipRootIps() | POST | /info (gossipRootIps) | |
| getOrderHistory() | 🔐 | POST | /info (historicalOrders) |
| getVipStatus() | 🔐 | POST | /info (isVip) |
| getOrderBook() | POST | /info (l2Book) | |
| getLeadingVaults() | 🔐 | POST | /info (leadingVaults) |
| getLegalStatus() | 🔐 | POST | /info (legalCheck) |
| getLiquidatablePositions() | POST | /info (liquidatable) | |
| getMarginTable() | POST | /info (marginTable) | |
| getMaxBuilderFee() | 🔐 | POST | /info (maxBuilderFee) |
| getMaxMarketOrderNotionals() | POST | /info (maxMarketOrderNtls) | |
| getPerpMetadata() | POST | /info (meta) | |
| getPerpAssetContexts() | POST | /info (metaAndAssetCtxs) | |
| getOpenOrders() | 🔐 | POST | /info (openOrders) |
| getOrderStatus() | 🔐 | POST | /info (orderStatus) |
| getOutcomeMetadata() | POST | /info (outcomeMeta) | |
| getOutcomeDeployerLimits() | POST | /info (outcomeDeployerLimits) | |
| getPerpAnnotation() | POST | /info (perpAnnotation) | |
| getPerpCategories() | POST | /info (perpCategories) | |
| getConcisePerpAnnotations() | POST | /info (perpConciseAnnotations) | |
| getPerpDeployAuctionStatus() | POST | /info (perpDeployAuctionStatus) | |
| getPerpDexLimits() | POST | /info (perpDexLimits) | |
| getPerpDexStatus() | POST | /info (perpDexStatus) | |
| getPerpDexs() | POST | /info (perpDexs) | |
| getPerpsAtOpenInterestCap() | POST | /info (perpsAtOpenInterestCap) | |
| getPortfolio() | 🔐 | POST | /info (portfolio) |
| getPreTransferCheck() | POST | /info (preTransferCheck) | |
| getPredictedFundingRates() | POST | /info (predictedFundings) | |
| getRecentTrades() | POST | /info (recentTrades) | |
| getReferralInfo() | 🔐 | POST | /info (referral) |
| getSettledOutcome() | POST | /info (settledOutcome) | |
| getBalances() | 🔐 | POST | /info (clearinghouseState, spotClearinghouseState) |
| getSpotBalances() | 🔐 | POST | /info (spotClearinghouseState) |
| getSpotDeployAuctionStatus() | 🔐 | POST | /info (spotDeployState) |
| getSpotMetadata() | POST | /info (spotMeta) | |
| getSpotAssetContexts() | POST | /info (spotMetaAndAssetCtxs) | |
| getSpotPairDeployAuctionStatus() | POST | /info (spotPairDeployAuctionStatus) | |
| getSubAccounts() | 🔐 | POST | /info (subAccounts) |
| getSubAccountsWithAllDexStates() | 🔐 | POST | /info (subAccounts2) |
| getTokenDetails() | POST | /info (tokenDetails) | |
| getTwapHistory() | 🔐 | POST | /info (twapHistory) |
| getUserAbstraction() | 🔐 | POST | /info (userAbstraction) |
| getUserBorrowLendInterest() | 🔐 | POST | /info (userBorrowLendInterest) |
| getUserDexAbstraction() | 🔐 | POST | /info (userDexAbstraction) |
| getUserFees() | 🔐 | POST | /info (userFees) |
| getUserFills() | 🔐 | POST | /info (userFills) |
| getUserFillsByTime() | 🔐 | POST | /info (userFillsByTime) |
| getUserFundingHistory() | 🔐 | POST | /info (userFunding) |
| getUserNonFundingLedgerUpdates() | 🔐 | POST | /info (userNonFundingLedgerUpdates) |
| getUserRateLimit() | 🔐 | POST | /info (userRateLimit) |
| getUserRole() | POST | /info (userRole) | |
| getMultiSigSigners() | 🔐 | POST | /info (userToMultiSigSigners) |
| getUserTwapSliceFills() | 🔐 | POST | /info (userTwapSliceFills) |
| getUserTwapSliceFillsByTime() | 🔐 | POST | /info (userTwapSliceFillsByTime) |
| getUserVaultDeposits() | 🔐 | POST | /info (userVaultEquities) |
| getValidatorL1Votes() | POST | /info (validatorL1Votes) | |
| getValidatorSummaries() | POST | /info (validatorSummaries) | |
| getVaultDetails() | POST | /info (vaultDetails) | |
| getVaultSummaries() | POST | /info (vaultSummaries) | |
| getWebData2() | 🔐 | POST | /info (webData2) |
| getAlignedQuoteTokenStatus() | POST | /info (alignedQuoteTokenInfo) | |
| submitOrder() | 🔐 | POST | /exchange (order) |
| submitMarketOrder() | 🔐 | POST | /exchange (order) |
| submitMarketClose() | 🔐 | POST | /exchange (order) |
| submitLimitOrder() | 🔐 | POST | /exchange (order) |
| modifyOrder() | 🔐 | POST | /exchange (modify) |
| modifyOrders() | 🔐 | POST | /exchange (batchModify) |
| cancelOrders() | 🔐 | POST | /exchange (cancel) |
| cancelOrdersByClientOrderId() | 🔐 | POST | /exchange (cancelByCloid) |
| updateLeverage() | 🔐 | POST | /exchange (updateLeverage) |
| updateIsolatedMargin() | 🔐 | POST | /exchange (updateIsolatedMargin) |
| setIsolatedMarginLeverage() | 🔐 | POST | /exchange (topUpIsolatedOnlyMargin) |
| submitTwapOrder() | 🔐 | POST | /exchange (twapOrder) |
| cancelTwapOrder() | 🔐 | POST | /exchange (twapCancel) |
| submitTrailingStop() | 🔐 | POST | /exchange (trailingStop) |
| setCancelAllAfter() | 🔐 | POST | /exchange (scheduleCancel) |
| setReferrer() | 🔐 | POST | /exchange (setReferrer) |
| registerReferrer() | 🔐 | POST | /exchange (registerReferrer) |
| approveApiWallet() | 🔐 | POST | /exchange (approveAgent) |
| sendUsd() | 🔐 | POST | /exchange (usdSend) |
| sendSpotAsset() | 🔐 | POST | /exchange (spotSend) |
| withdrawUsd() | 🔐 | POST | /exchange (withdraw3) |
| transferUsdBetweenSpotAndPerp() | 🔐 | POST | /exchange (usdClassTransfer) |
| sendAsset() | 🔐 | POST | /exchange (sendAsset) |
| sendToEvmWithData() | 🔐 | POST | /exchange (sendToEvmWithData) |
| sendAssetFromApiWallet() | 🔐 | POST | /exchange (agentSendAsset) |
| depositIntoStaking() | 🔐 | POST | /exchange (cDeposit) |
| withdrawFromStaking() | 🔐 | POST | /exchange (cWithdraw) |
| delegateOrUndelegateStake() | 🔐 | POST | /exchange (tokenDelegate) |
| convertToMultiSigUser() | 🔐 | POST | /exchange (convertToMultiSigUser) |
| linkStakingAccount() | 🔐 | POST | /exchange (linkStakingUser) |
| disableStakingTradingLink() | 🔐 | POST | /exchange (stakingLinkDisableTradingUser) |
| setUserPortfolioMargin() | 🔐 | POST | /exchange (userPortfolioMargin) |
| setUserAbstraction() | 🔐 | POST | /exchange (userSetAbstraction) |
| setUserDexAbstraction() | 🔐 | POST | /exchange (userDexAbstraction) |
| enableApiWalletDexAbstraction() | 🔐 | POST | /exchange (agentEnableDexAbstraction) |
| setApiWalletAbstraction() | 🔐 | POST | /exchange (agentSetAbstraction) |
| executeBorrowLendOperation() | 🔐 | POST | /exchange (borrowLend) |
| claimRewards() | 🔐 | POST | /exchange (claimRewards) |
| createSubAccount() | 🔐 | POST | /exchange (createSubAccount) |
| createVault() | 🔐 | POST | /exchange (createVault) |
| setEvmBigBlocks() | 🔐 | POST | /exchange (evmUserModify) |
| finalizeEvmContract() | 🔐 | POST | /exchange (finalizeEvmContract) |
| submitGossipPriorityBid() | 🔐 | POST | /exchange (gossipPriorityBid) |
| transferHip3LiquidatorFunds() | 🔐 | POST | /exchange (hip3LiquidatorTransfer) |
| invalidateNonce() | 🔐 | POST | /exchange (noop) |
| deployPerp() | 🔐 | POST | /exchange (perpDeploy) |
| deploySpot() | 🔐 | POST | /exchange (spotDeploy) |
| reserveAdditionalActions() | 🔐 | POST | /exchange (reserveRequestWeight) |
| setDisplayName() | 🔐 | POST | /exchange (setDisplayName) |
| setSpotDusting() | 🔐 | POST | /exchange (spotUser) |
| renameSubAccount() | 🔐 | POST | /exchange (subAccountModify) |
| transferSpotToOrFromSubAccount() | 🔐 | POST | /exchange (subAccountSpotTransfer) |
| transferUsdToOrFromSubAccount() | 🔐 | POST | /exchange (subAccountTransfer) |
| transferVaultFunds() | 🔐 | POST | /exchange (vaultTransfer) |
| distributeVaultFunds() | 🔐 | POST | /exchange (vaultDistribute) |
| modifyVault() | 🔐 | POST | /exchange (vaultModify) |
| updateValidatorL1Stream() | 🔐 | POST | /exchange (validatorL1Stream) |
| submitSignerAction() | 🔐 | POST | /exchange (CSignerAction) |
| submitValidatorAction() | 🔐 | POST | /exchange (CValidatorAction) |
| authorizeAqav2Role() | 🔐 | POST | /exchange (authorizeAqav2Role) |
| submitUserOutcome() | 🔐 | POST | /exchange (userOutcome) |
Hyperliquid JavaScript FAQ
What does the Hyperliquid JavaScript SDK cover?
Hyperliquid supports Spot, Futures, WebSockets, and WebSocket API workflows. The JavaScript guide covers the main REST and WebSocket integration patterns.
How do I authenticate private Hyperliquid API calls in JavaScript?
The public REST example above needs no credentials. For private calls, follow the authentication setup for @siebly/hyperliquid-api in the full tutorial, including the credentials or signer required by your exchange.
Hyperliquid authentication and setupDoes the Hyperliquid JavaScript SDK help with WebSocket connection management?
Yes. Use the SDK WebSocket client for subscriptions, reconnect handling, and stream lifecycle management instead of building raw socket flows yourself.
When should I use the Hyperliquid WebSocket API instead of REST?
Use REST for standard request and response workflows such as account queries and order management. Use the WebSocket API flow when you want persistent low-latency interactions over a connected session.
Direct Example Files
Open the example files below for JavaScript and TypeScript-compatible request, authentication, WebSocket, and Node.js service patterns.