Developers

TypeScript SDK

Install the grvt package, create a client, call any RPC, stream data, place signed orders and handle errors, in Node and the browser.

On this page

Preview. Any 0.x release can change the API. Install says what to pin.

The TypeScript 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). It runs on Node.js 24+ and in modern browsers.

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

Not on the npm registry yet. Install it from its public GitHub repository; npm builds it during the install. It needs Node.js 24 or newer.

npm install github:gravity-technologies/grvt-sdk-typescript

Then import it as grvt. The repository has no version tags yet and its main branch moves, so pin the commit you tested: npm install github:gravity-technologies/grvt-sdk-typescript#<commit> (your package-lock.json also records the exact commit).

With other package managers, pin the commit too:

  • yarn 1 installs and builds it.

  • pnpm (tested with pnpm 12) stops with ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED, because the package builds itself on install. Allow that build in your project's pnpm-workspace.yaml, keyed by the package's exact Git address and commit; a wildcard such as grvt@* is not accepted:

    allowBuilds:
      "grvt@<git URL>#<commit>": true
  • bun hasn't been tested.

Create a client

import { Grvt, PrivateKeySigner } from "grvt";

// The API key logs in; the signer signs orders with your signing key. Leave both out for public data only.
const client = new Grvt({
  env: "testnet",
  apiKey: process.env.GRVT_API_KEY,
  signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!),
});
const t = await client.ticker({ instrument: "BTC_USDT_Perp" });
console.log(t.result.mark_price); // the exchange's fair price, used for margin
await client.close();
  • env is "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.

Watch out: in the browser, only public calls and streams work. Anything that needs a session (private calls and streams, orders) is Node-only for now: browsers don't let code read the login cookie or send it on a WebSocket.

Call an RPC

Every call is a method on the client, client.<method>(request). Method names are the reference page's name in camelCase, with no exceptions: create_order is client.createOrder, trade_stream is client.tradeStream. Request and response fields stay snake_case, exactly as on the reference pages (for example mark_price), because they are the JSON sent and received.

const inst = await client.getInstrument({ instrument: "BTC_USDT_Perp" });
console.log(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 milliseconds: callTimeoutMs (30000), httpAttemptTimeoutMs (10000), wsRequestTimeoutMs (5000), resyncTimeoutMs (5000), idleTimeoutMs (30000). callTimeoutMs covers the whole call: login, instrument lookup, signing, retries and the reply. httpAttemptTimeoutMs caps each HTTP attempt within what is left of it. For one call, pass { timeoutMs } as the second argument; an earlier abort signal there still wins.

Pagination

History calls return one page and a next cursor. pages follows the cursors, fetching the next page only when your loop asks for it. Put the filters and call options in the callback.

import { pages } from "grvt";

for await (const page of pages((cursor) => client.tradeHistory({ instrument: "BTC_USDT_Perp", cursor }))) {
  for (const trade of page.result ?? []) console.log(trade);
}
  • An empty page can still have a next cursor. Breaking out of the loop stops further calls.
  • A repeated cursor throws PaginationCycle. Fetch errors pass through, with no extra retries.
  • Cursors are not a stable snapshot: records can change while you page.

Default sub-account

Pass subAccountId: "123" to new Grvt to fill in sub_account_id wherever a request or stream leaves it out.

  • An ID you pass explicitly wins.
  • An order in bulkOrders takes 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.tradeStream.

  1. Call the stream method to get a subscription.
  2. Read frames with for await.
  3. Break out of the loop or call close() to unsubscribe.
// rate: update interval in ms
for await (const frame of client.orderbookDeltaStream({ instrument: "BTC_USDT_Perp", rate: 500 })) {
  console.log(frame.sequence_number, frame.feed);
}

frame.sequence_number is a string, as on the wire, and so are a gap event's bounds. Compare them as BigInt(...), not as strings.

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 queueSize, at least 1). If your code falls behind, .s streams (every frame complete) drop their oldest frame and others throw StreamOverflow out of your for await: catch it and loop again (stream errors).

Place an order

  1. Build a models.OrderInput with Decimal price and size. is_buying_asset is true to buy, false to sell. GOOD_TILL_TIME (GTT) rests until filled, cancelled or expired; post_only rejects the order rather than let it trade at once (TimeInForce).
  2. Call createOrder. The SDK fills in the signature and a client_order_id, and looks up the instrument details it needs to sign. It works on a copy, so your order object is not changed.
  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).
import { Decimal, Grvt, PrivateKeySigner, type models } from "grvt";

const client = new Grvt({
  env: "testnet",
  apiKey: process.env.GRVT_API_KEY,
  signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!),
});
const order: models.OrderInput = {
  sub_account_id: process.env.GRVT_SUB_ACCOUNT_ID!,
  time_in_force: "GOOD_TILL_TIME",
  post_only: true,
  legs: [{ instrument: "BTC_USDT_Perp", size: new Decimal("0.01"), limit_price: new Decimal("60000"), is_buying_asset: true }],
};
const resp = await client.createOrder({ order });
console.log(resp.result.metadata.client_order_id);
await client.close();

To choose the client_order_id yourself, set it before you send the order, following the client order ID rules:

order.metadata = { client_order_id: (2n ** 63n | crypto.getRandomValues(new BigUint64Array(1))[0]!).toString() };

Orders go over HTTP by default. Pass orderTransport: "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 order again places a second order, with a new client_order_id unless you set one.
  • An order that breaks its instrument's limits throws OrderOutOfBounds and is not sent (Orders checked before sending). If the exchange still rejects an order for these limits, the SDK drops its cached instrument details and fetches them again for the next order. checkOrders: false on the client turns the check off.

Sign with a wallet or KMS

PrivateKeySigner keeps the key in your process. To sign elsewhere (a wallet, or a key management service (KMS) such as AWS KMS), pass your own Signer: an object with address (lowercase 0x address) and signTyped(domain, type, message). Inside it, type.toTypedData(domain, message) gives the JSON to hand to eth_signTypedData_v4. Return { signer, r, s, v }.

The SDK checks every signature it gets back and throws SigningError unless:

  • r and s are 32 bytes of 0x hex and v is 27 or 28;
  • s is low-s (Signing). Some KMS backends return a high s: replace it with n - s and flip v;
  • it recovers to signer.address, and its signer field is empty or equal to it.

Track and cancel an order

Private streams need a client with an API key. orderStream sends every change to your orders, rejections included; fillStream sends each fill, with its trade ID and client order ID.

  1. Open orderStream and await its subscribe() 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: "FILLED", "REJECTED" or "CANCELLED" (order states).
  4. To cancel, call cancelOrder with sub_account_id and client_order_id (or order_id), after the create has replied.
const sub = process.env.GRVT_SUB_ACCOUNT_ID!;
const orders = await client.orderStream({ sub_account_id: sub }).subscribe();
const resp = await client.createOrder({ order });
const id = resp.result.metadata.client_order_id;
await client.cancelOrder({ sub_account_id: sub, client_order_id: id });
for await (const { feed } of orders) {
  const status = feed.state?.status;
  if (feed.metadata.client_order_id !== id) continue;
  if (status === "FILLED" || status === "REJECTED" || status === "CANCELLED") {
    console.log(feed.order_id, status, feed.state?.reject_reason);
    break; // leaving the loop unsubscribes
  }
}

Recover a lost order response

When: a write times out or the socket drops before the response arrives. The call throws OrderStateUnknown. Look the order up with resolveOrder; don't resend it. Steps and code: When a write's outcome is unknown.

Recovery helpers

These are imports from grvt, not client methods.

import { OrderBook, backfillPages, refreshCancelCountdown, resolveOrder } from "grvt";
HelperWhat it does
resolveOrder(client, { sub_account_id, client_order_id })Looks up an order whose write outcome is unknown. It never resends.
new OrderBook(instrument)Keeps a local book from order-book stream frames.
backfillPages(fetch, gap)Pages through REST history after a gap. Your callback picks the call and time window.
refreshCancelCountdown(client, subAccountId, seconds)Arms or refreshes the cancel-on-disconnect countdown once (1 to 300 seconds). The SDK never does this for you.

Your onEvent hook gets the gap and session_rotated events they use. How to use them: SDK helpers.

Errors

ClassWhen
ApiErrorthe server answered with an error code; has code, serverMessage (message is the full text), status, rpc, retryable
RateLimitErrorcode 1006 (HTTP 429); a subclass of ApiError; reads were already retried
TransportErrorno 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 throws OrderStateUnknown instead
OrderStateUnknowna write may or may not have happened; look it up by clientOrderId (clientOrderIds for a bulk call). The original failure is its cause
OrderOutOfBoundsan order breaks its instrument's limits; nothing was sent; has nearest and serverCode
StreamOverflowyour code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced
SigningError, DecodeError, ConfigError, FrameTooLarge, ClosedErrorlocal problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed

All of them extend GrvtError. Error code constants are in ErrorCode. The full list is on Error codes.

Hooks and logging

  • GRVT_LOG=debug logs every request and frame to stderr, with keys and signatures redacted. setLogLevel() changes the level at runtime.
  • beforeSend runs before each RPC is signed and may change call.params (or return new params). It sees the wire names: bulk order fields order_ids and client_order_ids appear as order_i_ds and client_order_i_ds. 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.
  • onEvent gets typed events: connect, disconnect, reconnect, subscribe, gap, retry, frame, session_rotated and error. Keep it fast.
const client = new Grvt({
  env: "testnet",
  onEvent: (e) => { if (e.type === "gap") console.warn("re-syncing", e.stream, e.selector); },
});

Data types

  • Decimals use the SDK's Decimal wrapper. It checks for exact text and needs no arithmetic library. A value with more decimal places than the field allows throws SigningError; nothing is rounded.
  • Nanosecond timestamps use Timestamp over bigint. toDate() drops sub-millisecond precision.
  • IDs are strings.
  • Optional fields can be missing (undefined). Some list fields can be null instead of empty: check before you iterate.
  • 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.
  • Enum types accept any string. A value added by a newer server arrives as its plain string, so give your switch a default branch.
  • Millisecond schedule fields stay plain integers.

Not supported yet

  • Resuming a private stream from a sequence number. After a gap, fill missed events from history with backfillPages (Fill missed events from history).
  • Private calls, private streams and orders in the browser. Meanwhile, make them from a Node server and use the browser for public data (Create a client).
  • Logging in with a wallet. The client logs in with an API key only.
  • A client heartbeat. The global WebSocket has no ping API. On Node 24 and later the SDK still sees the server's pings, so a connection silent for idleTimeoutMs is dropped and reconnected. In browsers it can't tell a quiet connection from a dead one, so a dead one is noticed only when TCP gives up. A custom webSocket factory that sees ping frames can call the socket's onheartbeat to turn the check on.
  • Telling a rejected WebSocket handshake from a network error. The global WebSocket hides the HTTP status, so a 401 or 403 is retried with backoff. A custom webSocket factory that knows the status can set status on the close event to stop for good.
esc

↑ ↓ move↵ open⇧↵ open .mdTry an error code like 2002

Keyboard shortcuts

⌘ K
Search the docs
/
Search
l
Next code language (Python → TypeScript → Go → Rust → curl → WebSocket)
j / k
Next / previous page
t
Light / dark theme
?
This help
Esc
Close dialogs and drawers