Rust SDK
Add the grvt crate, build a client, call any RPC with builders, stream data, place signed orders and handle errors.
On this page
Help me with: Rust SDK. Add the grvt crate, build a client, call any RPC with builders, 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/rust.md (~33 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. Install says what to pin.
The Rust SDK has a method for every call and stream in the API reference, named as there. 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). Its client is async (tokio). If your engine runs its own sockets and event loop, use the crate without the client.
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 crate is grvt on crates.io and needs Rust 1.88 or newer. Add it with its async dependencies and
rust_decimal, which the SDK uses for prices and sizes:
cargo add grvt
cargo add tokio --features full
cargo add futures
cargo add rust_decimal
In preview, any 0.x release can change the API, so pin an exact version: change the grvt line in
Cargo.toml to an = requirement (grvt = "=<version>").
For the crate without the client, add --no-default-features to the first
cargo add and skip tokio and futures.
Create a client
use grvt::{Config, Grvt, PrivateKeySigner};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// The API key logs in; the signer signs orders with your signing key. Leave both out for public data only.
let client = Grvt::new(
Config::testnet()
.api_key(std::env::var("GRVT_API_KEY")?)
.signer(PrivateKeySigner::new(&std::env::var("GRVT_PRIVATE_KEY")?)?),
)?;
let t = client.ticker().instrument("BTC_USDT_Perp").await?;
println!("{:?}", t.result.mark_price); // the exchange's fair price, used for margin
client.close().await;
Ok(())
}
- Use
Config::prod()for production (Environments). - The client sends short (lite) field names on the wire by default; your code still uses the full names.
.encoding(grvt::Encoding::Full)on theConfigswitches 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.
Call an RPC
Every call is a method on the client, client.<method>(), named exactly as on its reference page.
- Call the method to get a request builder.
- Set request fields with setters named like the wire fields.
.awaitthe builder to send it.
let inst = client.get_instrument().instrument("BTC_USDT_Perp").await?;
println!("{:?}", inst.result);
If you leave out a required field, you get an error before anything is signed or sent.
- Reads are tried up to 3 times; writes are sent once (What the SDK retries).
- Timeouts, on the
Config:.call_timeout(...)(30 s),.http_attempt_timeout(...)(10 s),.ws_request_timeout(...)(5 s),.resync_timeout(...)(5 s),.idle_timeout(...)(30 s). For one call, add.timeout(...)to its builder..call_timeoutcovers the whole call (login, metadata, signing, retries and the response);.http_attempt_timeoutcaps each HTTP attempt within what is left of it. - To send a complete request instead of setting fields one by one, use
.with_request(req)on the builder.
Pagination
grvt::pages follows cursors one page at a time, only as you read. Keep the filters fixed inside the callback.
use futures::{pin_mut, StreamExt};
use grvt::pages;
let history = pages(|cursor| {
let mut call = client.trade_history().instrument("BTC_USDT_Perp");
if let Some(cursor) = cursor { call = call.cursor(cursor); }
async move { call.await }
}, None);
pin_mut!(history);
while let Some(page) = history.next().await {
for trade in page?.result.unwrap_or_default() { println!("{trade:?}"); }
}
- An empty page can still have a next cursor.
- Dropping the stream stops further calls.
- A cursor seen twice returns
Error::PaginationCycle. Fetch errors pass through, with no extra retries. - Cursors don't promise a stable snapshot while records change.
Default sub-account
Config::testnet().sub_account_id(123) fills in omitted account IDs on requests and streams.
- An ID you set yourself wins. In a request passed to
.with_request, a zero account counts as omitted; inOrderInput,Nonedoes. - Bulk orders take the request's account first, then the client default.
- Transfer source and destination IDs are never filled in.
- The default is applied before signing. Without one, calls that need an account still require it.
Stream data
Every stream method ends in _stream, for example client.trade_stream().
- Build the stream like any call and
.awaitit. You get aSubscription, which is afutures::Stream. - Read frames with
next().await. - Drop the subscription to unsubscribe.
use futures::StreamExt;
let mut book = client.orderbook_delta_stream().instrument("BTC_USDT_Perp").rate(500).await?; // rate: interval in ms
while let Some(frame) = book.next().await {
match frame {
Ok(frame) => println!("{:?} {:?}", frame.sequence_number, frame.feed),
Err(e) => eprintln!("{e}"), // the subscription carries on; it ends with None
}
}
frame.sequence_number is a u64. It is a string on the wire; the SDK decodes it for you. A gap event's
bounds are Option<u64>.
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, at least 1 (
.queue_size(...)on theConfig). If your code falls behind,.sstreams (every frame complete) drop their oldest frame and others yieldErr(Error::StreamOverflow { .. })(stream errors). Handle theErrand keep reading;frame?would stop your loop.
Place an order
- Build each input model with
Type::new(required_fields...), then add optional values with the typedwith_*setters.is_buying_assetis true to buy, false to sell.TimeInForce::GoodTillTime(GTT) rests until filled, cancelled or expired;with_post_only(true)rejects 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..order(...)takes the order by value, so the example sends a clone to keeporderfor later. - 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).
use grvt::{enums::TimeInForce, models as m, Config, Grvt, PrivateKeySigner};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Grvt::new(
Config::testnet()
.api_key(std::env::var("GRVT_API_KEY")?)
.signer(PrivateKeySigner::new(&std::env::var("GRVT_PRIVATE_KEY")?)?),
)?;
let is_buying_asset = true;
let leg = m::OrderLeg::new("BTC_USDT_Perp", Decimal::new(1, 2), is_buying_asset) // size 0.01
.with_limit_price(Decimal::from(60000));
let sub: u64 = std::env::var("GRVT_SUB_ACCOUNT_ID")?.parse()?;
let order = m::OrderInput::new(TimeInForce::GoodTillTime, Some(vec![leg]))
.with_sub_account_id(sub)
.with_post_only(true);
let resp = client.create_order().order(order.clone()).await?;
println!("{}", resp.result.metadata.client_order_id);
client.close().await;
Ok(())
}
To choose the client_order_id yourself, set it before you send the order, following the
client order ID rules. This example draws the random
bits from the standard library:
use std::hash::{BuildHasher, RandomState};
let id = 1 << 63 | RandomState::new().hash_one(());
let order = order.with_metadata(m::OrderMetadataInput::new().with_client_order_id(id));
Orders go over HTTP by default. Use .order_transport(grvt::OrderTransport::Ws) on the Config 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 a clone of the same order places a second order, with a new
client_order_idunless you set one. - An order that breaks its instrument's limits returns
Error::OrderOutOfBoundsand is not sent (Orders checked before sending)..check_orders(false)on theConfigturns the check off and leaves the limits to the exchange.
To sign without sending, call client.sign_<call>(req).await, for example
client.sign_order_create_order(req). It signs the way the RPC method does and returns the signed request.
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:
OrderStatus::Filled,RejectedorCancelled(order states). - To cancel, call
cancel_orderwithsub_account_idandclient_order_id(ororder_id), after the create has replied.
use futures::StreamExt;
use grvt::enums::OrderStatus;
let mut orders = client.order_stream().sub_account_id(sub).await?;
let resp = client.create_order().order(order).await?;
let id = resp.result.metadata.client_order_id;
client.cancel_order().sub_account_id(sub).client_order_id(id).await?;
while let Some(frame) = orders.next().await {
let Ok(frame) = frame else { continue };
let Some(state) = frame.feed.state.filter(|_| frame.feed.metadata.client_order_id == id) else { continue };
if matches!(state.status, OrderStatus::Filled | OrderStatus::Rejected | OrderStatus::Cancelled) {
println!("{:?} {:?} {:?}", frame.feed.order_id, state.status, state.reject_reason);
break; // dropping `orders` unsubscribes
}
}
Recover a lost order response
When: a write times out or the socket drops before the response arrives. You get
Error::OrderStateUnknown. Look the order up with grvt::resolve_order; don't resend it. Steps and code:
When a write's outcome is unknown.
Recovery helpers
These are items in the grvt crate, not client methods. Pass the client in where they need it.
use grvt::{backfill_pages, refresh_cancel_countdown, resolve_order, OrderBook};
| Helper | What it does |
|---|---|
grvt::resolve_order( | Looks up an order whose write outcome is unknown. It never resends. |
grvt::OrderBook::new( | Keeps a local book from order-book stream frames. |
grvt::backfill_pages( | Pages through REST history after a gap. Your callback picks the call and time window. |
grvt::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 Event::Gap and Event::SessionRotated events they use. How to use
them: SDK helpers.
Errors
Every error is one enum, grvt::Error:
| Variant | When |
|---|---|
Api { code, | the server answered with an error code |
RateLimit { message, | code 1006 (HTTP 429); err.code() returns Some(1006); reads were already retried |
Transport { message, | no usable answer (connection failed, read timed out, socket closed); sent says whether the request may have left. A write that may have left returns OrderStateUnknown instead |
OrderStateUnknown { client_order_id, | a write may or may not have happened; look it up (client_order_ids for a bulk call). The original failure is its source() |
OrderOutOfBounds( | an order breaks its instrument's limits; nothing was sent; has nearest and server_code |
StreamOverflow { stream, | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced |
Signing, Decode, Config, FrameTooLarge, Closed | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed |
Error code constants are in grvt::error_codes. The full list is on Error codes.
Hooks and logging
GRVT_LOG=debuglogs every request and frame throughtracing(targetgrvt), with the cookie, API key, private keys and signatures redacted. If your app has notracingsubscriber, the SDK installs one that writes to stderr. With lite encoding, wire logs and rawEvent::Framebytes show the short field names..before_send(|call| ...)on theConfigis a plain (not async) closure. It runs before each RPC is signed and may changecall.params(the request as JSON). 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(|ev| ...)gets connection and stream events: connect, reconnect, gap, retry and more.
let config = Config::testnet().on_event(|ev| {
if let grvt::Event::Gap { stream, selector, .. } = ev {
eprintln!("re-syncing {stream} {selector}");
}
});
Data types
- Decimals use
rust_decimal::Decimal. Values with too many decimal places are rejected, not rounded. - Nanosecond timestamps use
grvt::Timestampoveri64. - IDs are
u64. - Required fields use plain values. Optional and nullable fields use
Option; set one toNoneto clear it. Decoding rejects a missing required key, even a nullable one. - 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. - Models and enums are non-exhaustive. Use the typed
with_*setters, and add a wildcard arm when you match a generated enum. A value added by a newer server arrives asUnknown(String). Defaulton a model is for test fixtures; it doesn't make a valid request. Build requests withType::new(required_fields...)or the client's call builder, which checks required fields before sending.- Bulk order models use
order_idsandclient_order_ids; on the wire they areorder_i_dsandclient_order_i_ds. - Millisecond schedule fields stay plain integers.
Without the client
Advanced. With default features turned off (Install), the crate has no client and no I/O: no tokio, no HTTP or WebSocket library. It builds every request as plain data, signs it, and reads the replies and stream frames you hand back. Your code owns the sockets, threads and timers.
Every call and stream has a descriptor in grvt::ops, named like the client method (ops::CreateOrder,
ops::OrderbookDeltaStream):
use grvt::{models as m, ops, signing, Environment, RequestDefaults, RpcOp, SignContext};
let env = Environment::testnet();
let defaults = RequestDefaults { sub_account_id: Some(sub_account_id), client_order_ids: None };
let ids = grvt::prepare_request(ops::CreateOrder::SPEC, &mut req, &defaults)?; // fills client_order_id
signing::sign_order_create_order(&mut req, &SignContext::new(&key, &metadata, env.chain_id))?;
let http = grvt::rest_request::<ops::CreateOrder>(&env, &req, Some(&session))?; // method, url, headers, body
let (status, body) = send(&http); // send: your HTTP client
let reply = grvt::rest_response::<ops::CreateOrder>(status, &body, &ids);
- Signing is synchronous.
metadataholds the instruments and currencies thatsigning::needs_<call>names, loaded once.signing::instrument_metaturns aget_instrumentreply into it.SignContextalso takes an optional clock and nonce source (by default the system clock and the OS random source), turns order checks on or off, and withrecover_signerchecks each signature against the signer's address (about the cost of one more signature). - Bulk orders.
signing::digests_order_bulk_ordersreturns one digest per order, so you can sign on any thread or in a key management service (KMS).attach_order_bulk_orderschecks each signature against its own order before writing it in. - Wallet signers implement
grvt::SyncSignerand readSigningRequest::typed_data(). - Lost answers. If a write's reply never comes,
grvt::transport_failure(ops::CreateOrder::SPEC, sent, why, ids)gives youOrderStateUnknown. Look the order up withgrvt::resolve_order_requestandgrvt::resolve_order_result(When a write's outcome is unknown).grvt::may_retrysays whether a failed read may be sent again. - WebSocket.
grvt::ws_request::<Op>(&req, id)builds the JSON-RPC frame;grvt::ws_request_intoandgrvt::encode_request_intowrite into a buffer you keep.grvt::parse_ws_messagereads a frame once. Route replies byid(grvt::RequestTable) and stream frames by stream and selector, rungrvt::Sequencer::on_frame, thengrvt::decode_feed::<ops::OrderbookDeltaStream>(&msg)decodes only the payload.grvt::subscribe_frameandgrvt::parse_subscribe_resulthandle subscriptions;grvt::Backoffpaces reconnects. - Session.
grvt::api_key_login_request(&env, api_key)is the login request, andSessionState::on_login_responsereads the reply.session.headers()gives the headers to send andsession.refresh_due()says when to renew. Log in again when!session.fresh(now). - Lite encoding. Call the same functions on
grvt::Encoding::Lite, for exampleEncoding::Lite.rest_request::<Op>(..),.ws_request::<Op>(..),.parse_ws_message(..)and.subscribe_frame(..).ws_responseanddecode_feedfollow the parsed message's encoding.Environment::ws_url_for(gateway, Encoding::Lite)gives the lite URL; it swaps/ws/fullfor/ws/lite, so a customEnvironmentneeds WebSocket URLs ending in/ws/full. - Recovery steps.
grvt::cancel_countdown_request,grvt::backfill_status,grvt::PageCursorandOrderBook::on_gapare the no-I/O parts of the recovery helpers.
The crate's examples/order_and_subscribe.rs runs an order and an order-book subscription this way against a
fake transport.
Not supported yet
- Resuming a private stream from a sequence number. After a gap, fill missed events from history with
grvt::backfill_pages(Fill missed events from history). - Wallet session login. Log in with an API key (
.api_key(...)on theConfig). - A blocking client. Meanwhile, call the client from async code (for example inside a tokio runtime's
block_on), or use the crate without the client.