WebSocket
Connect, subscribe, read snapshots and deltas, detect gaps with sequence numbers, send orders over WebSocket, reconnect.
On this page
Help me with: WebSocket. Connect, subscribe, read snapshots and deltas, detect gaps with sequence numbers, send orders over WebSocket, reconnect.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/guides/websocket.md (~30 KB, plain Markdown: this page plus the AGENTS.md rules, Environments).
Fetch other pages from the index at {origin}/llms.txt only as you need them. {origin}/downloads/contract.json is a machine-readable contract for tools, not for reading.
Rules: follow AGENTS.md; do not send requests without the user asking you to; read credentials from environment variables; never retry writes automatically; show me the code and how to run it. URLs on this page: Testnet (chain ID 326). Other code on this page doesn't change: it stays on testnet until you switch it in your code. Tutorials, signing cases and live tools always use testnet.
One WebSocket per host carries both streams and RPC calls, on /ws/full.
With an SDK
The SDKs follow the protocol for you: they reconnect, subscribe again and check sequence
numbers. A connection that sends nothing, not even a ping or pong, for 30 s (idle_timeout) counts as
dead: the SDK drops it and reconnects, so a silent network failure ends in a gap instead of a stream that
waits forever. Leave idle_timeout at 30 s unless you need faster detection, and keep it well above 5 s: the
server pings every 5 s, and the TypeScript SDK, which can't send pings of its own, relies on those to see that a
quiet connection is alive. Whether a stream sends snapshots, deltas or events is explained in
Snapshots, deltas and events. Names used in this part:
| Python | TypeScript | Go | Rust |
|---|---|---|---|
on_event | onEvent | OnEvent (Config) | .on_event (Config) |
order_transport="ws" | orderTransport: "ws" | OrderTransport: grvt. (Config) | . (Config) |
EventKind. | type: "session_rotated" | grvt. | Event::SessionRotated |
websocket_reconnect_required | websocketReconnectRequired | WebsocketReconnectRequired | websocket_reconnect_required |
queue_size | queueSize | QueueSize (Config) | .queue_size (Config) |
idle_timeout (seconds) | idleTimeoutMs | IdleTimeout (Config) | .idle_timeout (Config) |
The recovery helpers (order lookup, local book, history paging) are on Recovery recipes.
Read a stream
Every stream has a method ending in _stream (Stream in TypeScript and Go). It returns a subscription you
iterate; closing it unsubscribes.
import asyncio
from grvt import AsyncGrvt
async def main():
async with AsyncGrvt(env="testnet") as client:
async with client.orderbook_snap_stream(instrument="BTC_USDT_Perp", rate=500, depth=10) as sub:
seen = 0
async for frame in sub:
print(frame.sequence_number, frame.feed.bids[:1], frame.feed.asks[:1])
seen += 1
if seen == 3:
break # leaving the async with block unsubscribes
asyncio.run(main())
import { Grvt } from "grvt";
const client = new Grvt({ env: "testnet" });
let seen = 0;
for await (const frame of client.orderbookSnapStream({ instrument: "BTC_USDT_Perp", rate: 500, depth: 10 })) {
console.log(frame.sequence_number, frame.feed.bids?.[0], frame.feed.asks?.[0]);
if (++seen === 3) break; // leaving the loop unsubscribes
}
await client.close();
sub, err := client.OrderbookSnapStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{
Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500), Depth: grvt.Ptr[uint32](10)})
if err != nil {
return err
}
defer sub.Close() // unsubscribes
seen := 0
for frame, err := range sub.All() {
if err != nil {
continue
}
fmt.Println(frame.SequenceNumber, len(frame.Feed.Bids), len(frame.Feed.Asks))
if seen++; seen == 3 {
break
}
}
use futures::StreamExt;
let mut sub = client.orderbook_snap_stream().instrument("BTC_USDT_Perp").rate(500).depth(10).await?;
let mut seen = 0;
while let Some(frame) = sub.next().await {
let Ok(frame) = frame else { continue }; // the subscription carries on after an error
println!("{} {:?}", frame.sequence_number, frame.feed.bids.as_ref().and_then(|b| b.first()));
seen += 1;
if seen == 3 {
break;
}
}
drop(sub); // unsubscribes
Reading a subscription can give an error in place of a frame. The subscription carries on after it:
- Overflow. Each subscription queues up to 4096 frames (client option
queue_size). If your code falls behind, a.sstream drops its oldest frame. Any other stream empties its queue, re-syncs and gives you a stream-overflow error; the frames in between are lost. - A frame that can't be decoded is skipped, with no gap event. If you build state from the stream, such as a book, treat it as a gap.
- A failed re-subscribe.
A fatal error (the socket can't connect for a reason retrying won't fix, such as a rejected API key or an invalid configuration) ends every subscription on that socket, after you read it.
When the sequence chain breaks, the SDK reports a gap event through the client's event hook (What happens after a gap).
Send orders over WebSocket
- Set the order transport to WebSocket when you create the client, for example
AsyncGrvt(..., order_transport="ws")(names in With an SDK). Create and cancel then go over the trading socket; everything else stays on HTTP. - Wait for a create's reply before cancelling that order (why).
In C++, your app builds the WebSocket frames and manages the connection.
Watch out: if the socket drops or the call times out after an order was sent, the SDK raises the outcome-unknown error and doesn't resend (When a write's outcome is unknown).
Session renewal
With an API key, the SDK logs in again at 80% of the session cookie's lifetime. It reads the lifetime from the
cookie's Expires, and assumes one hour if the cookie has none.
- When the new login succeeds, the SDK sends a
session_rotatedevent withwebsocket_reconnect_requiredset to true: open sockets still use the old cookie. - Each socket waits until none of its writes is still waiting for a reply, then reconnects with the new cookie and subscribes again. WebSocket writes sent meanwhile wait for the new socket.
Watch out:
- Renewal reconnects every socket of that client, public market data included, so every subscription gets a gap event. To record public market data without these gaps, use a separate client with no API key.
- Private streams can't be replayed across the reconnect. Treat it like any other gap (What happens after a gap).
Connect without an SDK
The sections from here to Unpublished limits describe the wire protocol, for apps without an SDK.
| Host | URL | Headers on the upgrade request |
|---|---|---|
| Market data | wss:/ | none |
| Trading | wss:/ | Cookie: gravity=... and X-Grvt-Account-Id (Authentication) |
The upgrade request is the HTTP request that opens the WebSocket, and the only place you authenticate. Messages
are JSON-RPC 2.0 text frames: a request has a method, params and an id; its reply has the same id and a
result or an error.
Subscribe
Send:
{
"jsonrpc": "2.0",
"method": "subscribe",
"params": {
"stream": "v1.ticker.d",
"selectors": ["BTC_USDT_Perp@500"],
"use_global_sequence_number": true
},
"id": 1
}
The reply's result is {stream, subs, unsubs, num_snapshots, first_sequence_number, latest_sequence_number}.
subs lists the selectors you are now subscribed to. The last three are arrays with one entry per selector, in
the same order as subs. After the reply, data frames arrive with no JSON-RPC envelope:
{
"stream": "v1.ticker.d",
"selector": "BTC_USDT_Perp@500",
"sequence_number": "0",
"prev_sequence_number": "0",
"feed": { "...": "..." }
}
A selector names what you want. Fields before @ pick the feed, fields after it set options, and several
fields are joined with -:
BTC_USDT_Perp@500: one instrument at a 500 ms rate.BTC_USDT_Perp@500-50: an order book at a 500 ms rate, 50 levels deep.<sub_account_id>-BTC_USDT_Perp: a private stream for one sub-account and instrument.
Each stream's reference page gives its exact format, for example
orderbook_snap and
orderbook_delta; All calls lists every
stream. unsubscribe takes the same {stream, selectors}. Subscribing again to a selector you have sends a new
snapshot, on streams that have one.
On one socket, each stream has one subscription per primary selector (the part before @). Subscribing with
the same primary selector and different options replaces the old subscription, and the reply lists the old
selector in unsubs. For example, with BTC_USDT_Perp@500-10 on v1.book.s, subscribing to
BTC_USDT_Perp@500-50 replies "subs": ["BTC_USDT_Perp@500-50"], "unsubs": ["BTC_USDT_Perp@500-10"].
Watch out: after you re-subscribe on the same socket, update frames from the earlier subscription can still arrive after the new reply. The sequence rules drop them. Don't assume the first frame after a reply belongs to the new subscription.
Connect to stream
Snapshots, deltas and events
The stream name's suffix says what a frame holds:
.s(snapshot): every frame is complete, so a missed frame costs nothing. Frames are still numbered, so you can see the gap..d(delta): the first frame after subscribing is a full snapshot. After that, frames hold only what changed, and you must apply every one in order.- no suffix (event): one frame per event, such as a fill or an order update.
Sequence numbers and gaps
Subscribe with use_global_sequence_number: true. Then every frame carries sequence_number and
prev_sequence_number: unsigned 64-bit integers sent as decimal strings. Compare them as integers (BigInt in
JavaScript), never as text or floating-point numbers. Each SDK page gives the types its frames use.
For each selector, the frames form a chain:
- The snapshot sent right after subscribing has
sequence_number"0". Every later frame is an update, on.sstreams too. - The first update after the subscribe reply has a
prev_sequence_numberat or below that selector'slatest_sequence_numberfrom the reply. Accept any such value, including"0": after a re-subscribe on the same socket it is often lower. Only a higher value is a gap. - Every later update has
prev_sequence_numberequal to the previous update'ssequence_number. - An update whose
sequence_numberis at or below the last one you accepted (for the first update, at or belowlatest_sequence_number) is a duplicate. Drop it.
Three frames from a testnet v1.book.d subscription (feeds shortened), after a reply with
"latest_sequence_number": ["8087017689000000"]:
{"sequence_number": "0", "prev_sequence_number": "0", "feed": {"bids": [4 levels], "asks": [4 levels]}}
{"sequence_number": "8087021381100000", "prev_sequence_number": "8087017689000000", "feed": {"bids": [], "asks": [...]}}
{"sequence_number": "8087021632000000", "prev_sequence_number": "8087021381100000", "feed": {"bids": [...], "asks": [...]}}
When: the chain breaks, which means you missed a frame. What to do depends on the stream kind:
.sstreams: nothing. The next frame is complete and current..dstreams: drop frames for that subscription, subscribe again with the same selector, wait for the new snapshot (sequence_number"0") and replace your state with it.- Event streams (fills, orders, positions, transfers, deposits, withdrawals, ...): subscribe again. There is no snapshot, so fetch what you missed over HTTP, for example open_orders, positions or fill_history. Each stream page names the calls.
Watch out: a snapshot restores current state. It doesn't recover missed private events.
Applying book deltas
On v1.book.d, the snapshot gives every price level. Each later frame lists only the levels that changed:
- A level's size is the new total at that price, not an amount to add.
- A size of zero removes the level. Compare it as a number: it can arrive as
"0"or"0.0". - An empty
bidsoraskslist means that side did not change.
For example, this testnet frame removes four ask levels and sets four bid levels:
{"bids": [{"price": "76869.0", "size": "4.96", "num_orders": 3}, ...],
"asks": [{"price": "76866.0", "size": "0.0", "num_orders": 0}, ...]}
Calling RPCs over WebSocket
Any RPC works over the socket: method is the RPC's WebSocket method (on its reference page), params the
request body, result the response body.
{
"jsonrpc": "2.0",
"method": "v1/create_order",
"params": { "order": { "...": "..." } },
"id": 7
}
A result means the same as an HTTP 200 for that call, with the same body. For create_order, the exchange
received the order; it may not rest on the book (What a create reply means).
Errors come back as {"jsonrpc": "2.0", "id": 7, "error": {"code": 2000, "message": "..."}}.
Watch out: the server doesn't promise to process requests in the order you sent them, on one socket or across HTTP connections. A cancel can overtake the create it refers to, so wait for a create's reply before cancelling that order.
Reconnect
On any disconnect:
- Reconnect with backoff: wait a little longer after each failed attempt, with some randomness, so clients don't all retry at once.
- Send the upgrade headers again.
- Subscribe to everything again.
- Treat each stream as after a gap (Sequence numbers and gaps).
After a new login, open the new socket with the new cookie. You can't log in again inside an open socket.
Unpublished limits
The heartbeat interval, maximum frame size, subscriptions per socket and per-stream rates are not published. Treat them as unknown (Rate limits).
Cancel orders if your app stops
The cancel-on-disconnect countdown is a timer on the server. If it runs out, the exchange cancels all of the
sub-account's open orders, with reject reason CLIENT_CANCEL_ON_DISCONNECT_TRIGGERED. Trigger orders
(take-profit and stop-loss orders waiting for their price) that haven't triggered yet are not cancelled. It fires
once, then stays off until you arm it again.
- Choose one component, in one process, to refresh the countdown for each sub-account.
- Arm the countdown with
refresh_cancel_countdown, in whole seconds (1 to 300). Then call it again on a schedule, well before the time runs out. - Stop refreshing when your app can no longer manage its orders, for example when it loses its trading connection or can't tell which orders are open. The countdown then runs out and cancels them.
- After recovery, check which orders exist and in what state, then refresh the countdown before allowing new orders.
For example, every 30 seconds:
from grvt import refresh_cancel_countdown
await refresh_cancel_countdown(client, sub_account_id=sub_account_id, countdown_seconds=120)
import { refreshCancelCountdown } from "grvt";
await refreshCancelCountdown(client, subAccountId, 120);
_, err := grvt.RefreshCancelCountdown(ctx, client, subAccountID, 120)
grvt::refresh_cancel_countdown(&client, sub_account_id, 120).await?;
To turn the countdown off, call cancel_on_disconnect with
countdown_time "0"; the helper only arms it. Without an SDK, call that RPC to arm it too. Its
countdown_time is in milliseconds, as a string, for example "120000". The server rounds it down to whole
seconds, so anything below "1000" turns the countdown off. It rejects more than 300 s with error 6000. The
helpers reject anything outside 1 to 300 s before sending.
Watch out:
- The countdown belongs to the sub-account, not to a socket or session, despite the RPC's name. Anyone who can trade on the sub-account replaces the same timer: two processes refreshing it overwrite each other, and a successful reply doesn't prove your timer is still the active one.
refresh_cancel_countdownsends once and never retries. A timeout raises the outcome-unknown error (When a write's outcome is unknown).- The SDK never refreshes the countdown on reconnect and never turns it off when the client closes.
Shut down cleanly
When: your app stops on purpose.
- Stop placing new orders.
- If you don't want orders left on the book, cancel them with cancel_all_orders, then check open_orders until they are gone. An accepted cancel doesn't prove an order was cancelled: it may have filled.
- If you armed the countdown, turn it off (
countdown_time"0") or let it run out, which cancels anything still open. - Close your subscriptions and wait for the writes you sent to return.
- Close the client.