Agent-readable docs index: /llms.txt. Full docs in one file: /llms-full.txt. Download /docs.zip to grep all markdown files locally.

Streaming

The gateway pushes everything that changes over one WebSocket, GET /v1/ws, on the same host as the API. This guide connects, subscribes, keeps a book, follows an account, and recovers. WebSocket is the reference for every frame.

Connect

wss://<the exchange's host>/v1/ws wss://<the exchange's host>/v1/ws?token=<session token>
Anyone may connect and read books, trades and reference prices. To follow your own account, connect with a session token, as ?token= or as Authorization: Bearer <token> (a browser's WebSocket cannot set the header, so use ?token= there). The token is checked when you connect and again every few seconds while the connection is open.
The first frame on every connection is hello, with the stream position (pos) and the input sequence (seq) the gateway has reached:
{ "type": "hello", "seq": 1834, "pos": 918274 }

Subscribe

Send one frame per channel:
{ "op": "subscribe", "channel": "book:7:859008923130267914" }
ChannelFirst answerThen
book:<underlyingKey>:<specifier>a book snapshotlevel frames, quoteRequest events, delisted
book:<underlyingKey>a book snapshot of every contract of the underlyingthe same, each naming its specifier
prints:<underlyingKey>:<specifier>subscribedfill events, without either side's balances
reference:<underlyingKey>subscribedreference events
account:<address>subscribedevery event of that account; needs a session for it
Keys and specifiers are written in decimal. A specifier is often above 253, so in JavaScript parse frames with a BigInt-safe JSON parser.

Keep a book

A book snapshot gives every level; each level frame after it gives one level's new total, and quantity: 0 empties it. Apply them in the order they arrive and the book is exact: every level frame on a channel has a pos at or after its snapshot's.
{ "type": "level", "channel": "book:7:859008923130267914", "pos": 918275, "seq": 1835, "side": 0, "price": 19500, "quantity": 3 }
When a contract settles, or is removed, its book channels get a delisted frame naming the specifier and why (instrumentSettled or instrumentUnregistered). Drop the contract then: it takes no more orders.

Follow your account

On account:<address> you receive your orders (inserted, cancelled, expired, refused, orderSettled), your fills with your balances and the fill's effect on your position, your settlements (positionSettled), your money (funds) and your own quote requests. The full list is on WebSocket.
The stream carries what happens from the moment you subscribe; it does not replay. To know where the account stands, read it from REST once you are subscribed:
An event whose pos is below that position is already in the answer; apply only the ones at or after it.

Recover

A connection ends for one of these reasons. In every case, reconnect, resubscribe, and take the fresh snapshots and REST reads as the truth: there is no replay of what you missed.
What happenedClose codeWhat to do
You fell more than 2048 events behind4008Reconnect at once.
Your session expired, or the signing key that opened it was revoked4401The token is dead. Sign in again, and reconnect with the new token.
You sent more than 10 requests a second, past a burst of 641008Send fewer subscribes at once.
The network dropped, or the gateway restartednoneReconnect with a backoff: start at half a second and double it, up to 15 seconds.
The gateway pings every 20 seconds; a connection it hears nothing from, not even the pong your WebSocket library sends, for 60 seconds is closed.

Limits

  • 16 connections per client, keyed by IP address (an IPv6 /56). A connect past it is refused 429 with Retry-After: 5; a place frees when one of your connections closes. Part of each gateway's connections is kept for clients signed in as an account that has deposited.
  • 256 channels per connection. One book:<underlyingKey> channel covers a whole underlying.
  • 10 requests a second per connection, in bursts of 64.
  • Each connect counts against your IP's request rate, like any request.

A complete client

In Python. It follows the first listed contract's book and trades, its underlying's reference price, and, with HV_PRIVATE_KEY set, your account. It reconnects with a backoff and signs in again when the gateway closes with 4401.
pip install requests eth-account websockets python stream.py
stream.py
"""Follow one contract's book and trades, its underlying's reference price, and your account, over the gateway's WebSocket, reconnecting as needed. pip install requests eth-account websockets python stream.py """ import asyncio import json import os import requests import websockets from eth_account import Account from eth_account.messages import encode_defunct GATEWAY = os.environ.get("HV_GATEWAY", "https://testnet.hv.exchange").rstrip("/") WS_URL = GATEWAY.replace("https://", "wss://", 1).replace("http://", "ws://", 1) + "/v1/ws" def sign_in(acct): """A session token for the account (POST /v1/session/challenge, then /v1/session).""" ch = requests.post(f"{GATEWAY}/v1/session/challenge", json={"address": acct.address}, timeout=30).json() sig = acct.sign_message(encode_defunct(text=ch["message"])).signature r = requests.post(f"{GATEWAY}/v1/session", json={ "address": acct.address, "challenge": ch["challenge"], "signature": "0x" + bytes(sig).hex(), }, timeout=30) r.raise_for_status() return r.json()["token"] acct = Account.from_key(os.environ["HV_PRIVATE_KEY"]) if os.environ.get("HV_PRIVATE_KEY") else None token = sign_in(acct) if acct else None inst = requests.get(f"{GATEWAY}/v1/instruments", timeout=30).json()[0] uk, spec = inst["underlyingKey"], inst["specifier"] channels = [f"book:{uk}:{spec}", f"prints:{uk}:{spec}", f"reference:{uk}"] book = {0: {}, 1: {}} # side -> {price: quantity}; 0 bids, 1 asks def resync_account(): """What the stream does not replay: the account as it stands, from REST. Events at or after `position` are not in it; apply those from the stream.""" h = {"Authorization": f"Bearer {token}"} me = requests.get(f"{GATEWAY}/v1/account/{acct.address}", headers=h, timeout=30).json() orders = requests.get(f"{GATEWAY}/v1/account/{acct.address}/orders?envelope=1", headers=h, timeout=30).json() print("account: free cash", me["engine"].get("freeCash"), "resting", len(orders["orders"]), "as of position", orders["position"]) def handle(m): t = m["type"] if t == "hello": print("hello: the gateway is at position", m["pos"]) elif t == "book": # a snapshot: replace the book book[0] = {l["price"]: l["quantity"] for l in m["bids"]} book[1] = {l["price"]: l["quantity"] for l in m["asks"]} print("book snapshot at", m["pos"], "bids", sorted(book[0].items(), reverse=True)[:3], "asks", sorted(book[1].items())[:3]) elif t == "level": # a level's new total; 0 empties it if m["quantity"] == 0: book[m["side"]].pop(m["price"], None) else: book[m["side"]][m["price"]] = m["quantity"] print("level", "bid" if m["side"] == 0 else "ask", m["price"], m["quantity"]) elif t == "delisted": print("delisted", m["specifier"], m["reason"]) elif t in ("subscribed", "unsubscribed"): print(t, m["channel"]) elif t == "error": print("error on", m.get("channel"), ":", m["error"]) else: # an event: fill, reference, quoteRequest, or the account's own ev = m["event"] print(m["channel"], ev["type"], {k: ev[k] for k in ("price", "size", "side", "nonce", "code", "amount") if k in ev}) async def run(): global token retry = 0.5 while True: url = WS_URL + (f"?token={token}" if token else "") try: async with websockets.connect(url, max_size=None) as ws: retry = 0.5 subs = channels + ([f"account:{acct.address}"] if token else []) for ch in subs: await ws.send(json.dumps({"op": "subscribe", "channel": ch})) if token: resync_account() async for raw in ws: handle(json.loads(raw)) except websockets.ConnectionClosed as e: code = e.rcvd.code if e.rcvd else None print("closed", code, e.rcvd.reason if e.rcvd else "") if code == 4401 and acct: # the session is dead: sign in again token = sign_in(acct) if code == 4008: # fell behind: resubscribe at once retry = 0 except (OSError, websockets.InvalidHandshake) as e: print("connect failed:", e) # a 429 here: no connection free; wait await asyncio.sleep(retry) retry = min(max(retry, 0.5) * 2, 15) asyncio.run(run())