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())import { ITMClient } from "@itmatrixhq/core";
const client = new ITMClient({ apiKey: process.env.ITM_API_KEY });
const spy = client.stream.gex("SPY", { nearest: 20 });
spy.on("update", (book) => {
console.log(book.symbol, book.spot, book.netGex, book.flip);
for (const row of book) console.log(row.strike, row.call, row.put, row.total);
});
spy.on("status", (status) => console.log("status:", status));
spy.on("error", (error) => console.error("error:", error));
await client.run(); // until Ctrl-C or every book closesclient.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.
| Python | TypeScript | What 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. |
latest | latest | The newest book, or none before the first one. Read it any time. |
age | age | Seconds since latest was computed. Use it to spot a stale book. |
status | status | connecting, 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 spy | for 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
| Event | Handler gets | When |
|---|---|---|
update | a Book | After every keyframe or update that changed the book, and once when you change the filter. |
status | the new status | On every change: connecting, live, reconnecting, closed. |
error | the error | A 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.
| Field | Meaning |
|---|---|
symbol | The underlying. |
spot | Underlying price in dollars, from the ITMatrixHQ price engine. |
net_gex | Whole-chain total in dollars per $1 move. It is not the sum of the listed strikes. |
flip | Zero-gamma level in dollars, or none when it cannot be computed. |
time | When the book was computed, UTC. A datetime in Python and a Date in TypeScript. |
age | Seconds since time, read now. |
| rows | for 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. |
| columns | strikes, 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. |
meta | book_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.
| Python | TypeScript | Keeps |
|---|---|---|
nearest=20 | nearest: 20 | The 20 strikes closest to spot. |
within=0.02 | within: 0.02 | Strikes 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)let side: "above" | "below" | undefined;
spy.on("update", (book) => {
if (book.flip === null) return;
const now = book.spot > book.flip ? "above" : "below";
if (side !== undefined && now !== side) {
console.log(`${book.symbol} crossed the flip at ${book.flip}, spot ${book.spot}`);
}
side = now;
});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))const books = ["SPY", "QQQ", "IWM"].map((s) => client.stream.gex(s, { nearest: 20 }));
for (const book of books) book.on("update", (b) => console.log(b.symbol, b.netGex));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 bookspy.update({ within: 0.02 });
spy.update({ top: 10 });
spy.update();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}import { createServer } from "node:http";
createServer((req, res) => {
const book = spy.latest;
res.setHeader("content-type", "application/json");
const body = book
? { spot: book.spot, netGex: book.netGex, flip: book.flip, age: book.age }
: { ready: false };
res.end(JSON.stringify(body));
}).listen(8080);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")spy.on("status", (status) => console.log("status:", status));
spy.on("error", (error) => console.error("error:", error));
if (spy.latest && spy.latest.age > 30) console.log("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)spy.on("update", async (book) => {
await fetch("https://example.com/hook", {
method: "POST",
body: JSON.stringify({ symbol: book.symbol, netGex: book.netGex }),
});
});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)for await (const book of client.stream.gex("SPY", { nearest: 20 })) {
console.log(book.spot, book.netGex);
}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
- Ticket. The SDK calls
POST /v2/stream/ticketwith 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. - Connect. The SDK opens
wss://api.itmatrixhq.com/v2/wswith the subprotocolitmatrixhq.v1. - Authenticate. The first frame is JSON and carries the ticket,
"proto": 8,"encoding": "protobuf"and the client name and version. The server answersauthedor a refusal. - Subscribe. The SDK sends a
subcontrol frame for topicgexwith a symbol. Onlysymbolis accepted as a parameter. A secondsubfor the same symbol replaces the first. - Receive. Control frames are JSON text. Data frames are binary protobuf: a
GexStrikeBookkeyframe or aGexStrikeBookUpdate, 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_idmatches and itsversionis 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_idor a failed check makes the SDK send aresynccontrol frame. It drops updates until the next keyframe arrives. Resyncs are rate limited per subscription. - A new
book_idmeans 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 Explorer | API Pro | |
|---|---|---|
| Concurrent connections | 5 | 100 |
| Active GEX subscriptions | 25 | 1,000 |
| Subscriptions per connection | 50 | 50 |
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.
| Code | Reason | What it means and what to do |
|---|---|---|
not_entitled_tier | stream_preview | Key streaming is switched off for the account. Do not retry. Contact ITMatrixHQ. |
invalid_params | protobuf_required | The first frame did not ask for protobuf. Use the SDK. |
invalid_params | proto_required | The protocol version was not 8. Upgrade the SDK to 1.2.0 or later. |
invalid_params | client_required | The subprotocol or client name was missing. Use the SDK. |
invalid_params | client_outdated | The SDK is older than the minimum version. Upgrade. |
invalid_params | unsupported_param | A subscription carried a parameter other than symbol. |
quota_exceeded | connection_limit | The account is at its connection limit. The limit field gives the number. Close a connection or wait. |
quota_exceeded | subscription_limit | The account or the connection is at its subscription limit. Unsubscribe something first. |
not_entitled_tier | none | A topic other than gex was requested. |
not_entitled_symbol | none | The 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.
| Situation | SDK behavior |
|---|---|
| Network error or unexpected close | Reconnect with exponential backoff from 0.25 s to 10 s, with full jitter. |
Ticket mint answered 429 | Wait for Retry-After, then retry. |
bye with draining | Wait for reconnect_after_ms, then reconnect. |
bye with slow_consumer | Close code 1013. Wait for reconnect_after_ms, then reconnect. |
bye with reauth | Reconnect 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_limit | Back off at least 30 seconds with jitter, then retry. |
Refused with stream_preview, client_outdated, client_required, protobuf_required or proto_required | Terminal. An error event with a StreamError, then the status becomes closed. |
Do not add your own retry loop around the SDK.