> ## Documentation Index
> Fetch the complete documentation index at: https://scalarfield.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Hyperliquid Perps & Spot

> Screen perp and spot markets, query OHLCV candles, read live order books, track hourly funding rates, and inspect any wallet's positions and fills — all from Hyperliquid's public on-chain exchange.

<Info>**Python functions:** `screenHyperliquidMarkets()`, `getHyperliquidOHLCV()`, `getHyperliquidPriceAndBook()`, `getHyperliquidFunding()`, `getHyperliquidPositions()`, `getHyperliquidTrades()`, `screenHyperliquidWallets()`</Info>

| Specification      | Value                                                                |
| ------------------ | -------------------------------------------------------------------- |
| Delivery Frequency | continuous, real-time                                                |
| Data Frequency     | event-driven (fills, book), bar-aggregated (OHLCV), hourly (funding) |
| Coverage           | All live Hyperliquid perpetual futures and spot markets              |
| OHLCV Timeframes   | 1min to monthly (14 native intervals)                                |
| Availability       | Free                                                                 |

# Product Overview

## Overview

Hyperliquid Data provides full read access to Hyperliquid, the leading on-chain perpetual futures exchange. The dataset spans seven functions covering market discovery, price history, order book depth, funding rates, and — because Hyperliquid is fully on-chain — the open positions and complete fill history of **any wallet on the exchange**, no authentication required.

That last property is what makes this dataset unusually powerful for strategy research: on a traditional exchange you only see your own account; on Hyperliquid you can watch what the most profitable traders are holding and doing in near real time, and build strategies that follow (or fade) them.

## Functions at a Glance

| Function                       | Purpose                                                         | Example strategy use                                         |
| ------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------------ |
| `screenHyperliquidMarkets()`   | Discover perp/spot markets with live price, volume, OI, funding | Universe selection for momentum or funding-carry strategies  |
| `getHyperliquidOHLCV()`        | OHLCV candles from 1-minute to monthly                          | Backtesting, trend/breakout signals, volatility sizing       |
| `getHyperliquidPriceAndBook()` | Live mid price and L2 order book                                | Slippage estimation and entry timing before execution        |
| `getHyperliquidFunding()`      | Historical hourly funding rates per perp                        | Funding-carry (basis) strategies, crowding/sentiment signals |
| `getHyperliquidPositions()`    | Open perp positions + spot balances for any wallet              | Copy-trading and whale-positioning signals                   |
| `getHyperliquidTrades()`       | Full fill history for any wallet                                | Reverse-engineering a top trader's entries and exits         |
| `screenHyperliquidWallets()`   | Rank \~40k wallets by PnL, ROI, volume                          | Finding which wallets are worth copying in the first place   |

## Data Sources

All functions read from Hyperliquid's own first-party endpoints — there is no third-party intermediary:

* **Public info API** (`POST https://api.hyperliquid.xyz/info`): market metadata and live asset context (`metaAndAssetCtxs`, `spotMetaAndAssetCtxs`), candles (`candleSnapshot`), L2 books (`l2Book`, `allMids`), funding history (`fundingHistory`), wallet positions (`clearinghouseState`, `spotClearinghouseState`), and wallet fills (`userFills`, `userFillsByTime`). This is the same API the Hyperliquid front end uses. No API key is needed; positions and fills are public on-chain data for any address.
* **Stats leaderboard endpoint** (`stats-data.hyperliquid.xyz`): the full \~40,000-wallet performance dataset behind the official app's leaderboard page, refreshed periodically upstream. Used only by `screenHyperliquidWallets()`; downloaded once and cached in-process for 10 minutes.

## Ticker Convention

Hyperliquid tickers use the `H:` namespace prefix, consistent with other Scalar Field asset classes (`X:` crypto, `I:` indices, `J:` Jupiter, `C:` forex):

| Ticker        | Market                   |
| ------------- | ------------------------ |
| `H:BTC`       | BTC perpetual            |
| `H:ETH`       | ETH perpetual            |
| `H:PURR/USDC` | PURR/USDC spot pair      |
| `H:@142`      | Spot pair by internal id |

All coin values returned by these functions carry the `H:` prefix, so outputs can be passed directly back as inputs. Bare API ids (`'BTC'`) are also accepted.

<Note>Hyperliquid is a tradable venue on Scalar Field: perps (long/short) and spot pairs execute through `venue.trade()` or `strategy.execute()`. See [Trading on Hyperliquid](/trading/venues/hyperliquid) for order semantics, funding, and connection steps.</Note>

# Querying the Data

## `screenHyperliquidMarkets()`

Discover and filter Hyperliquid markets with live prices, 24h volume, open interest, and current funding — the whole perp and/or spot universe in one call.

**Strategy angle:** this is the universe-selection step of almost any strategy. A momentum strategy screens for the biggest 24h movers with sufficient volume; a funding-carry strategy sorts by `funding_rate` to find perps paying the most to shorts; a market-making study filters by `volume_24h_usd` and `open_interest` to find liquid books worth quoting.

```python theme={null}
from scalarlib import screenHyperliquidMarkets

# Top perps by 24h volume
df = screenHyperliquidMarkets()

# Find BTC markets across perps and spot
df = screenHyperliquidMarkets(market_type='all', query='BTC')

# Funding-carry candidates: liquid perps with extreme funding
df = screenHyperliquidMarkets(min_volume=1_000_000, sort_by='funding_rate')

# Momentum candidates: biggest 24h movers
df = screenHyperliquidMarkets(sort_by='change_24h', limit=20)

# Feed a coin into the other functions
coin = df.iloc[0]['coin']
data = getHyperliquidOHLCV(coins=[coin], start='2026-01-01')
```

### Parameters

| Parameter           | Type  | Required | Description                                                                            |
| ------------------- | ----- | -------- | -------------------------------------------------------------------------------------- |
| `market_type`       | str   | No       | `'perp'` (default), `'spot'`, or `'all'`.                                              |
| `query`             | str   | No       | Case-insensitive substring match on coin id and name (e.g. `'BTC'`, `'sol'`).          |
| `min_volume`        | float | No       | Minimum 24h notional volume in USD.                                                    |
| `min_open_interest` | float | No       | Minimum open interest in base units (perps only).                                      |
| `sort_by`           | str   | No       | `'volume'` (default), `'open_interest'`, `'change_24h'`, `'funding_rate'`. Descending. |
| `limit`             | int   | No       | Maximum results (default 50).                                                          |
| `offset`            | int   | No       | Pagination offset (default 0).                                                         |

### Return Schema

| Column           | Type   | Description                                                  |
| ---------------- | ------ | ------------------------------------------------------------ |
| `coin`           | string | Canonical `H:`-prefixed ticker — pass to all other functions |
| `name`           | string | Human-readable name (resolved `BASE/QUOTE` for spot)         |
| `market_type`    | string | `'perp'` or `'spot'`                                         |
| `mark_price`     | float  | Mark price                                                   |
| `mid_price`      | float  | Mid price                                                    |
| `oracle_price`   | float  | Oracle price (NaN for spot)                                  |
| `funding_rate`   | float  | Current hourly funding rate (NaN for spot)                   |
| `open_interest`  | float  | Open interest in base units (NaN for spot)                   |
| `volume_24h_usd` | float  | 24h notional volume (USD)                                    |
| `prev_day_price` | float  | Mark price 24h ago                                           |
| `change_24h_pct` | float  | Percent change vs 24h ago                                    |
| `max_leverage`   | int    | Maximum leverage (NaN for spot)                              |
| `sz_decimals`    | int    | Size precision decimals                                      |

***

## `getHyperliquidOHLCV()`

OHLCV candles for perp or spot coins, from 1-minute up to monthly bars. Sourced from the public `candleSnapshot` endpoint; the API returns at most the most recent \~5,000 candles per coin per request. Omit `start` and `end` for live mode (latest bar).

**Strategy angle:** the backbone of any systematic approach — backtest a moving-average crossover on daily bars, compute realized volatility for position sizing, or detect intraday breakouts on 5-minute candles. `num_trades` per bar is a useful activity filter that plain OHLCV feeds don't give you: a price move on 10 trades means something different than the same move on 10,000.

```python theme={null}
from scalarlib import getHyperliquidOHLCV

# Daily bars for BTC perp
data = getHyperliquidOHLCV(coins=['H:BTC'], start='2026-01-01', end='2026-02-01')
df = data['H:BTC']

# Hourly bars (inferred from datetime format)
data = getHyperliquidOHLCV(coins=['H:BTC', 'H:ETH'],
                           start='2026-02-01T09:00:00', end='2026-02-01T18:00:00')

# 5-minute bars with explicit timeframe
data = getHyperliquidOHLCV(coins=['H:SOL'], start='2026-02-01', end='2026-02-02', timeframe='5min')

# Live mode — latest bar for each coin
data = getHyperliquidOHLCV(coins=['H:BTC', 'H:ETH'])
```

### Parameters

| Parameter   | Type        | Required | Description                                                                                                                                                                                                         |
| ----------- | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `coins`     | list of str | Yes      | `H:`-prefixed tickers from `screenHyperliquidMarkets()`. Bare ids accepted.                                                                                                                                         |
| `start`     | str         | No       | `"YYYY-MM-DD"` or `"YYYY-MM-DDTHH:MM:SS"` (New York time). Omit for live mode.                                                                                                                                      |
| `end`       | str         | No       | Same format as `start`. Date-only expands to end of day. Defaults to now.                                                                                                                                           |
| `timeframe` | str         | No       | `'day'`, `'hour'`, `'1min'`–`'30min'`, or native intervals `'1m'`, `'3m'`, `'5m'`, `'15m'`, `'30m'`, `'1h'`, `'2h'`, `'4h'`, `'8h'`, `'12h'`, `'1d'`, `'3d'`, `'1w'`, `'1M'`. Inferred from date format if omitted. |

### Return Schema

Returns `Dict[str, pd.DataFrame]` keyed by coin. Each DataFrame:

| Column       | Type                        | Description                        |
| ------------ | --------------------------- | ---------------------------------- |
| `ts_recv`    | datetime64\[ns, US/Eastern] | Bar open timestamp (New York time) |
| `ticker`     | string                      | Canonical `H:`-prefixed ticker     |
| `open`       | float                       | Opening price (USD)                |
| `high`       | float                       | High price                         |
| `low`        | float                       | Low price                          |
| `close`      | float                       | Closing price                      |
| `volume`     | float                       | Volume in base units               |
| `num_trades` | int                         | Number of trades in the bar        |

***

## `getHyperliquidPriceAndBook()`

Live mid price and aggregated L2 order book per coin. Mid prices for all coins come from one `allMids` call; books from the `l2Book` endpoint.

**Strategy angle:** the pre-trade sanity check. Before a strategy sizes an entry, walk the book to estimate slippage for your intended notional; a signal that looks great on close prices can be uneconomic once you account for a thin book. Book imbalance (bid depth vs ask depth) is also a short-horizon signal in its own right.

```python theme={null}
from scalarlib import getHyperliquidPriceAndBook

data = getHyperliquidPriceAndBook(coins=['H:BTC'])
info = data['H:BTC']

info['mid_price']                  # 63909.5
info['asks'].iloc[0]['price']      # best ask
info['bids'].iloc[0]['price']      # best bid

# Estimate slippage for a $500k buy by walking the ask side
asks = info['asks']
asks['notional'] = asks['price'] * asks['size']
asks['cum_notional'] = asks['notional'].cumsum()
```

### Parameters

| Parameter    | Type        | Required | Description                                                               |
| ------------ | ----------- | -------- | ------------------------------------------------------------------------- |
| `coins`      | list of str | Yes      | `H:`-prefixed tickers. Bare ids accepted.                                 |
| `book_depth` | int         | No       | Price levels per side (default 10). `None` = full book (up to 20 levels). |

### Return Schema

Returns `Dict[str, dict]` keyed by coin:

| Field       | Type         | Description                                            |
| ----------- | ------------ | ------------------------------------------------------ |
| `mid_price` | float        | Current mid price                                      |
| `ts`        | datetime     | Book snapshot timestamp (New York time, naive)         |
| `bids`      | pd.DataFrame | Columns `price`, `size`, `num_orders` — best bid first |
| `asks`      | pd.DataFrame | Columns `price`, `size`, `num_orders` — best ask first |

***

## `getHyperliquidFunding()`

Historical hourly funding rates for perps, from the `fundingHistory` endpoint. Rates are decimal hourly rates (e.g. `0.0000125` = 0.00125% per hour); funding on Hyperliquid accrues every hour.

**Strategy angle:** funding is both a carry source and a sentiment gauge. A **funding-carry strategy** shorts perps with persistently positive funding (longs pay shorts) while holding spot elsewhere, collecting the rate with limited price exposure. As a **contrarian signal**, extreme funding marks crowded positioning — spikes in positive funding often precede long squeezes. The `premium` column (mark vs oracle) tells you how stretched the perp is against its reference price.

```python theme={null}
from scalarlib import getHyperliquidFunding

# Last 7 days of BTC funding (default window)
df = getHyperliquidFunding(coins=['H:BTC'])

# Funding for multiple coins over a window
df = getHyperliquidFunding(coins=['H:BTC', 'H:ETH'], start='2026-06-01', end='2026-07-01')

# Annualized carry estimate from average hourly funding
df.groupby('coin')['funding_rate'].mean() * 24 * 365
```

### Parameters

| Parameter | Type        | Required | Description                                                                        |
| --------- | ----------- | -------- | ---------------------------------------------------------------------------------- |
| `coins`   | list of str | Yes      | `H:`-prefixed perp tickers. Spot markets have no funding.                          |
| `start`   | str         | No       | `"YYYY-MM-DD"` or `"YYYY-MM-DDTHH:MM:SS"` (New York time). Defaults to 7 days ago. |
| `end`     | str         | No       | Same format. Date-only expands to end of day. Defaults to now.                     |

### Return Schema

| Column         | Type                        | Description                        |
| -------------- | --------------------------- | ---------------------------------- |
| `ts_recv`      | datetime64\[ns, US/Eastern] | Funding timestamp                  |
| `coin`         | string                      | Canonical `H:`-prefixed ticker     |
| `funding_rate` | float                       | Hourly funding rate (decimal)      |
| `premium`      | float                       | Mark vs oracle premium at the time |

***

## `getHyperliquidPositions()`

Open perp positions and spot balances for **any** wallet — positions on Hyperliquid are public on-chain data, so no authentication is needed. Combines the perp clearinghouse state and spot balance state in one DataFrame.

**Strategy angle:** the core of a whale-watching or copy-trading strategy. Take wallets from `screenHyperliquidWallets()`, snapshot their positions on a schedule, and trade on changes: a top-decile trader flipping from long to short ETH is a signal you cannot get from price data alone. `liquidation_price` across many large wallets also lets you map where forced selling would cascade.

```python theme={null}
from scalarlib import getHyperliquidPositions

df = getHyperliquidPositions(wallet='0x6e6f...')

# Perp positions only
perps = df[df['position_type'] == 'perp']

# Net unrealized PnL and short exposure
perps['unrealized_pnl'].sum()
shorts = perps[perps['size'] < 0]
```

### Parameters

| Parameter | Type | Required | Description                                     |
| --------- | ---- | -------- | ----------------------------------------------- |
| `wallet`  | str  | Yes      | Wallet address, 0x-prefixed. Any address works. |

### Return Schema

One row per open perp position or nonzero spot balance:

| Column               | Type   | Description                                                         |
| -------------------- | ------ | ------------------------------------------------------------------- |
| `wallet`             | string | Queried wallet address                                              |
| `position_type`      | string | `'perp'` or `'spot'`                                                |
| `coin`               | string | Canonical `H:`-prefixed ticker                                      |
| `size`               | float  | Position size (negative = short for perps; token balance for spot)  |
| `entry_price`        | float  | Average entry price (perp only)                                     |
| `position_value`     | float  | Current notional value (perp only)                                  |
| `unrealized_pnl`     | float  | Unrealized P\&L (perp only)                                         |
| `return_on_equity`   | float  | Return on equity (perp only)                                        |
| `liquidation_price`  | float  | Liquidation price (perp only)                                       |
| `margin_used`        | float  | Margin allocated (perp only)                                        |
| `leverage`           | float  | Leverage value (perp only)                                          |
| `leverage_type`      | string | `'cross'` or `'isolated'` (perp only)                               |
| `max_leverage`       | int    | Maximum allowed leverage (perp only)                                |
| `funding_since_open` | float  | Cumulative funding paid since open; negative = received (perp only) |
| `hold`               | float  | Amount locked in open orders (spot only)                            |
| `entry_notional`     | float  | USD cost basis (spot only)                                          |

***

## `getHyperliquidTrades()`

Complete fill history for any wallet, from the `userFills` / `userFillsByTime` endpoints. Without `start`/`end` the API returns the wallet's most recent \~2,000 fills; with a start time, up to 2,000 fills from that window.

**Strategy angle:** where copy-trading gets precise. Positions tell you *what* a trader holds; fills tell you *when and how* they built it — do they scale in, add on dips, cut losers fast? `closed_pnl` per fill lets you verify a wallet's edge trade by trade before you commit capital to mirroring it, and the `crossed` flag separates urgent taker flow from patient maker flow.

<Note>Hyperliquid has no public market-wide trade tape over REST, so trade queries are wallet-scoped only (unlike `getPolymarketTrades()`, which can filter by market).</Note>

```python theme={null}
from scalarlib import getHyperliquidTrades

# Recent fills for a wallet
df = getHyperliquidTrades(wallet='0x6e6f...')

# BTC fills since a date
df = getHyperliquidTrades(wallet='0x6e6f...', coin='H:BTC', start='2026-06-01')

# Realized PnL over a window — verify the edge before copying
df = getHyperliquidTrades(wallet='0x6e6f...', start='2026-06-01', end='2026-07-01')
df['closed_pnl'].sum()
```

### Parameters

| Parameter | Type | Required | Description                                                |
| --------- | ---- | -------- | ---------------------------------------------------------- |
| `wallet`  | str  | Yes      | Wallet address, 0x-prefixed.                               |
| `start`   | str  | No       | `"YYYY-MM-DD"` or `"YYYY-MM-DDTHH:MM:SS"` (New York time). |
| `end`     | str  | No       | Same format. Only applied when `start` is provided.        |
| `coin`    | str  | No       | Filter to a single coin (`'H:BTC'` or bare `'BTC'`).       |
| `side`    | str  | No       | `'BUY'` or `'SELL'`.                                       |
| `limit`   | int  | No       | Maximum rows, newest first (default 1,000).                |

### Return Schema

| Column       | Type                        | Description                                   |
| ------------ | --------------------------- | --------------------------------------------- |
| `ts_recv`    | datetime64\[ns, US/Eastern] | Fill timestamp                                |
| `coin`       | string                      | Canonical `H:`-prefixed ticker                |
| `side`       | string                      | `'BUY'` or `'SELL'`                           |
| `price`      | float                       | Fill price (USD)                              |
| `size`       | float                       | Fill size in base units                       |
| `usd_value`  | float                       | `price * size`                                |
| `direction`  | string                      | e.g. `'Open Long'`, `'Close Short'`, `'Buy'`  |
| `closed_pnl` | float                       | Realized P\&L from this fill                  |
| `fee`        | float                       | Fee paid (negative = rebate)                  |
| `crossed`    | bool                        | `True` if the fill crossed the spread (taker) |
| `tx_hash`    | string                      | L1 transaction hash                           |
| `order_id`   | int                         | Order ID                                      |

***

## `screenHyperliquidWallets()`

Rank the full \~40,000-wallet universe by PnL, ROI, volume, or account value over daily, weekly, monthly, or all-time windows. Data comes from Hyperliquid's stats leaderboard endpoint — the same source the official app's leaderboard uses. The dataset is downloaded once and cached in-process for 10 minutes, so the first call pays a multi-second download and subsequent calls are instant.

**Strategy angle:** the discovery step of a copy-trading pipeline. Screen for wallets with high ROI *and* meaningful account value (to filter out lucky dust accounts), then feed them into `getHyperliquidPositions()` and `getHyperliquidTrades()` to validate consistency before mirroring. Comparing week vs all-time rankings also separates traders on a hot streak from durable performers.

```python theme={null}
from scalarlib import screenHyperliquidWallets

# Top 10 wallets by all-time PnL
df = screenHyperliquidWallets(limit=10)

# Best ROI this week among accounts with > $100k
df = screenHyperliquidWallets(time_period='week', sort_by='roi', min_account_value=100000)

# Copy-trading pipeline: screen -> positions -> fills
wallet = df.iloc[0]['wallet']
positions = getHyperliquidPositions(wallet=wallet)
fills = getHyperliquidTrades(wallet=wallet)
```

### Parameters

| Parameter           | Type  | Required | Description                                                            |
| ------------------- | ----- | -------- | ---------------------------------------------------------------------- |
| `time_period`       | str   | No       | `'all'` (default), `'month'`, `'week'`, `'day'`.                       |
| `sort_by`           | str   | No       | `'pnl'` (default), `'roi'`, `'volume'`, `'account_value'`. Descending. |
| `min_value`         | float | No       | Minimum value of the `sort_by` metric.                                 |
| `max_value`         | float | No       | Maximum value of the `sort_by` metric.                                 |
| `min_account_value` | float | No       | Minimum current account value in USD (independent of `sort_by`).       |
| `limit`             | int   | No       | Maximum results (default 50).                                          |
| `offset`            | int   | No       | Pagination offset (default 0).                                         |

### Return Schema

| Column          | Type   | Description                                                     |
| --------------- | ------ | --------------------------------------------------------------- |
| `rank`          | int    | 1-based rank in the full leaderboard for the chosen sort/window |
| `wallet`        | string | 0x-prefixed address                                             |
| `account_value` | float  | Current account value (USD)                                     |
| `pnl`           | float  | P\&L over the selected window (USD)                             |
| `roi`           | float  | Return over the window (decimal, 0.05 = 5%)                     |
| `volume`        | float  | Notional volume over the window (USD)                           |
| `display_name`  | string | Public display name (`''` if unset)                             |

# Strategy Playbook

Concrete ways to combine these functions into a strategy:

* **Funding carry.** `screenHyperliquidMarkets(sort_by='funding_rate', min_volume=1_000_000)` to find perps with extreme funding, `getHyperliquidFunding()` to confirm the rate is persistent rather than a one-hour spike, `getHyperliquidPriceAndBook()` to verify the book can absorb your size. Harvest the hourly payment with a hedged position.
* **Copy-trading.** `screenHyperliquidWallets(sort_by='roi', min_account_value=100_000)` to shortlist traders, `getHyperliquidTrades()` to audit their realized PnL and style, then poll `getHyperliquidPositions()` on a schedule and mirror position changes.
* **Crowding fade.** Track funding and open interest together: rising OI plus rapidly rising positive funding means crowded longs. Use `getHyperliquidOHLCV()` to time the mean-reversion entry when momentum stalls.
* **Cross-venue signals.** Hyperliquid perp funding and whale positioning in `H:BTC`/`H:ETH` often lead sentiment in correlated assets — use them as inputs to strategies that execute in crypto OHLCV universes (`X:` tickers) or even Polymarket crypto markets.
