Docs

API

Streaming

Live GEX books for API Explorer and API Pro keys through the official SDK. What a key receives, the live book and its events, filters, recipes, limits and reconnect rules.

API streaming

An API key receives GEX books and nothing else. For each symbol you subscribe to, a book holds the call GEX and the put GEX for the 120 strikes with the largest gross GEX, the net GEX for the whole chain, the flip point, and the underlying spot from the ITMatrixHQ price engine. Books update about every 5 seconds. The stream carries no trades, quotes, bars, chain data or any other topic.

API Explorer and API Pro keys can stream with SDK 1.2.0 or later. Every topic other than gex is refused for keys, and so are index symbols such as SPX. If key streaming is switched off for an account, its ticket request gets 403 not_entitled_tier with the reason stream_preview. Contact ITMatrixHQ if that happens.

REST reads stay the right choice for history, one-off lookups and anything that does not need a live feed. See Caching for polling rules.

Use the official SDK

The stream requires the ITMatrixHQ SDK protocol. That means protobuf frames, the itmatrixhq.v1 WebSocket subprotocol, protocol version 8 and a declared client name and version in the first frame. The server checks each of these and refuses a connection that leaves one out. The official Python and TypeScript SDKs do all of it for you.

The server cannot prove that the SDK was used. The client name and subprotocol are declarations, and any program can send them. They exist so that connections identify themselves and so that old clients can be retired. They are not a security control. The reasons to use the SDK are that it keeps the book correct, reconnects politely and stays inside your limits.

Streaming needs SDK 1.2.0 or later. For Python use pip install -U "itmatrix[stream]". For TypeScript use npm i @itmatrixhq/core@latest, with Node 22 or later. SDK 1.0.0 cannot open the stream.

Quick start

import asyncio
import os
import itmatrix as itm

def show(book: itm.Book) -> None:
    print(book.symbol, book.spot, book.net_gex, book.flip)
    for row in book:
        print(f"  {row.strike:>8g} call {row.call:>14,.0f} put {row.put:>14,.0f} total {row.total:>14,.0f}")

async def main() -> None:
    async with itm.AsyncITMClient(api_key=os.environ["ITM_API_KEY"]) as client:
        spy = client.stream.gex("SPY", nearest=20)
        spy.on("update", show)
        spy.on("status", lambda status: print("status:", status))
        spy.on("error", lambda error: print("error:", error))
        await client.run()  # until Ctrl-C or every book closes

asyncio.run(main())

client.stream.gex("SPY") returns a live book at once. It connects in the background and keeps the newest book for you. You do not write a loop. You register handlers, or you read the newest book when you need it. client.run() keeps the program alive until you press Ctrl-C or every live book has closed.

The live book

Each symbol is one live book. Open it once and keep it. Every live book on a client shares one connection, and the connection closes when the last book closes.

PythonTypeScriptWhat it does
on(event, handler)on(event, handler)Calls handler on update, status or error. Returns a function that removes the handler. Register as many handlers as you like.
latestlatestThe newest book, or none before the first one. Read it any time.
ageageSeconds since latest was computed. Use it to spot a stale book.
statusstatusconnecting, live, reconnecting or closed.
await ready()await ready()The first book. Returns latest at once if there is one.
await changed()await changed()The next book after now. Use it instead of polling latest.
update(nearest=40)update({ nearest: 40 })Replaces the filter. Handlers get the current book through the new filter at once.
close()close()Ends this book. Closing the client closes every live book on it.
async for book in spyfor await (const book of spy)Iterates books as they arrive, if you prefer a loop.

On the client, await client.run() waits until Ctrl-C or until every live book has closed. Ctrl-C closes every book cleanly.

Events

EventHandler getsWhen
updatea BookAfter every keyframe or update that changed the book, and once when you change the filter.
statusthe new statusOn every change: connecting, live, reconnecting, closed.
errorthe errorA handler raised or rejected, or the stream was refused. A refusal that retrying cannot fix is a StreamError, and the status becomes closed after it.

Conflation is the contract. latest, handlers, changed() and iteration always get the newest book. A slow handler never builds a backlog. If an async handler is still running when two newer books arrive, it is called next with the newest one and the book in between is skipped. Every book is complete, so nothing is lost by skipping one.

Handlers never stop the stream. A handler that raises or rejects is reported to the error handlers and the stream goes on. ready() and changed() raise the error that closed the book.

Where handlers run. With AsyncITMClient, handlers run on your event loop. An async def handler runs as a task, one call at a time per handler. A plain function runs inline, so keep it quick. In TypeScript a handler can return a promise, and the next call waits for it. The blocking Python ITMClient never runs handlers on its network thread. They run one at a time on the book's own thread, or on an executor you pass: spy.on("update", fn, executor=pool). There ready(timeout) and changed(timeout) block, and client.run() blocks.

Each symbol is its own live book with its own events. There is no ordering promise across symbols. To compare two symbols at one moment, read both latest values.

The book

A book is an immutable snapshot of one symbol. Iterate it for rows in strike order. Python uses the names below. TypeScript uses camelCase, so net_gex is netGex.

FieldMeaning
symbolThe underlying.
spotUnderlying price in dollars, from the ITMatrixHQ price engine.
net_gexWhole-chain total in dollars per $1 move. It is not the sum of the listed strikes.
flipZero-gamma level in dollars, or none when it cannot be computed.
timeWhen the book was computed, UTC. A datetime in Python and a Date in TypeScript.
ageSeconds since time, read now.
rowsfor row in book. Each row has strike, call, put and total.
get(600)The row at that strike, or none.
len(book)The number of strikes. book.length in TypeScript.
columnsstrikes, calls, puts, totals in Python. columns with typed arrays, and rows as an array, in TypeScript.
df()A pandas DataFrame, Python only, when pandas is installed.
metabook_id, version, changed (the strikes that moved in this frame, every strike for a full book) and reason (why the server sent a full book, or none).

Values are dollars of dealer hedging per $1 move. Calls are positive, puts are negative and total is their sum, computed by the SDK. Call and put values are single precision, as sent. The book carries no open interest. Use the GEX grid when you need it.

The book holds the 120 strikes with the largest gross GEX, which is the size of the call side plus the size of the put side. Ties go to the lower strike. Gross ranking keeps a strike where a large call wall and a large put wall cancel out, so both walls stay visible. Membership is fixed between keyframes. See Units for the dollar and share conventions.

Filters

Filters are keyword arguments in Python and an options object in TypeScript. Pass them to stream.gex(...), or later to update(...). They run in the SDK on your machine. Nothing is sent to the server.

PythonTypeScriptKeeps
nearest=20nearest: 20The 20 strikes closest to spot.
within=0.02within: 0.02Strikes within 2 percent of spot, above or below.
between=(590, 610)between: [590, 610]Strikes from 590 to 610 dollars, both included.
top=10, by="gross"top: 10, by: "gross"The 10 largest by gross, net, call or put. Gross is the default. It combines with one of the options above and applies after it.

Pass at most one of nearest, within and between. update() with no options goes back to the whole book. A bad combination raises when you call gex() or update(), not later.

Filters choose among the 120 strikes in the book. They cannot add a strike the server did not send. A strike close to spot with little GEX may not be in the book, so nearest=20 can show a gap. If you need every strike in a range, read the GEX grid. In a filtered book, meta.changed lists only the strikes in view.

Recipes

React when spot crosses the flip

side = None

def on_book(book: itm.Book) -> None:
    global side
    if book.flip is None:
        return
    now = "above" if book.spot > book.flip else "below"
    if side is not None and now != side:
        print(f"{book.symbol} crossed the flip at {book.flip:.2f}, spot {book.spot:.2f}")
    side = now

spy.on("update", on_book)

The same shape works for a change of sign in net_gex.

Several symbols on one client

books = {s: client.stream.gex(s, nearest=20) for s in ("SPY", "QQQ", "IWM")}
for book in books.values():
    book.on("update", lambda b: print(b.symbol, b.net_gex))

All of them share one connection. Open one live book per symbol and keep it.

Change the filter live

spy.update(within=0.02)      # strikes within 2% of spot
spy.update(top=10)           # the 10 largest by gross GEX
spy.update()                 # the whole book

Handlers get the current book through the new filter at once. No new keyframe is needed.

Serve the newest book from your own web app

from fastapi import FastAPI

app = FastAPI()

@app.get("/gex/spy")
def gex_spy() -> dict:
    book = spy.latest
    if book is None:
        return {"ready": False}
    return {"spot": book.spot, "net_gex": book.net_gex, "flip": book.flip, "age": book.age}

Reading latest costs nothing and never waits for the network.

A pandas DataFrame

book = await spy.ready()
frame = book.df()            # columns: strike, call, put, total
print(frame.nlargest(5, "total"))

df() needs pandas installed. It raises an ImportError that names the install command when it is not.

Watch the connection

spy.on("status", lambda status: print("status:", status))
spy.on("error", lambda error: print("error:", error))

book = spy.latest
if book is not None and book.age > 30:
    print("book is stale")

During a reconnect the status goes to reconnecting and back to live, and the book gets a fresh keyframe. You do not need to resubscribe.

An async handler that does I/O

import httpx

http = httpx.AsyncClient()

async def post(book: itm.Book) -> None:
    await http.post("https://example.com/hook", json={"symbol": book.symbol, "net_gex": book.net_gex})

spy.on("update", post)

If the request is slow, the next call gets the newest book. Books never queue up behind a slow handler.

A loop instead of handlers

async for book in client.stream.gex("SPY", nearest=20):
    print(book.spot, book.net_gex)

Iteration follows the same conflation rule. Breaking out of the loop stops reading. The live book stays open until you close it or the client closes.

The blocking Python client

with itm.ITMClient(api_key=os.environ["ITM_API_KEY"]) as client:
    spy = client.stream.gex("SPY", nearest=20)
    spy.on("update", lambda book: print(book.spot, book.net_gex))
    client.run()

Handlers run on the book's own thread, never on the network thread. Pass executor= to on() to run them on your own pool.

Lifecycle

  1. Ticket. The SDK calls POST /v2/stream/ticket with your key. A ticket expires 60 seconds after it is minted and authorizes one connection. The SDK mints a fresh ticket for every connect. A mint counts against your normal request limits.
  2. Connect. The SDK opens wss://api.itmatrixhq.com/v2/ws with the subprotocol itmatrixhq.v1.
  3. Authenticate. The first frame is JSON and carries the ticket, "proto": 8, "encoding": "protobuf" and the client name and version. The server answers authed or a refusal.
  4. Subscribe. The SDK sends a sub control frame for topic gex with a symbol. Only symbol is accepted as a parameter. A second sub for the same symbol replaces the first.
  5. Receive. Control frames are JSON text. Data frames are binary protobuf: a GexStrikeBook keyframe or a GexStrikeBookUpdate, and nothing else. The WebSocket schema lists both.

The server pings every 15 seconds and closes a connection that stays silent for 45 seconds. The SDK answers each ping.

Keyframes and updates

The first frame for a subscription is a GexStrikeBook keyframe. It replaces all state for the symbol. Later frames are GexStrikeBookUpdate messages. An update carries only the strikes that changed, plus spot, net GEX and flip point. A strike is listed when its call side or its put side moved, and both sides are sent for every listed strike.

ITMatrixHQ publishes about every 5 seconds. We will tune the cadence and work on bringing it up. A keyframe can arrive at any time: periodically, after a resync, when the book is rebuilt, or when the server sends a full book instead of an update. Treat every keyframe as a fresh book. API Explorer and API Pro receive the same cadence. The two plans differ by limits only.

The SDK applies these rules, so you do not have to. They are listed so you can reason about what you see.

  • A keyframe replaces state and sets the version.
  • An update applies only when its book_id matches and its version is exactly one more than the current version. Every update is checked against a checksum of the whole book after it is applied.
  • A version at or below the current one is a duplicate and is ignored.
  • Any other gap, a different book_id or a failed check makes the SDK send a resync control frame. It drops updates until the next keyframe arrives. Resyncs are rate limited per subscription.
  • A new book_id means discard everything and wait for the keyframe that carries it.

There is no resume across reconnects. A reconnect costs one keyframe per subscription.

Limits

Limits are counted per account across all of its keys. A request over a limit is refused. The server never closes an existing connection or subscription to make room.

API ExplorerAPI Pro
Concurrent connections5100
Active GEX subscriptions251,000
Subscriptions per connection5050

Open one live book per symbol and keep it. Reopening it to get a fresh snapshot costs a keyframe each time. Read latest instead. One SDK client is one connection, so share it. Open a second client only when you need more than 50 symbols. Reconnect storms are the main avoidable cost, so keep the backoff rules below.

Errors and refusal reasons

A refusal on the socket arrives as a nack control frame with a code and a reason, followed by close code 1008. The ticket mint applies the same streaming gate and connection limit before any socket opens, and returns an HTTP error with the same code and reason.

CodeReasonWhat it means and what to do
not_entitled_tierstream_previewKey streaming is switched off for the account. Do not retry. Contact ITMatrixHQ.
invalid_paramsprotobuf_requiredThe first frame did not ask for protobuf. Use the SDK.
invalid_paramsproto_requiredThe protocol version was not 8. Upgrade the SDK to 1.2.0 or later.
invalid_paramsclient_requiredThe subprotocol or client name was missing. Use the SDK.
invalid_paramsclient_outdatedThe SDK is older than the minimum version. Upgrade.
invalid_paramsunsupported_paramA subscription carried a parameter other than symbol.
quota_exceededconnection_limitThe account is at its connection limit. The limit field gives the number. Close a connection or wait.
quota_exceededsubscription_limitThe account or the connection is at its subscription limit. Unsubscribe something first.
not_entitled_tiernoneA topic other than gex was requested.
not_entitled_symbolnoneThe symbol is an index. Index symbols, SPX included, are not available to keys.

See Errors for the full code list.

Reconnect

One SDK client owns one connection and the live books on it. After a reconnect it resubscribes everything, and each live book receives a fresh keyframe. The status goes to reconnecting and back to live.

SituationSDK behavior
Network error or unexpected closeReconnect with exponential backoff from 0.25 s to 10 s, with full jitter.
Ticket mint answered 429Wait for Retry-After, then retry.
bye with drainingWait for reconnect_after_ms, then reconnect.
bye with slow_consumerClose code 1013. Wait for reconnect_after_ms, then reconnect.
bye with reauthReconnect immediately. Sessions are re-authenticated at least every 15 minutes, so a revoked key or a changed plan takes effect within that time.
Refused with connection_limitBack off at least 30 seconds with jitter, then retry.
Refused with stream_preview, client_outdated, client_required, protobuf_required or proto_requiredTerminal. An error event with a StreamError, then the status becomes closed.

Do not add your own retry loop around the SDK.