Connect
SignGET /trade-api/ws/v2/margin using your API key and offer kalshi.margin.sbe.v1 in the Sec-WebSocket-Protocol request header. Verify the HTTP 101 response echoes the subprotocol before you subscribe. Omit the offer to receive JSON data.
See Margin API environments for demo endpoints. Send subscription commands as JSON text. Acknowledgments, errors and unsubscribe notices arrive as JSON text. Ping, Pong and Close use native WebSocket frames. A negotiated
permessage-deflate extension applies independently of the data format.
Supported channels
Market filters, account permissions and subaccount restrictions apply to both encodings. Use a JSON connection for corporate actions, market lifecycle or exchange status. Requesting an unsupported channel on a binary connection returns error code 8 for the subscription command.
Decode a message
Each binary WebSocket message contains one SBE message. Its eight-byte little-endian header contains the four unsigned 16-bit fieldsblockLength, templateId, schemaId, and version. Margin uses schema ID 2 and version 1. Dispatch by schema and template ID. For example, template 4 in the Margin schema carries a signed 64-bit price. Pass the received block length and version to the decoder.
The next 32 bytes carry the subscription ID (sid, uint64), subscription sequence (seq, uint64), server send time (sendingTsMs, int64), and originating command ID (requestId, uint64). A zero sequence denotes an unsequenced message. A zero request ID can mean that no command ID was supplied or that the client sent ID zero. Use a nonzero command ID to correlate a requested snapshot. Business fields, repeating groups and length-prefixed UTF-8 strings follow in schema order.
Recover a subscription
Apply book snapshots as replacements. Trackseq by subscription ID across binary book updates and sequenced JSON responses. If a sequence is missing, request fresh snapshots for every market on that subscription. If the server cannot safely deliver a book update, it sends error 10 and ends the affected subscription. Wait for its unsubscribed response and subscribe again. Reconnects create new subscription IDs. Fills and user-order updates are unsequenced. Reconcile them with your authenticated REST fills and orders after reconnecting. See Margin order book updates.