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

# Binary Predictions WebSocket data

> Receive Predictions market data and trading updates in Simple Binary Encoding (SBE) format.

The Predictions Trade API WebSocket supports Simple Binary Encoding (SBE) for market data, private trading updates, RFQs, and reference prices. JSON is the default. You can generate native codecs from the [SBE XML schema](https://docs.kalshi.com/websockets/kalshi-predictions-sbe-v1.xml).

For perpetual futures, use the [Margin WebSocket schema and subprotocol](https://docs.kalshi.com/margin-ws/websockets/binary-data.md).

## Connect

Offer `kalshi.predictions.sbe.v1` in the `Sec-WebSocket-Protocol` header when opening the connection. Sign the request with your API key using the path for the endpoint.

| Predictions endpoint | Signing path | Available binary channels |
| - | - | - |
| Main WebSocket | `GET /trade-api/ws/v2` | All channels listed below, subject to your permissions |
| Fill and order updates | `GET /trade-api/ws/v2` | `fill` and `user_orders` |
| External feeds | `GET /trade-api/v2/external-feeds` | `cfbenchmarks_value`, `cfbenchmarks_value_5hz`, and `pyth_value` |

Before subscribing, verify that the HTTP 101 response returns `Sec-WebSocket-Protocol: kalshi.predictions.sbe.v1`. For a JSON connection, omit the subprotocol. See [API environments and endpoints](https://docs.kalshi.com/getting_started/api_environments.md) and the [WebSocket authentication example](https://docs.kalshi.com/getting_started/quick_start_websockets.md).

## Supported channels

| Subscription channel | SBE template IDs | Data |
| - | - | - |
| `orderbook_delta` | 1, 2, 3 | Snapshot, public delta, delta with your order details |
| `trade` | 4 | Public trade |
| `ticker` | 5 | Market statistics, including requested initial ticker snapshots |
| `fill` | 6 | Your executions, including fee and post-fill position |
| `user_orders` | 7 | Your order status, quantities, costs and timestamps |
| `market_positions` | 8 | Your current market positions and costs |
| `order_group_updates` | 9 | Your order-group state and contract limits |
| `communications` | 16–27 | Individual and batch RFQ and quote events, including best quotes |
| `cfbenchmarks_value` | 32 | CF Benchmarks index value, averages and upstream frame |
| `cfbenchmarks_value_5hz` | 33 | CF Benchmarks 5 Hz tick and upstream frame |
| `pyth_value` | 34 | Pyth price or yield with source and receipt times |

Private updates follow the same account permissions and subaccount restrictions as JSON. The server checks a subscription’s channels in request order. If a channel is unsupported (code 8) or a market-data-only key requests a private channel (code 9), the first error applies to the whole request. Use a JSON connection for other channels.

## Message types

| WebSocket frame | Contents |
| - | - |
| Text (`0x1`) | JSON commands and responses, including subscription acknowledgments, errors, unsubscribe notices, and index or underlying lists |
| Binary (`0x2`) | One SBE data message |
| Ping / Pong (`0x9` / `0xA`) | Connection heartbeat. A Pong echoes the Ping payload. Neither frame advances a subscription sequence. |
| Close (`0x8`) | WebSocket close handshake |

Compression is negotiated independently using `permessage-deflate`. When enabled, the WebSocket library decompresses and reassembles the message before SBE decoding. For heartbeat timing, see [connection keep-alive](https://docs.kalshi.com/websockets/connection-keep-alive.md).

## Decode a message

Each message starts with an eight-byte, little-endian header containing `blockLength`, `templateId`, `schemaId`, and `version`, in that order. Each field is an unsigned 16-bit integer. Schema ID and version are both `1`. Select the decoder by template ID and pass it the received block length and version. Repeating groups and variable-length fields follow the fixed block in schema order.

The delivery fields occupy the first 32 bytes after the header in every v1 template.

| Field | Type | Meaning |
| - | - | - |
| `sid` | uint64 | Subscription ID |
| `seq` | uint64 | Sequence within the subscription. Zero when the channel does not assign a sequence. |
| `sendingTsMs` | int64 | Server send time in Unix milliseconds |
| `requestId` | uint64 | Command ID for a response such as a requested book snapshot. Zero can mean an absent ID or an explicit zero. Use a nonzero ID for correlation. |

Published v1 layouts are stable. Additional channels can introduce new template IDs. An incompatible layout requires a new schema and subprotocol.

### Field conventions

| Data | Interpretation |
| - | - |
| Order books, trades, and tickers | 10,000 price units equal one US dollar. 100 quantity units equal one contract. |
| Order book prices | YES levels carry YES prices. NO levels carry NO prices by default. With `use_yes_price: true`, NO levels carry the complementary YES price and retain their NO side. |
| Public trades | NO price equals 10,000 minus the YES price. A YES taker outcome corresponds to a book bid. |
| Private trading updates | One million fee or cost units equal one US dollar. The signed fill price supports eligible FCC executions above one dollar. The template distinguishes the user’s order side from the outcome purchased. |
| RFQs and quotes | Use the fixed-point exponents and optional-value indicators in each template. Event timestamps carry Unix seconds and nanoseconds. |
| UUIDs | Fields declared as `uuidBytes` in the schema contain 16 bytes in standard UUID byte order. The `orderId` in `QuoteExecuted` (template 20) is length-prefixed UTF-8 text. |
| Reference prices | `indexNumber8` carries a value to eight decimal places. Its tag identifies the fixed-point mantissa, a rounded negative zero, or an extended IEEE-754 value. |
| CF Benchmarks | `rawData` contains the upstream UTF-8 text. On the one-second feed, `valueUsd` is the current tick and `avg60sData.windowEndTsExclusive` is its source time in Unix milliseconds. The trailing and quarter-hour averages use the ticks observed by the subscription. |

### Python example

This example subscribes to public trades and reads the contract count and YES price from template 4. Pass the signed headers from the [WebSocket quick start](https://docs.kalshi.com/getting_started/quick_start_websockets.md) and the market ticker you want to follow.

```python theme={null}
import json
import struct
from decimal import Decimal

import websockets

PROTOCOL = "kalshi.predictions.sbe.v1"
URL = "wss://external-api-ws.kalshi.com/trade-api/ws/v2"


async def watch_trades(auth_headers, ticker):
    async with websockets.connect(
        URL, additional_headers=auth_headers, subprotocols=[PROTOCOL]
    ) as ws:
        if ws.subprotocol != PROTOCOL:
            raise RuntimeError("Kalshi did not negotiate Predictions SBE v1")
        await ws.send(json.dumps({
            "id": 1, "cmd": "subscribe",
            "params": {"channels": ["trade"], "market_ticker": ticker},
        }))
        async for message in ws:
            if isinstance(message, str):
                control = json.loads(message)
                print(control)
                if control["type"] in {"error", "unsubscribed"}:
                    return
                continue

            if len(message) < 8:
                raise ValueError("Incomplete SBE header")
            block_length, template_id, schema_id, version = struct.unpack_from("<4H", message)
            if schema_id != 1 or version != 1:
                raise ValueError("Unexpected SBE schema")
            if template_id != 4:
                continue
            if block_length < 68 or len(message) < 8 + block_length:
                raise ValueError("Incomplete trade block")
            sid, seq, sending_ts_ms, request_id = struct.unpack_from("<QQqQ", message, 8)
            count, event_ts_ms, yes_price, side, is_block = struct.unpack_from("<qqHBB", message, 40)
            print(sid, seq, Decimal(count) / 100, Decimal(yes_price) / 10000)
```

## Sequence gaps and reconnects

Track `seq` by `sid`, including sequenced JSON responses on the same connection. If a book update is missing or cannot be decoded, request a fresh snapshot for every market on the affected subscription before applying subsequent deltas.

If overlapping snapshots leave the server unable to establish which queued orders belong to the book, it closes the affected subscription with code 10.

After a terminal channel error (code 10 or 25), wait for the matching `unsubscribed` message and subscribe again. After a disconnect, reconnect with backoff, verify the negotiated subprotocol, and rebuild subscriptions using the new SIDs. Fills and user-order updates are unsequenced. Reconcile them against your authenticated REST fills and orders after reconnecting. See [order book updates](https://docs.kalshi.com/websockets/orderbook-updates.md) and [WebSocket connection errors](https://docs.kalshi.com/websockets/websocket-connection.md).


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