---
title: "Rust SDK"
description: "Add the grvt crate, build a client, call any RPC with builders, stream data, place signed orders and handle errors."
order: 23
llms: trading, market-data, account
---

> [!WARNING]
> **Preview.** Any 0.x release can change the API. [Install](#install) says what to pin.

The Rust SDK has a method for every call and stream in the [API reference](../reference/index.md), 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](#without-the-client).

New here? [Install](#install) the SDK and run the [Quickstart](../guides/quickstart.md), then read this page
down to
[Track and cancel an order](#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:

```sh
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](#without-the-client), add `--no-default-features` to the first
`cargo add` and skip `tokio` and `futures`.

## Create a client

```rust
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](../guides/environments.md)).
- The client sends short (lite) field names on the wire by default; your code still uses the full names.
  `.encoding(grvt::Encoding::Full)` on the `Config` switches to full names
  ([Encoding](../guides/environments.md#encoding-full-or-lite)).
- The client logs in on the first private call and renews the session before it expires
  ([Authentication](../guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream
  gets a gap ([Session renewal](../guides/websocket.md#session-renewal)).
- To stop, follow [Shut down cleanly](../guides/websocket.md#shut-down-cleanly).

## Call an RPC

Every call is a method on the client, `client.<method>()`, named exactly as on its reference page.

1. Call the method to get a request builder.
2. Set request fields with setters named like the wire fields.
3. `.await` the builder to send it.

```rust
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](../guides/errors-and-retries.md#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_timeout` covers the whole call (login, metadata, signing, retries and the response);
  `.http_attempt_timeout` caps 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.

```rust
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; in
  `OrderInput`, `None` does.
- 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()`.

1. Build the stream like any call and `.await` it. You get a `Subscription`, which is a `futures::Stream`.
2. Read frames with `next().await`.
3. Drop the subscription to unsubscribe.

```rust
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](../guides/recovery.md#what-happens-after-a-gap)).
- Each subscription queues up to 4096 frames, at least 1 (`.queue_size(...)` on the `Config`). If your code falls behind,
  [`.s` streams](../guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest
  frame and others yield `Err(Error::StreamOverflow { .. })`
  ([stream errors](../guides/websocket.md#read-a-stream)). Handle the `Err` and keep reading; `frame?` would
  stop your loop.

## Place an order

1. Build each input model with `Type::new(required_fields...)`, then add optional values with the typed
   `with_*` setters. `is_buying_asset` is 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](../reference/enums.md)).
2. Call `create_order`. The SDK fills in the signature and a `client_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 keep
   `order` for later.
3. Save the `client_order_id`: you follow the order by it, because the reply's `order_id` is 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).

```rust
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](../guides/signing.md#rules-that-cause-most-rejections). This example draws the random
bits from the standard library:

```rust
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](../guides/errors-and-retries.md#what-a-create-reply-means)).
- An order still open 24 hours after signing expires ([Expiration](../guides/signing.md#rules-that-cause-most-rejections)).
- Sending a clone of the same order places a second order, with a new `client_order_id` unless you set one.
- An order that breaks its instrument's limits returns `Error::OrderOutOfBounds` and is not sent
  ([Orders checked before sending](../guides/errors-and-retries.md#orders-checked-before-sending)).
  `.check_orders(false)` on the `Config` turns 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.

1. Open `order_stream` before you place the order.
2. Match updates by `metadata.client_order_id`. The updates also carry the `order_id`.
3. Stop at a final status: `OrderStatus::Filled`, `Rejected` or `Cancelled`
   ([order states](../guides/errors-and-retries.md#what-a-create-reply-means)).
4. To cancel, call `cancel_order` with `sub_account_id` and `client_order_id` (or `order_id`), after the
   create has replied.

```rust
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](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown).

## Recovery helpers

These are items in the `grvt` crate, not client methods. Pass the client in where they need it.

```rust
use grvt::{backfill_pages, refresh_cancel_countdown, resolve_order, OrderBook};
```

| Helper | What it does |
|---|---|
| `grvt::resolve_order(&client, sub_account_id, client_order_id)` | Looks up an order whose write outcome is unknown. It never resends. |
| `grvt::OrderBook::new(instrument, grvt::BookMode::Delta)` | Keeps a local book from order-book stream frames. |
| `grvt::backfill_pages(fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. |
| `grvt::refresh_cancel_countdown(&client, sub_account_id, seconds)` | Arms or refreshes the [cancel-on-disconnect countdown](../guides/websocket.md#cancel-orders-if-your-app-stops) 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](../guides/recovery.md#sdk-helpers).

## Errors

Every error is one enum, `grvt::Error`:

| Variant | When |
|---|---|
| `Api { code, message, status, rpc, retryable }` | the server answered with an error code |
| `RateLimit { message, status, rpc }` | code `1006` (HTTP 429); `err.code()` returns `Some(1006)`; reads were already retried |
| `Transport { message, rpc, sent }` | 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, client_order_ids, .. }` | 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, selector, capacity }` | 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](../reference/errors.md).

## Hooks and logging

- `GRVT_LOG=debug` logs every request and frame through `tracing` (target `grvt`), with the cookie, API key,
  private keys and signatures redacted. If your app has no `tracing` subscriber, the SDK installs one that
  writes to stderr. With lite encoding, wire logs and raw `Event::Frame` bytes show the short field names.
- `.before_send(|call| ...)` on the `Config` is a plain (not async) closure. It runs before each RPC is signed
  and may change `call.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](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config
  error before anything is sent.
- `.on_event(|ev| ...)` gets connection and stream events: connect, reconnect, gap, retry and more.

```rust
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::Timestamp` over `i64`.
- IDs are `u64`.
- Required fields use plain values. Optional and nullable fields use `Option`; set one to `None` to clear it.
  Decoding rejects a missing required key, even a nullable one.
- Signed requests use `Input` models, so the SDK can fill in signatures and metadata.
- Ticker and mini-ticker delta streams yield `Partial` models: 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 as `Unknown(String)`.
- `Default` on a model is for test fixtures; it doesn't make a valid request. Build requests with
  `Type::new(required_fields...)` or the client's call builder, which checks required fields before sending.
- Bulk order models use `order_ids` and `client_order_ids`; on the wire they are `order_i_ds` and
  `client_order_i_ds`.
- Millisecond schedule fields stay plain integers.

## Without the client

**Advanced.** With default features turned off ([Install](#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`):

```rust
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. `metadata` holds the instruments and currencies that `signing::needs_<call>`
  names, loaded once. `signing::instrument_meta` turns a `get_instrument` reply into it. `SignContext` also
  takes an optional clock and nonce source (by default the system clock and the OS random source), turns order
  checks on or off, and with `recover_signer` checks each signature against the signer's address (about the
  cost of one more signature).
- **Bulk orders.** `signing::digests_order_bulk_orders` returns one digest per order, so you can sign on
  any thread or in a key management service (KMS). `attach_order_bulk_orders` checks each signature against its own order before
  writing it in.
- **Wallet signers** implement `grvt::SyncSigner` and read `SigningRequest::typed_data()`.
- **Lost answers.** If a write's reply never comes, `grvt::transport_failure(ops::CreateOrder::SPEC, sent,
  why, ids)` gives you `OrderStateUnknown`. Look the order up with `grvt::resolve_order_request` and
  `grvt::resolve_order_result`
  ([When a write's outcome is unknown](../guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). `grvt::may_retry` says whether a failed read may be sent
  again.
- **WebSocket.** `grvt::ws_request::<Op>(&req, id)` builds the JSON-RPC frame; `grvt::ws_request_into` and
  `grvt::encode_request_into` write into a buffer you keep. `grvt::parse_ws_message`
  reads a frame once. Route replies by `id` (`grvt::RequestTable`) and stream frames by stream and
  selector, run `grvt::Sequencer::on_frame`, then `grvt::decode_feed::<ops::OrderbookDeltaStream>(&msg)`
  decodes only the payload. `grvt::subscribe_frame` and `grvt::parse_subscribe_result` handle
  subscriptions; `grvt::Backoff` paces reconnects.
- **Session.** `grvt::api_key_login_request(&env, api_key)` is the login request, and
  `SessionState::on_login_response` reads the reply. `session.headers()` gives the headers to send and
  `session.refresh_due()` says when to renew. Log in again when `!session.fresh(now)`.
- **Lite encoding.** Call the same functions on `grvt::Encoding::Lite`, for example
  `Encoding::Lite.rest_request::<Op>(..)`, `.ws_request::<Op>(..)`, `.parse_ws_message(..)` and
  `.subscribe_frame(..)`. `ws_response` and `decode_feed` follow the parsed message's encoding.
  `Environment::ws_url_for(gateway, Encoding::Lite)` gives the lite URL; it swaps `/ws/full` for `/ws/lite`, so
  a custom `Environment` needs WebSocket URLs ending in `/ws/full`.
- **Recovery steps.** `grvt::cancel_countdown_request`, `grvt::backfill_status`, `grvt::PageCursor` and
  `OrderBook::on_gap` are the no-I/O parts of the [recovery helpers](#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](../guides/recovery.md#fill-missed-events-from-history)).
- **Wallet session login.** Log in with an API key (`.api_key(...)` on the `Config`).
- **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](#without-the-client).
