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

# Python SDK

> Official Python SDK for the Ironflow API.

<Note>
  **Package:** `ironflow-sdk`\
  **Requires:** Python 3.10+, `httpx`
</Note>

## Installation

```bash theme={null}
pip install ironflow-sdk
```

## Setup

```python Python theme={null}
from ironflow_sdk import Ironflow

# As a context manager (recommended — ensures connection cleanup)
async with Ironflow("if_your_api_key") as client:
    trades = await client.trades("BTC-PERP")

# Or directly
client = Ironflow("if_your_api_key")
# Remember to call: await client.close()

# Optional: custom base URL or source
client = Ironflow(
    "if_your_api_key",
    base_url="https://api.ironflow.sh",
    source="hyperliquid",
)
```

## Account & status

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    # Liveness probe (no auth required)
    health = await client.healthz()        # HealthResponse(status="ok")

    # Public component status + freshness
    status = await client.status()

    # Rolling-window API + pipeline + synthetic metrics (no auth required)
    metrics = await client.status_metrics()
    print(metrics.api.latency_p99_ms, metrics.pipeline.events_per_sec)

    # Uptime / freshness timeline — "24h" (default) or "7d"
    history = await client.status_history("7d")
    print(history.uptime_percent, len(history.points))
```

## Markets registry

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    # Every active market across all classes + issuers
    all_markets = await client.markets()

    # Filter by class and/or issuer
    perps    = await client.markets(market_class="perp")
    spot     = await client.markets(market_class="spot")
    outcomes = await client.markets(market_class="prediction")  # HIP-4 binary outcomes
    native   = await client.markets(issuer="")        # native non-builder only
    flx_only = await client.markets(issuer="flx")     # HIP-3 builder

    # Each Market dataclass carries the v3 identity tuple, so it joins with
    # /v1/* responses:
    #   market_id, source, market_class, issuer,
    #   base_asset, quote_asset, base_market, display_symbol,
    #   hl_coin, active_from_ms
```

This endpoint reads the registry directly — no per-tier query window applies.

## REST API

All list methods return a `Page[T]` dataclass with `.data`, `.has_more`, and `.next()`:

```python Python theme={null}
import asyncio
from ironflow_sdk import Ironflow

async def main():
    async with Ironflow("if_your_api_key") as client:
        trades     = await client.trades("BTC-PERP", limit=100)
        fills      = await client.fills("0xabc123", market="BTC-PERP")
        candles    = await client.candles("BTC-PERP", "1h", limit=24)

        funding      = await client.funding("BTC-PERP")
        oi           = await client.open_interest("BTC-PERP")
        marks        = await client.mark_prices("BTC-PERP")

asyncio.run(main())
```

## HIP-3 builder markets

Pass the full canonical symbol (`<issuer>:<base>-PERP`) as the `market` argument. Every response object carries `market`, `issuer`, and `base_market` — group by `issuer` to compare builders, by `base_market` to combine builds. Native HL perps return `issuer=""` and `market == base_market`.

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    # Felix Exchange's natural-gas perp
    gas = await client.trades("flx:GAS-PERP", limit=100)

    # XYZ's NVDA-PERP
    nvda = await client.trades("xyz:NVDA-PERP", limit=100)
    for trade in nvda.data:
        print(trade.issuer, trade.base_market, trade.price)
        # → "xyz" "NVDA-PERP" "881.20"
```

For **cross-issuer** queries (every builder's GOLD-PERP in one call) use the `base_market` + omitted-`issuer` form via cURL — the typed REST methods take `market` as their first argument. See [Sources & Markets](/concepts/sources-and-markets) for the full filter scheme.

## HIP-4 outcome contracts

HIP-4 binary prediction markets (live since 2026-05-02) carry `market_class="prediction"`. Display symbols read as `{UNDERLYING}-{TARGET}-{EXPIRY}-{Yes|No}` and complementary outcomes have prices summing to 1.0 (the implied probability).

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    # Latest trades on the "Yes" side of the BTC-above-$78,213 daily binary
    ticks = await client.trades("BTC-78213-20260503-Yes", limit=10)
    for t in ticks.data:
        print(f"Yes @ {t.price}, size {t.size}")  # price ∈ (0, 1)

    # Historical fills on the same market
    yes = await client.fills("0xabc", market="BTC-78213-20260503-Yes")

    # Resolution metadata (target price, expiry, period) lives on /v1/markets
    outcomes = await client.markets(market_class="prediction")
    print(outcomes[0].metadata)
    # → {'class': 'priceBinary', 'underlying': 'BTC', 'expiry': '20260503-0600',
    #    'targetPrice': '78213', 'period': '1d', ...}
```

Perp-only endpoints (`/v1/funding`, `/v1/open-interest`, `/v1/mark-prices`) return `400 INVALID_MARKET_CLASS` on prediction symbols — those concepts don't apply to fully-collateralized binaries.

## Pagination

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    page = await client.trades("BTC-PERP", limit=1000)

    while True:
        for trade in page.data:
            process(trade)
        if not page.has_more:
            break
        page = await page.next()
```

## Vault Operations

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    ops = await client.vault_operations(vault="0xvault_address")
```

## Cohorts

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    # List predefined + custom
    cohorts = await client.list_cohorts()

    # Create custom cohort
    await client.create_cohort("my_wallets", ["0xabc", "0xdef"])

    # Get addresses
    addrs = await client.cohort_addresses("top_pnl_30d")

    # Delete
    await client.delete_cohort("my_wallets")
```

## Analytics

`net-flows` and `funding-stats` work on every tier; `liquidation-levels`, `order-flow`, and `vault-leaderboard` require Builder or above.

```python Python theme={null}
async with Ironflow("if_your_api_key") as client:
    flows    = await client.net_flows(interval="1d", limit=7)
    levels   = await client.liquidation_levels("BTC-PERP", bucket_size=100)
    flow     = await client.order_flow()
    vaults   = await client.vault_leaderboard(limit=10)
    funding  = await client.funding_stats("BTC-PERP", interval="1d")
```

## Error handling

```python Python theme={null}
from ironflow_sdk.errors import RateLimitError, AuthError, TierError, IronflowError
import asyncio

async with Ironflow("if_your_api_key") as client:
    try:
        page = await client.trades("BTC-PERP")
    except RateLimitError as e:
        await asyncio.sleep(e.retry_after_ms / 1000)
    except AuthError:
        print("Invalid API key")
    except TierError:
        print("Feature not available on your tier")
    except IronflowError as e:
        print(e.code, e.status, str(e))
```

## Type reference

All response types are dataclasses:

```python Python theme={null}
from ironflow_sdk import (
    Trade, BookSnapshot, BookLevel, Candle,
    FundingRate, Liquidation, OpenInterest, MarkPrice,
    Deposit, Withdrawal, OrderStatus, VaultOperation,
    Trigger, CohortInfo, CohortAddresses,
    NetFlow, LiquidationLevel, OrderFlow,
    VaultLeaderboardEntry, FundingStats,
    Market, StatusResponse, StatusMetricsResponse, StatusHistoryResponse,
    APIMetrics, PipelineMetrics, SyntheticMetrics, UptimePoint,
    MeResponse, MeLimits, HealthResponse,
)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.