> This is part 1 of 3 of the full documentation (pages 1–100 of 229).
> The content is paginated: fetch every part to see all of it.
> Next part: https://hydromancer.xyz/docs/llms-full.txt/1
> Page index: https://hydromancer.xyz/docs/llms.txt

> Agents can also search and read this documentation through its [MCP server](https://hydromancer.xyz/docs/~gitbook/mcp).

# Hydromancer: Overview

Hydromancer is data infrastructure for Hyperliquid. We provide real-time APIs, WebSocket streams, and analytics — so you can ship unique features faster with better data.

{% hint style="info" %}
**TL;DR**: [Hydromancer is a data provider dedicated to Hyperliquid](https://hydromancer.xyz/). It offers REST and WebSocket APIs with order-level and market-wide data that Hyperliquid's native API doesn't expose, streams delivered faster than the native API, and free historical data. 100+ teams on Hyperliquid use the Hydromancer stack.
{% endhint %}

### Hydromancer at a glance

Hydromancer has the broadest endpoint coverage for Hyperliquid, on a stack built for both app builders and institutions: low-latency streams, replay after disconnects and SLA-backed infrastructure.&#x20;

Pricing is predictable, with data streaming plans and flat-priced add-ons for market-wide data that are never metered per call, row or message.

<details>

<summary>🌐 <strong>Coverage</strong></summary>

* Hyperliquid only: perps on the main DEX and on HIP-3 DEXes, spot markets, and HIP-4 outcome markets.
* A [REST API for queries and history](https://hydromancer.xyz/hyperliquid-rest-api), and a [WebSocket API for real-time streams](https://hydromancer.xyz/data-streaming). Testnet APIs are included on every tier.

</details>

<details>

<summary>🔍 <strong>Data the native Hyperliquid API doesn't provide</strong></summary>

* **L4 orderbooks**: every resting order with the address of the user who placed it, as a [snapshot](https://hydromancer.xyz/docs/rest-api/market-data/l4book) and as a [per-block update stream](https://hydromancer.xyz/docs/websocket/orderbook-streaming/l4bookupdates).
* **Market-wide streams** across all users: every [fill](https://hydromancer.xyz/docs/websocket/trades-data/allfills), [liquidation](https://hydromancer.xyz/docs/websocket/trades-data/liquidationfills), [deposit, withdrawal and transfer](https://hydromancer.xyz/docs/websocket/funding-and-deposits-data/allusernonfundingledgerevents), [leverage change](https://hydromancer.xyz/docs/websocket/leverage-and-margin-updates/allleverageupdates), [TWAP status](https://hydromancer.xyz/docs/websocket/alltwapstatusupdates) and [TP/SL trigger order](https://hydromancer.xyz/docs/websocket/tpslupdates).
* **Positioning snapshots**: the open positions of every trader ([perpSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/perpsnapshot)), spot holdings ([spotSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/spotsnapshot)) and account values ([accountValueSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/accountvaluesnapshot)).
* **Builder data**: fills, orders, funding and ledger events for a builder code and the users who approved its fee, over [REST](https://hydromancer.xyz/docs/rest-api/historical-data/builderfillsbytime) and [WebSocket](https://hydromancer.xyz/docs/websocket/builder-data).
* **Trader performance**: realized PnL summaries and leaderboards ([user performance](https://hydromancer.xyz/docs/rest-api/user-performance)).
* **Liquidity analytics** per market: [current depth](https://hydromancer.xyz/docs/rest-api/market-data/currentdepth), [liquidity history](https://hydromancer.xyz/docs/rest-api/market-data/marketliquidityhistory) and [slippage history](https://hydromancer.xyz/docs/rest-api/market-data/slippagehistory).

</details>

<details>

<summary>🛡️ <strong>Reliability</strong></summary>

* WebSocket sessions survive disconnects. Reconnect with your `sessionId` and `cursor`: subscriptions are restored automatically and missed data is replayed (up to 15 minutes for most channels, 3 minutes for L4 updates). `hasGap` tells you when history is incomplete. See [Session Management and Reconnection](https://hydromancer.xyz/docs/websocket/session-management-and-reconnection).
* Every live message carries a `seq` for gap detection and a `cursor` for resuming.
* The [Python SDK](https://github.com/hydromancerxyz/hydromancer-sdk) handles L4 and TP/SL book sync and recovery for you.
* Incidents are published as [public incident reports](https://hydromancer.xyz/docs/incidents).
* Teams running their own nodes can use [Peering](https://hydromancer.xyz/docs/peering), with a 99.99% uptime SLA.

</details>

<details>

<summary>📏 <strong>Limits</strong></summary>

* REST: a per-minute weight budget of 5,000 (Starter), 20,000 (Growth) or 50,000 (Scale). See [Rate Limits and User Limits](https://hydromancer.xyz/docs/rest-api/rate-limits-and-user-limits).
* WebSocket: up to 1,000 connections and 10,000 subscriptions on Scale, with per-coin caps per feed (for example, 200 coins of L4 updates on Scale). Feeds that cover every market are add-ons. See [WebSocket limits](https://hydromancer.xyz/docs/websocket/rate-limits-user-limits-and-heartbeats).

</details>

<details>

<summary>💵 <strong>Pricing model</strong></summary>

* Plans: Starter $300, Growth $1,200 and Scale $2,500 per month, each with a monthly token allowance for REST calls. Enterprise pricing is custom.
* Add-ons for market-wide data are a **flat monthly price for access**. They are not billed per call, per row, per message or per GB. See [Pricing](https://hydromancer.xyz/docs/pricing).
* Hyperliquid historical data is free through [Reservoir](https://hydromancer.xyz/docs/reservoir), under CC BY 4.0, with no API key required.&#x20;

</details>

<details>

<summary>🤖 <strong>For AI agents</strong></summary>

* The full documentation index is at [llms.txt](https://docs.hydromancer.xyz/llms.txt).
* Any page is available as markdown by appending `.md` to its URL.

</details>

### Who builds on Hydromancer

Hydromancer stack is optimized for demanding teams requiring granular data, low latency real-time streams, and better developer experience.

<details>

<summary>🛠 <strong>App builders</strong></summary>

You're building a trading interface, portfolio tracker, analytics dashboard, or DeFi product on Hyperliquid. You need real-time data that's fast, reliable, and easy to integrate.

**Why Hydromancer:**

* **Unique endpoints** — Hydromancer rebuilt and extended the schema with endpoints that don't exist natively, so you write less code and ship faster. Based on feedback from 30+ builders.
* **Real-time data** — Hydromancer provides WebSocket streams for orderbooks, trades, account updates, and more. They run at lower latency than native Hyperliquid connections.

</details>

<details>

<summary><strong>🧪 HIP-3 or HIP-4 deployers</strong></summary>

You are deploying markets on HIP-3 or HIP-4 and need to monitor your markets' liquidity, user activity, and show the traction of your DEX to the wider audience.

**Why Hydromancer:**

* **Granular data and metrics** - liquidity metrics with sub-second granularity, real-time market maker tracking, and chain replay capabilities.
* **Purpose-built infrastructure** - Hydromancer's product offering is shaped by deployer requirements and designed to drive impact to your HIP-3 DEX performance. Battle-tested, mission-critical features.

</details>

<details>

<summary><strong>⚡ Market Makers &#x26; Quantitative Firms</strong></summary>

You need the fastest possible view of what's happening on Hyperliquid — orderbook updates, trades, liquidations, all of it.

**Why Hydromancer:**

* **Faster than native** — Hydromancer's [orderbook streaming](https://hydromancer.xyz/orderbook-streaming) is faster than what Hyperliquid provides natively.
* **Full market streaming** — Subscribe to orderbook-only feeds or everything happening on Hyperliquid, depending on your needs.

</details>

#### Supporting the ecosystem

Building a public good? Just getting started as an app builder? Hydromancer provides access for public goods and early-stage teams.

Please reach out to learn more at [Hydromancer for Early-Stage Teams](https://hydromancer.xyz/docs/overview/hydromancer-for-early-stage-teams). We approve 3 teams a month to the early-stage builder program.

### **Pricing**

* **Plans & tiers:** Starter, Growth, Scale, and Enterprise — see [Hydromancer Pricing](https://hydromancer.xyz/pricing) for current monthly plans and included token allowances.
* **Token costs & add-ons:** Flat-priced market-wide add-ons (never metered per call, row, message, or GB) and per-endpoint REST token costs are documented in API Token Costs & Request Weights.
* **Free historical data:** Available through Reservoir under CC BY 4.0, with no API key required.


# Hydromancer for Early-Stage Teams

Free infrastructure access for public goods and early-stage builders.

If you are building a public good or are an early-stage builder, Hydromancer offers free infrastructure access. Please reach out to learn more.

#### Public goods

* You are building a public good - for example, a dashboard, a notifications bot, or an analytics tool.
* The tool is purely informational and does not have any trading execution, ads, or monetization functionality (referral links are okay if done transparently and in moderation)

#### Builder code apps

* You are building a builder code app and plan to monetize it in the future. You want to use Hydromancer infrastructure but can't commit to a paid plan yet.
* If you provide Hydromancer with details about your app, team, and builder address, you can access full-functionality Hydromancer APIs and WebSockets.
* Hydromancer starts charging when your builder wallet address starts earning revenue from users.<br>

### **How it works**

To apply, please email <data@hydromancer.xyz> with a short description of your project, your team, and, for builder code apps, your builder address. We will get back within a week or sooner.


# REST API

API service for querying user state information from Hyperliquid. All endpoints require Bearer token authentication.

### Authentication

All API requests must include an authorization header with a Bearer token.

```
Authorization: Bearer YOUR_API_KEY
```

### Mainnet URL

```url
https://api.hydromancer.xyz
```

### Testnet URL

{% hint style="warning" %}
Everything is the same except when it's described in the docs of the specific endpoint
{% endhint %}

See [Testnet](https://hydromancer.xyz/docs/rest-api/testnet) for keys, limits and differences from mainnet.

```url
https://api-testnet.hydromancer.xyz
```

### Base Endpoint

```
POST /info
```

All requests use the same endpoint with different `type` values to specify the operation.<br>

### Error responses

<details>

<summary>Error responses</summary>

400 Bad Request

```
{
  "error": "Invalid Ethereum address: 0xinvalid"
}
```

401 Unauthorized

```
{
  "error": "Invalid API key"
}
```

502 Bad Gateway

```
{
  "error": "Timeout error"
}
```

500 Internal Server Error

```
{
  "error": "An internal error occurred"
}
```

</details>

### Opt-in structured errors

Send `X-HM-Error-Format: structured-v1` on each request to select structured errors for a supported operation. Without this header, existing responses keep their legacy format. Successful response bodies do not change.

Supported operations are `POST /auth/token`, `GET /labels/{address}`, `fundingHistory`, `fundingPayments`, `allMids`, and these 43 `/info` types:

```
meta spotMeta spotClearinghouseState openOrders exchangeStatus frontendOpenOrders
maxMarketOrderNtls vaultSummaries userVaultEquities leadingVaults extraAgents
subAccounts userFees userRateLimit spotDeployState perpDeployAuctionStatus
delegations delegatorSummary maxBuilderFee userToMultiSigSigners userRole
perpsAtOpenInterestCap validatorL1Votes marginTable perpDexs activeAssetData
webData2 webData3 userAbstraction perpAnnotation perpCategories
perpConciseAnnotations allPerpMetas perpDexStatus perpDexLimits
allBorrowLendReserveStates borrowLendReserveState borrowLendUserState
spotPairDeployAuctionStatus approvedBuilders settledOutcome
outcomeTemplates outcomeDeployerLimits
```

The response confirms selection with `X-HM-Error-Format: structured-v1`. Check this header before decoding a structured error. An authenticated request selecting an unsupported operation returns 406 with `code: "error_format_unavailable"` and no confirmation header. `outcomeMeta` remains unsupported.&#x20;

Authentication and permission checks retain their precedence. Proxy-generated responses may lack confirmation.

A selected error has this shape:

```json
{
  "error": "The node could not complete the request",
  "code": "internal",
  "correlationId": "b69e0b20-329b-4ec5-9712-bfe273319064"
}
```

A forwarded node HTTP failure retains its upstream non-2xx status, including 3xx, 429, and 503, with code `internal`. Node transport failures use 502 or 503 with code `unavailable`. Cache and enrichment failures use 500 with code `internal`.&#x20;

Selected errors redact backend bodies, URLs, and diagnostics. HTTP 304 and HEAD responses remain bodyless, so only status and headers provide evidence for those responses.

An upstream 429 with code `internal` carries no invented retry fields. Admission rate limits retain their existing rate-limit details. Selection adds `X-HM-Error-Format` to `Vary` and exposes the confirmation header to browsers without changing CORS policy.

The Python SDK selects the format per call with `await client.call_structured(name, **params)`. It checks confirmation, retains status, headers, and raw body as evidence, and decodes failures before validating successful data.&#x20;

Selected calls do not follow redirects. Missing confirmation raises `ErrorFormatUnavailable` unless the caller explicitly permits a legacy response with `allow_legacy_response=True`.&#x20;

This option never resends the request. Existing bounded status-based 429 retries still apply.

For `GET /labels/{address}`, a proven missing row returns selected 404 with `not_found`. A ClickHouse query failure returns selected 503 with `unavailable`. Both failures retain legacy 500 responses without the selector.&#x20;

Automatic HEAD requests return the same status and headers as GET with no body. `PATCH /labels/{address}` remains outside structured support and returns selected 406 without confirmation before mutation.

For `fundingPayments`, a missing, expired, or unpublished snapshot and Redis failures return selected 503 with `unavailable`, never 404. Legacy failures remain 500. Successful compressed bytes and snapshot headers are unchanged.&#x20;

Use `await snapshots.fetch_funding_payments_raw(error_format="structured-v1")` to opt in. Missing confirmation fails without a retry. `allow_legacy_response=True` instead returns raw response evidence with `downgraded=True`; it does not resend the request.


# Rate Limits and User Limits

Hydromancer's Hyperliquid REST API rate limits: per-minute weight budgets by plan (5,000 / 20,000 / 50,000) and the weight of each endpoint.

#### Rest APIs

Aggregated weight limit per minute:

| Starter | Growth | Scale  |
| ------- | ------ | ------ |
| 5000    | 20,000 | 50,000 |

Every request draws its weight from this per-minute budget, except the [windowed endpoints](#windowed-endpoints) below. Requests have a default weight of 2 points except for the following:

| Endpoint                                                                                                                                                                                                      | Weight     | Notes                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------- |
| `userPnlSummary`                                                                                                                                                                                              | 20         |                                                                                                                         |
| `userPnlLeaderboard`                                                                                                                                                                                          | 200        |                                                                                                                         |
| `userCompletedTrades`                                                                                                                                                                                         | 20         |                                                                                                                         |
| `userCompletedTradesByTime`                                                                                                                                                                                   | 20         |                                                                                                                         |
| `userFills`                                                                                                                                                                                                   | 10         |                                                                                                                         |
| `userFillsByTime`                                                                                                                                                                                             | 10         |                                                                                                                         |
| `fillsByTime`                                                                                                                                                                                                 | 10         |                                                                                                                         |
| `tradesByTime`                                                                                                                                                                                                | 10         |                                                                                                                         |
| `userTwapSliceFills`                                                                                                                                                                                          | 10         |                                                                                                                         |
| `userTwapSummaries`                                                                                                                                                                                           | 10         |                                                                                                                         |
| `userTwapStatusesByTime`                                                                                                                                                                                      | 20         |                                                                                                                         |
| `userLeverageUpdatesByTime`                                                                                                                                                                                   | 20         |                                                                                                                         |
| `userIsolatedMarginUpdatesByTime`                                                                                                                                                                             | 20         |                                                                                                                         |
| `historicalOrders`                                                                                                                                                                                            | 10         |                                                                                                                         |
| `orderStatusByOid`                                                                                                                                                                                            | 10         |                                                                                                                         |
| `userFunding`                                                                                                                                                                                                 | 10         |                                                                                                                         |
| `userNonFundingLedgerUpdates`                                                                                                                                                                                 | 10         |                                                                                                                         |
| `metaAndAssetCtxs`                                                                                                                                                                                            | 20         |                                                                                                                         |
| `candleSnapshot`                                                                                                                                                                                              | 20         |                                                                                                                         |
| `registeredOutcomes`                                                                                                                                                                                          | 20         |                                                                                                                         |
| `registeredOutcomesById`                                                                                                                                                                                      | 20         |                                                                                                                         |
| `settledOutcomes`                                                                                                                                                                                             | 20         |                                                                                                                         |
| `settledOutcomesById`                                                                                                                                                                                         | 20         |                                                                                                                         |
| `outcomeVenueStats`                                                                                                                                                                                           | 20         |                                                                                                                         |
| `marketLiquidity`                                                                                                                                                                                             | 10         |                                                                                                                         |
| `marketLiquidityHistory`                                                                                                                                                                                      | 10         |                                                                                                                         |
| `slippageHistory`                                                                                                                                                                                             | 10         |                                                                                                                         |
| `perpPriceHistoryByTime`                                                                                                                                                                                      | 10         |                                                                                                                         |
| `allPerpMetas`                                                                                                                                                                                                | 10         | Full universe and margin tables across all perp DEXes.                                                                  |
| `builderFills`                                                                                                                                                                                                | 5          |                                                                                                                         |
| `builderFillsByTime`                                                                                                                                                                                          | 5          |                                                                                                                         |
| `builderApprovedFillsByTime`                                                                                                                                                                                  | 100        | Joins the approval index against `fills`.                                                                               |
| `builderApprovedFundingByTime`                                                                                                                                                                                | 100        | Joins the approval index against `funding_events`; a full page touches a granule per user, so it is priced accordingly. |
| `builderApprovedNonFundingLedgerUpdatesByTime`                                                                                                                                                                | 100        | Joins the approval index against `ledger_events`; priced like the funding sibling.                                      |
| `builderOrdersByTime`                                                                                                                                                                                         | 5          |                                                                                                                         |
| `fundingHistory`                                                                                                                                                                                              | 5          |                                                                                                                         |
| `liquidationHistoryByTime`                                                                                                                                                                                    | 5          |                                                                                                                         |
| `liquidationBuckets`                                                                                                                                                                                          | 5          |                                                                                                                         |
| `openInterestHistory`                                                                                                                                                                                         | 5          |                                                                                                                         |
| `currentDepth`                                                                                                                                                                                                | 5          |                                                                                                                         |
| `portfolioState`                                                                                                                                                                                              | 5          |                                                                                                                         |
| `apiUsage`                                                                                                                                                                                                    | 5          |                                                                                                                         |
| `stakingEvents`                                                                                                                                                                                               | 5          |                                                                                                                         |
| `validatorAprHistory`                                                                                                                                                                                         | 5          |                                                                                                                         |
| `delegatorHistory`                                                                                                                                                                                            | 5          |                                                                                                                         |
| `delegatorRewards`                                                                                                                                                                                            | 5          |                                                                                                                         |
| `perpSnapshotTimestamp`, `spotSnapshotTimestamp`, `perpTwapSnapshotTimestamp`, `spotTwapSnapshotTimestamp`, `accountValueSnapshotTimestamp`, `fundingPaymentTimestamp`, `registeredOutcomesSnapshotTimestamp` | 1          |                                                                                                                         |
| `batchClearinghouseStates`                                                                                                                                                                                    | 2 per user | Max 100 points. Up to 1000 users (100 with `ALL_DEXES`). Cost multiplied by number of dexes with `ALL_DEXES`.           |
| `batchPortfolioStates`                                                                                                                                                                                        | 3 per user | Max 200 points. Up to 500 users (100 with `ALL_DEXES`). Cost multiplied by number of dexes with `ALL_DEXES`.            |
| `batchPerpAnnotations`                                                                                                                                                                                        | 1 per user | Max 25 points.                                                                                                          |

#### Windowed endpoints

These endpoints have their own per-endpoint limit and do **not** draw from the per-minute budget above:

| Endpoint                                                                                                                                                                     | Limit                      |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| `perpSnapshots`, `spotSnapshots`, `perpTwapSnapshots`, `spotTwapSnapshots`, `accountValueSnapshots`, `fundingPayments`, `registeredOutcomesSnapshot`, `globalStakingSummary` | 5 requests per 10 minutes  |
| `l4Book`                                                                                                                                                                     | 20 requests per 5 minutes  |
| `tpslBook`                                                                                                                                                                   | 10 requests per 5 minutes  |
| `walletLabels` (add-on)                                                                                                                                                      | 10 requests per 10 minutes |
| `l2Book`                                                                                                                                                                     | 60 requests per 5 minutes  |
| `l2BookDiffSnapshot`                                                                                                                                                         | 300 requests per 5 minutes |

## Handling rate limits

Responses admitted by the REST limiter, including downstream errors, and its 429 rejections include:

| Header                  | Meaning                                                                                                                                             |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-RateLimit-Limit`     | Governing bucket capacity in weight points.                                                                                                         |
| `X-RateLimit-Remaining` | Points remaining immediately after admission; rejection consumes no points.                                                                         |
| `X-RateLimit-Reset`     | Whole seconds, rounded up, until all usage recorded in the admission snapshot expires. Handler elapsed time is deducted; an empty bucket reports 0. |
| `X-RateLimit-Cost`      | Weight consumed by this request; 0 on limiter rejection. This is independent of billed tokens.                                                      |
| `Retry-After`           | On 429 only: whole seconds, rounded up, until enough weight expires for this request.                                                               |

Windowed endpoints report their own weighted bucket, rather than the shared tier budget. For example, `exportLabels` costs 20 points and has a 100-point capacity: five requests per minute.

The limiter uses a sliding window: capacity returns as individual requests expire. `Reset` describes full restoration and can be longer than `Retry-After`. Remaining is an admission snapshot, not a reservation; concurrent requests can invalidate either estimate. State belongs to the enforcing process and can reset on restart.

The budget headers are omitted for keys permitted to bypass enforcement. Authentication, permission or JSON errors before the limiter, health checks and preflights have no budget snapshot. Missing headers alone do not imply unlimited access. `Access-Control-Expose-Headers` exposes these names for browser clients already permitted by the origin's CORS policy.

A 429 preserves the existing `error` string and adds retry metadata:

```json
{
  "error": "Rate limit exceeded. You have 8 points remaining. This request requires more points.",
  "code": "rate_limited",
  "message": "Rate limit exceeded. You have 8 points remaining. This request requires more points.",
  "retryAfterSecs": 12,
  "remaining": 8,
  "required": 20,
  "correlationId": "AB12CD34"
}
```

Honor `Retry-After` before retrying, optionally adding positive jitter. If unavailable, use the body's `retryAfterSecs`; otherwise use bounded exponential backoff with jitter. Limit attempts and total elapsed time to avoid retry storms. Do not retry 400s unchanged: oversized batches and requests whose weight exceeds total capacity must be corrected.

The SDK retries HTTP 429 by default, with at most three retries (four total attempts) and a 90-second total HTTP call budget. All REST, snapshot, L2/L4, TP/SL, asset-context and perp-price clients accept `max_rate_limit_retries` and `http_call_budget_seconds`; `OrderbookStream` forwards the same options. Set `max_rate_limit_retries=0` to disable retries. Longer-window customers can increase the call budget.

The SDK prefers a valid `Retry-After` integer or HTTP date, then body `retryAfterSecs`, otherwise exponential backoff starting at one second and capped at 30 seconds. Server guidance receives up to one second of positive jitter and is never shortened to that fallback ceiling. A delay that cannot fit the remaining budget raises immediately. Attempts and waits share the same budget, including injected sessions and per-request timeouts. Responses are released before waiting; cancellation propagates.

Exhausted HTTP `RateLimitError` exposes `http_status`, `retry_after_secs`, `remaining`, `required`, `limit`, `reset_secs`, `cost`, and `correlation_id` when available. Only exhausted HTTP 429s escape streaming `run()`/bootstrap instead of restarting the HTTP retry cycle. Other errors, including other HTTP 4xx responses and malformed successful snapshots, retain their previous reconnect behavior. Other HTTP errors and transport failures are not automatically retried by the HTTP helper. WebSocket reconnect options, including `max_retries=0` meaning unlimited WebSocket reconnects, retain their existing meaning.


# API Usage

Get your Hydromancer API usage statistics broken down by day and request type.

{% hint style="info" %}
This endpoint returns your Hydromancer API usage.
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"apiUsage"</code></td></tr><tr><td><code>days</code></td><td>integer</td><td>Number of days to look back (optional, default 30)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "apiUsage",
    "days": 7
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'apiUsage',
        'days': 7
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'apiUsage',
        days: 7
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                    | Type   | Description                                                                                                                                                                                                                                  |
| ------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `day`                    | string | Date in `YYYY-MM-DD` format                                                                                                                                                                                                                  |
| `request_type`           | string | Endpoint or request type name                                                                                                                                                                                                                |
| `total_requests`         | int    | Total number of requests                                                                                                                                                                                                                     |
| `success_requests`       | int    | Number of successful requests                                                                                                                                                                                                                |
| `failure_requests`       | int    | Number of failed requests                                                                                                                                                                                                                    |
| `avg_processing_time_ms` | float  | Average processing time in milliseconds                                                                                                                                                                                                      |
| `tokens_consumed`        | int    | Billable tokens consumed that day for this request type, rounded down to a whole token. `candleSnapshot` is reported at its current price (0.1 tokens per request) for every day shown, including days before its price change on 2026-10-22 |

<details>

<summary>Response</summary>

```json
[
    {
        "day": "2026-03-16",
        "request_type": "allMids",
        "total_requests": 1,
        "success_requests": 1,
        "failure_requests": 0,
        "avg_processing_time_ms": 2.0,
        "tokens_consumed": 1
    },
    {
        "day": "2026-03-16",
        "request_type": "delegations",
        "total_requests": 5,
        "success_requests": 5,
        "failure_requests": 0,
        "avg_processing_time_ms": 0.0,
        "tokens_consumed": 5
    }
]
```

</details>


# Candlesticks

Get Hyperliquid OHLCV candles for any coin and interval, including 1s, 15s and 30s candles and history older than the native API’s last 5,000 candles.

{% hint style="info" %}
**Hydromancer offers 1s, 15s and 30s candles, which Hyperliquid’s API doesn’t have. It also keeps older history: Hyperliquid’s own candleSnapshot only returns the most recent 5,000 candles per interval.**
{% endhint %}

### Overview

Returns OHLCV candle data for a given coin and interval. Uses the `candleSnapshot` request type, with an API key.

Returns OHLCV candle data for a given coin and interval, using the `candleSnapshot` request type.

### Request

* **Endpoint**: `POST /info`

```json
{
    "type": "candleSnapshot",
    "req": {
        "coin": "BTC",
        "interval": "1m",
        "startTime": 1700000000000,
        "endTime": 1700003600000
    }
}
```

| Field       | Type   | Required | Description                                                                        |
| ----------- | ------ | -------- | ---------------------------------------------------------------------------------- |
| `coin`      | string | Yes      | Coin name. For HIP-3 assets, prefix with dex name (e.g. `"hyna:ETH"`)              |
| `interval`  | string | Yes      | Candle interval (see valid intervals below)                                        |
| `startTime` | number | Yes      | Start time in milliseconds since epoch (inclusive)                                 |
| `endTime`   | number | Yes      | End time in milliseconds since epoch (exclusive). Must be greater than `startTime` |
| `limit`     | number | No       | Maximum number of candles to return. Default and max: 5000                         |

#### Valid intervals

| Interval | Duration                 |
| -------- | ------------------------ |
| `1s`     | 1 second                 |
| `15s`    | 15 seconds               |
| `30s`    | 30 seconds               |
| `1m`     | 1 minute                 |
| `3m`     | 3 minutes                |
| `5m`     | 5 minutes                |
| `15m`    | 15 minutes               |
| `30m`    | 30 minutes               |
| `1h`     | 1 hour                   |
| `2h`     | 2 hours                  |
| `4h`     | 4 hours                  |
| `8h`     | 8 hours                  |
| `12h`    | 12 hours                 |
| `1d`     | 1 day                    |
| `3d`     | 3 days                   |
| `1w`     | 1 week (Monday-aligned)  |
| `1M`     | 1 month (calendar month) |

{% hint style="info" %}
`1s`, `15s`, and `30s` candles are Hydromancer additions — they are not available on the native Hyperliquid API.
{% endhint %}

### Response

Returns a JSON array of candle objects sorted by time ascending. Maximum 5000 candles per request.

```json
[
    {
        "s": "BTC",
        "i": "1m",
        "t": 1700000040000,
        "T": 1700000099999,
        "o": "45000.00",
        "h": "45100.50",
        "l": "44980.00",
        "c": "45050.25",
        "v": "123.45",
        "q": "5560125.00",
        "n": 312,
        "x": true
    }
]
```

| Field | Type           | Description                                                                         |
| ----- | -------------- | ----------------------------------------------------------------------------------- |
| `s`   | string         | Coin name                                                                           |
| `i`   | string         | Interval string                                                                     |
| `t`   | number         | Candle open time (milliseconds, interval start)                                     |
| `T`   | number         | Candle close time (milliseconds, interval end)                                      |
| `o`   | string         | Open price                                                                          |
| `h`   | string         | High price                                                                          |
| `l`   | string         | Low price                                                                           |
| `c`   | string         | Close (latest) price                                                                |
| `v`   | string         | Volume in base asset                                                                |
| `q`   | string \| null | Quote volume (notional value, sum of price \* size). May be `null` — see note below |
| `n`   | number         | Number of trades                                                                    |
| `x`   | boolean        | `true` if the candle is closed/finalized, `false` if still open                     |

{% hint style="info" %}
**Differences from Hyperliquid's response:** Hydromancer adds `q` (quote volume) and `x` (closed flag). Field names (`s`, `i`, `t`, `T`, `o`, `h`, `l`, `c`, `v`, `n`) are identical to Hyperliquid's format.
{% endhint %}

{% hint style="warning" %}
**`q` may be `null` for candles before 2025-08-01.** Pre-Aug-2025 history was imported from Hyperliquid's `candleSnapshot` API, which does not expose quote volume. Rather than emit a misleading sentinel zero, those buckets are returned as `null`. This propagates to aggregated intervals (`3d`, `1w`, `1M`) whose window includes any pre-cutoff day. From 2025-08-01 onward, `q` is always a string. Clients parsing `q` must handle the `null` branch (e.g. `parseFloat(c.q ?? "0")` or skipping the field entirely for older buckets).
{% endhint %}

### Rate limits

20 points per request (see [rate limits](https://hydromancer.xyz/docs/rest-api/rate-limits-and-user-limits)).

### Examples

{% tabs %}
{% tab title="Python" %}

```python
import requests
import os

api_key = os.environ["HYDROMANCER_API_KEY"]
base_url = os.getenv("HYDROMANCER_API_URL", "https://api.hydromancer.xyz")

resp = requests.post(
    f"{base_url}/info",
    json={
        "type": "candleSnapshot",
        "req": {
            "coin": "BTC",
            "interval": "1h",
            "startTime": 1700000000000,
            "endTime": 1700036000000,
        },
    },
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    },
)
candles = resp.json()

for c in candles:
    status = "closed" if c["x"] else "open"
    print(f"{c['t']}  O={c['o']}  H={c['h']}  L={c['l']}  C={c['c']}  V={c['v']}  trades={c['n']}  [{status}]")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

const apiKey = process.env.HYDROMANCER_API_KEY;
const baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';

async function getCandles() {
    const resp = await axios.post(
        `${baseUrl}/info`,
        {
            type: 'candleSnapshot',
            req: {
                coin: 'BTC',
                interval: '1h',
                startTime: 1700000000000,
                endTime: 1700036000000,
            },
        },
        {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`,
            },
        }
    );

    for (const c of resp.data) {
        const status = c.x ? 'closed' : 'open';
        console.log(`${c.t}  O=${c.o}  H=${c.h}  L=${c.l}  C=${c.c}  V=${c.v}  trades=${c.n}  [${status}]`);
    }
}

getCandles().catch(console.error);
```

{% endtab %}
{% endtabs %}

### Common errors

| Error                                    | Cause                                       |
| ---------------------------------------- | ------------------------------------------- |
| `Invalid interval`                       | Interval string not in the valid list above |
| `endTime must be greater than startTime` | `endTime <= startTime`                      |
| `Missing required field: coin`           | `coin` field not provided                   |


# Subaccounts

Get Hyperliquid subaccount information for a user.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"subAccounts"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "subAccounts",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'subAccounts',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'subAccounts',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field         | Type   | Description                                          |
| ------------- | ------ | ---------------------------------------------------- |
| `role`        | string | Account role (e.g. `"subAccount"`)                   |
| `data`        | object | Role-specific data                                   |
| `data.master` | string | Master account address (when role is `"subAccount"`) |

<details>

<summary>Response</summary>

```json
{
    "role": "subAccount",
    "data": {
        "master": "0x..."
    }
}
```

</details>


# Testnet

Use Hydromancer on Hyperliquid testnet: URLs, API keys, limits and what's different from mainnet.

Hydromancer serves Hyperliquid testnet data on its own host, so you can build and test against testnet before you switch to mainnet.&#x20;

Requests, responses and errors work the same way as on mainnet.

#### **URLs**

|           | Mainnet                            | Testnet                                    |
| --------- | ---------------------------------- | ------------------------------------------ |
| REST      | <https://api.hydromancer.xyz/info> | <https://api-testnet.hydromancer.xyz/info> |
| WebSocket | wss\://api.hydromancer.xyz/ws      | wss\://api-testnet.hydromancer.xyz/ws      |

#### **API key**

Testnet uses its own API key. A mainnet key on the testnet host, or a testnet key on the mainnet host, returns `401 {"error":"Invalid API key"}`.&#x20;

{% hint style="info" %}
To get a testnet key, please reach out to us.
{% endhint %}

Authentication is the same as mainnet: `Authorization: Bearer <testnet key>` for REST and `?token=<testnet key>` for WebSocket.

#### **Testnet Rate limits**

Testnet has the same limits as your plan, counted separately: testnet requests don't use up your mainnet per-minute limit, and mainnet requests don't use up testnet's. Testnet usage does count toward your plan's monthly allowance.&#x20;

Check the `x-ratelimit-limit`, `x-ratelimit-remaining` and `x-ratelimit-cost` headers on any response; they work the same way as on mainnet.

#### **What is different on testnet**

* **Data comes from Hyperliquid testnet.** Markets, prices, asset indexes and addresses differ from mainnet, so don't reuse mainnet addresses or asset IDs in testnet requests.
* **History can have gaps.** Hyperliquid changes its testnet often, so testnet history may be missing some periods.
* **Some data needs time to build up.** A few requests that summarize the market over time, such as `currentDepth`, can return "not yet available" on testnet.

#### **Moving to mainnet**

Change the host to `api.hydromancer.xyz` and use your mainnet key. Request bodies stay the same, but update any testnet addresses and asset IDs.

**Related**

* [Hyperliquid testnet guide](https://hydromancer.xyz/blog/hyperliquid-testnet): faucets, API wallets, and what breaks when you move to mainnet.


# User position data

Endpoints for querying Hyperliquid perp and spot account summaries, asset data and leverage settings for one or many users.

#### **Retrieving user's&#x20;**<mark style="background-color:green;">**perpetual accounts**</mark>**&#x20;summary**

{% content-ref url="/pages/8GtMwfBKVkjt1oF8NO2J" %}
[clearinghouseState](https://hydromancer.xyz/docs/rest-api/user-position-data/clearinghousestate)
{% endcontent-ref %}

#### **Retrieving multiple users'&#x20;**<mark style="background-color:green;">**perpetual accounts**</mark>**&#x20;summary**

{% content-ref url="/pages/QoZnodKzgRSvYcIl0ycA" %}
[batchClearinghouseStates](https://hydromancer.xyz/docs/rest-api/user-position-data/batchclearinghousestates)
{% endcontent-ref %}

#### **Retrieving user's asset data and leverage settings**

Includes available trade size, leverage on a given asset, and mark price.

{% content-ref url="/pages/y1C2hZW72aGfl9UyJrsQ" %}
[activeAssetData](https://hydromancer.xyz/docs/rest-api/user-position-data/activeassetdata)
{% endcontent-ref %}

#### **Retrieving user's&#x20;**<mark style="background-color:orange;">**spot**</mark>**&#x20;summary**

{% content-ref url="/pages/UhcfGYdqlEc3AuwVuhNB" %}
[spotClearinghouseState](https://hydromancer.xyz/docs/rest-api/user-position-data/spotclearinghousestate)
{% endcontent-ref %}

#### **Retrieving user's account abstraction mode**

{% content-ref url="/pages/inHz3xpIMzCp2VGWeIuK" %}
[userAbstraction](https://hydromancer.xyz/docs/rest-api/user-position-data/userabstraction)
{% endcontent-ref %}

#### **Retrieving user's full portfolio state (perp + spot + abstraction mode)**

{% content-ref url="/pages/NkGZmiqskyXzzFxtk6Ws" %}
[portfolioState](https://hydromancer.xyz/docs/rest-api/user-position-data/portfoliostate)
{% endcontent-ref %}

#### **Retrieving multiple users' full portfolio states (perp + spot + abstraction mode)**

{% content-ref url="/pages/gcgNOVuR9YI3Rk9lgt8z" %}
[batchPortfolioStates](https://hydromancer.xyz/docs/rest-api/user-position-data/batchportfoliostates)
{% endcontent-ref %}

#### **Retrieve web data**

{% content-ref url="/pages/HG2Lubojmc9FYNAtKwJI" %}
[webData2](https://hydromancer.xyz/docs/rest-api/user-position-data/webdata2)
{% endcontent-ref %}


# clearinghouseState

Get a Hyperliquid user’s complete clearinghouse state: positions, margin and account value.

## POST Request

| Field  | Type   | Description                                                                                                                                                      |
| ------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | string | Must be `"clearinghouseState"`                                                                                                                                   |
| `user` | string | Ethereum address (0x-prefixed, 42 characters)                                                                                                                    |
| `dex`  | string | Perp DEX name. Defaults to empty string (native DEX). Use `"ALL_DEXES"` to fetch clearinghouse state across all dexes (native + all HIP-3 dexes) in one request. |

### Usage

If ALL\_DEXES is not passed one call will consume 1 point.

When passing ALL\_DEXES as dex the points consumed is the number of dexes that are operational. Therefore, you should be mindful about if you really need to this.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "clearinghouseState",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'clearinghouseState',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'clearinghouseState',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
{
  "marginSummary": {
    "accountValue": "50000.00",
    "totalMarginUsed": "10000.00",
    "totalNtlPos": "25000.00",
    "totalRawUsd": "45000.00",
    "withdrawable": "15000.00"
  },
  "crossMarginSummary": {
    "accountValue": "50000.00",
    "totalMarginUsed": "10000.00",
    "totalNtlPos": "25000.00",
    "totalRawUsd": "45000.00",
    "withdrawable": "15000.00"
  },
  "assetPositions": [
    {
      "position": {
        "coin": "BTC",
        "entryPx": "45000.00",
        "leverage": {
          "type": "cross",
          "value": 5
        },
        "liquidationPx": "40000.00",
        "marginUsed": "5000.00",
        "maxTradeSzs": ["100000.00", "100000.00"],
        "positionValue": "50000.00",
        "returnOnEquity": "0.10",
        "szi": "1.0",
        "unrealizedPnl": "500.00"
      },
      "type": "oneWay"
    }
  ],
  "time": 1234567890123
}
```

</details>

<details>

<summary>Response ALL_DEXES</summary>

```json
{
    "native": {
      "marginSummary": {
        "accountValue": "50000.00",
        "totalMarginUsed": "10000.00",
        "totalNtlPos": "25000.00",
        "totalRawUsd": "45000.00",
        "withdrawable": "15000.00"
      },
      "crossMarginSummary": {
        "accountValue": "50000.00",
        "totalMarginUsed": "10000.00",
        "totalNtlPos": "25000.00",
        "totalRawUsd": "45000.00",
        "withdrawable": "15000.00"
      },
      "assetPositions": [],
      "time": 1234567890123
    },
    "xyz": {
      "marginSummary": {
        "accountValue": "10000.00",
        "totalMarginUsed": "2000.00",
        "totalNtlPos": "5000.00",
        "totalRawUsd": "9000.00",
        "withdrawable": "3000.00"
      },
      "crossMarginSummary": {
        "accountValue": "10000.00",
        "totalMarginUsed": "2000.00",
        "totalNtlPos": "5000.00",
        "totalRawUsd": "9000.00",
        "withdrawable": "3000.00"
      },
      "assetPositions": [],
      "time": 1234567890123
    }, 
    ....
  }
```

</details>


# batchClearinghouseStates

Get Hyperliquid clearinghouse states for multiple users in a single request.

`batchClearinghouseStates` returns the current perp positions and account state of multiple wallets in a single request.

Each wallet's result has the same shape as [clearinghouseState](https://docs.hydromancer.xyz/readme/rest-api/user-position-data/clearinghousestate), so you can reuse the same parsing code.

{% hint style="info" %}
💧**New endpoint - this endpoint is not part of the original Hyperliquid API. Hydromancer added it for builder convenience.**
{% endhint %}

Why is `batchClearinghouseStates` introduced?

On the official Hyperliquid API, `clearinghouseState` covers one wallet per request and each request has a weight of 2, against a budget of 1,200 per minute per IP.

Checking 1,000 wallets would take 1,000 requests and 2,000 weight, more than a whole minute's budget. With `batchClearinghouseStates` it's 1 request and 100 weight.

## Structured errors and partial results

Send `X-HM-Error-Format: structured-v1` to select structured errors. Application responses echo this header. Errors retain `error` and add `code` and `correlationId`. Selector-free behavior is unchanged.

Mixed wallet successes and failures remain HTTP 200. The response retains the snake\_case `successful_states` and `failed_wallets` arrays. Inspect `failed_wallets` before treating the request as complete. Retry failed wallets separately to avoid repeating successful members. Existing manager failure reporting is retained and does not guarantee a complete inventory of component failures.

The Python SDK supports `RestClient.call_structured` for this mode. Its validated result exposes both arrays and does not automatically replay successful wallets. A confirmed 503 raises a typed error and does not resend as legacy, including when `allow_legacy_response=True`.

## POST Request

<table><thead><tr><th width="163.06915283203125">Field</th><th width="135.80908203125">Type</th><th width="471.56585693359375">Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"batchClearinghouseStates"</code></td></tr><tr><td><code>users</code></td><td>array</td><td>Array of Ethereum addresses</td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name. Defaults to empty string (native DEX). Use <code>"ALL_DEXES"</code> to fetch clearinghouse state across all dexes (native + all HIP-3 dexes) in one request.</td></tr></tbody></table>

### Limits

You can query 1000 users at once. Note that with the ALL\_DEXES field passed that limit is 100 users.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "batchClearinghouseStates",
    "users": [
      "0x0000000000000000000000000000000000000001",
      "0x0000000000000000000000000000000000000002"
    ]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'batchClearinghouseStates',
        'users': [
            '0x0000000000000000000000000000000000000001',
            '0x0000000000000000000000000000000000000002'
        ]
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'batchClearinghouseStates',
        users: [
            '0x0000000000000000000000000000000000000001',
            '0x0000000000000000000000000000000000000002'
        ]
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                        | Type   | Description                                                                            |
| -------------------------------------------- | ------ | -------------------------------------------------------------------------------------- |
| `successful_states`                          | array  | Array of `[address, clearinghouseState]` tuples                                        |
| `successful_states[n][0]`                    | string | User address                                                                           |
| `successful_states[n][1].marginSummary`      | object | Margin summary (accountValue, totalMarginUsed, totalNtlPos, totalRawUsd, withdrawable) |
| `successful_states[n][1].crossMarginSummary` | object | Cross margin summary (same fields as marginSummary)                                    |
| `successful_states[n][1].assetPositions`     | array  | Array of position objects                                                              |
| `successful_states[n][1].time`               | int    | Timestamp in milliseconds                                                              |
| `failed_wallets`                             | array  | Array of addresses that failed to fetch                                                |

<details>

<summary>Response</summary>

```json
{
  "successful_states": [
    [
      "0x0000000000000000000000000000000000000001",
      {
        "marginSummary": {
          "accountValue": "50000.00",
          "totalMarginUsed": "10000.00",
          "totalNtlPos": "25000.00",
          "totalRawUsd": "45000.00",
          "withdrawable": "15000.00"
        },
        "crossMarginSummary": {
          "accountValue": "50000.00",
          "totalMarginUsed": "10000.00",
          "totalNtlPos": "25000.00",
          "totalRawUsd": "45000.00",
          "withdrawable": "15000.00"
        },
        "assetPositions": [
          {
            "position": {
              "coin": "BTC",
              "entryPx": "45000.00",
              "leverage": {
                "type": "cross",
                "value": 5
              },
              "liquidationPx": "40000.00",
              "marginUsed": "5000.00",
              "maxTradeSzs": ["100000.00", "100000.00"],
              "positionValue": "50000.00",
              "returnOnEquity": "0.10",
              "szi": "1.0",
              "unrealizedPnl": "500.00"
            },
            "type": "oneWay"
          }
        ],
        "time": 1234567890123
      }
    ]
  ],
  "failed_wallets": [
    "0x0000000000000000000000000000000000000003"
  ]
}
```

</details>

<details>

<summary>Response ALL_DEXES</summary>

```json
{
    "successful_states": [
      [
        "0x0000000000000000000000000000000000000001",
        {
          "native": {
            "marginSummary": {
              "accountValue": "50000.00",
              "totalMarginUsed": "10000.00",
              "totalNtlPos": "25000.00",
              "totalRawUsd": "45000.00",
              "withdrawable": "15000.00"
            },
            "crossMarginSummary": {
              "accountValue": "50000.00",
              "totalMarginUsed": "10000.00",
              "totalNtlPos": "25000.00",
              "totalRawUsd": "45000.00",
              "withdrawable": "15000.00"
            },
            "assetPositions": [],
            "time": 1234567890123
          },
          "xyz": {
            "marginSummary": {
              "accountValue": "10000.00",
              "totalMarginUsed": "2000.00",
              "totalNtlPos": "5000.00",
              "totalRawUsd": "9000.00",
              "withdrawable": "3000.00"
            },
            "crossMarginSummary": {
              "accountValue": "10000.00",
              "totalMarginUsed": "2000.00",
              "totalNtlPos": "5000.00",
              "totalRawUsd": "9000.00",
              "withdrawable": "3000.00"
            },
            "assetPositions": [],
            "time": 1234567890123
          },
          ..
        }
      ]
    ],
    "failed_wallets": []
  }
```

</details>


# portfolioState

Get a Hyperliquid user's clearinghouse state, spot clearinghouse state and account abstraction mode in one request.

To see one wallet's perpetual positions, spot balances and account mode on Hyperliquid, use Hydromancer's `portfolioState` endpoint. It returns all three in one request.

{% hint style="info" %}

#### New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.

{% endhint %}

How is it different from `clearinghouseState`?

* `clearinghouseState`: "Show me this wallet's perp positions and margin."
* `portfolioState`: "Show me its perp positions, spot balances and account mode together."

This matters for unified account and portfolio margin wallets: their money sits in the spot balances, so `clearinghouseState` alone shows only part of it, or `0.0` if the wallet has no open positions.

## POST Request

| Field  | Type   | Description                                                                                                                                                         |
| ------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | string | Must be `"portfolioState"`                                                                                                                                          |
| `user` | string | Ethereum address (0x-prefixed, 42 characters)                                                                                                                       |
| `dex`  | string | (Optional) Perp DEX name. Omit for native DEX (default). Use `"ALL_DEXES"` to fetch clearinghouse state across all dexes (native + all HIP-3 dexes) in one request. |

### Usage

This endpoint combines three calls into one:

* `clearinghouseState` - perp positions and margin
* `spotClearinghouseState` - spot balances
* `userAbstraction` - account abstraction mode

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "portfolioState",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'portfolioState',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'portfolioState',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                         | Type   | Description                                                                        |
| --------------------------------------------- | ------ | ---------------------------------------------------------------------------------- |
| `clearinghouseState`                          | object | Perp clearinghouse state (marginSummary, crossMarginSummary, assetPositions, time) |
| `spotClearinghouseState`                      | object | Spot clearinghouse state containing balances array                                 |
| `spotClearinghouseState.balances[n].coin`     | string | Coin symbol                                                                        |
| `spotClearinghouseState.balances[n].token`    | int    | Token index                                                                        |
| `spotClearinghouseState.balances[n].total`    | string | Total balance                                                                      |
| `spotClearinghouseState.balances[n].hold`     | string | Amount on hold                                                                     |
| `spotClearinghouseState.balances[n].entryNtl` | string | Entry notional                                                                     |
| `userAbstraction`                             | string | Account abstraction mode (see values below)                                        |

<details>

<summary>Response</summary>

```json
{
  "clearinghouseState": {
    "marginSummary": {..},
    "crossMarginSummary": {..},
    "assetPositions": [..],
    "time": 1234567890123
  },
  "spotClearinghouseState": {
    "balances": [
      {
        "coin": "USDC",
        "token": 0,
        "total": "0.02221591",
        "hold": "0.0",
        "entryNtl": "0.0"
      }
    ]
  },
  "userAbstraction": "unifiedAccount"
}
```

</details>

<details>

<summary>Response ALL_DEXES</summary>

```json
{
  "clearinghouseState": {
    "native": {
      "marginSummary": {..},
      "crossMarginSummary": {..},
      "assetPositions": [..],
      "time": 1234567890123
    },
    "xyz": {
      "marginSummary": {..},
      "crossMarginSummary": {..},
      "assetPositions": [..],
      "time": 1234567890123
    }
  },
  "spotClearinghouseState": {
    "balances": [
      {
        "coin": "USDC",
        "token": 0,
        "total": "0.02221591",
        "hold": "0.0",
        "entryNtl": "0.0"
      }
    ]
  },
  "userAbstraction": "unifiedAccount"
}
```

</details>

<details>

<summary>userAbstraction values</summary>

The user's account abstraction mode. Possible values:

| Value               | Description                                                                                                   |
| ------------------- | ------------------------------------------------------------------------------------------------------------- |
| `"unifiedAccount"`  | Unified account mode - single balance per asset across all DEXes, all cross margin positions share collateral |
| `"portfolioMargin"` | Portfolio margin mode - single portfolio unifying eligible assets with borrowing/LTV                          |
| `"disabled"`        | Abstraction disabled - separate perp and spot balances                                                        |
| `"default"`         | Default mode                                                                                                  |
| `"dexAbstraction"`  | DEX abstraction mode (legacy, being discontinued)                                                             |

</details>


# batchPortfolioStates

Get Hyperliquid perp and spot clearinghouse states for multiple users in a single request.

`batchPortfolioStates` is the multi-wallet version of [portfolioState](https://docs.hydromancer.xyz/readme/rest-api/user-position-data/portfoliostate). It returns perp positions, spot balances and account mode for many wallets in one request, instead of one wallet at a time.

**Typical use:** a copy-trading leaderboard or portfolio dashboard that shows each wallet's full account, including spot balances for unified account and portfolio margin users.

{% hint style="info" %}

#### New endpoint: This endpoint is not a part of original Hyperliquid API and is added by Hydromancer for builder convenience.

{% endhint %}

## Structured errors and partial results

Send `X-HM-Error-Format: structured-v1` to select structured errors. Application responses echo this header. Errors retain `error` and add `code` and `correlationId`. Selector-free behavior is unchanged.

Mixed wallet successes and failures remain HTTP 200. The response retains the snake\_case `successful_states` and `failed_wallets` arrays. Inspect `failed_wallets` before treating the request as complete. Retry failed wallets separately to avoid repeating successful members. Existing manager failure reporting is retained and does not guarantee a complete inventory of component failures.

The Python SDK supports `RestClient.call_structured` for this mode. Its validated result exposes both arrays and does not automatically replay successful wallets. A confirmed 503 raises a typed error and does not resend as legacy, including when `allow_legacy_response=True`.

## POST Request

<table><thead><tr><th width="163.06915283203125">Field</th><th width="135.80908203125">Type</th><th width="471.56585693359375">Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"batchPortfolioStates"</code></td></tr><tr><td><code>users</code></td><td>array</td><td>Array of Ethereum addresses</td></tr><tr><td><code>dex</code></td><td>string</td><td>(Optional) Perp DEX name. Omit for native DEX (default). Use a specific dex name (e.g., <code>"xyz"</code>) to fetch that dex only, or <code>"ALL_DEXES"</code> to fetch clearinghouse state across all dexes (native + all HIP-3 dexes) in one request.</td></tr></tbody></table>

### Limits

You can query 500 users at once. Note that with the ALL\_DEXES field passed that limit is 100 users.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "batchPortfolioStates",
    "users": [
      "0x0000000000000000000000000000000000000001",
      "0x0000000000000000000000000000000000000002"
    ]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'batchPortfolioStates',
        'users': [
            '0x0000000000000000000000000000000000000001',
            '0x0000000000000000000000000000000000000002'
        ]
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'batchPortfolioStates',
        users: [
            '0x0000000000000000000000000000000000000001',
            '0x0000000000000000000000000000000000000002'
        ]
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                            | Type   | Description                                                                        |
| ------------------------------------------------ | ------ | ---------------------------------------------------------------------------------- |
| `successful_states`                              | array  | Array of `[address, portfolioState]` tuples                                        |
| `successful_states[n][0]`                        | string | User address                                                                       |
| `successful_states[n][1].clearinghouseState`     | object | Perp clearinghouse state (marginSummary, crossMarginSummary, assetPositions, time) |
| `successful_states[n][1].spotClearinghouseState` | object | Spot clearinghouse state containing balances array                                 |
| `successful_states[n][1].userAbstraction`        | string | Account abstraction mode                                                           |
| `failed_wallets`                                 | array  | Array of addresses that failed to fetch                                            |

<details>

<summary>Response</summary>

```json
{
  "successful_states": [
    [
      "0x0000000000000000000000000000000000000001",
      {
        "clearinghouseState": {
          "marginSummary": {..},
          "crossMarginSummary": {..},
          "assetPositions": [..],
          "time": 1234567890123
        },
        "spotClearinghouseState": {
          "balances": [
            {
              "coin": "USDC",
              "token": 0,
              "total": "0.02221591",
              "hold": "0.0",
              "entryNtl": "0.0"
            }
          ]
        },
        "userAbstraction": "unifiedAccount"
      }
    ]
  ],
  "failed_wallets": [
    "0x0000000000000000000000000000000000000003"
  ]
}
```

</details>

<details>

<summary>Response ALL_DEXES</summary>

```json
{
  "successful_states": [
    [
      "0x0000000000000000000000000000000000000001",
      {
        "clearinghouseState": {
          "native": {
            "marginSummary": {..},
            "crossMarginSummary": {..},
            "assetPositions": [..],
            "time": 1234567890123
          },
          "xyz": {
            "marginSummary": {..},
            "crossMarginSummary": {..},
            "assetPositions": [..],
            "time": 1234567890123
          }
        },
        "spotClearinghouseState": {
          "balances": [
            {
              "coin": "USDC",
              "token": 0,
              "total": "0.02221591",
              "hold": "0.0",
              "entryNtl": "0.0"
            }
          ]
        },
        "userAbstraction": "unifiedAccount"
      }
    ]
  ],
  "failed_wallets": []
}
```

</details>

<details>

<summary>userAbstraction values</summary>

The user's account abstraction mode. Possible values:

| Value               | Description                                                                                                   |
| ------------------- | ------------------------------------------------------------------------------------------------------------- |
| `"unifiedAccount"`  | Unified account mode - single balance per asset across all DEXes, all cross margin positions share collateral |
| `"portfolioMargin"` | Portfolio margin mode - single portfolio unifying eligible assets with borrowing/LTV                          |
| `"disabled"`        | Abstraction disabled - separate perp and spot balances                                                        |
| `"default"`         | Default mode                                                                                                  |
| `"dexAbstraction"`  | DEX abstraction mode (legacy, being discontinued)                                                             |

</details>


# activeAssetData

Get Hyperliquid asset data for a specific user and coin.

`activeAssetData` gives you a wallet's trading settings and capacity for one coin in a single API request: its leverage, the largest order it can place, and the margin available.

It works for main perps and HIP-3 markets (e.g. `xyz:XYZ100`).

## POST Request

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"activeAssetData"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>coin</code></td><td>string</td><td>symbol e.g. "BTC"</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "activeAssetData",
    "user": "0x0000000000000000000000000000000000000000",
    "coin": "BTC"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'activeAssetData',
        'user': '0x0000000000000000000000000000000000000000',
        'coin': 'BTC'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'activeAssetData',
        user: '0x0000000000000000000000000000000000000000',
        coin: 'BTC'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field              | Type           | Description                               |
| ------------------ | -------------- | ----------------------------------------- |
| `user`             | string         | User address                              |
| `coin`             | string         | Coin symbol                               |
| `leverage.type`    | string         | Leverage type (`"cross"` or `"isolated"`) |
| `leverage.value`   | int            | Leverage value                            |
| `leverage.rawUsd`  | string \| null | Raw USD margin (only present if isolated) |
| `maxTradeSzs`      | array          | Maximum trade sizes `[long, short]`       |
| `availableToTrade` | array          | Available to trade `[long, short]`        |
| `markPx`           | string         | Current mark price                        |

<details>

<summary>Response</summary>

```json
{
  "user": "0x0000000000000000000000000000000000000000",
  "coin": "BTC",
  "leverage": {
    "type": "cross", // "cross" or "isolated"
    "value": 5,
    "rawUsd": null // Only present if isolated
  },
  "maxTradeSzs": ["100000.00", "100000.00"],
  "availableToTrade": ["50000.00", "50000.00"],
  "markPx": "45000.00"
}
```

</details>


# spotClearinghouseState

Get the Hyperliquid spot clearinghouse state for a single user.

`spotClearinghouseState` gives you a wallet's spot token balances on Hyperliquid in a single API request.

You provide a wallet address, and it returns every token the wallet holds, its total balance, the amount on hold in open orders, and its cost basis.

### &#x20;<a href="#post-request-1" id="post-request-1"></a>

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"spotClearinghouseState"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "spotClearinghouseState",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'spotClearinghouseState',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'spotClearinghouseState',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                  | Type   | Description                   |
| ---------------------- | ------ | ----------------------------- |
| `balances`             | array  | Array of spot balance objects |
| `balances[n].coin`     | string | Coin symbol                   |
| `balances[n].token`    | int    | Token index                   |
| `balances[n].total`    | string | Total balance                 |
| `balances[n].hold`     | string | Amount on hold                |
| `balances[n].entryNtl` | string | Entry notional                |

<details>

<summary>Response</summary>

```json
{
  "balances": [
    {
      "coin": "USDC",
      "token": 0,
      "total": "0.02221591",
      "hold": "0.0",
      "entryNtl": "0.0"
    }
  ]
}
```

</details>


# userAbstraction

Get the account abstraction mode of a Hyperliquid user.

`userAbstraction` tells you which account mode a wallet is using, in a single API request.

{% hint style="info" %}
In simple terms: "How is this account set up to handle balances and collateral?"

The answer changes where you should read the wallet's money from, so check it before showing balances or margin.
{% endhint %}

## POST Request

| Field  | Type   | Description                                   |
| ------ | ------ | --------------------------------------------- |
| `type` | string | Must be `"userAbstraction"`                   |
| `user` | string | Ethereum address (0x-prefixed, 42 characters) |

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userAbstraction",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userAbstraction',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userAbstraction',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

Returns a string indicating the user's account abstraction mode:

```json
"unifiedAccount"
```

Possible values:

| Value             | Description                                       |
| ----------------- | ------------------------------------------------- |
| `unifiedAccount`  | Unified account mode                              |
| `portfolioMargin` | Portfolio margin mode                             |
| `disabled`        | Abstraction disabled                              |
| `default`         | Default mode                                      |
| `dexAbstraction`  | DEX abstraction mode (legacy, being discontinued) |

</details>


# webData2

Get aggregated Hyperliquid web data, including clearinghouse state, metadata and market info.

{% hint style="warning" %}
`webData2` is deprecated. Please use [webData3](https://hydromancer.xyz/docs/rest-api/user-position-data/webdata3) for the latest version. Existing `webData2` integrations will continue to work.
{% endhint %}

{% hint style="info" %}
This is a composite endpoint returning clearinghouse state, open orders, metadata, asset contexts, and more.
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"webData2"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "webData2",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'webData2',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'webData2',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                           | Type    | Description                                                                                            |
| ----------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------ |
| `clearinghouseState`                            | object  | User's clearinghouse state (margin summary, positions, etc.)                                           |
| `clearinghouseState.marginSummary`              | object  | Margin summary with `accountValue`, `totalNtlPos`, `totalRawUsd`, `totalMarginUsed`                    |
| `clearinghouseState.crossMarginSummary`         | object  | Cross margin summary (same fields as marginSummary)                                                    |
| `clearinghouseState.crossMaintenanceMarginUsed` | string  | Cross maintenance margin used                                                                          |
| `clearinghouseState.withdrawable`               | string  | Withdrawable amount                                                                                    |
| `clearinghouseState.assetPositions`             | array   | List of asset positions                                                                                |
| `clearinghouseState.time`                       | int     | Timestamp (ms)                                                                                         |
| `leadingVaults`                                 | array   | Leading vaults for the user                                                                            |
| `totalVaultEquity`                              | string  | Total vault equity                                                                                     |
| `openOrders`                                    | array   | Open orders                                                                                            |
| `agentAddress`                                  | string? | Agent address (null if none)                                                                           |
| `agentValidUntil`                               | int?    | Agent validity timestamp (null if none)                                                                |
| `cumLedger`                                     | string  | Cumulative ledger value                                                                                |
| `meta`                                          | object  | Metadata including universe and margin tables                                                          |
| `meta.universe`                                 | array   | List of perp assets with `szDecimals`, `name`, `maxLeverage`, `marginTableId`, `isDelisted` (optional) |
| `meta.marginTables`                             | array   | Margin table definitions with tiers                                                                    |
| `meta.collateralToken`                          | int     | Collateral token index                                                                                 |
| `assetCtxs`                                     | array   | Asset contexts                                                                                         |
| `serverTime`                                    | int     | Server timestamp (ms)                                                                                  |
| `isVault`                                       | boolean | Whether the user is a vault                                                                            |
| `user`                                          | string  | User address                                                                                           |
| `twapStates`                                    | array   | Active TWAP order states                                                                               |
| `perpsAtOpenInterestCap`                        | array   | List of perp symbols at open interest cap                                                              |

<details>

<summary>Response (truncated)</summary>

```json
{
    "clearinghouseState": {
        "marginSummary": {
            "accountValue": "0.0",
            "totalNtlPos": "0.0",
            "totalRawUsd": "0.0",
            "totalMarginUsed": "0.0"
        },
        "crossMarginSummary": {
            "accountValue": "0.0",
            "totalNtlPos": "0.0",
            "totalRawUsd": "0.0",
            "totalMarginUsed": "0.0"
        },
        "crossMaintenanceMarginUsed": "0.0",
        "withdrawable": "0.0",
        "assetPositions": [],
        "time": 1773660497365
    },
    "leadingVaults": [],
    "totalVaultEquity": "0.0",
    "openOrders": [],
    "agentAddress": null,
    "agentValidUntil": null,
    "cumLedger": "0.0",
    "meta": {
        "universe": [
            {
                "szDecimals": 5,
                "name": "BTC",
                "maxLeverage": 40,
                "marginTableId": 56
            }
        ],
        "marginTables": [
            [
                56,
                {
                    "description": "tiered 40x",
                    "marginTiers": [
                        {
                            "lowerBound": "0.0",
                            "maxLeverage": 40
                        },
                        {
                            "lowerBound": "150000000.0",
                            "maxLeverage": 20
                        }
                    ]
                }
            ]
        ],
        "collateralToken": 0
    },
    "assetCtxs": [],
    "serverTime": 1773660497365,
    "isVault": false,
    "user": "0x0000000000000000000000000000000000000000",
    "twapStates": [],
    "perpsAtOpenInterestCap": [
        "CANTO",
        "FTM",
        "JELLY"
    ]
}
```

</details>


# webData3

Get a lightweight Hyperliquid account summary for a user: agent wallet, account mode, cumulative ledger and per-DEX vault equity.

{% hint style="info" %}
webData3 replaces webData2. It returns a compact account summary with one entry per perp DEX. It does not include positions, open orders, market metadata or asset contexts. Fetch those from the dedicated endpoints listed in Migrating from webData2.
{% endhint %}

#### POST Request

| Field  | Type   | Description                                        |
| ------ | ------ | -------------------------------------------------- |
| `type` | string | Must be `"webData3"`                               |
| `user` | string | User Ethereum address (0x-prefixed, 42 characters) |

The response always covers every perp DEX. There is no `dex` filter.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "webData3",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'webData3',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'webData3',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

### Response Fields <a href="#response-fields" id="response-fields"></a>

| Field                                    | Type    | Description                                                                                              |
| ---------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------- |
| `userState`                              | object  | Account-level summary                                                                                    |
| `userState.agentAddress`                 | string? | Approved agent (API) wallet address (null if none)                                                       |
| `userState.agentValidUntil`              | int?    | Agent validity timestamp in ms (null if none)                                                            |
| `userState.cumLedger`                    | string  | Cumulative ledger value                                                                                  |
| `userState.serverTime`                   | int     | Server timestamp (ms)                                                                                    |
| `userState.isVault`                      | boolean | Whether the user is a vault                                                                              |
| `userState.user`                         | string  | User address                                                                                             |
| `userState.dexAbstractionEnabled`        | boolean | Whether per-DEX abstraction is enabled. Omitted for some accounts                                        |
| `userState.abstraction`                  | string  | Account abstraction mode, e.g. `unifiedAccount` or `portfolioMargin`. Omitted for some accounts          |
| `perpDexStates`                          | array   | One entry per perp DEX. Index 0 is the native Hyperliquid DEX, followed by HIP-3 DEXes in perpDexs order |
| `perpDexStates[].totalVaultEquity`       | string  | User's total vault equity on that DEX                                                                    |
| `perpDexStates[].perpsAtOpenInterestCap` | array   | Perp symbols on that DEX currently at their open interest cap. Omitted when there are none               |

#### Response

<details>

<summary>Response (truncated)</summary>

```json
{
    "userState": {
        "agentAddress": null,
        "agentValidUntil": null,
        "cumLedger": "0.0",
        "serverTime": 1791361435566,
        "isVault": false,
        "user": "0x0000000000000000000000000000000000000000"
    },
    "perpDexStates": [
        {
            "totalVaultEquity": "0.0",
            "perpsAtOpenInterestCap": [
                "CANTO",
                "FTM",
                "JELLY",
                "LOOM",
                "RLB",
                "VINE",
                "ZEREBRO"
            ]
        },
        {
            "totalVaultEquity": "0.0"
        },
        {
            "totalVaultEquity": "0.0"
        }
    ]
}
```

</details>

### Migrating from webData2 <a href="#migrating-from-webdata2" id="migrating-from-webdata2"></a>

webData2 returned positions, orders and market data in one response. webData3 returns only the account summary, so fetch the rest from these endpoints:

| webData2 field                                                                  | Use now                                                                                      |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `agentAddress`, `agentValidUntil`, `cumLedger`, `isVault`, `serverTime`, `user` | webData3 → `userState`                                                                       |
| `totalVaultEquity`                                                              | webData3 → `perpDexStates[].totalVaultEquity` (now per DEX)                                  |
| `perpsAtOpenInterestCap`                                                        | webData3 → `perpDexStates[].perpsAtOpenInterestCap` (now per DEX), or perpsAtOpenInterestCap |
| `clearinghouseState`                                                            | clearinghouseState, or portfolioState for perp + spot together                               |
| `openOrders`                                                                    | openOrders or frontendOpenOrders                                                             |
| `meta`, `assetCtxs`                                                             | metaAndAssetCtxs                                                                             |
| `leadingVaults`                                                                 | leadingVaults                                                                                |
| `twapStates`                                                                    | userTwapSummaries                                                                            |


# User order data

Endpoints for querying a Hyperliquid user's open orders, with or without frontend details.

#### **Retrieving user's open orders**

{% content-ref url="/pages/PX3ZGFCRu29iq0QLMzBH" %}
[openOrders](https://hydromancer.xyz/docs/rest-api/user-order-data/openorders)
{% endcontent-ref %}

#### **Retrieving user's open orders&#x20;*****with additional frontend information***

Additional frontend information includes order trigger condition, reduceOnly toggle, whether the order is TP/SL, and more.

{% content-ref url="/pages/y00Nntqs5kDT0faEcEfS" %}
[frontendOpenOrders](https://hydromancer.xyz/docs/rest-api/user-order-data/frontendopenorders)
{% endcontent-ref %}


# openOrders

Get the open orders of a Hyperliquid user.

Returns the open orders for a user.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"openOrders"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "openOrders",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'openOrders',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'openOrders',
    user: '0x0000000000000000000000000000000000000000'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field       | Type   | Description                   |
| ----------- | ------ | ----------------------------- |
| `coin`      | string | Asset symbol                  |
| `limitPx`   | string | Limit price                   |
| `oid`       | int    | Order ID                      |
| `side`      | string | `"A"` (sell) or `"B"` (buy)   |
| `sz`        | string | Order size                    |
| `timestamp` | int    | Order creation timestamp (ms) |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "limitPx": "29792.0",
    "oid": 91490942,
    "side": "A",
    "sz": "0.0",
    "timestamp": 1681247412573
  }
]
```

</details>


# frontendOpenOrders

Get a Hyperliquid user's open orders with frontend details such as order type and trigger conditions.

Returns open orders for a user with additional frontend display information such as order type and trigger details.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"frontendOpenOrders"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name (optional). Defaults to empty string for first perp DEX. Spot open orders are only included with the first perp DEX.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "frontendOpenOrders",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'frontendOpenOrders',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'frontendOpenOrders',
    user: '0x0000000000000000000000000000000000000000'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field              | Type    | Description                                                                                                 |
| ------------------ | ------- | ----------------------------------------------------------------------------------------------------------- |
| `coin`             | string  | Asset symbol                                                                                                |
| `isPositionTpsl`   | boolean | Whether this is a position TP/SL order                                                                      |
| `isTrigger`        | boolean | Whether this is a trigger order                                                                             |
| `limitPx`          | string  | Limit price                                                                                                 |
| `oid`              | int     | Order ID                                                                                                    |
| `orderType`        | string  | Order type (e.g. `"Limit"`, `"Stop Market"`, `"Stop Limit"`, `"Take Profit Market"`, `"Take Profit Limit"`) |
| `origSz`           | string  | Original order size                                                                                         |
| `reduceOnly`       | boolean | Whether this is a reduce-only order                                                                         |
| `side`             | string  | `"A"` (sell) or `"B"` (buy)                                                                                 |
| `sz`               | string  | Remaining order size                                                                                        |
| `timestamp`        | int     | Order creation timestamp (ms)                                                                               |
| `triggerCondition` | string  | Trigger condition (e.g. `"N/A"`, `"tp"`, `"sl"`)                                                            |
| `triggerPx`        | string  | Trigger price for stop/take-profit orders                                                                   |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "isPositionTpsl": false,
    "isTrigger": false,
    "limitPx": "29792.0",
    "oid": 91490942,
    "orderType": "Limit",
    "origSz": "5.0",
    "reduceOnly": false,
    "side": "A",
    "sz": "5.0",
    "timestamp": 1681247412573,
    "triggerCondition": "N/A",
    "triggerPx": "0.0"
  }
]
```

</details>


# Historical data

Hyperliquid historical data API endpoints: fills, orders, funding, ledger updates and leverage changes for users and builders.

Query historical Hyperliquid fills, trades, orders, funding, liquidations, TWAPs, and builder activity over REST. Need multi-month bulk Parquet exports for backtesting?&#x20;

Use free Parquet archives on S3 (requester pays for transfer, no API key) via [Hydromancer Reservoir](https://hydromancer.xyz/docs/reservoir/overview) or see [Hyperliquid historical data](https://hydromancer.xyz/hyperliquid-historical-data).

| Need                                 | Primary Endpoints                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Notes                                                                                               |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| **User fills**                       | [userFills](https://hydromancer.xyz/docs/rest-api/historical-data/userfills), [userFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userfillsbytime)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Latest 2,000 fills (`userFills`) or time-range history (`userFillsByTime`); both include TWAP fills |
| **Market-wide trades & fills (24h)** | [fillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/fillsbytime), [tradesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/tradesbytime)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Optionally filtered by coin; oldest-first, max 2,000 per page                                       |
| **Liquidations**                     | [liquidationHistoryByTime](https://hydromancer.xyz/docs/rest-api/historical-data/liquidationhistorybytime), [liquidationBuckets](https://hydromancer.xyz/docs/rest-api/historical-data/liquidationbuckets)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Raw events (coin or market-wide) or long/short totals per perp market in up to 200 UTC buckets      |
| **Funding & ledger transfers**       | [userFunding](https://hydromancer.xyz/docs/rest-api/historical-data/userfunding), [fundingHistory](https://hydromancer.xyz/docs/rest-api/historical-data/fundinghistory), [userNonFundingLedgerUpdates](https://hydromancer.xyz/docs/rest-api/historical-data/usernonfundingledgerupdates)                                                                                                                                                                                                                                                                                                                                                                                                                                           | User funding payments, per-coin funding rates, and deposits, withdrawals and transfers              |
| **Orders, TWAPs & margin/leverage**  | [historicalOrders](https://hydromancer.xyz/docs/rest-api/historical-data/historicalorders), [orderStatusByOid](https://hydromancer.xyz/docs/rest-api/historical-data/orderstatusbyoid), [userTwapSummaries](https://hydromancer.xyz/docs/rest-api/historical-data/usertwapsummaries), [userTwapSliceFills](https://hydromancer.xyz/docs/rest-api/historical-data/usertwapslicefills), [userTwapStatusesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/usertwapstatusesbytime), [userLeverageUpdatesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userleverageupdatesbytime), [userIsolatedMarginUpdatesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userisolatedmarginupdatesbytime) | Order lifecycle, TWAP execution, leverage changes and isolated-margin updates                       |
| **Builder code & approved users**    | [builderFills](https://hydromancer.xyz/docs/rest-api/historical-data/builderfills), [builderFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderfillsbytime), [builderOrdersByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderordersbytime), [builderApprovedFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovedfillsbytime), [builderApprovedFundingByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovedfundingbytime), [builderApprovedNonFundingLedgerUpdatesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovednonfundingledgerupdatesbytime)                                                         | Builder-routed fills and orders (revenue), plus all activity by users who approved your builder     |


# userFills

Get the 2000 latest Hyperliquid fills of a user. Includes TWAP fills.

{% hint style="info" %}
**All data is fully available from 28-07-2025. Hydromancer performed a full backfill of fills offered by the native Hyperliquid API. The result includes full historical data for most traders, except some very high-volume addresses. TWAP fills are included from 02-08-2025.**
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userFills"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>builder</code></td><td>string</td><td>Filter to fills routed through this builder address (0x-prefixed, 42 characters). Omit (or send <code>null</code>) for no filtering. A malformed, empty or non-string value is a <code>400</code> rather than a silently unfiltered result (optional)</td></tr><tr><td><code>aggregateByTime</code></td><td>boolean</td><td><code>true</code> or <code>false</code> false by default (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>i.e. "xyz" or "main_dex" or dont pass for no filtering (optional)</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return, default 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userFills",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userFills',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userFills',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field           | Type    | Description                                     |
| --------------- | ------- | ----------------------------------------------- |
| `coin`          | string  | Asset symbol                                    |
| `px`            | string  | Fill price                                      |
| `sz`            | string  | Fill size                                       |
| `side`          | string  | `"A"` (sell) or `"B"` (buy)                     |
| `time`          | int     | Fill timestamp (ms)                             |
| `startPosition` | string  | Position size before the fill                   |
| `dir`           | string  | Direction (e.g. `"Open Long"`, `"Close Short"`) |
| `closedPnl`     | string  | Closed PnL from this fill                       |
| `hash`          | string  | Transaction hash                                |
| `oid`           | int     | Order ID                                        |
| `crossed`       | boolean | Whether the order crossed the spread            |
| `fee`           | string  | Fee amount                                      |
| `tid`           | int     | Trade ID                                        |
| `cloid`         | string? | Client order ID (optional)                      |
| `builderFee`    | string? | Builder fee (optional)                          |
| `deployerFee`   | string? | Deployer fee (optional, HIP-3 fills only)       |
| `priorityGas`   | string? | Priority gas fee in HYPE (optional)             |
| `feeToken`      | string  | Fee token (e.g. `"USDC"`)                       |
| `builder`       | string? | Builder address (optional)                      |
| `twapId`        | int?    | TWAP order ID (null if not a TWAP fill)         |
| `txIndex`       | int     | Transaction index                               |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "px": "45000.00",
    "sz": "0.5",
    "side": "B",
    "time": 1234567890123,
    "startPosition": "1.0",
    "dir": "Open Long",
    "closedPnl": "0.00",
    "hash": "0x1234567890abcdef",
    "oid": 123456,
    "crossed": false,
    "fee": "22.50",
    "tid": 789012,
    "cloid": "client-123",
    "builderFee": "0.10",
    "deployerFee": "0.05",
    "priorityGas": null,
    "feeToken": "USDC",
    "builder": "0x...",
    "twapId": 123456,
    "txIndex": 12
  }
]
```

</details>


# userFillsByTime

Get Hyperliquid trading fills for a single user within a time range. Includes TWAP fills.

{% hint style="info" %}
**All data is fully available from 28-07-2025. Hydromancer performed a full backfill of fills offered by the native Hyperliquid API. The result includes full historical data for most traders, except some very high-volume addresses. TWAP fills are included from 02-08-2025.**
{% endhint %}

This endpoint is for user-specific fills. For market-specific fills, use [fillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/fillsbytime).

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userFillsByTime"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Earliest fill time to include (Unix ms, inclusive). Skipped when <code>cursor</code> is used. Either <code>startTime</code> or <code>cursor</code> must be supplied</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>Latest fill time to include (Unix ms, inclusive). Default: now (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of <code>time</code> and <code>txIndex</code> with <code>"_"</code> separator (e.g. <code>"1234567890000_23"</code>). Take from the <strong>last record</strong> of the previous response (optional)</td></tr><tr><td><code>builder</code></td><td>string</td><td>Filter to fills routed through this builder address (0x-prefixed, 42 characters). Omit (or send <code>null</code>) for no filtering. A malformed, empty or non-string value is a <code>400</code> rather than a silently unfiltered result (optional)</td></tr><tr><td><code>aggregateByTime</code></td><td>boolean</td><td><code>true</code> or <code>false</code>, <code>false</code> by default (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>i.e. <code>"xyz"</code> or <code>"main_dex"</code>, or omit for no filtering (optional)</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return, default 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userFillsByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 1234567890000,
    "endTime": 1234567900000,
    "cursor": "1234567890000_23"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userFillsByTime',
        'user': '0x0000000000000000000000000000000000000000',
        'startTime': 1234567890000,
        'endTime': 1234567900000,
        'cursor': '1234567890000_12'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userFillsByTime',
        user: '0x0000000000000000000000000000000000000000',
        startTime: 1234567890000,
        endTime: 1234567900000,
        cursor: '1234567890000_12'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field           | Type    | Description                                                                                                                                                                    |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `coin`          | string  | Asset symbol                                                                                                                                                                   |
| `px`            | string  | Fill price                                                                                                                                                                     |
| `sz`            | string  | Fill size                                                                                                                                                                      |
| `side`          | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                    |
| `time`          | int     | Fill timestamp (ms)                                                                                                                                                            |
| `startPosition` | string  | Position size before the fill                                                                                                                                                  |
| `dir`           | string  | Direction (e.g. `"Open Long"`, `"Close Short"`, `"Settlement"`)                                                                                                                |
| `closedPnl`     | string  | Closed PnL from this fill                                                                                                                                                      |
| `hash`          | string  | Transaction hash                                                                                                                                                               |
| `oid`           | int     | Order ID                                                                                                                                                                       |
| `crossed`       | boolean | Whether the order crossed the spread                                                                                                                                           |
| `fee`           | string  | Fee amount                                                                                                                                                                     |
| `tid`           | int     | Trade ID                                                                                                                                                                       |
| `cloid`         | string? | Client order ID (optional)                                                                                                                                                     |
| `builderFee`    | string? | Builder fee (optional)                                                                                                                                                         |
| `subBuilders`   | array?  | Sub-builders sharing `builderFee`, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `deployerFee`   | string? | Deployer fee (optional, HIP-3 fills only)                                                                                                                                      |
| `priorityGas`   | string? | Priority gas fee in HYPE (optional)                                                                                                                                            |
| `feeToken`      | string  | Fee token (e.g. `"USDC"`)                                                                                                                                                      |
| `twapId`        | int?    | TWAP order ID (null if not a TWAP fill)                                                                                                                                        |
| `txIndex`       | int     | Transaction index                                                                                                                                                              |
| `venue`         | string? | HIP-4 venue of an outcome (`#NNNN`) market, e.g. `"out"`. Omitted for validator-deployed outcomes and all other coins                                                          |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "hyna:LIT",
    "px": "3.38",
    "sz": "306.0635",
    "side": "A",
    "time": 1766411264116,
    "startPosition": "306.0635",
    "dir": "Settlement",
    "closedPnl": "0.00",
    "hash": "0xe9700f27f4c60944eae90431e255630202d5000d8fc928168d38ba7ab3c9e32f",
    "oid": 276429539434,
    "crossed": false,
    "fee": "0.00",
    "tid": 587851719766407,
    "feeToken": "USDE",
    "twapId": null,
    "txIndex": 1
  }
]
```

</details>


# fillsByTime

Market-wide Hyperliquid fills of the last 24 hours, by time, optionally filtered by coin.

This endpoint is for market-specific fills. For user-specific fills, use [userFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userfillsbytime).

## POST Request

<table><thead><tr><th width="180">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Required. <code>"fillsByTime"</code></td></tr><tr><td><code>startTime</code></td><td>number</td><td>Required unless <code>cursor</code> is given. Inclusive, milliseconds. A value older than 24 hours is moved forward to 24 hours ago.</td></tr><tr><td><code>endTime</code></td><td>number</td><td>Optional. Inclusive, milliseconds. Default: now.</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Optional. Continue from a previous page. Format <code>"{time}_{txIndex}"</code>. A cursor older than 24 hours resumes at 24 hours ago.</td></tr><tr><td><code>coin</code></td><td>string</td><td>Optional. Only fills on this coin, e.g. <code>"BTC"</code>, <code>"xyz:GOLD"</code>, <code>"@107"</code>, <code>"#40080"</code>.</td></tr><tr><td><code>dex</code></td><td>string</td><td>Optional. <code>"main_dex"</code> or a HIP-3 dex such as <code>"xyz"</code>.</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>number</td><td>Optional. Default and maximum 2000.</td></tr></tbody></table>

Results are returned oldest-first, ordered by `(time, txIndex)`. A range that lies entirely before the last 24 hours returns an empty list.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "type": "fillsByTime",
    "coin": "BTC",
    "startTime": 1786000000000,
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

resp = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "type": "fillsByTime",
        "coin": "BTC",
        "startTime": 1786000000000,
        "limit": 100,
    },
)
fills = resp.json()
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const resp = await fetch("https://api.hydromancer.xyz/info", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": "YOUR_API_KEY" },
  body: JSON.stringify({
    type: "fillsByTime",
    coin: "BTC",
    startTime: 1786000000000,
    limit: 100,
  }),
});
const fills = await resp.json();
```

{% endtab %}
{% endtabs %}

***

## Pagination

Take the last returned fill and build `cursor` as `"{time}_{txIndex}"`, then repeat the request with that `cursor` instead of `startTime`. A page shorter than `limit` means you have reached the end of the range.

At the busiest hours the market produces about 300 fills a second, so a 2000-fill page covers only a few seconds. Filter by `coin` when you can.

## Response Fields

An array of fill objects, each including the `user` that made the fill. The `builder` field is the builder the fill was routed through, `null` when there was none.

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "px": "50000.0",
    "sz": "1.5",
    "side": "B",
    "time": 1786000001000,
    "startPosition": "0.0",
    "dir": "Open Long",
    "closedPnl": "0.0",
    "hash": "0x...",
    "oid": 12345,
    "crossed": true,
    "fee": "0.5",
    "tid": 20001,
    "feeToken": "USDC",
    "builder": null,
    "user": "0x0000000000000000000000000000000000000001",
    "txIndex": 0
  }
]
```

</details>


# tradesByTime

Hyperliquid market trades of the last 24 hours, in the WebSocket trades shape, by time, optionally filtered by coin.

Market trades of the last 24 hours. Each trade is exactly what the [trades](https://hydromancer.xyz/docs/websocket/trades-data/trades) WebSocket channel sent for it, so a client can backfill a gap in its stream and get identical objects.

## POST Request

<table><thead><tr><th width="180">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Required. <code>"tradesByTime"</code></td></tr><tr><td><code>startTime</code></td><td>number</td><td>Required unless <code>cursor</code> is given. Inclusive, milliseconds. A value older than 24 hours is moved forward to 24 hours ago.</td></tr><tr><td><code>endTime</code></td><td>number</td><td>Optional. Inclusive, milliseconds. Default: now.</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Optional. The <code>cursor</code> from the previous response. Pass it back unchanged. A cursor older than 24 hours resumes at 24 hours ago.</td></tr><tr><td><code>coin</code></td><td>string</td><td>Optional. Only trades on this coin, e.g. <code>"BTC"</code>, <code>"xyz:GOLD"</code>, <code>"@107"</code>, <code>"#40080"</code>.</td></tr><tr><td><code>dex</code></td><td>string</td><td>Optional. <code>"main_dex"</code> or a HIP-3 dex such as <code>"xyz"</code>.</td></tr><tr><td><code>limit</code></td><td>number</td><td>Optional. Default and maximum 2000.</td></tr></tbody></table>

Trades are returned oldest-first, in the order the WebSocket sent them. A range that lies entirely before the last 24 hours returns no trades.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "type": "tradesByTime",
    "coin": "BTC",
    "startTime": 1786000000000,
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

resp = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "type": "tradesByTime",
        "coin": "BTC",
        "startTime": 1786000000000,
        "limit": 100,
    },
)
page = resp.json()
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const resp = await fetch("https://api.hydromancer.xyz/info", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": "YOUR_API_KEY" },
  body: JSON.stringify({
    type: "tradesByTime",
    coin: "BTC",
    startTime: 1786000000000,
    limit: 100,
  }),
});
const page = await resp.json();
```

{% endtab %}
{% endtabs %}

***

## Pagination

While `hasMore` is `true`, repeat the request with the response's `cursor` instead of `startTime`. On the last page `hasMore` is `false` and `cursor` is absent.

The cursor is opaque. Trades carry no field it could be built from, because a mirrored outcome trade and the trade it mirrors share every field the WebSocket sends.

## Response Fields

| Field     | Type    | Description                                       |
| --------- | ------- | ------------------------------------------------- |
| `trades`  | array   | Trades, each in the WebSocket `trades` shape      |
| `hasMore` | boolean | `true` when another page follows                  |
| `cursor`  | string  | Pass to the next request. Absent on the last page |

Each trade:

| Field   | Type   | Description                                |
| ------- | ------ | ------------------------------------------ |
| `coin`  | string | Coin                                       |
| `side`  | string | The taker's side: `"B"` bought, `"A"` sold |
| `px`    | string | Price                                      |
| `sz`    | string | Size                                       |
| `hash`  | string | Transaction hash                           |
| `time`  | number | Block time, milliseconds                   |
| `tid`   | number | Trade id                                   |
| `users` | array  | `[buyer, seller]`                          |

On outcome markets a trade on one side also appears on the other side's coin, at `1 − px` with the side and the users swapped, as on the WebSocket.

<details>

<summary>Response</summary>

```json
{
  "trades": [
    {
      "coin": "BTC",
      "side": "B",
      "px": "64000.0",
      "sz": "0.1",
      "hash": "0x...",
      "time": 1786000001000,
      "tid": 20001,
      "users": [
        "0x0000000000000000000000000000000000000001",
        "0x0000000000000000000000000000000000000002"
      ]
    }
  ],
  "hasMore": true,
  "cursor": "1786000001000_812345678_0"
}
```

</details>


# userTwapSliceFills

Get the 2000 most recent Hyperliquid TWAP slice fills for a user.

{% hint style="info" %}
**All data is fully available from 28-07-2025. Hydromancer performed a full backfill of fills offered by the native Hyperliquid API. The result includes full historical data for most traders, except some very high-volume addresses. TWAP fills are included from 02-08-2025.**
{% endhint %}

Returns fills that were executed as part of a TWAP (Time-Weighted Average Price) order. Each fill is an individual "slice" of the TWAP execution. Only fills with a non-null `twapId` are returned.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userTwapSliceFills"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userTwapSliceFills",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userTwapSliceFills',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userTwapSliceFills',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field           | Type    | Description                                                                                                           |
| --------------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| `coin`          | string  | Asset symbol                                                                                                          |
| `px`            | string  | Fill price                                                                                                            |
| `sz`            | string  | Fill size                                                                                                             |
| `side`          | string  | `"A"` (sell) or `"B"` (buy)                                                                                           |
| `time`          | int     | Fill timestamp (ms)                                                                                                   |
| `startPosition` | string  | Position size before the fill                                                                                         |
| `dir`           | string  | Direction (e.g. `"Open Long"`, `"Open Short"`)                                                                        |
| `closedPnl`     | string  | Closed PnL from this fill                                                                                             |
| `hash`          | string  | Transaction hash (always `0x000...000` for TWAP fills)                                                                |
| `oid`           | int     | Order ID                                                                                                              |
| `crossed`       | boolean | Whether the order crossed the spread                                                                                  |
| `fee`           | string  | Fee amount                                                                                                            |
| `tid`           | int     | Trade ID                                                                                                              |
| `cloid`         | string? | Client order ID (optional)                                                                                            |
| `builderFee`    | string? | Builder fee (optional)                                                                                                |
| `deployerFee`   | string? | Deployer fee (optional, HIP-3 fills only)                                                                             |
| `feeToken`      | string  | Fee token (e.g. `"USDC"`)                                                                                             |
| `twapId`        | int     | TWAP order ID                                                                                                         |
| `txIndex`       | int     | Transaction index                                                                                                     |
| `venue`         | string? | HIP-4 venue of an outcome (`#NNNN`) market, e.g. `"out"`. Omitted for validator-deployed outcomes and all other coins |

<details>

<summary>Response</summary>

```json
[
{
"coin": "BTC",
"px": "67950.00",
"sz": "0.00108",
"side": "A",
"time": 1772096268036,
"startPosition": "-1.78931",
"dir": "Open Short",
"closedPnl": "0.00",
"hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"oid": 330647838320,
"crossed": true,
"fee": "0.033023",
"tid": 792432692404914,
"feeToken": "USDC",
"twapId": 1628419,
"txIndex": 12
}
]
```

</details>

<details>

<summary>Notes</summary>

* Returns at most 2000 most recent TWAP slice fills, ordered by time descending
* TWAP fills always have a hash of `0x000...000`
* The `twapId` field identifies which TWAP order the slice belongs to — multiple fills can share the same `twapId`
* Unlike Hyperliquid's native endpoint which wraps fills as `{ "fill": {...}, "twapId": N }`, Hydromancer returns fills in the same flat format as `userFills`

</details>


# userTwapSummaries

Get aggregated Hyperliquid TWAP order summaries for a user.

{% hint style="info" %}
**All data is fully available from 28-07-2025. Hydromancer performed a full backfill of fills offered by the native Hyperliquid API. The result includes full historical data for most traders, except some very high-volume addresses. TWAP fills are included from 02-08-2025.**
{% endhint %}

{% hint style="info" %}
💧New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

Returns one summary per TWAP order for a user, aggregating all slice fills that share the same `twapId`. Includes the volume-weighted average price, total size, total fees, total closed PnL, number of slices, and the time range of execution.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userTwapSummaries"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userTwapSummaries",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userTwapSummaries',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userTwapSummaries',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

{% hint style="warning" %}
**Number formatting:** Numeric fields (`avgPx`, `sz`, `fee`, `closedPnl`) are emitted in normalized form — trailing zeros are stripped and the decimal point is dropped for integers (e.g. `"0.054"` not `"0.05400"`, `"0"` not `"0.00"`). Compare values numerically, not by string equality.
{% endhint %}

```json
[
{
"user": "0x0000000000000000000000000000000000000000",
"twapId": 1628419,
"coin": "BTC",
"side": "A",
"avgPx": "67832.45",
"sz": "0.054",
"fee": "1.65115",
"closedPnl": "0",
"nSlices": 50,
"firstFillTime": 1772092668036,
"lastFillTime": 1772096268036
}
]
```

</details>

<details>

<summary>Response Fields</summary>

| Field           | Type   | Description                                          |
| --------------- | ------ | ---------------------------------------------------- |
| `user`          | string | User address                                         |
| `twapId`        | number | TWAP order identifier                                |
| `coin`          | string | Asset symbol (e.g. `"BTC"`)                          |
| `side`          | string | `"B"` for buy, `"A"` for sell                        |
| `avgPx`         | string | Volume-weighted average fill price across all slices |
| `sz`            | string | Total size filled across all slices                  |
| `fee`           | string | Total fees paid across all slices                    |
| `closedPnl`     | string | Total closed PnL across all slices                   |
| `nSlices`       | number | Number of individual slice fills executed            |
| `firstFillTime` | number | Timestamp (ms) of the first slice fill               |
| `lastFillTime`  | number | Timestamp (ms) of the last slice fill                |

</details>

<details>

<summary>Notes</summary>

* Returns at most 500 most recent TWAP summaries, ordered by last fill time descending
* Each summary aggregates all slice fills that share the same `twapId` — use `userTwapSliceFills` to get the individual fills
* `avgPx` is the volume-weighted average price: `sum(px * sz) / sum(sz)` across all slices
* Summaries update incrementally as new TWAP slices are executed

</details>


# userTwapStatusesByTime

Paginate a user's Hyperliquid TWAP order status events by time, oldest-first.

Returns TWAP status events for a user with `time` ≥ `startTime` (or after a `cursor`), ordered **oldest-first** by `time` then `tx_index`.

For pagination: pass `startTime` for the first page, then on each subsequent page pass the `cursor` `"{time}_{tx_index}"` built from the **last record** of the previous response. When `cursor` is supplied, `startTime` is ignored and the boundary record is excluded from the next page (no duplicates).

`dex` is optional. Omit to return statuses from every perp DEX. Set to `"main_dex"` for the native Hyperliquid dex, or to a HIP-3 dex name (e.g. `"xyz"`) to scope to that dex.

**note: TWAP status events are retained for \~24h on the server, so this endpoint can return at most one day of history.**

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userTwapStatusesByTime"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Earliest <code>time</code> to include (Unix ms, inclusive). Skipped when <code>cursor</code> is used. Either <code>startTime</code> or <code>cursor</code> must be supplied</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>Latest <code>time</code> to include (Unix ms, inclusive). Default: now (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of <code>time</code> and <code>tx_index</code> with <code>"_"</code> separator (e.g. <code>"1734571490123_12"</code>). Take from the <strong>last record</strong> of the previous response (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return. Default 100, max 500 (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Scope to a single perp DEX. <code>"main_dex"</code> for the native Hyperliquid dex, or a HIP-3 dex name (e.g. <code>"xyz"</code>). Omit for all dexes (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
# First page
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userTwapStatusesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0,
    "limit": 100
  }'

# Next page — cursor built from the last record of the previous response
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userTwapStatusesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "cursor": "1734571490123_12",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

url = 'https://api.hydromancer.xyz/info'
headers = {
    'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
    'Content-Type': 'application/json',
}
user = '0x0000000000000000000000000000000000000000'
limit = 500

params = {'type': 'userTwapStatusesByTime', 'user': user, 'startTime': 0, 'limit': limit}
while True:
    page = requests.post(url, json=params, headers=headers).json()
    if not page:
        break
    for status in page:
        ...  # process status event
    if len(page) < limit:
        break
    last = page[-1]
    params = {
        'type': 'userTwapStatusesByTime',
        'user': user,
        'cursor': f"{last['time']}_{last['tx_index']}",
        'limit': limit,
    }
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const url = 'https://api.hydromancer.xyz/info';
const headers = {
    'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
    'Content-Type': 'application/json',
};
const user = '0x0000000000000000000000000000000000000000';
const limit = 500;

let params = { type: 'userTwapStatusesByTime', user, startTime: 0, limit };
while (true) {
    const { data: page } = await axios.post(url, params, { headers });
    if (!page.length) break;
    for (const status of page) { /* process status event */ }
    if (page.length < limit) break;
    const last = page[page.length - 1];
    params = {
        type: 'userTwapStatusesByTime',
        user,
        cursor: `${last.time}_${last.tx_index}`,
        limit,
    };
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

JSON array of TWAP status records, ordered **oldest-first** by `time` then `tx_index`.

| Field            | Type    | Description                                                                                                                                                           |
| ---------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `time`           | int     | Block time when the status was emitted (Unix ms) — **first half of the next-page `cursor`**                                                                           |
| `block_number`   | int     | L1 block number containing the status update                                                                                                                          |
| `tx_index`       | int     | Transaction index within the block — **second half of the next-page `cursor`**                                                                                        |
| `twap_id`        | int     | TWAP order identifier (matches `twap_id` on `userTwapSliceFills` / `userTwapSummaries`)                                                                               |
| `user`           | string  | Ethereum address                                                                                                                                                      |
| `coin`           | string  | Asset symbol                                                                                                                                                          |
| `side`           | string  | `"B"` (buy) or `"A"` (sell)                                                                                                                                           |
| `sz`             | string  | Total intended TWAP size, in contracts                                                                                                                                |
| `executed_sz`    | string  | Cumulative executed size at the time of this status, in contracts                                                                                                     |
| `executed_ntl`   | string  | Cumulative executed notional at the time of this status (USDC)                                                                                                        |
| `minutes`        | int     | TWAP duration, in minutes                                                                                                                                             |
| `reduce_only`    | boolean | `true` if the TWAP order is reduce-only                                                                                                                               |
| `randomize`      | boolean | `true` if slice timing is randomized                                                                                                                                  |
| `twap_timestamp` | int     | TWAP order timestamp (Unix ms) as recorded by the protocol                                                                                                            |
| `status`         | string  | Lifecycle status string (`"activated"`, `"finished"`, `"terminated"`, `"stopped"`, `"waitingForTrigger"`) or — when `is_error` is `true` — the protocol error message |
| `is_error`       | boolean | `true` if `status` carries an error message rather than a normal lifecycle string                                                                                     |
| `stop_px`        | string  | Stop price attached to the TWAP, or `null` if none                                                                                                                    |
| `trigger_px`     | string  | Trigger price for a trigger TWAP (`"waitingForTrigger"`), or `null` if none                                                                                           |
| `trigger_above`  | boolean | For trigger TWAPs: `true` = activates when mark price rises above `trigger_px`, `false` = below. `null` if no trigger                                                 |


# builderFills

Get the 2000 latest Hyperliquid fills submitted by a builder.

{% hint style="info" %}
**Data available from 28-07-2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"builderFills"</code></td></tr><tr><td><code>builder</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return, default and max 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "builderFills",
    "builder": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'builderFills',
        'builder': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'builderFills',
        builder: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field           | Type    | Description                                                                                                                                                                    |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `coin`          | string  | Asset symbol                                                                                                                                                                   |
| `px`            | string  | Fill price                                                                                                                                                                     |
| `sz`            | string  | Fill size                                                                                                                                                                      |
| `side`          | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                    |
| `time`          | int     | Fill timestamp (ms)                                                                                                                                                            |
| `startPosition` | string  | Position size before the fill                                                                                                                                                  |
| `dir`           | string  | Direction (e.g. `"Open Long"`, `"Open Short"`, `"Short > Long"`)                                                                                                               |
| `closedPnl`     | string  | Closed PnL from this fill                                                                                                                                                      |
| `hash`          | string  | Transaction hash                                                                                                                                                               |
| `oid`           | int     | Order ID                                                                                                                                                                       |
| `crossed`       | boolean | Whether the order crossed the spread                                                                                                                                           |
| `fee`           | string  | Fee amount                                                                                                                                                                     |
| `tid`           | int     | Trade ID                                                                                                                                                                       |
| `builderFee`    | string  | Builder fee                                                                                                                                                                    |
| `subBuilders`   | array?  | Sub-builders sharing `builderFee`, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `deployerFee`   | string? | Deployer fee (HIP-3 fills only)                                                                                                                                                |
| `priorityGas`   | string? | Priority gas fee in HYPE (optional)                                                                                                                                            |
| `feeToken`      | string  | Fee token (e.g. `"USDC"`)                                                                                                                                                      |
| `user`          | string  | User address who placed the order                                                                                                                                              |
| `twapId`        | int     | TWAP order ID (null if not a TWAP fill)                                                                                                                                        |
| `cloid`         | string? | Client order ID (optional)                                                                                                                                                     |
| `txIndex`       | int     | Transaction index                                                                                                                                                              |
| `venue`         | string? | HIP-4 venue of an outcome (`#NNNN`) market, e.g. `"out"`. Omitted for validator-deployed outcomes and all other coins                                                          |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "px": "71070.00",
    "sz": "0.00541",
    "side": "A",
    "time": 1773429781878,
    "startPosition": "0.00",
    "dir": "Open Short",
    "closedPnl": "0.00",
    "hash": "0xa33ab861b80567f1a4b40436ff72410204530047530886c3470363b4770941dc",
    "oid": 348153004784,
    "crossed": true,
    "fee": "0.211467",
    "tid": 491098859095794,
    "builderFee": "0.038448",
    "deployerFee": "0.019224",
    "priorityGas": null,
    "feeToken": "USDC",
    "user": "0x5e24ba0e5753fb533e8ac74c63f00fa73488c484",
    "twapId": null,
    "txIndex": 21
  }
]
```

</details>


# builderFillsByTime

Get Hyperliquid fills submitted by a builder within a time range.

Get Hyperliquid fills submitted by a builder within a time range.

{% hint style="info" %}
💧New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

{% hint style="info" %}
**Data available from 28-07-2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="164.6666259765625">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be "builderFillsByTime"</td></tr><tr><td><code>builder</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Start timestamp in milliseconds (skipped when cursor is used)</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>End timestamp in milliseconds (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of time and txIndex with "_" separator (optional)</td></tr><tr><td><code>aggregateByTime</code></td><td>boolean</td><td>Collapse an order's partial fills at the same timestamp into a single fill. <code>true</code> or <code>false</code>, <code>false</code> by default (optional)</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return, default and max 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "builderFillsByTime",
    "builder": "0x0000000000000000000000000000000000000000",
    "startTime": 1234567890000,
    "endTime": 1234567900000,
    "cursor": "1234567890000_12"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'builderFillsByTime',
        'builder': '0x0000000000000000000000000000000000000000',
        'startTime': 1234567890000,
        'endTime': 1234567900000,
        'cursor': '1234567890000_12'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'builderFillsByTime',
        builder: '0x0000000000000000000000000000000000000000',
        startTime: 1234567890000,
        endTime: 1234567900000,
        cursor: '1234567890000_12'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field           | Type    | Description                                                                                                                                                                    |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `coin`          | string  | Asset symbol                                                                                                                                                                   |
| `px`            | string  | Fill price                                                                                                                                                                     |
| `sz`            | string  | Fill size                                                                                                                                                                      |
| `side`          | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                    |
| `time`          | int     | Fill timestamp (ms)                                                                                                                                                            |
| `startPosition` | string  | Position size before the fill                                                                                                                                                  |
| `dir`           | string  | Direction (e.g. `"Open Long"`, `"Open Short"`, `"Short > Long"`)                                                                                                               |
| `closedPnl`     | string  | Closed PnL from this fill                                                                                                                                                      |
| `hash`          | string  | Transaction hash                                                                                                                                                               |
| `oid`           | int     | Order ID                                                                                                                                                                       |
| `crossed`       | boolean | Whether the order crossed the spread                                                                                                                                           |
| `cloid`         | string? | Client order ID (optional)                                                                                                                                                     |
| `fee`           | string  | Fee amount                                                                                                                                                                     |
| `tid`           | int     | Trade ID                                                                                                                                                                       |
| `builderFee`    | string? | Builder fee (optional)                                                                                                                                                         |
| `subBuilders`   | array?  | Sub-builders sharing `builderFee`, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `deployerFee`   | string? | Deployer fee (HIP-3 fills only)                                                                                                                                                |
| `priorityGas`   | string? | Priority gas fee in HYPE (optional)                                                                                                                                            |
| `feeToken`      | string  | Fee token (e.g. `"USDC"`)                                                                                                                                                      |
| `user`          | string  | User address who placed the order                                                                                                                                              |
| `twapId`        | int     | TWAP order ID (null if not a TWAP fill)                                                                                                                                        |
| `txIndex`       | int     | Transaction index                                                                                                                                                              |
| `venue`         | string? | HIP-4 venue of an outcome (`#NNNN`) market, e.g. `"out"`. Omitted for validator-deployed outcomes and all other coins                                                          |

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "px": "71070.00",
    "sz": "0.00541",
    "side": "A",
    "time": 1773429781878,
    "startPosition": "0.00",
    "dir": "Open Short",
    "closedPnl": "0.00",
    "hash": "0xa33ab861b80567f1a4b40436ff72410204530047530886c3470363b4770941dc",
    "oid": 348153004784,
    "crossed": true,
    "fee": "0.211467",
    "tid": 491098859095794,
    "builderFee": "0.038448",
    "deployerFee": "0.019224",
    "priorityGas": null,
    "feeToken": "USDC",
    "user": "0x5e24ba0e5753fb533e8ac74c63f00fa73488c484",
    "twapId": null,
    "txIndex": 21
  }
]
```

</details>


# builderApprovedFillsByTime

Hyperliquid fills that occurred while a user had an active builder-fee approval for your builder address.

{% hint style="info" %}
This is **not** the same as [builderFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderfillsbytime).

`builderFillsByTime` returns fills that were *routed through* your builder — the order carried your builder address. `builderApprovedFillsByTime` returns **every** fill a user made while they had approved your builder, including trades placed elsewhere and trades with no builder attached at all.

A user who approves your builder and then trades on another frontend appears here, and not in `builderFillsByTime`.
{% endhint %}

### Why you need this

Some fills can never carry a builder code, so they are invisible to `builderFillsByTime` no matter how the user trades:

* **Liquidations** — the fill is generated by the protocol, not by an order the user signed, so there is no builder to attach.
* **TWAP sub-fills** — the individual slices carry no builder code.

Attributing by *approval* rather than by *routing* captures both, so activity from your users stops disappearing from your numbers the moment it takes one of these paths.

{% hint style="warning" %}
The flip side: approval-based attribution reflects what a user **could** route through you, not what they did. A user who holds their own private key can trade directly or through another builder while your approval is still active, and those fills appear here. Treat this endpoint as "activity by users who approved me", not as "revenue routed through me" — for the latter, use [builderFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderfillsbytime).
{% endhint %}

## POST Request

<table><thead><tr><th width="180">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Required. <code>"builderApprovedFillsByTime"</code></td></tr><tr><td><code>builder</code></td><td>string</td><td>Required. Builder address, 42-char hex.</td></tr><tr><td><code>startTime</code></td><td>number</td><td>Required unless <code>cursor</code> is given. Inclusive, milliseconds.</td></tr><tr><td><code>endTime</code></td><td>number</td><td>Optional. Inclusive, milliseconds.</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Optional. Continue from a previous page. Format <code>"{time}_{txIndex}"</code>.</td></tr><tr><td><code>venue</code></td><td>string</td><td>Only fills on outcome markets deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; an unknown venue returns an empty list (optional)</td></tr><tr><td><code>limit</code></td><td>number</td><td>Optional. Default and maximum 2000.</td></tr></tbody></table>

Results are returned oldest-first, ordered by `(time, txIndex)`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "type": "builderApprovedFillsByTime",
    "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
    "startTime": 1786000000000,
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

resp = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "type": "builderApprovedFillsByTime",
        "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
        "startTime": 1786000000000,
        "limit": 100,
    },
)
fills = resp.json()
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const resp = await fetch("https://api.hydromancer.xyz/info", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": "YOUR_API_KEY" },
  body: JSON.stringify({
    type: "builderApprovedFillsByTime",
    builder: "0x1924b8561eef20e70ede628a296175d358be80e5",
    startTime: 1786000000000,
    limit: 100,
  }),
});
const fills = await resp.json();
```

{% endtab %}
{% endtabs %}

***

## Pagination

Take the last returned fill and build `cursor` as `"{time}_{txIndex}"`, then repeat the request with that `cursor` instead of `startTime`. A page shorter than `limit` means you have reached the end of the range.

## Semantics

An approval applies from the block it lands in, and a revocation likewise. A fill that happened while an approval was active stays attributed permanently — revoking does not remove past fills from this endpoint.

## Response Fields

An array of fill objects, each including the `user` that made the fill — the same shape as [builderFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderfillsbytime), plus a `builder` field.

The `builder` field is the builder the fill was **routed through**, which is a separate question from why the fill is in this response. It is usually `null`: liquidations and TWAP sub-fills carry no builder code, and a user who approved you can trade through anyone. `builderFillsByTime` does not return this field, because there every fill is routed through the builder you asked for.

<details>

<summary>Response</summary>

```json
[
  {
    "coin": "BTC",
    "px": "50000.0",
    "sz": "1.5",
    "side": "B",
    "time": 1786000001000,
    "startPosition": "0.0",
    "dir": "Open Long",
    "closedPnl": "0.0",
    "hash": "0x...",
    "oid": 12345,
    "crossed": false,
    "fee": "0.5",
    "tid": 20001,
    "feeToken": "USDC",
    "builder": null,
    "user": "0x0000000000000000000000000000000000000001",
    "txIndex": 0
  }
]
```

</details>


# builderApprovedFundingByTime

Hourly Hyperliquid funding payments made by users who had an active builder-fee approval for your builder address.

The funding counterpart of [builderApprovedFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovedfillsbytime): every hourly funding payment made by a user while they had approved your builder, across all of those users at once. Each row is exactly a [userFunding](https://hydromancer.xyz/docs/rest-api/historical-data/userfunding) row with the paying `user` added.

{% hint style="info" %}
**Attribution is by approval, not by routing.** A funding payment has no builder code and no order behind it — it is charged by the protocol once an hour on every open position — so it can only be attributed by asking who the user had approved at that block. A user who approved your builder and then opened a position through another frontend still appears here.
{% endhint %}

### Why you need this

Funding is often the largest recurring cost or income for a perp position, and it is invisible to every routing-based endpoint. If you report net PnL for the users who approved you, fills alone overstate it; this endpoint supplies the missing leg without you having to poll `userFunding` per user.

## POST Request

<table><thead><tr><th width="180">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Required. <code>"builderApprovedFundingByTime"</code></td></tr><tr><td><code>builder</code></td><td>string</td><td>Required. Builder address, 42-char hex.</td></tr><tr><td><code>startTime</code></td><td>number</td><td>Required unless <code>cursor</code> is given. Inclusive, milliseconds.</td></tr><tr><td><code>endTime</code></td><td>number</td><td>Optional. Inclusive, milliseconds.</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Optional. Continue from a previous page. Format <code>"{time}_{user}_{coin}"</code>.</td></tr><tr><td><code>limit</code></td><td>number</td><td>Optional. Default and maximum 2000.</td></tr></tbody></table>

Results are returned oldest-first, ordered by `(time, user, coin)`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "type": "builderApprovedFundingByTime",
    "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
    "startTime": 1786000000000,
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

resp = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "type": "builderApprovedFundingByTime",
        "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
        "startTime": 1786000000000,
        "limit": 100,
    },
)
funding = resp.json()
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const resp = await fetch("https://api.hydromancer.xyz/info", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": "YOUR_API_KEY" },
  body: JSON.stringify({
    type: "builderApprovedFundingByTime",
    builder: "0x1924b8561eef20e70ede628a296175d358be80e5",
    startTime: 1786000000000,
    limit: 100,
  }),
});
const funding = await resp.json();
```

{% endtab %}
{% endtabs %}

***

## Pagination

Take the last returned row and build `cursor` as `"{time}_{user}_{delta.coin}"`, then repeat the request with that `cursor` instead of `startTime`. A page shorter than `limit` means you have reached the end of the range.

Funding is charged once an hour, and every payment of that hour carries the same `time`, so a page boundary usually falls **inside** an hour. That is why the cursor carries `user` and `coin` rather than a transaction index: it resumes exactly after the last row you saw without repeating or skipping the rest of the hour.

## Semantics

* **Hourly rows.** One row per `(user, coin)` position per funding hour, with the block timestamp of the funding event as `time`. There are no rows between funding hours.
* **Attributed at the block.** An approval applies from the block it lands in, and a revocation likewise. A payment that happened while an approval was active stays attributed permanently — revoking does not remove past rows from this endpoint.
* **Same row as `userFunding`.** `time`, `hash` and `delta` are byte-for-byte what [userFunding](https://hydromancer.xyz/docs/rest-api/historical-data/userfunding) returns for that user; only `user` is added. `hash` is always the zero hash, as it is there, because funding is a protocol event with no transaction.

## Response Fields

| Field               | Type   | Description                                                                               |
| ------------------- | ------ | ----------------------------------------------------------------------------------------- |
| `user`              | string | The user who paid or received the funding, and who had approved your builder at the time. |
| `time`              | int    | Funding block timestamp (ms).                                                             |
| `hash`              | string | Always the zero hash.                                                                     |
| `delta`             | object | Funding payment details, identical to `userFunding`.                                      |
| `delta.type`        | string | Always `"funding"`.                                                                       |
| `delta.coin`        | string | Asset symbol.                                                                             |
| `delta.usdc`        | string | USDC amount of the funding payment (negative when paid).                                  |
| `delta.szi`         | string | Position size at the time of funding.                                                     |
| `delta.fundingRate` | string | Funding rate applied.                                                                     |

<details>

<summary>Response</summary>

```json
[
  {
    "user": "0x0000000000000000000000000000000000000001",
    "time": 1786000000066,
    "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "delta": {
      "type": "funding",
      "coin": "BTC",
      "usdc": "0.014419",
      "szi": "-0.01",
      "fundingRate": "0.0000125"
    }
  }
]
```

</details>


# builderApprovedNonFundingLedgerUpdatesByTime

Hyperliquid deposits, withdrawals, transfers and other non-funding ledger updates made by users who had an active builder-fee approval for your builder address.

The ledger counterpart of [builderApprovedFillsByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovedfillsbytime): every non-funding ledger update — deposits, withdrawals, transfers, vault flows, liquidations and the rest — made by a user while they had approved your builder, across all of those users at once. Each row is exactly a [userNonFundingLedgerUpdates](https://hydromancer.xyz/docs/rest-api/historical-data/usernonfundingledgerupdates) row with the `user` it was attributed to, their `role`, and the `txIndex` needed to page added.

{% hint style="info" %}
**Attribution is by approval, not by routing.** Ledger updates carry no builder code, so the only way to attribute one is to ask who the user had approved at that block. A deposit made through any frontend by a user who had approved your builder appears here.
{% endhint %}

### Why you need this

Deposits and withdrawals are the earliest and latest signals you have about a user: a first deposit precedes any fill, and a withdrawal often precedes churn. Funding aside, this is the rest of the money movement for the users who approved you, without polling `userNonFundingLedgerUpdates` per user.

## POST Request

<table><thead><tr><th width="180">Field</th><th width="110">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Required. <code>"builderApprovedNonFundingLedgerUpdatesByTime"</code></td></tr><tr><td><code>builder</code></td><td>string</td><td>Required. Builder address, 42-char hex.</td></tr><tr><td><code>startTime</code></td><td>number</td><td>Required unless <code>cursor</code> is given. Inclusive, milliseconds.</td></tr><tr><td><code>endTime</code></td><td>number</td><td>Optional. Inclusive, milliseconds.</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Optional. Continue from a previous page. Format <code>"{time}_{txIndex}_{user}_{role}"</code>.</td></tr><tr><td><code>limit</code></td><td>number</td><td>Optional. Default and maximum 2000.</td></tr></tbody></table>

Results are returned oldest-first, ordered by `(time, txIndex, user, role)`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "type": "builderApprovedNonFundingLedgerUpdatesByTime",
    "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
    "startTime": 1786000000000,
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

resp = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "type": "builderApprovedNonFundingLedgerUpdatesByTime",
        "builder": "0x1924b8561eef20e70ede628a296175d358be80e5",
        "startTime": 1786000000000,
        "limit": 100,
    },
)
updates = resp.json()
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
const resp = await fetch("https://api.hydromancer.xyz/info", {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": "YOUR_API_KEY" },
  body: JSON.stringify({
    type: "builderApprovedNonFundingLedgerUpdatesByTime",
    builder: "0x1924b8561eef20e70ede628a296175d358be80e5",
    startTime: 1786000000000,
    limit: 100,
  }),
});
const updates = await resp.json();
```

{% endtab %}
{% endtabs %}

***

## Pagination

Take the last returned row and build `cursor` as `"{time}_{txIndex}_{user}_{role}"`, then repeat the request with that `cursor` instead of `startTime`. A page shorter than `limit` means you have reached the end of the range.

Several updates land in one block and share `time`, and a self-transfer even shares `txIndex` and `user` across its two rows, so the cursor carries all four parts: it resumes exactly after the last row you saw without repeating or skipping the rest of the block.

## Semantics

* **One row per participating approving user.** A transfer names two users, and each is attributed independently. If the sender approved you, you get their row with `role: "sender"`; if the receiver approved you, you get theirs with `role: "receiver"`; if both did, you get both. `delta` is what `userNonFundingLedgerUpdates` shows that participant: `user` is always the sender and `destination` the receiver on either row, and the fee appears on the sender's row only — `role` is what tells you which side the row is for. Single-party updates such as deposits carry `role: "user"`.
* **Attributed at the block.** An approval applies from the block it lands in, and a revocation likewise. An update that happened while an approval was active stays attributed permanently — revoking does not remove past rows from this endpoint.
* **Same row as `userNonFundingLedgerUpdates`.** `time`, `hash` and `delta` are byte-for-byte what [userNonFundingLedgerUpdates](https://hydromancer.xyz/docs/rest-api/historical-data/usernonfundingledgerupdates) returns for that user; only `user`, `role` and `txIndex` are added. Funding is excluded here exactly as it is there — use [builderApprovedFundingByTime](https://hydromancer.xyz/docs/rest-api/historical-data/builderapprovedfundingbytime) for it.

## Response Fields

| Field     | Type   | Description                                                                                                                                                                                                              |
| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `user`    | string | The participant this row is attributed to, who had approved your builder at the time.                                                                                                                                    |
| `role`    | string | `"user"` for single-party updates; `"sender"` or `"receiver"` for the side of a transfer this row is for.                                                                                                                |
| `time`    | int    | Block timestamp (ms).                                                                                                                                                                                                    |
| `txIndex` | int    | Position of the update within its block. Needed only to build `cursor`.                                                                                                                                                  |
| `hash`    | string | Transaction hash.                                                                                                                                                                                                        |
| `delta`   | object | Ledger update details, identical to `userNonFundingLedgerUpdates`. Fields vary by `delta.type`; see [that page](https://hydromancer.xyz/docs/rest-api/historical-data/usernonfundingledgerupdates) for every delta type. |

<details>

<summary>Response</summary>

```json
[
  {
    "user": "0x0000000000000000000000000000000000000001",
    "role": "user",
    "time": 1786000001000,
    "txIndex": 0,
    "hash": "0xdc02464296095090dd7c04304bdac40205640028310c6f627fcaf195550d2a7b",
    "delta": {
      "type": "deposit",
      "usdc": "1000.50"
    }
  },
  {
    "user": "0x0000000000000000000000000000000000000002",
    "role": "receiver",
    "time": 1786000002000,
    "txIndex": 3,
    "hash": "0x9d3f0a2c4b6e8f1a3c5e7a9b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f",
    "delta": {
      "type": "internalTransfer",
      "usdc": "25.00",
      "user": "0x0000000000000000000000000000000000000001",
      "destination": "0x0000000000000000000000000000000000000002",
      "fee": "0.00"
    }
  }
]
```

</details>


# userFunding

Get a user's Hyperliquid funding payment history.

{% hint style="info" %}
**Data available from 28-07-2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="107.333251953125">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userFunding"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>int</td><td>Start time in ms (inclusive)</td></tr><tr><td><code>endTime</code></td><td>int</td><td>End time in ms (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userFunding",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userFunding',
        'user': '0x0000000000000000000000000000000000000000',
        'startTime': 0
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userFunding',
        user: '0x0000000000000000000000000000000000000000',
        startTime: 0
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field               | Type   | Description                                |
| ------------------- | ------ | ------------------------------------------ |
| `time`              | int    | Timestamp (ms)                             |
| `hash`              | string | Transaction hash                           |
| `delta`             | object | Funding payment details                    |
| `delta.type`        | string | Always `"funding"`                         |
| `delta.coin`        | string | Asset symbol                               |
| `delta.usdc`        | string | USDC amount of funding payment             |
| `delta.szi`         | string | Position size at time of funding           |
| `delta.fundingRate` | string | Funding rate applied                       |
| `delta.nSamples`    | int    | Number of samples (null if not applicable) |

<details>

<summary>Response</summary>

```json
[
    {
        "time": 1754064000066,
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "delta": {
            "type": "funding",
            "coin": "BTC",
            "usdc": "0.014419",
            "szi": "-0.01",
            "fundingRate": "0.0000125",
            "nSamples": null
        }
    }
]
```

</details>


# fundingHistory

Get the Hyperliquid funding history for a coin.

{% hint style="info" %}
**Data available from 28-07-2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="107.333251953125">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"fundingHistory"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>i.e. "BTC", "ETH"</td></tr><tr><td><code>startTime</code></td><td>int</td><td>Start time in ms (inclusive)</td></tr><tr><td><code>endTime</code></td><td>int</td><td>End time in ms (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>Max results to return, default and max 500 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "fundingHistory",
    "coin": "BTC",
    "startTime": 0
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'fundingHistory',
        'coin': 'BTC',
        'startTime': 0
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'fundingHistory',
        coin: 'BTC',
        startTime: 0
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field         | Type   | Description                 |
| ------------- | ------ | --------------------------- |
| `coin`        | string | Asset symbol                |
| `fundingRate` | string | Funding rate for the period |
| `time`        | int    | Timestamp (ms)              |

<details>

<summary>Response</summary>

```json
[
    {
        "coin": "BTC",
        "fundingRate": "0.0000125",
        "time": 1762398000007
    },
    {
        "coin": "BTC",
        "fundingRate": "0.0000125",
        "time": 1762401600087
    }
]
```

</details>

## Structured errors

Send `X-HM-Error-Format: structured-v1` to select errors with `error`, `code`, and `correlationId`. Applied responses echo the selector. Missing echo is unconfirmed and must not trigger replay. Only fundingHistory and POST /auth/token support this format initially. Other legacy modes return 406 after authentication and permission, before admission, with configured billing. Funding history keeps potentially incomplete 200 results after cache failure. Required ClickHouse failure is selected 503/unavailable and legacy 500. Hydromancer omits Hyperliquid's premium field. The SDK's `RestClient.call_structured` returns validated data with raw response evidence; explicit downgrade accepts only the response already received.


# liquidationHistoryByTime

Get historical Hyperliquid liquidation events for a coin or market-wide.

Get [historical liquidation events](https://hydromancer.xyz/hyperliquid-liquidations), for a single coin or across all markets. The most recent events are returned first.

{% hint style="info" %}
**All data is fully available from 28-07-2025. Hydromancer performed a full backfill of fills offered by the native Hyperliquid API. The result includes full historical data for most traders, except some very high-volume addresses. TWAP fills are included from 02-08-2025.**
{% endhint %}

## POST Request

<table><thead><tr><th width="120">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"liquidationHistoryByTime"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>i.e. "BTC", "ETH", or a HIP-3 market like "xyz:JPY". Omit for market-wide (optional)</td></tr><tr><td><code>startTime</code></td><td>int</td><td>Start time in ms, inclusive (optional)</td></tr><tr><td><code>endTime</code></td><td>int</td><td>End time in ms, inclusive (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>Max results to return, default 500, max 1000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "liquidationHistoryByTime",
    "coin": "BTC"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'liquidationHistoryByTime',
        'coin': 'BTC'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'liquidationHistoryByTime',
        coin: 'BTC'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Each event is the liquidated user's fill. `side` is `"A"` when a long was liquidated (forced sell) and `"B"` when a short was liquidated (forced buy).

| Field           | Type    | Description                                                                                                                                                                    |
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `coin`          | string  | Asset symbol                                                                                                                                                                   |
| `user`          | string  | Address that was liquidated                                                                                                                                                    |
| `px`            | string  | Fill price                                                                                                                                                                     |
| `sz`            | string  | Fill size                                                                                                                                                                      |
| `side`          | string  | `"A"` = long liquidated, `"B"` = short liquidated                                                                                                                              |
| `time`          | int     | Timestamp (ms)                                                                                                                                                                 |
| `startPosition` | string  | Position size before the fill                                                                                                                                                  |
| `dir`           | string  | Direction, e.g. `"Close Long"`                                                                                                                                                 |
| `closedPnl`     | string  | Realized PnL on the fill                                                                                                                                                       |
| `hash`          | string  | Transaction hash                                                                                                                                                               |
| `oid`           | int     | Order id                                                                                                                                                                       |
| `crossed`       | bool    | Whether the fill crossed the book                                                                                                                                              |
| `fee`           | string  | Fee paid                                                                                                                                                                       |
| `tid`           | int     | Trade id                                                                                                                                                                       |
| `cloid`         | string? | Client order ID (optional)                                                                                                                                                     |
| `builderFee`    | string? | Builder fee (optional)                                                                                                                                                         |
| `deployerFee`   | string? | Deployer fee (optional, HIP-3 fills only)                                                                                                                                      |
| `priorityGas`   | string? | Priority gas fee in HYPE (optional)                                                                                                                                            |
| `feeToken`      | string  | Token the fee was paid in                                                                                                                                                      |
| `builder`       | string? | Builder address (optional)                                                                                                                                                     |
| `subBuilders`   | array?  | Sub-builders sharing `builderFee`, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `twapId`        | int?    | TWAP order ID (null if not a TWAP fill)                                                                                                                                        |
| `liquidation`   | object  | Liquidation detail (see below)                                                                                                                                                 |
| `txIndex`       | int     | Intra-block ordering index                                                                                                                                                     |

`liquidation` object:

| Field            | Type   | Description                                                                                                          |
| ---------------- | ------ | -------------------------------------------------------------------------------------------------------------------- |
| `liquidatedUser` | string | Address that was liquidated                                                                                          |
| `markPx`         | string | Mark price at liquidation                                                                                            |
| `method`         | string | `"market"` (closed against the order book) or `"backstop"` (absorbed by the backstop liquidator at bankruptcy price) |

<details>

<summary>Response</summary>

```json
[
    {
        "coin": "BTC",
        "px": "50000.00",
        "sz": "1.0",
        "side": "A",
        "time": 1762398000007,
        "startPosition": "1.0",
        "dir": "Close Long",
        "closedPnl": "-1200.00",
        "hash": "0x1234567890abcdef",
        "oid": 123456,
        "crossed": true,
        "fee": "25.00",
        "tid": 789012,
        "cloid": null,
        "builderFee": null,
        "deployerFee": null,
        "priorityGas": null,
        "feeToken": "USDC",
        "builder": null,
        "twapId": null,
        "user": "0xabc...",
        "liquidation": {
            "liquidatedUser": "0xabc...",
            "markPx": "50000.00",
            "method": "market"
        },
        "txIndex": 12
    }
]
```

</details>


# liquidationBuckets

Get grouped long and short liquidation totals in up to 200 UTC periods.

Returns historical liquidation totals for one perpetual market, including HIP-3. Send an authenticated `POST /info` using your normal bearer API key.

| Field         | Type    | Meaning                                                                                       |
| ------------- | ------- | --------------------------------------------------------------------------------------------- |
| `type`        | string  | `"liquidationBuckets"`                                                                        |
| `coin`        | string  | Required, case-sensitive: e.g. `"BTC"` or `"xyz:NVDA"`. Spot/outcome markets are unsupported. |
| `granularity` | string  | Required: `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`.                                         |
| `startTime`   | integer | Optional Unix milliseconds selecting the first containing bucket.                             |
| `endTime`     | integer | Optional Unix milliseconds selecting the last containing bucket, inclusive.                   |

| Supplied times | Selection                                               |
| -------------- | ------------------------------------------------------- |
| Neither        | Most recent 200 periods, including the current period.  |
| End only       | 200 periods ending in the end timestamp's bucket.       |
| Start only     | 200 periods commencing in the start timestamp's bucket. |
| Both           | Start through end buckets, capped at the first 200.     |

Times must be nonnegative JSON integers in **milliseconds**; there is no seconds conversion. Null, strings, floats, booleans and reversed ranges are invalid. Inputs and the complete derived query window must fit `1970-01-01T00:00:00.000Z` through `2299-12-31T23:59:59.999Z`. A derived start before the Unix epoch is clamped to zero.

Buckets align to UTC and include **whole periods**. At `5m`, start 12:03 and end 12:11 select 12:00, 12:05 and 12:10, covering `[12:00, 12:15)`. End exactly at 12:10 includes that whole bucket.

```json
{
  "type": "liquidationBuckets",
  "coin": "BTC",
  "granularity": "1m",
  "startTime": 1767225600000,
  "endTime": 1767225660000
}
```

## Response

An oldest-first array with these fields per bucket:

| Field                         | Type    | Meaning                                           |
| ----------------------------- | ------- | ------------------------------------------------- |
| `ts`                          | integer | UTC bucket start in Unix milliseconds.            |
| `longLiquidationNotionalUsd`  | string  | Exact USD notional of forced sells closing longs. |
| `shortLiquidationNotionalUsd` | string  | Exact USD notional of forced buys closing shorts. |
| `longLiquidationCount`        | integer | Grouped long liquidation executions.              |
| `shortLiquidationCount`       | integer | Grouped short liquidation executions.             |

Counts group fills by liquidated user, original millisecond timestamp and order ID within the market. Four fills of one execution count once; all four contribute notional. Counts are not distinct accounts or entire multi-order liquidation cycles. Market and backstop liquidations are included; notionals have up to 20 fractional places.

**Quiet periods remain in the response**, with `"0"` notionals and zero counts. A 200-period query returns all 200 rows even when the market has no liquidations. Only a shorter explicit range or the Unix-epoch boundary reduces the row count. Unknown perpetual names also return zeros; names are not uppercased or aliased.

The current bucket is incomplete, and historical writes can arrive late. Zeros mean no matching stored rows, not proof of complete ingestion. Read failures return an error; they never become successful empty or zero-filled fallback data.

Continue with `startTime = last_ts + period_ms`, retaining the original end for a bounded range. Stop once the next start exceeds the desired final bucket. No cursor, caller-controlled bucket limit, page number or `interval` alias is used.

## Python SDK

```python
from hydromancer_sdk import RestClient

client = RestClient(api_key="YOUR_API_KEY")
buckets = await client.liquidation_buckets(
    "BTC", "1m", start_time=1767225600000, end_time=1767225660000
)
```

Returns `list[LiquidationBucket]`. Generic `call("liquidationBuckets", ...)` is also typed; `call_structured(...)` additionally retains response headers/evidence.

## Errors and cost

This method defaults to `structured-v1` after authentication/method identification. Errors contain `error`, `code` and `correlationId`: invalid inputs return `400 invalid_request`, history/resource failures `503 unavailable`, and internal failures `500 internal`. Existing auth/rate limits apply; selector-free auth rejection retains the normal legacy 401. Admission costs **five points**.


# userNonFundingLedgerUpdates

Get a user's Hyperliquid non-funding ledger updates.

{% hint style="info" %}
**Data available from 28-07-2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="107.333251953125">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userNonFundingLedgerUpdates"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>int</td><td>Start time in ms (inclusive)</td></tr><tr><td><code>endTime</code></td><td>int</td><td>End time in ms (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userNonFundingLedgerUpdates",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userNonFundingLedgerUpdates',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userNonFundingLedgerUpdates',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                  | Type   | Description                                                                             |
| ---------------------- | ------ | --------------------------------------------------------------------------------------- |
| `time`                 | int    | Timestamp (ms)                                                                          |
| `hash`                 | string | Transaction hash                                                                        |
| `delta`                | object | Ledger update details (fields vary by `delta.type`, see delta types below)              |
| `delta.type`           | string | Type of ledger update (e.g. `"send"`, `"deposit"`, `"withdraw"`, `"liquidation"`, etc.) |
| `delta.amount`         | string | Transfer amount (present on most delta types)                                           |
| `delta.token`          | string | Token symbol                                                                            |
| `delta.usdc`           | string | USDC amount (used by some delta types instead of `amount`)                              |
| `delta.usdcValue`      | string | USD value of the transfer                                                               |
| `delta.user`           | string | Sender/source user address                                                              |
| `delta.destination`    | string | Destination address                                                                     |
| `delta.destinationDex` | string | Destination DEX (e.g. `"spot"`)                                                         |
| `delta.sourceDex`      | string | Source DEX (e.g. `"spot"`)                                                              |
| `delta.fee`            | string | Fee amount                                                                              |
| `delta.feeToken`       | string | Fee token symbol                                                                        |
| `delta.nativeTokenFee` | string | Native token fee amount                                                                 |
| `delta.nonce`          | int    | Transaction nonce (null if not applicable)                                              |

<details>

<summary>Response</summary>

```json
[
    {
        "time": 1764256235694,
        "hash": "0xdc02464296095090dd7c04304bdac40205640028310c6f627fcaf195550d2a7b",
        "delta": {
            "amount": "0.00710881",
            "destination": "0x0000000000000000000000000000000000000000",
            "destinationDex": "spot",
            "fee": "",
            "feeToken": "",
            "nativeTokenFee": "",
            "nonce": null,
            "sourceDex": "spot",
            "token": "LIQUID",
            "type": "send",
            "usdcValue": "0.001473",
            "user": "0x9eff7b0c989f52003c0868b5353290d277196e6d"
        }
    }
]
```

</details>

<details>

<summary>All possible delta types</summary>

**withdraw**

```json
{
  "type": "withdraw",
  "usdc": "1000.0",
  "nonce": 12345,
  "fee": "1.5"
}
```

**deposit**

```json
{
  "type": "deposit",
  "usdc": "1000.0"
}
```

**vaultCreate**

```json
{
  "type": "vaultCreate",
  "vault": "0x...",
  "usdc": "10000.0",
  "fee": "10.0"
}
```

**vaultDeposit**

```json
{
  "type": "vaultDeposit",
  "vault": "0x...",
  "usdc": "5000.0"
}
```

**vaultWithdraw**

```json
{
  "type": "vaultWithdraw",
  "vault": "0x...",
  "user": "0x...",
  "requestedUsd": "1000.0",
  "commission": "10.0",
  "closingCost": "5.0",
  "basis": "995.0",
  "netWithdrawnUsd": "985.0"
}
```

**vaultDistribution**

```json
{
  "type": "vaultDistribution",
  "vault": "0x...",
  "usdc": "100.0"
}
```

**vaultLeaderCommission**

```json
{
  "type": "vaultLeaderCommission",
  "user": "0x...",
  "usdc": "50.0"
}
```

**liquidation**

```json
{
  "type": "liquidation",
  "liquidatedNtlPos": "10000.0",
  "accountValue": "-500.0",
  "leverageType": "Cross",
  "liquidatedPositions": [
    {
      "coin": "ETH",
      "szi": "-5.0"
    }
  ]
}
```

**internalTransfer**

```json
{
  "type": "internalTransfer",
  "usdc": "1000.0",
  "user": "0x...",
  "destination": "0x...",
  "fee": "0.0"
}
```

**subAccountTransfer**

```json
{
  "type": "subAccountTransfer",
  "usdc": "500.0",
  "user": "0x...",
  "destination": "0x..."
}
```

**spotTransfer**

```json
{
  "type": "spotTransfer",
  "token": "USDC",
  "amount": "1000.0",
  "usdcValue": "1000.0",
  "user": "0x...",
  "destination": "0x...",
  "fee": "1.5",
  "nativeTokenFee": "0.1",
  "nonce": 12345,
  "feeToken": "USDC"
}
```

**spotGenesis**

```json
{
  "type": "spotGenesis",
  "token": "HYPE",
  "amount": "1000000.0"
}
```

**rewardsClaim**

```json
{
  "type": "rewardsClaim",
  "amount": "100.0",
  "token": "USDC"
}
```

**accountClassTransfer**

```json
{
  "type": "accountClassTransfer",
  "usdc": "1000.0",
  "toPerp": true
}
```

**accountActivationGas**

```json
{
  "type": "accountActivationGas",
  "amount": "0.1",
  "token": "ETH"
}
```

**perpDexClassTransfer**

```json
{
  "type": "perpDexClassTransfer",
  "amount": "1000.0",
  "token": "USDC",
  "dex": "hyperliquid",
  "toPerp": true
}
```

**deployGasAuction**

```json
{
  "type": "deployGasAuction",
  "token": "ETH",
  "amount": "0.5"
}
```

**cStakingTransfer**

```json
{
  "type": "cStakingTransfer",
  "amount": "1000.0",
  "isDeposit": true,
  "token": "HYPE"
}
```

**send**

```json
{
  "type": "send",
  "amount": "100.0",
  "destination": "0x...",
  "destinationDex": "",
  "fee": "1.0",
  "feeToken": "USDC",
  "nativeTokenFee": "0.1",
  "nonce": 12345,
  "sourceDex": "",
  "token": "USDC",
  "usdcValue": "100.0",
  "user": "0x..."
}
```

**activateDexAbstraction**

```json
{
  "type": "activateDexAbstraction",
  "dex": "hyperliquid",
  "token": "USDC",
  "amount": "10.0"
}
```

**borrowLend**

```json
{
  "type": "borrowLend",
  "token": "USDC",
  "operation": "supply",
  "amount": "5000.0",
  "interestAmount": "12.5"
}
```

**borrowLendBackstopLiquidation**

```json
{
  "type": "borrowLendBackstopLiquidation",
  "token": "USDC",
  "balanceChange": "-500.0"
}
```

</details>


# historicalOrders

Get the 2000 latest Hyperliquid order status updates of a user.

{% hint style="info" %}
**Data available from 7th of Aug 2025**
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"historicalOrders"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return, default and max 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "historicalOrders",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'historicalOrders',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'historicalOrders',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                    | Type    | Description                                                                                                                                                                       |
| ------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `builder`                | string  | Builder address if order was placed via builder (optional)                                                                                                                        |
| `builderFee`             | int     | Builder fee in basis points (optional)                                                                                                                                            |
| `subBuilders`            | array?  | Sub-builders sharing the builder fee, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `txIndex`                | int     | Transaction index                                                                                                                                                                 |
| `order`                  | object  | Order details (see Order Object below)                                                                                                                                            |
| `status`                 | string  | Order status (see status values below)                                                                                                                                            |
| `statusTimestamp`        | int     | Timestamp of status update in milliseconds                                                                                                                                        |
| `order.coin`             | string  | Asset symbol                                                                                                                                                                      |
| `order.side`             | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                       |
| `order.limitPx`          | string  | Limit price                                                                                                                                                                       |
| `order.sz`               | string  | Order size                                                                                                                                                                        |
| `order.oid`              | int     | Order ID                                                                                                                                                                          |
| `order.timestamp`        | int     | Order creation timestamp in milliseconds                                                                                                                                          |
| `order.triggerCondition` | string  | Trigger condition if applicable                                                                                                                                                   |
| `order.isTrigger`        | boolean | Whether order is a trigger order                                                                                                                                                  |
| `order.triggerPx`        | string  | Trigger price                                                                                                                                                                     |
| `order.children`         | array   | Child orders for take profit/stop loss orders                                                                                                                                     |
| `order.isPositionTpsl`   | boolean | Whether order is position TP/SL                                                                                                                                                   |
| `order.reduceOnly`       | boolean | Whether order is reduce-only                                                                                                                                                      |
| `order.orderType`        | string  | Order type (e.g. `"Limit"`, `"Market"`)                                                                                                                                           |
| `order.origSz`           | string  | Original order size                                                                                                                                                               |
| `order.tif`              | string  | Time in force, e.g. `"Gtc"`, `"Ioc"`, `"Alo"` (optional)                                                                                                                          |
| `order.cloid`            | string  | Client order ID (optional)                                                                                                                                                        |

<details>

<summary>Response</summary>

```json
[
  {
    "builder": "0x...", // optional
    "builderFee": 100, // optional
    "txIndex": 12,
    "order": {
      "coin": "BTC",
      "side": "B",
      "limitPx": "45000.00",
      "sz": "0.5",
      "oid": 123456,
      "timestamp": 1234567890123,
      "triggerCondition": "tp",
      "isTrigger": false,
      "triggerPx": "0.00",
      "children": [],
      "isPositionTpsl": false,
      "reduceOnly": false,
      "orderType": "Limit",
      "origSz": "0.5",
      "tif": "Gtc", // optional
      "cloid": "client-order-123" // optional
    },
    "status": "filled",
    "statusTimestamp": 1234567890123
  }
]
```

</details>

<details>

<summary>Status values</summary>

**Active:**

* `open` - Order is resting on the orderbook
* `triggered` - Stop/trigger order was triggered
* `scheduledCancel` - Order is scheduled for cancellation

**Filled:**

* `filled` - Order completely filled

**Canceled:**

* `canceled` - Canceled by user
* `marginCanceled` - Insufficient margin
* `liquidatedCanceled` - Position was liquidated
* `delistedCanceled` - Asset was delisted
* `reduceOnlyCanceled` - Reduce-only order canceled (no position)
* `selfTradeCanceled` - Would have resulted in self-trade
* `siblingFilledCanceled` - Sibling TP/SL order filled
* `vaultWithdrawalCanceled` - Vault withdrawal triggered cancellation
* `openInterestCapCanceled` - Open interest cap reached

**Rejected:**

* `badAloPxRejected` - ALO price would cross the book
* `iocCancelRejected` - IOC order couldn't fill
* `reduceOnlyRejected` - Reduce-only order rejected
* `oracleRejected` - Oracle price check failed
* `perpMarginRejected` - Insufficient perp margin
* `perpMaxPositionRejected` - Max position size exceeded
* `openInterestIncreaseRejected` - Open interest increase rejected
* `positionFlipAtOpenInterestCapRejected` - Position flip at OI cap rejected
* `positionIncreaseAtOpenInterestCapRejected` - Position increase at OI cap rejected
* `tooAggressiveAtOpenInterestCapRejected` - Too aggressive at OI cap
* `minTradeNtlRejected` - Below minimum trade notional
* `insufficientSpotBalanceRejected` - Insufficient spot balance

</details>


# orderStatusByOid

Get the latest status snapshot of a single Hyperliquid order by oid or cloid.

Look up the latest status of a single order, identified by `(user, oid)` or `(user, cloid)`. Returns a single snapshot object reflecting the most recent transition for that order, or `null` if the order is not in our index.

{% hint style="info" %}
**Data available from \~90 days back** for orders with terminal status (`filled`, `triggered`), and from the last 3 days for orders in any other status (`open`, `canceled`, all rejection variants, etc.). Older non-terminal transitions are pruned by TTL.
{% endhint %}

{% hint style="info" %}
The Hydromancer endpoint covers every wallet uniformly back to the 90-day terminal-retention boundary, regardless of order volume.
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"orderStatusByOid"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>oid</code></td><td>integer</td><td>Order ID (unsigned 64-bit integer). Provide exactly one of <code>oid</code> or <code>cloid</code>.</td></tr><tr><td><code>cloid</code></td><td>string</td><td>Client order ID. Provide exactly one of <code>oid</code> or <code>cloid</code>.</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}
OID lookup:

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "orderStatusByOid",
    "user": "0x0000000000000000000000000000000000000000",
    "oid": 123456789
  }'
```

CLOID lookup:

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "orderStatusByOid",
    "user": "0x0000000000000000000000000000000000000000",
    "cloid": "0x000000334e48424f354c36373646384d"
  }'
```

{% endtab %}

{% tab title="Python" %}
OID lookup:

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'orderStatusByOid',
        'user': '0x0000000000000000000000000000000000000000',
        'oid': 123456789
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

CLOID lookup:

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'orderStatusByOid',
        'user': '0x0000000000000000000000000000000000000000',
        'cloid': '0x000000334e48424f354c36373646384d'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}
OID lookup:

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'orderStatusByOid',
        user: '0x0000000000000000000000000000000000000000',
        oid: 123456789
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

CLOID lookup:

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'orderStatusByOid',
        user: '0x0000000000000000000000000000000000000000',
        cloid: '0x000000334e48424f354c36373646384d'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns a **single order-snapshot object**, or JSON `null` when the `(user, oid)` or `(user, cloid)` is not found in our index. The response is **not** an array (unlike most other historical-data endpoints, which return an array).

| Field                    | Type    | Description                                                                                                                                                                       |
| ------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `builder`                | string  | Builder address if order was placed via builder (optional)                                                                                                                        |
| `builderFee`             | int     | Builder fee in basis points (optional)                                                                                                                                            |
| `subBuilders`            | array?  | Sub-builders sharing the builder fee, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `txIndex`                | int     | Transaction index of the latest status transition                                                                                                                                 |
| `order`                  | object  | Order details (see Order Object below)                                                                                                                                            |
| `status`                 | string  | Latest order status (see status values below)                                                                                                                                     |
| `statusTimestamp`        | int     | Timestamp of the latest status transition in milliseconds                                                                                                                         |
| `order.coin`             | string  | Asset symbol                                                                                                                                                                      |
| `order.side`             | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                       |
| `order.limitPx`          | string  | Limit price                                                                                                                                                                       |
| `order.sz`               | string  | Remaining order size (0 if fully filled)                                                                                                                                          |
| `order.oid`              | int     | Order ID                                                                                                                                                                          |
| `order.timestamp`        | int     | Order creation timestamp in milliseconds                                                                                                                                          |
| `order.triggerCondition` | string  | Trigger condition if applicable                                                                                                                                                   |
| `order.isTrigger`        | boolean | Whether order is a trigger order                                                                                                                                                  |
| `order.triggerPx`        | string  | Trigger price                                                                                                                                                                     |
| `order.children`         | array   | Child orders for take profit/stop loss orders                                                                                                                                     |
| `order.isPositionTpsl`   | boolean | Whether order is position TP/SL                                                                                                                                                   |
| `order.reduceOnly`       | boolean | Whether order is reduce-only                                                                                                                                                      |
| `order.orderType`        | string  | Order type (e.g. `"Limit"`, `"Market"`)                                                                                                                                           |
| `order.origSz`           | string  | Original order size — use `origSz - sz` for cumulative fill                                                                                                                       |
| `order.tif`              | string  | Time in force, e.g. `"Gtc"`, `"Ioc"`, `"Alo"` (optional)                                                                                                                          |
| `order.cloid`            | string  | Client order ID (optional)                                                                                                                                                        |

<details>

<summary>Response — hit (order found)</summary>

```json
{
  "builder": "0x...",
  "builderFee": 100,
  "txIndex": 1243,
  "order": {
    "coin": "BTC",
    "side": "B",
    "limitPx": "45000.00",
    "sz": "0.0",
    "oid": 123456789,
    "timestamp": 1234567890123,
    "triggerCondition": "N/A",
    "isTrigger": false,
    "triggerPx": "0.00",
    "children": [],
    "isPositionTpsl": false,
    "reduceOnly": false,
    "orderType": "Limit",
    "origSz": "0.5",
    "tif": "Gtc",
    "cloid": "0x000000334e48424f354c36373646384d"
  },
  "status": "filled",
  "statusTimestamp": 1234567890456
}
```

</details>

<details>

<summary>Response — miss (order not found)</summary>

```json
null
```

</details>

<details>

<summary>Status values</summary>

**Active:**

* `open` — Order is resting on the orderbook
* `triggered` — Stop/trigger order was triggered
* `scheduledCancel` — Order is scheduled for cancellation

**Filled:**

* `filled` — Order completely filled

**Canceled:**

* `canceled` — Canceled by user
* `marginCanceled` — Insufficient margin
* `liquidatedCanceled` — Position was liquidated
* `delistedCanceled` — Asset was delisted
* `reduceOnlyCanceled` — Reduce-only order canceled (no position)
* `selfTradeCanceled` — Would have resulted in self-trade
* `siblingFilledCanceled` — Sibling TP/SL order filled
* `vaultWithdrawalCanceled` — Vault withdrawal triggered cancellation
* `openInterestCapCanceled` — Open interest cap reached

**Rejected:**

* `badAloPxRejected` — ALO price would cross the book
* `iocCancelRejected` — IOC order couldn't fill
* `reduceOnlyRejected` — Reduce-only order rejected
* `oracleRejected` — Oracle price check failed
* `perpMarginRejected` — Insufficient perp margin
* `perpMaxPositionRejected` — Max position size exceeded
* `openInterestIncreaseRejected` — Open interest increase rejected
* `positionFlipAtOpenInterestCapRejected` — Position flip at OI cap rejected
* `positionIncreaseAtOpenInterestCapRejected` — Position increase at OI cap rejected
* `tooAggressiveAtOpenInterestCapRejected` — Too aggressive at OI cap
* `minTradeNtlRejected` — Below minimum trade notional
* `insufficientSpotBalanceRejected` — Insufficient spot balance

</details>

***

## Errors

| HTTP | Body                                                                                   | Cause                                             |
| ---- | -------------------------------------------------------------------------------------- | ------------------------------------------------- |
| 400  | `{"error":"Missing field: user"}`                                                      | `user` field absent from request                  |
| 400  | `{"error":"Invalid Ethereum address: ..."}`                                            | `user` is not a valid 0x-prefixed 42-char address |
| 400  | ``{"error":"Missing required field: provide either `oid` (u64) or `cloid` (string)"}`` | Neither `oid` nor `cloid` was provided            |
| 400  | ``{"error":"Provide exactly one of `oid` or `cloid`, not both"}``                      | Both `oid` and `cloid` were provided              |

A successful lookup that finds nothing returns HTTP 200 with body `null` — **not** a 404.


# builderOrdersByTime

Returns the Hyperliquid order status updates a builder sent within a time range.

{% hint style="info" %}
💧New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

{% hint style="info" %}
Historical data is available from August 7th, 2025. Users who had >100k orders between Aug 7 and Nov 4, 2025 will have only last 100k orders available. All orders are retained indefinitely going forward.
{% endhint %}

## POST Request

<table><thead><tr><th width="164.6666259765625">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"builderOrdersByTime"</code></td></tr><tr><td><code>builder</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Start timestamp in milliseconds (skipped when cursor is used)</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>End timestamp in milliseconds (optional, defaults to now)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of statusTimestamp and txIndex with "_" separator (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "builderOrdersByTime",
    "builder": "0x0000000000000000000000000000000000000000",
    "startTime": 1234567890000,
    "endTime": 1234567900000
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'builderOrdersByTime',
        'builder': '0x0000000000000000000000000000000000000000',
        'startTime': 1234567890000,
        'endTime': 1234567900000
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'builderOrdersByTime',
        builder: '0x0000000000000000000000000000000000000000',
        startTime: 1234567890000,
        endTime: 1234567900000
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                    | Type    | Description                                                                                                                                                                       |
| ------------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`                   | string  | User address who placed the order                                                                                                                                                 |
| `builderFee`             | int     | Builder fee in basis points                                                                                                                                                       |
| `subBuilders`            | array?  | Sub-builders sharing the builder fee, as `[{"b": "<address>", "s": <share>}]`; `s` is in 0.001% units (`30000` = 30%) and the builder keeps the rest. Omitted when there are none |
| `txIndex`                | int     | Transaction index                                                                                                                                                                 |
| `order`                  | object  | Order details (see Order Object below)                                                                                                                                            |
| `status`                 | string  | Order status (see status values below)                                                                                                                                            |
| `statusTimestamp`        | int     | Timestamp of status update in milliseconds                                                                                                                                        |
| `order.coin`             | string  | Asset symbol                                                                                                                                                                      |
| `order.side`             | string  | `"A"` (sell) or `"B"` (buy)                                                                                                                                                       |
| `order.limitPx`          | string  | Limit price                                                                                                                                                                       |
| `order.sz`               | string  | Order size                                                                                                                                                                        |
| `order.oid`              | int     | Order ID                                                                                                                                                                          |
| `order.timestamp`        | int     | Order creation timestamp in milliseconds                                                                                                                                          |
| `order.triggerCondition` | string  | Trigger condition if applicable                                                                                                                                                   |
| `order.isTrigger`        | boolean | Whether order is a trigger order                                                                                                                                                  |
| `order.triggerPx`        | string  | Trigger price                                                                                                                                                                     |
| `order.children`         | array   | Child orders for take profit/stop loss orders                                                                                                                                     |
| `order.isPositionTpsl`   | boolean | Whether order is position TP/SL                                                                                                                                                   |
| `order.reduceOnly`       | boolean | Whether order is reduce-only                                                                                                                                                      |
| `order.orderType`        | string  | Order type (e.g. `"Limit"`, `"Market"`)                                                                                                                                           |
| `order.origSz`           | string  | Original order size                                                                                                                                                               |
| `order.tif`              | string  | Time in force, e.g. `"Gtc"`, `"Ioc"`, `"Alo"` (optional)                                                                                                                          |
| `order.cloid`            | string  | Client order ID (optional, null if not set)                                                                                                                                       |

<details>

<summary>Response</summary>

```json
[
  {
    "user": "0x...",
    "builderFee": 100, // optional
    "txIndex": 12,
    "order": {
      "coin": "BTC",
      "side": "B",
      "limitPx": "45000.00",
      "sz": "0.5",
      "oid": 123456,
      "timestamp": 1234567890123,
      "triggerCondition": "tp",
      "isTrigger": false,
      "triggerPx": "0.00",
      "children": [],
      "isPositionTpsl": false,
      "reduceOnly": false,
      "orderType": "Limit",
      "origSz": "0.5",
      "tif": "Gtc", // optional
      "cloid": "client-order-123" // optional
    },
    "status": "filled",
    "statusTimestamp": 1234567890123
  }
]
```

</details>

<details>

<summary>Status values</summary>

**Active:**

* `open` - Order is resting on the orderbook
* `triggered` - Stop/trigger order was triggered
* `scheduledCancel` - Order is scheduled for cancellation

**Filled:**

* `filled` - Order completely filled

**Canceled:**

* `canceled` - Canceled by user
* `marginCanceled` - Insufficient margin
* `liquidatedCanceled` - Position was liquidated
* `delistedCanceled` - Asset was delisted
* `reduceOnlyCanceled` - Reduce-only order canceled (no position)
* `selfTradeCanceled` - Would have resulted in self-trade
* `siblingFilledCanceled` - Sibling TP/SL order filled
* `vaultWithdrawalCanceled` - Vault withdrawal triggered cancellation
* `openInterestCapCanceled` - Open interest cap reached

**Rejected:**

* `badAloPxRejected` - ALO price would cross the book
* `iocCancelRejected` - IOC order couldn't fill
* `reduceOnlyRejected` - Reduce-only order rejected
* `oracleRejected` - Oracle price check failed
* `perpMarginRejected` - Insufficient perp margin
* `perpMaxPositionRejected` - Max position size exceeded
* `openInterestIncreaseRejected` - Open interest increase rejected
* `positionFlipAtOpenInterestCapRejected` - Position flip at OI cap rejected
* `positionIncreaseAtOpenInterestCapRejected` - Position increase at OI cap rejected
* `tooAggressiveAtOpenInterestCapRejected` - Too aggressive at OI cap
* `minTradeNtlRejected` - Below minimum trade notional
* `insufficientSpotBalanceRejected` - Insufficient spot balance

</details>

<details>

<summary>Pagination</summary>

* When a cursor is provided, `startTime` is ignored
* Results are ordered by timestamp
* For pagination construct the cursor with the statusTimestamp and txIndex of the last order returned in the previous fetch like "cursor":"{statusTimestamp}\_{txIndex}"

</details>


# userLeverageUpdatesByTime

Paginate a Hyperliquid user's leverage change history by time, oldest-first.

Returns leverage updates (`updateLeverage` actions) for a user with `time` ≥ `startTime` (or after a `cursor`), ordered **oldest-first** by `time` then `tx_index`.

For pagination: pass `startTime` for the first page, then on each subsequent page pass the `cursor` `"{time}_{tx_index}"` built from the **last record** of the previous response. When `cursor` is supplied, `startTime` is ignored and the boundary record is excluded from the next page (no duplicates).

{% hint style="info" %}
New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

{% hint style="info" %}
This endpoint returns **leverage changes only**. The [userLeverageUpdates WebSocket channel](https://hydromancer.xyz/docs/websocket/leverage-and-margin-updates/userleverageupdates) additionally interleaves isolated-margin records for backward compatibility — for that history, use [userIsolatedMarginUpdatesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userisolatedmarginupdatesbytime). Record shapes match the WS channel's, so REST history and the live stream can be merged and deduplicated on `(time, tx_index)`.
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userLeverageUpdatesByTime"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Earliest <code>time</code> to include (Unix ms, inclusive). Skipped when <code>cursor</code> is used. Either <code>startTime</code> or <code>cursor</code> must be supplied</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>Latest <code>time</code> to include (Unix ms, inclusive). Default: now (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of <code>time</code> and <code>tx_index</code> with <code>"_"</code> separator (e.g. <code>"1734571490123_12"</code>). Take from the <strong>last record</strong> of the previous response (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return. Default 100, max 500 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
# First page
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userLeverageUpdatesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0,
    "limit": 100
  }'

# Next page — cursor built from the last record of the previous response
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userLeverageUpdatesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "cursor": "1734571490123_12",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

url = 'https://api.hydromancer.xyz/info'
headers = {
    'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
    'Content-Type': 'application/json',
}
user = '0x0000000000000000000000000000000000000000'
limit = 500

params = {'type': 'userLeverageUpdatesByTime', 'user': user, 'startTime': 0, 'limit': limit}
while True:
    page = requests.post(url, json=params, headers=headers).json()
    if not page:
        break
    for update in page:
        ...  # process leverage update
    if len(page) < limit:
        break
    last = page[-1]
    params = {
        'type': 'userLeverageUpdatesByTime',
        'user': user,
        'cursor': f"{last['time']}_{last['tx_index']}",
        'limit': limit,
    }
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const url = 'https://api.hydromancer.xyz/info';
const headers = {
    'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
    'Content-Type': 'application/json',
};
const user = '0x0000000000000000000000000000000000000000';
const limit = 500;

let params = { type: 'userLeverageUpdatesByTime', user, startTime: 0, limit };
while (true) {
    const { data: page } = await axios.post(url, params, { headers });
    if (!page.length) break;
    for (const update of page) { /* process leverage update */ }
    if (page.length < limit) break;
    const last = page[page.length - 1];
    params = {
        type: 'userLeverageUpdatesByTime',
        user,
        cursor: `${last.time}_${last.tx_index}`,
        limit,
    };
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

JSON array of leverage update records, ordered **oldest-first** by `time` then `tx_index`.

| Field         | Type    | Description                                                                              |
| ------------- | ------- | ---------------------------------------------------------------------------------------- |
| `update_type` | string  | Always `"leverage"`                                                                      |
| `time`        | int     | Block time when the update was made (Unix ms) — **first half of the next-page `cursor`** |
| `user`        | string  | Ethereum address                                                                         |
| `coin`        | string  | Asset symbol                                                                             |
| `is_cross`    | boolean | `true` for cross margin, `false` for isolated margin                                     |
| `leverage`    | int     | New leverage value                                                                       |
| `tx_index`    | int     | Transaction index within the block — **second half of the next-page `cursor`**           |


# userIsolatedMarginUpdatesByTime

Paginate a Hyperliquid user's isolated margin update history by time, oldest-first.

Returns isolated margin updates (`updateIsolatedMargin` and `topUpIsolatedOnlyMargin` actions) for a user with `time` ≥ `startTime` (or after a `cursor`), ordered **oldest-first** by `time` then `tx_index`.

For pagination: pass `startTime` for the first page, then on each subsequent page pass the `cursor` `"{time}_{tx_index}"` built from the **last record** of the previous response. When `cursor` is supplied, `startTime` is ignored and the boundary record is excluded from the next page (no duplicates).

{% hint style="info" %}
New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

{% hint style="info" %}
Record shapes match the [userIsolatedMarginUpdates WebSocket channel](https://hydromancer.xyz/docs/websocket/leverage-and-margin-updates/userisolatedmarginupdates), so REST history and the live stream can be merged and deduplicated on `(time, tx_index)`. For leverage change history, see [userLeverageUpdatesByTime](https://hydromancer.xyz/docs/rest-api/historical-data/userleverageupdatesbytime).
{% endhint %}

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userIsolatedMarginUpdatesByTime"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Earliest <code>time</code> to include (Unix ms, inclusive). Skipped when <code>cursor</code> is used. Either <code>startTime</code> or <code>cursor</code> must be supplied</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>Latest <code>time</code> to include (Unix ms, inclusive). Default: now (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of <code>time</code> and <code>tx_index</code> with <code>"_"</code> separator (e.g. <code>"1734571490123_12"</code>). Take from the <strong>last record</strong> of the previous response (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return. Default 100, max 500 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
# First page
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userIsolatedMarginUpdatesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0,
    "limit": 100
  }'

# Next page — cursor built from the last record of the previous response
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userIsolatedMarginUpdatesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "cursor": "1734571490123_12",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

url = 'https://api.hydromancer.xyz/info'
headers = {
    'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
    'Content-Type': 'application/json',
}
user = '0x0000000000000000000000000000000000000000'
limit = 500

params = {'type': 'userIsolatedMarginUpdatesByTime', 'user': user, 'startTime': 0, 'limit': limit}
while True:
    page = requests.post(url, json=params, headers=headers).json()
    if not page:
        break
    for update in page:
        ...  # process isolated margin update
    if len(page) < limit:
        break
    last = page[-1]
    params = {
        'type': 'userIsolatedMarginUpdatesByTime',
        'user': user,
        'cursor': f"{last['time']}_{last['tx_index']}",
        'limit': limit,
    }
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const url = 'https://api.hydromancer.xyz/info';
const headers = {
    'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
    'Content-Type': 'application/json',
};
const user = '0x0000000000000000000000000000000000000000';
const limit = 500;

let params = { type: 'userIsolatedMarginUpdatesByTime', user, startTime: 0, limit };
while (true) {
    const { data: page } = await axios.post(url, params, { headers });
    if (!page.length) break;
    for (const update of page) { /* process isolated margin update */ }
    if (page.length < limit) break;
    const last = page[page.length - 1];
    params = {
        type: 'userIsolatedMarginUpdatesByTime',
        user,
        cursor: `${last.time}_${last.tx_index}`,
        limit,
    };
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

JSON array of isolated margin update records, ordered **oldest-first** by `time` then `tx_index`. `update_type` selects one of two record shapes; fields the shape doesn't carry are omitted.

#### `"isolated_margin"` — margin added or removed (`updateIsolatedMargin`)

| Field         | Type    | Description                                                                              |
| ------------- | ------- | ---------------------------------------------------------------------------------------- |
| `update_type` | string  | `"isolated_margin"`                                                                      |
| `time`        | int     | Block time when the update was made (Unix ms) — **first half of the next-page `cursor`** |
| `user`        | string  | Ethereum address                                                                         |
| `coin`        | string  | Asset symbol                                                                             |
| `is_buy`      | boolean | Position side the margin change applies to                                               |
| `ntli`        | string  | Notional transfer amount (USDC); positive adds margin, negative removes                  |
| `tx_index`    | int     | Transaction index within the block — **second half of the next-page `cursor`**           |

#### `"top_up_isolated_margin"` — margin topped up to a target leverage (`topUpIsolatedOnlyMargin`)

| Field             | Type   | Description                                                                              |
| ----------------- | ------ | ---------------------------------------------------------------------------------------- |
| `update_type`     | string | `"top_up_isolated_margin"`                                                               |
| `time`            | int    | Block time when the update was made (Unix ms) — **first half of the next-page `cursor`** |
| `user`            | string | Ethereum address                                                                         |
| `coin`            | string | Asset symbol                                                                             |
| `target_leverage` | string | Leverage the margin top-up targets                                                       |
| `tx_index`        | int    | Transaction index within the block — **second half of the next-page `cursor`**           |


# User performance

Endpoints for analyzing a user's trading performance — realized PnL from closed positions, win/loss stats, fees, funding, ranked leaderboards, and (coming soon) unrealized PnL, ROI, and other metrics.

#### **Aggregate stats for a single user**

{% content-ref url="/pages/gD4ErKzaspk4KWMVIhII" %}
[userPnlSummary](https://hydromancer.xyz/docs/rest-api/user-performance/userpnlsummary)
{% endcontent-ref %}

#### **Top traders ranked by PnL, win rate, or volume**

{% content-ref url="/pages/Ak3VdFVO5mH2tR2zer07" %}
[userPnlLeaderboard](https://hydromancer.xyz/docs/rest-api/user-performance/userpnlleaderboard)
{% endcontent-ref %}

#### **A user's most recent completed trades**

{% content-ref url="/pages/yK9zbUW4vMxCUan8phPm" %}
[userCompletedTrades](https://hydromancer.xyz/docs/rest-api/user-performance/usercompletedtrades)
{% endcontent-ref %}

#### **Paginate a user's completed trades by time (cursor-based)**

{% content-ref url="/pages/R9FKEZaKOJWO8wo2JDtG" %}
[userCompletedTradesByTime](https://hydromancer.xyz/docs/rest-api/user-performance/usercompletedtradesbytime)
{% endcontent-ref %}


# userPnlSummary

Aggregate realized-PnL stats for a single Hyperliquid user, computed from completed trades.

Returns aggregate realized-PnL metrics for a user, derived from their completed (fully closed) positions. Includes total net PnL, win/loss rates, median holding time, volume traded, fees, funding PnL, account age, traded pairs, and a heuristic "human score" (0–100, higher = more likely human, lower = more likely an algorithmic trader).

`startTime` and `endTime` are optional and let you scope the metrics to a specific window (filtered on the position's `close_time`).

`dex` is optional. Omit for aggregate across every perp DEX. Set to `"main_dex"` for the native Hyperliquid dex, or to a HIP-3 dex name (e.g. `"xyz"`) to scope to that dex. When the filter is set, `tradedPairs` is scoped to the dex; `accountAgeDays` is always lifetime by design.

**note: data used to compute the leaderboard is starting from 1st of aug 2025**

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userPnlSummary"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>int</td><td>Start time in ms, filters on <code>close_time</code> (optional)</td></tr><tr><td><code>endTime</code></td><td>int</td><td>End time in ms, filters on <code>close_time</code> (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Scope to a single perp DEX. <code>"main_dex"</code> for the native Hyperliquid dex, or a HIP-3 dex name (e.g. <code>"xyz"</code>). Omit for all dexes (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userPnlSummary",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userPnlSummary',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userPnlSummary',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                   | Type      | Description                                                                                                                                                                        |
| ----------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`                  | string    | Ethereum address (echoed from the request)                                                                                                                                         |
| `totalPnl`              | string    | Sum of net PnL across all completed trades in the window. Net PnL is `gross_pnl - fees + funding_pnl`                                                                              |
| `winRate`               | float     | Fraction of trades with `net_pnl > 0`, rounded to 4 decimals (0–1)                                                                                                                 |
| `lossRate`              | float     | Fraction of trades with `net_pnl <= 0`, rounded to 4 decimals (0–1)                                                                                                                |
| `totalTrades`           | int       | Number of completed trades in the window                                                                                                                                           |
| `medianDurationSeconds` | int       | Exact median of completed-trade hold times in the close-time window, as integer seconds. Even counts average the two middle holds. `0` if there are no completed trades            |
| `volumeTraded`          | string    | Sum of `\|px × sz\|` across all of the user's fills in the window (notional traded)                                                                                                |
| `totalFees`             | string    | Sum of fees paid across completed trades                                                                                                                                           |
| `totalFunding`          | string    | Sum of cumulative funding PnL across completed trades (positive = received, negative = paid). Already included in `totalPnl`                                                       |
| `daysActive`            | int       | Number of distinct UTC days on which the user had any fill in the window                                                                                                           |
| `accountAgeDays`        | int?      | Days between the user's earliest known fill and now. `null` if the user has never had a fill on record                                                                             |
| `tradedPairs`           | string\[] | Distinct coin symbols the user has ever filled on (lifetime)                                                                                                                       |
| `humanScore`            | int       | Heuristic 0–100 score, higher = more likely a human trader. Combines average fills per trade, average distinct trading hours per active day, and the ratio of maker to taker fills |

<details>

<summary>Response</summary>

```json
{
  "user": "0x0000000000000000000000000000000000000000",
  "totalPnl": "12345.67",
  "winRate": 0.6234,
  "lossRate": 0.3766,
  "totalTrades": 412,
  "medianDurationSeconds": 18432,
  "volumeTraded": "8421000.00",
  "totalFees": "1684.20",
  "totalFunding": "-23.45",
  "daysActive": 87,
  "accountAgeDays": 312,
  "tradedPairs": ["BTC", "ETH", "SOL", "HYPE"],
  "humanScore": 95
}
```

</details>


# userPnlLeaderboard

Top Hyperliquid traders ranked by realized PnL, win rate, or volume, with quality filters.

Returns a ranked list of users by realized PnL, win rate, or volume traded over a configurable window. Quality filters (`minTrades`, `minDaysActive`, `minAccountAgeDays`, `minHumanScore`) let you exclude one-shot accounts, brand-new wallets, and high-frequency bots.

`builder` is optional. Set it to a builder address to rank only the traders who have routed a fill through that builder — useful for "how are *my* users doing" rather than the whole exchange. Membership is **lifetime**: a trader counts if they have ever routed a fill through the builder, not only within the selected window. `total` reflects the builder-scoped result set, so pagination stays correct. An address that has never routed a fill returns an empty board, not the unfiltered one, and a malformed `builder` is a `400` rather than a silently unfiltered result — omit the field (or send `null`) when you want every user.

`dex` is optional. Omit for a leaderboard aggregated across every perp DEX. Set to `"main_dex"` for the native Hyperliquid dex, or to a HIP-3 dex name (e.g. `"xyz"`) to scope the leaderboard to that dex. When the filter is set, each user's `tradedPairs` is scoped to the dex; `accountAgeDays` is always lifetime by design.

**note: data used to compute the leaderboard is starting from 1st of aug 2025**

## POST Request

<table><thead><tr><th width="180">Field</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userPnlLeaderboard"</code></td></tr><tr><td><code>window</code></td><td>string</td><td>One of <code>"1d"</code>, <code>"7d"</code>, <code>"30d"</code>, <code>"90d"</code>, <code>"all"</code>. Default <code>"30d"</code> (optional)</td></tr><tr><td><code>sortBy</code></td><td>string</td><td>One of <code>"totalPnl"</code>, <code>"winRate"</code>, <code>"volumeTraded"</code>. Default <code>"totalPnl"</code> (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>Max results to return. Default 100, max 1000 (optional)</td></tr><tr><td><code>offset</code></td><td>int</td><td>Pagination offset. Default 0 (optional)</td></tr><tr><td><code>minTrades</code></td><td>int</td><td>Minimum completed trades to include a user. Default 5 (optional)</td></tr><tr><td><code>minDaysActive</code></td><td>int</td><td>Minimum distinct active days to include a user. Default 1 (optional)</td></tr><tr><td><code>minAccountAgeDays</code></td><td>int</td><td>Minimum account age in days. Default 0 (optional)</td></tr><tr><td><code>minHumanScore</code></td><td>int</td><td>Minimum human score (0–100). Filters out users below this score (optional)</td></tr><tr><td><code>builder</code></td><td>string</td><td>Rank only traders who have ever routed a fill through this builder address. Omit for all users (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Scope the leaderboard to a single perp DEX. <code>"main_dex"</code> for the native Hyperliquid dex, or a HIP-3 dex name (e.g. <code>"xyz"</code>). Omit for all dexes (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userPnlLeaderboard",
    "window": "30d",
    "sortBy": "totalPnl",
    "limit": 50,
    "minTrades": 10,
    "minHumanScore": 60
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userPnlLeaderboard',
        'window': '30d',
        'sortBy': 'totalPnl',
        'limit': 50,
        'minTrades': 10,
        'minHumanScore': 60
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userPnlLeaderboard',
        window: '30d',
        sortBy: 'totalPnl',
        limit: 50,
        minTrades: 10,
        minHumanScore: 60
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

The response is an object with `users`, `total`, `limit`, and `offset` fields. Each entry in `users` has the same shape as a [userPnlSummary](https://hydromancer.xyz/docs/rest-api/user-performance/userpnlsummary) response (minus `lossRate` and `medianDurationSeconds`).

| Field    | Type      | Description                                                         |
| -------- | --------- | ------------------------------------------------------------------- |
| `users`  | object\[] | Ranked list of user entries (see below)                             |
| `total`  | int       | Total users matching all filters before `limit`/`offset` is applied |
| `limit`  | int       | Echo of the request's `limit`                                       |
| `offset` | int       | Echo of the request's `offset`                                      |

### `users[]` entry

| Field            | Type      | Description                                                                                                                                                                        |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`           | string    | Ethereum address                                                                                                                                                                   |
| `totalPnl`       | string    | Sum of net PnL across the user's completed trades in the window. Net PnL is `gross_pnl - fees + funding_pnl`                                                                       |
| `winRate`        | float     | Fraction of trades with `net_pnl > 0`, rounded to 4 decimals (0–1)                                                                                                                 |
| `totalTrades`    | int       | Number of completed trades in the window                                                                                                                                           |
| `volumeTraded`   | string    | Sum of `\|px × sz\|` across all of the user's fills in the window                                                                                                                  |
| `totalFees`      | string    | Sum of fees paid across completed trades                                                                                                                                           |
| `totalFunding`   | string    | Sum of cumulative funding PnL across completed trades. Already included in `totalPnl`                                                                                              |
| `daysActive`     | int       | Number of distinct UTC days on which the user had any fill in the window                                                                                                           |
| `accountAgeDays` | int?      | Days between the user's earliest known fill and now. `null` if the user has never had a fill on record                                                                             |
| `tradedPairs`    | string\[] | Distinct coin symbols the user has ever filled on (lifetime)                                                                                                                       |
| `humanScore`     | int       | Heuristic 0–100 score, higher = more likely a human trader. Combines average fills per trade, average distinct trading hours per active day, and the ratio of maker to taker fills |

<details>

<summary>Response</summary>

```json
{
  "users": [
    {
      "user": "0xabc0000000000000000000000000000000000001",
      "totalPnl": "248913.50",
      "winRate": 0.7124,
      "totalTrades": 178,
      "volumeTraded": "12450000.00",
      "totalFees": "2490.10",
      "totalFunding": "412.33",
      "daysActive": 28,
      "accountAgeDays": 145,
      "tradedPairs": ["BTC", "ETH", "HYPE"],
      "humanScore": 88
    },
    {
      "user": "0xabc0000000000000000000000000000000000002",
      "totalPnl": "187654.21",
      "winRate": 0.6489,
      "totalTrades": 312,
      "volumeTraded": "9821000.00",
      "totalFees": "1964.20",
      "totalFunding": "-87.41",
      "daysActive": 30,
      "accountAgeDays": 312,
      "tradedPairs": ["SOL", "BTC", "ETH", "HYPE"],
      "humanScore": 75
    }
  ],
  "total": 1842,
  "limit": 50,
  "offset": 0
}
```

</details>


# userCompletedTrades

Get a Hyperliquid user's most recent completed (fully closed) positions, newest-first.

Returns the latest N completed trades for a user, newest-first. A completed trade represents a position that has been fully closed (size returned to \~0). Each record includes gross/net/funding PnL, average entry and exit prices, fees, fill counts (total and maker), open/close timestamps, duration, peak position size during the position's lifetime, leverage at close, and last-touch builder attribution.

`dex` is optional. Omit to return trades from every perp DEX. Set to `"main_dex"` for the native Hyperliquid dex, or to a HIP-3 dex name (e.g. `"xyz"`) to scope the trade list to that dex.

**note: data used to compute the leaderboard is starting from 1st of aug 2025**

`outcomes` is optional. Set it to `true` to return trades from HIP-4 outcome markets (coins like `#8131`) instead of perp and spot trades. The two sets are disjoint and are never mixed in one response.

Outcome records **omit** `positionType`, `fundingPnl`, `leverage` and `isCross` entirely. These are not unknown values — they do not apply. Outcome exposure is a token holding, so there is no short side, no leverage and no funding, and emitting `"Long"` or `"0"` would assert facts about the market that are not true.

On a perp or spot record all four are **always present and always carry a value**, so a client may read them directly there. Treat an absent field as "not applicable to this market type" — equivalently, as "this record is from an outcome market".

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userCompletedTrades"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>builder</code></td><td>string</td><td>Filter to trades whose closing fill was routed through this builder address (last-touch attribution, 0x-prefixed). Omit (or send <code>null</code>) for no filtering. A malformed, empty or non-string value is a <code>400</code> rather than a silently unfiltered result (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>Max results to return. Default 100, max 500 (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Scope to a single perp DEX. <code>"main_dex"</code> for the native Hyperliquid dex, or a HIP-3 dex name (e.g. <code>"xyz"</code>). Omit for all dexes (optional)</td></tr><tr><td><code>outcomes</code></td><td>bool</td><td>Return HIP-4 outcome-market trades instead of perp/spot trades. Defaults to <code>false</code>. Cannot be combined with <code>dex</code>, since outcome markets are not dex-scoped. Outcome records <strong>omit</strong> <code>positionType</code>, <code>fundingPnl</code>, <code>leverage</code> and <code>isCross</code> entirely, rather than reporting placeholder values: outcome exposure is a token holding that is only ever long, is unlevered, and accrues no funding. All four are always present on perp and spot records (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userCompletedTrades",
    "user": "0x0000000000000000000000000000000000000000",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userCompletedTrades',
        'user': '0x0000000000000000000000000000000000000000',
        'limit': 100
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userCompletedTrades',
        user: '0x0000000000000000000000000000000000000000',
        limit: 100
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

The response is a JSON array of completed-trade records, ordered newest-first by `close_time` then `tx_index`.

| Field                  | Type    | Description                                                                                                                                                                           |
| ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`                 | string  | Ethereum address                                                                                                                                                                      |
| `coin`                 | string  | Asset symbol                                                                                                                                                                          |
| `position_type`        | string  | `"Long"` or `"Short"`. Omitted on outcome markets, which are only ever long                                                                                                           |
| `gross_pnl`            | string  | Realized PnL before fees (`exit_value - entry_value`, sign-adjusted for shorts)                                                                                                       |
| `net_pnl`              | string  | Realized PnL after fees and funding (`gross_pnl - fees + funding_pnl`)                                                                                                                |
| `funding_pnl`          | string  | Cumulative funding PnL accrued while the position was open (positive = received, negative = paid). Already included in `net_pnl`. Omitted on outcome markets, which accrue no funding |
| `entry_px`             | string  | Volume-weighted average entry price                                                                                                                                                   |
| `exit_px`              | string  | Volume-weighted average exit price                                                                                                                                                    |
| `position_closed_size` | string  | Size of the closed position, in contracts                                                                                                                                             |
| `fees`                 | string  | Total fees paid on fills attributed to this position                                                                                                                                  |
| `fills`                | int     | Number of fills on this position                                                                                                                                                      |
| `maker_fills`          | int     | Number of uncrossed (maker) fills on this position                                                                                                                                    |
| `open_time`            | int     | Time the position was opened (Unix ms)                                                                                                                                                |
| `close_time`           | int     | Time the position was fully closed (Unix ms)                                                                                                                                          |
| `duration_ms`          | int     | `close_time - open_time` in milliseconds                                                                                                                                              |
| `max_position_size`    | string  | Peak absolute position size reached during the position's lifetime                                                                                                                    |
| `builder`              | string? | Builder address from the closing fill, if any (last-touch attribution)                                                                                                                |
| `tx_index`             | int     | Transaction index of the closing fill (use with `close_time` for cursor-based pagination)                                                                                             |
| `leverage`             | int     | Leverage multiplier at close (e.g. `10` = 10x). Omitted on outcome markets, which are unlevered                                                                                       |
| `is_cross`             | boolean | `true` = cross margin, `false` = isolated. Omitted on outcome markets                                                                                                                 |

<details>

<summary>Response</summary>

```json
[
  {
    "user": "0x0000000000000000000000000000000000000000",
    "coin": "BTC",
    "position_type": "Long",
    "gross_pnl": "1240.50",
    "net_pnl": "1215.15",
    "funding_pnl": "-3.10",
    "entry_px": "45000.00",
    "exit_px": "45620.00",
    "position_closed_size": "2.0",
    "fees": "22.25",
    "fills": 4,
    "maker_fills": 2,
    "open_time": 1734567890123,
    "close_time": 1734571490123,
    "duration_ms": 3600000,
    "max_position_size": "2.5",
    "builder": null,
    "tx_index": 12,
    "leverage": 10,
    "is_cross": true
  }
]
```

</details>


# userCompletedTradesByTime

Paginate a Hyperliquid user's completed (fully closed) positions by close time, oldest-first.

Returns completed trades for a user with `close_time` ≥ `startTime` (or after a `cursor`), ordered **oldest-first** by `close_time` then `tx_index`. Pagination is identical to [`userFillsByTime`](https://hydromancer.xyz/docs/rest-api/historical-data/userfillsbytime): pass `startTime` for the first page, then on each subsequent page pass the `cursor` `"{close_time}_{tx_index}"` built from the **last record** of the previous response. When `cursor` is supplied, `startTime` is ignored and the boundary record is excluded from the next page (no duplicates, no `+ 1` hack).

`dex` is optional. Omit to return trades from every perp DEX. Set to `"main_dex"` for the native Hyperliquid dex, or to a HIP-3 dex name (e.g. `"xyz"`) to scope the trade list to that dex.

`outcomes` is optional. Set it to `true` to return trades from HIP-4 outcome markets (coins like `#8131`) instead of perp and spot trades. The two sets are disjoint and are never mixed in one response.

Outcome records **omit** `positionType`, `fundingPnl`, `leverage` and `isCross` entirely. These are not unknown values — they do not apply. Outcome exposure is a token holding, so there is no short side, no leverage and no funding, and emitting `"Long"` or `"0"` would assert facts about the market that are not true.

On a perp or spot record all four are **always present and always carry a value**, so a client may read them directly there. Treat an absent field as "not applicable to this market type" — equivalently, as "this record is from an outcome market".

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userCompletedTradesByTime"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Earliest <code>close_time</code> to include (Unix ms, inclusive). Skipped when <code>cursor</code> is used. Either <code>startTime</code> or <code>cursor</code> must be supplied</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>Latest <code>close_time</code> to include (Unix ms, inclusive). Default: now (optional)</td></tr><tr><td><code>cursor</code></td><td>string</td><td>Composite of <code>close_time</code> and <code>tx_index</code> with <code>"_"</code> separator (e.g. <code>"1734571490123_12"</code>). Take from the <strong>last record</strong> of the previous response (optional)</td></tr><tr><td><code>builder</code></td><td>string</td><td>Filter to trades whose closing fill was routed through this builder address (last-touch attribution, 0x-prefixed). Omit (or send <code>null</code>) for no filtering. A malformed, empty or non-string value is a <code>400</code> rather than a silently unfiltered result (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max results to return. Default 100, max 500 (optional)</td></tr><tr><td><code>dex</code></td><td>string</td><td>Scope to a single perp DEX. <code>"main_dex"</code> for the native Hyperliquid dex, or a HIP-3 dex name (e.g. <code>"xyz"</code>). Omit for all dexes (optional)</td></tr><tr><td><code>outcomes</code></td><td>bool</td><td>Return HIP-4 outcome-market trades instead of perp/spot trades. Defaults to <code>false</code>. Cannot be combined with <code>dex</code>, since outcome markets are not dex-scoped. Outcome records <strong>omit</strong> <code>positionType</code>, <code>fundingPnl</code>, <code>leverage</code> and <code>isCross</code> entirely, rather than reporting placeholder values: outcome exposure is a token holding that is only ever long, is unlevered, and accrues no funding. All four are always present on perp and spot records (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
# First page
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userCompletedTradesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "startTime": 0,
    "limit": 100
  }'

# Next page — cursor built from the last record of the previous response
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userCompletedTradesByTime",
    "user": "0x0000000000000000000000000000000000000000",
    "cursor": "1734571490123_12",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

url = 'https://api.hydromancer.xyz/info'
headers = {
    'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
    'Content-Type': 'application/json',
}
user = '0x0000000000000000000000000000000000000000'
limit = 500

params = {'type': 'userCompletedTradesByTime', 'user': user, 'startTime': 0, 'limit': limit}
while True:
    page = requests.post(url, json=params, headers=headers).json()
    if not page:
        break
    for trade in page:
        ...  # process trade
    if len(page) < limit:
        break
    last = page[-1]
    params = {
        'type': 'userCompletedTradesByTime',
        'user': user,
        'cursor': f"{last['close_time']}_{last['tx_index']}",
        'limit': limit,
    }
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const url = 'https://api.hydromancer.xyz/info';
const headers = {
    'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
    'Content-Type': 'application/json',
};
const user = '0x0000000000000000000000000000000000000000';
const limit = 500;

let params = { type: 'userCompletedTradesByTime', user, startTime: 0, limit };
while (true) {
    const { data: page } = await axios.post(url, params, { headers });
    if (!page.length) break;
    for (const trade of page) { /* process trade */ }
    if (page.length < limit) break;
    const last = page[page.length - 1];
    params = {
        type: 'userCompletedTradesByTime',
        user,
        cursor: `${last.close_time}_${last.tx_index}`,
        limit,
    };
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

JSON array of completed-trade records, ordered **oldest-first** by `close_time` then `tx_index`. Same record shape as [userCompletedTrades](https://hydromancer.xyz/docs/rest-api/user-performance/usercompletedtrades):

| Field                  | Type    | Description                                                                                                                                                                           |
| ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `user`                 | string  | Ethereum address                                                                                                                                                                      |
| `coin`                 | string  | Asset symbol                                                                                                                                                                          |
| `position_type`        | string  | `"Long"` or `"Short"`. Omitted on outcome markets, which are only ever long                                                                                                           |
| `gross_pnl`            | string  | Realized PnL before fees                                                                                                                                                              |
| `net_pnl`              | string  | Realized PnL after fees and funding (`gross_pnl - fees + funding_pnl`)                                                                                                                |
| `funding_pnl`          | string  | Cumulative funding PnL accrued while the position was open (positive = received, negative = paid). Already included in `net_pnl`. Omitted on outcome markets, which accrue no funding |
| `entry_px`             | string  | Volume-weighted average entry price                                                                                                                                                   |
| `exit_px`              | string  | Volume-weighted average exit price                                                                                                                                                    |
| `position_closed_size` | string  | Size of the closed position, in contracts                                                                                                                                             |
| `fees`                 | string  | Total fees paid on fills attributed to this position                                                                                                                                  |
| `fills`                | int     | Number of fills on this position                                                                                                                                                      |
| `maker_fills`          | int     | Number of uncrossed (maker) fills on this position                                                                                                                                    |
| `open_time`            | int     | Time the position was opened (Unix ms)                                                                                                                                                |
| `close_time`           | int     | Time the position was fully closed (Unix ms) — **first half of the next-page `cursor`**                                                                                               |
| `duration_ms`          | int     | `close_time - open_time` in milliseconds                                                                                                                                              |
| `max_position_size`    | string  | Peak absolute position size during the position's lifetime                                                                                                                            |
| `builder`              | string? | Builder address from the closing fill, if any                                                                                                                                         |
| `tx_index`             | int     | Transaction index of the closing fill — **second half of the next-page `cursor`**                                                                                                     |
| `leverage`             | int     | Leverage multiplier at close (e.g. `10` = 10x). Omitted on outcome markets, which are unlevered                                                                                       |
| `is_cross`             | boolean | `true` = cross margin, `false` = isolated. Omitted on outcome markets                                                                                                                 |


# walletLabels (experimental)

Every labelled Hyperliquid wallet with its trader tag and market-maker / delta-neutral / new-wallet flags, as one gzip download. Experimental add-on.

{% hint style="warning" %}
**Experimental add-on.** This endpoint needs the `wallet-labels` add-on on your API key; without it the call returns `403`. The response shape may change while the endpoint is experimental.
{% endhint %}

Returns the full wallet label list (about 250k wallets) in a single response. The list is refreshed hourly, so polling more often returns the same data. The response header `x-fetched-at-ms` tells you when the current copy was fetched.

The body is always **gzip-compressed** (`Content-Encoding: gzip`, about 6 MB on the wire, about 36 MB decoded). Python `requests`/`httpx`, JavaScript `fetch`, and Rust `reqwest` decompress it automatically. With cURL, pass `--compressed`.

**Rate limit:** 10 requests per 10 minutes per API key, separate from your per-minute points budget.

## POST Request

<table><thead><tr><th width="180">Field</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"walletLabels"</code></td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl --compressed -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "walletLabels"}' \
  -o wallet_labels.json
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"Authorization": f"Bearer {os.environ['HYDROMANCER_API_KEY']}"},
    json={"type": "walletLabels"},
)
response.raise_for_status()
wallets = response.json()  # requests decompresses gzip automatically
print(len(wallets), response.headers["x-fetched-at-ms"])
```

{% endtab %}
{% endtabs %}

## Response

A JSON array with one object per wallet, sorted by address.

<table><thead><tr><th width="180">Field</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>address</code></td><td>string</td><td>Wallet address, lowercase <code>0x</code>-prefixed hex</td></tr><tr><td><code>name</code></td><td>string | null</td><td>Known name for the wallet, if any</td></tr><tr><td><code>tag</code></td><td>string</td><td>Trader classification, for example <code>"New wallet"</code>, <code>"+ day"</code>, <code>"- swing"</code>, <code>"+ intraday"</code>, <code>"- scalper"</code></td></tr><tr><td><code>marketMaker</code></td><td>bool</td><td>Wallet is classified as a market maker</td></tr><tr><td><code>deltaNeutral</code></td><td>bool</td><td>Wallet is classified as delta-neutral</td></tr><tr><td><code>newWallet</code></td><td>bool</td><td>Wallet is classified as new</td></tr></tbody></table>

```json
[
  {
    "address": "0x000000000000000000000000000000000000dead",
    "name": "Burn Address 2",
    "tag": "New wallet",
    "marketMaker": false,
    "deltaNeutral": false,
    "newWallet": true
  },
  {
    "address": "0x0000000000005ef5a16bd687b9b9c41b498435db",
    "name": null,
    "tag": "+ day",
    "marketMaker": false,
    "deltaNeutral": false,
    "newWallet": false
  }
]
```

## Errors

| Status | Meaning                                                              |
| ------ | -------------------------------------------------------------------- |
| `403`  | Your API key does not have the `wallet-labels` add-on.               |
| `429`  | More than 10 requests in 10 minutes.                                 |
| `503`  | The list has not loaded yet after a restart. Retry in a few minutes. |


# Fees

Endpoints for querying a Hyperliquid user's trading fees and referral rewards.

#### **Retrieve user fees**

{% content-ref url="/pages/f2HWHESYenJadxbXZCFG" %}
[userFees](https://hydromancer.xyz/docs/rest-api/fees/userfees)
{% endcontent-ref %}

#### **Retrieve a user's referral and builder rewards**

{% content-ref url="/pages/k71ISRmpoYkcMgQEWiAb" %}
[referral](https://hydromancer.xyz/docs/rest-api/fees/referral)
{% endcontent-ref %}


# userFees

Get Hyperliquid fee information for a user.

| Field  | Type   | Descriptions                                  |
| ------ | ------ | --------------------------------------------- |
| `type` | string | Must be `"userFees"`                          |
| `user` | string | Ethereum address (0x-prefixed, 42 characters) |


# referral

A Hyperliquid user's referrer, volume, and unclaimed, claimed and builder rewards per token.

Returns a user's referral and builder reward state: who referred them, their volume, and their unclaimed, claimed and builder rewards, in total for USDC and per collateral token.

The request and field names match Hyperliquid's `referral` info type, with two differences:

{% hint style="warning" %}
The amounts are based on snapshots taken roughly every 12 minutes. You can use `snapshotTime` to show users how recent the data is.
{% endhint %}

{% hint style="info" %}
`referrerState` and `rewardHistory` are not returned at this time.
{% endhint %}

## POST Request

<table><thead><tr><th width="180">Field</th><th width="105">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"referral"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address: <code>0x</code> followed by 40 hex digits, in either case</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "referral", "user": "0x1234567890abcdef1234567890abcdef12345678"}'
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    "https://api.hydromancer.xyz/info",
    headers={"Authorization": f"Bearer {os.environ['HYDROMANCER_API_KEY']}"},
    json={"type": "referral", "user": "0x1234567890abcdef1234567890abcdef12345678"},
)
response.raise_for_status()
state = response.json()
print(state["unclaimedRewards"], state["snapshotTime"])
```

{% endtab %}
{% endtabs %}

## Response

<table><thead><tr><th width="200">Field</th><th width="130">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>referredBy</code></td><td>object | null</td><td>The user's referrer as <code>{"referrer": address, "code": string}</code>, or <code>null</code> if the user was not referred</td></tr><tr><td><code>cumVlm</code></td><td>string</td><td>USDC volume</td></tr><tr><td><code>unclaimedRewards</code></td><td>string</td><td>USDC rewards not yet claimed</td></tr><tr><td><code>claimedRewards</code></td><td>string</td><td>USDC rewards already claimed</td></tr><tr><td><code>builderRewards</code></td><td>string</td><td>USDC builder fees collected</td></tr><tr><td><code>tokenToState</code></td><td>array</td><td>The same four amounts per collateral token, as <code>[tokenId, amounts]</code> pairs ordered by token id</td></tr><tr><td><code>snapshotTime</code></td><td>integer</td><td>Block time of the snapshot these values come from, in Unix milliseconds</td></tr></tbody></table>

```json
{
  "referredBy": {
    "referrer": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
    "code": "EXAMPLE"
  },
  "cumVlm": "152340.75",
  "unclaimedRewards": "12.5031",
  "claimedRewards": "48.2",
  "builderRewards": "60.7031",
  "tokenToState": [
    [0, {"cumVlm": "152340.75", "unclaimedRewards": "12.5031", "claimedRewards": "48.2", "builderRewards": "60.7031"}],
    [360, {"cumVlm": "8120.4", "unclaimedRewards": "1.75", "claimedRewards": "0.0", "builderRewards": "1.75"}]
  ],
  "snapshotTime": 1794689881053
}
```

### Tokens

The four top-level amounts are the **USDC** values only, as on Hyperliquid. Rewards and volume in other collateral tokens appear only in `tokenToState`, so sum across its rows if you need every token. Token ids are Hyperliquid spot token indexes:

| Token id | Token |
| -------- | ----- |
| `0`      | USDC  |
| `235`    | USDe  |
| `268`    | USDT0 |
| `360`    | USDH  |

A token appears once the user has state in it; new collateral tokens show up with their own id.

### Notes

* Amounts are decimal strings with trailing zeros removed and at least one decimal place (`"0.0"`, `"48.2"`).
* A user with no referral state gets `referredBy: null`, `"0.0"` amounts and an empty `tokenToState`.
* A user who can no longer be referred has `referredBy` set to the zero address with code `"N/A"`.
* A referrer without a code has `code: ""`.
* `code` is free text chosen by the referrer. Escape it before putting it in HTML, a shell command or a query.
* `cumVlm` is exact to the cent. Hyperliquid's own response can show floating-point noise in this field (for example `"1976518.1899999999"` where we return `"1976518.19"`).

## Rate limits and cost

2 points per request, the default weight (see [rate limits](https://hydromancer.xyz/docs/rest-api/rate-limits-and-user-limits)), and 0.1 tokens per request (see [pricing](https://hydromancer.xyz/docs/pricing)).

## Errors

Errors use the structured format (`error`, `code`, `correlationId`) without needing the `X-HM-Error-Format` header.

| Status | `code`            | When                                                                                |
| ------ | ----------------- | ----------------------------------------------------------------------------------- |
| `400`  | `invalid_request` | `user` is missing or is not a valid address                                         |
| `503`  | `unavailable`     | No snapshot is loaded yet. Retry in a few minutes; a `503` never means zero rewards |


# Roles and agents

Endpoints for querying a Hyperliquid wallet's role, API key names, request allowance, and multisig signers.

#### **Retrieving user's role**

Wallets on Hyperliquid can have different roles, such as agent wallets, subaccounts, vaults, and so on.

{% content-ref url="/pages/F4Va5CVFaWdDW0LDVyZr" %}
[userRole](https://hydromancer.xyz/docs/rest-api/roles-and-agents/userrole)
{% endcontent-ref %}

#### **Retrieving user's API key names**

{% content-ref url="/pages/dizBn0zywwJ6SF2qIqLS" %}
[extraAgents](https://hydromancer.xyz/docs/rest-api/roles-and-agents/extraagents)
{% endcontent-ref %}

#### **Retrieving a user's request allowance**

{% content-ref url="/pages/z9258ZcXiKgrnRVN3jOe" %}
[userRateLimit](https://hydromancer.xyz/docs/rest-api/roles-and-agents/userratelimit)
{% endcontent-ref %}

#### **Retrieving multisigs by signer**

{% content-ref url="/pages/Sjc3uYygQLFiZv97V5cI" %}
[multiSigsBySigner](https://hydromancer.xyz/docs/rest-api/roles-and-agents/multisigsbysigner)
{% endcontent-ref %}

#### **Retrieving a multisig's signers**

{% content-ref url="/pages/VGH3ixcu8nPpYsX6xXk6" %}
[userToMultiSigSigners](https://hydromancer.xyz/docs/rest-api/roles-and-agents/usertomultisigsigners)
{% endcontent-ref %}


# userRole

Get the role of a Hyperliquid user account.

Get the role of a Hyperliquid user account.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"userRole"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userRole",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'userRole',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'userRole',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field  | Type   | Description                                             |
| ------ | ------ | ------------------------------------------------------- |
| `role` | string | Account role (e.g. `"user"`, `"subAccount"`, `"vault"`) |

<details>

<summary>Response</summary>

```json
{
    "role": "user"
}
```

</details>


# extraAgents

Get the extra agents (API wallets) of a Hyperliquid user.

Get the extra agents (API wallets) of a Hyperliquid user.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"extraAgents"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "extraAgents",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'extraAgents',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'extraAgents',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field        | Type   | Description                      |
| ------------ | ------ | -------------------------------- |
| `name`       | string | Agent name                       |
| `address`    | string | Agent wallet address             |
| `validUntil` | int    | Expiry timestamp in milliseconds |

<details>

<summary>Response</summary>

```json
[
    {
        "name": "Agent 1",
        "address": "0x77deafccbb9ddbc5da3e8f5d066624265bdb2a74",
        "validUntil": 1775216111330
    },
    {
        "name": "Agent 2",
        "address": "0xfff6471954ad1bbe70f18e2fea9928fd7aba31ad",
        "validUntil": 1782653334723
    }
]
```

</details>


# multiSigsBySigner

Get the Hyperliquid multisig accounts associated with an address.

Get all multisig accounts where an address is an authorized signer, plus the full signer set and threshold for each multisig account.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"multiSigsBySigner"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>Ethereum address (0x-prefixed, 42 characters)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "multiSigsBySigner",
    "user": "0x0000000000000000000000000000000000000000"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'multiSigsBySigner',
        'user': '0x0000000000000000000000000000000000000000'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'multiSigsBySigner',
        user: '0x0000000000000000000000000000000000000000'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field             | Type           | Description                                           |
| ----------------- | -------------- | ----------------------------------------------------- |
| `user`            | string         | Multisig account address                              |
| `authorizedUsers` | array\[string] | Addresses authorized to sign for the multisig account |
| `threshold`       | int            | Minimum number of authorized signatures required      |

<details>

<summary>Response</summary>

```json
[
  {
    "user": "0x1111111111111111111111111111111111111111",
    "authorizedUsers": [
      "0x0000000000000000000000000000000000000000",
      "0x2222222222222222222222222222222222222222"
    ],
    "threshold": 2
  }
]
```

</details>


# approvedBuilders

Returns the list of builder addresses a Hyperliquid user has approved to charge builder fees.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"approvedBuilders"</code></td></tr><tr><td><code>user</code></td><td>string</td><td>User Ethereum address (required)</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "approvedBuilders",
    "user": "0xd38809cc442fe4f10937c5988d2b723a15a89e5b"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'approvedBuilders',
        'user': '0xd38809cc442fe4f10937c5988d2b723a15a89e5b'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'approvedBuilders',
    user: '0xd38809cc442fe4f10937c5988d2b723a15a89e5b'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field  | Type  | Description                                                                       |
| ------ | ----- | --------------------------------------------------------------------------------- |
| (root) | array | List of approved builder Ethereum addresses (empty if the user has approved none) |

<details>

<summary>Response</summary>

```json
[
  "0xe966a12bf7b93838096e4519a684519ab22df618"
]
```

</details>


# userRateLimit

Get a user's Hyperliquid API request allowance and usage.

Get a user's Hyperliquid address-based rate limit: cumulative volume, requests used, and the request cap.

Hyperliquid limits the number of actions an address can send based on trading volume. Every address starts with 10,000 requests. It earns one more request for every 1 USDC of cumulative trading volume.

This endpoint reports the address's position against that limit. It applies to actions sent through Hyperliquid's exchange endpoint. Info and Hydromancer requests use your plan's weight budget instead.

## POST Request

| Field  | Type   | Description                                   |
| ------ | ------ | --------------------------------------------- |
| `type` | string | Must be `"userRateLimit"`                     |
| `user` | string | Ethereum address (0x-prefixed, 42 characters) |

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userRateLimit",
    "user": "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    "https://api.hydromancer.xyz/info",
    json={
        "type": "userRateLimit",
        "user": "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"
    },
    headers={
        "Authorization": f"Bearer {os.environ.get('HYDROMANCER_API_KEY')}",
        "Content-Type": "application/json"
    }
)

print(response.json())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import axios from "axios";

const response = await axios.post(
  "https://api.hydromancer.xyz/info",
  {
    type: "userRateLimit",
    user: "0x5b5d51203a0f9079f8aeb098a6523a13f298c060"
  },
  {
    headers: {
      Authorization: `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      "Content-Type": "application/json"
    }
  }
);

console.log(response.data);
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field              | Type   | Description                                                                      |
| ------------------ | ------ | -------------------------------------------------------------------------------- |
| `cumVlm`           | string | Cumulative trading volume of the address in USDC, since it first traded          |
| `nRequestsUsed`    | int    | Actions the address has sent, less any reserved allowance. `0` for a new address |
| `nRequestsCap`     | int    | Total actions allowed: 10,000 plus one per 1 USDC of `cumVlm`                    |
| `nRequestsSurplus` | int    | Reserved allowance not yet used. `0` unless the address bought extra allowance   |

When `nRequestsUsed` reaches `nRequestsCap`, Hyperliquid permits one action every 10 seconds. Trading more volume increases the cap.&#x20;

An address that never traded returns `cumVlm` `"0.0"` and a cap of 10,000.

<details>

<summary>Response</summary>

```json
{
  "cumVlm": "5677568944.3100004196",
  "nRequestsUsed": 5568463,
  "nRequestsCap": 5677578944,
  "nRequestsSurplus": 0
}
```

</details>


# userToMultiSigSigners

Get the authorized signers and threshold for a Hyperliquid multisig account.

Get the authorized signers and signature threshold of a multisig account.

A Hyperliquid multisig account is a normal address converted for multi-party signing. This endpoint returns its authorized signers and required signature count.

For the reverse lookup, see [multiSigsBySigner](https://hydromancer.xyz/docs/rest-api/roles-and-agents/multisigsbysigner).

## POST Request

| Field  | Type   | Description                                           |
| ------ | ------ | ----------------------------------------------------- |
| `type` | string | Must be `"userToMultiSigSigners"`                     |
| `user` | string | Multisig account address (0x-prefixed, 42 characters) |

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "userToMultiSigSigners",
    "user": "0x7a8b673a176a430b80cfcdfdfb6b10ed55010ebb"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    "https://api.hydromancer.xyz/info",
    json={
        "type": "userToMultiSigSigners",
        "user": "0x7a8b673a176a430b80cfcdfdfb6b10ed55010ebb"
    },
    headers={
        "Authorization": f"Bearer {os.environ.get('HYDROMANCER_API_KEY')}",
        "Content-Type": "application/json"
    }
)

print(response.json())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import axios from "axios";

const response = await axios.post(
  "https://api.hydromancer.xyz/info",
  {
    type: "userToMultiSigSigners",
    user: "0x7a8b673a176a430b80cfcdfdfb6b10ed55010ebb"
  },
  {
    headers: {
      Authorization: `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      "Content-Type": "application/json"
    }
  }
);

console.log(response.data);
```

{% endtab %}
{% endtabs %}

***

## Response Fields

The response is an object, or `null` when the address is not a multisig account.

| Field             | Type           | Description                                                     |
| ----------------- | -------------- | --------------------------------------------------------------- |
| `authorizedUsers` | array\[string] | Addresses authorized to sign for the multisig account, up to 10 |
| `threshold`       | int            | Minimum authorized signatures required per action               |

<details>

<summary>Response</summary>

```json
{
  "authorizedUsers": [
    "0x563c175e6f11582f65d6d9e360a618699dee14a9"
  ],
  "threshold": 1
}
```

</details>

<details>

<summary>Response (not a multisig account)</summary>

```json
null
```

</details>


# Asset data

Endpoints for querying Hyperliquid mid, mark and oracle prices, live and historical.

Retrieve live and historical Hyperliquid mid, mark, and oracle prices.&#x20;

For real-time oracle feeds and overview, see [Hyperliquid oracle data](https://hydromancer.xyz/hyperliquid-oracle-data) or read [Hyperliquid Mark Price vs. Oracle Price](https://hydromancer.xyz/blog/hyperliquid-oracle-price-vs-mark-price).

| Endpoint                                                                                              | Data Returned                                          | Ordering / Scope                                             | Best For                                                                   |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------ | -------------------------------------------------------------------------- |
| [allMids](https://hydromancer.xyz/docs/rest-api/asset-data/allmids)                                   | Live mid prices                                        | All perp assets (default dex; `dex: ALL_DEXS` for every dex) | Lightweight ticker & portfolio valuation                                   |
| [assetContext](https://hydromancer.xyz/docs/rest-api/asset-data/assetcontext)                         | Live mid, mark, oracle, impact prices, OI & 24h volume | One coin, or up to 20 per request                            | Quote widgets, mark/oracle spread checks, OI and 24h volume                |
| [oraclePriceHistory](https://hydromancer.xyz/docs/rest-api/asset-data/oraclepricehistory)             | Recent oracle price updates                            | Newest first, single coin                                    | Quick recent oracle lookback                                               |
| [oraclePriceHistoryByTime](https://hydromancer.xyz/docs/rest-api/asset-data/oraclepricehistorybytime) | Historical oracle price updates                        | Oldest first, time range                                     | Oracle auditing (HIP-3: deployer-submitted prices)                         |
| [perpPriceHistoryByTime](https://hydromancer.xyz/docs/rest-api/asset-data/perppricehistorybytime)     | Accepted oracle **and** mark prices                    | Oldest first, time range, 1–20 perps                         | Historical mark-vs-oracle divergence, margining & liquidation verification |


# assetContext

Get the Hyperliquid asset context (mid, mark and oracle price, for example) of one or more symbols.

## Single coin

Request

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"</code>assetContext<code>"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>symbol e.g. "BTC" or with dex prefix "xyz:XYZ100"</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "assetContext",
    "coin": "BTC"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'assetContext',
        'coin': 'BTC'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)

print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post('https://api.hydromancer.xyz/info', {
    type: 'assetContext',
    coin: 'BTC'
}, {
    headers: {
        'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
        'Content-Type': 'application/json'
    }
});

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
{
  "oraclePx": "96500.50",
  "markPx": "96485.25",
  "midPx": "96490.50",
  "impactPxs": [ "96490", "96491" ],
  "openInterest": "25401.1214",
  "dayNtlVlm": "1643278247.97882",
  "dayBaseVlm": "26703.40439"
}
```

</details>

{% hint style="warning" %}
If the coin is not found (all prices are unavailable), the endpoint returns `HTTP 404 Not Found`.
{% endhint %}

***

## Multiple coins

Query up to 20 coins in a single request. Use `coins` instead of `coin`.

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"assetContext"</code></td></tr><tr><td><code>coins</code></td><td>string[]</td><td>Array of symbols, max 20. e.g. <code>["BTC", "ETH"]</code></td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "assetContext",
    "coins": ["BTC", "ETH", "SOL"]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'assetContext',
        'coins': ['BTC', 'ETH', 'SOL']
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)

print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post('https://api.hydromancer.xyz/info', {
    type: 'assetContext',
    coins: ['BTC', 'ETH', 'SOL']
}, {
    headers: {
        'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
        'Content-Type': 'application/json'
    }
});

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
{
  "BTC": {
    "oraclePx": "96500.50",
    "markPx": "96485.25",
    "midPx": "96490.50",
    "impactPxs": [ "96490", "96491" ],
    "openInterest": "25401.1214",
    "dayNtlVlm": "1643278247.97882",
    "dayBaseVlm": "26703.40439"
  },
  "ETH": {
    "oraclePx": "3450.10",
    "markPx": "3448.75",
    "midPx": "3449.50",
    "impactPxs": [ "3449", "3450" ],
    "openInterest": "192841.521",
    "dayNtlVlm": "543210987.65432",
    "dayBaseVlm": "157234.21098"
  },
  "SOL": null
}
```

</details>

{% hint style="info" %}
Coins that are not found return `null` in the response map instead of causing a 404.
{% endhint %}

***

## Response Fields

| Field          | Type    | Description                                                                                                                                                                                                                                                               |
| -------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `oraclePx`     | string? | Oracle price (null if not available)                                                                                                                                                                                                                                      |
| `markPx`       | string? | Mark price (null if not available)                                                                                                                                                                                                                                        |
| `midPx`        | string? | Mid price (null if not available)                                                                                                                                                                                                                                         |
| `impactPxs`    | array?  | Avg execution price to trade impact notional (20k$ BTC/ETH, 6k$ other coins) on the bid and ask (null if not available)                                                                                                                                                   |
| `openInterest` | string? | Number of outstanding contracts (null if not available)                                                                                                                                                                                                                   |
| `dayNtlVlm`    | string? | 24-hour notional volume — sum of price × size over the trailing 24 hours. `"0.0"` for an untraded perp; null for a coin absent from the context store, or briefly after a service restart while the 24h window re-seeds (last-known values are preserved where available) |
| `dayBaseVlm`   | string? | 24-hour base volume — sum of size over the trailing 24 hours. `"0.0"` for an untraded perp; null for a coin absent from the context store, or briefly after a service restart while the 24h window re-seeds (last-known values are preserved where available)             |


# oraclePriceHistory

Returns the most recent Hyperliquid oracle price updates for a coin in descending order (newest first).

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"</code>oraclePriceHistory<code>"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>symbol e.g. "BTC" or with dex prefix "xyz:XYZ100"</td></tr><tr><td><code>limit</code></td><td>int</td><td>max 2000</td></tr><tr><td><code>dex</code></td><td>string</td><td>DEX identifier e.g. "hyna", "xyz" (optional, returns all if omitted)</td></tr></tbody></table>

Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "oraclePriceHistory",
    "coin": "BTC",
    "limit": 100
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import os

import requests

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'oraclePriceHistory',
        'coin': 'BTC',
        'limit': 100
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)

print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'oraclePriceHistory',
    coin: 'BTC',
    limit: 100
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field       | Type    | Description                                                                                                                      |
| ----------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `time`      | int     | Unix timestamp in milliseconds                                                                                                   |
| `dex`       | string  | DEX source (e.g. `"hyna"`)                                                                                                       |
| `coin`      | string  | Coin symbol                                                                                                                      |
| `oraclePx`  | string? | Oracle price (null if not available)                                                                                             |
| `markPx`    | string? | Mark price (null if not available)                                                                                               |
| `markPx2`   | string? | Secondary mark price, only relevant for some HIP-3 dexes (available from 12 Jan 2026, null for earlier data or non-HIP-3 assets) |
| `extPerpPx` | string? | External perp price (null if not available)                                                                                      |

<details>

<summary>Response</summary>

```json
[ 
    { 
        "time": 1765641295024, 
        "dex": "hyna", 
        "coin": "hyna:BTC", 
        "oraclePx": "90090.00",
        "markPx": "90063.00",
        "markPx2": "90061.50",
        "extPerpPx": "90055.85"
    },
    {
        "time": 1765641292010,
        "dex": "hyna",
        "coin": "hyna:BTC",
        "oraclePx": "90090.00",
        "markPx": "90063.00",
        "markPx2": "90061.50",
        "extPerpPx": "90055.85" 
    } 
]
```

</details>


# oraclePriceHistoryByTime

Returns Hyperliquid oracle price updates for a coin within a time range in ascending order (oldest first).

{% hint style="info" %}
For HIP-3 dexes this endpoint returns the prices the dex deployer **submitted** in its `setOracle` action (`markPx` / `markPx2` are the mark-price inputs). The prices the network **accepted** for the round — the ones used for margining and liquidation — are served by [perpPriceHistoryByTime](https://hydromancer.xyz/docs/rest-api/asset-data/perppricehistorybytime). For the native dex the two endpoints agree.
{% endhint %}

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"oraclePriceHistoryByTime"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>symbol e.g. "BTC" or with dex prefix "xyz:XYZ100"</td></tr><tr><td><code>startTime</code></td><td>int</td><td>ms unix timestamp</td></tr><tr><td><code>endTime</code></td><td>int</td><td>ms unix timestamp (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>max 2000</td></tr><tr><td><code>dex</code></td><td>string</td><td>DEX identifier e.g. "hyna", "xyz" (optional, returns all if omitted)</td></tr></tbody></table>

Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
-H "Authorization: Bearer $HYDROMANCER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
      "type": "oraclePriceHistoryByTime",
      "coin": "BTC",
      "startTime": 1765641292010,
      "endTime": 1765641295024
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
 'https://api.hydromancer.xyz/info',
 json={
        'type': 'oraclePriceHistoryByTime',
        'coin': 'BTC',
        'startTime': 1765641292010,
        'endTime': 1765641295024
 },
 headers={
          'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
          'Content-Type': 'application/json'
      }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'oraclePriceHistoryByTime',
    coin: 'BTC',
    limit: 100,
    startTime: 1765641292010,
    endTime: 1765641295024
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field       | Type    | Description                                                                                      |
| ----------- | ------- | ------------------------------------------------------------------------------------------------ |
| `time`      | int     | Timestamp (ms)                                                                                   |
| `dex`       | string  | DEX identifier                                                                                   |
| `coin`      | string  | Trading pair                                                                                     |
| `oraclePx`  | string? | Oracle price                                                                                     |
| `markPx`    | string? | Mark price (first input)                                                                         |
| `markPx2`   | string? | Mark price (second input) — added from 2026-01-12, only present if hip3 dex pushes 2 mark prices |
| `extPerpPx` | string? | External perp price                                                                              |

<details>

<summary>Response (HIP-3 dex with 2 mark prices)</summary>

```json
[
  {
    "time": 1767965552339,
    "dex": "xyz",
    "coin": "xyz:XYZ100",
    "oraclePx": "25546.00",
    "markPx": "25546.00",
    "markPx2": "25545.00",
    "extPerpPx": "25546.00"
  },
  {
    "time": 1767965555526,
    "dex": "xyz",
    "coin": "xyz:XYZ100",
    "oraclePx": "25555.00",
    "markPx": "25555.00",
    "markPx2": "25554.00",
    "extPerpPx": "25555.00"
  }
]
```

</details>

<details>

<summary>Response (HIP-3 dex with 1 mark price)</summary>

```json
[
  {
    "time": 1767965617506,
    "dex": "hyna",
    "coin": "hyna:BTC",
    "oraclePx": "90527.00",
    "markPx": "90508.27",
    "extPerpPx": "90473.25"
  },
  {
    "time": 1767965620725,
    "dex": "hyna",
    "coin": "hyna:BTC",
    "oraclePx": "90528.00",
    "markPx": "90502.00",
    "extPerpPx": "90473.25"
  }
]
```

</details>


# perpPriceHistoryByTime

Returns the accepted oracle and mark prices of a Hyperliquid perp within a time range.

Rows are in ascending order (oldest first), one per oracle round (roughly every 3 seconds per dex). These are the prices the exchange actually uses for margining and liquidation, on every dex including HIP-3.&#x20;

For HIP-3 they are the values the network **accepted** for the round, not what the dex deployer submitted in its `setOracle` action — use [oraclePriceHistoryByTime](https://hydromancer.xyz/docs/rest-api/asset-data/oraclepricehistorybytime) for the raw submission. For the native Hyperliquid dex both endpoints return the same validator round.

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpPriceHistoryByTime"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>symbol e.g. "BTC" or with dex prefix "xyz:XYZ100"</td></tr><tr><td><code>coins</code></td><td>string[]</td><td>batch form: 1–20 symbols. <code>prices</code> is then an object keyed by coin instead of an array. Use <em>either</em> <code>coin</code> or <code>coins</code>.</td></tr><tr><td><code>startTime</code></td><td>int</td><td>ms unix timestamp</td></tr><tr><td><code>endTime</code></td><td>int</td><td>ms unix timestamp (optional)</td></tr><tr><td><code>limit</code></td><td>int</td><td>1–2000 (default 2000)</td></tr><tr><td><code>dex</code></td><td>string</td><td>DEX identifier e.g. "hyna", "xyz"; "main_dex" for the native dex (optional, returns all if omitted)</td></tr></tbody></table>

Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
-H "Authorization: Bearer $HYDROMANCER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
      "type": "perpPriceHistoryByTime",
      "coin": "xyz:AAOI",
      "startTime": 1787528956000,
      "endTime": 1787528966000
    }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
 'https://api.hydromancer.xyz/info',
 json={
        'type': 'perpPriceHistoryByTime',
        'coin': 'xyz:AAOI',
        'startTime': 1787528956000,
        'endTime': 1787528966000
 },
 headers={
          'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
          'Content-Type': 'application/json'
      }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpPriceHistoryByTime',
    coin: 'xyz:AAOI',
    limit: 100,
    startTime: 1787528956000,
    endTime: 1787528966000
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Batch (multiple coins)

Pass `coins` (an array of 1–20 symbols) instead of `coin` to fetch several markets over the same time range in one request. `startTime`, `endTime` and `dex` apply to every coin. `limit` is **per coin, max 100** in the batch form (default 100) — so a 20-coin batch returns at most \~2000 rows; use the single-coin form for a wider window on one market. `prices` is an **object keyed by coin**, each value the same row array as the single-coin form; a requested coin with no data maps to an empty array. There is one `height` for all coins.

This is served by a single ClickHouse query (`coin` is the table's leading sort key), so it is cheaper than looping the single-coin request. Billing is **1 token per coin** (a single-coin request is 1 token), and the rate-limit cost scales with the number of coins.

```bash
curl -X POST https://api.hydromancer.xyz/info \
-H "Authorization: Bearer $HYDROMANCER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
      "type": "perpPriceHistoryByTime",
      "coins": ["BTC", "xyz:GOLD"],
      "startTime": 1787528956000,
      "endTime": 1787528966000
    }'
```

```json
{
  "height": 1130393772,
  "timestamp": 1787528959402,
  "prices": {
    "BTC": [ { "time": 1787528958000, "blockNumber": 1130393728, "dex": "hyperliquid", "coin": "BTC", "oraclePx": "...", "markPx": "..." } ],
    "xyz:GOLD": [ { "time": 1787528958000, "blockNumber": 1130393728, "dex": "xyz", "coin": "xyz:GOLD", "oraclePx": "...", "markPx": "...", "updateClass": "Normal" } ]
  }
}
```

## Knowing a time window is complete

Every response tells you how far we had processed the chain:

```json
{
  "height": 1130393772,
  "timestamp": 1787528959402,
  "prices": [ { "time": 1787528956211, "blockNumber": 1130393728, "coin": "BTC", "...": "..." } ]
}
```

`height` is the latest block we had processed when we answered. Price rounds up to that block are normally all in `prices`. `height` is usually past the last row, because most blocks carry no price round.

**Example.** Your window ends at 16:30:00. The last BTC round was at 16:29:58. You poll at 16:30:00.5 and get `timestamp` 16:30:00.3 with no new row. We had processed the chain past 16:30:00 and saw no BTC round after 16:29:58, so you don't have to wait for the next round to see that.

* **Look for `timestamp` past the window end.** Wait for `timestamp` greater than the end, not equal to it. Several blocks can share the same millisecond.
* **A page cut by `limit`** only reaches its last row. Fetch the next page from there.
* **While our storage catches up**, the response can stop at an older `height` even though newer rounds exist. Rows never skip a round: poll again until `timestamp` passes your window end.
* **`height` is the same for all coins and dexes.** In the batch form there is one `height` for all coins, and `prices` is keyed by coin.
* **No rows for a coin means no price round for it.** For HIP-3 this also covers a deployer that stopped posting prices.
* **`503`** means the height is not known yet, which only happens for a few seconds after a restart. Retry.

The perpPrices WebSocket [`height`](https://hydromancer.xyz/docs/websocket/prices-data-and-asset-context/perpprices#knowing-a-time-window-is-complete) means the same thing.

## Response Fields

| Field       | Type               | Description                                                       |
| ----------- | ------------------ | ----------------------------------------------------------------- |
| `height`    | int                | The latest block we had processed when we answered                |
| `timestamp` | int                | Block timestamp of `height` (ms)                                  |
| `prices`    | object\[] / object | The rows, oldest first; in the batch form an object keyed by coin |

Each row in `prices`:

| Field         | Type    | Description                                                                                                                                                                                                                                                                |
| ------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `time`        | int     | Block timestamp of the oracle round (ms)                                                                                                                                                                                                                                   |
| `blockNumber` | int     | Height of the block that committed the round — joins to `userFillsByTime` / block-level data                                                                                                                                                                               |
| `dex`         | string  | DEX identifier (`"hyperliquid"` for the native dex)                                                                                                                                                                                                                        |
| `coin`        | string  | Trading pair                                                                                                                                                                                                                                                               |
| `oraclePx`    | string? | Accepted oracle price. Omitted when the round carried no oracle slot for the asset: delisted native assets kept a frozen `markPx` with no oracle until 2026-06-13 (they drop out entirely after that), and the natively-priced HYPE/PURR miss the slot in \~2 rounds a day |
| `markPx`      | string  | Accepted mark price — the value used for margining, liquidations and funding. Always present                                                                                                                                                                               |
| `extPerpPx`   | string? | External perp reference price; omitted for assets without one                                                                                                                                                                                                              |
| `updateClass` | string? | HIP-3 only: how the network sourced the round as reported by the node (`"Deployer"`, `"Fallback"`, `"Normal"`). Omitted for the native dex                                                                                                                                 |

When a block commits more than one oracle round for the same dex, the last round is returned.

Accepted HIP-3 rounds are available from 2026-02-24; native rounds from 2025-08-01.

<details>

<summary>Response (HIP-3 dex)</summary>

```json
{
  "height": 1130393790,
  "timestamp": 1787528960657,
  "prices": [
    {
      "time": 1787528956211,
      "blockNumber": 1130393728,
      "dex": "xyz",
      "coin": "xyz:AAOI",
      "oraclePx": "106.88",
      "markPx": "106.97",
      "extPerpPx": "106.88",
      "updateClass": "Deployer"
    },
    {
      "time": 1787528959402,
      "blockNumber": 1130393772,
      "dex": "xyz",
      "coin": "xyz:AAOI",
      "oraclePx": "106.88",
      "markPx": "106.96",
      "extPerpPx": "106.88",
      "updateClass": "Deployer"
    }
  ]
}
```

</details>

<details>

<summary>Response (native dex)</summary>

```json
{
  "height": 1130393790,
  "timestamp": 1787528960657,
  "prices": [
    {
      "time": 1787528956211,
      "blockNumber": 1130393728,
      "dex": "hyperliquid",
      "coin": "BTC",
      "oraclePx": "108712.00",
      "markPx": "108708.40",
      "extPerpPx": "108709.50"
    },
    {
      "time": 1787528959402,
      "blockNumber": 1130393772,
      "dex": "hyperliquid",
      "coin": "BTC",
      "oraclePx": "108715.00",
      "markPx": "108711.10",
      "extPerpPx": "108712.00"
    }
  ]
}
```

</details>


# allMids

Get the mid prices of all Hyperliquid perp assets.

Request

<table><thead><tr><th width="115.50848388671875">Field</th><th width="177.66351318359375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"</code>allMids<code>"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td><strong>optional</strong> will default to the first dex, can set to ALL_DEXS for all mids of all dexes</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "allMids",
    "dex": ""
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'allMids',
        'dex': ''
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)

print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post('https://api.hydromancer.xyz/info', {
    type: 'allMids',
    dex: ''
}, {
    headers: {
        'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
        'Content-Type': 'application/json'
    }
});

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns a JSON object where each key is a coin symbol and the value is the mid price as a string.

| Field    | Type   | Description                  |
| -------- | ------ | ---------------------------- |
| `{coin}` | string | Mid price for the given coin |

{% hint style="warning" %}
Currently only returns perp mid prices, not spot mid prices.
{% endhint %}

<details>

<summary>Response</summary>

```json
{
  "BTC": "96500.50",
  "ETH": "3000.21",
  ....
}
```

</details>

## Structured errors

Select `X-HM-Error-Format: structured-v1` to receive confirmed structured errors. A DEX name longer than six bytes returns 400 with code `invalid_request`, except for the `ALL_DEXS` and `ALL_DEXES` sentinels. A mid-price fetch failure returns 503 with code `unavailable` and the public message `Mid-prices are temporarily unavailable`.

Without selection, DEX validation keeps its existing 400 response and fetch failures keep their text/plain 500 response. Successful price maps and decimal strings keep their existing format. A non-success HTTP response from the orderbook service currently produces an empty successful map. See [structured errors](https://hydromancer.xyz/docs/rest-api#opt-in-structured-errors) for confirmation and SDK behavior.


# Market data

Endpoints for market-wide Hyperliquid data: open interest history, position and TWAP snapshots, L4 orderbooks, liquidity, slippage and funding payments.

Query market-wide Hyperliquid positioning, orderbook snapshots, liquidity depth, slippage, open interest, and hourly funding snapshots via the [Hydromancer REST API](https://hydromancer.xyz/hyperliquid-rest-api).&#x20;

For live sub-second depth updates, see [Hyperliquid orderbook streaming](https://hydromancer.xyz/orderbook-streaming).

| Category                           | Endpoints                                                                                                                                                                                                                                                                                                                                                                                                                                           | Best For                                                     |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| **Orderbook & trigger snapshots**  | [l4Book](https://hydromancer.xyz/docs/rest-api/market-data/l4book), [l2Book](https://hydromancer.xyz/docs/rest-api/market-data/l2book), [l2BookDiffSnapshot](https://hydromancer.xyz/docs/rest-api/market-data/l2bookdiffsnapshot), [tpslBook](https://hydromancer.xyz/docs/rest-api/market-data/tpslbook)                                                                                                                                          | Bootstrapping L2/L4 books and building TP/SL heatmaps        |
| **Market-wide trader snapshots**   | [perpSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/perpsnapshot), [spotSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/spotsnapshot), [accountValueSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/accountvaluesnapshot), [perpTwapSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/perptwapsnapshot), [spotTwapSnapshots](https://hydromancer.xyz/docs/rest-api/market-data/spottwapsnapshot) | Whale positioning, OI distribution, and active TWAP trackers |
| **Liquidity & slippage analytics** | [currentDepth](https://hydromancer.xyz/docs/rest-api/market-data/currentdepth), [marketLiquidity](https://hydromancer.xyz/docs/rest-api/market-data/marketliquidity), [marketLiquidityHistory](https://hydromancer.xyz/docs/rest-api/market-data/marketliquidityhistory), [slippageHistory](https://hydromancer.xyz/docs/rest-api/market-data/slippagehistory)                                                                                      | Execution quality benchmarks and BPS depth monitoring        |
| **OI, funding & order limits**     | [openInterestHistory](https://hydromancer.xyz/docs/rest-api/market-data/openinteresthistory), [fundingPayments](https://hydromancer.xyz/docs/rest-api/market-data/fundingpayments), [maxMarketOrderNtls](https://hydromancer.xyz/docs/rest-api/market-data/maxmarketorderntls), [perpsAtOpenInterestCap](https://hydromancer.xyz/docs/rest-api/market-data/perpsatopeninterestcap)                                                                  | Risk dashboards, OI caps, and market-wide funding analytics  |

{% hint style="info" %}
**Add-on endpoints:** `perpSnapshots`, `spotSnapshots`, `accountValueSnapshots`, and `currentDepth` are add-on endpoints; access is purchased separately. See [API Costs & Request Weights](https://hydromancer.xyz/docs/pricing).
{% endhint %}


# openInterestHistory

Historical OHLC of Hyperliquid open interest, per coin or per sector, in contracts and USD.

{% hint style="info" %}
`openInterestHistory` is a Hydromancer addition — it is not available on the native Hyperliquid API, which only exposes the *current* open interest.
{% endhint %}

### Overview

Returns open interest as an OHLC time series, rolled up to any interval, reconstructed minute-by-minute from fills and periodic on-chain state. Two modes:

* **Per coin** — pass `coin`. Returns OI in contracts (OHLC) plus its USD notional. `oiClose` matches Hyperliquid's `openInterest` for that coin 1:1.
* **Per sector** — pass `sector`. Returns the summed **USD** OI across a group of markets (OHLC). Contracts aren't additive across different markets, so sector OI is dollars only.

`coin` and `sector` are mutually exclusive. History is available from **2025-08-01**; earlier `startTime`s are clamped to that.

Open interest follows the Hyperliquid convention — it is **two-sided**: the sum of all long *and* all short positions (equivalently, 2× the one-sided outstanding contracts). See [Convention](#convention).

### Request

* **Endpoint**: `POST /info`

**Per coin:**

```json
{
    "type": "openInterestHistory",
    "coin": "BTC",
    "interval": "1h",
    "startTime": 1753833600000,
    "endTime": 1753920000000
}
```

**Per sector:**

```json
{
    "type": "openInterestHistory",
    "sector": "hip3",
    "interval": "1d",
    "startTime": 1753833600000
}
```

| Field       | Type   | Required               | Description                                                                         |
| ----------- | ------ | ---------------------- | ----------------------------------------------------------------------------------- |
| `coin`      | string | One of `coin`/`sector` | Coin name. For HIP-3 assets, prefix with dex name (e.g. `"xyz:SP500"`)              |
| `sector`    | string | One of `coin`/`sector` | Market group to aggregate (see [sectors](#sectors)). Mutually exclusive with `coin` |
| `interval`  | string | Yes                    | Bucket interval (see [valid intervals](#valid-intervals))                           |
| `startTime` | number | Yes                    | Start time in milliseconds since epoch (inclusive). Clamped to 2025-08-01           |
| `endTime`   | number | No                     | End time in milliseconds since epoch (exclusive). Defaults to now                   |
| `limit`     | number | No                     | Maximum number of buckets to return. Default and max: 5000                          |

#### Sectors

| `sector`    | Aggregates                                                |
| ----------- | --------------------------------------------------------- |
| `total`     | Every market on every dex                                 |
| `native`    | The core Hyperliquid dex only                             |
| `hip3`      | Every builder (HIP-3) dex — i.e. everything except native |
| `<dexName>` | A single named dex, e.g. `"xyz"`, `"hyna"`                |

An unknown dex name returns an empty array.

#### Valid intervals

| Interval | Duration                 |
| -------- | ------------------------ |
| `1m`     | 1 minute                 |
| `3m`     | 3 minutes                |
| `5m`     | 5 minutes                |
| `15m`    | 15 minutes               |
| `30m`    | 30 minutes               |
| `1h`     | 1 hour                   |
| `2h`     | 2 hours                  |
| `4h`     | 4 hours                  |
| `8h`     | 8 hours                  |
| `12h`    | 12 hours                 |
| `1d`     | 1 day                    |
| `3d`     | 3 days                   |
| `1w`     | 1 week (Monday-aligned)  |
| `1M`     | 1 month (calendar month) |

### Response

Returns a JSON array sorted by time ascending. Maximum 5000 buckets per request.

**Per coin** — OI in contracts (OHLC) plus USD:

```json
[
    {
        "t": 1753833600000,
        "oiOpen": "34871.33654",
        "oiHigh": "34929.32676",
        "oiLow": "34672.06294",
        "oiClose": "34841.65018",
        "oiUsd": "2083983622.21634"
    }
]
```

| Field     | Type           | Description                                                                 |
| --------- | -------------- | --------------------------------------------------------------------------- |
| `t`       | number         | Bucket start time (milliseconds)                                            |
| `oiOpen`  | string         | Open interest (contracts) at the bucket open                                |
| `oiHigh`  | string         | Highest open interest in the bucket                                         |
| `oiLow`   | string         | Lowest open interest in the bucket                                          |
| `oiClose` | string         | Open interest at the bucket close. Matches Hyperliquid's `openInterest` 1:1 |
| `oiUsd`   | string \| null | USD notional = `oiClose × mark`. `null` when no mark is known (see note)    |

**Per sector** — USD only:

```json
[
    {
        "t": 1753833600000,
        "oiUsdOpen": "9569412034.55",
        "oiUsdHigh": "9612388120.10",
        "oiUsdLow": "9540117234.22",
        "oiUsdClose": "9585021998.71"
    }
]
```

| Field        | Type   | Description                                        |
| ------------ | ------ | -------------------------------------------------- |
| `t`          | number | Bucket start time (milliseconds)                   |
| `oiUsdOpen`  | string | Summed USD OI across the sector at the bucket open |
| `oiUsdHigh`  | string | Highest summed USD OI in the bucket                |
| `oiUsdLow`   | string | Lowest summed USD OI in the bucket                 |
| `oiUsdClose` | string | Summed USD OI at the bucket close                  |

#### Convention

{% hint style="info" %}
Open interest is **two-sided**, following the Hyperliquid convention: it is the sum of all long *and* all short positions (equivalently, 2× the one-sided outstanding contracts). This matches Hyperliquid's `openInterest` and Hydromancer's `oi` field 1:1. The USD value uses the oracle mark price, falling back to the last-trade price where no oracle price exists.
{% endhint %}

{% hint style="warning" %}
**`oiUsd` may be `null`.** A bucket has no USD value when no mark price was known for that market at that time — e.g. a freshly-listed market before its first trade, or history before the oracle price feed began (2025-08-01). The open interest itself (contracts) is always present; only the USD denominator is unknown. Sector totals simply skip such markets.
{% endhint %}

### Rate limits

5 points per request (see [rate limits](https://hydromancer.xyz/docs/rest-api/rate-limits-and-user-limits)).

### Examples

{% tabs %}
{% tab title="Python" %}

```python
import requests
import os

api_key = os.environ["HYDROMANCER_API_KEY"]
base_url = os.getenv("HYDROMANCER_API_URL", "https://api.hydromancer.xyz")

def oi_history(body):
    return requests.post(
        f"{base_url}/info",
        json={"type": "openInterestHistory", **body},
        headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"},
    ).json()

# Per coin — daily BTC open interest
for c in oi_history({"coin": "BTC", "interval": "1d", "startTime": 1753833600000}):
    print(f"{c['t']}  oi={c['oiClose']}  usd={c['oiUsd']}")

# Per sector — daily total HIP-3 open interest, in USD
for c in oi_history({"sector": "hip3", "interval": "1d", "startTime": 1753833600000}):
    print(f"{c['t']}  hip3_usd={c['oiUsdClose']}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

const apiKey = process.env.HYDROMANCER_API_KEY;
const baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';

async function oiHistory(body) {
    const resp = await axios.post(
        `${baseUrl}/info`,
        { type: 'openInterestHistory', ...body },
        { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` } }
    );
    return resp.data;
}

// Per coin — daily BTC open interest
for (const c of await oiHistory({ coin: 'BTC', interval: '1d', startTime: 1753833600000 })) {
    console.log(`${c.t}  oi=${c.oiClose}  usd=${c.oiUsd}`);
}

// Per sector — daily total HIP-3 open interest, in USD
for (const c of await oiHistory({ sector: 'hip3', interval: '1d', startTime: 1753833600000 })) {
    console.log(`${c.t}  hip3_usd=${c.oiUsdClose}`);
}
```

{% endtab %}
{% endtabs %}

### Common errors

| Error                                | Cause                                                                                                    |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `unsupported interval: <x>`          | Interval string not in the valid list above                                                              |
| `Missing startTime field`            | `startTime` not provided                                                                                 |
| `range too wide for interval <x>: …` | The range at that interval exceeds the 5000-bucket cap — use a coarser interval or a narrower time range |
| `invalid sector: <x>`                | `sector` is not a keyword or a valid dex name                                                            |
| `<coin> has no open interest`        | `coin` is a spot or outcome market (no perp open interest)                                               |


# perpSnapshots

Unique endpoint allowing to get entire perps positioning of all Hyperliquid traders.

{% hint style="info" %}
💧**New endpoint - this endpoint is not part of the original Hyperliquid API. Hydromancer added it for builder convenience.**
{% endhint %}

{% hint style="warning" %}

### ⚠️ This is an add-on endpoint - access has to be purchased separately.

{% endhint %}

### Overview

perpSnapshot endpoint allows you to access the entire positioning of all traders on Hyperliquid across all assets, including entries and liquidations.

There are two ways to access the data:

1. **Metadata Endpoint (Fast)**: Check for updates without downloading data
2. **Snapshots Endpoint (Heavy)**: Download actual market snapshot data

<details>

<summary>Efficient polling pattern</summary>

To minimize bandwidth and server load, you should:

1. Poll the metadata endpoint to check for updates
2. Only call the snapshots endpoint when data has changed
3. Cache the snapshot ID locally to avoid unnecessary downloads

</details>

<details>

<summary>Dependencies and best practices</summary>

#### Dependencies

**JavaScript**

* **zstd**: For decompression (e.g., `fzstd`, `@gera2ld/zstd`)
* **msgpack**: For decoding (e.g., `@msgpack/msgpack`)

**Python**

* **zstd**: For decompression (e.g., `zstandard`)
* **msgpack**: For decoding (e.g., `msgpack`)
* **aiohttp**: For async HTTP requests

***

✅ **Best Practices**

1. **Always poll metadata first** - Don't skip the lightweight metadata check.
2. **Cache snapshots locally** - Avoid unnecessary downloads of large files.
3. **Handle errors gracefully** - Network issues are common; implement retry logic.
4. **Use appropriate poll intervals** - 5-10 seconds is usually sufficient.
5. **Request specific markets** - Don't use `['ALL']` unless you truly need all data.
6. **Monitor bandwidth usage** - Snapshots can be large (1-13MB+).

</details>

<details>

<summary>Error handling</summary>

* **404**: No snapshots are available yet. Wait and retry.
* **500**: A server error occurred. Retry with exponential backoff.
* **Network errors**: Implement retry logic with jitter to avoid overwhelming the server.
* **Parse errors**: Log the issue and continue using cached data if available.

</details>

### Perp Snapshot Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check if snapshots have been updated
* **Response Time**: \~1ms

#### Request

```json
{
  "type": "perpSnapshotTimestamp"
}
```

#### Response

```json
{
  "snapshot_id": "20240915_state_123456789",
  "timestamp": 1694764800
}
```

### Perp Snapshots (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download market snapshot data
* **Response Time**: \~100ms+

#### Request

```json
{
  "type": "perpSnapshots",
  "market_names": ["BTC", "FARTCOIN"]  // or ["ALL"] for all core markets
}
```

## Query Options (HIP-3 Multi-Dex)

**Specific markets:**

* `["BTC", "ETH"]` → Defaults to the main dex
* `["xyz:BTC", "vntl:ETH"]` → Specify DEX with `dex:market` format

**All markets patterns:**

* `["ALL"]` → All markets from the main dex
* `["ALL:xyz"]` → All markets from xyz DEX
* `["ALL:ALL_DEXES"]` → All markets from all available DEXes (takes precedence over everything)

**Mixed queries:**

* `["ALL", "ALL:xyz", "BTC"]` → All from main dex + all from xyz (BTC ignored, covered by main dex)
* `["ALL:xyz", "vntl:ETH"]` → All from xyz + specific ETH from vntls

**Rules:**

1. `ALL:ALL_DEXES` takes precedence - if present, returns everything from all dexes
2. Multiple `ALL` patterns allowed - one per dex (e.g., `["ALL", "ALL:xyz"]` gets all from both)
3. Specific markets are filtered - if a dex is covered by an ALL pattern, specific markets from that dex are ignored
4. No duplicates - each dex's ALL pattern is deduplicated

#### Response Headers

* **Single Market**: `x-payload-format: msgpack`, `Content-Encoding: zstd`
* **Multiple Markets**: `x-payload-format: multi-zstd`, `x-compression: inner-zstd`

### Data Format

<details>

<summary>Single Market Response</summary>

**Format**: Raw zstd-compressed MessagePack data

**Decompressed Structure:**

{% code overflow="wrap" %}

```json
[
  "20240915_state_123456789",       // Snapshot ID
  "BTC",                            // Market ID
  [                                 // Positions array
    [1.5, 1500.0, -2.5, 1000.0, 0.0, 5.0, 950.0, 10000.0],
    [/* more position tuples */]
  ],
  [                                 // Addresses array
    "0x1234567890abcdef...",
    "0xfedcba0987654321...",
    /* more addresses */
  ]
}
```

{% endcode %}

ℹ️ **Position Tuple Format** The array `p` contains tuples with the following 8 values in order:

```
size
notional_size
funding_pnl
entry_price
leverage_type_flag // 0 is cross and 1 is isolated
leverage_multiplier
liquidation_price  // Adjusted for unified/PM cross-collateral
account_value      // Reflects unified or PM total account value
```

{% hint style="info" %}
**Unified & Portfolio Margin accounts:** For unified account users, `account_value` includes spot collateral across all dexes. For Portfolio Margin users, `account_value` reflects the per-settlement-token equity and `liquidation_price` is recomputed using PM available margin. Use the `accountValueSnapshots` endpoint to get the full PM breakdown (pm\_ratio, avail per branch).
{% endhint %}

</details>

<details>

<summary>Multiple Markets Response</summary>

**Format**: Custom binary format with length prefixes

**Binary Structure:**

{% code overflow="wrap" %}

```
[market_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]...
```

{% endcode %}

ℹ️ **Position Tuple Format** The array `p` contains tuples with the following 8 values in order:

```
size
notional_size
funding_pnl
entry_price
leverage_type_flag // 0 is cross and 1 is isolated
leverage_multiplier
liquidation_price  // Adjusted for unified/PM cross-collateral
account_value      // Reflects unified or PM total account value
```

{% hint style="info" %}
**Unified & Portfolio Margin accounts:** For unified account users, `account_value` includes spot collateral across all dexes. For Portfolio Margin users, `account_value` reflects the per-settlement-token equity and `liquidation_price` is recomputed using PM available margin. Use the `accountValueSnapshots` endpoint to get the full PM breakdown (pm\_ratio, avail per branch).
{% endhint %}

</details>

### Implementation examples

**Note**: Make sure to set **HYDROMANCER\_API\_KEY** in your .env file

Note: Make sure to download required packages

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { compress, decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
const fs = require('fs').promises;
require('dotenv').config();

class PerpSnapshotClient {
    constructor() {
        this.baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';
        this.apiKey = process.env.HYDROMANCER_API_KEY;
        
        if (!this.apiKey || this.apiKey === 'INSERT_API_KEY_HERE') {
            throw new Error('API key not found. Please set HYDROMANCER_API_KEY in .env file');
        }
        
        this.cachedTimestamp = null;
        this.cachedSnapshots = {};
        this.outputFile = 'perp_snapshot.json';
    }

    async checkForUpdates() {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                { type: 'perpSnapshotTimestamp' },
                { headers }
            );

            const currentTimestamp = response.data.timestamp || response.data.snapshot_id;
            const hasUpdates = this.cachedTimestamp !== currentTimestamp;
            
            if (hasUpdates) {
                console.log(`Perp snapshot updated: ${this.cachedTimestamp} -> ${currentTimestamp}`);
                this.cachedTimestamp = currentTimestamp;
            } else {
                console.log(`No perp snapshot updates (timestamp: ${currentTimestamp})`);
            }

            return hasUpdates;
        } catch (error) {
            throw new Error(`Timestamp request failed: ${error.response?.status} - ${error.response?.data || error.message}`);
        }
    }

    async pollSnapshots(marketNames = ['BTC', 'ETH']) {
        try {
            const hasUpdates = await this.checkForUpdates();
            
            if (!hasUpdates) {
                console.log('No updates available, using cached perp data');
                return this.cachedSnapshots;
            }

            console.log('New perp snapshots available, downloading...');
            const snapshots = await this.downloadSnapshots(marketNames);
            
            this.cachedSnapshots = snapshots;
            await this.saveToFile(snapshots);
            
            return snapshots;
        } catch (error) {
            console.error('Error polling perpetual snapshots:', error);
            throw error;
        }
    }

    async downloadSnapshots(marketNames) {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                { type: 'perpSnapshots', market_names: marketNames },
                { 
                    headers,
                    responseType: 'arraybuffer'
                }
            );

            const payloadFormat = response.headers['x-payload-format'];
            const binaryData = Buffer.from(response.data);
            
            console.log(`Payload format: ${payloadFormat}`);
            console.log(`Downloaded ${binaryData.length} bytes`);
            
            if (payloadFormat === 'multi-zstd') {
                return await this.parseMultipleMarkets(binaryData);
            } else {
                // Single market - could be msgpack or zstd compressed
                return await this.parseSingleMarket(binaryData, marketNames[0]);
            }
        } catch (error) {
            throw new Error(`Perp snapshots request failed: ${error.response?.status} - ${error.response?.data || error.message}`);
        }
    }

    async parseSingleMarket(binaryData, marketName) {
        try {
            // Try to decompress first (if it's zstd compressed)
            let decompressed;
            try {
                decompressed = await decompress(binaryData);
                console.log('Successfully decompressed single market data');
            } catch (e) {
                // If decompression fails, assume it's already uncompressed msgpack
                console.log('Data appears to be uncompressed msgpack');
                decompressed = binaryData;
            }
            
            // Decode msgpack
            const data = msgpack.decode(decompressed);
            
            // According to docs, the structure could be:
            // For perps: [identifier, market, positions, addresses]
            if (Array.isArray(data) && data.length >= 4) {
                const [identifier, market, positions, addresses] = data;
                return {
                    [market]: {
                        identifier: identifier,
                        market: market,
                        positions: positions || [],
                        addresses: addresses || [],
                        timestamp: this.cachedTimestamp
                    }
                };
            }
            
            // Or it could be the object format from docs: {i, m, p, a}
            if (data.i !== undefined && data.m !== undefined) {
                return {
                    [marketName || data.m]: {
                        identifier: data.i,
                        market: data.m,
                        positions: data.p || [],
                        addresses: data.a || [],
                        timestamp: this.cachedTimestamp
                    }
                };
            }
            
            throw new Error('Unknown single market data format');
        } catch (error) {
            console.error('Error parsing single market:', error);
            throw error;
        }
    }

    async parseMultipleMarkets(binaryData) {
        let offset = 0;
        
        // Read number of snapshots (4 bytes, little-endian)
        const count = binaryData.readUInt32LE(offset);
        offset += 4;
        
        console.log(`Number of perp snapshots: ${count}`);
        
        const markets = {};
        
        for (let i = 0; i < count; i++) {
            // Read length of this snapshot (4 bytes, little-endian)
            const length = binaryData.readUInt32LE(offset);
            offset += 4;
            
            console.log(`Snapshot ${i + 1}/${count}: ${length} bytes`);
            
            // Extract and decompress snapshot
            const zstdData = binaryData.slice(offset, offset + length);
            
            try {
                const decompressed = await decompress(zstdData);
                const data = msgpack.decode(decompressed);
                
                // Handle array format: [identifier, market, positions, addresses]
                if (Array.isArray(data) && data.length >= 4) {
                    const [identifier, market, positions, addresses] = data;
                    markets[market] = {
                        identifier: identifier,
                        market: market,
                        positions: positions || [],
                        addresses: addresses || [],
                        timestamp: this.cachedTimestamp
                    };
                    console.log(`Parsed market: ${market} with ${positions?.length || 0} positions`);
                }
                // Handle object format: {i, m, p, a}
                else if (data.i !== undefined && data.m !== undefined) {
                    markets[data.m] = {
                        identifier: data.i,
                        market: data.m,
                        positions: data.p || [],
                        addresses: data.a || [],
                        timestamp: this.cachedTimestamp
                    };
                    console.log(`Parsed market: ${data.m} with ${data.p?.length || 0} positions`);
                }
            } catch (error) {
                console.error(`Error parsing snapshot ${i + 1}:`, error);
            }
            
            offset += length;
        }
        
        return markets;
    }

    async saveToFile(snapshots) {
        const outputData = {
            timestamp: this.cachedTimestamp,
            markets: {}
        };
        
        for (const [market, data] of Object.entries(snapshots)) {
            const positions = data.positions || [];
            const addresses = data.addresses || [];
            
            // Create readable position list (first 100 positions)
            const positionList = [];
            const numPositions = Math.min(100, positions.length, addresses.length);
            
            for (let i = 0; i < numPositions; i++) {
                if (Array.isArray(positions[i]) && positions[i].length >= 8) {
                    positionList.push({
                        address: addresses[i],
                        size: positions[i][0],
                        notional_size: positions[i][1],
                        funding_pnl: positions[i][2],
                        entry_price: positions[i][3],
                        leverage_type_flag: positions[i][4],
                        leverage_multiplier: positions[i][5],
                        liquidation_price: positions[i][6],
                        account_value: positions[i][7]
                    });
                }
            }
            
            outputData.markets[market] = {
                identifier: data.identifier,
                total_positions: positions.length,
                positions: positionList
            };
        }
        
        await fs.writeFile(this.outputFile, JSON.stringify(outputData, null, 2));
        console.log(`Saved perp snapshot to ${this.outputFile}`);
    }
}

// Example usage
async function main() {
    const client = new PerpSnapshotClient();
    
    while (true) {
        try {
            const snapshots = await client.pollSnapshots(['FARTCOIN', 'HYPE']);
            
            for (const [market, data] of Object.entries(snapshots)) {
                console.log(`Market ${market}: ${data.positions?.length || 0} positions`);
            }
            
            console.log('Waiting 5 seconds...');
            await new Promise(resolve => setTimeout(resolve, 5000));
            
        } catch (error) {
            console.error('Polling error:', error.message);
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
    }
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = PerpSnapshotClient;
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import aiohttp
import struct
from typing import Optional, Dict, List, Any
import time
import json
import zstandard as zstd
import msgpack
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()


class PerpSnapshotClient:
    def __init__(self):
        self.base_url = os.getenv('HYDROMANCER_API_URL', 'https://api.hydromancer.xyz')
        self.api_key = os.getenv('HYDROMANCER_API_KEY')
        
        if not self.api_key or self.api_key == 'INSERT_API_KEY_HERE':
            raise ValueError("API key not found. Please set HYDROMANCER_API_KEY in .env file")
            
        self.cached_timestamp: Optional[str] = None
        self.cached_snapshots: Dict[str, Any] = {}
        self.session: Optional[aiohttp.ClientSession] = None
        self.output_file = "perp_snapshot.json"

    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()

    async def check_for_updates(self) -> bool:
        """Check if snapshots have been updated since last poll"""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'perpSnapshotTimestamp'},
            headers=headers
        ) as response:
            if not response.ok:
                text = await response.text()
                raise Exception(f'Timestamp request failed: {response.status} - {text}')

            data = await response.json()
            current_timestamp = data.get('timestamp', data.get('snapshot_id'))
            
            has_updates = self.cached_timestamp != current_timestamp
            
            if has_updates:
                print(f'Perp snapshot updated: {self.cached_timestamp} -> {current_timestamp}')
                self.cached_timestamp = current_timestamp
            else:
                print(f'No perp snapshot updates (timestamp: {current_timestamp})')

            return has_updates

    async def poll_snapshots(self, market_names: List[str] = ["BTC", "ETH"]) -> Dict[str, Any]:
        """Efficiently poll for perpetual snapshots"""
        try:
            has_updates = await self.check_for_updates()
            
            if not has_updates:
                print('No updates available, using cached perp data')
                return self.cached_snapshots

            print('New perp snapshots available, downloading...')
            snapshots = await self.download_snapshots(market_names)
            
            self.cached_snapshots = snapshots
            await self.save_to_file(snapshots)
            
            return snapshots
        except Exception as error:
            print(f'Error polling perpetual snapshots: {error}')
            raise

    async def download_snapshots(self, market_names: List[str]) -> Dict[str, Any]:
        """Download perpetual market snapshots"""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'perpSnapshots', 'market_names': market_names},
            headers=headers
        ) as response:
            if not response.ok:
                text = await response.text()
                raise Exception(f'Perp snapshots request failed: {response.status} - {text}')

            payload_format = response.headers.get('x-payload-format')
            binary_data = await response.read()
            
            print(f"Payload format: {payload_format}")
            print(f"Downloaded {len(binary_data)} bytes")
            
            if payload_format == 'multi-zstd':
                return await self.parse_multiple_markets(binary_data)
            else:
                # Single market - could be msgpack or zstd compressed
                return await self.parse_single_market(binary_data, market_names[0])

    async def parse_single_market(self, binary_data: bytes, market_name: str) -> Dict[str, Any]:
        """Parse single market response"""
        try:
            # Try to decompress first (if it's zstd compressed)
            try:
                decompressed = self.decompress_zstd(binary_data)
                print('Successfully decompressed single market data')
            except:
                # If decompression fails, assume it's already uncompressed msgpack
                print('Data appears to be uncompressed msgpack')
                decompressed = binary_data
            
            # Decode msgpack
            data = msgpack.unpackb(decompressed, raw=False)
            
            # For perps: [identifier, market, positions, addresses]
            if isinstance(data, list) and len(data) >= 4:
                identifier, market, positions, addresses = data[:4]
                return {
                    market: {
                        'identifier': identifier,
                        'market': market,
                        'positions': positions or [],
                        'addresses': addresses or [],
                        'timestamp': self.cached_timestamp
                    }
                }
            
            # Or object format: {i, m, p, a}
            if isinstance(data, dict) and 'i' in data and 'm' in data:
                return {
                    market_name or data['m']: {
                        'identifier': data['i'],
                        'market': data['m'],
                        'positions': data.get('p', []),
                        'addresses': data.get('a', []),
                        'timestamp': self.cached_timestamp
                    }
                }
            
            raise ValueError('Unknown single market data format')
        except Exception as error:
            print(f'Error parsing single market: {error}')
            raise

    async def parse_multiple_markets(self, binary_data: bytes) -> Dict[str, Any]:
        """Parse multiple markets response (multi-zstd format)"""
        offset = 0
        
        # Read number of snapshots (4 bytes, little-endian)
        count = struct.unpack('<I', binary_data[offset:offset + 4])[0]
        offset += 4
        
        print(f"Number of perp snapshots: {count}")
        
        markets = {}
        
        for i in range(count):
            # Read length of this snapshot (4 bytes, little-endian)
            length = struct.unpack('<I', binary_data[offset:offset + 4])[0]
            offset += 4
            
            print(f"Snapshot {i + 1}/{count}: {length} bytes")
            
            # Extract and decompress snapshot
            zstd_data = binary_data[offset:offset + length]
            
            try:
                decompressed = self.decompress_zstd(zstd_data)
                data = msgpack.unpackb(decompressed, raw=False)
                
                # Handle array format: [identifier, market, positions, addresses]
                if isinstance(data, list) and len(data) >= 4:
                    identifier, market, positions, addresses = data[:4]
                    markets[market] = {
                        'identifier': identifier,
                        'market': market,
                        'positions': positions or [],
                        'addresses': addresses or [],
                        'timestamp': self.cached_timestamp
                    }
                    print(f"Parsed market: {market} with {len(positions) if positions else 0} positions")
                    
                # Handle object format: {i, m, p, a}
                elif isinstance(data, dict) and 'i' in data and 'm' in data:
                    market = data['m']
                    markets[market] = {
                        'identifier': data['i'],
                        'market': market,
                        'positions': data.get('p', []),
                        'addresses': data.get('a', []),
                        'timestamp': self.cached_timestamp
                    }
                    print(f"Parsed market: {market} with {len(data.get('p', [])) if data.get('p') else 0} positions")
                    
            except Exception as e:
                print(f"Error parsing snapshot {i + 1}: {e}")
                
            offset += length
        
        return markets

    def decompress_zstd(self, data: bytes) -> bytes:
        """Decompress zstd data"""
        dctx = zstd.ZstdDecompressor()
        return dctx.decompress(data)

    async def save_to_file(self, snapshots: Dict[str, Any]):
        """Save snapshots to JSON file"""
        output_data = {
            'timestamp': self.cached_timestamp,
            'markets': {}
        }
        
        for market, data in snapshots.items():
            positions = data.get('positions', [])
            addresses = data.get('addresses', [])
            
            position_list = []
            
            for i in range(len(positions)):
                if isinstance(positions[i], list) and len(positions[i]) >= 8:
                    position_list.append({
                        'address': addresses[i],
                        'size': positions[i][0],
                        'notional_size': positions[i][1],
                        'funding_pnl': positions[i][2],
                        'entry_price': positions[i][3],
                        'leverage_type_flag': positions[i][4],
                        'leverage_multiplier': positions[i][5],
                        'liquidation_price': positions[i][6],
                        'account_value': positions[i][7]
                    })
            
            output_data['markets'][market] = {
                'identifier': data.get('identifier'),
                'total_positions': len(positions),
                'positions': position_list
            }
        
        with open(self.output_file, 'w') as f:
            json.dump(output_data, f, indent=2)
        
        print(f"Saved perp snapshot to {self.output_file}")


async def main():
    """Example usage with different market configurations"""
    async with PerpSnapshotClient() as client:
        while True:
            try:
                snapshots = await client.poll_snapshots(['FARTCOIN', 'HYPE'])
                
                for market, data in snapshots.items():
                    print(f"Market {market}: {len(data.get('positions', []))} positions")
                
                print("Waiting 5 seconds...")
                await asyncio.sleep(5)
                
            except Exception as error:
                print(f'Polling error: {error}')
                await asyncio.sleep(5)


if __name__ == "__main__":
    asyncio.run(main())
```

{% endtab %}
{% endtabs %}


# perpTwapSnapshots

Endpoint to get all active TWAP orders across all Hyperliquid perpetual markets.

{% hint style="info" %}
💧**New endpoint - this endpoint is not part of the original Hyperliquid API. Hydromancer added it for builder convenience.**
{% endhint %}

### Overview

perpTwapSnapshot endpoint allows you to access all active TWAP (Time-Weighted Average Price) orders on Hyperliquid perpetual markets. TWAPs are algorithmic orders that execute over time, splitting large orders into smaller pieces.

There are two ways to access the data:

1. **Metadata Endpoint (Fast)**: Check for updates without downloading data
2. **Snapshots Endpoint (Heavy)**: Download actual TWAP snapshot data

<details>

<summary>Efficient polling pattern</summary>

To minimize bandwidth and server load, you should:

1. Poll the metadata endpoint to check for updates
2. Only call the snapshots endpoint when data has changed
3. Cache the snapshot ID locally to avoid unnecessary downloads

</details>

<details>

<summary>Dependencies and best practices</summary>

#### Dependencies

**JavaScript**

* **zstd**: For decompression (e.g., `fzstd`, `@gera2ld/zstd`)
* **msgpack**: For decoding (e.g., `@msgpack/msgpack`)

**Python**

* **zstd**: For decompression (e.g., `zstandard`)
* **msgpack**: For decoding (e.g., `msgpack`)
* **aiohttp**: For async HTTP requests

***

</details>

<details>

<summary>Error handling</summary>

* **404**: No TWAP snapshots are available yet. Wait and retry.
* **500**: A server error occurred. Retry with exponential backoff.
* **Network errors**: Implement retry logic with jitter to avoid overwhelming the server.
* **Parse errors**: Log the issue and continue using cached data if available.

</details>

### Perp TWAP Snapshot Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check if TWAP snapshots have been updated
* **Response Time**: \~1ms

#### Request

```json
{
  "type": "perpTwapSnapshotTimestamp"
}
```

#### Response

```json
{
  "snapshot_id": "20240915_state_123456789",
  "timestamp": 1694764800
}
```

### Perp TWAP Snapshots (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download TWAP snapshot data
* **Response Time**: \~50ms+

#### Request

```json
{
  "type": "perpTwapSnapshots",
  "market_names": ["BTC", "ETH"]
}
```

## Query Options (HIP-3 Multi-Dex)

**Specific markets:**

* `["BTC", "ETH"]` -> Defaults to the main dex
* `["xyz:BTC", "vntl:ETH"]` -> Specify DEX with `dex:market` format

**All markets patterns:**

* `["ALL"]` -> All TWAP markets from the main dex
* `["ALL:xyz"]` -> All TWAP markets from xyz DEX
* `["ALL:ALL_DEXES"]` -> All TWAP markets from all available DEXes

**Mixed queries:**

* `["ALL", "ALL:xyz", "BTC"]` -> All from main dex + all from xyz
* `["ALL:xyz", "vntl:ETH"]` -> All from xyz + specific ETH from vntls

**Rules:**

1. `ALL:ALL_DEXES` takes precedence - if present, returns everything from all dexes
2. Multiple `ALL` patterns allowed - one per dex
3. Specific markets are filtered - if a dex is covered by an ALL pattern, specific markets from that dex are ignored
4. No duplicates - each dex's ALL pattern is deduplicated

#### Response Headers

* **Single Market**: `x-payload-format: msgpack`, `Content-Encoding: zstd`
* **Multiple Markets**: `x-payload-format: multi-zstd`, `x-compression: inner-zstd`

### Data Format

<details>

<summary>Single Market Response</summary>

**Format**: Raw zstd-compressed MessagePack data

**Decompressed Structure:**

{% code overflow="wrap" %}

```json
[
  "20240915_state_123456789",
  "BTC",
  [
    ["0x1234567890abcdef...", 1, "BTC", true, 1.5, 0.75, 0.75, 75000.0, 50.0, 86400.0, 1694764800000, false, true, "2024-09-15T12:00:00Z", 100],
    ["0xfedcba0987654321...", 2, "BTC", false, 2.0, 1.0, 1.0, 100000.0, 50.0, 43200.0, 1694764800000, true, false, "2024-09-15T13:00:00Z", 50]
  ]
]
```

{% endcode %}

**Snapshot Array Format:**

```
[snapshot_id, market_name, twaps_array]
```

| Index | Field        | Description                                                 |
| ----- | ------------ | ----------------------------------------------------------- |
| 0     | snapshot\_id | Snapshot identifier                                         |
| 1     | market\_name | Market name ("BTC" for main dex, "xyz:BTC" for HIP-3 dexes) |
| 2     | twaps        | Array of TWAP tuples                                        |

**TWAP Tuple Format:**

```
[address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
```

| Index | Field             | Description                                                                                      |
| ----- | ----------------- | ------------------------------------------------------------------------------------------------ |
| 0     | address           | User address (hex string)                                                                        |
| 1     | twap\_id          | TWAP ID (unique per user)                                                                        |
| 2     | asset             | Asset symbol (e.g., "BTC", "ETH")                                                                |
| 3     | is\_buy           | Direction: true = buy, false = sell                                                              |
| 4     | total\_sz         | Total size to execute (normalized)                                                               |
| 5     | executed\_sz      | Size already executed (normalized)                                                               |
| 6     | remaining\_sz     | Remaining size (total\_sz - executed\_sz)                                                        |
| 7     | executed\_ntl     | Notional value executed (USD)                                                                    |
| 8     | progress\_pct     | Progress percentage (0-100)                                                                      |
| 9     | duration\_secs    | Total TWAP duration in seconds                                                                   |
| 10    | start\_time\_ms   | TWAP creation timestamp (milliseconds since epoch)                                               |
| 11    | reduce\_only      | Whether TWAP is reduce-only (boolean)                                                            |
| 12    | randomize         | Whether execution timing is randomized (boolean)                                                 |
| 13    | next\_slice\_time | Next slice execution time (ISO timestamp string)                                                 |
| 14    | slice\_number     | Current slice number in execution                                                                |
| 15    | market\_name      | Always null on perp entries (spot-only placeholder, keeps positions aligned with spot snapshots) |
| 16    | market\_readable  | Always null on perp entries (spot-only placeholder)                                              |
| 17    | stop\_px          | Stop price (normalized), null when not set                                                       |
| 18    | trigger\_px       | Trigger price (normalized) for waiting trigger TWAPs, null otherwise                             |
| 19    | trigger\_above    | Trigger direction: true = activates above trigger\_px, null when no trigger                      |
| 20    | waiting           | true = trigger TWAP registered but not yet activated (no execution yet)                          |

</details>

<details>

<summary>Multiple Markets Response</summary>

**Format**: Custom binary format with length prefixes

**Binary Structure:**

{% code overflow="wrap" %}

```
[market_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]...
```

{% endcode %}

Each `zstd_data` blob, when decompressed, contains a single market's TWAP snapshot in the same array format as the single market response.

</details>

### Implementation Examples

**Note**: Make sure to set **HYDROMANCER\_API\_KEY** in your .env file

{% tabs %}
{% tab title="Python" %}

```python
import struct
import aiohttp
import asyncio
import zstandard as zstd
import msgpack
import os
from datetime import datetime

def parse_twap_snapshot(data: list) -> dict:
    """Parse a single TWAP snapshot from decompressed msgpack data."""
    # Format: [snapshot_id, market_name, twaps_array]
    # TWAP tuple: [address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
    snapshot_id, market_name, twaps_raw = data[0], data[1], data[2]

    twaps = []
    for t in twaps_raw:
        twaps.append({
            "address": t[0],
            "twap_id": t[1],
            "asset": t[2],
            "is_buy": t[3],
            "total_sz": t[4],
            "executed_sz": t[5],
            "remaining_sz": t[6],
            "executed_ntl": t[7],
            "progress_pct": t[8],
            "duration_secs": t[9],
            "start_time_ms": t[10],
            "reduce_only": t[11],
            "randomize": t[12],
            "next_slice_time": t[13],
            "slice_number": t[14],
            # New fields (2026-08): tolerate older snapshots that lack them.
            # t[15]/t[16] are always null on perp entries (spot-only metadata,
            # kept as placeholders so tuple positions match spot snapshots).
            "stop_px": t[17] if len(t) > 17 else None,
            "trigger_px": t[18] if len(t) > 18 else None,
            "trigger_above": t[19] if len(t) > 19 else None,
            "waiting": t[20] if len(t) > 20 else False
        })

    return {
        "snapshot_id": snapshot_id,
        "market": market_name,
        "twaps": twaps
    }

def parse_multi_zstd_response(data: bytes) -> list:
    """Parse multi-zstd response format."""
    offset = 0
    count = struct.unpack_from('<I', data, offset)[0]
    offset += 4

    dctx = zstd.ZstdDecompressor()
    markets = []

    for _ in range(count):
        blob_len = struct.unpack_from('<I', data, offset)[0]
        offset += 4
        blob = data[offset:offset + blob_len]
        offset += blob_len

        decompressed = dctx.decompress(blob, max_output_size=blob_len * 20)
        snapshot_data = msgpack.unpackb(decompressed, raw=False)
        markets.append(parse_twap_snapshot(snapshot_data))

    return markets

async def fetch_perp_twap_snapshots(market_names=None):
    """Fetch perp TWAP snapshots from API."""
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

    request = {'type': 'perpTwapSnapshots'}
    if market_names:
        request['market_names'] = market_names
    else:
        request['market_names'] = ['ALL']

    async with aiohttp.ClientSession() as session:
        async with session.post(
            'https://api.hydromancer.xyz/info',
            json=request,
            headers=headers
        ) as resp:
            payload_format = resp.headers.get('x-payload-format')
            data = await resp.read()

            if payload_format == 'multi-zstd':
                return parse_multi_zstd_response(data)
            else:
                # Single market response - aiohttp auto-decompresses based on Content-Encoding
                snapshot_data = msgpack.unpackb(data, raw=False)
                return [parse_twap_snapshot(snapshot_data)]

async def fetch_perp_twap_timestamp():
    """Fetch perp TWAP snapshot metadata."""
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(
            'https://api.hydromancer.xyz/info',
            json={'type': 'perpTwapSnapshotTimestamp'},
            headers=headers
        ) as resp:
            return await resp.json()

if __name__ == "__main__":
    async def main():
        # Check timestamp first
        metadata = await fetch_perp_twap_timestamp()
        print(f"Snapshot ID: {metadata.get('snapshot_id')}")
        print(f"Timestamp: {metadata.get('timestamp')}")

        # Fetch all TWAP snapshots
        snapshots = await fetch_perp_twap_snapshots(['ALL:ALL_DEXES'])

        for market in snapshots:
            print(f"\nMarket: {market['market']}")
            for twap in market['twaps'][:3]:  # Show first 3 TWAPs
                direction = "BUY" if twap['is_buy'] else "SELL"
                duration_hrs = twap['duration_secs'] / 3600
                start_time = datetime.fromtimestamp(twap['start_time_ms'] / 1000).isoformat()
                print(f"  {twap['address'][:10]}... | {direction} {twap['asset']} | "
                      f"Progress: {twap['progress_pct']:.1f}% (slice {twap['slice_number']}) | "
                      f"Remaining: {twap['remaining_sz']:.4f} | "
                      f"Duration: {duration_hrs:.1f}h | Started: {start_time}")

    asyncio.run(main())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
require('dotenv').config();

function parseTwapSnapshot(data) {
    // Format: [snapshot_id, market_name, twaps_array]
    // TWAP tuple: [address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
    const [snapshotId, marketName, twapsRaw] = data;

    const twaps = twapsRaw.map(t => ({
        address: t[0],
        twap_id: t[1],
        asset: t[2],
        is_buy: t[3],
        total_sz: t[4],
        executed_sz: t[5],
        remaining_sz: t[6],
        executed_ntl: t[7],
        progress_pct: t[8],
        duration_secs: t[9],
        start_time_ms: t[10],
        reduce_only: t[11],
        randomize: t[12],
        next_slice_time: t[13],
        slice_number: t[14],
        // New fields (2026-08): undefined on older snapshots. t[15]/t[16] are
        // always null on perp entries (spot-only metadata, kept as
        // placeholders so tuple positions match spot snapshots).
        stop_px: t[17] ?? null,
        trigger_px: t[18] ?? null,
        trigger_above: t[19] ?? null,
        waiting: t[20] ?? false
    }));

    return {
        snapshot_id: snapshotId,
        market: marketName,
        twaps: twaps
    };
}

async function parseMultiZstdResponse(buffer) {
    let offset = 0;
    const count = buffer.readUInt32LE(offset);
    offset += 4;

    const markets = [];

    for (let i = 0; i < count; i++) {
        const blobLen = buffer.readUInt32LE(offset);
        offset += 4;
        const blob = buffer.slice(offset, offset + blobLen);
        offset += blobLen;

        const decompressed = await decompress(blob);
        const snapshotData = msgpack.decode(decompressed);
        markets.push(parseTwapSnapshot(snapshotData));
    }

    return markets;
}

async function fetchPerpTwapSnapshots(marketNames = ['ALL']) {
    const apiKey = process.env.HYDROMANCER_API_KEY;
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    };

    const response = await axios.post(
        'https://api.hydromancer.xyz/info',
        { type: 'perpTwapSnapshots', market_names: marketNames },
        { headers, responseType: 'arraybuffer' }
    );

    const payloadFormat = response.headers['x-payload-format'];
    const buffer = Buffer.from(response.data);

    if (payloadFormat === 'multi-zstd') {
        return await parseMultiZstdResponse(buffer);
    } else {
        // Single market response - HTTP client auto-decompresses based on Content-Encoding
        const snapshotData = msgpack.decode(buffer);
        return [parseTwapSnapshot(snapshotData)];
    }
}

async function fetchPerpTwapTimestamp() {
    const apiKey = process.env.HYDROMANCER_API_KEY;
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    };

    const response = await axios.post(
        'https://api.hydromancer.xyz/info',
        { type: 'perpTwapSnapshotTimestamp' },
        { headers }
    );

    return response.data;
}

async function main() {
    // Check timestamp first
    const metadata = await fetchPerpTwapTimestamp();
    console.log(`Snapshot ID: ${metadata.snapshot_id}`);
    console.log(`Timestamp: ${metadata.timestamp}`);

    // Fetch all TWAP snapshots
    const snapshots = await fetchPerpTwapSnapshots(['ALL:ALL_DEXES']);

    for (const market of snapshots) {
        console.log(`\nMarket: ${market.market}`);
        for (const twap of market.twaps.slice(0, 3)) {  // Show first 3 TWAPs
            const direction = twap.is_buy ? 'BUY' : 'SELL';
            const durationHrs = (twap.duration_secs / 3600).toFixed(1);
            const startTime = new Date(twap.start_time_ms).toISOString();
            console.log(`  ${twap.address.slice(0, 10)}... | ${direction} ${twap.asset} | ` +
                `Progress: ${twap.progress_pct.toFixed(1)}% (slice ${twap.slice_number}) | ` +
                `Remaining: ${twap.remaining_sz.toFixed(4)} | ` +
                `Duration: ${durationHrs}h | Started: ${startTime}`);
        }
    }
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = { fetchPerpTwapSnapshots, fetchPerpTwapTimestamp };
```

{% endtab %}
{% endtabs %}


# accountValueSnapshots

Unique endpoint allowing to get an account value snapshot of all accounts on Hyperliquid, including filtering by a specific type of collateral or HIP-3 DEX.

## accountValueSnapshot

{% hint style="info" %}

#### 💧New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.

{% endhint %}

{% hint style="warning" %}

### ⚠️ This is an add-on endpoint - access has to be purchased separately.

{% endhint %}

### Overview

The accountValueSnapshot endpoint provides access to aggregated account value data for all users holding positions in specific collateral tokens. This data includes total account values, long/short notional exposures, and is updated in real-time.

There are two ways to access the data:

1. **Metadata Endpoint (Fast)**: Check for updates without downloading data
2. **Snapshots Endpoint (Heavy)**: Download actual account value snapshot data

**Use Cases:**

* Track total value locked (TVL) per collateral token
* Analyze user distribution and concentration
* Monitor leverage and exposure across the platform
* Build leaderboards and analytics dashboards
* Monitor Portfolio Margin users' cross-collateral health (pm\_ratio, avail per branch)

<details>

<summary>Efficient polling pattern</summary>

To minimize bandwidth and server load, you should:

1. Poll the metadata endpoint to check for updates
2. Only call the snapshots endpoint when data has changed
3. Cache the snapshot ID locally to avoid unnecessary downloads

</details>

<details>

<summary>Dependencies and best practices</summary>

#### Dependencies

**JavaScript**

* **zstd**: For decompression (e.g., `@mongodb-js/zstd`)
* **msgpack**: For decoding (e.g., `msgpack-lite`)

**Python**

* **zstd**: For decompression (e.g., `zstandard`)
* **msgpack**: For decoding (e.g., `msgpack`)
* **aiohttp**: For async HTTP requests

***

✅ **Best Practices**

1. **Request specific tokens** - Don't use `['ALL']` unless you truly need all collateral data.
2. **Handle errors gracefully** - Network issues are common; implement retry logic.
3. **Use appropriate poll intervals** - 10-30 seconds is usually sufficient for account value data.
4. **Monitor bandwidth usage** - Snapshots can be large depending on user count.
5. **Cache locally** - Store snapshots to avoid unnecessary repeated downloads.

</details>

<details>

<summary>Error handling</summary>

* **404**: No snapshots are available yet. Wait and retry.
* **500**: A server error occurred. Retry with exponential backoff.
* **Network errors**: Implement retry logic with jitter to avoid overwhelming the server.
* **Parse errors**: Log the issue and continue using cached data if available.

</details>

### Account Value Snapshot Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check if snapshots have been updated
* **Response Time**: \~1ms

#### Request

```json
{
  "type": "accountValueSnapshotTimestamp"
}
```

#### Response

```json
{
  "snapshot_id": "20240915_state_123456789",
  "timestamp": 1694764800
}
```

{% hint style="info" %}
**Note:** Account value snapshots are generated at the same time as perp snapshots, so they share the same timestamp. This endpoint returns the perp snapshot metadata which applies to account values as well.
{% endhint %}

### Account Value Snapshots (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download account value snapshot data for specific collateral tokens
* **Response Time**: \~100ms+

#### Request

```json
{
  "type": "accountValueSnapshots",
  "collateral_tokens": ["USDC"]
}
```

#### Query Options

**Token-only (gets all DEXes using that collateral):**

* `["USDC"]` → Gets account values for all DEXes that use USDC as collateral
* `["USDE"]` → Gets account values for all DEXes that use USDE as collateral

**Specific DEX:Token combinations:**

* `["hyperliquid:USDC"]` → Only Hyperliquid's USDC collateral accounts
* `["xyz:USDC", "vntls:USDE"]` → Specific DEX:token combinations

**Mixed queries:**

* `["USDC", "xyz:USDE"]` → All USDC collateral across DEXes + specific xyz:USDE

**Practical Query Examples:**

```json
// Get all DEXes using USDC as collateral
{"type": "accountValueSnapshots", "collateral_tokens": ["USDC"]}
// Might return: hyperliquid:USDC, xyz:USDC, vntls:USDC (multiple snapshots)

// Get only Hyperliquid's USDC accounts
{"type": "accountValueSnapshots", "collateral_tokens": ["hyperliquid:USDC"]}
// Returns: Only hyperliquid:USDC (single snapshot)

// Get USDC from all DEXes + specific USDE from xyz only
{"type": "accountValueSnapshots", "collateral_tokens": ["USDC", "xyz:USDE"]}
// Returns: All *:USDC snapshots + xyz:USDE snapshot (multiple snapshots)
```

#### Response Headers

* **Single Snapshot Result**: `x-payload-format: msgpack`, `Content-Encoding: zstd`
* **Multiple Snapshot Results**: `x-payload-format: multi-zstd`, `x-compression: inner-zstd`

**Note:** The response format depends on the number of snapshots found, not the number of tokens requested:

* `["USDC"]` might return multiple snapshots if USDC is used on multiple DEXes
* `["hyperliquid:USDC"]` will return a single snapshot (specific DEX:token combination)

#### Data Format

<details>

<summary>Single Token Response</summary>

**Format**: Raw zstd-compressed MessagePack data

**Decompressed Structure:**

{% code overflow="wrap" %}

```json
[
  "20240915_account_value_123456789",  // Snapshot ID
  "USDC",                               // Collateral token
  {                                     // Users map
    "0x1234...": [25000.50, 15000.00, 5000.00],
    "0x5678...": [100000.00, 50000.00, 30000.00],
    // more users...
  }
]
```

{% endcode %}

ℹ️ **User Data Format**

Each user entry is a tuple. Standard users have 5 values; Portfolio Margin users have 8 values:

**Standard / Unified users (5 values):**

```
account_value          // Total account value in USD
total_long_notional    // Sum of all long position notionals
total_short_notional   // Sum of all short position notionals (absolute value)
is_unified             // Boolean: true if unified account (spot included in account_value)
account_mode           // 0=Standard, 1=DexAbstraction, 2=Unified, 3=PortfolioMargin
```

**Portfolio Margin users (8 values):**

```
account_value          // Per-settlement-token account value (perp equity + spot); negative when the token is borrowed
total_long_notional    // Sum of all long position notionals
total_short_notional   // Sum of all short position notionals (absolute value)
is_unified             // Boolean (false for PM users)
account_mode           // 3 (PortfolioMargin)
pm_ratio               // Portfolio margin ratio: max across branches, capped at 1.0 like Hyperliquid's portfolioMarginRatio (1.0 = at or past liquidation)
pm_avail_by_branch     // Array of [token_name, available_margin] tuples
pm_total_account_value // Total account value across all collateral tokens
```

{% hint style="info" %}
**Detecting account type:** Check `account_mode` (index 4) to determine the user's margin mode. For Portfolio Margin users (`account_mode == 3`), the tuple contains 3 additional fields at indices 5-7. For backwards compatibility, always check the array length before accessing PM fields.
{% endhint %}

**Example PM user data:**

```json
"0x1234...": [2597.64, 1500.00, 800.00, false, 3, 0.138, [["USDC", 1999.40], ["USDH", 1000.00]], 5788.74]
```

**Alternative Object Format:**

```json
{
  "i": "20240915_account_value_123456789",
  "t": "USDC",
  "u": {
    "0x1234...": {
      "v": 25000.50,
      "l": 15000.00,
      "s": 5000.00,
      "m": false,
      "am": 0
    },
    "0x5678...": {
      "v": 2597.64,
      "l": 1500.00,
      "s": 800.00,
      "m": false,
      "am": 3,
      "pm": 0.138,
      "pa": [["USDC", 1999.40], ["USDH", 1000.00]],
      "pt": 5788.74
    }
  }
}
```

</details>

<details>

<summary>Multiple Tokens Response</summary>

**Format**: Custom binary format with length prefixes

**Binary Structure:**

{% code overflow="wrap" %}

```
[token_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]...
```

{% endcode %}

Each zstd\_data segment contains a msgpack-encoded AccountValueSnapshot with the same structure as the single token response.

</details>

### Implementation Examples

**Note**: Make sure to set **HYDROMANCER\_API\_KEY** in your .env file

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
const fs = require('fs').promises;
require('dotenv').config();

class AccountValueSnapshotClient {
    constructor() {
        this.baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';
        this.apiKey = process.env.HYDROMANCER_API_KEY;

        if (!this.apiKey || this.apiKey === 'INSERT_API_KEY_HERE') {
            throw new Error('API key not found. Please set HYDROMANCER_API_KEY in .env file');
        }

        this.cachedSnapshots = {};
        this.cachedTimestamp = null;
        this.outputFile = 'account_value_snapshot.json';
    }

    async checkForUpdates() {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                { type: 'accountValueSnapshotTimestamp' },
                { headers }
            );

            const currentTimestamp = response.data.timestamp || response.data.snapshot_id;
            const hasUpdates = this.cachedTimestamp !== currentTimestamp;

            if (hasUpdates) {
                console.log(`Account value snapshot updated: ${this.cachedTimestamp} -> ${currentTimestamp}`);
                this.cachedTimestamp = currentTimestamp;
            } else {
                console.log(`No account value snapshot updates (timestamp: ${currentTimestamp})`);
            }

            return hasUpdates;
        } catch (error) {
            throw new Error(`Timestamp request failed: ${error.response?.status} - ${error.response?.data || error.message}`);
        }
    }

    async pollSnapshots(collateralTokens = ['USDC']) {
        try {
            const hasUpdates = await this.checkForUpdates();

            if (!hasUpdates) {
                console.log('No updates available, using cached data');
                return this.cachedSnapshots;
            }

            console.log('New snapshots available, downloading...');
            const snapshots = await this.downloadSnapshots(collateralTokens);

            this.cachedSnapshots = snapshots;
            await this.saveToFile(snapshots);

            return snapshots;
        } catch (error) {
            console.error('Error polling account value snapshots:', error.message);
            throw error;
        }
    }

    async downloadSnapshots(collateralTokens) {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                {
                    type: 'accountValueSnapshots',
                    collateral_tokens: collateralTokens
                },
                {
                    headers,
                    responseType: 'arraybuffer'
                }
            );

            const payloadFormat = response.headers['x-payload-format'];
            const binaryData = Buffer.from(response.data);

            console.log(`Payload format: ${payloadFormat}`);
            console.log(`Downloaded ${binaryData.length} bytes`);

            if (payloadFormat === 'multi-zstd') {
                return await this.parseMultipleTokens(binaryData);
            } else {
                return await this.parseSingleToken(binaryData, collateralTokens[0]);
            }
        } catch (error) {
            if (error.response) {
                throw new Error(`Request failed: ${error.response.status} - ${error.response.statusText}`);
            }
            throw error;
        }
    }

    async parseSingleToken(binaryData, tokenName) {
        try {
            // Decompress zstd data
            let decompressed;
            try {
                decompressed = await decompress(binaryData);
                console.log('Successfully decompressed single token data');
            } catch (e) {
                // If decompression fails, assume it's already uncompressed
                decompressed = binaryData;
            }

            // Decode msgpack
            const data = msgpack.decode(decompressed);

            // Array format: [snapshot_id, token, users_map]
            if (Array.isArray(data) && data.length >= 3) {
                const [snapshotId, token, usersMap] = data;
                return {
                    [token]: {
                        snapshot_id: snapshotId,
                        token: token,
                        users: this.parseUsers(usersMap),
                        total_users: Object.keys(usersMap).length
                    }
                };
            }

            // Object format: {i: snapshot_id, t: token, u: users}
            if (data.i !== undefined && data.t !== undefined && data.u !== undefined) {
                return {
                    [data.t]: {
                        snapshot_id: data.i,
                        token: data.t,
                        users: this.parseUsers(data.u),
                        total_users: Object.keys(data.u).length
                    }
                };
            }

            throw new Error('Unknown single token data format');
        } catch (error) {
            console.error('Error parsing single token:', error);
            throw error;
        }
    }

    async parseMultipleTokens(binaryData) {
        let offset = 0;

        // Read number of snapshots (4 bytes, little-endian)
        const count = binaryData.readUInt32LE(offset);
        offset += 4;

        console.log(`Number of account value snapshots: ${count}`);

        const tokens = {};

        for (let i = 0; i < count; i++) {
            // Read length of this snapshot (4 bytes, little-endian)
            const length = binaryData.readUInt32LE(offset);
            offset += 4;

            console.log(`Snapshot ${i + 1}/${count}: ${length} bytes`);

            // Extract and decompress snapshot
            const zstdData = binaryData.slice(offset, offset + length);

            try {
                const decompressed = await decompress(zstdData);
                const data = msgpack.decode(decompressed);

                // Array format: [snapshot_id, token, users_map]
                if (Array.isArray(data) && data.length >= 3) {
                    const [snapshotId, token, usersMap] = data;
                    tokens[token] = {
                        snapshot_id: snapshotId,
                        token: token,
                        users: this.parseUsers(usersMap),
                        total_users: Object.keys(usersMap).length
                    };
                    console.log(`Parsed token: ${token} with ${Object.keys(usersMap).length} users`);
                }
                // Object format: {i, t, u}
                else if (data.i !== undefined && data.t !== undefined && data.u !== undefined) {
                    tokens[data.t] = {
                        snapshot_id: data.i,
                        token: data.t,
                        users: this.parseUsers(data.u),
                        total_users: Object.keys(data.u).length
                    };
                    console.log(`Parsed token: ${data.t} with ${Object.keys(data.u).length} users`);
                }
            } catch (error) {
                console.error(`Error parsing snapshot ${i + 1}:`, error);
            }

            offset += length;
        }

        return tokens;
    }

    parseUsers(usersMap) {
        const userList = [];

        for (const [address, userData] of Object.entries(usersMap)) {
            // Array format: [account_value, total_long_notional, total_short_notional]
            if (Array.isArray(userData) && userData.length >= 3) {
                userList.push({
                    address: address,
                    account_value: userData[0],
                    total_long_notional: userData[1],
                    total_short_notional: userData[2]
                });
            }
            // Object format: {v, l, s}
            else if (userData.v !== undefined) {
                userList.push({
                    address: address,
                    account_value: userData.v,
                    total_long_notional: userData.l || 0,
                    total_short_notional: userData.s || 0
                });
            }
        }

        // Sort by account value descending
        userList.sort((a, b) => b.account_value - a.account_value);

        return userList;
    }

    async saveToFile(snapshots) {
        const outputData = {
            timestamp: new Date().toISOString(),
            tokens: {}
        };

        for (const [token, data] of Object.entries(snapshots)) {
            const users = data.users || [];

            // Calculate statistics
            const totalAccountValue = users.reduce((sum, u) => sum + u.account_value, 0);
            const totalLongNotional = users.reduce((sum, u) => sum + u.total_long_notional, 0);
            const totalShortNotional = users.reduce((sum, u) => sum + u.total_short_notional, 0);

            outputData.tokens[token] = {
                snapshot_id: data.snapshot_id,
                total_users: users.length,
                statistics: {
                    total_account_value: totalAccountValue,
                    total_long_notional: totalLongNotional,
                    total_short_notional: totalShortNotional,
                    avg_account_value: users.length > 0 ? totalAccountValue / users.length : 0
                },
                top_10_users: users.slice(0, 10),
                // all_users: users  // Uncomment to save all users
            };
        }

        await fs.writeFile(this.outputFile, JSON.stringify(outputData, null, 2));
        console.log(`\nSaved account value snapshot to ${this.outputFile}`);

        // Print summary
        for (const [token, data] of Object.entries(outputData.tokens)) {
            const stats = data.statistics;
            console.log(`\nToken: ${token}`);
            console.log(`  Total users: ${data.total_users}`);
            console.log(`  Total account value: $${stats.total_account_value.toLocaleString()}`);
            console.log(`  Total long notional: $${stats.total_long_notional.toLocaleString()}`);
            console.log(`  Total short notional: $${stats.total_short_notional.toLocaleString()}`);
            console.log(`  Average account value: $${stats.avg_account_value.toLocaleString()}`);
        }
    }
}

// Example usage - Continuous polling with timestamp check
async function main() {
    const client = new AccountValueSnapshotClient();

    console.log('Starting continuous polling for USDC account values...');
    console.log('Checking for updates every 5 seconds');
    console.log('Press Ctrl+C to stop\n');

    let pollCount = 0;

    while (true) {
        try {
            pollCount++;
            console.log(`\n[${'='.repeat(50)}]`);
            console.log(`Poll #${pollCount} at ${new Date().toISOString()}`);
            console.log(`[${'='.repeat(50)}]`);

            // pollSnapshots automatically checks timestamp first and only downloads if updated
            const snapshots = await client.pollSnapshots(['USDC']);

            // Log results
            for (const [token, data] of Object.entries(snapshots)) {
                console.log(`\n${token}:`);
                console.log(`  Total users: ${data.users?.length || 0}`);
                console.log(`  Snapshot ID: ${data.snapshot_id}`);

                if (data.users && data.users.length > 0) {
                    const totalValue = data.users.reduce((sum, u) => sum + u.account_value, 0);
                    console.log(`  Total account value: $${totalValue.toLocaleString(undefined, {maximumFractionDigits: 2})}`);
                }
            }

            // Wait 5 seconds before next poll
            console.log('\nWaiting 15 seconds before next check...');
            await new Promise(resolve => setTimeout(resolve, 15000));

        } catch (error) {
            console.error('\nPolling error:', error.message);
            console.log('Retrying in 5 seconds...');
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
    }
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = AccountValueSnapshotClient;

```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import aiohttp
import struct
from typing import Optional, Dict, List, Any
import time
import json
import zstandard as zstd
import msgpack
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()


class AccountValueSnapshotClient:
    def __init__(self):
        self.base_url = os.getenv('HYDROMANCER_API_URL', 'https://api.hydromancer.xyz')
        self.api_key = os.getenv('HYDROMANCER_API_KEY')

        if not self.api_key or self.api_key == 'INSERT_API_KEY_HERE':
            raise ValueError("API key not found. Please set HYDROMANCER_API_KEY in .env file")

        self.cached_snapshots: Dict[str, Any] = {}
        self.cached_timestamp: Optional[str] = None
        self.session: Optional[aiohttp.ClientSession] = None
        self.output_file = "account_value_snapshot.json"

    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()

    async def check_for_updates(self) -> bool:
        """Check if snapshots have been updated since last poll"""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'accountValueSnapshotTimestamp'},
            headers=headers
        ) as response:
            if not response.ok:
                text = await response.text()
                raise Exception(f'Timestamp request failed: {response.status} - {text}')

            data = await response.json()
            current_timestamp = data.get('timestamp', data.get('snapshot_id'))

            has_updates = self.cached_timestamp != current_timestamp

            if has_updates:
                print(f'Account value snapshot updated: {self.cached_timestamp} -> {current_timestamp}')
                self.cached_timestamp = current_timestamp
            else:
                print(f'No account value snapshot updates (timestamp: {current_timestamp})')

            return has_updates

    async def poll_snapshots(self, collateral_tokens: List[str] = ["USDC"]) -> Dict[str, Any]:
        """Efficiently poll for account value snapshots"""
        try:
            has_updates = await self.check_for_updates()

            if not has_updates:
                print('No updates available, using cached data')
                return self.cached_snapshots

            print('New snapshots available, downloading...')
            snapshots = await self.download_snapshots(collateral_tokens)

            self.cached_snapshots = snapshots
            await self.save_to_file(snapshots)

            return snapshots
        except Exception as error:
            print(f'Error polling account value snapshots: {error}')
            raise

    async def download_snapshots(self, collateral_tokens: List[str]) -> Dict[str, Any]:
        """Download account value snapshots"""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'accountValueSnapshots', 'collateral_tokens': collateral_tokens},
            headers=headers
        ) as response:
            if not response.ok:
                text = await response.text()
                raise Exception(f'Request failed: {response.status} - {text}')

            payload_format = response.headers.get('x-payload-format')
            binary_data = await response.read()

            print(f"Payload format: {payload_format}")
            print(f"Downloaded {len(binary_data)} bytes")

            if payload_format == 'multi-zstd':
                return await self.parse_multiple_tokens(binary_data)
            else:
                return await self.parse_single_token(binary_data, collateral_tokens[0] if len(collateral_tokens) == 1 else None)

    async def parse_single_token(self, binary_data: bytes, token_name: Optional[str] = None) -> Dict[str, Any]:
        """Parse single token response"""
        try:
            # Decompress zstd data
            try:
                decompressed = self.decompress_zstd(binary_data)
                print('Successfully decompressed single token data')
            except:
                decompressed = binary_data

            # Decode msgpack
            data = msgpack.unpackb(decompressed, raw=False)

            # Array format: [snapshot_id, token, users_map]
            if isinstance(data, list) and len(data) >= 3:
                snapshot_id, token, users_map = data[0], data[1], data[2]
                return {
                    token: {
                        'snapshot_id': snapshot_id,
                        'token': token,
                        'users': self.parse_users(users_map),
                        'total_users': len(users_map)
                    }
                }

            # Object format: {i, t, u}
            if isinstance(data, dict) and 'i' in data and 't' in data and 'u' in data:
                return {
                    data['t']: {
                        'snapshot_id': data['i'],
                        'token': data['t'],
                        'users': self.parse_users(data['u']),
                        'total_users': len(data['u'])
                    }
                }

            raise ValueError('Unknown single token data format')
        except Exception as error:
            print(f'Error parsing single token: {error}')
            raise

    async def parse_multiple_tokens(self, binary_data: bytes) -> Dict[str, Any]:
        """Parse multiple tokens response"""
        offset = 0

        # Read number of snapshots
        count = struct.unpack('<I', binary_data[offset:offset + 4])[0]
        offset += 4

        print(f"Number of snapshots: {count}")

        tokens = {}

        for i in range(count):
            # Read length
            length = struct.unpack('<I', binary_data[offset:offset + 4])[0]
            offset += 4

            print(f"Snapshot {i + 1}/{count}: {length} bytes")

            # Extract and decompress
            zstd_data = binary_data[offset:offset + length]

            try:
                decompressed = self.decompress_zstd(zstd_data)
                data = msgpack.unpackb(decompressed, raw=False)

                # Array format
                if isinstance(data, list) and len(data) >= 3:
                    snapshot_id, token, users_map = data[0], data[1], data[2]
                    tokens[token] = {
                        'snapshot_id': snapshot_id,
                        'token': token,
                        'users': self.parse_users(users_map),
                        'total_users': len(users_map)
                    }
                    print(f"Parsed token: {token} with {len(users_map)} users")

                # Object format
                elif isinstance(data, dict) and 'i' in data and 't' in data and 'u' in data:
                    token = data['t']
                    tokens[token] = {
                        'snapshot_id': data['i'],
                        'token': token,
                        'users': self.parse_users(data['u']),
                        'total_users': len(data['u'])
                    }
                    print(f"Parsed token: {token} with {len(data['u'])} users")

            except Exception as e:
                print(f"Error parsing snapshot {i + 1}: {e}")

            offset += length

        return tokens

    def parse_users(self, users_map: Dict) -> List[Dict[str, Any]]:
        """Parse users data from msgpack format"""
        user_list = []

        for address, user_data in users_map.items():
            # Array format: [account_value, total_long_notional, total_short_notional]
            if isinstance(user_data, list) and len(user_data) >= 3:
                user_list.append({
                    'address': address,
                    'account_value': user_data[0],
                    'total_long_notional': user_data[1],
                    'total_short_notional': user_data[2]
                })
            # Object format: {v, l, s}
            elif isinstance(user_data, dict):
                user_list.append({
                    'address': address,
                    'account_value': user_data.get('v', 0),
                    'total_long_notional': user_data.get('l', 0),
                    'total_short_notional': user_data.get('s', 0)
                })

        # Sort by account value descending
        user_list.sort(key=lambda x: x['account_value'], reverse=True)

        return user_list

    def decompress_zstd(self, data: bytes) -> bytes:
        """Decompress zstd data"""
        dctx = zstd.ZstdDecompressor()
        return dctx.decompress(data)

    async def save_to_file(self, snapshots: Dict[str, Any]):
        """Save snapshots to JSON file"""
        output_data = {
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()),
            'tokens': {}
        }

        for token, data in snapshots.items():
            users = data.get('users', [])

            # Calculate statistics
            total_account_value = sum(u['account_value'] for u in users)
            total_long_notional = sum(u['total_long_notional'] for u in users)
            total_short_notional = sum(u['total_short_notional'] for u in users)

            output_data['tokens'][token] = {
                'snapshot_id': data.get('snapshot_id'),
                'total_users': len(users),
                'statistics': {
                    'total_account_value': total_account_value,
                    'total_long_notional': total_long_notional,
                    'total_short_notional': total_short_notional,
                    'avg_account_value': total_account_value / len(users) if users else 0
                },
                'top_10_users': users[:10],
                # 'all_users': users  # Uncomment to save all users
            }

        with open(self.output_file, 'w') as f:
            json.dump(output_data, f, indent=2)

        print(f"\nSaved account value snapshot to {self.output_file}")

        # Print summary
        for token, data in output_data['tokens'].items():
            stats = data['statistics']
            print(f"\nToken: {token}")
            print(f"  Total users: {data['total_users']}")
            print(f"  Total account value: ${stats['total_account_value']:,.2f}")
            print(f"  Total long notional: ${stats['total_long_notional']:,.2f}")
            print(f"  Total short notional: ${stats['total_short_notional']:,.2f}")
            print(f"  Average account value: ${stats['avg_account_value']:,.2f}")


async def main():
    """Example usage - Continuous polling with timestamp check"""
    async with AccountValueSnapshotClient() as client:
        print('Starting continuous polling for USDC account values...')
        print('Checking for updates every 5 seconds')
        print('Press Ctrl+C to stop\n')

        poll_count = 0

        while True:
            try:
                poll_count += 1
                print(f"\n[{'=' * 50}]")
                print(f"Poll #{poll_count} at {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())}")
                print(f"[{'=' * 50}]")

                # poll_snapshots automatically checks timestamp first and only downloads if updated
                snapshots = await client.poll_snapshots(['USDC'])

                # Log results
                for token, data in snapshots.items():
                    print(f"\n{token}:")
                    print(f"  Total users: {len(data.get('users', []))}")
                    print(f"  Snapshot ID: {data.get('snapshot_id')}")

                    users = data.get('users', [])
                    if users:
                        total_value = sum(u['account_value'] for u in users)
                        print(f"  Total account value: ${total_value:,.2f}")

                # Wait 5 seconds before next poll
                print('\nWaiting 15 seconds before next check...')
                await asyncio.sleep(15)

            except Exception as error:
                print(f'\nPolling error: {error}')
                print('Retrying in 5 seconds...')
                await asyncio.sleep(5)


if __name__ == "__main__":
    asyncio.run(main())

```

{% endtab %}
{% endtabs %}


# spotSnapshots

Unique endpoint allowing to get entire spot positioning of all Hyperliquid spot holders.

{% hint style="info" %}
💧**New endpoint - this endpoint is not part of the original Hyperliquid API. Hydromancer added it for builder convenience.**
{% endhint %}

{% hint style="warning" %}

### ⚠️ This is an add-on endpoint - access has to be purchased separately.

{% endhint %}

### Overview

spotSnapshot endpoint allows you to access all balances of Hypercore users that hold spot assets.

There are two ways to access the data:

1. **Metadata Endpoint (Fast)**: Check for updates without downloading data
2. **Snapshots Endpoint (Heavy)**: Download actual market snapshot data

<details>

<summary>Efficient polling pattern</summary>

To minimize bandwidth and server load, you should:

1. Poll the metadata endpoint to check for updates
2. Only call the snapshots endpoint when data has changed
3. Cache the snapshot ID locally to avoid unnecessary downloads

</details>

<details>

<summary>Dependencies and best practices</summary>

### Dependencies

#### JavaScript

* **zstd**: For decompression (e.g., `fzstd`, `@gera2ld/zstd`)
* **msgpack**: For decoding (e.g., `@msgpack/msgpack`)

#### Python

* **zstd**: For decompression (e.g., `zstandard`)
* **msgpack**: For decoding (e.g., `msgpack`)
* **aiohttp**: For async HTTP requests

***

✅ **Best Practices**

1. **Always poll metadata first** - Don't skip the lightweight metadata check.
2. **Cache snapshots locally** - Avoid unnecessary downloads of large files.
3. **Handle errors gracefully** - Network issues are common; implement retry logic.
4. **Use appropriate poll intervals** - 5-10 seconds is usually sufficient.
5. **Request specific markets** - Don't use `['ALL']` unless you truly need all data.
6. **Monitor bandwidth usage** - Snapshots can be large (1-35MB+) compressed.

</details>

<details>

<summary>Error handling</summary>

* **404**: No snapshots are available yet. Wait and retry.
* **500**: A server error occurred. Retry with exponential backoff.
* **Network errors**: Implement retry logic with jitter to avoid overwhelming the server.
* **Parse errors**: Log the issue and continue using cached data if available.

</details>

### Spot Snapshot Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check if snapshots have been updated
* **Response Time**: \~1ms

#### Request

```json
{
  "type": "spotSnapshotTimestamp"
}
```

#### Response

```json
{
  "snapshot_id": "20240915_state_123456789",
  "timestamp": 1694764800
}
```

### Spot Snapshots (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download market snapshot data
* **Response Time**: \~100ms+

#### Request

```json
{
  "type": "spotSnapshots",
  "tokens": ["HYPE", "UBTC", "USOL"]  // or ["ALL"] for all markets
}
```

#### Response Headers

* **Single Market**: `x-payload-format: msgpack`, `Content-Encoding: zstd`
* **Multiple Markets**: `x-payload-format: multi-zstd`, `x-compression: inner-zstd`

### Data Format

<details>

<summary>Single Market Response</summary>

**Format**: Raw zstd-compressed MessagePack data

**Decompressed Structure:**

{% code overflow="wrap" %}

```json
[
  "20240915_state_123456789",  // Snapshot ID
  "UBTC",                      // Token name
  [                            // Balances array
    [
      20,                      // current balance
      2000000                  // entry value $
    ],
    /* more balances and entries */
  ],
  [                            // Addresses array
    "0x1234567890abcdef...",
    "0xfedcba0987654321...",
    /* more addresses */
  ]
}
```

{% endcode %}

ℹ️ **Balance Tuple Format** The format of the balances array has 2 values in the following order:

```
size
entry_value
```

</details>

<details>

<summary>Multiple Markets Response</summary>

**Format**: Custom binary format with length prefixes

**Binary Structure:**

{% code overflow="wrap" %}

```
[market_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]...
```

{% endcode %}

</details>

### Implementation examples

**Note**: Make sure to set **HYDROMANCER\_API\_KEY** in your .env file

Note: Make sure to download required packages

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { compress, decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
const fs = require('fs').promises;
require('dotenv').config();

class SpotSnapshotClient {
    constructor() {
        this.baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';
        this.apiKey = process.env.HYDROMANCER_API_KEY;
        
        if (!this.apiKey || this.apiKey === 'INSERT_API_KEY_HERE') {
            throw new Error('API key not found. Please set HYDROMANCER_API_KEY in .env file');
        }
        
        this.cachedTimestamp = null;
        this.cachedSnapshots = {};
        this.outputFile = 'spot_snapshot.json';
    }

    async checkForUpdates() {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                { type: 'spotSnapshotTimestamp' },
                { headers }
            );

            const currentTimestamp = response.data.timestamp || response.data.snapshot_id;
            const hasUpdates = this.cachedTimestamp !== currentTimestamp;
            
            if (hasUpdates) {
                console.log(`Spot snapshot updated: ${this.cachedTimestamp} -> ${currentTimestamp}`);
                this.cachedTimestamp = currentTimestamp;
            } else {
                console.log(`No spot snapshot updates (timestamp: ${currentTimestamp})`);
            }

            return hasUpdates;
        } catch (error) {
            throw new Error(`Timestamp request failed: ${error.response?.status} - ${error.response?.data || error.message}`);
        }
    }

    async pollSnapshots(tokens = ['UBTC', 'PUP']) {
        try {
            const hasUpdates = await this.checkForUpdates();
            
            if (!hasUpdates) {
                console.log('No updates available, using cached spot data');
                return this.cachedSnapshots;
            }

            console.log('New spot snapshots available, downloading...');
            const snapshots = await this.downloadSnapshots(tokens);
            
            this.cachedSnapshots = snapshots;
            await this.saveToFile(snapshots);
            
            return snapshots;
        } catch (error) {
            console.error('Error polling spot snapshots:', error);
            throw error;
        }
    }

    async downloadSnapshots(tokens) {
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiKey}`
        };

        try {
            const response = await axios.post(
                `${this.baseUrl}/info`,
                { type: 'spotSnapshots', tokens: tokens },
                { 
                    headers,
                    responseType: 'arraybuffer'
                }
            );

            const payloadFormat = response.headers['x-payload-format'];
            const binaryData = Buffer.from(response.data);
            
            console.log(`Payload format: ${payloadFormat}`);
            console.log(`Downloaded ${binaryData.length} bytes`);
            
            if (payloadFormat === 'multi-zstd') {
                return await this.parseMultipleTokens(binaryData);
            } else {
                // Single token - could be msgpack or zstd compressed
                return await this.parseSingleToken(binaryData, tokens[0]);
            }
        } catch (error) {
            throw new Error(`Spot snapshots request failed: ${error.response?.status} - ${error.response?.data || error.message}`);
        }
    }

    async parseSingleToken(binaryData, tokenName) {
        try {
            // Try to decompress first (if it's zstd compressed)
            let decompressed;
            try {
                decompressed = await decompress(binaryData);
                console.log('Successfully decompressed single token data');
            } catch (e) {
                // If decompression fails, assume it's already uncompressed msgpack
                console.log('Data appears to be uncompressed msgpack');
                decompressed = binaryData;
            }
            
            // Decode msgpack
            const data = msgpack.decode(decompressed);
            
            // For spot: [identifier, token, balances, addresses]
            if (Array.isArray(data) && data.length >= 4) {
                const [identifier, token, balances, addresses] = data;
                return {
                    [token]: {
                        identifier: identifier,
                        token: token,
                        balances: balances || [],
                        addresses: addresses || [],
                        timestamp: this.cachedTimestamp
                    }
                };
            }
            
            // Or it could be object format: {i, t, b, a} or similar
            if (data.i !== undefined || data.identifier !== undefined) {
                const token = data.t || data.token || tokenName;
                return {
                    [token]: {
                        identifier: data.i || data.identifier,
                        token: token,
                        balances: data.b || data.balances || [],
                        addresses: data.a || data.addresses || [],
                        timestamp: this.cachedTimestamp
                    }
                };
            }
            
            throw new Error('Unknown single token data format');
        } catch (error) {
            console.error('Error parsing single token:', error);
            throw error;
        }
    }

    async parseMultipleTokens(binaryData) {
        let offset = 0;
        
        // Read number of snapshots (4 bytes, little-endian)
        const count = binaryData.readUInt32LE(offset);
        offset += 4;
        
        console.log(`Number of spot snapshots: ${count}`);
        
        const tokens = {};
        
        for (let i = 0; i < count; i++) {
            // Read length of this snapshot (4 bytes, little-endian)
            const length = binaryData.readUInt32LE(offset);
            offset += 4;
            
            console.log(`Snapshot ${i + 1}/${count}: ${length} bytes`);
            
            // Extract and decompress snapshot
            const zstdData = binaryData.slice(offset, offset + length);
            
            try {
                const decompressed = await decompress(zstdData);
                const data = msgpack.decode(decompressed);
                
                // Handle array format: [identifier, token, balances, addresses]
                if (Array.isArray(data) && data.length >= 4) {
                    const [identifier, token, balances, addresses] = data;
                    tokens[token] = {
                        identifier: identifier,
                        token: token,
                        balances: balances || [],
                        addresses: addresses || [],
                        timestamp: this.cachedTimestamp
                    };
                    console.log(`Parsed token: ${token} with ${balances?.length || 0} balances`);
                }
                // Handle object format
                else if ((data.i !== undefined || data.identifier !== undefined) && 
                         (data.t !== undefined || data.token !== undefined)) {
                    const token = data.t || data.token;
                    tokens[token] = {
                        identifier: data.i || data.identifier,
                        token: token,
                        balances: data.b || data.balances || [],
                        addresses: data.a || data.addresses || [],
                        timestamp: this.cachedTimestamp
                    };
                    console.log(`Parsed token: ${token} with ${(data.b || data.balances)?.length || 0} balances`);
                }
            } catch (error) {
                console.error(`Error parsing snapshot ${i + 1}:`, error);
            }
            
            offset += length;
        }
        
        return tokens;
    }

    async saveToFile(snapshots) {
        const outputData = {
            timestamp: this.cachedTimestamp,
            tokens: {}
        };
        
        for (const [token, data] of Object.entries(snapshots)) {
            const balances = data.balances || [];
            const addresses = data.addresses || [];
            
            // Create readable balance list (first 100 balances)
            const balanceList = [];
            const numBalances = Math.min(100, balances.length, addresses.length);
            
            for (let i = 0; i < numBalances; i++) {
                if (Array.isArray(balances[i]) && balances[i].length >= 2) {
                    balanceList.push({
                        address: addresses[i],
                        balance: balances[i][0],
                        entry_value: balances[i][1]
                    });
                }
            }
            
            outputData.tokens[token] = {
                identifier: data.identifier,
                total_balances: balances.length,
                balances: balanceList
            };
        }
        
        await fs.writeFile(this.outputFile, JSON.stringify(outputData, null, 2));
        console.log(`Saved spot snapshot to ${this.outputFile}`);
    }
}

// Example usage
async function main() {
    const client = new SpotSnapshotClient();
    
    while (true) {
        try {
            const snapshots = await client.pollSnapshots(['UBTC', "PUP"]);
            
            for (const [token, data] of Object.entries(snapshots)) {
                console.log(`Token ${token}: ${data.balances?.length || 0} balances`);
            }
            
            console.log('Waiting 5 seconds...');
            await new Promise(resolve => setTimeout(resolve, 5000));
            
        } catch (error) {
            console.error('Polling error:', error.message);
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
    }
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = SpotSnapshotClient;
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import aiohttp
import struct
from typing import Optional, Dict, List, Any
import time
import json
import zstandard as zstd
import msgpack
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()


class SpotSnapshotClient:
    def __init__(self):
        # Use environment variables with fallbacks
        self.base_url = os.getenv('HYDROMANCER_API_URL', 'https://api.hydromancer.xyz')
        self.api_key = os.getenv('HYDROMANCER_API_KEY')

        if not self.api_key:
            raise ValueError("API key not found. Please set HYDROMANCER_API_KEY in .env file")
        self.cached_timestamp: Optional[str] = None
        self.cached_snapshots: Dict[str, Any] = {}
        self.session: Optional[aiohttp.ClientSession] = None
        self.output_file = "spot_snapshot.json"

    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()

    async def check_for_updates(self) -> bool:
        """Check if snapshots have been updated since last poll"""
        if not self.session:
            raise RuntimeError("Client session not initialized")

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        start_time = time.time()
        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'spotSnapshotTimestamp'},
            headers=headers
        ) as response:
            fetch_time = time.time() - start_time
            
            if not response.ok:
                text = await response.text()
                raise Exception(f'Timestamp request failed: {response.status} - {text}')

            data = await response.json()
            current_timestamp = data.get('timestamp', data.get('snapshot_id'))
            
            # Check if this is a new snapshot
            has_updates = self.cached_timestamp != current_timestamp
            
            if has_updates:
                print(f'📈 Spot snapshot updated: {self.cached_timestamp} -> {current_timestamp} (fetched in {fetch_time:.3f}s)')
                self.cached_timestamp = current_timestamp
            else:
                print(f'⏳ No spot snapshot updates (timestamp: {current_timestamp}, checked in {fetch_time:.3f}s)')

            return has_updates

    async def poll_snapshots(self, tokens: List[str] = ["UBTC", "PUP"]) -> Dict[str, Any]:
        """
        Efficiently poll for spot snapshots
        Only downloads data when snapshots have been updated
        """
        try:
            # Step 1: Check if snapshots have been updated
            has_updates = await self.check_for_updates()
            
            if not has_updates:
                print('Waiting for next update, using cached spot data')
                return self.cached_snapshots

            # Step 2: Download new snapshots
            print('New spot snapshots available, downloading...')
            snapshots = await self.download_snapshots(tokens)
            
            # Update cache
            self.cached_snapshots = snapshots
            
            # Save to file
            self.save_to_file(snapshots)
            
            return snapshots
        except Exception as error:
            print(f'Error polling spot snapshots: {error}')
            raise

    async def download_snapshots(self, tokens: List[str]) -> Dict[str, Any]:
        """Download spot market snapshots"""
        if not self.session:
            raise RuntimeError("Client session not initialized")

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        start_time = time.time()
        async with self.session.post(
            f'{self.base_url}/info',
            json={'type': 'spotSnapshots', 'tokens': tokens},
            headers=headers
        ) as response:
            fetch_time = time.time() - start_time
            
            if not response.ok:
                text = await response.text()
                raise Exception(f'Spot snapshots request failed: {response.status} - {text}')

            payload_format = response.headers.get('x-payload-format')
            binary_data = await response.read()
            
            # Format file size in human readable format
            def format_bytes(bytes_size):
                for unit in ['B', 'KB', 'MB', 'GB']:
                    if bytes_size < 1024.0:
                        return f"{bytes_size:.2f} {unit}"
                    bytes_size /= 1024.0
                return f"{bytes_size:.2f} TB"
            
            readable_size = format_bytes(len(binary_data))
            print(f"📦 Downloaded {readable_size} ({len(binary_data):,} bytes) in {fetch_time:.3f}s")
            print(f"🔧 Payload format: {payload_format}")
            
            if payload_format == 'multi-zstd':
                return self.parse_multiple_tokens(binary_data)
            else:
                return self.parse_single_snapshot(binary_data)

    def parse_single_snapshot(self, binary_data: bytes) -> Dict[str, Any]:
        """Parse single compressed msgpack response"""
        # Decompress zstd
        decompressed = self.decompress_zstd(binary_data)
        
        # Decode msgpack
        data = self.decode_msgpack(decompressed)
        
        # Handle single snapshot response
        if isinstance(data, list) and len(data) >= 4:
            # Spot format: [identifier, token, balances, addresses]
            token = data[1]
            return {
                token: {
                    'identifier': data[0],
                    'token': token,
                    'balances': data[2],
                    'addresses': data[3],
                    'timestamp': self.cached_timestamp
                }
            }
        
        return data

    def parse_multiple_tokens(self, binary_data: bytes) -> Dict[str, Any]:
        """Parse multiple tokens response (multi-zstd format)"""
        offset = 0
        
        # Read number of snapshots (4 bytes, little-endian)
        if len(binary_data) < 4:
            raise ValueError(f"Data too short: {len(binary_data)} bytes")
            
        count = struct.unpack('<I', binary_data[offset:offset + 4])[0]
        offset += 4
        
        print(f"Number of spot snapshots: {count}")
        
        tokens = {}
        
        for i in range(count):
            # Read length of this snapshot (4 bytes, little-endian)
            if offset + 4 > len(binary_data):
                raise ValueError(f"Unexpected end of data at offset {offset}")
                
            length = struct.unpack('<I', binary_data[offset:offset + 4])[0]
            offset += 4
            
            print(f"Spot snapshot {i}: {length} bytes")
            
            # Extract and decompress snapshot
            if offset + length > len(binary_data):
                raise ValueError(f"Data too short for snapshot {i}")
                
            zstd_data = binary_data[offset:offset + length]
            
            try:
                decompressed = self.decompress_zstd(zstd_data)
                snapshot = self.decode_msgpack(decompressed)
                
                # Handle list format
                if isinstance(snapshot, list) and len(snapshot) >= 4:
                    # Spot format: [identifier, token, balances, addresses]
                    identifier = snapshot[0]
                    token_name = snapshot[1]
                    balances = snapshot[2]  # Array of [balance, entry_value]
                    addresses = snapshot[3]
                    
                    # Store as a structured dict
                    tokens[token_name] = {
                        'identifier': identifier,
                        'token': token_name,
                        'balances': balances,
                        'addresses': addresses,
                        'timestamp': self.cached_timestamp
                    }
                    
                    print(f"Parsed spot token: {token_name} with {len(balances) if isinstance(balances, list) else 0} balances")
                else:
                    # Fallback for unexpected format
                    key = f'token_{i}'
                    tokens[key] = snapshot
                    print(f"Unexpected format for token {i}: {type(snapshot)}")
                
            except Exception as e:
                print(f"Error parsing spot snapshot {i}: {e}")
                # Continue with next snapshot
                
            offset += length
        
        return tokens

    def decompress_zstd(self, data: bytes) -> bytes:
        """Decompress zstd data"""
        try:
            dctx = zstd.ZstdDecompressor()
            return dctx.decompress(data)
        except Exception as e:
            print(f"Decompression error: {e}")
            raise

    def decode_msgpack(self, data: bytes) -> Any:
        """Decode MessagePack data"""
        return msgpack.unpackb(data, raw=False)

    def save_to_file(self, snapshots: Dict[str, Any]):
        """Save snapshots to JSON file"""
        # Convert balances to a more readable format
        output_data = {
            'timestamp': self.cached_timestamp,
            'tokens': {}
        }
        
        for token, data in snapshots.items():
            if isinstance(data, dict):
                balances = data.get('balances', [])
                addresses = data.get('addresses', [])
                
                # Create list of balance objects
                balance_list = []
                for i, (balance_entry, address) in enumerate(zip(balances, addresses)):
                    if isinstance(balance_entry, list) and len(balance_entry) >= 2:
                        balance_list.append({
                            'address': address,
                            'balance': balance_entry[0],
                            'entry_value': balance_entry[1]
                        })
                
                output_data['tokens'][token] = {
                    'identifier': data.get('identifier'),
                    'total_balances': len(balances),
                    'balances': balance_list
                }
        
        with open(self.output_file, 'w') as f:
            json.dump(output_data, f, indent=2)
        
        print(f"Saved spot snapshot to {self.output_file}")

    def parse_spot_balance(self, balance: List[float]) -> Dict[str, float]:
        """Parse a spot balance array into a dictionary"""
        if not isinstance(balance, list) or len(balance) < 2:
            return {}
        
        return {
            'balance': balance[0],
            'entry_value': balance[1]
        }


async def main():
    """Poll spot snapshots every 5 seconds, only download when updated"""
    async with SpotSnapshotClient() as client:
        while True:
            try:
                # Poll for updates
                snapshots = await client.poll_snapshots(["UBTC", "PUP"])
                
                # Print summary
                for token, data in snapshots.items():
                    if isinstance(data, dict):
                        balances = data.get('balances', [])
                        # print(f"Spot Token {token}: {len(balances)} balances")
                
                # Wait 5 seconds before next check
                # print("Waiting 5 seconds before next timestamp check...")
                await asyncio.sleep(5)
                
            except Exception as error:
                print(f'Polling failed: {error}')
                await asyncio.sleep(5)  # Wait before retrying


if __name__ == "__main__":
    asyncio.run(main())
```

{% endtab %}
{% endtabs %}


# spotTwapSnapshots

Endpoint to get all active TWAP orders across all Hyperliquid spot markets.

{% hint style="info" %}
💧**New endpoint - this endpoint is not part of the original Hyperliquid API. Hydromancer added it for builder convenience.**
{% endhint %}

### Overview

spotTwapSnapshot endpoint allows you to access all active TWAP (Time-Weighted Average Price) orders on Hyperliquid spot markets. TWAPs are algorithmic orders that execute over time, splitting large orders into smaller pieces.

There are two ways to access the data:

1. **Metadata Endpoint (Fast)**: Check for updates without downloading data
2. **Snapshots Endpoint (Heavy)**: Download actual TWAP snapshot data

<details>

<summary>Efficient polling pattern</summary>

To minimize bandwidth and server load, you should:

1. Poll the metadata endpoint to check for updates
2. Only call the snapshots endpoint when data has changed
3. Cache the snapshot ID locally to avoid unnecessary downloads

</details>

<details>

<summary>Dependencies and best practices</summary>

#### Dependencies

**JavaScript**

* **zstd**: For decompression (e.g., `fzstd`, `@gera2ld/zstd`)
* **msgpack**: For decoding (e.g., `@msgpack/msgpack`)

**Python**

* **zstd**: For decompression (e.g., `zstandard`)
* **msgpack**: For decoding (e.g., `msgpack`)
* **aiohttp**: For async HTTP requests

***

</details>

<details>

<summary>Error handling</summary>

* **404**: No TWAP snapshots are available yet. Wait and retry.
* **500**: A server error occurred. Retry with exponential backoff.
* **Network errors**: Implement retry logic with jitter to avoid overwhelming the server.
* **Parse errors**: Log the issue and continue using cached data if available.

</details>

### Spot TWAP Snapshot Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check if TWAP snapshots have been updated
* **Response Time**: \~1ms

#### Request

```json
{
  "type": "spotTwapSnapshotTimestamp"
}
```

#### Response

```json
{
  "snapshot_id": "20240915_state_123456789",
  "timestamp": 1694764800
}
```

### Spot TWAP Snapshots (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download TWAP snapshot data
* **Response Time**: \~50ms+

#### Request

```json
{
  "type": "spotTwapSnapshots",
  "tokens": ["HYPE", "PURR"]
}
```

## Query Options

**Specific tokens:**

* `["HYPE", "PURR"]` -> Specific spot tokens
* `["@107"]` -> By spot index
* `["HYPE/USDC"]` -> By pair name

**All tokens:**

* `["ALL"]` -> All spot tokens with active TWAPs

#### Response Headers

* **Single Token**: `x-payload-format: msgpack`, `Content-Encoding: zstd`
* **Multiple Tokens**: `x-payload-format: multi-zstd`, `x-compression: inner-zstd`

### Data Format

<details>

<summary>Single Token Response</summary>

**Format**: Raw zstd-compressed MessagePack data

**Decompressed Structure:**

{% code overflow="wrap" %}

```json
[
  "20240915_state_123456789",
  "HYPE",
  [
    ["0x1234567890abcdef...", 1, "HYPE", true, 1000.0, 500.0, 500.0, 5000.0, 50.0, 86400.0, 1694764800000, false, true, "2024-09-15T12:00:00Z", 100, "@107", "HYPE/USDC"],
    ["0xfedcba0987654321...", 2, "HYPE", false, 2000.0, 1000.0, 1000.0, 10000.0, 50.0, 43200.0, 1694764800000, true, false, "2024-09-15T13:00:00Z", 50, "@232", "HYPE/USDH"]
  ]
]
```

{% endcode %}

**Snapshot Array Format:**

```
[snapshot_id, token_name, twaps_array]
```

| Index | Field        | Description                       |
| ----- | ------------ | --------------------------------- |
| 0     | snapshot\_id | Snapshot identifier               |
| 1     | token\_name  | Token name (e.g., "HYPE", "PURR") |
| 2     | twaps        | Array of TWAP tuples              |

**TWAP Tuple Format:**

```
[address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
```

| Index | Field             | Description                                                                                              |
| ----- | ----------------- | -------------------------------------------------------------------------------------------------------- |
| 0     | address           | User address (hex string)                                                                                |
| 1     | twap\_id          | TWAP ID (unique per user)                                                                                |
| 2     | asset             | Asset symbol (e.g., "HYPE", "PURR")                                                                      |
| 3     | is\_buy           | Direction: true = buy, false = sell                                                                      |
| 4     | total\_sz         | Total size to execute (normalized)                                                                       |
| 5     | executed\_sz      | Size already executed (normalized)                                                                       |
| 6     | remaining\_sz     | Remaining size (total\_sz - executed\_sz)                                                                |
| 7     | executed\_ntl     | Notional value executed (USD)                                                                            |
| 8     | progress\_pct     | Progress percentage (0-100)                                                                              |
| 9     | duration\_secs    | Total TWAP duration in seconds                                                                           |
| 10    | start\_time\_ms   | TWAP creation timestamp (milliseconds since epoch)                                                       |
| 11    | reduce\_only      | Whether TWAP is reduce-only (boolean)                                                                    |
| 12    | randomize         | Whether execution timing is randomized (boolean)                                                         |
| 13    | next\_slice\_time | Next slice execution time (ISO timestamp string)                                                         |
| 14    | slice\_number     | Current slice number in execution                                                                        |
| 15    | market\_name      | Spot market index (e.g., "@107", "@232"); null if market metadata could not be resolved                  |
| 16    | market\_readable  | Human-readable pair name (e.g., "HYPE/USDC", "HYPE/USDH"); null if market metadata could not be resolved |
| 17    | stop\_px          | Stop price (normalized), null when not set                                                               |
| 18    | trigger\_px       | Trigger price (normalized) for waiting trigger TWAPs, null otherwise                                     |
| 19    | trigger\_above    | Trigger direction: true = activates above trigger\_px, null when no trigger                              |
| 20    | waiting           | true = trigger TWAP registered but not yet activated (no execution yet)                                  |

</details>

<details>

<summary>Multiple Tokens Response</summary>

**Format**: Custom binary format with length prefixes

**Binary Structure:**

{% code overflow="wrap" %}

```
[token_count: 4 bytes][length1: 4 bytes][zstd_data1][length2: 4 bytes][zstd_data2]...
```

{% endcode %}

Each `zstd_data` blob, when decompressed, contains a single token's TWAP snapshot in the same array format as the single token response.

</details>

### Implementation Examples

**Note**: Make sure to set **HYDROMANCER\_API\_KEY** in your .env file

{% tabs %}
{% tab title="Python" %}

```python
import struct
import aiohttp
import asyncio
import zstandard as zstd
import msgpack
import os
from datetime import datetime

def parse_twap_snapshot(data: list) -> dict:
    """Parse a single TWAP snapshot from decompressed msgpack data."""
    # Format: [snapshot_id, token_name, twaps_array]
    # TWAP tuple: [address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
    snapshot_id, token_name, twaps_raw = data[0], data[1], data[2]

    twaps = []
    for t in twaps_raw:
        twaps.append({
            "address": t[0],
            "twap_id": t[1],
            "asset": t[2],
            "is_buy": t[3],
            "total_sz": t[4],
            "executed_sz": t[5],
            "remaining_sz": t[6],
            "executed_ntl": t[7],
            "progress_pct": t[8],
            "duration_secs": t[9],
            "start_time_ms": t[10],
            "reduce_only": t[11],
            "randomize": t[12],
            "next_slice_time": t[13],
            "slice_number": t[14],
            "market_name": t[15],      # e.g., "@232"
            "market_readable": t[16],  # e.g., "HYPE/USDH"
            # New fields (2026-08): tolerate older snapshots that lack them
            "stop_px": t[17] if len(t) > 17 else None,
            "trigger_px": t[18] if len(t) > 18 else None,
            "trigger_above": t[19] if len(t) > 19 else None,
            "waiting": t[20] if len(t) > 20 else False
        })

    return {
        "snapshot_id": snapshot_id,
        "token": token_name,
        "twaps": twaps
    }

def parse_multi_zstd_response(data: bytes) -> list:
    """Parse multi-zstd response format."""
    offset = 0
    count = struct.unpack_from('<I', data, offset)[0]
    offset += 4

    dctx = zstd.ZstdDecompressor()
    tokens = []

    for _ in range(count):
        blob_len = struct.unpack_from('<I', data, offset)[0]
        offset += 4
        blob = data[offset:offset + blob_len]
        offset += blob_len

        decompressed = dctx.decompress(blob, max_output_size=blob_len * 20)
        snapshot_data = msgpack.unpackb(decompressed, raw=False)
        tokens.append(parse_twap_snapshot(snapshot_data))

    return tokens

async def fetch_spot_twap_snapshots(tokens=None):
    """Fetch spot TWAP snapshots from API."""
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

    request = {'type': 'spotTwapSnapshots'}
    if tokens:
        request['tokens'] = tokens
    else:
        request['tokens'] = ['ALL']

    async with aiohttp.ClientSession() as session:
        async with session.post(
            'https://api.hydromancer.xyz/info',
            json=request,
            headers=headers
        ) as resp:
            payload_format = resp.headers.get('x-payload-format')
            data = await resp.read()

            if payload_format == 'multi-zstd':
                return parse_multi_zstd_response(data)
            else:
                # Single token response - aiohttp auto-decompresses based on Content-Encoding
                snapshot_data = msgpack.unpackb(data, raw=False)
                return [parse_twap_snapshot(snapshot_data)]

async def fetch_spot_twap_timestamp():
    """Fetch spot TWAP snapshot metadata."""
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(
            'https://api.hydromancer.xyz/info',
            json={'type': 'spotTwapSnapshotTimestamp'},
            headers=headers
        ) as resp:
            return await resp.json()

if __name__ == "__main__":
    async def main():
        # Check timestamp first
        metadata = await fetch_spot_twap_timestamp()
        print(f"Snapshot ID: {metadata.get('snapshot_id')}")
        print(f"Timestamp: {metadata.get('timestamp')}")

        # Fetch all spot TWAP snapshots
        snapshots = await fetch_spot_twap_snapshots(['ALL'])

        for token_data in snapshots:
            print(f"\nToken: {token_data['token']}")
            for twap in token_data['twaps'][:3]:  # Show first 3 TWAPs
                direction = "BUY" if twap['is_buy'] else "SELL"
                duration_hrs = twap['duration_secs'] / 3600
                start_time = datetime.fromtimestamp(twap['start_time_ms'] / 1000).isoformat()
                print(f"  {twap['address']} | {direction} {twap['market_readable']} ({twap['market_name']}) | "
                      f"Progress: {twap['progress_pct']:.1f}% (slice {twap['slice_number']}) | "
                      f"Remaining: {twap['remaining_sz']:.4f} | "
                      f"Duration: {duration_hrs:.1f}h | Started: {start_time}")

    asyncio.run(main())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
require('dotenv').config();

function parseTwapSnapshot(data) {
    // Format: [snapshot_id, token_name, twaps_array]
    // TWAP tuple: [address, twap_id, asset, is_buy, total_sz, executed_sz, remaining_sz, executed_ntl, progress_pct, duration_secs, start_time_ms, reduce_only, randomize, next_slice_time, slice_number, market_name, market_readable, stop_px, trigger_px, trigger_above, waiting]
    const [snapshotId, tokenName, twapsRaw] = data;

    const twaps = twapsRaw.map(t => ({
        address: t[0],
        twap_id: t[1],
        asset: t[2],
        is_buy: t[3],
        total_sz: t[4],
        executed_sz: t[5],
        remaining_sz: t[6],
        executed_ntl: t[7],
        progress_pct: t[8],
        duration_secs: t[9],
        start_time_ms: t[10],
        reduce_only: t[11],
        randomize: t[12],
        next_slice_time: t[13],
        slice_number: t[14],
        market_name: t[15],      // e.g., "@232"
        market_readable: t[16],  // e.g., "HYPE/USDH"
        // New fields (2026-08): undefined on older snapshots
        stop_px: t[17] ?? null,
        trigger_px: t[18] ?? null,
        trigger_above: t[19] ?? null,
        waiting: t[20] ?? false
    }));

    return {
        snapshot_id: snapshotId,
        token: tokenName,
        twaps: twaps
    };
}

async function parseMultiZstdResponse(buffer) {
    let offset = 0;
    const count = buffer.readUInt32LE(offset);
    offset += 4;

    const tokens = [];

    for (let i = 0; i < count; i++) {
        const blobLen = buffer.readUInt32LE(offset);
        offset += 4;
        const blob = buffer.slice(offset, offset + blobLen);
        offset += blobLen;

        const decompressed = await decompress(blob);
        const snapshotData = msgpack.decode(decompressed);
        tokens.push(parseTwapSnapshot(snapshotData));
    }

    return tokens;
}

async function fetchSpotTwapSnapshots(tokens = ['ALL']) {
    const apiKey = process.env.HYDROMANCER_API_KEY;
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    };

    const response = await axios.post(
        'https://api.hydromancer.xyz/info',
        { type: 'spotTwapSnapshots', tokens: tokens },
        { headers, responseType: 'arraybuffer' }
    );

    const payloadFormat = response.headers['x-payload-format'];
    const buffer = Buffer.from(response.data);

    if (payloadFormat === 'multi-zstd') {
        return await parseMultiZstdResponse(buffer);
    } else {
        // Single token response - HTTP client auto-decompresses based on Content-Encoding
        const snapshotData = msgpack.decode(buffer);
        return [parseTwapSnapshot(snapshotData)];
    }
}

async function fetchSpotTwapTimestamp() {
    const apiKey = process.env.HYDROMANCER_API_KEY;
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    };

    const response = await axios.post(
        'https://api.hydromancer.xyz/info',
        { type: 'spotTwapSnapshotTimestamp' },
        { headers }
    );

    return response.data;
}

async function main() {
    // Check timestamp first
    const metadata = await fetchSpotTwapTimestamp();
    console.log(`Snapshot ID: ${metadata.snapshot_id}`);
    console.log(`Timestamp: ${metadata.timestamp}`);

    // Fetch all spot TWAP snapshots
    const snapshots = await fetchSpotTwapSnapshots(['ALL']);

    for (const tokenData of snapshots) {
        console.log(`\nToken: ${tokenData.token}`);
        for (const twap of tokenData.twaps.slice(0, 3)) {  // Show first 3 TWAPs
            const direction = twap.is_buy ? 'BUY' : 'SELL';
            const durationHrs = (twap.duration_secs / 3600).toFixed(1);
            const startTime = new Date(twap.start_time_ms).toISOString();
            console.log(`  ${twap.address.slice(0, 10)}... | ${direction} ${twap.market_readable} (${twap.market_name}) | ` +
                `Progress: ${twap.progress_pct.toFixed(1)}% (slice ${twap.slice_number}) | ` +
                `Remaining: ${twap.remaining_sz.toFixed(4)} | ` +
                `Duration: ${durationHrs}h | Started: ${startTime}`);
        }
    }
}

if (require.main === module) {
    main().catch(console.error);
}

module.exports = { fetchSpotTwapSnapshots, fetchSpotTwapTimestamp };
```

{% endtab %}
{% endtabs %}


# l4Book

Get a Hyperliquid L4 orderbook snapshot for perpetual markets.

{% hint style="info" %}
💧 New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

### Overview

The `l4Book` endpoint returns L4 orderbook snapshots. It includes all resting limit orders on the book with user addresses, but does **not** include trigger orders (stop-loss, take-profit) unless they have been triggered and placed on the book.

**Key details:**

* Refreshed every second
* Perpetual markets by default; outcome markets available via `marketTypes` or explicit `coins`
* Includes user address for each order

## Request

**Endpoint:** `POST /info`

**All markets (perps only — default):**

```json
{
    "type": "l4Book"
}
```

**All markets, perps + outcomes:**

```json
{
    "type": "l4Book",
    "marketTypes": ["perp", "outcome"]
}
```

**Specific coins (any market type):**

```json
{
    "type": "l4Book",
    "coins": ["ETH", "BTC", "#2870"]
}
```

**Parameters:**

| Parameter     | Type      | Required | Description                                                                                                                                                                                                  |
| ------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `coins`       | string\[] | No       | Specific markets to fetch. Omit for all markets. Duplicates are ignored; more than 2048 distinct coins is rejected with HTTP 400.                                                                            |
| `marketTypes` | string\[] | No       | All-markets only. Each entry is `"perp"`, `"spot"`, `"outcome"`, or the wildcard `"*"` (alone) for every type the server currently tracks. Omit for `["perp"]` (default). Rejected if combined with `coins`. |

### Response

**Headers:**

* `Content-Type: application/octet-stream`
* `x-payload-format: multi-zstd`
* `x-compression: inner-zstd`

**Format:** Multi-zstd binary format

```
[count:u32][height:u64][timestamp_ms:u64][len:u32][blob]...
```

Each blob is a zstd-compressed msgpack market snapshot:

```json
{
    "coin": "ETH",
    "bids": [
        {
            "oid": 217148811876,
            "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2",
            "px": "3245.50",
            "sz": "1.5"
        }
    ],
    "asks": [
        {
            "oid": 217148811900,
            "user": "0x010461c14e146ac35fe42271bdc1134ee31c703a",
            "px": "3246.00",
            "sz": "2.0"
        }
    ]
}
```

### Example

{% tabs %}
{% tab title="Python" %}

```python
import struct
import aiohttp
import asyncio
import zstandard as zstd
import msgpack
import os

def parse_l4_book_response(data: bytes) -> dict:
    """Parse multi-zstd L4 book response."""
    offset = 0

    # Read header
    count = struct.unpack_from('<I', data, offset)[0]
    offset += 4
    height = struct.unpack_from('<Q', data, offset)[0]
    offset += 8
    timestamp_ms = struct.unpack_from('<Q', data, offset)[0]
    offset += 8

    # Read and decompress each market
    dctx = zstd.ZstdDecompressor()
    markets = []

    for _ in range(count):
        blob_len = struct.unpack_from('<I', data, offset)[0]
        offset += 4
        blob = data[offset:offset + blob_len]
        offset += blob_len

        # max_output_size needed when zstd frame lacks content size
        decompressed = dctx.decompress(blob, max_output_size=blob_len * 20)
        m = msgpack.unpackb(decompressed, raw=False)

        # Wire format: [coin, bids, asks] where order = [user, px, sz, oid]
        bids = [{"oid": o[3], "user": o[0], "px": o[1], "sz": o[2]} for o in m[1]]
        asks = [{"oid": o[3], "user": o[0], "px": o[1], "sz": o[2]} for o in m[2]]
        markets.append({"coin": m[0], "bids": bids, "asks": asks})

    return {
        'height': height,
        'timestamp_ms': timestamp_ms,
        'markets': markets
    }

async def fetch_l4_book(coins=None):
    """Fetch L4 book snapshot from API."""
    api_key = os.environ.get('HYDROMANCER_API_KEY')
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    request = {'type': 'l4Book'}
    if coins:
        request['coins'] = coins

    async with aiohttp.ClientSession() as session:
        async with session.post(
            'https://api.hydromancer.xyz/info',
            json=request,
            headers=headers
        ) as resp:
            data = await resp.read()
            return parse_l4_book_response(data)

if __name__ == "__main__":
    result = asyncio.run(fetch_l4_book(['ETH', 'BTC']))
    print(f"Height: {result['height']}")
    for market in result['markets']:
        print(f"{market['coin']}: {len(market['bids'])} bids, {len(market['asks'])} asks")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');

async function parseL4BookResponse(buffer) {
    let offset = 0;

    // Read header
    const count = buffer.readUInt32LE(offset);
    offset += 4;
    const height = buffer.readBigUInt64LE(offset);
    offset += 8;
    const timestampMs = buffer.readBigUInt64LE(offset);
    offset += 8;

    // Read and decompress each market
    const markets = [];

    for (let i = 0; i < count; i++) {
        const blobLen = buffer.readUInt32LE(offset);
        offset += 4;
        const blob = buffer.slice(offset, offset + blobLen);
        offset += blobLen;

        const decompressed = await decompress(blob);
        const m = msgpack.decode(decompressed);

        // Wire format: [coin, bids, asks] where order = [user, px, sz, oid]
        const bids = m[1].map(o => ({ oid: o[3], user: o[0], px: o[1], sz: o[2] }));
        const asks = m[2].map(o => ({ oid: o[3], user: o[0], px: o[1], sz: o[2] }));
        markets.push({ coin: m[0], bids, asks });
    }

    return {
        height: Number(height),
        timestampMs: Number(timestampMs),
        markets
    };
}

async function fetchL4Book(coins = null) {
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`
    };

    const request = { type: 'l4Book' };
    if (coins) {
        request.coins = coins;
    }

    const response = await axios.post(
        'https://api.hydromancer.xyz/info',
        request,
        { headers, responseType: 'arraybuffer' }
    );

    return parseL4BookResponse(Buffer.from(response.data));
}

// Example usage
(async () => {
    const result = await fetchL4Book(['ETH', 'BTC']);
    console.log(`Height: ${result.height}`);
    for (const market of result.markets) {
        console.log(`${market.coin}: ${market.bids.length} bids, ${market.asks.length} asks`);
    }
})();
```

{% endtab %}
{% endtabs %}

### Rate limits

* 20 requests per 5 minutes

### Common errors

* **400**: Invalid request (e.g. more than 2048 distinct `coins`)
* **403**: Permission denied - check API key
* **404**: None of the requested coins have an L4 book. The error names those coins.
* **503**: Snapshot metadata is missing, or no all-markets blob is ready. Honor `Retry-After: 1`.
* **429**: Rate limit exceeded


# l2Book

Get a Hyperliquid L2 orderbook snapshot with aggregated price levels.

### Overview

The `l2Book` endpoint returns L2 orderbook snapshots — aggregated price levels with total size and order count at each level. Supports optional price aggregation via significant figures and mantissa parameters.

**Key details:**

* Depth-20 snapshots (top 20 bids and asks)
* Refreshed once per second
* Supports price aggregation (`nSigFigs`, `mantissa`)
* Returns zstd-compressed msgpack

### Request

**Endpoint:** `POST /info`

**Single coin:**

```json
{
    "type": "l2Book",
    "coin": "ETH"
}
```

**Multiple coins:**

```json
{
    "type": "l2Book",
    "coins": ["ETH", "BTC", "SOL"]
}
```

**With aggregation:**

```json
{
    "type": "l2Book",
    "coin": "BTC",
    "nSigFigs": 5,
    "mantissa": 2
}
```

**Parameters:**

| Parameter  | Type      | Required | Description                                                                                             |
| ---------- | --------- | -------- | ------------------------------------------------------------------------------------------------------- |
| `coin`     | string    | No\*     | Single coin to fetch. Spot (`"@107"`, `"PURR/USDC"`) and outcome markets (`"#2870"` etc.) are accepted. |
| `coins`    | string\[] | No\*     | Multiple coins to fetch. Spot and outcome markets are accepted.                                         |
| `nSigFigs` | number    | No       | Aggregate price levels to N significant figures (2-5).                                                  |
| `mantissa` | number    | No       | Snap to mantissa step (2 or 5). Only valid when `nSigFigs=5`.                                           |

\* Either `coin` or `coins` must be provided. This endpoint has no all-markets / firehose mode — use [`l2BookDiffSnapshot`](https://hydromancer.xyz/docs/rest-api/market-data/l2bookdiffsnapshot) for that.

### Response

**Headers:**

* `Content-Type: application/octet-stream`
* `Content-Encoding: zstd`

**Format:** Zstd-compressed msgpack `L2BookSnapshot`:

```json
{
    "coin": "ETH",
    "time": 1704067200000,
    "levels": [
        [
            {"px": "3245.5", "sz": "12.4", "n": 3},
            {"px": "3244.0", "sz": "8.7", "n": 5}
        ],
        [
            {"px": "3246.0", "sz": "6.2", "n": 2},
            {"px": "3247.5", "sz": "15.3", "n": 4}
        ]
    ],
    "height": 782007304
}
```

For multiple coins, each snapshot is returned as a separate zstd-compressed msgpack blob.

### Field reference

| Field           | Type   | Description                                               |
| --------------- | ------ | --------------------------------------------------------- |
| `coin`          | string | Market symbol                                             |
| `time`          | number | Block timestamp (milliseconds since epoch)                |
| `levels`        | array  | Tuple of `[bids, asks]`. Bids descending, asks ascending. |
| `levels[][].px` | string | Price as decimal string                                   |
| `levels[][].sz` | string | Total size at this price level                            |
| `levels[][].n`  | number | Number of orders at this level                            |
| `height`        | number | Block height of this snapshot                             |

### Common errors

* **400**: Missing or invalid `coin`/`coins` parameter
* **400**: Invalid `nSigFigs` (must be 2-5) or `mantissa` (must be 2 or 5 with `nSigFigs=5`)
* **403**: Permission denied - check API key
* **404** `"{coin} is not listed"`: the coin is not in Hyperliquid's current listings (the dex's perp `meta`, `spotMeta` or `outcomeMeta`). Typical causes are a typo, a missing dex prefix (`xyz:GOLD`, not `GOLD`), or a market that has not launched yet. Retrying will not help until the coin is listed. With `coins`, this is returned only when no requested coin has a snapshot and every one of them is unlisted; the message names them (`"xyz:FOO, xyz:BAR are not listed"`).
* **404** `"snapshot not available — orderbook_service may be starting up, retry shortly"`: the coin is listed but its snapshot is not ready, which is on our side. Retry after a short delay.
* **429**: Rate limit exceeded

With `coins`, coins that have no snapshot are left out of the response as long as at least one coin has one.


# l2BookDiffSnapshot

Get a Hyperliquid L2 orderbook snapshot for bootstrapping the l2BookDiff WebSocket stream.

{% hint style="info" %}
💧 New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

### Overview

The `l2BookDiffSnapshot` endpoint returns full-depth L2 orderbook snapshots with `height`, `epoch`, and `seq` fields. This is the bootstrap endpoint for clients using the [`l2BookDiff`](https://hydromancer.xyz/docs/websocket/orderbook-streaming/l2bookdiff) WebSocket stream — fetch a snapshot here, then apply incremental diffs from the WebSocket to maintain a local orderbook.

**Key details:**

* Full-depth snapshots (all price levels)
* Includes `height`, `epoch`, and `seq` for diff stream synchronization
* Returns msgpack — zstd-compressed only when the request sends `Accept-Encoding: zstd`, otherwise uncompressed

### Request

**Endpoint:** `POST /info`

**Single coin:**

```json
{
    "type": "l2BookDiffSnapshot",
    "coin": "ETH"
}
```

**Multiple coins:**

```json
{
    "type": "l2BookDiffSnapshot",
    "coins": ["ETH", "BTC"]
}
```

**All markets, perps only (default):**

```json
{
    "type": "l2BookDiffSnapshot"
}
```

**All markets, perps + outcomes:**

```json
{
    "type": "l2BookDiffSnapshot",
    "marketTypes": ["perp", "outcome"]
}
```

**Parameters:**

| Parameter     | Type      | Required | Description                                                                                                                                                                                                           |
| ------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `coin`        | string    | No       | Single coin to fetch.                                                                                                                                                                                                 |
| `coins`       | string\[] | No       | Multiple coins to fetch.                                                                                                                                                                                              |
| `marketTypes` | string\[] | No       | All-markets only. Each entry is `"perp"`, `"spot"`, `"outcome"`, or the wildcard `"*"` (alone) for every type the server currently tracks. Omit for `["perp"]` (default). Rejected if combined with `coin` / `coins`. |

Omit both `coin` and `coins` to fetch all markets. Always returns full-depth snapshots.

### Response

**Headers:**

* `Content-Type: application/octet-stream`
* `Content-Encoding: zstd` — **only** when the request sends `Accept-Encoding: zstd`. Without it, the body is uncompressed msgpack. (Only `zstd` is supported; `gzip` is ignored.)

**Format:** msgpack `L2BookSnapshot`. Each snapshot is encoded as a **positional array** (not a keyed map), always with this exact field order and length:

```
[coin, time, levels, height, epoch, seq]
```

All six elements are always present (`epoch` and `seq` are never omitted — `seq` is `0` only if the coin has had no diff this epoch). Shown as JSON for readability:

```json
{
    "coin": "ETH",
    "time": 1704067200000,
    "levels": [
        [
            {"px": "3245.5", "sz": "12.4", "n": 3},
            {"px": "3244.0", "sz": "8.7", "n": 5}
        ],
        [
            {"px": "3246.0", "sz": "6.2", "n": 2},
            {"px": "3247.5", "sz": "15.3", "n": 4}
        ]
    ],
    "height": 782007304,
    "epoch": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "seq": 206670
}
```

### Field reference

| Field           | Type   | Description                                                                                                                                                                                                                             |
| --------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `coin`          | string | Market symbol                                                                                                                                                                                                                           |
| `time`          | number | Block timestamp (milliseconds since epoch)                                                                                                                                                                                              |
| `levels`        | array  | Tuple of `[bids, asks]`. Bids descending, asks ascending.                                                                                                                                                                               |
| `levels[][].px` | string | Price as decimal string                                                                                                                                                                                                                 |
| `levels[][].sz` | string | Total size at this price level                                                                                                                                                                                                          |
| `levels[][].n`  | number | Number of orders at this level                                                                                                                                                                                                          |
| `height`        | number | Block height of this snapshot — use this to align with the `l2BookDiff` stream.                                                                                                                                                         |
| `epoch`         | string | Server epoch (UUID) — must match `epoch` in `l2BookDiff` messages. A different `epoch` means the snapshot is stale; re-fetch.                                                                                                           |
| `seq`           | number | Per-coin sequence number as of this snapshot. Always present (`0` if the coin has had no diff this epoch). Matches the per-coin `seq` in the `l2BookDiff` stream — the first diff you apply for the coin should have `prev_seq == seq`. |

### Bootstrapping the diff stream

Align on **`height`** — it is always present and is shared by this snapshot and every `l2BookDiff` batch. The snapshot already includes the diffs *up to and including* its own `height` (it is taken after that block is applied), so discard any diff at or below it.

> Don't align on the diff stream's top-level `seq`; that is a per-connection message counter, unrelated to this snapshot. See [`l2BookDiff` → Sequencing and gap detection](https://hydromancer.xyz/docs/websocket/orderbook-streaming/l2bookdiff#sequencing-and-gap-detection).

1. Subscribe to [`l2BookDiff`](https://hydromancer.xyz/docs/websocket/orderbook-streaming/l2bookdiff) for your coin(s) — start buffering messages.
2. Fetch this snapshot — note `height`, `epoch`, and the per-coin `seq`.
3. Discard already-applied diffs: drop any buffered batch whose `data.height <= snapshot.height`.
4. Verify `epoch`: every remaining diff's `epoch` must equal the snapshot's `epoch`. A different `epoch` means the server restarted after the snapshot — re-fetch and restart.
5. Apply the remaining batches in `height` order. The first diff you apply for each coin should have `prev_seq == snapshot.seq` (the per-coin `seq`).
6. Ongoing gap detection: per coin, check `prev_seq` continuity against the last `seq` you applied (see [`l2BookDiff` → Sequencing and gap detection](https://hydromancer.xyz/docs/websocket/orderbook-streaming/l2bookdiff#sequencing-and-gap-detection)). On a gap or `epoch` change, re-fetch this snapshot.

### Common errors

* **400**: Invalid `coin`/`coins` parameter
* **403**: Permission denied - check API key
* **404** `"{coin} is not listed"`: the coin is not in Hyperliquid's current listings (the dex's perp `meta`, `spotMeta` or `outcomeMeta`). Typical causes are a typo, a missing dex prefix (`xyz:GOLD`, not `GOLD`), or a market that has not launched yet. Retrying will not help until the coin is listed. With `coins`, this is returned only when no requested coin has a snapshot and every one of them is unlisted; the message names them (`"xyz:FOO, xyz:BAR are not listed"`).
* **404** `"snapshot not available — orderbook_service may be starting up, retry shortly"`: the coin is listed but its snapshot is not ready, which is on our side. Retry after a short delay.
* **404** (all-markets request, `coin`/`coins` omitted): no snapshot is ready yet for the requested `marketTypes`. Retry after a short delay.
* **429**: Rate limit exceeded

With `coins`, coins that have no snapshot are left out of the response as long as at least one coin has one.


# tpslBook

Get a snapshot of all active Hyperliquid TP/SL trigger orders.

{% hint style="info" %}
💧 New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

### Overview

The `tpslBook` endpoint returns a snapshot of all untriggered TP/SL orders (take profit, stop loss) across all markets. These are orders that exist on Hyperliquid but have **not yet been triggered** — they are not visible in the L4 orderbook.

**Key details:**

* \~110K trigger orders across \~330 markets (typical)
* Updated in real-time (per-block)
* Includes user address, trigger price, size, and order type for each order
* Use with [tpslUpdates](https://hydromancer.xyz/docs/websocket/tpslupdates) WebSocket stream for real-time sync

## Request

**Endpoint:** `POST /info`

**All markets:**

```json
{
    "type": "tpslBook"
}
```

**Specific coins:**

```json
{
    "type": "tpslBook",
    "coins": ["BTC", "ETH"]
}
```

**Parameters:**

| Parameter              | Type      | Required | Description                                                                                   |
| ---------------------- | --------- | -------- | --------------------------------------------------------------------------------------------- |
| `coins`                | string\[] | No       | Specific markets to fetch. Omit for all markets.                                              |
| `includeTrailingState` | boolean   | No       | Defaults to false. Explicitly request the versioned trailing-state snapshot and replay fence. |

### Optional trailing state

`{"type":"tpslBook","coins":["BTC"],"includeTrailingState":true}` requests an enhanced snapshot. Availability requires the environment feature to be enabled and a committed enhanced view. A disabled environment returns `403` with code `trailing_feature_disabled`. An enabled environment without a ready view returns retryable `503` with code `trailing_state_unavailable` and `Retry-After`; it never substitutes an ordinary snapshot. Omitting the option or setting false keeps the original response and its EOF, in either environment.

Enhanced responses preserve the ordinary outer framing and append exactly one `[trailer_len:u32_le][trailer_blob]`. The blob is `zstd(msgpack(map))` containing `schemaVersion:1`, `height`, `timestampMs`, `cursor`, `resetFence` and `orders`. Each `orders` entry contains `coin`, `oid`, `orderVersion` and required `trailing`: null for non-trailing orders, otherwise the complete derived state (`triggerPx`, `bestPx`, `activationPx`, `retracement`, `retracementType`, `lifecycle`, `quality`). Nullable derived values are explicit null. Exactly one placement version covers every included active order; coin filtering applies to both ordinary and enhanced data. Ordinary order fields remain in the market blobs.

The `x-tpsl-lifecycle-height`, `x-tpsl-pricing-cursor` and `x-tpsl-reset-fence` headers match the same immutable body and are exposed to browser clients. Use the native version-1 cursor for exact snapshot cutover; see the [enhanced cursor contract](https://hydromancer.xyz/docs/websocket/tpslupdates#enhanced-cursors-and-bootstrap). Do not compare cursor strings or use height alone for enhanced cutover. Enhanced decoders must reject missing/conflicting headers, unknown trailer versions and legacy EOF after opt-in. Default decoders read only the original layout and receive no trailer.

Python: `await client.fetch_tpsl_snapshot(include_trailing_state=True)` returns the decoded snapshot with an additional `trailing` member. It raises `TpslFeatureDisabled` for disabled admission and `TpslSnapshotUnavailable` for retryable unavailability (`retry_after_secs` exposes a numeric `Retry-After`). This REST option does not enable trailing WebSocket updates.

### Response

**Content-Type:** `application/octet-stream`

The response is a binary multi-zstd payload (\~4.2 MB for all markets, vs \~31 MB if served as JSON). Each market is compressed independently and concatenated with the same outer framing as [l4Book](https://hydromancer.xyz/docs/rest-api/market-data/l4book). The SDK's `TpslClient` decodes this transparently — see [Streaming sync](#streaming-sync) below.

**Response headers:**

| Header             | Value                      |
| ------------------ | -------------------------- |
| `Content-Type`     | `application/octet-stream` |
| `x-payload-format` | `multi-zstd`               |
| `x-compression`    | `inner-zstd`               |

**Logical content (after decode):**

```json
{
    "height": 1012534610,
    "timestamp_ms": 1779884746878,
    "markets": [
        {
            "coin": "BTC",
            "orders": [
                {
                    "oid": 443601009265,
                    "coin": "BTC",
                    "user": "0x106cf0642235394d51cba33693ac49ce05262298",
                    "side": "B",
                    "triggerPx": "71000",
                    "limitPx": "63900",
                    "sz": "0.00789",
                    "triggerCondition": "Price below 71000",
                    "orderType": "Take Profit Market",
                    "isPositionTpsl": false,
                    "reduceOnly": true,
                    "timestamp": 1779821645206
                }
            ]
        }
    ]
}
```

### Response fields

| Field              | Type   | Description                              |
| ------------------ | ------ | ---------------------------------------- |
| `height`           | int    | Block height at the time of the snapshot |
| `timestamp_ms`     | int    | Block timestamp (ms since epoch)         |
| `markets`          | array  | Array of markets with trigger orders     |
| `markets[].coin`   | string | Market symbol                            |
| `markets[].orders` | array  | Trigger orders in this market            |

Order fields are the same as the [tpslUpdates](https://hydromancer.xyz/docs/websocket/tpslupdates) `add` diff — see that page for full field descriptions.

<details>

<summary>Wire format (for non-SDK decoders)</summary>

All integers are little-endian. The SDK's [tpsl\_formats.py](https://github.com/hydromancerxyz/hydromancer-sdk/blob/main/src/hydromancer_sdk/_internal/tpsl_formats.py) is a \~100-line reference decoder.

**Outer framing:**

```
[count:u32_le][height:u64_le][timestamp_ms:u64_le]
  [blob_len:u32_le][blob_bytes] × count
```

| Field          | Bytes      | Description                                 |
| -------------- | ---------- | ------------------------------------------- |
| `count`        | 4          | Number of market blobs that follow          |
| `height`       | 8          | Block height of the snapshot                |
| `timestamp_ms` | 8          | Block timestamp (ms since epoch)            |
| `blob_len`     | 4          | Length in bytes of the next compressed blob |
| `blob_bytes`   | `blob_len` | zstd-compressed market payload (see below)  |

Markets are sorted by coin name. Coins with no trigger orders are omitted.

**Per-market blob:**

Each blob is `zstd(msgpack([coin, [order_tuples...]]))`. The msgpack uses positional arrays (not maps) for compactness — `rmp_serde::to_vec` on the Rust side. Each order is a 12-element array in struct-declaration order:

```
[oid, coin, user, side, trigger_px, limit_px, sz,
 trigger_condition, order_type, is_position_tpsl,
 reduce_only, timestamp]
```

| Index | Field               | Type   | Notes                                        |
| ----- | ------------------- | ------ | -------------------------------------------- |
| 0     | `oid`               | uint64 | Order ID                                     |
| 1     | `coin`              | string | Market symbol (matches outer `coin`)         |
| 2     | `user`              | string | User address (0x...)                         |
| 3     | `side`              | string | `"A"` (sell) or `"B"` (buy)                  |
| 4     | `trigger_px`        | string | Trigger price, decimal string                |
| 5     | `limit_px`          | string | Limit price, decimal string                  |
| 6     | `sz`                | string | Size, decimal string                         |
| 7     | `trigger_condition` | string | Human-readable condition                     |
| 8     | `order_type`        | string | E.g. `"Take Profit Market"`, `"Stop Market"` |
| 9     | `is_position_tpsl`  | bool   | `true` if attached to a position             |
| 10    | `reduce_only`       | bool   | `true` if reduce-only                        |
| 11    | `timestamp`         | uint64 | Order creation timestamp (ms)                |

</details>

### Streaming sync

For a default add/remove subscription:

1. Subscribe to [tpslUpdates](https://hydromancer.xyz/docs/websocket/tpslupdates) WebSocket stream
2. Fetch `tpslBook` snapshot — note the `height`
3. Apply buffered WS updates where `height > snapshot_height`
4. Continue applying live updates

Enhanced subscriptions require exact native cursor cutover rather than the height-only recipe above. Request `includeTrailingUpdates:true` independently on the WebSocket and follow the [enhanced bootstrap contract](https://hydromancer.xyz/docs/websocket/tpslupdates#enhanced-cursors-and-bootstrap).

See the [TP/SL heatmap streaming guide](https://hydromancer.xyz/docs/builder-guides/tpsl-heatmap-streaming) for details.

### Rate limits

* 10 requests per 5 minutes

### Common errors

* **403**: Permission denied - check API key
* **429**: Rate limit exceeded
* **503**: Service unavailable - heatmap service is bootstrapping


# marketLiquidity

Get aggregated orderbook depth for a specific Hyperliquid market.

## Overview

The `marketLiquidity` endpoint returns aggregated orderbook depth data for a specific market.

**Key details:**

* Refreshed every second
* Data retained for 24 hours
* Depth available at multiple bps levels (2, 5, 10, 25, 25-500)
* Supports time-based filtering (up to 24h back)

#### Request

**Endpoint:** `POST /info`

<table><thead><tr><th width="164">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"marketLiquidity"</code></td></tr><tr><td><code>market</code></td><td>string</td><td>Market symbol (e.g., "BTC", "flx:TSLA") - required</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Start timestamp in milliseconds, must be within 24h (optional)</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>End timestamp in milliseconds, used with startTime (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max rows to return, default/max 500 (optional)</td></tr></tbody></table>

**Note:** When `startTime` is provided, results are returned in ascending order (oldest first). Without `startTime`, results are returned in descending order (newest first).

{% tabs %}
{% tab title="Python" %}

<pre class="language-python"><code class="lang-python"><strong>import requests 
</strong>import os
response = requests.post(
    'https://api.hydromancer.xyz/info', 
    json={ 'type': 'marketLiquidity', 'market': 'BTC', 'limit': 100 }, 
    headers={ 
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}', 
        'Content-Type': 'application/json' 
        } 
    )
print(response.json())
</code></pre>

{% endtab %}
{% endtabs %}

<details>

<summary>Response Fields</summary>

```json
[
  {
    "timestamp": 1769093272236,
    "market": "BTC",
    "bestBidPrice": "89216.00",
    "bestAskPrice": "89217.00",
    "bidDepth2bps": "2.74368",
    "bidDepth5bps": "54.3951",
    "bidDepth10bps": "181.87754",
    "bidDepth25bps": "569.9405",
    "bidDepth25To500bps": "1956.54844",
    "askDepth2bps": "134.67537",
    "askDepth5bps": "207.53212",
    "askDepth10bps": "376.64531",
    "askDepth25bps": "672.82051",
    "askDepth25To500bps": "1890.64212"
  }
]
```

| Field                | Description                                                          |
| -------------------- | -------------------------------------------------------------------- |
| `timestamp`          | Snapshot timestamp in milliseconds                                   |
| `market`             | Market symbol                                                        |
| `bestBidPrice`       | Best bid price across all addresses                                  |
| `bestAskPrice`       | Best ask price across all addresses                                  |
| `bidDepth2bps`       | Total bid depth within 2 basis points of mid (in market asset)       |
| `bidDepth5bps`       | Total bid depth within 5 basis points of mid (in market asset)       |
| `bidDepth10bps`      | Total bid depth within 10 basis points of mid (in market asset)      |
| `bidDepth25bps`      | Total bid depth within 25 basis points of mid (in market asset)      |
| `bidDepth25To500bps` | Total bid depth between 25-500 basis points of mid (in market asset) |
| `askDepth2bps`       | Total ask depth within 2 basis points of mid (in market asset)       |
| `askDepth5bps`       | Total ask depth within 5 basis points of mid (in market asset)       |
| `askDepth10bps`      | Total ask depth within 10 basis points of mid (in market asset)      |
| `askDepth25bps`      | Total ask depth within 25 basis points of mid (in market asset)      |
| `askDepth25To500bps` | Total ask depth between 25-500 basis points of mid (in market asset) |

</details>

#### Rate limits

* 10 points per request

#### Common errors

* **400**: `market parameter is required` - must provide market symbol
* **400**: `startTime cannot be more than 24 hours in the past` - time filter limit
* **403**: Permission denied - check API key
* **429**: Rate limit exceeded


# marketLiquidityHistory

Get hourly-averaged orderbook depth history for a specific Hyperliquid market with unlimited retention.

### Overview

The `marketLiquidityHistory` endpoint returns hourly-averaged orderbook depth data for a specific market. It provides the same depth metrics as `marketLiquidity` but pre-aggregated into hourly buckets with **unlimited retention** (whereas `marketLiquidity` is limited to 24 hours).

**Key details:**

* Hourly granularity (average depth per snapshot within each hour)
* Unlimited data retention
* Depth available at multiple bps levels (2, 5, 10, 25, 25-500)
* `startTime` is required; results always returned in ascending order

## Request

**Endpoint:** `POST /info`

<table><thead><tr><th width="164">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"marketLiquidityHistory"</code></td></tr><tr><td><code>market</code></td><td>string</td><td>Market symbol (e.g., "BTC", "ETH") - required</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Start timestamp in milliseconds - required</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>End timestamp in milliseconds (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max rows to return, default 500, max 2000 (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "marketLiquidityHistory",
    "market": "BTC",
    "startTime": 1706000000000,
    "endTime": 1706100000000,
    "limit": 500
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'marketLiquidityHistory',
        'market': 'BTC',
        'startTime': 1706000000000,
        'endTime': 1706100000000,
        'limit': 500
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'marketLiquidityHistory',
        market: 'BTC',
        startTime: 1706000000000,
        endTime: 1706100000000,
        limit: 500
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
[
  {
    "timestamp": 1706000000000,
    "market": "BTC",
    "snapshots": 3600,
    "avgBidDepth2bps": "2.74368",
    "avgBidDepth5bps": "54.3951",
    "avgBidDepth10bps": "181.87754",
    "avgBidDepth25bps": "569.9405",
    "avgBidDepth25To500bps": "1956.54844",
    "avgAskDepth2bps": "134.67537",
    "avgAskDepth5bps": "207.53212",
    "avgAskDepth10bps": "376.64531",
    "avgAskDepth25bps": "672.82051",
    "avgAskDepth25To500bps": "1890.64212"
  }
]
```

</details>

## Response Fields

| Field                   | Description                                                            |
| ----------------------- | ---------------------------------------------------------------------- |
| `timestamp`             | Hour start timestamp in milliseconds                                   |
| `market`                | Market symbol                                                          |
| `snapshots`             | Number of per-market snapshots aggregated in this hour                 |
| `avgBidDepth2bps`       | Average bid depth within 2 basis points of mid (in market asset)       |
| `avgBidDepth5bps`       | Average bid depth within 5 basis points of mid (in market asset)       |
| `avgBidDepth10bps`      | Average bid depth within 10 basis points of mid (in market asset)      |
| `avgBidDepth25bps`      | Average bid depth within 25 basis points of mid (in market asset)      |
| `avgBidDepth25To500bps` | Average bid depth between 25-500 basis points of mid (in market asset) |
| `avgAskDepth2bps`       | Average ask depth within 2 basis points of mid (in market asset)       |
| `avgAskDepth5bps`       | Average ask depth within 5 basis points of mid (in market asset)       |
| `avgAskDepth10bps`      | Average ask depth within 10 basis points of mid (in market asset)      |
| `avgAskDepth25bps`      | Average ask depth within 25 basis points of mid (in market asset)      |
| `avgAskDepth25To500bps` | Average ask depth between 25-500 basis points of mid (in market asset) |

### Comparison with marketLiquidity

| Feature     | `marketLiquidity`        | `marketLiquidityHistory` |
| ----------- | ------------------------ | ------------------------ |
| Granularity | Per-second snapshots     | Hourly averages          |
| Retention   | 24 hours                 | Unlimited                |
| Values      | Total depth per snapshot | Average depth per hour   |
| `startTime` | Optional (within 24h)    | Required                 |

### Rate limits

* 10 points per request

### Common errors

* **400**: `market parameter is required` - must provide market symbol
* **400**: `startTime parameter is required` - startTime is mandatory
* **403**: Permission denied - check API key
* **429**: Rate limit exceeded


# slippageHistory

Get historical slippage estimates for a specific Hyperliquid market and notional size.

### Overview

The `slippageHistory` endpoint returns historical slippage data sampled every 15 minutes. For a given coin and USD notional amount, it provides the estimated buy and sell slippage in basis points, along with the half-spread.

**Key details:**

* 15-minute sample interval
* Slippage measured in basis points (bps) for a specific USD notional size
* Available notional amounts: $1K, $5K, $10K, $30K, $50K, $100K, $250K, $500K, $1M
* Supports all perp markets including HIP-3 dexes
* Values rounded to 2 decimal places
* `startTime` and `amount` are required; results returned in ascending order

## Request

**Endpoint:** `POST /info`

<table><thead><tr><th width="164">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"slippageHistory"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>Coin symbol (e.g., "BTC", "ETH", "xyz:GOLD") - required</td></tr><tr><td><code>amount</code></td><td>number</td><td>USD notional amount (e.g., 100000) - required</td></tr><tr><td><code>startTime</code></td><td>integer</td><td>Start timestamp in milliseconds - required</td></tr><tr><td><code>endTime</code></td><td>integer</td><td>End timestamp in milliseconds (optional)</td></tr><tr><td><code>limit</code></td><td>integer</td><td>Max rows to return, default 500, max 2000 (optional)</td></tr></tbody></table>

**Coin format:** For Hyperliquid native markets, use the coin symbol directly (e.g., `"BTC"`, `"ETH"`). For HIP-3 dex markets, prefix with the dex name and a colon (e.g., `"xyz:GOLD"`, `"cash:TSLA"`).

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "slippageHistory",
    "coin": "BTC",
    "amount": 100000,
    "startTime": 1706000000000,
    "limit": 500
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'slippageHistory',
        'coin': 'BTC',
        'amount': 100000,
        'startTime': 1706000000000,
        'limit': 500
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'slippageHistory',
        coin: 'BTC',
        amount: 100000,
        startTime: 1706000000000,
        limit: 500
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
[
  {
    "timestamp": 1764777547234,
    "dex": "hyperliquid",
    "coin": "BTC",
    "halfSpreadBps": 0.05,
    "amountUsd": 100000.0,
    "buySlippageBps": 1.36,
    "sellSlippageBps": 0.05
  },
  {
    "timestamp": 1764778383619,
    "dex": "hyperliquid",
    "coin": "BTC",
    "halfSpreadBps": 0.05,
    "amountUsd": 100000.0,
    "buySlippageBps": 0.05,
    "sellSlippageBps": 0.05
  }
]
```

</details>

## Response Fields

| Field             | Description                                                              |
| ----------------- | ------------------------------------------------------------------------ |
| `timestamp`       | Sample timestamp in milliseconds                                         |
| `dex`             | DEX identifier (e.g., `"hyperliquid"`, `"xyz"`)                          |
| `coin`            | Coin symbol                                                              |
| `halfSpreadBps`   | Half-spread at time of sample, in basis points                           |
| `amountUsd`       | USD notional amount this slippage was estimated for                      |
| `buySlippageBps`  | Estimated buy slippage in basis points (null if insufficient liquidity)  |
| `sellSlippageBps` | Estimated sell slippage in basis points (null if insufficient liquidity) |

### Comparison with marketLiquidityHistory

| Feature        | `marketLiquidityHistory`      | `slippageHistory`               |
| -------------- | ----------------------------- | ------------------------------- |
| Units          | Depth in market asset (coins) | Slippage in basis points        |
| Denominated in | Asset quantity                | USD notional                    |
| Granularity    | Hourly averages               | 15-minute samples               |
| Use case       | How deep is the book?         | How much would a $X trade slip? |

### Rate limits

* 10 points per request

### Common errors

* **400**: `coin parameter is required` - must provide coin symbol
* **400**: `amount parameter is required (positive USD notional)` - must provide a positive USD amount
* **400**: `startTime parameter is required` - startTime is mandatory
* **403**: Permission denied - check API key
* **429**: Rate limit exceeded


# currentDepth

Get real-time cumulative orderbook depth at multiple BPS levels for all Hyperliquid markets.

{% hint style="info" %}
New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

{% hint style="warning" %}

### ⚠️ This is an add-on endpoint - access has to be purchased separately.

{% endhint %}

### Overview

The `currentDepth` endpoint returns a real-time snapshot of cumulative orderbook depth at wide BPS levels (10, 25, 50, 100, 200, 500) for all markets. Depth is computed from the full L4 orderbook with no minimum liquidity filter.

**Key details:**

* Refreshed every second (same cadence as foundational data snapshots)
* Returns all markets in a single batch response
* Depth values are cumulative (e.g., 50 bps includes all liquidity within 50 bps)
* Grouped by DEX, filterable with optional `dex` parameter
* Values are in USD
* Includes `timestampMs` for data freshness verification

## Request

**Endpoint:** `POST /info`

<table><thead><tr><th width="164">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"currentDepth"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td>Filter by DEX (e.g., "hyperliquid", "hyna") (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
# All markets, all DEXes
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "currentDepth"}'

# Filter by DEX
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "currentDepth", "dex": "hyperliquid"}'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'currentDepth',
        'dex': 'hyperliquid'  # optional
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'currentDepth',
        dex: 'hyperliquid'  // optional
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

<details>

<summary>Response</summary>

```json
{
  "timestampMs": 1712930000000,
  "data": [
    {
      "coin": "BTC",
      "dex": "hyperliquid",
      "levels": [
        { "bps": 10, "bidDepthUsd": 4523891.23, "askDepthUsd": 3891234.56 },
        { "bps": 25, "bidDepthUsd": 12345678.90, "askDepthUsd": 11234567.89 },
        { "bps": 50, "bidDepthUsd": 28456789.01, "askDepthUsd": 26789012.34 },
        { "bps": 100, "bidDepthUsd": 45678901.23, "askDepthUsd": 43210987.65 },
        { "bps": 200, "bidDepthUsd": 67890123.45, "askDepthUsd": 65432109.87 },
        { "bps": 500, "bidDepthUsd": 89012345.67, "askDepthUsd": 87654321.09 }
      ]
    },
    {
      "coin": "ETH",
      "dex": "hyperliquid",
      "levels": [
        { "bps": 10, "bidDepthUsd": 1234567.89, "askDepthUsd": 1123456.78 },
        { "bps": 25, "bidDepthUsd": 3456789.01, "askDepthUsd": 3234567.89 },
        { "bps": 50, "bidDepthUsd": 6789012.34, "askDepthUsd": 6543210.98 },
        { "bps": 100, "bidDepthUsd": 12345678.90, "askDepthUsd": 11234567.89 },
        { "bps": 200, "bidDepthUsd": 18901234.56, "askDepthUsd": 17890123.45 },
        { "bps": 500, "bidDepthUsd": 23456789.01, "askDepthUsd": 22345678.90 }
      ]
    }
  ]
}
```

</details>

## Response Fields

| Field                         | Description                                             |
| ----------------------------- | ------------------------------------------------------- |
| `timestampMs`                 | Epoch milliseconds when the depth snapshot was computed |
| `data`                        | Array of per-market depth entries                       |
| `data[].coin`                 | Base coin symbol (e.g., "BTC", "ETH")                   |
| `data[].dex`                  | DEX name (e.g., "hyperliquid", "hyna")                  |
| `data[].levels`               | Array of depth levels, one per BPS threshold            |
| `data[].levels[].bps`         | BPS threshold (10, 25, 50, 100, 200, 500)               |
| `data[].levels[].bidDepthUsd` | Cumulative bid depth within this BPS level, in USD      |
| `data[].levels[].askDepthUsd` | Cumulative ask depth within this BPS level, in USD      |

### Comparison with marketLiquidity

| Feature     | currentDepth              | marketLiquidity               |
| ----------- | ------------------------- | ----------------------------- |
| BPS levels  | 10, 25, 50, 100, 200, 500 | 2, 5, 10, 25, 25-500          |
| Granularity | Real-time snapshot        | Time series (24h retention)   |
| Values      | USD                       | Market asset units            |
| Scope       | All markets in one call   | Single market per call        |
| History     | Current only              | Up to 24h with time filtering |

### Rate limits

* 5 points per request

### Common errors

* **403**: Permission denied - check API key
* **429**: Rate limit exceeded
* **500**: Internal error - depth data may not yet be published


# fundingPayments

Get all Hyperliquid funding payments for the most recent hour across all markets and users as a compressed snapshot.

### Overview

The fundingPayments endpoint returns all funding payments from the most recent funding hour across every market and user on Hyperliquid. Data is grouped by coin and compressed using msgpack + zstd.

There are two endpoints:

1. **Metadata Endpoint (Fast)**: Check the current snapshot timestamp and event count
2. **Snapshot Endpoint (Heavy)**: Download the full funding payment data

### Funding Payment Metadata (Fast)

* **Endpoint**: `POST /info`
* **Purpose**: Check the current snapshot timestamp and size without downloading data

#### Request

```json
{
  "type": "fundingPaymentTimestamp"
}
```

#### Response

```json
{
  "time": 1709251200000,
  "count": 198432
}
```

| Field   | Description                            |
| ------- | -------------------------------------- |
| `time`  | Funding hour timestamp in milliseconds |
| `count` | Total number of funding payment events |

### Funding Payments Snapshot (Heavy)

* **Endpoint**: `POST /info`
* **Purpose**: Download the full funding payment snapshot
* **Response**: zstd-compressed msgpack binary

#### Request

```json
{
  "type": "fundingPayments"
}
```

#### Response Headers

| Header             | Value                       |
| ------------------ | --------------------------- |
| `Content-Type`     | `application/zstd`          |
| `x-payload-format` | `msgpack`                   |
| `x-snapshot-time`  | Funding hour timestamp (ms) |
| `x-snapshot-count` | Total event count           |

### Python SDK raw download

`SnapshotsClient.fetch_funding_payments_raw()` returns the compressed response bytes without decoding or HTTP decompression. It uses the snapshot client's authentication, bounded 429 retries, and existing HTTP error handling.

```python
from hydromancer_sdk import SnapshotsClient

snapshots = SnapshotsClient(api_key="YOUR_API_KEY")
compressed = await snapshots.fetch_funding_payments_raw()
```

Generic `RestClient.call("fundingPayments")` keeps its existing HTTP and JSON/text decoding behavior. Use the raw method to download the compressed snapshot.

Pass `error_format="structured-v1"` to select structured errors. The snapshot bytes and metadata headers remain unchanged. Missing, expired, or unpublished snapshots and Redis failures return 503 with `code: "unavailable"`. These failures remain legacy 500 without the selector. `fundingPaymentTimestamp` is a separate operation and remains outside structured support.

The SDK requires the `X-HM-Error-Format: structured-v1` response header. Missing confirmation raises `ErrorFormatUnavailable` without a retry. Pass `allow_legacy_response=True` to receive raw response evidence with `downgraded=True` instead. This option does not resend the request; a confirmed structured failure still raises a typed error with HTTP status, code, and raw evidence.

### Data Format

The response body is a zstd-compressed msgpack binary. After decompressing (zstd) and decoding (msgpack), the payload is an array:

```json
[
  1709251200000,
  [
    ["BTC", "0.0001", ["0xabc...", "0xdef..."], ["12.345", "-5.678"], ["1.5", "-0.8"]],
    ["ETH", "-0.00005", ["0x123..."], ["-2.1"], ["10.0"]]
  ]
]
```

| Index      | Description                                                    |
| ---------- | -------------------------------------------------------------- |
| `[0]`      | Funding hour timestamp in milliseconds                         |
| `[1]`      | Array of per-coin funding data                                 |
| `[1][][0]` | Coin name (e.g., "BTC", "ETH")                                 |
| `[1][][1]` | Funding rate for this coin (string, same for all users)        |
| `[1][][2]` | User addresses (parallel array)                                |
| `[1][][3]` | Funding payment amounts per user (string, parallel with `[2]`) |
| `[1][][4]` | Position sizes per user (string, parallel with `[2]`)          |

All numeric values (rate, amounts, sizes) are decimal strings for exact precision.

### Implementation Examples

**Note**: Set **HYDROMANCER\_API\_KEY** in your .env file.

{% tabs %}
{% tab title="Python" %}

```python
import asyncio
import io
import aiohttp
import zstandard as zstd
import msgpack
import os
from dotenv import load_dotenv

load_dotenv()


async def get_funding_payments():
    base_url = os.getenv("HYDROMANCER_API_URL", "https://api.hydromancer.xyz")
    api_key = os.getenv("HYDROMANCER_API_KEY")
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
    }

    async with aiohttp.ClientSession() as session:
        # 1. Check metadata first
        async with session.post(
            f"{base_url}/info",
            json={"type": "fundingPaymentTimestamp"},
            headers=headers,
        ) as resp:
            meta = await resp.json()
            print(f"Snapshot time: {meta['time']}, events: {meta['count']}")

        # 2. Download snapshot
        async with session.post(
            f"{base_url}/info",
            json={"type": "fundingPayments"},
            headers=headers,
        ) as resp:
            compressed = await resp.read()
            print(f"Downloaded {len(compressed)} bytes")

            # Decompress and decode
            dctx = zstd.ZstdDecompressor()
            raw = dctx.stream_reader(io.BytesIO(compressed)).read()
            data = msgpack.unpackb(raw, raw=False)

            timestamp, markets = data[0], data[1]
            print(f"Funding hour: {timestamp}")
            print(f"Markets: {len(markets)}")

            for market in markets:
                coin, rate, addresses, amounts, sizes = market
                print(f"  {coin}: rate={rate}, users={len(addresses)}")


asyncio.run(get_funding_payments())
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const { decompress } = require('@mongodb-js/zstd');
const msgpack = require('msgpack-lite');
require('dotenv').config();

async function getFundingPayments() {
    const baseUrl = process.env.HYDROMANCER_API_URL || 'https://api.hydromancer.xyz';
    const apiKey = process.env.HYDROMANCER_API_KEY;
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
    };

    // 1. Check metadata first
    const metaResp = await axios.post(
        `${baseUrl}/info`,
        { type: 'fundingPaymentTimestamp' },
        { headers }
    );
    console.log(`Snapshot time: ${metaResp.data.time}, events: ${metaResp.data.count}`);

    // 2. Download snapshot
    const resp = await axios.post(
        `${baseUrl}/info`,
        { type: 'fundingPayments' },
        { headers, responseType: 'arraybuffer' }
    );

    const compressed = Buffer.from(resp.data);
    console.log(`Downloaded ${compressed.length} bytes`);

    // Decompress and decode
    const raw = await decompress(compressed);
    const data = msgpack.decode(raw);

    const [timestamp, markets] = data;
    console.log(`Funding hour: ${timestamp}`);
    console.log(`Markets: ${markets.length}`);

    for (const [coin, rate, addresses, amounts, sizes] of markets) {
        console.log(`  ${coin}: rate=${rate}, users=${addresses.length}`);
    }
}

getFundingPayments().catch(console.error);
```

{% endtab %}
{% endtabs %}


# maxMarketOrderNtls

Get Hyperliquid's maximum market order notional sizes by leverage tier.

Get Hyperliquid's maximum market order notional sizes by leverage tier.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"maxMarketOrderNtls"</code></td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "maxMarketOrderNtls"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'maxMarketOrderNtls'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'maxMarketOrderNtls'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns an array of `[maxLeverage, maxNtl]` tuples.

| Index | Type   | Description                                      |
| ----- | ------ | ------------------------------------------------ |
| `[0]` | int    | Maximum leverage tier                            |
| `[1]` | string | Maximum market order notional size for this tier |

<details>

<summary>Response</summary>

```json
[
    [25, "15000000.0"],
    [20, "5000000.0"],
    [10, "2000000.0"],
    [1, "500000.0"]
]
```

</details>


# perpsAtOpenInterestCap

Get the list of Hyperliquid perp assets currently at their open interest cap.

Get the list of Hyperliquid perp assets currently at their open interest cap.

## POST Request

<table><thead><tr><th width="161.9998779296875">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpsAtOpenInterestCap"</code></td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpsAtOpenInterestCap"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpsAtOpenInterestCap'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'perpsAtOpenInterestCap'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns an array of coin symbol strings representing perp assets currently at their open interest cap.

| Index | Type   | Description                      |
| ----- | ------ | -------------------------------- |
| `[n]` | string | Coin symbol at open interest cap |

<details>

<summary>Response</summary>

```json
["CANTO", "FTM", "JELLY", "LOOM", "MAVIA", "RLB"]
```

</details>


# Metadata

Retrieve metadata about Hyperliquid perpetual and spot markets, margin requirements, exchange status, available DEXes, and perp asset annotations and limits.

{% content-ref url="/pages/hl0uXWbwFhkUVExFvgbj" %}
[meta](https://hydromancer.xyz/docs/rest-api/metadata/meta)
{% endcontent-ref %}

{% content-ref url="/pages/w8F0Q7fQiYikI2579tpl" %}
[allPerpMetas](https://hydromancer.xyz/docs/rest-api/metadata/allperpmetas)
{% endcontent-ref %}

{% content-ref url="/pages/CxeUQnY3fCBeiDGTUruE" %}
[spotMeta](https://hydromancer.xyz/docs/rest-api/metadata/spotmeta)
{% endcontent-ref %}

{% content-ref url="/pages/Z5Kz1LIv1OLopA0Ie1wA" %}
[marginTable](https://hydromancer.xyz/docs/rest-api/metadata/margintable)
{% endcontent-ref %}

{% content-ref url="/pages/44utyohbX9tVMMlYpWQN" %}
[exchangeStatus](https://hydromancer.xyz/docs/rest-api/metadata/exchangestatus)
{% endcontent-ref %}

{% content-ref url="/pages/9eG7qcvh5edw8A8dctMW" %}
[perpDexs](https://hydromancer.xyz/docs/rest-api/metadata/perpdexs)
{% endcontent-ref %}

{% content-ref url="/pages/jxPAmP2MhXvz0Nz77tqg" %}
[perpAnnotation](https://hydromancer.xyz/docs/rest-api/metadata/perpannotation)
{% endcontent-ref %}

{% content-ref url="/pages/34mUlAQtcATPGFOqEhBE" %}
[perpCategories](https://hydromancer.xyz/docs/rest-api/metadata/perpcategories)
{% endcontent-ref %}

{% content-ref url="/pages/M2OBDiDu098zowC43Bad" %}
[perpConciseAnnotations](https://hydromancer.xyz/docs/rest-api/metadata/perpconciseannotations)
{% endcontent-ref %}

{% content-ref url="/pages/FLVprdA4MIoDtGyuiz1D" %}
[perpDexStatus](https://hydromancer.xyz/docs/rest-api/metadata/perpdexstatus)
{% endcontent-ref %}

{% content-ref url="/pages/1zGdPp7VLKr0GtbSoIwK" %}
[perpDexLimits](https://hydromancer.xyz/docs/rest-api/metadata/perpdexlimits)
{% endcontent-ref %}


# meta

Returns metadata for Hyperliquid perpetual markets including asset names, size decimals, and max leverage.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"meta"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name (optional). Defaults to empty string for the first perp DEX.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "meta"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'meta'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'meta'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                     | Type    | Description                              |
| ------------------------- | ------- | ---------------------------------------- |
| `universe`                | array   | List of perpetual asset metadata objects |
| `universe[].name`         | string  | Asset symbol (e.g. `"BTC"`)              |
| `universe[].szDecimals`   | int     | Number of decimal places for size        |
| `universe[].maxLeverage`  | int     | Maximum allowed leverage                 |
| `universe[].onlyIsolated` | boolean | Whether only isolated margin is allowed  |

<details>

<summary>Response</summary>

```json
{
  "universe": [
    {
      "name": "BTC",
      "szDecimals": 5,
      "maxLeverage": 50,
      "onlyIsolated": false
    },
    {
      "name": "ETH",
      "szDecimals": 4,
      "maxLeverage": 50,
      "onlyIsolated": false
    }
  ]
}
```

</details>


# metaAndAssetCtxs

Returns Hyperliquid perpetual market metadata together with the per-asset trading context (prices, open interest, and 24h volume) in a single request.

{% hint style="info" %}
This endpoint is currently **mainnet-only**.
{% endhint %}

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"metaAndAssetCtxs"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name (optional). Defaults to empty string for the first perp DEX; pass a builder-deployed DEX name for a HIP-3 market.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept-Encoding: gzip" \
  -d '{
    "type": "metaAndAssetCtxs"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'metaAndAssetCtxs'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'metaAndAssetCtxs'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

The response can be large (\~50 KB for the full native universe). Send `Accept-Encoding: gzip` (or `br`) to receive it compressed.

***

## Response Fields

The response is a two-element array: `[meta, assetCtxs]`.

`meta` is identical to the [meta](https://hydromancer.xyz/docs/rest-api/metadata/meta) endpoint (`universe`, `marginTables`, `collateralToken`).

`assetCtxs` is an array of per-asset context objects in the same order as `meta.universe`, so `assetCtxs[i]` corresponds to `meta.universe[i]`. An asset with no cached context is returned with null fields, keeping the array aligned with the universe.

| Field          | Type   | Description                                                              |
| -------------- | ------ | ------------------------------------------------------------------------ |
| `oraclePx`     | string | Oracle price                                                             |
| `markPx`       | string | Mark price                                                               |
| `midPx`        | string | Mid price; `null` when there is no book                                  |
| `impactPxs`    | array  | `[impact bid, impact ask]`; `null` when unavailable                      |
| `openInterest` | string | Open interest, in base units                                             |
| `dayNtlVlm`    | string | 24-hour notional volume (sum of price × size over the trailing 24 hours) |
| `dayBaseVlm`   | string | 24-hour base volume (sum of size over the trailing 24 hours)             |

<details>

<summary>Response</summary>

```json
[
  {
    "universe": [
      {
        "name": "BTC",
        "szDecimals": 5,
        "maxLeverage": 40,
        "onlyIsolated": false
      }
    ],
    "marginTables": [],
    "collateralToken": 0
  },
  [
    {
      "oraclePx": "63961",
      "markPx": "63970",
      "midPx": "63965.5",
      "impactPxs": ["63960", "63971"],
      "openInterest": "37318.54584",
      "dayNtlVlm": "1690219500.99709",
      "dayBaseVlm": "26703.40439"
    }
  ]
]
```

</details>


# spotMeta

Returns metadata for Hyperliquid spot markets including token names, size decimals, and trading pair information.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"spotMeta"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "spotMeta"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'spotMeta'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'spotMeta'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                         | Type    | Description                                         |
| --------------------------------------------- | ------- | --------------------------------------------------- |
| `universe`                                    | array   | List of spot market metadata objects                |
| `universe[].tokens`                           | array   | Token pair `[base, quote]` indices                  |
| `universe[].name`                             | string  | Market name (e.g. `"HYPE"`)                         |
| `universe[].index`                            | int     | Market index                                        |
| `universe[].isCanonical`                      | boolean | Whether this is the canonical spot market           |
| `tokens`                                      | array   | List of token metadata objects                      |
| `tokens[].name`                               | string  | Token symbol (e.g. `"USDC"`)                        |
| `tokens[].szDecimals`                         | int     | Number of decimal places for size                   |
| `tokens[].weiDecimals`                        | int     | Number of wei decimals                              |
| `tokens[].index`                              | int     | Token index                                         |
| `tokens[].tokenId`                            | string  | Token identifier                                    |
| `tokens[].isCanonical`                        | boolean | Whether this is the canonical token                 |
| `tokens[].evmContract`                        | object? | EVM contract details, `null` if not deployed on EVM |
| `tokens[].evmContract.address`                | string  | EVM contract address                                |
| `tokens[].evmContract.evm_extra_wei_decimals` | int     | Extra wei decimals for EVM conversion               |
| `tokens[].fullName`                           | string? | Full token name, `null` if not set                  |
| `tokens[].deployerTradingFeeShare`            | string  | Deployer's share of trading fees                    |

<details>

<summary>Response</summary>

```json
{
  "universe": [
    {
      "tokens": [0, 1],
      "name": "PURR/USDC",
      "index": 0,
      "isCanonical": true
    }
  ],
  "tokens": [
    {
      "name": "USDC",
      "szDecimals": 8,
      "weiDecimals": 8,
      "index": 0,
      "tokenId": "0x6d1e7cde53ba9467b783cb7c530ce054",
      "isCanonical": true,
      "evmContract": {
        "address": "0x6b9e773128f453f5c2c60935ee2de2cbc5390a24",
        "evm_extra_wei_decimals": -2
      },
      "fullName": null,
      "deployerTradingFeeShare": "0.0"
    },
    {
      "name": "PURR",
      "szDecimals": 0,
      "weiDecimals": 5,
      "index": 1,
      "tokenId": "0xc1fb593aeffbeb02f85e0308e9956a90",
      "isCanonical": true,
      "evmContract": {
        "address": "0x9b498c3c8a0b8cd8ba1d9851d40d186f1872b44e",
        "evm_extra_wei_decimals": 13
      },
      "fullName": null,
      "deployerTradingFeeShare": "0.0"
    }
  ]
}
```

</details>


# marginTable

Returns the margin requirements table for a specific Hyperliquid perpetual asset by index.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"marginTable"</code></td></tr><tr><td><code>id</code></td><td>int</td><td>Asset index (required)</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "marginTable",
    "id": 1
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'marginTable',
        'id': 1
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'marginTable',
    id: 1
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                       | Type   | Description                                        |
| --------------------------- | ------ | -------------------------------------------------- |
| `description`               | string | Description of the margin table                    |
| `marginTiers`               | array  | List of margin tier objects                        |
| `marginTiers[].lowerBound`  | string | Lower bound of the notional position for this tier |
| `marginTiers[].maxLeverage` | int    | Maximum leverage allowed at this tier              |

<details>

<summary>Response</summary>

```json
{
  "description": "",
  "marginTiers": [
    {
      "lowerBound": "0.0",
      "maxLeverage": 1
    }
  ]
}
```

</details>


# perpDexs

Returns the list of all available Hyperliquid perpetual DEXes.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpDexs"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpDexs"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpDexs'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpDexs'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                                | Type    | Description                                                                                 |
| ------------------------------------ | ------- | ------------------------------------------------------------------------------------------- |
| (root)                               | array   | Array where index 0 is `null` (the native/first DEX) and subsequent entries are DEX objects |
| `[n].name`                           | string  | Short DEX identifier (e.g. `"xyz"`)                                                         |
| `[n].fullName`                       | string  | Full DEX display name                                                                       |
| `[n].deployer`                       | string  | Deployer Ethereum address                                                                   |
| `[n].oracleUpdater`                  | string? | Oracle updater address, `null` if not set                                                   |
| `[n].feeRecipient`                   | string  | Fee recipient address                                                                       |
| `[n].assetToStreamingOiCap`          | array   | Array of `[asset, cap]` pairs for streaming open interest caps                              |
| `[n].subDeployers`                   | array   | Array of `[permission, [addresses]]` pairs                                                  |
| `[n].deployerFeeScale`               | string  | Deployer fee scale factor                                                                   |
| `[n].lastDeployerFeeScaleChangeTime` | string  | Timestamp of last fee scale change                                                          |
| `[n].assetToFundingMultiplier`       | array   | Array of `[asset, multiplier]` pairs                                                        |
| `[n].assetToFundingInterestRate`     | array   | Array of `[asset, rate]` pairs for custom funding interest rates                            |

<details>

<summary>Response</summary>

```json
[
  null,
  {
    "name": "xyz",
    "fullName": "XYZ",
    "deployer": "0x88806a71d74ad0a510b350545c9ae490912f0888",
    "oracleUpdater": null,
    "feeRecipient": "0x9cd0a696c7cbb9d44de99268194cb08e5684e5fe",
    "assetToStreamingOiCap": [
      ["xyz:NVDA", "250000000.0"],
      ["xyz:GOLD", "500000000.0"]
    ],
    "subDeployers": [
      ["registerAsset", ["0x7d16f116d252db609c56d27d6c9605eb03e16657"]],
      ["setOracle", ["0x1234567890545d1df9ee64b35fdd16966e08acec"]]
    ],
    "deployerFeeScale": "1.0",
    "lastDeployerFeeScaleChangeTime": "1970-01-01T00:00:00",
    "assetToFundingMultiplier": [
      ["xyz:NVDA", "0.5"],
      ["xyz:GOLD", "0.5"]
    ],
    "assetToFundingInterestRate": [
      ["xyz:EUR", "0.0"],
      ["xyz:JPY", "0.0"]
    ]
  }
]
```

</details>


# allPerpMetas

Returns the perpetuals metadata (universe definitions and margin tables) for every Hyperliquid perp DEX in a single response.

The first element is the native Hyperliquid perp DEX; subsequent elements are builder-deployed (HIP-3) perp DEXes, in the same order as [perpDexs](https://hydromancer.xyz/docs/rest-api/metadata/perpdexs).

For the metadata of a single DEX, use [meta](https://hydromancer.xyz/docs/rest-api/metadata/meta) with the `dex` field.

{% hint style="info" %}
This endpoint returns the full universe and margin tables across all DEXes and is correspondingly heavier — it costs **10 points** per request (vs 2 for `meta`). See [Rate limits and user limits](https://hydromancer.xyz/docs/rest-api/rate-limits-and-user-limits).
{% endhint %}

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"allPerpMetas"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "allPerpMetas"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'allPerpMetas'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'allPerpMetas'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                               | Type   | Description                                                                                                       |
| ----------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------- |
| (root)                              | array  | One entry per perp DEX. Index 0 is the native Hyperliquid perp DEX; later entries are builder-deployed perp DEXes |
| `[n].universe`                      | array  | List of perp asset definitions for this DEX                                                                       |
| `[n].universe[].name`               | string | Asset name (with DEX prefix for builder-deployed perps)                                                           |
| `[n].universe[].szDecimals`         | int    | Number of decimals for the size field                                                                             |
| `[n].universe[].maxLeverage`        | int    | Maximum leverage for the asset                                                                                    |
| `[n].universe[].marginTableId`      | int    | Margin table id referenced in `marginTables`                                                                      |
| `[n].universe[].isDelisted`         | bool?  | Present and `true` if the asset is delisted                                                                       |
| `[n].marginTables`                  | array  | List of `[marginTableId, marginTable]` pairs for this DEX                                                         |
| `[n].marginTables[][0]`             | int    | Margin table id                                                                                                   |
| `[n].marginTables[][1].description` | string | Description of the margin table                                                                                   |
| `[n].marginTables[][1].marginTiers` | array  | List of `{ lowerBound, maxLeverage }` tiers                                                                       |
| `[n].collateralToken`               | int    | Token index used as collateral for this DEX                                                                       |

<details>

<summary>Response (trimmed)</summary>

```json
[
  {
    "universe": [
      { "szDecimals": 5, "name": "BTC", "maxLeverage": 40, "marginTableId": 56 },
      { "szDecimals": 4, "name": "ETH", "maxLeverage": 25, "marginTableId": 55 }
    ],
    "marginTables": [
      [
        50,
        {
          "description": "",
          "marginTiers": [
            { "lowerBound": "0.0", "maxLeverage": 50 }
          ]
        }
      ]
    ],
    "collateralToken": 0
  }
]
```

</details>


# perpAnnotation

Returns the human-readable annotation (category, description, and keywords) for a single Hyperliquid perpetual asset.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpAnnotation"</code></td></tr><tr><td><code>coin</code></td><td>string</td><td>Perp asset name, including the DEX prefix for builder-deployed perps (e.g. <code>"xyz:TSLA"</code>). Required. Only perp assets are accepted — spot and outcome markets are rejected.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpAnnotation",
    "coin": "xyz:TSLA"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpAnnotation',
        'coin': 'xyz:TSLA'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpAnnotation',
    coin: 'xyz:TSLA'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns `null` if the asset has no annotation.

| Field         | Type   | Description                                                                        |
| ------------- | ------ | ---------------------------------------------------------------------------------- |
| `category`    | string | Asset category (e.g. `"stocks"`, `"crypto"`, `"commodities"`, `"indices"`, `"FX"`) |
| `description` | string | Human-readable description of the underlying asset                                 |
| `displayName` | string | Display name for the asset                                                         |
| `keywords`    | array? | Optional list of search keywords                                                   |

<details>

<summary>Response</summary>

```json
{
  "category": "stocks",
  "description": "TSLA tracks the value of 1 share of common stock in Tesla, Inc. Tesla designs and manufactures electric vehicles, battery energy storage systems, and solar products. The company is a global leader in EV production and autonomous driving technology.",
  "displayName": "TSLA",
  "keywords": ["tesla", "ev"]
}
```

</details>


# batchPerpAnnotations

Get human-readable annotations for multiple Hyperliquid perpetual assets in a single request.

Returns the human-readable annotation (category, description, display name, and keywords) for multiple perpetual assets in a single request. This is the batched form of [perpAnnotation](https://hydromancer.xyz/docs/rest-api/metadata/perpannotation) — results are returned as an object keyed by coin.

## POST Request

<table><thead><tr><th width="163">Field</th><th width="135">Type</th><th width="471">Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"batchPerpAnnotations"</code></td></tr><tr><td><code>coins</code></td><td>array</td><td>Array of perp asset names, including the DEX prefix for builder-deployed perps (e.g. <code>"xyz:TSLA"</code>). Required, non-empty. Only perp assets are accepted — spot and outcome markets are rejected. Duplicates are de-duplicated.</td></tr></tbody></table>

### Limits

You can query up to **100 coins** at once. Requests exceeding this are rejected with a 400 error.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "batchPerpAnnotations",
    "coins": ["xyz:TSLA", "xyz:NVDA"]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'batchPerpAnnotations',
        'coins': ['xyz:TSLA', 'xyz:NVDA']
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'batchPerpAnnotations',
    coins: ['xyz:TSLA', 'xyz:NVDA']
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field          | Type   | Description                                                                                                                                                                                                                                                    |
| -------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `annotations`  | object | Map of `coin` → annotation payload. Each value is the same object returned by [perpAnnotation](https://hydromancer.xyz/docs/rest-api/metadata/perpannotation) (`category`, `description`, `displayName`, `keywords`), or `null` if the perp has no annotation. |
| `failed_coins` | array  | Coins whose underlying request failed (transport/HTTP error). Distinct from a successful `null` annotation.                                                                                                                                                    |

A coin with no annotation appears in `annotations` with a `null` value — it is **not** a failure. Only coins whose node request errored land in `failed_coins`.

<details>

<summary>Response</summary>

```json
{
  "annotations": {
    "xyz:TSLA": {
      "category": "stocks",
      "description": "TSLA tracks the value of 1 share of common stock in Tesla, Inc.",
      "displayName": "TSLA",
      "keywords": ["tesla", "ev"]
    },
    "xyz:NVDA": {
      "category": "stocks",
      "description": "NVDA tracks the value of 1 share of common stock in NVIDIA Corporation.",
      "displayName": "NVDA",
      "keywords": ["nvidia", "gpu", "ai"]
    }
  },
  "failed_coins": []
}
```

</details>


# perpCategories

Returns the category for every annotated Hyperliquid perpetual asset as a list of \[coin, category] pairs.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpCategories"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpCategories"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpCategories'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpCategories'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field    | Type   | Description                                                   |
| -------- | ------ | ------------------------------------------------------------- |
| (root)   | array  | Array of `[coin, category]` pairs                             |
| `[n][0]` | string | Perp asset name (with DEX prefix for builder-deployed perps)  |
| `[n][1]` | string | Asset category (e.g. `"crypto"`, `"stocks"`, `"commodities"`) |

<details>

<summary>Response</summary>

```json
[
  ["flx:BTC", "crypto"],
  ["flx:COIN", "stocks"],
  ["flx:COPPER", "commodities"]
]
```

</details>


# perpConciseAnnotations

Returns concise annotations for every annotated Hyperliquid perpetual asset as a list of \[coin, annotation] pairs.

Each annotation carries the category plus optional display name and keywords — the description is omitted (use [perpAnnotation](https://hydromancer.xyz/docs/rest-api/metadata/perpannotation) for the full description of a single asset).

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpConciseAnnotations"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpConciseAnnotations"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpConciseAnnotations'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpConciseAnnotations'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field                | Type    | Description                                                  |
| -------------------- | ------- | ------------------------------------------------------------ |
| (root)               | array   | Array of `[coin, annotation]` pairs                          |
| `[n][0]`             | string  | Perp asset name (with DEX prefix for builder-deployed perps) |
| `[n][1].category`    | string  | Asset category                                               |
| `[n][1].displayName` | string? | Optional display name                                        |
| `[n][1].keywords`    | array?  | Optional list of search keywords                             |

<details>

<summary>Response</summary>

```json
[
  ["flx:BTC", { "category": "crypto" }],
  ["flx:COIN", { "category": "stocks" }],
  ["para:AVGO", { "category": "stocks", "keywords": ["broadcom", "ai"] }],
  ["para:BTCD", { "category": "crypto", "displayName": "BTC.D", "keywords": ["dominance", "index"] }]
]
```

</details>


# perpDexStatus

Returns the status of a builder-deployed (HIP-3) Hyperliquid perp DEX, including its total net deposits.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpDexStatus"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name (e.g. <code>"xyz"</code>). Required. An empty string selects the native Hyperliquid perp DEX.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpDexStatus",
    "dex": "xyz"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpDexStatus',
        'dex': 'xyz'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpDexStatus',
    dex: 'xyz'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field             | Type   | Description                     |
| ----------------- | ------ | ------------------------------- |
| `totalNetDeposit` | string | Total net deposits into the DEX |

<details>

<summary>Response</summary>

```json
{
  "totalNetDeposit": "825489811.4041969776"
}
```

</details>


# perpDexLimits

Returns the open-interest and transfer limits for a builder-deployed (HIP-3) Hyperliquid perp DEX, including the per-asset open-interest caps.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"perpDexLimits"</code></td></tr><tr><td><code>dex</code></td><td>string</td><td>Perp DEX name (e.g. <code>"xyz"</code>). Required. An empty string selects the native Hyperliquid perp DEX.</td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "perpDexLimits",
    "dex": "xyz"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'perpDexLimits',
        'dex': 'xyz'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'perpDexLimits',
    dex: 'xyz'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

Returns `null` for a DEX that has no configured limits.

| Field            | Type   | Description                                                           |
| ---------------- | ------ | --------------------------------------------------------------------- |
| `totalOiCap`     | string | Total open-interest cap across the DEX                                |
| `oiSzCapPerPerp` | string | Open-interest size cap per perp                                       |
| `maxTransferNtl` | string | Maximum transfer notional                                             |
| `coinToOiCap`    | array  | Array of `[coin, oiCap]` pairs giving the per-asset open-interest cap |

<details>

<summary>Response (trimmed)</summary>

```json
{
  "totalOiCap": "6000000000.0",
  "oiSzCapPerPerp": "20000000000.0",
  "maxTransferNtl": "2000000000.0",
  "coinToOiCap": [
    ["xyz:AAPL", "100000000.0"],
    ["xyz:ALUMINIUM", "25000000.0"]
  ]
}
```

</details>


# exchangeStatus

Returns the current status of the Hyperliquid exchange.

<table><thead><tr><th width="115">Field</th><th width="177">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"exchangeStatus"</code></td></tr></tbody></table>

## Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "exchangeStatus"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os
import json

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'exchangeStatus'
    },
    headers={
        'Authorization': f'Bearer {os.environ["HYDROMANCER_API_KEY"]}',
        'Content-Type': 'application/json'
    }
)
print(json.dumps(response.json(), indent=2))
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

const response = await axios.post(
  'https://api.hydromancer.xyz/info',
  {
    type: 'exchangeStatus'
  },
  {
    headers: {
      'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);

console.log(JSON.stringify(response.data, null, 2));
```

{% endtab %}
{% endtabs %}

***

## Response Fields

| Field             | Type    | Description                                         |
| ----------------- | ------- | --------------------------------------------------- |
| `specialStatuses` | object? | Special status flags, `null` under normal operation |
| `time`            | int     | Current exchange timestamp (ms)                     |

<details>

<summary>Response</summary>

```json
{
  "specialStatuses": null,
  "time": 1773647974412
}
```

</details>


# Outcomes

Endpoints for querying Hyperliquid prediction market outcomes.

Query Hyperliquid **HIP-4** prediction market outcomes, settlement specs, templates, active balance snapshots, and permissionless venue stats.&#x20;

For full product overview and live streams, see [Hyperliquid HIP-4 data](https://hydromancer.xyz/hip-4) and the [hip4MarketEvents](https://hydromancer.xyz/docs/websocket/hip4marketevents) WebSocket stream.

| Need                               | Endpoints                                                                                                                                                                                                                                                                                         | Best For                                                                                                            |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Discovery & metadata**           | [outcomeMeta](https://hydromancer.xyz/docs/rest-api/outcomes/outcomemeta), [outcomeTemplates](https://hydromancer.xyz/docs/rest-api/outcomes/outcometemplates)                                                                                                                                    | Listing active prediction markets and reusable outcome schemas                                                      |
| **Registered outcomes & balances** | [registeredOutcomes](https://hydromancer.xyz/docs/rest-api/outcomes/registeredoutcomes), [registeredOutcomesById](https://hydromancer.xyz/docs/rest-api/outcomes/registeredoutcomesbyid), [registeredOutcomesSnapshot](https://hydromancer.xyz/docs/rest-api/outcomes/registeredoutcomessnapshot) | Active outcome state and compressed per-side balance snapshots (`registeredOutcomesSnapshot` is an add-on endpoint) |
| **Settlement results**             | [settledOutcome](https://hydromancer.xyz/docs/rest-api/outcomes/settledoutcome), [settledOutcomes](https://hydromancer.xyz/docs/rest-api/outcomes/settledoutcomes), [settledOutcomesById](https://hydromancer.xyz/docs/rest-api/outcomes/settledoutcomesbyid)                                     | Verifying settlement specs and results                                                                              |
| **HIP-4 venues & deployers**       | [outcomeVenuesOverview](https://hydromancer.xyz/docs/rest-api/outcomes/outcomevenuesoverview), [outcomeVenueStats](https://hydromancer.xyz/docs/rest-api/outcomes/outcomevenuestats), [outcomeDeployerLimits](https://hydromancer.xyz/docs/rest-api/outcomes/outcomedeployerlimits)               | Venue volume/OI dashboards and deployer quota monitoring                                                            |


# outcomeMeta

Get metadata for all registered Hyperliquid prediction market outcomes.

Returns metadata for all registered prediction market outcomes. This request returns currently active outcomes with their descriptions and side specifications.

## POST Request

<table><thead><tr><th width="161">Field</th><th width="119">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>type</code></td><td>string</td><td>Must be <code>"outcomeMeta"</code></td></tr><tr><td><code>venue</code></td><td>string</td><td>Only outcomes deployed by this permissionless venue, e.g. <code>"skew"</code>. 2–4 ASCII letters, case-insensitive; a venue not present in <code>deployers</code> returns <code>400</code> (optional)</td></tr><tr><td><code>deployedBy</code></td><td>string</td><td><code>"all"</code> (default), <code>"validator"</code> (registered by validator quorum, no venue), or <code>"venue"</code> (any permissionless venue) (optional)</td></tr></tbody></table>

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "outcomeMeta"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import os

response = requests.post(
    'https://api.hydromancer.xyz/info',
    json={
        'type': 'outcomeMeta'
    },
    headers={
        'Authorization': f'Bearer {os.environ.get("HYDROMANCER_API_KEY")}',
        'Content-Type': 'application/json'
    }
)

print(response.json())
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
import axios from 'axios';

try {
    const response = await axios.post('https://api.hydromancer.xyz/info', {
        type: 'outcomeMeta'
    }, {
        headers: {
            'Authorization': `Bearer ${process.env.HYDROMANCER_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    console.log(response.data);
} catch (error) {
    console.error('Error:', error.message);
}
```

{% endtab %}
{% endtabs %}

Only outcomes deployed by the `skew` venue, then only validator-deployed outcomes:

```bash
curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "outcomeMeta", "venue": "skew"}'

curl -X POST https://api.hydromancer.xyz/info \
  -H "Authorization: Bearer $HYDROMANCER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "outcomeMeta", "deployedBy": "validator"}'
```

***

## Response Fields

| Field                              | Type    | Description                                                                                                                                   |
| ---------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `outcomes`                         | array   | List of registered outcome entries                                                                                                            |
| `outcomes[].outcome`               | integer | The outcome ID                                                                                                                                |
| `outcomes[].name`                  | string  | Outcome name                                                                                                                                  |
| `outcomes[].description`           | string  | Description or pipe-delimited metadata (e.g. \`"class:priceBinary                                                                             |
| `outcomes[].sideSpecs`             | array   | Side specifications with name for each side                                                                                                   |
| `outcomes[].sideSpecs[].name`      | string  | Name of the side (e.g. `"Yes"`, `"No"`, `"Hypurr"`)                                                                                           |
| `outcomes[].venue`                 | string? | Permissionless venue that deployed this outcome. **Absent** (not null) on validator-deployed outcomes                                         |
| `outcomes[].quoteToken`            | string? | Quote token **name** (e.g. `"USDC"`), not the numeric index — resolve via [spotMeta](https://hydromancer.xyz/docs/rest-api/metadata/spotmeta) |
| `outcomes[].deployerFeeScale`      | string? | Deployer-fee multiplier. Absent at the default of `1`; absence means the default, not unknown                                                 |
| `feeScale`                         | string? | Chain-wide default fee scale that each outcome's `deployerFeeScale` overrides                                                                 |
| `deployers`                        | array   | Registered permissionless deployers, one entry per venue                                                                                      |
| `deployers[].deployer`             | string  | Deployer address that claimed the venue                                                                                                       |
| `deployers[].venue`                | string  | Venue name, as it appears in `outcomes[].venue`                                                                                               |
| `deployers[].subDeployers`         | array   | Addresses the deployer has delegated actions to, with the action variants each may perform                                                    |
| `questions`                        | array   | List of multi-outcome questions                                                                                                               |
| `questions[].question`             | integer | The question ID                                                                                                                               |
| `questions[].name`                 | string  | Question text                                                                                                                                 |
| `questions[].description`          | string  | Question description                                                                                                                          |
| `questions[].fallbackOutcome`      | integer | Outcome ID used as fallback                                                                                                                   |
| `questions[].namedOutcomes`        | array   | List of outcome IDs that are part of this question                                                                                            |
| `questions[].settledNamedOutcomes` | array   | List of outcome IDs that have been settled                                                                                                    |

<details>

<summary>Response</summary>

```json
{
  "outcomes": [
    {
      "outcome": 9,
      "name": "Who will win the HL 100 meter dash?",
      "description": "This race is yet to be scheduled.",
      "sideSpecs": [
        { "name": "Hypurr" },
        { "name": "Usain Bolt" }
      ]
    },
    {
      "outcome": 3151,
      "name": "Recurring",
      "description": "class:priceBinary|underlying:HYPE|expiry:20260404-1145|targetPrice:38|period:15m",
      "sideSpecs": [
        { "name": "Yes" },
        { "name": "No" }
      ],
      "venue": "skew",
      "quoteToken": "USDC",
      "deployerFeeScale": "10"
    }
  ],
  "questions": [
    {
      "question": 1,
      "name": "What will Hypurr eat the most of in Feb 2026?",
      "description": "Hypurr has committed to weighing and recording daily food intake in a food journal.",
      "fallbackOutcome": 13,
      "namedOutcomes": [10, 11, 12],
      "settledNamedOutcomes": []
    }
  ],
  "deployers": [
    {
      "deployer": "0xb48c1a1ac675dcaa294ca7831eb729622c487671",
      "venue": "skew",
      "subDeployers": []
    }
  ],
  "feeScale": "1"
}
```

</details>




---

[Next Page](https://hydromancer.xyz/docs/llms-full.txt/1)

