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

# Horizon + Hyperliquid

> Trade perpetual futures and spot on Hyperliquid's L1 chain with wallet-based auth.

<Note>
  **Partially verified.** As of v0.8.7+, the critical signing issues from the
  earlier audit (msgpack key ordering, cloid format, spot asset offset, error
  handling, cancel-by-cloid action type) are fixed. Order submission and cancel
  should now work end-to-end. Has not been tested against a live Hyperliquid
  account with real funds, so verify the behavior matches expectations before
  deploying significant size.
</Note>

[Hyperliquid](https://hyperliquid.xyz) is a decentralized perpetual futures and spot exchange running on its own L1 chain. It offers deep liquidity, sub-second finality, and transparent on-chain order books. Horizon connects to Hyperliquid for perp/spot trading with wallet-based EIP-712 authentication.

## Quick Setup

```python theme={null}
hz.run(
    name="hl_perps",
    exchange=hz.Hyperliquid(private_key="0x..."),
    mode="live",
    ...
)
```

## Credentials

<Tabs>
  <Tab title="Explicit">
    ```python theme={null}
    hz.Hyperliquid(private_key="0xac0974bec39a...")
    ```
  </Tab>

  <Tab title="Environment variables">
    ```bash theme={null}
    export HYPERLIQUID_PRIVATE_KEY="0xac0974bec39a..."
    ```

    ```python theme={null}
    hz.Hyperliquid()  # reads from env
    ```
  </Tab>
</Tabs>

## Hyperliquid Configuration

```python theme={null}
@dataclass
class Hyperliquid:
    private_key: str | None = None
    testnet: bool = False
    api_url: str | None = None
    vault_address: str | None = None
```

| Field           | Default | Description                                                              |
| --------------- | ------- | ------------------------------------------------------------------------ |
| `private_key`   | `None`  | EVM private key, 0x-prefixed hex (env: `HYPERLIQUID_PRIVATE_KEY`)        |
| `testnet`       | `False` | Use testnet endpoint                                                     |
| `api_url`       | auto    | Override API URL (auto-selects mainnet/testnet)                          |
| `vault_address` | `None`  | Vault address for sub-account trading (env: `HYPERLIQUID_VAULT_ADDRESS`) |

## Authentication

Hyperliquid uses **EIP-712 wallet signing** — no API key/secret needed, just a private key. Every write operation is signed with the wallet's secp256k1 key using a Hyperliquid-specific EIP-712 domain:

* **Domain**: `{name: "Exchange", version: "1", chainId: 1337, verifyingContract: 0x0}`
* **Type**: `Agent(address source, bytes32 connectionId)`
* **Source**: `keccak256("a")` (mainnet) or `keccak256("b")` (testnet)

Only two REST endpoints are used:

* `POST /info` — all read operations (metadata, fills, positions, prices)
* `POST /exchange` — all write operations (orders, cancels) with EIP-712 signature

## Symbol Mapping

Hyperliquid identifies assets by integer indices, not ticker symbols. The SDK resolves symbols automatically via metadata on first use:

| Asset Type | Index Range | Examples            |
| ---------- | ----------- | ------------------- |
| Perpetuals | 0–9999      | BTC=0, ETH=1, SOL=2 |
| Spot       | ≥10000      | Spot tokens         |

```python theme={null}
# Use standard ticker symbols — SDK resolves to indices
market = hz.Market(id="BTC", name="Bitcoin Perpetual")
market = hz.Market(id="ETH", name="Ethereum Perpetual")
```

| Horizon Field             | Hyperliquid Field | Notes                              |
| ------------------------- | ----------------- | ---------------------------------- |
| `OrderRequest.market_id`  | `coin`            | Resolved to asset index internally |
| `OrderRequest.order_side` | `is_buy`          | `true` for buy, `false` for sell   |
| `OrderRequest.price`      | `limit_px`        | Sent as string with 5 sig figs     |
| `OrderRequest.size`       | `sz`              | Sent as string with 5 sig figs     |

## Market Orders

Hyperliquid has no native market order type. The SDK implements market orders as **aggressive limit IOC** with 5% slippage:

1. Fetch current mid price via `allMids`
2. Place limit IOC at `mid × 1.05` (buy) or `mid × 0.95` (sell)
3. Unfilled portion is immediately canceled (IOC behavior)

<Note>
  Hyperliquid uses `Side.Long` for all positions — perps and spot. Prediction market concepts like `Side.Yes` / `Side.No` do not apply.
</Note>

## Vault Trading

For sub-account (vault) trading, specify a vault address:

```python theme={null}
hz.Hyperliquid(
    private_key="0x...",
    vault_address="0xabcdef...",
)
```

The vault address is included in the EIP-712 signing payload and sent with every request.

## Testnet

```python theme={null}
hz.Hyperliquid(testnet=True)
```

Uses `https://api.hyperliquid-testnet.xyz` automatically. Get testnet funds from the [Hyperliquid testnet faucet](https://app.hyperliquid-testnet.xyz).

## Multi-Exchange

Use Hyperliquid alongside other exchanges:

```python theme={null}
hz.run(
    name="cross_venue",
    exchanges=[
        hz.Hyperliquid(),       # perps
        hz.Coinbase(),          # spot hedge
        hz.Polymarket(),        # prediction markets
    ],
    mode="live",
    ...
)
```

## Getting Started

1. Generate or use an existing EVM private key
2. Fund your Hyperliquid account by depositing USDC via the [Hyperliquid bridge](https://app.hyperliquid.xyz)
3. Set the environment variable or pass directly:
   ```bash theme={null}
   export HYPERLIQUID_PRIVATE_KEY="0x..."
   ```
4. Start trading:
   ```python theme={null}
   hz.run(
       name="my_strategy",
       exchange=hz.Hyperliquid(),
       markets=["BTC", "ETH"],
       mode="live",
       pipeline=[my_pipeline],
   )
   ```
