9 min read
Overview
If your application follows a HIP-3 market such as xyz:NVDA, you may need to flag a wide bid/ask spread, a gap between the mark and published oracle prices, or inputs that have stopped updating. This guide uses Quicknode's live book snapshots and market contexts to build a TypeScript monitor that makes those conditions visible.
HIP-3, or Hyperliquid Improvement Proposal 3, lets builders deploy perpetual markets on Hyperliquid. These derivatives have no fixed expiry, and their deployers define the oracle and contract specifications. The monitor follows one of these markets and reports its spread, mark/oracle divergence, and data health in the terminal. Quicknode supplies the managed market-data access, so you can focus on the conditions your application needs to recognize.
You'll run the complete example, read its output, and inspect the essential integration code to adapt it to your market.
- A HIP-3 market's qualified name includes its builder exchange prefix, such as
xyz:NVDA. - The monitor combines a streamed best bid and ask with periodically fetched mark and oracle prices.
- Market threshold alerts use valid, recent inputs. Stale data and connection loss produce separate health states.
What You Will Need
The example runs as a server process on Hyperliquid mainnet. You need:
- A Quicknode account with a Hyperliquid mainnet endpoint and Build plan or higher for gRPC streaming. See plan access and metering.
- Node.js, latest LTS, and npm. The example requires Node.js 22 or newer.
- Git and familiarity with TypeScript and bid/ask prices.
No wallet or funds are required. If you need an endpoint, follow the Hyperliquid quickstart, then copy its HTTPS endpoint URL from the Quicknode dashboard.
Run a HIP-3 Market Monitor with Quicknode
Start with xyz:NVDA to see the monitor in action. It needs two views of the same market: the book tells you the current bid/ask spread, while the market context lets you compare the published mark and oracle prices.
| Market Input | Quicknode Source | How the Example Updates It |
|---|---|---|
| Best bid and ask | StreamL2Book | Replaces the book with a complete snapshot each block. |
| Mark and oracle prices | metaAndAssetCtxs | Requests context ten seconds after the previous request finishes. |
The monitor checks the age and validity of both inputs before calculating a condition. If context reads stop succeeding, for example, fresh book snapshots alone won't keep the monitor in OK.
Configure and Start the Example
The example is a ready-to-run Node.js process. It uses perpDexs to check your builder exchange, then metaAndAssetCtxs to find your selected market and its mark and oracle prices. After that initial context read, it opens StreamL2Book for the same market. As snapshots arrive, the monitor validates the combined inputs, calculates the spread and mark/oracle divergence, and prints its own health events. Periodic context reads refresh the reference prices.
Clone the examples repository and install the monitor's dependencies:
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/hyperliquid/hip3-market-monitor
npm ci
cp .env.example .env
In .env, replace QUICKNODE_ENDPOINT with the complete HTTPS endpoint URL from your dashboard, including the token. Leave COIN as xyz:NVDA for the first run, or use another qualified HIP-3 market name:
QUICKNODE_ENDPOINT=https://YOUR-ENDPOINT.hype-mainnet.quiknode.pro/YOUR-TOKEN/evm
COIN=xyz:NVDA
Keep .env private and out of version control. Run this process on your server so the token stays out of browser code. The example derives the /info path and gRPC credentials from the endpoint URL.
From the monitor directory, start it with the .env values:
npm start
Press Ctrl+C to close the stream and stop context polling.
If the monitor fails before WAITING, read the startup error to see which check failed. If the book subscription fails, check your endpoint token and confirm that your plan includes gRPC access. The Free Trial includes /info, so the market lookup can succeed before the stream fails.
Read the First Market Health Event
After npm start, the example process prints JSON health events to your terminal. The monitor.ts code generates these events by combining the Quicknode book snapshots and market contexts with its own status, reasons, and age checks.
The monitor starts in WAITING until it receives a book snapshot. The event below is the monitor's output from a live xyz:NVDA run with the default thresholds, expanded here for readability:
{
"type": "health",
"coin": "xyz:NVDA",
"status": "OK",
"reasons": [],
"spreadBps": 0.5924697099855382,
"markOracleBps": 11.267939746174696,
"bookAgeMs": 258,
"contextReadAgeMs": 389
}
Read status first, then the metrics. Here, OK means the inputs passed the configured checks and neither market threshold was exceeded. The spread was about 0.59 basis points (bps), and the mark was about 11.27 bps above the published oracle price. One basis point is 0.01%.
bookAgeMs measures the age of the book's source timestamp. contextReadAgeMs measures the time since this process successfully fetched the context. Your values will vary with the market and receipt times. The monitor emits state changes immediately and summaries every ten seconds, so it doesn't print every snapshot.
With that output as a reference, the following excerpts show how to choose your market, connect its data, and set the conditions your application should flag.
Adapt the Monitor to Your HIP-3 Market
The same integration can follow another qualified HIP-3 market. Keep its identity consistent across the book subscription and context lookup, then choose spread and divergence limits that suit your application. The excerpts below come from monitor.ts; the complete source includes the surrounding client setup, error handling, and shutdown logic.
Select a Market from Its Builder Exchange
In xyz:NVDA, xyz identifies the builder's decentralized exchange (DEX), and the complete string identifies the market. Set COIN in .env to the full name. At startup, the example checks the prefix against perpDexs, then requests that DEX's metaAndAssetCtxs. This selects the builder's markets instead of the default core perpetual universe.
That context response contains two aligned arrays: the market universe and its contexts. The index of your selected market identifies the context containing its mark and oracle prices. In this excerpt, config.coin is the complete name, dex is its prefix, and info is the example's authenticated HTTP POST helper for /info:
const [meta, contexts] = (await info({
type: "metaAndAssetCtxs",
dex,
})) as [{ universe: Asset[] }, Context[]];
if (stopped) return;
const index = meta.universe.findIndex(
(asset) => asset.name === config.coin && !asset.isDelisted
);
if (index < 0 || !contexts[index]) {
context = undefined;
contextAt = 0;
throw Error("Market missing or delisted.");
}
context = contexts[index];
contextAt = Date.now();
Choose a non-delisted name from that DEX's universe when changing markets. The example requires a matching market and context before it starts monitoring.
Subscribe to the Best Bid and Ask
Use that same full name in the book subscription. Quicknode's StreamL2Book supplies a complete aggregated snapshot each block. With n_levels: 1, the monitor receives the best bid and ask levels it needs for spread, and replaces its previous book on each message. It doesn't need to reconstruct incremental order updates.
The complete example creates an encrypted gRPC client on port 10000 and sends the endpoint token through x-token metadata. This excerpt subscribes and records when each matching snapshot arrives:
const stream = client.StreamL2Book(
{ coin: config.coin, n_levels: 1 },
metadata
);
call = stream;
stream.on("data", (next: Book) => {
if (stopped || call !== stream || next.coin !== config.coin) return;
book = next;
bookAt = Date.now();
attempt = 0;
report();
});
Book updates drive the spread calculation. Mark/oracle divergence uses the most recently fetched context, so that metric refreshes periodically. The L2 dataset reference covers the snapshot fields if you want to inspect more book depth.
Choose the Conditions to Flag
For a trading interface, a wide spread could prompt a liquidity warning. A gap between the mark and published oracle prices could prompt investigation of those prices. The monitor expresses both measurements in basis points so you can compare them with your configured limits:
spread = ((ask - bid) / ((ask + bid) / 2)) * 10000;
divergence = ((mark - oracle) / oracle) * 10000;
if (spread > spreadLimit) reasons.push("wide spread");
if (Math.abs(divergence) > divergenceLimit)
reasons.push("mark/oracle divergence");
status = reasons.length ? "ALERT" : "OK";
Spread measures the bid/ask gap relative to the midpoint. Divergence retains its sign in the output: a positive value means the mark is above the oracle. The threshold uses its absolute value, so either direction can produce an alert.
The defaults are 20 bps for spread and 50 bps for absolute divergence. Set spreadBps and divergenceBps in the startMonitor options in run.ts to suit your application. These example thresholds don't define universal market health.
To exercise the alert path, choose a spread threshold below the spread you observe and restart the monitor. A controlled local replay of captured prices, using a refreshed book timestamp and a deliberately low spreadBps: 0.01, produced this event:
{
"type": "health",
"coin": "xyz:NVDA",
"status": "ALERT",
"reasons": [
"wide spread"
],
"spreadBps": 0.5956813104983414,
"markOracleBps": 11.33043115272215,
"bookAgeMs": 0,
"contextReadAgeMs": 4
}
This was a threshold exercise, not an observed live market incident. The same replay produced OK at the default 20 bps spread limit. reasons identifies the condition that exceeded its limit; restore an appropriate threshold after your own exercise.
Handle Stale Inputs and Connection Recovery
Market conditions are meaningful only while the monitor has usable inputs. It tracks the book's source timestamp, its local receipt time, and the last successful context read. With the defaults, book source or receipt age above five seconds, or a context read older than 25 seconds, produces STALE and suppresses both metrics.
| State | How to Interpret It |
|---|---|
WAITING | A stream attempt has started; wait for its first snapshot. |
OK | Required inputs passed the configured checks and neither threshold was exceeded. |
ALERT | Usable inputs exceeded a configured market threshold. Read the reasons field. |
STALE | Book or context inputs are too old. Market metrics are omitted. |
DISCONNECTED | The stream ended or failed. The previous book has been discarded. |
UNKNOWN | Inputs cannot support a valid calculation. Inspect prices, timestamps, and the receiver clock. |
For a status display, distinguish a market warning such as ALERT from an inability to evaluate the market, such as STALE. Missing or invalid prices, a crossed book, and invalid timestamps also prevent usable calculations. Keep the receiver's clock synchronized for the age checks.
When the stream disconnects, the monitor discards its book. It exits with status 1 if gRPC returns UNAUTHENTICATED or PERMISSION_DENIED. Otherwise, it retries with backoff and waits for a fresh snapshot before evaluating thresholds. A live run with a deliberately canceled stream produced the following sequence, shown with selected fields from consecutive events:
{"status":"DISCONNECTED","bookAgeMs":null}
{"type":"reconnect","delayMs":1000}
{"status":"WAITING","bookAgeMs":null}
{"status":"OK","bookAgeMs":294,"spreadBps":0.5923293351114661}
The OK event followed a fresh snapshot. This demonstrates recovery from one forced interruption; it doesn't establish behavior through a prolonged outage.
Context-request failures age out separately. A live-book run with locally injected context failures reached STALE while snapshots kept arriving, then returned to OK when context reads resumed. Your application should preserve that distinction when consuming the emitted events. The example reports terminal JSON events; it doesn't send external notifications.
A successful context read records when this process fetched the published prices, not when the deployer's underlying oracle source updated. OK means the configured checks passed. It doesn't establish execution safety, upstream oracle freshness, or an arbitrage opportunity.
Wrapping Up
You have a single-market monitor whose events can feed a warning or status display in your application. Change the qualified market name and thresholds to adapt it, and keep the example README available for configuration and connection details.
Next Steps
Use the health events to add a market-status display to your trading interface. Keep the monitor and its endpoint credentials on the server, and pass the status and metrics your interface needs to the frontend. A notification integration could consume the same events, with filtering to distinguish state changes from periodic summaries. These are extensions you can build around the example.
For a view of liquidity beyond the spread, request more levels with n_levels in StreamL2Book and adapt the processing to use their aggregated sizes. The L2 dataset reference describes the fields for a depth display.
Quicknode meters the data StreamL2Book delivers after subscription filtering, so longer runs or more price levels can increase credit usage. See gRPC pricing.
Resources
- HIP-3 market monitor source, including the runnable TypeScript integration and pinned protobuf.
- Quicknode StreamL2Book reference, for request and snapshot fields.
- Quicknode market context reference, for the metadata and published prices used in divergence calculations.
- HIP-3 specification, for builder-deployed market responsibilities.
Frequently Asked Questions
How do I select a HIP-3 market through the Hyperliquid API?
Use Quicknode's perpDexs info request to discover builder DEX names, then request metaAndAssetCtxs with the selected dex. Choose a non-delisted market from its universe and pass the full qualified name, such as xyz:NVDA, to StreamL2Book.
Why use full L2 snapshots to monitor only the best bid and ask?
Quicknode's StreamL2Book with n_levels set to 1 returns a complete snapshot containing the top level on each side and a source timestamp. Each snapshot replaces the previous book, which lets this example measure spread and check data age without reconstructing incremental updates.
Does a recent market context prove the HIP-3 oracle is fresh?
No. A successful Quicknode metaAndAssetCtxs read records when the monitor fetched the published context, not when the deployer's underlying oracle source updated. Mark/oracle divergence compares the two published prices and does not verify the underlying source.
What happens if the HIP-3 book stream disconnects?
The example discards the previous book and emits DISCONNECTED. It exits with status 1 if gRPC returns UNAUTHENTICATED or PERMISSION_DENIED. Otherwise, it retries the StreamL2Book subscription with backoff and waits for a fresh snapshot before evaluating market thresholds.
Can this example monitor multiple HIP-3 markets or send notifications?
The example monitors one qualified market through one Quicknode StreamL2Book subscription and emits terminal JSON events. It does not implement multiple-market monitoring or external notifications. You can use its events as inputs to your own application.
