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

# Trading HIP-4 outcome markets on Hyperliquid

> Build Python code for trading HIP-4 outcome and prediction markets on Hyperliquid: asset encoding, settlement formula, fees, and SDK patching.

HIP-4 introduces outcome markets to Hyperliquid — fully collateralized binary contracts that settle within a fixed range. They are a general-purpose primitive for prediction markets and bounded options-like instruments. HIP-4 launched on mainnet on May 2, 2026 with a recurring BTC daily binary. Mainnet now also lists recurring markets on other assets and markets that third-party deployers create from validator-approved templates.

> [!NOTE]
>
> **Prerequisites**
>
> * Python 3.10 or higher
> * `hyperliquid-python-sdk` and `httpx` installed (`pip install hyperliquid-python-sdk httpx`)
> * [Reliable Hyperliquid RPC endpoint](https://chainstack.com/build-better-with-hyperliquid/) ([sign up for free](https://console.chainstack.com/))
> * A funded testnet or mainnet wallet with **USDC** — outcome markets quote and settle in USDC, as the `quoteToken` field in `outcomeMeta` shows.

## What HIP-4 outcome markets are

An outcome market is a fully collateralized binary contract priced as a probability between 0 and 1. At expiry, the contract settles to either YES (1) or NO (0) based on a deterministic rule. Each side is held as a native HyperCore asset — there are no ERC-20 wrappers, no Gnosis Conditional Tokens, and no separate matching layer.

Outcomes share the matching engine, account model, and API surface with spot and perpetuals. Once you handle the asset encoding correctly, every existing tool works — order placement, cancels, modifies, fills, the websocket. There is no leverage and no liquidation. Positions are fully collateralized at open.

Mainnet lists two kinds of outcome markets:

* Recurring markets — the protocol deploys and settles them on a fixed cadence. They include daily binaries on BTC, ETH, SOL, and HYPE that settle at 06:00 UTC against the HyperCore mark price, and a daily BTC price-bucket question.
* Deployer markets — HIP-4 deployers create them from templates that validators vote on, such as price targets, sports results, company events, and policy-rate decisions. Each deployer publishes under its own venue name.

A *question* groups several outcomes, of which exactly one settles to YES and all others settle to NO.

## Why the standard Python SDK won't work

The official `hyperliquid-python-sdk` (v0.24.0, the latest release) does not know about HIP-4. The `Info` client builds its `coin_to_asset` map from `spot_meta` only — outcome encodings starting at `100_000_000` are unknown to the resolver.

A naive call fails:

```python theme={"system"}
from hyperliquid.info import Info

info = Info("https://api.hyperliquid.xyz", skip_ws=True)
info.l2_snapshot("#10")  # KeyError: '#10' — coin not registered
```

The fix is small but necessary: fetch `outcomeMeta`, compute the asset id and coin string for every live outcome, and inject those entries into the SDK's resolver maps. After that, `Exchange.order(coin="#10", ...)` and `Info.l2_snapshot("#10")` work as if HIP-4 were a native concept.

## Asset ID encoding

Outcomes share most implementation details with spot, but the API representation is different. The encoding is the single biggest source of bugs for new HIP-4 integrators.

For an outcome with id `outcome` and side `side` (only `0` and `1` are valid):

```
encoding = 10 * outcome + side
```

Side `0` is YES and side `1` is NO, matching the order of `sideSpecs` in `outcomeMeta`. The same `encoding` integer is used in **three different string forms**, each in a different context:

| Form | Used in | Example: outcome 1, side 0 (YES) |
| - | - | - |
| `#<encoding>` (outcome spot coin) | `/info` `l2Book`, `Exchange.order(...)`, websocket subscriptions | `#10` |
| `+<encoding>` (outcome token name) | `spotClearinghouseState` balances | `+10` |
| `100_000_000 + encoding` (outcome asset id) | Internal asset references where an integer is needed | `100_000_010` |

> [!WARNING]
>
> **Two coin strings exist for the same side asset.** The `#` form is what `/info` [`l2Book`](https://docs.chainstack.com/reference/hyperliquid-info-l2-book) and `Exchange.order(...)` expect. The `+` form is what [`spotClearinghouseState`](https://docs.chainstack.com/reference/hyperliquid-info-spotclearinghousestate) returns under your account balances. Mixing them up will silently fail to find your position — `l2Book` with `+10` returns nothing, balance lookup with `#10` returns nothing.

A small encoding helper:

```python theme={"system"}
def encode_coin(outcome_id: int, side: int) -> str:
    """Coin string for l2Book and order placement."""
    if side not in (0, 1):
        raise ValueError(f"side must be 0 or 1, got {side}")
    return f"#{10 * outcome_id + side}"


def encode_balance_coin(outcome_id: int, side: int) -> str:
    """Coin string for spotClearinghouseState balances."""
    if side not in (0, 1):
        raise ValueError(f"side must be 0 or 1, got {side}")
    return f"+{10 * outcome_id + side}"


def encode_asset_id(outcome_id: int, side: int) -> int:
    if side not in (0, 1):
        raise ValueError(f"side must be 0 or 1, got {side}")
    return 100_000_000 + 10 * outcome_id + side
```

## Discovering markets with `outcomeMeta`

The `outcomeMeta` info request returns all live outcomes and questions. Point HIP-4 trading code at the official Hyperliquid public API — `https://api.hyperliquid.xyz` (mainnet) or `https://api.hyperliquid-testnet.xyz` (testnet) — which serves every method this guide uses, including `l2Book` and the `/exchange` actions that Chainstack-hosted endpoints do not serve. For HyperEVM operations and the `/info` methods your node supports, including `outcomeMeta` and `settledOutcome`, use your Chainstack endpoint. See [Hyperliquid methods](https://docs.chainstack.com/docs/hyperliquid-methods.md) for the full availability matrix.

```python theme={"system"}
import httpx

HYPERLIQUID_PUBLIC_URL = "https://api.hyperliquid.xyz"


def fetch_outcome_meta(base_url: str = HYPERLIQUID_PUBLIC_URL) -> dict:
    r = httpx.post(
        f"{base_url}/info",
        json={"type": "outcomeMeta"},
        timeout=10.0,
    )
    r.raise_for_status()
    return r.json()


data = fetch_outcome_meta()
for o in data["outcomes"]:
    print(f"outcome={o['outcome']} name={o['name']} desc={o['description']}")
for q in data.get("questions", []):
    print(f"question={q['question']} name={q['name']} legs={q['namedOutcomes']}")
```

A mainnet response, with each array shortened to one or two entries — a recurring BTC daily binary, a deployer market, and the recurring BTC price-bucket question:

```json theme={"system"}
{
  "outcomes": [
    {
      "outcome": 33246,
      "name": "Recurring",
      "description": "class:priceBinary|underlying:BTC|expiry:20261113-0600|targetPrice:73567|period:1d",
      "sideSpecs": [{"name": "Yes"}, {"name": "No"}],
      "quoteToken": "USDC"
    },
    {
      "outcome": 26822,
      "name": "template:binaryPrice",
      "description": "perp:BTC|priceDescription:the Pyth BTC/USD price|seconds:90|threshold:79000|time:20261113-0800",
      "sideSpecs": [{"name": "template:Yes"}, {"name": "template:No"}],
      "quoteToken": "USDC",
      "venue": "skew",
      "deployerFeeScale": "1.0"
    }
  ],
  "questions": [
    {
      "question": 634,
      "name": "Recurring",
      "description": "class:priceBucket|underlying:BTC|expiry:20261113-0600|priceThresholds:72095,75038|period:1d",
      "fallbackOutcome": 33250,
      "namedOutcomes": [33251, 33252, 33253],
      "settledNamedOutcomes": []
    }
  ],
  "deployers": [
    {
      "deployer": "0x08e9c89f46dccee91bdb85c6532eb93a4c335efe",
      "venue": "skew",
      "subDeployers": [["settleOutcome", ["0x1c867861e0cffb0eba07d9d94f716189c130dac6"]]]
    }
  ],
  "feeScale": 1.0
}
```

Outcome and question IDs change with every recurring instance — a new BTC daily binary gets a new `outcome` id each day — so discover them from `outcomeMeta` instead of hardcoding them.

The fields on each outcome:

* `name` — `Recurring` for protocol-deployed recurring markets, or `template:<template name>` for deployer markets.
* `description` — a pipe-separated list of `key:value` pairs. Recurring binaries use `class:priceBinary` with `underlying`, `expiry` (`YYYYMMDD-HHMM` UTC), `targetPrice`, and `period`. Deployer markets carry their template's keywords instead, for example `perp`, `threshold`, and `time`.
* `sideSpecs` — the side names, YES first.
* `quoteToken` — the token the market quotes and settles in.
* `venue` and `deployerFeeScale` — present on deployer markets; `venue` is the deployer's venue name.

Questions carry `namedOutcomes` (the outcomes that can settle to YES), a `fallbackOutcome`, and `settledNamedOutcomes`. The recurring BTC price-bucket question uses `class:priceBucket` with two `priceThresholds`. The top-level `deployers` array lists each deployer with its venue and sub-deployers.

> [!NOTE]
>
> `outcomeMeta` does not return the per-side coin strings or asset ids. You compute them client-side from `outcome` and `side` using the [asset ID encoding](#asset-id-encoding) formula.

A short parser for the recurring-binary description format, and a helper that finds the current instance of a recurring daily binary:

```python theme={"system"}
from dataclasses import dataclass


@dataclass
class RecurringSpec:
    cls: str
    underlying: str
    expiry: str
    target_price: float
    period: str


def parse_recurring_description(desc: str) -> RecurringSpec | None:
    if not desc.startswith("class:"):
        return None
    parts = dict(p.split(":", 1) for p in desc.split("|") if ":" in p)
    try:
        return RecurringSpec(
            cls=parts["class"],
            underlying=parts["underlying"],
            expiry=parts["expiry"],
            target_price=float(parts["targetPrice"]),
            period=parts["period"],
        )
    except KeyError:
        return None


def find_recurring_binary(data: dict, underlying: str = "BTC") -> int:
    """Outcome id of the live recurring daily binary for an underlying."""
    for o in data["outcomes"]:
        spec = parse_recurring_description(o["description"])
        if spec and spec.cls == "priceBinary" and spec.underlying == underlying:
            return o["outcome"]
    raise LookupError(f"no recurring {underlying} binary listed")
```

## Patching the SDK

Once you have the live outcomes, inject them into the SDK's resolver maps so the existing client methods accept HIP-4 coin strings:

```python theme={"system"}
from eth_account import Account
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info


def make_clients(
    private_key: str,
    address: str,
    base_url: str = HYPERLIQUID_PUBLIC_URL,
) -> tuple[Info, Exchange]:
    account = Account.from_key(private_key)
    info = Info(base_url, skip_ws=True)
    exchange = Exchange(account, base_url, account_address=address)

    data = fetch_outcome_meta(base_url)
    for o in data.get("outcomes", []):
        for side in (0, 1):
            coin = encode_coin(o["outcome"], side)
            asset_id = encode_asset_id(o["outcome"], side)
            # Skip if the SDK ever ships native HIP-4 support and these are present.
            if coin in info.coin_to_asset:
                continue
            info.coin_to_asset[coin] = asset_id
            info.name_to_coin[coin] = coin
            exchange.info.coin_to_asset[coin] = asset_id
            exchange.info.name_to_coin[coin] = coin

    return info, exchange
```

The `if coin in info.coin_to_asset: continue` guard is defensive: if a future SDK release adds native HIP-4 support, the patch becomes a no-op rather than producing duplicate entries. Pin a tested SDK version in your `requirements.txt` regardless.

## Settlement mechanics

Recurring outcomes are auto-deployed and auto-settled by the protocol on a fixed cadence. The settlement rule for binary price-based outcomes:

```
Contract settles to YES if and only if
    markPrice0 + (settlementTime - t0) / (t1 - t0) * (markPrice1 - markPrice0) >= targetPrice
```

Where `markPrice0` and `markPrice1` are the two HyperCore mark-price updates immediately before and after `settlementTime`, and `t0`, `t1` are their timestamps. The protocol takes those two flanking samples, linearly interpolates between them at the exact settlement timestamp, and compares the interpolated value to the target.

The recurring price-bucket question uses the same interpolated price to pick one of three buckets — below the first threshold, between the two thresholds, or at or above the second — and the matching named outcome settles to YES.

> [!WARNING]
>
> The samples are mark-price updates, not candle OHLCV closes, not oracle snapshots, and not a TWAP. If you implement pre-expiry position management against candle data, your settlement estimate will diverge from the actual settled value, especially in fast-moving markets where mark updates are dense around the settlement timestamp.

For very fast-moving markets the choice of `t0` and `t1` updates can move the settled price by several ticks compared to the visible mark price at the exact timestamp.

Deployer markets settle according to their template — for example, a `template:binaryPrice` market names its price source in `priceDescription`.

## Holding to settlement

Settlement is automatic. There is no `claim`, `redeem`, or `settle` call. At expiry, YES converts to `settleFraction` USDC per share and NO to `1 - settleFraction` USDC per share — 1 and 0 for a binary YES result — and the outcome is removed from the next `outcomeMeta` response. To read the result of a settled outcome, query [`settledOutcome`](https://docs.chainstack.com/reference/hyperliquid-info-settled-outcome), which returns the outcome spec, its `settleFraction`, and the settlement `details` such as the settled price.

To watch a position through settlement, poll `spotClearinghouseState` for the `+<encoding>` balance until it disappears, or compare your USDC balance before and after the expiry timestamp:

```python theme={"system"}
import time

def wait_for_settlement(
    info: Info,
    address: str,
    outcome_id: int,
    poll_interval: float = 5.0,
):
    while True:
        state = info.spot_user_state(address)
        balances = {b["coin"]: b for b in state.get("balances", [])}
        held = any(
            encode_balance_coin(outcome_id, side) in balances
            for side in (0, 1)
        )
        if not held:
            return
        time.sleep(poll_interval)
```

If a reader expects a Polymarket or Gnosis CTF flow with a `redeemPositions` call, they will wait for a transaction that never comes — settlement happens inside the matching engine. To exit before expiry, sell your shares on the book, or [merge](#splitting-merging-and-negating-outcomes) matching YES and NO shares back into USDC.

## Reading the order book

The YES and NO books of an outcome are merged into one book that shares liquidity: buying YES at price `p` is the same order as selling NO at `1 - p`. `l2Book` returns the merged book from the side you ask for, so the NO book is the YES book mirrored around 1:

```python theme={"system"}
def fetch_book(base_url: str, coin: str) -> tuple[list, list]:
    r = httpx.post(
        f"{base_url}/info",
        json={"type": "l2Book", "coin": coin},
        timeout=10.0,
    )
    r.raise_for_status()
    levels = r.json().get("levels", [[], []])
    return levels[0], levels[1]


# Mainnet BTC daily binary, current instance
btc_daily = find_recurring_binary(fetch_outcome_meta(), "BTC")
yes_bids, yes_asks = fetch_book(HYPERLIQUID_PUBLIC_URL, encode_coin(btc_daily, 0))
no_bids, no_asks = fetch_book(HYPERLIQUID_PUBLIC_URL, encode_coin(btc_daily, 1))
```

On the BTC daily book, a YES bid of `0.48543` for 87 shares appears as a NO ask of `0.51457` for the same 87 shares. Use the `#<encoding>` form for `l2Book` and websocket subscriptions, never the `+<encoding>` balance form.

## Placing an order

Once the SDK is patched, order placement is a normal `Exchange.order(...)` call:

```python theme={"system"}
info, exchange = make_clients(private_key, address)
btc_daily = find_recurring_binary(fetch_outcome_meta(), "BTC")

result = exchange.order(
    encode_coin(btc_daily, 0),    # BTC daily, side 0 (YES) — see encoding table
    is_buy=True,
    sz=10,                        # whole shares
    limit_px=0.42,                # probability between 0 and 1
    order_type={"limit": {"tif": "Gtc"}},
)
print(result)
```

Outcome orders follow these rules:

| Rule | Value |
| - | - |
| Price | A probability between 0 and 1 — mainnet books quote up to 5 decimal places, such as `0.00024` and `0.99976`. See [Order precision](https://docs.chainstack.com/docs/hyperliquid-order-precision.md) for the general rules |
| Order size | Whole shares — integer sizes |
| Leverage | None — fully collateralized at open |

Validate the price and integer size client-side before signing the order — the round-trip to discover an invalid value via server rejection is wasteful in latency-sensitive code.

To bet against an outcome, buy its NO side. On the merged book, buying NO at price `q` is the same order as selling YES at `1 - q`.

## Fees, mint, normal trade, and burn

Outcome trading **only charges fees when closing or settling, not when opening**. Buys that open or add to a position pay no fee; sells that close a position and merges pay the fee, in USDC. Only fee-paying volume counts toward your volume. The matching engine classifies every fill into one of six cases:

| Case | What happened | Fee and volume |
| - | - | - |
| Mint | Both counterparties open new positions | No fee; no volume counted |
| Normal trade, one side pays | One side opens, the other closes | The closing side pays; both users get `fee_paying_px * sz` volume |
| Normal trade, no one pays | Neither side's fill is fee-paying | No volume counted |
| Burn, both pay | Both counterparties close opposite sides together | Both pay; both users get `(maker_px + taker_px) * sz = 1 * sz` volume |
| Burn, taker only | Both counterparties close opposite sides together, and only the taker pays | Taker pays; both users get `taker_px * sz` volume |
| Settlement | Auto-settlement at expiry | Each user gets `settle_fraction * sz` volume |

Fee rates follow your spot fee tier, returned by [`userFees`](https://docs.chainstack.com/reference/hyperliquid-info-userfees) as `userSpotCrossRate` (taker) and `userSpotAddRate` (maker), after any referral discount. Deployer markets with a `deployerFeeScale` of `1.0` charge twice that rate: at a `userSpotCrossRate` of `0.0006` and a 4% referral discount, a taker sell pays `2 * 0.0006 * 0.96 = 0.001152` of `px * sz`. Outcome trading has no maker rebates — users who would otherwise receive rebates pay zero on maker orders instead.

Mint and burn happen implicitly inside the matching engine as a side effect of the fill — you cannot request them through an order.

## Splitting, merging, and negating outcomes

The [`userOutcome`](https://docs.chainstack.com/reference/hyperliquid-exchange-user-outcome) exchange action converts between USDC and outcome shares directly, without trading on the book:

* `splitOutcome` — split `X` USDC into `X` YES and `X` NO shares of an outcome.
* `mergeOutcome` — merge `X` YES and `X` NO shares of an outcome back into `X` USDC.
* `mergeQuestion` — merge `X` YES shares from every outcome of a question into `X` USDC.
* `negateOutcome` — convert `X` NO shares of one outcome in a question into `X` YES shares of every other outcome in that question.

Because exactly one outcome of a question settles to YES, `mergeQuestion` and `negateOutcome` let holders of a full set redeem USDC before the outcomes settle. The `hyperliquid-python-sdk` has no helper for `userOutcome`; sign it as an L1 action. See the [`userOutcome` reference](https://docs.chainstack.com/reference/hyperliquid-exchange-user-outcome) for request examples.

## Where to go next

Worked-out reference implementation with progressive examples and a market-maker bot:

* [chainstacklabs/hyperliquid-hip-4](https://github.com/chainstacklabs/hyperliquid-hip-4) — Python scripts for market discovery, questions, account state, order book snapshots, the websocket feed, the order lifecycle, categorical trades, split and merge, a settlement watcher, and a passive market-maker.

Related reference and guides on Chainstack:

* [Hyperliquid methods](https://docs.chainstack.com/docs/hyperliquid-methods.md) — full method availability matrix.
* [outcomeMeta API reference](https://docs.chainstack.com/reference/hyperliquid-info-outcomemeta.md) — request and response schema.
* [settledOutcome API reference](https://docs.chainstack.com/reference/hyperliquid-info-settled-outcome.md) — the result of a settled outcome.
* [userOutcome API reference](https://docs.chainstack.com/reference/hyperliquid-exchange-user-outcome.md) — split, merge, and negate actions.
* [Hyperliquid order precision](https://docs.chainstack.com/docs/hyperliquid-order-precision.md) — `szDecimals` and price tick rules that apply to outcome orders too.
* [Hyperliquid signing overview](https://docs.chainstack.com/docs/hyperliquid-signing-overview.md) — required for every `Exchange.*` call.

Upstream documentation:

* [HIP-4 specification](https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-4-outcome-markets)
* [Asset IDs (encoding spec)](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/asset-ids)
* [Contract specifications (settlement formula)](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/contract-specifications)
* [Fees (the six cases)](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees)
* [HIP-4 deployer actions](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/hip-4-deployer-actions)
