Hyperliquid API errors come back as strings. In @siebly/hyperliquid-api, inspect the HTTP status, error class and any per-order status to determine whether to correct the request, check the signer or wait before retrying.
Before you start
- Node.js 24, which runs the
.tsfiles below directly withnode file.ts. @siebly/hyperliquid-api1.0.5 andethers, which a few examples use to create throwaway keys and check addresses.- No funded account. The signed examples use a fresh random key on testnet, which is enough to trigger the errors safely, and the read only examples use public mainnet data.
npm init -y
npm pkg set type=module
npm install @siebly/hyperliquid-api ethers
If you have not used the SDK before, start with getting started with the Hyperliquid JavaScript SDK, which covers API wallets, REST calls and placing an order.
Quick lookup of Hyperliquid API errors
| Error text | Arrives as | Usual cause |
|---|---|---|
User or API Wallet 0x... does not exist. |
HyperliquidApiError, HTTP 200 |
The signing key is not an account or an approved API wallet on this network |
The signer is not a Hyperliquid account on this network. Set accountAddress when using an API wallet. |
TypeError from the SDK |
An account read with no accountAddress, and Hyperliquid does not know the signer |
Invalid nonce: duplicate nonce ... |
HyperliquidApiError, HTTP 200 |
Two processes signing with the same key in the same millisecond |
Failed to deserialize the JSON body into the target type |
HyperliquidApiError, HTTP 422 |
A malformed /info request, such as a bad address or unknown type |
Request failed with status code 429 |
HyperliquidApiError, HTTP 429 |
Over the per IP rate limit |
timeout of ...ms exceeded, WebSocket connection timed out after 1000 ms. |
HyperliquidApiError with code ECONNABORTED, or HyperliquidWebSocketError |
No response in time |
Unknown Hyperliquid asset "BTC-PERP"..., Invalid decimal string "1e-7"..., size rounds to zero... |
RangeError or TypeError from the SDK |
A coin name or number the SDK will not send |
Price must be divisible by tick size., Insufficient margin to place order. |
No throw: an error in the order’s status |
Price precision, or not enough margin on the account |
How Hyperliquid API errors reach your JavaScript code
Check the HTTP status and error type before matching a message. The SDK exposes exchangeCode when the exchange embeds a numeric code in the error text.
- Hyperliquid rejected the whole request. The HTTP status is 200, but the body is
{"status":"err","response":"..."}. The SDK turns that into aHyperliquidApiErrorwhosemessageis the response string and whosestatusis 200. - Hyperliquid answered with an HTTP error, such as 422 or 429. You get a
HyperliquidApiErrorwith thatstatus, andresponseholds the body. - No response arrived: a timeout, DNS failure or reset connection. You get a
HyperliquidApiErrorwith nostatusand a networkcodesuch asECONNABORTED. - The SDK refused the input before sending anything. These are plain
TypeErrororRangeErrorexceptions.
There is a fifth case that is not an exception: an order request that succeeds overall while individual orders in it are rejected. That is covered in its own section. The SDK does not retry any of the first four for you.
This helper sorts an error into one of the four kinds. Save it as handle-error.ts:
import { HyperliquidApiError } from '@siebly/hyperliquid-api';
export type ErrorKind =
| 'rejected' // Hyperliquid answered HTTP 200 with {"status":"err"}
| 'http' // Hyperliquid answered with an HTTP error status (422, 429, 5xx)
| 'network' // no response at all: timeout, DNS, connection reset
| 'local'; // the SDK refused the input before sending anything
export interface ErrorSummary {
kind: ErrorKind;
message: string;
status?: number;
code?: string;
}
export function summariseError(error: unknown): ErrorSummary {
if (error instanceof HyperliquidApiError) {
if (error.status === 200) {
return { kind: 'rejected', message: error.message, status: 200 };
}
if (error.status !== undefined) {
return { kind: 'http', message: error.message, status: error.status, code: error.code };
}
return { kind: 'network', message: error.message, code: error.code };
}
if (error instanceof TypeError || error instanceof RangeError) {
return { kind: 'local', message: error.message };
}
throw error; // a bug in your own code: let it surface
}
The WebSocket clients throw HyperliquidWebSocketError for connection and protocol failures, which this helper passes on unchanged. Catch it separately if you use them.
To see each kind, this script triggers one of each with a throwaway key that was never approved anywhere. Save it as errors-demo.ts:
import { RestClient } from '@siebly/hyperliquid-api';
import { Wallet } from 'ethers';
import { summariseError } from './handle-error.ts';
// A fresh key that was never approved anywhere, so nothing here can trade.
const wallet = Wallet.createRandom();
const client = new RestClient({ testnet: true, privateKey: wallet.privateKey, accountAddress: wallet.address });
const order = { symbol: 'BTC', side: 'buy', price: '1000', size: '0.001', postOnly: true } as const;
const attempts: [string, () => Promise<unknown>][] = [
['order from an unapproved key', () => client.submitLimitOrder(order)],
['order for an unknown coin', () => client.submitLimitOrder({ ...order, symbol: 'BTC-PERP' })],
['malformed /info request', () => client.submitRawInfoRequest({ type: 'notARealType' })],
['request with a 1 ms timeout', () => new RestClient({ testnet: true }, { timeout: 1 }).getAllMids()],
];
for (const [label, attempt] of attempts) {
try {
await attempt();
} catch (error) {
console.log(label, '->', JSON.stringify(summariseError(error)));
}
}
Output from testnet:
order from an unapproved key -> {"kind":"rejected","message":"User or API Wallet 0x5773185935fb830706110a8932009a5c3d9aeb44 does not exist.","status":200}
order for an unknown coin -> {"kind":"local","message":"Unknown Hyperliquid asset \"BTC-PERP\". Call refreshAssetMetadata() after a new listing."}
malformed /info request -> {"kind":"http","message":"Failed to deserialize the JSON body into the target type","status":422,"code":"ERR_BAD_REQUEST"}
request with a 1 ms timeout -> {"kind":"network","message":"timeout of 1ms exceeded","code":"ECONNABORTED"}
Log the whole summary, not just the message. A 200 status on an error surprises people, and it is the quickest way to tell “Hyperliquid said no” apart from “the request never got there”. The SDK’s error handling guide describes the same error fields.
“User or API Wallet 0x… does not exist.”
The address in this message identifies the signing key. Check its registration on the selected network and, for an API wallet, its approval by the account.
Common causes:
- The key was never approved as an API wallet.
- It was approved on the other network. Mainnet and testnet approvals are separate, so a mainnet API wallet does not exist on testnet.
- The API wallet was replaced, expired or pruned. This is covered in depth in Hyperliquid API wallet stopped working? Expiry, pruning and rotation in Node.js.
Ask Hyperliquid what it thinks the signer is, on the network you are actually using. Save this as check-signer.ts:
import { RestClient } from '@siebly/hyperliquid-api';
import { Wallet } from 'ethers';
// Which account, if any, does this signing key belong to on this network?
export async function describeSigner(privateKey: string, testnet: boolean): Promise<string> {
const signer = new Wallet(privateKey).address;
const role = await new RestClient({ testnet }).getUserRole({ user: signer });
switch (role.role) {
case 'agent':
return `${signer} is an API wallet for account ${role.data.user}. Use that as accountAddress.`;
case 'missing':
return `${signer} is unknown on ${testnet ? 'testnet' : 'mainnet'}. Approve it as an API wallet on this network, or check you are on the right network.`;
default:
return `${signer} has role "${role.role}" on ${testnet ? 'testnet' : 'mainnet'}.`;
}
}
const key = process.env.HYPERLIQUID_API_WALLET_KEY ?? Wallet.createRandom().privateKey;
console.log(await describeSigner(key, true));
console.log(await describeSigner(key, false));
Run with no key set, it checks a fresh random key:
0x56de1fdeEEdB02060FBB1C27Ff3dD888e96D36ae is unknown on testnet. Approve it as an API wallet on this network, or check you are on the right network.
0x56de1fdeEEdB02060FBB1C27Ff3dD888e96D36ae is unknown on mainnet. Approve it as an API wallet on this network, or check you are on the right network.
A missing role on the network you trade on means the key is not registered there: approve that key as an API wallet there, or use one that is. Hyperliquid runs this check before it validates prices and sizes, so an unapproved key gets this error for every order, however wrong the price is.
“The signer is not a Hyperliquid account on this network. Set accountAddress when using an API wallet.”
This one comes from the SDK, not Hyperliquid, and it is a TypeError, not a HyperliquidApiError. It appears when you call an account method such as getPerpAccountSummary() on a client that has a privateKey but no accountAddress. From the SDK source, the client then asks Hyperliquid for the signer’s role to work out which account to read, and throws this message when the answer is missing.
import { RestClient } from '@siebly/hyperliquid-api';
import { Wallet } from 'ethers';
// Test only: a fresh key Hyperliquid has never seen, standing in for an API wallet key.
const apiWalletKey = Wallet.createRandom().privateKey;
const accountAddress = Wallet.createRandom().address;
const withoutAccount = new RestClient({ testnet: true, privateKey: apiWalletKey });
try {
await withoutAccount.getPerpAccountSummary();
} catch (error) {
console.log(`${(error as Error).name}: ${(error as Error).message}`);
}
const withAccount = new RestClient({ testnet: true, privateKey: apiWalletKey, accountAddress });
const summary = await withAccount.getPerpAccountSummary();
console.log('with accountAddress, account value:', summary.marginSummary.accountValue);
TypeError: The signer is not a Hyperliquid account on this network. Set accountAddress when using an API wallet.
with accountAddress, account value: 0.0
The fix is in the message: always pass accountAddress, set to the main account or subaccount the API wallet trades for. The API wallet only signs; balances and positions belong to the account. The authentication guide maps exchange style API keys onto these two options. If you set accountAddress and orders then fail with “does not exist”, the key itself is the problem: see the previous section.
“Invalid nonce: duplicate nonce …”
Every signed action carries a nonce, and Hyperliquid tracks nonces per signer. The SDK uses the current time in milliseconds and, within one Node.js process, keeps nonces increasing across every client that uses the same key. It cannot see other processes. Run two processes with the same API wallet and sooner or later both sign in the same millisecond. Hyperliquid accepts the first and rejects the second.
This script starts two worker processes with the same key and has them send orders at the same moments. Save it as two-processes.ts:
// Two Node.js processes signing with the same key, SDK default nonces.
// Test only: a fresh key that was never approved, passed to the children through env.
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
import { spawn } from 'node:child_process';
import { Wallet } from 'ethers';
if (!process.env.WORKER) {
const wallet = Wallet.createRandom();
const startAt = Date.now() + 5_000; // both workers fire at the same moments
for (const worker of ['A', 'B']) {
spawn(process.execPath, [process.argv[1]], {
env: { ...process.env, WORKER: worker, KEY: wallet.privateKey, ADDRESS: wallet.address, START_AT: String(startAt) },
stdio: 'inherit',
});
}
} else {
const client = new RestClient({ testnet: true, privateKey: process.env.KEY!, accountAddress: process.env.ADDRESS! });
await client.refreshAssetMetadata(); // load coin metadata before the timed loop
const order = { symbol: 'BTC', side: 'buy', price: '1000', size: '0.001' } as const;
for (let i = 0; i < 5; i++) {
const at = Number(process.env.START_AT) + i * 1_000;
while (Date.now() < at) await new Promise((resolve) => setImmediate(resolve));
try {
await client.submitLimitOrder(order);
} catch (error) {
if (error instanceof HyperliquidApiError) {
console.log(`worker ${process.env.WORKER}, order ${i + 1}: ${error.message}`);
}
}
}
}
Example output from testnet. In a round that clashes, one worker passes the nonce check (and then gets “does not exist”, because the key is unapproved) and the other is refused:
worker A, order 1: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker B, order 1: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker A, order 2: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker B, order 2: Invalid nonce: duplicate nonce 1795797631463
worker A, order 3: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker B, order 3: Invalid nonce: duplicate nonce 1795797632463
worker A, order 4: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker B, order 4: Invalid nonce: duplicate nonce 1795797633463
worker B, order 5: User or API Wallet 0x80ece5cdba3193b13b58d37361c4a3b5bc408c8a does not exist.
worker A, order 5: Invalid nonce: duplicate nonce 1795797634463
Four of the five rounds in the example clash. With a real API wallet, the winner’s order goes through and the loser’s is rejected, which is easy to miss in logs. The fix is one API wallet per process: approve a separate API wallet for each bot, worker or container, all trading for the same accountAddress. Several clients inside one process can share a key, because they share one nonce counter.
HTTP 422: “Failed to deserialize the JSON body into the target type”
/info returns HTTP 422 for a malformed request, including an unknown request type, a missing coin or an invalid user address. The body may omit the field name.
The SDK’s typed methods take care of request types and field names, so in practice this usually means a bad address passed through from config or user input. The SDK sends it as given, so check it first. Save this as safe-read.ts:
import { HyperliquidApiError, RestClient } from '@siebly/hyperliquid-api';
import { isAddress } from 'ethers';
const client = new RestClient();
export async function readAccount(user: string) {
// A malformed address reaches /info and comes back as HTTP 422.
if (!isAddress(user)) throw new TypeError(`Not an EVM address: "${user}"`);
return client.getPerpAccountSummary({ user });
}
for (const user of ['0x123', '0x' + 'ab'.repeat(20)]) {
try {
const summary = await readAccount(user);
console.log(user, 'account value', summary.marginSummary.accountValue);
} catch (error) {
console.log(user, '->', error instanceof HyperliquidApiError ? `HTTP ${error.status}` : (error as Error).message);
}
}
// Without the check, the same bad address is a 422 from Hyperliquid:
try {
await client.getPerpAccountSummary({ user: '0x123' });
} catch (error) {
if (error instanceof HyperliquidApiError) console.log(`HTTP ${error.status}: ${error.message}`);
}
0x123 -> Not an EVM address: "0x123"
0xabababababababababababababababababababab account value 0.0
HTTP 422: Failed to deserialize the JSON body into the target type
If you build raw requests with submitRawInfoRequest(), compare them with Hyperliquid’s info endpoint documentation field by field when you see a 422.
HTTP 429
For HTTP 429, the SDK throws a HyperliquidApiError with status 429. It does not retry automatically. With an empty response body, the SDK supplies the following message.
[429 empty body] name: HyperliquidApiError; message: "Request failed with status code 429"; status: 429; code: ERR_BAD_REQUEST; response: ""
That message comes from the HTTP client and changes with the body, so check the status instead:
if (error instanceof HyperliquidApiError && error.status === 429) {
// back off, then fix whatever is spending the budget
}
The weights, the 1,200 per minute budget, a retry helper and how to move polling onto WebSockets are all in Hyperliquid API rate limits in Node.js.
Timeouts: “timeout of …ms exceeded” and “WebSocket connection timed out after 1000 ms.”
On a REST timeout, HyperliquidApiError carries ECONNABORTED and no HTTP status. The default timeout is 10,000 ms. Set it in the second RestClient argument.
const client = new RestClient({ testnet: true }, { timeout: 15_000 });
A timeout does not tell you whether Hyperliquid received the request. For reads, retry. For orders, look the order up before sending it again; a client order id makes that possible, as shown in Hyperliquid cloid and scheduleCancel in Node.js.
The WebSocket connection timeout defaults to 1,000 ms, including DNS and TLS. Set connectionTimeout in the WebSocket client options.
import { WebsocketClient } from '@siebly/hyperliquid-api';
const quiet = { trace: () => {}, info: () => {}, error: () => {} };
for (const connectionTimeout of [1_000, 5_000]) {
const ws = new WebsocketClient({ connectionTimeout }, quiet);
const started = Date.now();
try {
await ws.subscribe({ type: 'allMids' });
console.log(`connectionTimeout ${connectionTimeout}: subscribed after ${Date.now() - started} ms`);
} catch (error) {
console.log(`connectionTimeout ${connectionTimeout}: ${(error as Error).name}: ${(error as Error).message}`);
}
ws.closeAll();
}
connectionTimeout 1000: HyperliquidWebSocketError: WebSocket connection timed out after 1000 ms.
connectionTimeout 5000: subscribed after 1337 ms
Set connectionTimeout: 5_000 on both WebsocketClient and WebsocketAPIClient. Heartbeats and reconnects are covered in Hyperliquid WebSocket API in TypeScript.
SDK input errors: unknown coins, decimal strings and zero sizes
The SDK validates coin names, prices and sizes before signing or sending an order, so these errors never reach the Hyperliquid API.
| Message | Type | Cause |
|---|---|---|
Unknown Hyperliquid asset "BTC-PERP". Call refreshAssetMetadata() after a new listing. |
RangeError |
The coin name is not in Hyperliquid’s metadata. Perps use the bare name, such as BTC. |
Invalid decimal string "1e-7". Use plain decimal notation without exponents or leading zeroes. |
TypeError |
A price or size string in exponent notation, or with a leading zero such as "01000" |
size must be greater than zero. |
RangeError |
A size of "0" |
size rounds to zero at 5 decimal places. |
RangeError |
A market order size smaller than one size step. BTC has szDecimals 5. |
The decimal string error is easy to hit by accident. Prices and sizes are strings, and JavaScript writes small numbers in exponent notation, so String(0.0000001) is "1e-7". Build sizes with toFixed() from the coin’s szDecimals instead. Save this as order-inputs.ts:
import { RestClient } from '@siebly/hyperliquid-api';
const client = new RestClient();
// JavaScript switches to exponent notation for small numbers.
console.log(String(0.0000001)); // '1e-7': the SDK rejects this string
/** Turn a number into a size string the SDK accepts, cut to the coin's szDecimals. */
export async function sizeString(coin: string, size: number): Promise<string> {
const asset = await client.resolveAsset(coin); // throws RangeError for unknown coins
const decimals = asset.szDecimals ?? 0;
const factor = 10 ** decimals;
// toPrecision(12) stops 0.29 * 100 = 28.999... from flooring to 28
const steps = Math.floor(Number((size * factor).toPrecision(12)));
const text = (steps / factor).toFixed(decimals);
if (Number(text) <= 0) throw new RangeError(`${size} ${coin} is below the smallest size step.`);
return text;
}
console.log(await sizeString('BTC', 0.0012345)); // '0.00123' with szDecimals 5
console.log(await sizeString('SOL', 0.29)); // '0.29' with szDecimals 2
try {
await sizeString('BTC-PERP', 1);
} catch (error) {
console.log((error as Error).message);
}
1e-7
0.00123
0.29
Unknown Hyperliquid asset "BTC-PERP". Call refreshAssetMetadata() after a new listing.
resolveAsset() also gives you an early, clear error for a mistyped coin, before you build the order. Prices follow stricter rules than sizes, which is the next section.
Rejected orders that do not throw: tick size and insufficient margin
An order request can succeed as a whole while individual orders in it are rejected. The SDK then returns normally with status: 'ok', and each rejected order has an error string in response.data.statuses. If your code only uses try and catch, these Hyperliquid API errors pass silently. Hyperliquid’s error responses page lists the per order strings. Two of them come up most in API code:
Price must be divisible by tick size.The price has more significant figures or decimals than the coin allows. The page also notes that some tick size checks happen earlier, in which case the whole request is rejected with a single error instead.Insufficient margin to place order.The account the order is placed for does not have enough free margin for it.
The error strings above come from Hyperliquid’s documented order responses. Match them in the per-order status.
import type { ExchangeResponse, OrderResponseData } from '@siebly/hyperliquid-api';
/** Per order rejections: the request succeeded, but some orders in it did not. */
export function orderErrors(result: ExchangeResponse<OrderResponseData>): string[] {
if (result.status !== 'ok') return [result.response];
return result.response.data.statuses.flatMap((status, index) =>
'error' in status ? [`order ${index}: ${status.error}`] : [],
);
}
Called with a response holding one resting order and two rejections:
[
'order 1: Price must be divisible by tick size.',
'order 2: Insufficient margin to place order.'
]
Cancels work the same way: each entry in their statuses is either 'success' or an object with an error string.
Fixing “Price must be divisible by tick size.”
Hyperliquid has no fixed tick per market. Perp prices may have at most five significant figures and at most 6 - szDecimals decimal places, and a mid price from getAllMids() often breaks that rule. The rules, a rounding helper and the difference between submitLimitOrder() (no rounding) and submitMarketOrder() (rounds for you) are covered in Hyperliquid tick size and szDecimals in Node.js.
Fixing “Insufficient margin to place order.”
For API code, the useful habit is to read the account before you sign an order, and to read the right account: the accountAddress the order is placed for, not the API wallet’s address. Save this as margin-check.ts:
import { RestClient } from '@siebly/hyperliquid-api';
const client = new RestClient({ testnet: process.env.HYPERLIQUID_TESTNET === 'true' });
/** Read the perp account the order will be placed for, before you sign anything. */
export async function freeMargin(accountAddress: string): Promise<number> {
const summary = await client.getPerpAccountSummary({ user: accountAddress });
console.log(
`account value ${summary.marginSummary.accountValue}, ` +
`margin used ${summary.marginSummary.totalMarginUsed}, withdrawable ${summary.withdrawable}`,
);
return Number(summary.withdrawable);
}
// Pass the account address (not the API wallet address) as the first argument.
const account = process.argv[2];
if (!account) throw new Error('Usage: node margin-check.ts <accountAddress>');
if ((await freeMargin(account)) <= 0) {
console.log('No free margin on this account: not sending the order.');
}
Run against a fresh, empty address on mainnet:
account value 0.0, margin used 0.0, withdrawable 0.0
No free margin on this account: not sending the order.
The check is approximate. How much margin an order needs depends on the account’s settings, and Hyperliquid makes the final decision, so keep handling the per order error as well. If an account you know is funded reads as empty, the usual cause is an accountAddress pointing at the wrong account or subaccount, or a client on the wrong network.
No error at all: an unknown coin on a WebSocket subscription
An unrecognised coin subscription can close the socket before an acknowledgement. Validate coin names with resolveAsset() to avoid repeatedly reconnecting to the same invalid topic.
Further reading
- The SDK’s error handling guide and troubleshooting guide
- Hyperliquid API keys and API wallets in the SDK docs
- Hyperliquid’s error responses page
- Hyperliquid JavaScript and TypeScript SDK on siebly.io, and the source on GitHub
- Hyperliquid API rate limits in Node.js and Hyperliquid tick size and szDecimals in Node.js
