← All articles

Hyperliquid HIP-4 outcome markets in JavaScript and TypeScript: metadata, books and settlement

Hyperliquid HIP-4 outcome markets have two sides per outcome, Yes and No, and each side trades like a spot token with a price between 0 and 1 in the reads below. Hyperliquid’s asset ids page says outcomes share most implementation details with spot trading, with a different token for each side. In the API that means a market list in one info request, prices in the spot asset contexts, books under a # coin name and orders against a large asset id.

@siebly/hyperliquid-api 1.0.5 has methods for the pieces: getOutcomeMetadata(), getSpotAssetContexts(), getSettledOutcome(), submitUserOutcome() and an asset resolver that accepts outcome coins. The reads need no key: the market list, prices and volume, order books, share balances and settlements. A limit order and split/merge are signed calls, shown as testnet code without output.

Versions: @siebly/hyperliquid-api 1.0.5, Node.js 24.

Setup

  • Node.js 24, which runs the TypeScript files directly with node file.ts.
  • No key, account or funds for the reads. The signed examples need an API wallet and use testnet.
  • RestClient takes { testnet: true } to read testnet instead of mainnet. Testnet has its own outcome list with different ids.
npm init -y
npm pkg set type=module
npm install @siebly/hyperliquid-api
npm install --save-dev typescript @types/node

The scripts import each other with .ts extensions, which Node.js 24 runs as they are. This tsconfig.json type-checks them with npx tsc -p .:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src/*.ts"]
}

New to the SDK? Getting started with the Hyperliquid JavaScript SDK covers API wallets and a first order, and the Hyperliquid JavaScript tutorial on siebly.io walks through the REST client.

One number names an outcome side

An outcome id and a side (0 or 1) combine into one number, encoding = 10 * outcome + side. Hyperliquid’s asset ids page uses that number in three forms:

Where Form Outcome 51267, side 0 Side 1
Info requests, trades, mids, asset contexts #<encoding> #512670 #512671
Spot balances +<encoding> +512670 +512671
Signed orders 100000000 + encoding 100512670 100512671

The HIP-4 page says the two side tokens are labelled by sideSpecs, often Yes and No, so side 0 is the first entry and side 1 the second. The helpers below are used by every script in this post:

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

export const client = new RestClient();

export type Side = 0 | 1;

const OUTCOME_ASSET_OFFSET = 100_000_000;

/** One number per outcome side: 10 * outcome + side. */
export const encoding = (outcome: number, side: Side): number => 10 * outcome + side;

/** Coin name in info requests, trades, mids and asset contexts. */
export const outcomeCoin = (outcome: number, side: Side): string => `#${encoding(outcome, side)}`;

/** Token name in spot balances. */
export const outcomeToken = (outcome: number, side: Side): string => `+${encoding(outcome, side)}`;

/** Asset id in signed orders. */
export const outcomeAssetId = (outcome: number, side: Side): number =>
  OUTCOME_ASSET_OFFSET + encoding(outcome, side);

export function decodeEncoding(value: number): { outcome: number; side: Side } {
  return { outcome: Math.floor(value / 10), side: value % 10 === 0 ? 0 : 1 };
}

/** Descriptions are `key:value` pairs separated by `|`. Values can contain colons. */
export function parseDescription(description: string): Record<string, string> {
  const fields: Record<string, string> = {};
  for (const pair of description.split('|')) {
    const colon = pair.indexOf(':');
    if (colon > 0) fields[pair.slice(0, colon)] = pair.slice(colon + 1);
  }
  return fields;
}

List Hyperliquid HIP-4 outcome markets with getOutcomeMetadata

getOutcomeMetadata() sends the outcomeMeta info request. It returns every outcome and question that is currently listed, plus the deployers allowed to create them.

import { client, parseDescription } from './outcomes.ts';

const meta = await client.getOutcomeMetadata();

console.log('top level fields:', Object.keys(meta).join(', '));
console.log(`outcomes: ${meta.outcomes.length}, questions: ${meta.questions.length}, deployers: ${meta.deployers.length}`);

const outcome = meta.outcomes.find((o) => o.name === 'template:binaryPrice');
if (!outcome) throw new Error('No binaryPrice outcome listed right now');

const { description, ...rest } = outcome;
console.log('\noutcome:', JSON.stringify(rest, null, 2));
console.log('\ndescription:', description);
console.log('parsed:', parseDescription(description));

const question = meta.questions.find((q) => !q.name.startsWith('template:sports'));
if (question) {
  console.log('\nquestion:', JSON.stringify({ ...question, description: question.description.slice(0, 80) }, null, 2));
}
top level fields: outcomes, questions, deployers, feeScale
outcomes: 325, questions: 30, deployers: 4

outcome: {
  "outcome": 23745,
  "name": "template:binaryPrice",
  "sideSpecs": [
    {
      "name": "template:Yes"
    },
    {
      "name": "template:No"
    }
  ],
  "quoteToken": "USDC",
  "venue": "txyz"
}

description: perp:xyz:SPCX|priceDescription:1-minute candle|seconds:300|threshold:150|time:20261130-2100
parsed: {
  perp: 'xyz:SPCX',
  priceDescription: '1-minute candle',
  seconds: '300',
  threshold: '150',
  time: '20261130-2100'
}

question: {
  "question": 735,
  "name": "Recurring",
  "description": "class:priceBucket|underlying:BTC|expiry:20261130-0600|priceThresholds:58358,6074",
  "fallbackOutcome": 51658,
  "namedOutcomes": [
    51659,
    51660,
    51661
  ],
  "settledNamedOutcomes": []
}

The fields of an outcome:

  • outcome is the numeric id used in the encoding above.
  • name is either a template id such as template:binaryPrice or a literal name such as Recurring.
  • description is one string of key:value pairs separated by |. For template:binaryPrice the keys include perp, threshold and time. A value can contain colons, as in perp:xyz:SPCX, so split each pair at its first colon.
  • sideSpecs holds the two side names: template:Yes and template:No in the output above, Yes and No on the recurring outcomes.
  • quoteToken names the quote token, USDC in the output above and USDH on the older settled outcomes further down.
  • venue is optional. In the example read only the outcomes named Recurring, Recurring Named Outcome and Recurring Fallback have none.

questions group outcomes. A question lists its namedOutcomes and one fallbackOutcome, and settledNamedOutcomes, which is empty for every question in the example output. Per the HIP-4 page, exactly one outcome of a question settles to Yes and the rest settle to No. The fallback outcome carries the case where none of the named outcomes applies, and its description is other. Group outcomes under their question before counting markets, because a fallback is a listed outcome with its own coins.

import { client, outcomeCoin } from './outcomes.ts';

const meta = await client.getOutcomeMetadata();
const outcomes = new Map(meta.outcomes.map((o) => [o.outcome, o]));

const question = meta.questions.find((q) => !q.name.startsWith('template:sports'));
if (!question) throw new Error('No matching question listed right now');

console.log(`question ${question.question}: ${question.name}`);
console.log(`settled named outcomes: ${JSON.stringify(question.settledNamedOutcomes)}`);

for (const id of [...question.namedOutcomes, question.fallbackOutcome]) {
  const outcome = outcomes.get(id);
  const role = id === question.fallbackOutcome ? 'fallback' : 'named';
  console.log(`${role.padEnd(8)} outcome ${id}  coins ${outcomeCoin(id, 0)}, ${outcomeCoin(id, 1)}  ${outcome?.name} / ${outcome?.description}`);
}
question 735: Recurring
settled named outcomes: []
named    outcome 51659  coins #516590, #516591  Recurring Named Outcome / index:0
named    outcome 51660  coins #516600, #516601  Recurring Named Outcome / index:1
named    outcome 51661  coins #516610, #516611  Recurring Named Outcome / index:2
fallback outcome 51658  coins #516580, #516581  Recurring Fallback / other

Join prices and volume by coin

outcomeMeta carries no prices. getSpotAssetContexts() returns the spot metadata and one context per spot coin, and the outcome sides are in that list under their # coin names. Build a Map by coin and look each side up with outcomeCoin():

import { client, outcomeCoin, parseDescription } from './outcomes.ts';

const [meta, [, contexts]] = await Promise.all([client.getOutcomeMetadata(), client.getSpotAssetContexts()]);
const byCoin = new Map(contexts.map((context) => [context.coin, context]));

const rows = meta.outcomes
  .filter((o) => o.name === 'template:binaryPrice')
  .flatMap((o) => {
    const side0 = byCoin.get(outcomeCoin(o.outcome, 0));
    const side1 = byCoin.get(outcomeCoin(o.outcome, 1));
    if (!side0 || !side1) return [];
    const fields = parseDescription(o.description);
    return [{
      outcome: o.outcome,
      market: fields.perp,
      threshold: fields.threshold,
      time: fields.time,
      side0Mid: side0.midPx,
      side1Mid: side1.midPx,
      dayNtlVlm: Number(side0.dayNtlVlm),
    }];
  })
  .sort((a, b) => b.dayNtlVlm - a.dayNtlVlm);

console.log(`${rows.length} binaryPrice outcomes have both side contexts. Top 5 by side 0 day volume:`);
console.table(rows.slice(0, 5));
109 binaryPrice outcomes have both side contexts. Top 5 by side 0 day volume:
┌─────────┬─────────┬──────────────┬───────────┬─────────────────┬────────────┬────────────┬─────────────┐
│ (index) │ outcome │ market       │ threshold │ time            │ side0Mid   │ side1Mid   │ dayNtlVlm   │
├─────────┼─────────┼──────────────┼───────────┼─────────────────┼────────────┼────────────┼─────────────┤
│ 0       │ 51267   │ 'xyz:GOLD'   │ '3655.1'  │ '20261129-2200' │ '0.914995' │ '0.085005' │ 23153.28437 │
│ 1       │ 51204   │ 'xyz:SPCX'   │ '132.25'  │ '20261129-2100' │ '0.9665'   │ '0.0335'   │ 12676.56345 │
│ 2       │ 23752   │ 'xyz:SPCX'   │ '125'     │ '20261130-2100' │ '0.97841'  │ '0.02159'  │ 11745.59185 │
│ 3       │ 51266   │ 'xyz:SILVER' │ '43.751'  │ '20261129-2200' │ '0.83494'  │ '0.16506'  │ 10967.22645 │
│ 4       │ 51209   │ 'xyz:SNDK'   │ '85.403'  │ '20261129-2100' │ '0.514485' │ '0.485515' │ 8181.15326  │
└─────────┴─────────┴──────────────┴───────────┴─────────────────┴────────────┴────────────┴─────────────┘

Every listed outcome side has a context in the example output. A context holds markPx, midPx, prevDayPx, dayNtlVlm, dayBaseVlm and supply fields, all as strings, and midPx is null when a side has no mid. The two mids of an outcome add up to about 1, because the docs merge the Yes and No books: a buy of Yes at price p is equivalent to a sell of No at 1 - p. getAllMids() also includes the # coins when only mids are needed.

Read an outcome order book

The book of an outcome side is a regular l2Book info request with the # coin. submitRawInfoRequest() posts any info request body and takes the response type as a generic, and OrderBookResponse is exported by the SDK. getRecentTrades() takes the same coin.

import type { OrderBookResponse } from '@siebly/hyperliquid-api';
import { client, outcomeCoin } from './outcomes.ts';

const outcome = Number(process.argv[2]);
if (!Number.isInteger(outcome)) throw new Error('Usage: node src/book.ts <outcome id>');

const coin = outcomeCoin(outcome, 0);
const book = await client.submitRawInfoRequest<OrderBookResponse>({ type: 'l2Book', coin });
const [bids, asks] = book.levels;

console.log(`${book.coin}: ${bids.length} bid levels, ${asks.length} ask levels, keys ${Object.keys(book).join(', ')}`);
console.log('best bid:', bids[0]);
console.log('best ask:', asks[0]);

const trades = await client.getRecentTrades({ coin });
console.log(`${trades.length} recent trades, latest:`, { px: trades[0]?.px, sz: trades[0]?.sz, side: trades[0]?.side, time: trades[0]?.time });
#512670: 14 bid levels, 13 ask levels, keys coin, time, levels
best bid: { px: '0.88', sz: '153.0', n: 1 }
best ask: { px: '0.94999', sz: '400.0', n: 1 }
10 recent trades, latest: { px: '0.89', sz: '86.0', side: 'A', time: 1795968814246 }

levels is [bids, asks], each level has px, sz and n as in any other book, and prices are decimal strings. A coin with no market, such as #99999990, returns HTTP 500.

The WebsocketClient subscribes to the same coin with { type: 'l2Book', coin }. The l2Book post covers fast mode, l2 diffs and rebuilding a book after a reconnect, and the tick size post covers Hyperliquid’s price and size rounding rules.

import { WebsocketClient } from '@siebly/hyperliquid-api';
import { outcomeCoin } from './outcomes.ts';

const outcome = Number(process.argv[2]);
if (!Number.isInteger(outcome)) throw new Error('Usage: node src/ws-book.ts <outcome id>');

// The default connection timeout is 1,000 ms; allow for slow DNS and TLS.
const ws = new WebsocketClient({ connectionTimeout: 5_000 });

ws.on('message', (event) => {
  if (event.channel !== 'l2Book') return;
  const [bids, asks] = event.data.levels;
  console.log(event.data.coin, 'best bid', bids[0]?.px, 'best ask', asks[0]?.px);
});

await ws.subscribe({ type: 'l2Book', coin: outcomeCoin(outcome, 0) });
setTimeout(() => ws.closeAll(), 3000);
#512670 best bid 0.88 best ask 0.94999

Read outcome share balances

An address that holds outcome shares lists them in getSpotBalances() under the +<encoding> token names. The token names are not in the spot token list, so the script decodes them arithmetically and looks the side name up in outcomeMeta:

import { client, decodeEncoding } from './outcomes.ts';

const user = process.argv[2];
if (!user) throw new Error('Usage: node src/balances.ts <0x address>');

const [meta, balances] = await Promise.all([client.getOutcomeMetadata(), client.getSpotBalances({ user })]);
const outcomes = new Map(meta.outcomes.map((o) => [o.outcome, o]));

for (const balance of balances.balances) {
  if (!balance.coin.startsWith('+')) continue;
  const { outcome, side } = decodeEncoding(Number(balance.coin.slice(1)));
  const spec = outcomes.get(outcome);
  console.log(balance.coin, `outcome ${outcome} side ${side}`, spec?.sideSpecs[side]?.name, 'total', balance.total);
}
+512671 outcome 51267 side 1 template:No total 156.0
+199880 outcome 19988 side 0 Yes total 351.0

The address is a public trader taken from getRecentTrades(), whose rows list the two traders in users. It is not shown here.

Read a settlement with getSettledOutcome

getSettledOutcome({ outcome }) returns null while an outcome is unsettled, and also for an id that does not exist. After settlement it returns the outcome’s spec (the same shape as an outcomeMeta entry), a settleFraction string, a details string and, for a named outcome of a question, a question object.

import { client } from './outcomes.ts';

// Full response for one settled outcome.
console.log(JSON.stringify(await client.getSettledOutcome({ outcome: 1 }), null, 2));

// The fields that differ between outcomes, including `question` for a named outcome.
for (const outcome of [4, 99]) {
  const settled = await client.getSettledOutcome({ outcome });
  if (!settled) {
    console.log(outcome, 'not settled');
    continue;
  }
  console.log(outcome, {
    description: settled.spec.description,
    settleFraction: settled.settleFraction,
    details: settled.details,
    question: settled.question && { name: settled.question.name, settled: settled.question.question.settled },
  });
}

// An outcome that is still listed in outcomeMeta returns null.
const meta = await client.getOutcomeMetadata();
const listed = meta.outcomes[0];
if (listed) console.log(listed.outcome, await client.getSettledOutcome({ outcome: listed.outcome }));
{
  "spec": {
    "outcome": 1,
    "name": "Recurring",
    "description": "class:priceBinary|underlying:BTC|expiry:20260504-0600|targetPrice:78213|period:1d",
    "sideSpecs": [
      {
        "name": "Yes"
      },
      {
        "name": "No"
      }
    ],
    "quoteToken": "USDH"
  },
  "settleFraction": "1.0",
  "details": "price:79980"
}
4 {
  description: 'class:priceBinary|underlying:BTC|expiry:20260507-0600|targetPrice:81287|period:1d',
  settleFraction: '0.0',
  details: 'price:81047.1',
  question: undefined
}
99 {
  description: 'index:2',
  settleFraction: '0.0',
  details: 'price:76876.9',
  question: { name: 'Recurring', settled: 18 }
}
46302 null

Per the HIP-4 page, settlement converts a Yes share into settleFraction quote tokens and a No share into 1 - settleFraction, so "1.0" is a binary Yes and "0.0" a binary No. For the two price outcomes above, details holds the settlement price: 79980 against a target of 78213 gave "1.0", and 81047.1 against 81287 gave "0.0". question.question.settled is a number that is the same for every outcome of one question. A negative or fractional outcome is rejected by the info endpoint with Failed to deserialize the JSON body into the target type.

Resolve the asset id for orders

Order requests take an asset. The SDK’s asset resolver turns #<encoding> into 100000000 + encoding from the string alone, with no metadata request. resolveAsset() exposes it:

import { client, outcomeAssetId, outcomeCoin } from './outcomes.ts';

const outcome = Number(process.argv[2]);
if (!Number.isInteger(outcome)) throw new Error('Usage: node src/resolve-asset.ts <outcome id>');

for (const side of [0, 1] as const) {
  const resolved = await client.resolveAsset(outcomeCoin(outcome, side));
  console.log(resolved, resolved.assetId === outcomeAssetId(outcome, side));
}
{ assetId: 100512670, canonicalName: '#512670', kind: 'outcome' } true
{ assetId: 100512671, canonicalName: '#512671', kind: 'outcome' } true

A bare number is also accepted as an asset id, and any id from 100000000 upward is classed as outcome. A malformed coin such as #abc throws Unknown Hyperliquid asset "#abc".

Place a limit order on testnet

Signed calls need an API wallet key and the master account address. API wallets have an expiry date, and the API wallet expiry post covers expiry, pruning and rotation. The client below points at testnet:

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

const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY;
const accountAddress = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!privateKey || !accountAddress) {
  throw new Error('Set HYPERLIQUID_PRIVATE_KEY (API wallet key) and HYPERLIQUID_ACCOUNT_ADDRESS (master account)');
}

export const testnetClient = new RestClient({ privateKey, accountAddress, testnet: true });

submitLimitOrder() takes the outcome coin as symbol and prices and sizes as decimal strings. The SDK sends it as asset 100000000 + encoding in the order action. Pick a testnet outcome id from getOutcomeMetadata() on a testnet client and pass it with a price and size:

import { outcomeCoin } from './outcomes.ts';
import { testnetClient } from './testnet-client.ts';

const [outcomeArg, price, size] = process.argv.slice(2);
const outcome = Number(outcomeArg);
if (!Number.isInteger(outcome) || !price || !size) {
  throw new Error('Usage: node src/testnet-order.ts <outcome id> <price> <size>');
}

const response = await testnetClient.submitLimitOrder({
  symbol: outcomeCoin(outcome, 0), // '#<10 * outcome + side>', sent as asset 100000000 + encoding
  side: 'buy',
  price, // decimal string
  size, // decimal string
  timeInForce: 'GTC',
});

if (response.status === 'err') {
  console.error('Rejected:', response.response);
} else {
  console.log(response.response.data.statuses[0]); // { resting: { oid } }, { filled: {...} } or { error }
}

Split and merge shares with submitUserOutcome

submitUserOutcome() sends the userOutcome action. Each request carries one operation key. The shapes below follow Hyperliquid’s exchange endpoint docs:

Operation Request Effect
Split { splitOutcome: { outcome, amount } } Quote tokens become the same amount of Yes and No shares
Merge { mergeOutcome: { outcome, amount } } Yes and No shares become quote tokens. amount: null merges the maximum
Merge question { mergeQuestion: { question, amount } } Yes shares of every outcome in a question become quote tokens. amount: null merges the maximum
Negate { negateOutcome: { question, outcome, amount } } No shares of one outcome become Yes shares of every other outcome in the question

outcome and question are numbers. amount is a decimal string, and "1.0" is sent as "1". The testnet script below uses split and merge:

import { testnetClient } from './testnet-client.ts';

const [action, outcomeArg, amount] = process.argv.slice(2);
const outcome = Number(outcomeArg);
if ((action !== 'split' && action !== 'merge') || !Number.isInteger(outcome)) {
  throw new Error('Usage: node src/testnet-split-merge.ts <split|merge> <outcome id> [amount]');
}

// Quote tokens in, Yes and No shares out.
const split = () => testnetClient.submitUserOutcome({ splitOutcome: { outcome, amount: amount ?? '1.0' } });

// Yes and No shares in, quote tokens out. amount: null merges the maximum.
const merge = () => testnetClient.submitUserOutcome({ mergeOutcome: { outcome, amount: amount ?? null } });

const response = await (action === 'split' ? split() : merge());
console.log(response);

Keys, testnet and settled outcomes

Do I need an API key to read outcome markets?

No. getOutcomeMetadata(), getSpotAssetContexts(), getSettledOutcome(), the l2Book request and getSpotBalances() are public info requests, and a RestClient without options sends them.

Can I use a mainnet outcome id on testnet?

Mainnet and testnet list different outcomes. Outcome 51267 from the mainnet reads above has no testnet context, and an l2Book request for #512670 on testnet returns HTTP 500. Read the metadata with a testnet client before building a coin name.

Do settled outcomes stay in getOutcomeMetadata()?

No. Outcomes 1 and 4 are absent from the example output, where the lowest listed id is 1472, and getSettledOutcome() still returns them. Use getOutcomeMetadata() for what is currently listed and getSettledOutcome() for a finished outcome by id.

Further reading

@siebly/hyperliquid-api is one of Siebly’s open-source SDKs for crypto exchange APIs, with over 4.8 million npm downloads across 10+ SDKs.