← All articles

Getting started with the Hyperliquid JavaScript SDK (Node.js and TypeScript)

Hyperliquid serves public market data through /info and accepts signed actions through /exchange. Read positions and balances with the account address. Use an approved API wallet to sign orders for that account.

The examples use @siebly/hyperliquid-api 1.0.5 with Node.js and TypeScript.

What you need

  • Node.js 22 or newer (the minimum the SDK supports).
  • For the market data and WebSocket sections, nothing else. Public data needs no wallet or key.
  • For the order section, a Hyperliquid account with an approved API wallet, ideally on testnet first. Both are covered below.

Install the Hyperliquid Node.js SDK

Create a project and install the package. The SDK ships ES module and CommonJS builds with its own TypeScript declarations, so there is no separate @types package to add.

mkdir hyperliquid-quickstart && cd hyperliquid-quickstart
npm init -y
npm pkg set type=module
npm install @siebly/hyperliquid-api

# Optional, to run .ts files directly with TypeScript checks available
npm install -D typescript tsx @types/node

Setting "type": "module" lets you use import and top-level await. The examples below are TypeScript files run with npx tsx. If you prefer plain JavaScript, drop the type annotations and save them as .js files; the method calls are identical.

Read market data with REST info calls

Hyperliquid’s info endpoint takes a type field such as allMids, meta, l2Book or candleSnapshot. The SDK’s RestClient wraps each one in a typed method named after what it returns: getAllMids(), getPerpMetadata(), getOrderBook() and getCandles(). A client created with no options talks to mainnet and needs no credentials.

Save this as market-data.ts:

import { RestClient } from '@siebly/hyperliquid-api';

// Public info calls need no private key.
// Pass { testnet: true } to read from Hyperliquid testnet instead.
const client = new RestClient();

async function main() {
  // 1. Mid prices for every listed coin
  const mids = await client.getAllMids();
  console.log('BTC mid:', mids.BTC);
  console.log('ETH mid:', mids.ETH);

  // 2. Perpetual metadata: names, size decimals and max leverage
  const meta = await client.getPerpMetadata();
  const btc = meta.universe.find((asset) => asset.name === 'BTC');
  console.log('perp markets:', meta.universe.length);
  console.log('BTC meta:', btc);

  // 3. L2 order book (up to 20 levels per side)
  const book = await client.getOrderBook({ coin: 'BTC' });
  const [bids, asks] = book?.levels ?? [[], []];
  console.log('best bid:', bids[0]);
  console.log('best ask:', asks[0]);

  // 4. One minute candles from the last five minutes
  const candles = await client.getCandles({
    coin: 'BTC',
    interval: '1m',
    startTime: Date.now() - 5 * 60_000,
  });
  console.log('candles:', candles.length, candles.at(-1));
}

main().catch((error) => {
  console.error('request failed:', error);
  process.exit(1);
});

Run npx tsx market-data.ts. Prices and book sizes change with the market.

BTC mid: 60680.5
ETH mid: 1694.65
perp markets: 235
BTC meta: { szDecimals: 5, name: 'BTC', maxLeverage: 40, marginTableId: 56 }
best bid: { px: '60656.0', sz: '9.0001', n: 49 }
best ask: { px: '60657.0', sz: '0.00164', n: 1 }
candles: 6 {
  t: 1795739760000,
  T: 1795739819999,
  s: 'BTC',
  i: '1m',
  o: '60692.0',
  c: '60657.0',
  h: '60693.0',
  l: '60653.0',
  v: '4.62545',
  n: 92
}

What the output shows:

  • Prices and sizes are strings. Order book levels, candles and mids all return decimal strings such as '60656.0'. Keep them as strings until you genuinely need arithmetic, and send strings back when you trade.
  • levels is a pair. levels[0] holds bids and levels[1] holds asks, each level carrying px, sz and n. The book returns at most 20 levels per side.
  • szDecimals matters. It is the number of decimal places an order size may have for that asset. BTC has 5 and ETH has 4. Order sizes depend on it.
  • Candle fields t and T are the open and close times in milliseconds. Fields o, h, l and c hold the OHLC prices. A window that crosses minute boundaries can include a partial candle at either end.

Account data is public on Hyperliquid too. Methods such as getOpenOrders(), getUserFills() and getPerpAccountSummary() accept { user: '0x...' } with any account address, no key required. The market data guide lists the rest of the info methods.

API wallets vs your main wallet

Hyperliquid has no API key and secret pair. Every trading action is signed with an Ethereum private key, and there are two kinds of key you can sign with:

  • Main wallet. The wallet that owns the account. Its private key can sign anything the account can do.
  • API wallet (Hyperliquid’s docs also call it an agent wallet). A separate key that your main account approves on the Hyperliquid API page. Once approved, it can sign on behalf of the main account or its subaccounts.

Use an API wallet for anything automated, and keep your main wallet key out of servers and scripts. Two rules from Hyperliquid’s nonces and API wallets docs trip up most people the first time:

  1. The API wallet only signs. To query account data you must use the master account or subaccount address. Passing the API wallet’s own address returns empty results rather than an error.
  2. Nonces are tracked per signer. Two processes sharing one API wallet share one nonce set. Hyperliquid recommends one API wallet per trading process, and a separate API wallet per subaccount you trade in parallel.

In the SDK, that maps to two constructor options: privateKey for the API wallet key and accountAddress for the account it trades for. If you leave out accountAddress, the SDK looks up the master account once with a userRole request and caches it, but passing it saves that round trip.

An unregistered, expired or replaced API wallet can produce this signer error:

Hyperliquid rejected the request: User or API Wallet 0xbea5014325966a390a73510b2f357d4b685527f5 does not exist.

If you see that with a wallet that used to work, read Hyperliquid API wallet stopped working? Expiry, pruning and rotation in Node.js. The SDK’s authentication guide covers custom signers as an alternative to a raw private key.

Use testnet first

Pass testnet: true to RestClient or WebsocketClient and every request goes to Hyperliquid’s testnet instead of mainnet. Testnet has its own API page at app.hyperliquid-testnet.xyz/API, so approve a separate API wallet there.

Testnet funds come from the testnet faucet. Hyperliquid’s docs state that the faucet requires the same address to have deposited on mainnet, after which it provides 1,000 mock USDC. The testing environments guide has more detail.

Place and cancel an order

This script places a post-only ETH perpetual buy, reads back the order id, then cancels it. It reads the API wallet key and account address from environment variables, so no secret ever sits in the code. Save it as place-and-cancel.ts:

import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';

// API wallet private key: signs orders and cancels
const privateKey = process.env.HYPERLIQUID_API_WALLET_KEY;
// Master account (or subaccount) address: the account that owns the orders
const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;

if (!privateKey || !accountAddress) {
  throw new Error(
    'Set HYPERLIQUID_API_WALLET_KEY and HYPERLIQUID_ACCOUNT_ADDRESS first.',
  );
}

const client = new RestClient({
  privateKey,
  accountAddress,
  testnet: process.env.HYPERLIQUID_TESTNET === 'true',
});

// Smallest size, in whole szDecimals steps, worth at least `notional` USDC
function sizeForNotional(price: string, szDecimals: number, notional: number) {
  const factor = 10 ** szDecimals;
  const size = Math.ceil((notional / Number(price)) * factor) / factor;
  return size.toFixed(szDecimals);
}

async function main() {
  const meta = await client.getPerpMetadata();
  const eth = meta.universe.find((asset) => asset.name === 'ETH');
  const book = await client.getOrderBook({ coin: 'ETH' });

  // The fifth bid is a price the exchange already accepts, below the best ask
  const bid = book?.levels[0][4] ?? book?.levels[0][0];
  if (!eth || !bid) throw new Error('No ETH metadata or bids returned.');

  const order = await client.submitLimitOrder({
    symbol: 'ETH',
    side: 'buy',
    price: bid.px,
    size: sizeForNotional(bid.px, eth.szDecimals, 12),
    postOnly: true, // rejected instead of filled if it would cross the book
  });

  // Signed and accepted does not mean placed: check the per order status
  if (order.status !== 'ok') return;
  const status = order.response.data.statuses[0];

  if (!status || 'error' in status) {
    console.error('order rejected:', status?.error);
    return;
  }
  if ('filled' in status) {
    console.log('order filled:', status.filled);
    return;
  }

  const oid = status.resting.oid;
  console.log('resting order id:', oid);

  const cancel = await client.cancelOrders({
    cancels: [{ a: 'ETH', o: oid }],
  });
  if (cancel.status === 'ok') {
    console.log('cancel status:', cancel.response.data.statuses[0]);
  }
}

main().catch((error) => {
  if (error instanceof HyperliquidApiError) {
    console.error('Hyperliquid rejected the request:', error.message);
  } else {
    console.error('request failed:', error);
  }
  process.exit(1);
});

Run it against testnet with your own values:

HYPERLIQUID_TESTNET=true \
HYPERLIQUID_API_WALLET_KEY='0x...' \
HYPERLIQUID_ACCOUNT_ADDRESS='0x...' \
npx tsx place-and-cancel.ts

Why the price and size are calculated, not typed in

Hyperliquid validates every price and size. From the official tick and lot size rules:

  • Prices can have up to 5 significant figures, and no more than MAX_DECIMALS - szDecimals decimal places, where MAX_DECIMALS is 6 for perps and 8 for spot. Integer prices are always allowed.
  • Sizes are rounded to the asset’s szDecimals. With szDecimals = 3, 1.001 is valid and 1.0001 is not.

The script takes the fifth bid as a price on the tick grid and sizes the order in whole szDecimals increments to reach at least 12 USDC. Hyperliquid lists the minimum order value in its error responses.

The SDK also requires prices and sizes as decimal strings. It does not accept JavaScript numbers for these fields, which avoids floating point surprises such as 0.1 + 0.2 creeping into a signed order.

For the full pattern, including a rounding helper for prices and sizes and what to do about Price must be divisible by tick size., see Hyperliquid tick size and szDecimals in Node.js.

Check two levels of success

An order request can fail in two different places, and the script handles both:

  • The whole request is rejected, for example a bad signature or an unknown wallet. The SDK throws a HyperliquidApiError with Hyperliquid’s message, which the catch block prints.
  • The request is accepted but the order is not placed. The response has status: 'ok', yet response.data.statuses[0] holds { error: '...' } instead of { resting: { oid } } or { filled: { ... } }. Insufficient margin, an invalid price, or a post-only order that would have crossed the book all land here.

Cancels follow the same pattern. Each entry in the cancel response’s statuses array is either 'success' or an object with an error field. Hyperliquid documents Order was never placed, already canceled, or filled. as the error for cancelling an order it cannot find.

Other order helpers

  • postOnly: true sends Hyperliquid’s Alo time in force. Leave it out for a normal good-till-cancelled order, or pass timeInForce: 'IOC' for immediate-or-cancel.
  • submitMarketOrder() sends an immediate-or-cancel order with a protection price derived from the current mid and a maxSlippage setting.
  • submitOrder() takes Hyperliquid’s native order shape for batches and TP/SL orders.
  • cancelOrdersByClientOrderId() cancels by your own client order id, which is useful when a request times out before you see the exchange’s order id. Hyperliquid cloid and scheduleCancel in Node.js walks through that pattern.

The orders guide and the repository’s examples folder cover spot orders, TP/SL, leverage and rounding helpers.

Stream trades over WebSocket

REST is fine for snapshots. For live updates, WebsocketClient opens the connection when you first subscribe, sends heartbeats, and reconnects and resubscribes on its own. Data arrives on the message event, tagged with its channel. Save this as websocket-trades.ts:

import { WebsocketClient } from '@siebly/hyperliquid-api';

const ws = new WebsocketClient({
  // testnet: true,
  // The default is 1,000 ms. Allow more on slower or distant networks.
  connectionTimeout: 5_000,
});

ws.on('message', (event) => {
  if (event.channel === 'trades') {
    for (const trade of event.data) {
      console.log(trade.coin, trade.side, trade.px, trade.sz);
    }
  }
});

ws.on('exception', ({ wsKey, event, data }) => {
  console.error('WebSocket exception:', wsKey, event ?? data);
});

await ws.subscribe({ type: 'trades', coin: 'BTC' });

// Stop after 30 seconds for this demo
setTimeout(() => ws.closeAll(), 30_000);
BTC A 60620.0 0.07084
BTC A 60620.0 0.44697
BTC A 60620.0 0.05804
BTC B 60621.0 0.0002

If the WebSocket handshake exceeds the default 1,000 ms connection timeout, increase connectionTimeout. The example allows five seconds.

That is one subscription. For order book and user fill streams, heartbeats, reconnect handling and running the WebSocket alongside REST, read Hyperliquid WebSocket API in TypeScript.

Where to go next

The Hyperliquid SDK is one of Siebly’s open source exchange SDKs, which have over 4.8 million npm downloads across 10+ SDKs.