# Export Hyperliquid OHLCV Candles to CSV or Parquet

If you just want the full archive as one file without building a fetcher, use the managed [Hyperliquid OHLCV Full-History Exports](https://www.dwellir.com/docs/hyperliquid/hyperliquid-index/ohlcv-data/full-history-exports) — download a gzipped CSV for any market and interval directly from the Dwellir dashboard. This guide is for teams that want to control the fetch loop, market selection, and storage layout themselves.

This guide builds a CSV exporter for Dwellir's Hyperliquid OHLCV API, then shows the changes to write Parquet instead. It supports two paths:

- export one market and one interval, such as `BTC` `1m`
- discover all currently listed Hyperliquid markets and export one interval for each market into one CSV

The exporter uses the paginated [`/v1/candles/range`](https://www.dwellir.com/docs/hyperliquid/hyperliquid-index/ohlcv-data/candle-ranges) endpoint instead of requesting one bucket at a time. Range pages return sparse finalized candles only, so empty buckets are skipped by the API and do not need special handling in the script.

## Copy-Paste Prompt for Your Coding Tool

Paste this into Claude Code, Codex, Cursor, Windsurf, or another coding agent:

```text
Build me a Python script that exports Hyperliquid OHLCV candles from Dwellir into CSV.

Requirements:
- First check whether the `dwellir` CLI is installed.
- If it is not installed, recommend installing it with one of these options:
  - `brew tap dwellir-public/homebrew-tap && brew install dwellir`
  - `curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh`
- Ask me to authenticate with `dwellir auth login`.
- Check authentication with `dwellir auth status`.
- Get an enabled API key name with `dwellir keys list --toon`. The CLI shows keys masked.
- Write that key to `.env` with `dwellir keys env <name>`. Never print the key.
- Use `dwellir endpoints search hyperliquid --ecosystem hyperliquid --network mainnet --json` to discover both:
  - `Hyperliquid Index` for OHLCV range requests
  - `Hyperliquid HyperCore Info` for market discovery
- The endpoint URLs contain a `<key>` placeholder. At runtime, replace it with `DWELLIR_API_KEY` from the environment or from `.env`.
- Support `--market BTC` for one market.
- Support `--all-markets` for all markets discovered from Info endpoint calls:
  - `{"type":"meta"}` for currently listed native perp names
  - `{"type":"spotMeta"}` for spot symbols, using canonical names such as `PURR/USDC` and `@INDEX` names for non-canonical pairs
  - `{"type":"perpDexs"}` for HIP-3 `prefix:ASSET` symbols
- Support `--max-markets` for short smoke tests before a full all-markets run.
- Use `GET /v1/candles/range` with `limit=5000`, follow `nextCursor`, and keep `end` exclusive.
- Support `1s`, `1m`, and `5m`.
- Write CSV columns: s, i, t, T, o, h, l, c, v, q, n, x.
- Show me how to run a one-market export and an all-markets export for one interval.
```

## What You Will Learn

- discover the Dwellir Hyperliquid Index and Info endpoint URLs with the CLI
- export a sparse candle range for one market with cursor pagination
- discover native perp, spot, and HIP-3 market symbols from the Info endpoint
- iterate all discovered markets for one interval and append them to one CSV
- verify the exported CSV before loading it into downstream tooling
- write the same export to Parquet with a streaming PyArrow writer

## Prerequisites

Install Python `3.10+` and `requests`:

```bash
python --version
pip install requests
```

Install and authenticate the Dwellir CLI:

```bash
brew tap dwellir-public/homebrew-tap
brew install dwellir
dwellir auth login
dwellir auth status
dwellir keys list --toon
dwellir keys env YOUR_KEY_NAME
```

Replace `YOUR_KEY_NAME` with an enabled key name from `dwellir keys list --toon`. `dwellir keys env` writes the key to `.env` as `DWELLIR_API_KEY` without printing it. The script reads the key from the `DWELLIR_API_KEY` environment variable or from `.env` in the working directory. These commands need Dwellir CLI 0.3.0 or later.

## How the Export Works

The OHLCV range endpoint returns pages of candle objects:

```text
GET https://api-hyperliquid-index.n.dwellir.com/<key>/v1/candles/range
```

Each request includes:

- `market`, for example `BTC`, `@142`, or `hyna:ETH`
- `interval`, one of `1s`, `1m`, or `5m`
- `start`, the inclusive lower bound
- `end`, the exclusive upper bound
- `limit=5000`
- `cursor`, only after the first page when `hasMore` is `true`

For all-market exports, we first discover symbols from Dwellir's HyperCore Info endpoint:

| Market type    | Info request          | Symbol format                                                                     |
| -------------- | --------------------- | --------------------------------------------------------------------------------- |
| Native perps   | `{"type":"meta"}`     | listed `name`, for example `BTC`                                                  |
| Spot           | `{"type":"spotMeta"}` | canonical `name`, for example `PURR/USDC`, otherwise `@INDEX`, for example `@142` |
| HIP-3 perpDexs | `{"type":"perpDexs"}` | first element of `assetToStreamingOiCap`, for example `hyna:ETH`                  |

**Important:** the Info endpoint discovers currently listed markets. Historical OHLCV can include markets that are no longer listed; use the dashboard export catalog when you need Dwellir's full indexed catalog including retired symbols.

## Python Export Script

Save this as `export_ohlcv_csv.py`:

```python
import argparse
import csv
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any

import requests

FIELDS = ["s", "i", "t", "T", "o", "h", "l", "c", "v", "q", "n", "x"]
VALID_INTERVALS = {"1s", "1m", "5m"}

def load_endpoint_catalog() -> dict[str, Any]:
    try:
        raw = subprocess.check_output(
            [
                "dwellir",
                "endpoints",
                "search",
                "hyperliquid",
                "--ecosystem",
                "hyperliquid",
                "--network",
                "mainnet",
                "--json",
            ],
            text=True,
        )
    except FileNotFoundError as exc:
        raise SystemExit("Install the dwellir CLI first, then run `dwellir auth login`.") from exc
    return json.loads(raw)

def load_api_key(env_file: str = ".env") -> str:
    key = os.environ.get("DWELLIR_API_KEY")
    if key:
        return key
    path = Path(env_file)
    if path.is_file():
        for line in path.read_text(encoding="utf-8").splitlines():
            name, _, value = line.partition("=")
            if name.strip() == "DWELLIR_API_KEY":
                return value.strip().strip("'\"")
    raise SystemExit("Run `dwellir keys env YOUR_KEY_NAME` to write DWELLIR_API_KEY to .env.")

def endpoint_url(catalog: dict[str, Any], endpoint_name: str, api_key: str) -> str:
    for item in catalog.get("data", []):
        if item.get("name") == endpoint_name:
            return item["networks"][0]["nodes"][0]["https"].replace("<key>", api_key)
    raise RuntimeError(f"Could not find endpoint named {endpoint_name!r}")

def post_info(session: requests.Session, info_url: str, payload: dict[str, Any]) -> Any:
    response = session.post(info_url, json=payload, timeout=30)
    response.raise_for_status()
    return response.json()

def discover_markets(session: requests.Session, info_url: str) -> list[str]:
    meta = post_info(session, info_url, {"type": "meta"})
    spot_meta = post_info(session, info_url, {"type": "spotMeta"})
    perp_dexs = post_info(session, info_url, {"type": "perpDexs"})

    perps = [
        asset["name"]
        for asset in meta.get("universe", [])
        if isinstance(asset, dict) and asset.get("name") and not asset.get("isDelisted")
    ]
    spots = [
        pair["name"] if pair.get("isCanonical") else f"@{pair['index']}"
        for pair in spot_meta.get("universe", [])
        if isinstance(pair, dict) and pair.get("name") and "index" in pair
    ]

    hip3 = []
    dex_items = perp_dexs if isinstance(perp_dexs, list) else perp_dexs.get("dexs", [])
    for dex in dex_items:
        if not isinstance(dex, dict):
            continue
        for pair in dex.get("assetToStreamingOiCap", []) or []:
            if isinstance(pair, list) and pair:
                hip3.append(pair[0])

    markets = []
    seen = set()
    for market in perps + spots + hip3:
        if market not in seen:
            seen.add(market)
            markets.append(market)
    return markets

def candle_pages(
    session: requests.Session,
    index_base_url: str,
    market: str,
    interval: str,
    start: str | None,
    end: str | None,
):
    cursor = None
    while True:
        params = {"market": market, "interval": interval, "limit": "5000"}
        if cursor:
            params["cursor"] = cursor
        elif start:
            params["start"] = start
        if end:
            params["end"] = end

        response = session.get(
            f"{index_base_url}/v1/candles/range",
            params=params,
            timeout=60,
        )
        response.raise_for_status()
        page = response.json()
        rows = page.get("data", [])
        if rows:
            yield rows
        if not page.get("hasMore"):
            break
        cursor = page["nextCursor"]

def export_csv(args: argparse.Namespace) -> int:
    if args.interval not in VALID_INTERVALS:
        raise SystemExit(f"Unsupported interval: {args.interval}")
    if bool(args.market) == bool(args.all_markets):
        raise SystemExit("Pass exactly one of --market or --all-markets")

    api_key = load_api_key()
    catalog = load_endpoint_catalog()
    index_base_url = endpoint_url(catalog, "Hyperliquid Index", api_key)
    info_url = endpoint_url(catalog, "Hyperliquid HyperCore Info", api_key)

    session = requests.Session()
    markets = [args.market] if args.market else discover_markets(session, info_url)
    if args.max_markets is not None:
        markets = markets[: args.max_markets]
    written = 0

    with open(args.output, "w", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        for index, market in enumerate(markets, start=1):
            print(f"exporting {market} ({index}/{len(markets)})", file=sys.stderr)
            for rows in candle_pages(session, index_base_url, market, args.interval, args.start, args.end):
                writer.writerows(rows)
                written += len(rows)

    print(f"wrote {written} candles for {len(markets)} market(s) to {args.output}")
    return 0

def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--market", help="One market symbol, for example BTC, @142, or hyna:ETH")
    parser.add_argument("--all-markets", action="store_true", help="Discover and export all currently listed markets")
    parser.add_argument("--max-markets", type=int, help="Limit discovered markets for smoke tests")
    parser.add_argument("--interval", required=True, choices=sorted(VALID_INTERVALS))
    parser.add_argument("--start", help="Inclusive ISO-8601 UTC start, for example 2026-03-01T00:00:00Z")
    parser.add_argument("--end", help="Exclusive ISO-8601 UTC end, for example 2026-04-01T00:00:00Z")
    parser.add_argument("--output", required=True)
    return export_csv(parser.parse_args())

if __name__ == "__main__":
    raise SystemExit(main())
```

## Run a Single-Market Export

Export BTC `1m` candles for March 2026:

```bash
python export_ohlcv_csv.py \
  --market BTC \
  --interval 1m \
  --start 2026-03-01T00:00:00Z \
  --end 2026-04-01T00:00:00Z \
  --output btc-1m-march-2026.csv
```

## Run an All-Markets Export

Start with a short validation window:

```bash
python export_ohlcv_csv.py \
  --all-markets \
  --interval 1m \
  --max-markets 10 \
  --start 2025-07-27T08:50:00Z \
  --end 2025-07-27T08:51:00Z \
  --output hyperliquid-all-1m-smoke.csv
```

Then run the full interval export. Omit `--end` to read through the latest completed bucket:

```bash
python export_ohlcv_csv.py \
  --all-markets \
  --interval 1m \
  --start 2025-07-27T08:00:00Z \
  --output hyperliquid-all-1m.csv
```

This can return tens of millions of billable candle objects for `1m`, and substantially more for `1s`. Use your plan limits and expected billing weight when sizing a full-universe run.

## Verify the Result

Inspect the first rows:

```bash
head -5 hyperliquid-all-1m-smoke.csv
```

Load it with DuckDB:

```sql
SELECT s, i, count(*) AS rows, min(t) AS first_open, max(t) AS last_open
FROM read_csv_auto('hyperliquid-all-1m.csv')
GROUP BY s, i
ORDER BY rows DESC
LIMIT 10;
```

## Write Parquet Instead of CSV

Parquet is columnar and compressed, so it suits large all-markets exports that you query with DuckDB, Polars or Spark. The fetch loop stays the same. Only the writer changes.

Install `pyarrow` next to `requests`:

```bash
pip install requests pyarrow
```

In `export_ohlcv_csv.py`, replace `import csv` and `FIELDS` with a fixed schema:

```python
import pyarrow as pa
import pyarrow.parquet as pq

SCHEMA = pa.schema(
    [
        ("s", pa.string()),
        ("i", pa.string()),
        ("t", pa.int64()),
        ("T", pa.int64()),
        ("o", pa.string()),
        ("h", pa.string()),
        ("l", pa.string()),
        ("c", pa.string()),
        ("v", pa.string()),
        ("q", pa.string()),
        ("n", pa.int64()),
        ("x", pa.bool_()),
    ]
)
```

Then replace the `with open(...)` block in `export_csv` with a streaming `ParquetWriter`. Each API page is written as it arrives, so memory stays bounded when an all-markets run returns millions of candles:

```python
    writer = pq.ParquetWriter(args.output, SCHEMA, compression="zstd")
    try:
        for index, market in enumerate(markets, start=1):
            print(f"exporting {market} ({index}/{len(markets)})", file=sys.stderr)
            for rows in candle_pages(session, index_base_url, market, args.interval, args.start, args.end):
                writer.write_table(pa.Table.from_pylist(rows, schema=SCHEMA))
                written += len(rows)
        if written == 0:
            writer.write_table(pa.Table.from_pylist([], schema=SCHEMA))
    finally:
        writer.close()
```

Run it with the same flags and a `.parquet` output path:

```bash
python export_ohlcv_csv.py \
  --all-markets \
  --interval 1m \
  --max-markets 10 \
  --start 2025-07-27T08:50:00Z \
  --end 2025-07-27T08:51:00Z \
  --output hyperliquid-all-1m-smoke.parquet
```

Check the schema with PyArrow, then query the file with DuckDB:

```python
import pyarrow.parquet as pq

table = pq.read_table("hyperliquid-all-1m-smoke.parquet")
print(table.schema)
print(table.num_rows)
```

```sql
SELECT s, i, count(*) AS rows, min(t) AS first_open, max(t) AS last_open
FROM read_parquet('hyperliquid-all-1m.parquet')
GROUP BY s, i
ORDER BY rows DESC
LIMIT 10;
```

The schema keeps the abbreviated field names from the REST payload. Prices and volumes stay decimal strings, so downstream tools do not lose precision. For very large exports, write one Parquet file per market, or partition by `interval` and `market`, so a retry only redoes one file.

## Production Notes

- Keep `start`, `end`, and `cursor` aligned to the requested interval.
- Store progress per market if you are running a full-history all-markets export. The compact script above is intentionally simple and writes one pass.
- Retry transient `429` and `5xx` responses with exponential backoff before restarting a large job.
- The range API bills by returned candle objects, not by empty sparse buckets or by HTTP page count.
- For a resumable, multi-process pull of the full archive, use [Backfill the Full Hyperliquid OHLCV Archive](https://www.dwellir.com/guides/hyperliquid-ohlcv-archive-backfill).
