Positions stream
Stream your positions, one frame each time a position is opened or changes.
On this page
Write a small program that subscribes to `execution.positions` on Grvt {environment} {using}, checks sequence numbers and re-subscribes on a gap.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/reference/streams/positions.md (~59 KB, plain Markdown: this page plus the AGENTS.md rules, Authentication and sessions, WebSocket, Python SDK, 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 and generated code samples 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.
| SDK | client. |
|---|---|
| Channel | v1.position on wss:/, or /ws/lite for lite names (the SDKs' default) |
| Selector | <sub_account_id>[-<instrument>] |
| Auth | Session required on the WebSocket upgrade (Authentication) |
| Kind | event. Each frame is one event (an update to one object). |
| Sequenced | Yes: the first update's prev_sequence_number is at or below the subscribe reply's latest_sequence_number, then each one equals the last sequence_number (rules). On a gap, re-subscribe, then fetch current state over HTTP (positions) for what you missed. |
| Contract id | execution.positions (StreamPositionsV1) |
Selector
Grammar <sub_account_id>[-<instrument>], e.g. <sub_account_id>-BTC_USDT_Perp. Parts:
- The sub-account ID to filter by
- The instrument filter to apply.
Frame
Type WSPositionsFeedDataV1.
- The stream this frame belongs to, e.g.
v1.position. - The selector this frame is for, as you subscribed with it.
- This frame's number, an unsigned 64-bit integer sent as a decimal string: compare it as an integer.
"0"on the snapshot sent right after subscribing.- With
use_global_sequence_number: true(recommended), the number is unique across the exchange. One exchange event can produce several frames, so the number isevent number × 10^5 + a counterthat tells them apart. - With
false, it counts up by one per frame of this stream and starts again when the server you are connected to restarts.
- With
- A Position being created or updated matching the request filter
21 fields of
Positions- Time at which the event was emitted in unix nanoseconds
- The sub-account ID that participated in the trade
- The instrument being represented
- The size of the position. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. Negative for short positions
- The notional value of the position, negative for short assets, in the quote asset. Decimal string, e.g. "12.5".
- The entry price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. Whenever increasing the size of a position, the entry price is updated to the new average entry price
new_entry_price = (old_entry_price * old_size + trade_price * trade_size) / (old_size + trade_size) - The exit price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. Whenever decreasing the size of a position, the exit price is updated to the new average exit price
new_exit_price = (old_exit_price * old_exit_trade_size + trade_price * trade_size) / (old_exit_trade_size + trade_size) - The mark price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals.
- The unrealized PnL of the position, in the quote asset. Decimal string, e.g. "12.5".
unrealized_pnl = (mark_price - entry_price) * size - The realized PnL of the position, in the quote asset. Decimal string, e.g. "12.5".
realized_pnl = (exit_price - entry_price) * exit_trade_size - The total PnL of the position, in the quote asset. Decimal string, e.g. "12.5".
total_pnl = realized_pnl + unrealized_pnl - The ROI of the position, expressed as a percentage
roi = (total_pnl / (entry_price * abs(size))) * 100^ - The index price of the quote currency. (reported in
USD) - The estimated liquidation price
- The current leverage value for this position
- The cumulative fee paid on the position, in the quote asset. Decimal string, e.g. "12.5".
- The cumulative realized funding payment of the position, in the quote asset. Decimal string, e.g. "12.5". Positive if paid, negative if received
- The margin type of the position
2 values
- [IsolatedOnly] The wallet balance reserved for this isolated margin position, in the quote asset. Decimal string, e.g. "12.5". If this positions is liquidated, this is the maximal balance that can be lost
- [IsolatedOnly] The initial margin of the isolated margin position, in the quote asset. Decimal string, e.g. "12.5". The
total_equityrequired to open more size in the position - [IsolatedOnly] The maintenance margin of the isolated margin position, in the quote asset. Decimal string, e.g. "12.5". The
total_equityrequired to avoid liquidation of the position
- The
sequence_numberof the frame before this one on this selector. If it doesn't match the last frame you accepted, you missed frames.
Errors
Subscribe errors arrive as a JSON-RPC error object {code, message} (lite {c, m}). Codes this stream can return (all error codes):
1101InvalidFeedFormat400- Feed Format must be in the format of <primary>@<secondary>
1102PrimarySelectorParts400- Wrong number of primary selectors
1103SecondarySelectorParts400- Wrong number of secondary selectors
3000InvalidInstrument400- Instrument is invalid
3007NotApplicableForSpotInstrument400- API is not applicable for spot instruments
3020InvalidSubAccountID400- Sub account ID must be an uint64 integer
Example
Example code
import asyncio
import os
from grvt import AsyncGrvt
async def main():
async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client:
async with client.positions_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub:
async for frame in sub:
print(frame.sequence_number, frame.feed)
asyncio.run(main())
Raw WebSocket: connect to wss://trades.testnet.grvt.io/ws/full (/ws/lite for lite names) with the Cookie: gravity=... and X-Grvt-Account-Id headers and send:
With full field names:
{
"jsonrpc": "2.0",
"method": "subscribe",
"params": {
"stream": "v1.position",
"selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"],
"use_global_sequence_number": true
},
"id": 1
}With lite field names:
{
"j": "2.0",
"m": "subscribe",
"p": {
"s": "v1.position",
"s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"],
"ug": true
},
"i": 1
}The reply's result is a WSSubscribeResult (subs, num_snapshots, latest_sequence_number); then frames arrive in the shape under Frame above, with no JSON-RPC envelope.
Build subscription
v1.position is on the trading gateway and needs a logged-in session (Cookie: gravity=… and X-Grvt-Account-Id on the WebSocket upgrade). The docs only build the subscription and never open the socket. Log in with the SDK or follow Authentication, then subscribe with the selector <sub_account_id>-BTC_USDT_Perp.