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.12wss://<the exchange's host>/v1/ws wss://<the exchange's host>/v1/ws?token=<session token>
?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.hello, with the stream position (pos)
and the input sequence (seq) the gateway has reached:1{ "type": "hello", "seq": 1834, "pos": 918274 }
1{ "op": "subscribe", "channel": "book:7:859008923130267914" }
| Channel | First answer | Then |
book:<underlyingKey>:<specifier> | a book snapshot | level frames, quoteRequest events, delisted |
book:<underlyingKey> | a book snapshot of every contract of the underlying | the same, each naming its specifier |
prints:<underlyingKey>:<specifier> | subscribed | fill events, without either side's balances |
reference:<underlyingKey> | subscribed | reference events |
account:<address> | subscribed | every event of that account; needs a session for it |
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.12{ "type": "level", "channel": "book:7:859008923130267914", "pos": 918275, "seq": 1835, "side": 0, "price": 19500, "quantity": 3 }
delisted frame
naming the specifier and why (instrumentSettled or instrumentUnregistered).
Drop the contract then: it takes no more orders.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.GET /v1/account/{addr}: balances, positions, keys;
engine.position is the first stream position the answer does not include.GET /v1/account/{addr}/orders?envelope=1: the resting
orders, with the position they are complete to.pos is below that position is already in the answer; apply
only the ones at or after it.| What happened | Close code | What to do |
| You fell more than 2048 events behind | 4008 | Reconnect at once. |
| Your session expired, or the signing key that opened it was revoked | 4401 | The token is dead. Sign in again, and reconnect with the new token. |
| You sent more than 10 requests a second, past a burst of 64 | 1008 | Send fewer subscribes at once. |
| The network dropped, or the gateway restarted | none | Reconnect with a backoff: start at half a second and double it, up to 15 seconds. |
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.book:<underlyingKey> channel covers a
whole underlying.HV_PRIVATE_KEY set, your account. It
reconnects with a backoff and signs in again when the gateway closes with 4401.12pip install requests eth-account websockets python 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())