Python SDK
Install the grvt package, create a client, call any RPC, stream data, place signed orders and handle errors.
On this page
Help me with: Python SDK. Install the grvt package, create a client, call any RPC, stream data, place signed orders and handle errors.
Target environment: {environment} (chain ID {chainId}). Recorded signing cases keep their original environment.
{executionGuidance}
Read this first: {origin}/bundle/sdks/python.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. Preview. Any 0.x release can change the API, so pin the exact version you install (Install).
The Python SDK has a method for every call and stream in the API reference. It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data).
New here? Install the SDK and run the Quickstart, then read this page down to Track and cancel an order. Later sections are for when you need them.
Install
The package is grvt on PyPI. It needs Python 3.11 or newer.
pip install grvt
Preview: any 0.x release can change the API, so pin the exact version you install (for example in requirements.txt).
Create a client
AsyncGrvt is the client for asyncio code. Every example on this page uses it.
import asyncio
import os
from grvt import AsyncGrvt, PrivateKeySigner
async def main():
# The API key logs in; the signer signs orders with your signing key. Leave both out for public data only.
async with AsyncGrvt(
env="testnet",
api_key=os.environ["GRVT_API_KEY"],
signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]),
) as client:
t = await client.ticker(instrument="BTC_USDT_Perp")
print(t.result.mark_price) # the exchange's fair price, used for margin
asyncio.run(main())
Grvt is the blocking version, for scripts and notebooks. It takes the same arguments and has the same
methods, without await:
from grvt import Grvt
with Grvt(env="testnet") as client:
print(client.ticker(instrument="BTC_USDT_Perp").result.mark_price)
Grvt runs its own event loop on a background thread, so it also works in Jupyter. Each call blocks the cell
until it returns. To run calls side by side in a notebook, use AsyncGrvt with top-level await.
envis"testnet", or"prod"for production (Environments).- The client sends short (lite) field names on the wire by default; your code still uses the full names.
encoding="full"switches to full names (Encoding). - The client logs in on the first private call and renews the session before it expires (Authentication). Renewal reconnects the client's WebSockets, so every stream gets a gap (Session renewal).
- To stop, follow Shut down cleanly.
- Client settings are keyword arguments, typed by
ClientOptions, so a type checker catches unknown names. transport=takes your ownHttpTransportfor HTTP calls. WebSockets always use aiohttp.- A custom
Environmentwithencoding="lite"usesmd_ws_url/td_ws_urlwith the ending/ws/fullswapped for/ws/lite. Setmd_ws_lite_url/td_ws_lite_urlonly when its URLs don't end in/ws/full.
Call an RPC
Every call is a method on the client, client.<method>(...), named exactly as on its reference page. Pass
the request fields as keyword arguments; you get back a typed model.
inst = await client.get_instrument(instrument="BTC_USDT_Perp")
print(inst.result.tick_size, inst.result.min_size)
- Reads are tried up to 3 times; writes are sent once (What the SDK retries).
- Timeouts, as client options in seconds:
call_timeout(30 s),http_attempt_timeout(10 s),ws_request_timeout(5 s),resync_timeout(5 s),idle_timeout(30 s).call_timeoutlimits the whole call: login, instrument lookup, signing, retries and the response.http_attempt_timeoutcaps each HTTP attempt within what's left. - For one call, pass
options=CallOptions(timeout=...). It replacescall_timeoutfor that call; the blocking client takes it too.
from grvt import CallOptions
inst = await client.get_instrument(instrument="BTC_USDT_Perp", options=CallOptions(timeout=2.0))
Pagination
pages follows the next cursor of a history call, one page at a time, and never fetches ahead. Your callback
gets the cursor; keep its other filters fixed. With Grvt, use pages_sync.
from grvt import pages
async for page in pages(lambda cursor: client.trade_history(instrument="BTC_USDT_Perp", cursor=cursor)):
for trade in page.result or []:
print(trade)
- An empty page can still have a next cursor. Leaving the loop stops further calls.
- A repeated cursor raises
PaginationCycle. Fetch errors pass through, with no retries beyond the call's own. - Cursors don't give a stable snapshot while records change.
Default sub-account
Pass sub_account_id="123" to AsyncGrvt or Grvt to fill in the account ID wherever a request or stream
leaves it out.
- An ID you pass explicitly wins.
- An order in
bulk_orderstakes the request's account first, then the client default. - Transfer source and destination IDs are never filled in.
- The default is applied to a copy, before signing.
- Without a default, calls that need an account still require one.
Stream data
Every stream method ends in _stream, for example client.trade_stream(...).
- Open the stream with
async with. - Read frames with
async for. - Leave the
async withblock to unsubscribe.
async with client.orderbook_delta_stream(instrument="BTC_USDT_Perp", rate=500) as book: # rate: interval in ms
async for frame in book:
print(frame.sequence_number, frame.feed)
frame.sequence_number is a str, as on the wire. Convert it with int() before you compare it, for
example with a gap event's bounds, which are int.
Watch out:
- After a gap, older frames can still come first and missed private events aren't replayed (What happens after a gap).
- Each subscription queues up to 4096 frames (client option
queue_size, at least 1). If your code falls behind,.sstreams (every frame complete) drop their oldest frame and others raiseStreamOverflowout of yourasync for: catch it and loop again (stream errors).
Place an order
- Build an
OrderInputwithDecimalprice and size.is_buying_assetis true to buy, false to sell.GOOD_TILL_TIME(GTT) rests until filled, cancelled or expired;post_onlyrejects the order rather than let it trade at once (TimeInForce). - Call
create_order. The SDK fills in the signature and aclient_order_id, and looks up the instrument details it needs to sign. It works on a copy, so yourOrderInputis not changed. - Save the
client_order_id: you follow the order by it, because the reply'sorder_idis always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below).
import asyncio
import os
from decimal import Decimal
from grvt import AsyncGrvt, PrivateKeySigner, enums, models as m
async def main():
async with AsyncGrvt(
env="testnet",
api_key=os.environ["GRVT_API_KEY"],
signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]),
) as client:
order = m.OrderInput(
sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"],
time_in_force=enums.TimeInForce.GOOD_TILL_TIME,
post_only=True,
legs=[
m.OrderLeg(
instrument="BTC_USDT_Perp", size=Decimal("0.01"), limit_price=Decimal("60000"), is_buying_asset=True
)
],
)
resp = await client.create_order(order=order)
print(resp.result.metadata.client_order_id)
asyncio.run(main())
To choose the client_order_id yourself, set it before you send the order, following the
client order ID rules:
import secrets
order.metadata = m.OrderMetadataInput(client_order_id=str(2**63 | secrets.randbits(63)))
bulk_orders signs each order on its own, with its own nonce and expiration, by the same rules as
create_order. Both fill in a missing client_order_id on each order. Bulk calls and their models use
order_ids and client_order_ids; the SDK sends them as the server's order_i_ds and client_order_i_ds
JSON keys.
Orders go over HTTP by default. Pass order_transport="ws" to the client to send them over the trading
WebSocket instead.
Watch out:
- A reply means the exchange received the order, not that it rests on the book (What a create reply means).
- An order still open 24 hours after signing expires (Expiration).
- Sending the same
OrderInputagain places a second order, with a newclient_order_idunless you set one. - An order that breaks its instrument's limits raises
OrderOutOfBoundsand is not sent (Orders checked before sending).check_orders=Falseon the client turns the check off and leaves the limits to the exchange.
Sign with a wallet or KMS
PrivateKeySigner signs in your process. To sign with a hardware wallet or a key service (KMS) instead, pass
your own object as signer=. It needs:
- an
addressproperty: the signing wallet's address; - an async
sign_typed(domain, primary_type, message)method that returns agrvt.Signature(signer,r,s,v). If your backend wants EIP-712 typed data,primary_type.to_typed_data(domain, message)builds it.
The SDK checks every returned signature against its own digest, and raises SigningError unless:
randsare 32 bytes of hex andvis 27 or 28;sis low-s (Signing, step 5). Some KMS backends, AWS KMS for one, return a highs: replace it with n - s (n is the secp256k1 curve order) and flipvbetween 27 and 28;- the signature recovers to
address; - the
signerfield is empty or equal toaddress.
The SDK signs Grvt's own message types only; there is no API for custom EIP-712 types.
Track and cancel an order
Private streams need a client with an API key. order_stream sends every change to your orders, rejections
included; fill_stream sends each fill, with its trade ID and client order ID.
- Open
order_streambefore you place the order. - Match updates by
metadata.client_order_id. The updates also carry theorder_id. - Stop at a final status:
enums.OrderStatus.FILLED,REJECTEDorCANCELLED(order states). - To cancel, call
cancel_orderwithsub_account_idandclient_order_id(ororder_id), after the create has replied.
from grvt import enums
sub = os.environ["GRVT_SUB_ACCOUNT_ID"]
FINAL = {enums.OrderStatus.FILLED, enums.OrderStatus.REJECTED, enums.OrderStatus.CANCELLED}
async with client.order_stream(sub_account_id=sub) as orders:
resp = await client.create_order(order=order)
coid = resp.result.metadata.client_order_id
await client.cancel_order(sub_account_id=sub, client_order_id=coid)
async for frame in orders:
o = frame.feed
if o.metadata.client_order_id == coid and o.state and o.state.status in FINAL:
print(o.order_id, o.state.status, o.state.reject_reason)
break
Recover a lost order response
When: a write times out or the socket drops before the response arrives. The call raises
OrderStateUnknown. Look the order up with resolve_order; don't resend it. Steps and code:
When a write's outcome is unknown.
Recovery helpers
These are imports from grvt, not client methods. Blocking versions end in _sync.
from grvt import OrderBook, backfill_pages, refresh_cancel_countdown, resolve_order
| Helper | What it does |
|---|---|
resolve_order( | Looks up an order whose write outcome is unknown. It never resends. |
OrderBook( | Keeps a local book from order-book stream frames. |
backfill_pages( | Pages through REST history after a gap. Your callback picks the call and time window. |
refresh_cancel_countdown( | Arms or refreshes the cancel-on-disconnect countdown once (1 to 300 seconds). The SDK never does this for you. |
Your on_event hook gets the gap and session_rotated events they use. How to use them:
SDK helpers.
Errors
| Exception | When |
|---|---|
ApiError | the server answered with an error code; has code, message, status, rpc, retryable |
RateLimitError | code 1006 (HTTP 429); a subclass of ApiError; reads were already retried |
TransportError | no usable answer (connection failed, read timed out, socket closed); has rpc, and sent (whether the request may have left). A write that may have left raises OrderStateUnknown instead |
OrderStateUnknown | a write may or may not have happened; look it up by client_order_id (client_order_ids for a bulk call). The original failure is its __cause__ |
OrderOutOfBounds | an order breaks its instrument's limits; nothing was sent; has nearest and server_code |
StreamOverflow (stream, selector, capacity) | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced |
FrameTooLarge (size, limit) | a WebSocket request is bigger than Environment.; nothing was sent. The check is off unless you set that limit |
DecodeError | a response or stream frame did not match its type; the original error is its __cause__ |
SigningError, ConfigError, ClosedError | local problems: a request that can't be signed, a bad option or a missing signer or API key, a closed client. SigningError and ConfigError are also ValueError |
All of them extend GrvtError. A wrong argument type still raises TypeError.
Every error code also has its own class in grvt.api_errors. The full list is on
Error codes.
Hooks and logging
GRVT_LOG=debugprints every request and frame to stderr, with keys and signatures redacted.before_send=runs before each RPC is signed and may change the request. It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an unknown outcome: that fails with a config error before anything is sent.on_event=gets connection and stream events: connect, reconnect, gap, retry and more. Each event's details are attributes (ev.code,ev.attempt,ev.error, ...), set for its kind andNoneotherwise.frameevents carry the raw bytes sent and received, not redacted.
def on_event(ev):
if ev.kind.value == "gap":
print("re-syncing", ev.stream, ev.selector)
client = AsyncGrvt(env="testnet", on_event=on_event)
Data types
- Decimals use
decimal.Decimal. - Nanosecond timestamps use
grvt.Timestamp.to_datetime()gives a UTCdatetime, cut to the microsecond.Timestamp.from_datetime()needs adatetimewith a timezone. - IDs in models are strings. Top-level ID arguments accept
int | str. - Constructors and decoding reject a missing required field. Optional fields default to
None. Some list fields can beNoneinstead of empty: check before you iterate. - Signed requests use
Inputmodels, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield
Partialmodels: every feed field is optional. - Enums are generated string enums. A value added by a newer server decodes as an extra member, so give your
matcha default case. - Millisecond schedule fields stay plain integers.
- Response fields the SDK doesn't know are dropped.
Not supported yet
- Resuming a private stream from a sequence number. After a gap, fill missed events from history with
backfill_pages(Fill missed events from history). - Logging in again after a WebSocket auth failure. A subscribe rejected for auth raises to your code. A rejected handshake (401/403) or a failed API-key login stops the socket reconnecting for good.
- Keeping streams open across session renewal. Renewal reconnects every socket, so every stream gets a gap (Session renewal).
- Ordered requests on one WebSocket. The server can process a cancel before its create; wait for the create's reply (Calling RPCs over WebSocket).
- Wallet login. The client manages API-key sessions only.
- Keeping response fields the SDK doesn't know. A field the server adds after your SDK version is dropped when the reply is decoded. Update the SDK to read it.