# Grvt API — market data: instruments, tickers, order books, trades, candles, public streams Generated from contract.json (contract 0.1.0). Pages are separated by `=====` lines; each starts with its path. Links are site paths: fetch them from the host that served this file. ===== index.md # Overview Grvt is a crypto derivatives exchange. Its API lets you read market data, trade and move funds, with an SDK (Python, TypeScript, Go or Rust) or with plain HTTP and WebSocket calls. > [!WARNING] > **Preview.** The SDKs are in preview: any 0.x release can change them. The HTTP and WebSocket API is not > affected. ## Start here To place your first order on testnet (the test exchange, with free funds): 1. Install the SDK from your SDK's page ([Python](/sdks/python.md), [TypeScript](/sdks/typescript.md), [Go](/sdks/go.md), [Rust](/sdks/rust.md)), then run the [Quickstart](/guides/quickstart.md): one example reads market data, then one places and cancels an order. 2. Back on your SDK's page: create a client, then place, track and cancel an order. 3. [Errors and retries](/guides/errors-and-retries.md): what to do when a call fails, above all when you don't know whether an order was placed. Read these when you need them: [Environments](/guides/environments.md) (testnet or production), [Authentication](/guides/authentication.md), [Accounts and permissions](/guides/accounts.md) and [Rate limits](/guides/rate-limits.md). **Advanced:** [WebSocket](/guides/websocket.md) protocol details, [Recovery recipes](/guides/recovery.md), [Signing](/guides/signing.md) by hand, and the [C++ signing core and reference](/sdks/cpp.md): C++ has no client, so your app handles networking, sessions, streams and recovery itself. **Topics:** [Strategies](/guides/strategies.md), [Stable funding perps (SFP)](/guides/stable-perps.md), [Builders](/guides/builders.md), [Deposits and withdrawals](/guides/deposits-and-withdrawals.md) and [Referrals](/guides/referrals.md). Other ways in: - Writing code with an AI agent: give it [Notes for coding agents](/AGENTS.md) and [llms.txt](/llms.txt). - Looking for a call: [All calls](/reference/index.md) lists every RPC and stream. - Trading several exchanges through one library: [CCXT](https://docs.ccxt.com/#/exchanges/grvt) supports Grvt. - Questions about your account or the Grvt web app: the [Help Center](https://help.grvt.io/en/). ## Glossary | Term | What it is | |---|---| | Main account | Your account on Grvt, identified by a `0x` address (`main_account_id`). Deposits arrive here and withdrawals leave from here; it does not trade. The Grvt web app calls it the **Funding Account**, and some calls say "funding account". | | Sub-account | A trading account under your main account, identified by a number, the sub-account ID (`sub_account_id`). Orders, positions and margin live here. The Grvt web app calls it a **Trading Account**. Move funds between the main account and its sub-accounts with [transfer](/reference/rpc/transfer.md). | | API key | Logs you in: exchanged for a session ([Authentication](/guides/authentication.md)). | | Signing key | Signs orders, transfers and withdrawals and never leaves your machine ([Two keys, two jobs](/guides/authentication.md#two-keys-two-jobs)). | | Session | The `gravity` cookie and `X-Grvt-Account-Id` header a login returns. Every call to the trading host sends them. | ## How the API is laid out | Part | Host | What it does | |---|---|---| | Market data | `market-data.` | Instruments, tickers, order books, trades, candles. Public, no login. | | Trading | `trades.` | Orders, positions, fills, accounts, transfers. Needs a session. | | Edge | `edge.` | Login (API key or wallet signature). | `` is `testnet.grvt.io` or `grvt.io` ([Environments](/guides/environments.md)). The market data and trading hosts speak the same two protocols: - **HTTP**: `POST /full/v1/` with a JSON body. The response body is the result object. - **WebSocket**: JSON-RPC 2.0 on `/ws/full`. Every RPC works here too (`method: "v1/"`), and streams are subscribed with `method: "subscribe"`. Writes that move money or create orders carry an **EIP-712 signature** made with your signing key. The SDKs sign for you; [Signing](/guides/signing.md) explains the bytes if you sign yourself. ## Contract and signing test cases The reference pages and the SDKs are generated from the same API contract ([contract.json](/downloads/contract.json)), so they agree on names and types. [signing.json](/downloads/signing.json) holds signing test cases to check your own signing code against. ===== guides/quickstart.md # Quickstart Run one example to read testnet data. Then, if you want, run it again to place and cancel one testnet order. The full example for each language is in [Full examples](/guides/quickstart.md#full-examples). ## What you need The SDK for your language. The SDKs are in preview and any 0.x release can change the API, so pin the exact version you install. | SDK | Needs | Install | | --- | --- | --- | | [Python](/sdks/python.md) | Python 3.11+ | `pip install grvt` | | [TypeScript](/sdks/typescript.md) | Node.js 24+ | `npm install github:gravity-technologies/grvt-sdk-typescript` (from its public GitHub repository; not on the package registry yet) | | [Go](/sdks/go.md) | Go 1.27.4+ | `go get github.com/gravity-technologies/grvt-sdk-go` | | [Rust](/sdks/rust.md) | Rust 1.88+ | `cargo add grvt` | What else you need depends on what you run: | Part | Needs | | --- | --- | | Public data | Nothing | | Reading your account, for example your sub-account ID | Any testnet API key, read-only included ([API keys](/guides/accounts.md#api-keys)) | | The test order | A testnet API key with the **Trade** permission, its [signing key](/guides/authentication.md#two-keys-two-jobs), your sub-account ID, and testnet funds in that sub-account ([Get testnet funds](/guides/environments.md#get-testnet-funds)) | Your sub-account ID is the number of your Trading Account in the Grvt web app. [get_sub_accounts](/reference/rpc/get_sub_accounts.md) lists it once you log in with the key. ## Run public data first **When:** you want to check that your setup works. No credentials needed. 1. In the SDK's folder (the one that contains `examples/`), run the command for your language: | SDK | Command | | --- | --- | | Python | `python examples/quickstart.py` | | TypeScript | `npm run example` | | Go | `go run ./examples/quickstart` | | Rust | `cargo run --example quickstart` | 2. Check the output: the example prints a ticker and its instrument rules, then exits. These commands use testnet. The trading quickstarts intentionally stay on testnet, even when the portal's environment selector shows production. For production data in your own app, pick the `prod` environment ([Environments](/guides/environments.md)). ## Place one testnet order **When:** you have a funded testnet account ([What you need](/guides/quickstart.md#what-you-need)) and want to see one order placed, watched and cancelled. 1. Set `GRVT_API_KEY`, `GRVT_PRIVATE_KEY` (your signing key) and `GRVT_SUB_ACCOUNT_ID` for your **testnet** account. If one is missing, the program stops before it sends anything. 2. Run the command for your language with `--trade`: | SDK | Command | | --- | --- | | Python | `python examples/quickstart.py --trade` | | TypeScript | `npm run example -- --trade` | | Go | `go run ./examples/quickstart --trade` | | Rust | `cargo run --example quickstart -- --trade` | 3. Optional: change the spending cap with `--max-notional 100` (default `200`). Notional is price × size, in the instrument's quote asset (the currency of its price: USDT for `BTC_USDT_Perp`). If the smallest valid order is worth more than the cap, the program sends nothing. 4. Save the client order ID that the program prints before it sends the order. You need it if the response is lost. 5. Read the exit code: | Exit code | Meaning | | --- | --- | | `0` | The program saw the order cancelled or filled. | | `3` | The program saw the order rejected. | | `2` | The outcome is unknown. | | Anything else | Something failed. Investigate before you run it again. | What the program does: 1. Reads the instrument's tick size (smallest price step), minimum size and minimum notional. 2. Sends a post-only buy (an order that is rejected rather than trade at once) one tick below the best bid, with the smallest valid size. 3. Cancels the order once if it is still open. 4. Watches the order by its client order ID until it is cancelled or in another final state. A cancel reply alone doesn't prove the order is cancelled. **Watch out:** - The order is post-only, but it can still fill once it rests on the book. - On exit code `2`, don't run it again: look up the printed ID first ([When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). ## Full examples ### Python
View the complete Python example [Download this example](/downloads/examples/python/examples/quickstart.py) ```python """Read testnet data; add --trade to place, observe and cancel one testnet order.""" import argparse import asyncio import os import secrets import sys from decimal import ROUND_CEILING, ROUND_FLOOR, Decimal from typing import Any from urllib.parse import urlparse from grvt import AsyncGrvt, Environment, OrderStateUnknown, PrivateKeySigner, enums, models, resolve_order async def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--trade", action="store_true", help="send one real testnet order; it may fill") parser.add_argument("--instrument", default="BTC_USDT_Perp") parser.add_argument("--max-notional", type=Decimal, default=Decimal("200"), help="quote asset spending limit") parser.add_argument("--fixture-url", help=argparse.SUPPRESS) args = parser.parse_args() env = "testnet" encoding = "lite" if args.fixture_url: url = urlparse(args.fixture_url) if ( url.scheme != "http" or url.hostname != "127.0.0.1" or url.path or url.query or url.fragment or url.username or url.password or not url.port ): parser.error("fixture URL must be an HTTP loopback origin") env = Environment( "fixture", args.fixture_url, args.fixture_url, args.fixture_url, args.fixture_url.replace("http:", "ws:"), args.fixture_url.replace("http:", "ws:"), 326, ) encoding = "full" # the local fixture gateway speaks full names only credentials: dict[str, Any] = {} account = "" if args.trade: names = ("GRVT_API_KEY", "GRVT_PRIVATE_KEY", "GRVT_SUB_ACCOUNT_ID") if any(not os.environ.get(name, "").strip() for name in names): parser.error("trading requires GRVT_API_KEY, GRVT_PRIVATE_KEY and GRVT_SUB_ACCOUNT_ID") account = os.environ["GRVT_SUB_ACCOUNT_ID"] if not account.isascii() or not account.isdigit() or not 0 < int(account) < 2**64: parser.error("GRVT_SUB_ACCOUNT_ID must be a positive uint64") credentials = dict(api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"])) if not args.max_notional.is_finite() or args.max_notional <= 0: parser.error("max-notional must be finite and positive") async with AsyncGrvt(env=env, encoding=encoding, http_attempt_timeout=5, **credentials) as client: ticker = (await client.ticker(instrument=args.instrument)).result instrument = (await client.get_instrument(instrument=args.instrument)).result print("mark price", ticker.mark_price, flush=True) if not args.trade: return 0 tick, step = instrument.tick_size, instrument.min_size bid = ticker.best_bid_price if tick <= 0 or step <= 0 or bid is None or bid <= tick: raise ValueError("instrument has no usable bid, tick or size") price = ((bid / tick).to_integral_value(rounding=ROUND_FLOOR) - 1) * tick if price <= 0: print("no positive passive price; no order sent", file=sys.stderr) return 1 count = max(Decimal(1), (instrument.min_notional / (price * step)).to_integral_value(rounding=ROUND_CEILING)) size = step * count if size * price > args.max_notional: raise ValueError("minimum order exceeds max-notional; no order sent") order_id = str(secrets.randbits(63) | (1 << 63)) print("client_order_id", order_id, "price", price, "size", size, flush=True) order = models.OrderInput( sub_account_id=account, time_in_force=enums.TimeInForce.GOOD_TILL_TIME, post_only=True, legs=[models.OrderLeg(instrument=args.instrument, size=size, limit_price=price, is_buying_asset=True)], metadata=models.OrderMetadataInput(client_order_id=order_id), ) try: await client.create_order(order=order) except OrderStateUnknown: print("create outcome unknown; looking up the same ID", flush=True) # Acknowledgements do not prove terminal state. Observe before and after one cancel. cancelled = False for _ in range(8): try: found = await resolve_order(client, sub_account_id=account, client_order_id=order_id) except Exception as error: print("lookup unavailable:", type(error).__name__, flush=True) await asyncio.sleep(0.5) continue if found.status == "found" and found.order.state: status = found.order.state.status.value print("order status", status, flush=True) if status in ("CANCELLED", "FILLED", "REJECTED"): return 0 if status != "REJECTED" else 3 if status == "OPEN" and not cancelled: cancelled = True try: await client.cancel_order(sub_account_id=account, client_order_id=order_id) except Exception as error: # Even a failed cancel may have reached the server. Observe; do not retry. print("cancel response unavailable:", type(error).__name__, flush=True) await asyncio.sleep(0.5) print("outcome still unknown; retain client_order_id and reconcile manually; do not resend", flush=True) return 2 async def bounded_main(): try: async with asyncio.timeout(60): return await main() except TimeoutError: print("deadline reached; retain any printed client_order_id and reconcile; do not resend", flush=True) return 2 if __name__ == "__main__": raise SystemExit(asyncio.run(bounded_main())) ```
### TypeScript
View the complete TypeScript example [Download this example](/downloads/examples/typescript/examples/quickstart.ts) ```typescript // Public testnet data by default. --trade places one real order which may fill. import { randomBytes } from "node:crypto"; import { Grvt, Decimal, OrderStateUnknown, PrivateKeySigner, resolveOrder } from "grvt"; const args = process.argv.slice(2); const option = (name: string, fallback: string) => { const i = args.indexOf(name); if (i < 0) return fallback; if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`missing ${name} value`); return args[i + 1]; }; for (let i = 0; i < args.length; i++) { if (args[i] === "--trade") continue; if (!["--instrument", "--max-notional", "--fixture-url"].includes(args[i])) throw new Error(`unknown option ${args[i]}`); i++; } const trade = args.includes("--trade"); const instrument = option("--instrument", "BTC_USDT_Perp"); const fixture = option("--fixture-url", ""); let env: NonNullable[0]>["env"] = "testnet"; let encoding: "full" | "lite" = "lite"; if (fixture) { const url = new URL(fixture); if ( url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/" || url.search || url.hash || url.username || url.password || !url.port ) throw new Error("fixture URL must be an HTTP loopback origin"); env = { name: "fixture", mdUrl: fixture, tdUrl: fixture, edgeUrl: fixture, mdWsUrl: fixture.replace("http:", "ws:"), tdWsUrl: fixture.replace("http:", "ws:"), chainId: 326, }; encoding = "full"; // the local fixture gateway speaks full names only } // Keep arithmetic exact: Decimal is a wire value, while BigInt calculates tick counts. function fraction(text: string) { if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("expected a positive plain decimal"); const [whole, tail = ""] = text.split("."); return { n: BigInt(whole + tail), d: 10n ** BigInt(tail.length), scale: tail.length }; } function multiple(text: string, count: bigint) { const { n, scale } = fraction(text); const digits = (n * count).toString().padStart(scale + 1, "0"); return scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits; } const cap = fraction(option("--max-notional", "200")); if (cap.n <= 0n) throw new Error("max-notional must be positive"); let credentials = {}; const account = process.env.GRVT_SUB_ACCOUNT_ID ?? ""; if (trade) { if ( !process.env.GRVT_API_KEY?.trim() || !process.env.GRVT_PRIVATE_KEY?.trim() || !/^\d+$/.test(account) || BigInt(account) <= 0n || BigInt(account) >= 1n << 64n ) throw new Error( "trading requires GRVT_API_KEY, GRVT_PRIVATE_KEY and a positive uint64 GRVT_SUB_ACCOUNT_ID", ); credentials = { apiKey: process.env.GRVT_API_KEY, signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY), }; } const deadline = setTimeout(() => { console.error( "deadline reached; retain any printed client_order_id and reconcile; do not resend", ); process.exit(2); }, 60_000); const client = new Grvt({ env, encoding, httpAttemptTimeoutMs: 5000, ...credentials }); try { const ticker = (await client.ticker({ instrument })).result; const metadata = (await client.getInstrument({ instrument })).result; console.log("mark price", ticker.mark_price?.toString()); if (trade) { const bid = fraction(ticker.best_bid_price?.toString() ?? "0"); const tick = fraction(metadata.tick_size.toString()); const step = fraction(metadata.min_size.toString()); if (!tick.n || !step.n) throw new Error("instrument has no usable tick or size"); const ticks = (bid.n * tick.d) / (bid.d * tick.n) - 1n; if (ticks <= 0n) throw new Error("instrument has no usable bid"); const price = multiple(metadata.tick_size.toString(), ticks); const p = fraction(price); const minimum = fraction(metadata.min_notional.toString()); const numerator = minimum.n * p.d * step.d; const denominator = minimum.d * p.n * step.n; const count = (numerator + denominator - 1n) / denominator; const size = multiple(metadata.min_size.toString(), count > 0n ? count : 1n); const s = fraction(size); if (p.n * s.n * cap.d > cap.n * p.d * s.d) throw new Error("minimum order exceeds max-notional; no order sent"); const id = (randomBytes(8).readBigUInt64BE() | (1n << 63n)).toString(); console.log("client_order_id", id, "price", price, "size", size); try { await client.createOrder({ order: { sub_account_id: account, time_in_force: "GOOD_TILL_TIME", post_only: true, legs: [ { instrument, size: new Decimal(size), limit_price: new Decimal(price), is_buying_asset: true, }, ], metadata: { client_order_id: id }, }, }); } catch (error) { if (!(error instanceof OrderStateUnknown)) throw error; console.log("create outcome unknown; looking up the same ID"); } let cancelled = false; process.exitCode = 2; for (let attempt = 0; attempt < 8; attempt++) { let found; try { found = await resolveOrder(client, { sub_account_id: account, client_order_id: id }); } catch { console.log("lookup unavailable; continuing bounded observation"); await new Promise((resolve) => setTimeout(resolve, 500)); continue; } if (found.status === "found") { const status = found.order.state?.status; console.log("order status", status); if (status === "CANCELLED" || status === "FILLED" || status === "REJECTED") { process.exitCode = status === "REJECTED" ? 3 : 0; break; } if (status === "OPEN" && !cancelled) { cancelled = true; try { await client.cancelOrder({ sub_account_id: account, client_order_id: id }); } catch { console.log("cancel response unavailable; observing without retry"); } } } await new Promise((resolve) => setTimeout(resolve, 500)); } if (process.exitCode === 2) console.log( "outcome still unknown; retain client_order_id and reconcile manually; do not resend", ); } } finally { await client.close(); clearTimeout(deadline); } ```
### Go
View the complete Go example [Download this example](/downloads/examples/go/examples/quickstart/main.go) ```go // Read testnet market data; --trade opts into one bounded order lifecycle. package main import ( "context" "crypto/rand" "encoding/binary" "errors" "flag" "fmt" grvt "github.com/gravity-technologies/grvt-sdk-go" "github.com/gravity-technologies/grvt-sdk-go/models" "math/big" "net" "net/url" "os" "strconv" "strings" "time" ) func main() { os.Exit(run()) } func run() int { trade := flag.Bool("trade", false, "place and cancel one testnet order") fixture := flag.String("fixture-url", "", "loopback test gateway URL") instrument := flag.String("instrument", "BTC_USDT_Perp", "instrument") capText := flag.String("max-notional", "200", "maximum quote amount") flag.Parse() fail := func(err error) int { fmt.Fprintln(os.Stderr, err); return 1 } capValue, err := models.ParseDecimal(*capText) if err != nil || capValue.Rat().Sign() <= 0 { return fail(errors.New("max-notional must be positive")) } config := grvt.Config{Env: grvt.Testnet(), HTTPAttemptTimeout: 5 * time.Second} if *fixture != "" { u, parseErr := url.Parse(*fixture) if parseErr != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { return fail(errors.New("fixture-url must be a loopback HTTP base URL")) } ip := net.ParseIP(u.Hostname()) if ip == nil || !ip.IsLoopback() { return fail(errors.New("fixture-url must use a loopback IP")) } config.Env.MarketDataURL, config.Env.TradingURL, config.Env.EdgeURL = *fixture, *fixture, *fixture // The local fixture gateway speaks full names only. config.Encoding = grvt.EncodingFull } // Check credentials before the first network request. if *trade { config.APIKey = strings.TrimSpace(os.Getenv("GRVT_API_KEY")) config.SubAccountID, err = strconv.ParseUint(os.Getenv("GRVT_SUB_ACCOUNT_ID"), 10, 64) if config.APIKey == "" || err != nil || config.SubAccountID == 0 || os.Getenv("GRVT_PRIVATE_KEY") == "" { return fail(errors.New("--trade requires GRVT_API_KEY, GRVT_PRIVATE_KEY and a positive GRVT_SUB_ACCOUNT_ID")) } config.Signer, err = grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY")) if err != nil { return fail(err) } } client, err := grvt.New(config) if err != nil { return fail(err) } defer client.Close() ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() ticker, err := client.Ticker(ctx, &models.ApiTickerRequest{Instrument: *instrument}) if err != nil { return fail(err) } info, err := client.GetInstrument(ctx, &models.ApiGetInstrumentRequest{Instrument: *instrument}) if err != nil { return fail(err) } fmt.Println("mark price", ticker.Result.MarkPrice) if !*trade { return 0 } if ticker.Result.BestBidPrice == nil { return fail(errors.New("ticker has no best bid")) } price, size, err := orderAmounts(*ticker.Result.BestBidPrice, info.Result.TickSize, info.Result.MinSize, info.Result.MinNotional, capValue) if err != nil { return fail(err) } var rawID [8]byte if _, err = rand.Read(rawID[:]); err != nil { return fail(err) } id := binary.BigEndian.Uint64(rawID[:]) | 1<<63 // Keep this ID when submission is uncertain. Never resend the order. fmt.Println("client_order_id", id) _, err = client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: models.OrderInput{ SubAccountID: grvt.Ptr(config.SubAccountID), TimeInForce: models.TimeInForceGoodTillTime, PostOnly: grvt.Ptr(true), Metadata: &models.OrderMetadataInput{ClientOrderID: &id}, Legs: []models.OrderLeg{{Instrument: *instrument, Size: size, LimitPrice: &price, IsBuyingAsset: true}}, }}) if err != nil { fmt.Fprintln(os.Stderr, "submission failed or uncertain; looking up client_order_id", id, err) } cancelled := false for attempt := 0; attempt < 8; attempt++ { result, lookupErr := grvt.ResolveOrder(ctx, client, config.SubAccountID, id) if lookupErr != nil { fmt.Fprintln(os.Stderr, "lookup failed; preserving client_order_id", id, lookupErr) } if lookupErr == nil && result.Status == grvt.OrderFound && result.Order.State != nil { status := result.Order.State.Status fmt.Println("order status", status) switch string(status) { case "CANCELLED", "FILLED": return 0 case "REJECTED": return 3 case "OPEN": if !cancelled { cancelled = true if _, cancelErr := client.CancelOrder(ctx, &models.ApiCancelOrderRequest{SubAccountID: config.SubAccountID, ClientOrderID: &id}); cancelErr != nil { fmt.Fprintln(os.Stderr, "cancel outcome uncertain; continue lookup", id, cancelErr) } } } } if attempt < 7 { select { case <-time.After(500 * time.Millisecond): case <-ctx.Done(): fmt.Fprintln(os.Stderr, "still unknown; reconcile client_order_id", id) return 2 } } } fmt.Fprintln(os.Stderr, "still unknown; reconcile client_order_id", id, "before further trading") return 2 } // Exact decimals keep the order on tick and size boundaries. func orderAmounts(bid, tick, minimum, notional, capValue models.Decimal) (models.Decimal, models.Decimal, error) { zero := models.Decimal{} if bid.Rat().Sign() <= 0 || tick.Rat().Sign() <= 0 || minimum.Rat().Sign() <= 0 || notional.Rat().Sign() < 0 { return zero, zero, errors.New("invalid market limits") } ticks := new(big.Rat).Quo(bid.Rat(), tick.Rat()) whole := new(big.Int).Quo(ticks.Num(), ticks.Denom()) whole.Sub(whole, big.NewInt(1)) price := new(big.Rat).Mul(new(big.Rat).SetInt(whole), tick.Rat()) if price.Sign() <= 0 { return zero, zero, errors.New("no positive passive price") } lots := new(big.Rat).Quo(notional.Rat(), new(big.Rat).Mul(price, minimum.Rat())) count, remainder := new(big.Int), new(big.Int) count.QuoRem(lots.Num(), lots.Denom(), remainder) if remainder.Sign() > 0 { count.Add(count, big.NewInt(1)) } if count.Sign() == 0 { count.SetInt64(1) } size := new(big.Rat).Mul(new(big.Rat).SetInt(count), minimum.Rat()) if new(big.Rat).Mul(price, size).Cmp(capValue.Rat()) > 0 { return zero, zero, errors.New("minimum order exceeds max-notional") } p := models.MustParseDecimal(price.FloatString(decimalPlaces(tick.String()))) s := models.MustParseDecimal(size.FloatString(decimalPlaces(minimum.String()))) return p, s, nil } func decimalPlaces(s string) int { for i, c := range s { if c == '.' { return len(s) - i - 1 } } return 0 } ```
### Rust
View the complete Rust example [Download this example](/downloads/examples/rust/examples/quickstart.rs) ```rust //! Public testnet data by default. --trade places one real order which may fill. use grvt::{ enums::{OrderStatus, TimeInForce}, models as m, resolve_order, Config, Encoding, Environment, Error, Grvt, OrderResolution, PrivateKeySigner, }; use rust_decimal::Decimal; use std::{ env, io::{self, Write}, str::FromStr, time::Duration, }; type Result = std::result::Result>; #[tokio::main] async fn main() -> Result<()> { let args: Vec = env::args().skip(1).collect(); let mut trade = false; let mut instrument = "BTC_USDT_Perp".to_owned(); let mut cap = Decimal::from(200); let mut environment = Environment::testnet(); let mut fixture = false; let mut index = 0; while index < args.len() { if args[index] == "--trade" { trade = true; index += 1; continue; } let value = args.get(index + 1).ok_or("missing option value")?; match args[index].as_str() { "--instrument" => instrument = value.clone(), "--max-notional" => cap = Decimal::from_str(value)?, "--fixture-url" => { let port = value .strip_prefix("http://127.0.0.1:") .ok_or("fixture URL must be an HTTP loopback origin")?; let _: u16 = port.parse()?; environment = Environment { name: "fixture".into(), md_url: value.clone(), td_url: value.clone(), edge_url: value.clone(), md_ws_url: value.replace("http:", "ws:"), td_ws_url: value.replace("http:", "ws:"), chain_id: 326, ws_max_frame_bytes: None, }; fixture = true; } _ => return Err("unknown option".into()), } index += 2; } if cap <= Decimal::ZERO { return Err("max-notional must be positive".into()); } let mut config = Config::new(environment).http_attempt_timeout(Duration::from_secs(5)); if fixture { // the local fixture gateway speaks full names only config = config.encoding(Encoding::Full); } let mut account = 0; if trade { let key = env::var("GRVT_API_KEY")?; if key.trim().is_empty() { return Err("GRVT_API_KEY is required".into()); } account = env::var("GRVT_SUB_ACCOUNT_ID")?.parse::()?; if account == 0 { return Err("GRVT_SUB_ACCOUNT_ID must be positive".into()); } config = config .api_key(key) .signer(PrivateKeySigner::new(&env::var("GRVT_PRIVATE_KEY")?)?); } let client = Grvt::new(config)?; let outcome = tokio::time::timeout( Duration::from_secs(60), journey(&client, trade, &instrument, account, cap), ) .await; client.close().await; let code = match outcome { Ok(result) => result?, Err(_) => { eprintln!("deadline reached; retain any printed client_order_id and reconcile; do not resend"); 2 } }; std::process::exit(code); } async fn journey(client: &Grvt, trade: bool, instrument: &str, account: u64, cap: Decimal) -> Result { let ticker = client.ticker().instrument(instrument).await?.result; let metadata = client.get_instrument().instrument(instrument).await?.result; println!("mark price {:?}", ticker.mark_price); if !trade { return Ok(0); } let tick = metadata.tick_size; let step = metadata.min_size; let bid = ticker.best_bid_price.ok_or("instrument has no usable bid")?; if tick <= Decimal::ZERO || step <= Decimal::ZERO || bid <= tick { return Err("instrument has no usable tick, bid or size".into()); } let price = ((bid / tick).floor() - Decimal::ONE) * tick; if price <= Decimal::ZERO { return Err("no positive passive price; no order sent".into()); } let size = (metadata.min_notional / (price * step)).ceil().max(Decimal::ONE) * step; if price * size > cap { return Err("minimum order exceeds max-notional; no order sent".into()); } let id = rand::random::() | (1 << 63); println!("client_order_id {id} price {price} size {size}"); io::stdout().flush()?; let leg = m::OrderLeg::new(instrument, size, true).with_limit_price(price); let order = m::OrderInput::new(TimeInForce::GoodTillTime, Some(vec![leg])) .with_sub_account_id(account) .with_post_only(true) .with_metadata(m::OrderMetadataInput::default().with_client_order_id(id)); match client.create_order().order(order).await { Ok(_) => (), Err(Error::OrderStateUnknown { .. }) => println!("create outcome unknown; looking up the same ID"), Err(error) => return Err(error.into()), } let mut cancelled = false; for _ in 0..8 { let observed = match resolve_order(client, account, id).await { Ok(value) => value, Err(_) => { println!("lookup unavailable; continuing bounded observation"); tokio::time::sleep(Duration::from_millis(500)).await; continue; } }; if let OrderResolution::Found(order) = observed { if let Some(state) = order.state { println!("order status {}", state.status.as_str()); match state.status { OrderStatus::Cancelled | OrderStatus::Filled => return Ok(0), OrderStatus::Rejected => return Ok(3), OrderStatus::Open if !cancelled => { cancelled = true; if client .cancel_order() .sub_account_id(account) .client_order_id(id) .await .is_err() { println!("cancel response unavailable; observing without retry"); } } _ => (), } } } tokio::time::sleep(Duration::from_millis(500)).await; } println!("outcome still unknown; retain client_order_id and reconcile manually; do not resend"); Ok(2) } ```
### C++ signing core and reference **Advanced.** C++ has a signing core only: your app handles networking and state itself ([C++ signing core and reference](/sdks/cpp.md)). This example uses fixed inputs and makes no network calls. Don't send its recorded order as a new request.
View the complete C++ example [Download this example](/downloads/examples/cpp/examples/reference.cpp) ```cpp // Offline reference. Replace the print callback with your own HTTP transport. #include // Published conformance inputs. These are test values, never production credentials. #include "grvt/grvt.hpp" namespace reference { inline auto order() { grvt::models::OrderLeg leg("BTC_USDT_Perp", *grvt::Decimal::parse("0.01"), true); leg.limit_price = *grvt::Decimal::parse("60000"); grvt::models::OrderInput input(grvt::enums::TimeInForce::GOOD_TILL_TIME, std::vector{leg}); input.sub_account_id = 8289849667772468ULL; input.is_market = false; input.post_only = true; input.reduce_only = false; input.metadata.emplace(); input.metadata->client_order_id = (1ULL << 63) | 1001; // API client ID range input.signature.emplace(); input.signature->signer = "0x1267c6181aee40f5ddbd70c56ecf4613117326b5"; input.signature->nonce = 1001; input.signature->expiration = grvt::timestamp_from_ns(4102444800000000000LL); input.signature->chain_id = 326; return grvt::models::ApiCreateOrderRequestInput(std::move(input)); } inline grvt::SigningMetadata metadata() { grvt::SigningMetadata meta; meta.instruments["BTC_USDT_Perp"] = {"0x030501", 9, 6}; return meta; } inline constexpr auto test_key = "0xbfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89"; } // namespace reference #ifdef GRVT_WITH_SIGNER #include "grvt/signer.hpp" #endif // The host owns HTTP, secrets, cookies and account state. Nothing is sent by this example. using HostPost = void (*)(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body); void print_wire(std::string_view path, std::string_view cookie, std::string_view account_id, std::string_view body) { std::printf("POST %.*s\n", int(path.size()), path.data()); if (!cookie.empty()) std::printf("Cookie: %.*s\n", int(cookie.size()), cookie.data()); if (!account_id.empty()) std::printf("X-Grvt-Account-Id: %.*s\n", int(account_id.size()), account_id.data()); std::printf("%.*s\n", int(body.size()), body.data()); } int main() { HostPost post = &print_wire; // API-key login wire shape. Read Set-Cookie gravity and X-Grvt-Account-Id from the // real response in the host. Never print real keys or cookies in production logs. post("/auth/api_key/login", {}, {}, R"({"api_key":"REPLACE_IN_HOST"})"); auto order = reference::order(); auto meta = reference::metadata(); grvt::SignContext ctx; ctx.chain_id = 326; // caller selects the chain; the core has no environment lookup ctx.metadata = &meta; auto digest = grvt::signing::digest_order_create_order(order, ctx); if (!digest) return 1; std::printf("digest: %s\n", grvt::hex0x(digest->digest).c_str()); #ifdef GRVT_WITH_SIGNER auto signer = grvt::PrivateKeySigner::from_hex(reference::test_key); if (!signer) return 2; ctx.signer = &*signer; ctx.verify = &grvt::verify_signature; if (!grvt::signing::sign_order_create_order(order, ctx)) return 3; post("/full/v1/create_order", "gravity=HOST_COOKIE", "HOST_ACCOUNT_ID", grvt::encode(order)); #endif // If a write times out after sending, its result is unknown. Keep client_order_id // and reconcile with get_order/order history. An absent lookup does not prove that // the order was rejected. Keep the result unknown and never automatically resend. // A fresh nonce is not a retry guarantee. The host owns this policy and its storage. std::puts("unknown write: reconcile by client_order_id; absent lookup stays unknown; never automatically resend"); return 0; } ```
===== guides/environments.md # Environments Grvt has two environments: testnet, with free test funds, and production, with real funds. Test on testnet first. Each has its own accounts, API keys and balances. On this site, the API environment picker appears only on pages it changes. It switches the URLs on those pages, and the generated code samples on reference pages, and stays set as you move between them. Every other example is written for testnet. For production, use the production values in [Pick an environment](/guides/environments.md#pick-an-environment). Tutorials and live tools always use testnet. ## Pick an environment - **With an SDK:** pass the environment name when you create the client. Production is `"prod"`. - **Without an SDK:** set `GRVT_DOMAIN` to `testnet.grvt.io` or `grvt.io`. The raw Markdown examples use it. | Environment | `GRVT_DOMAIN` | Chain ID | Ethereum chain ID | |---|---|---|---| | Testnet | `testnet.grvt.io` | 326 | 11155111 (Sepolia) | | Production | `grvt.io` | 325 | 1 (Ethereum mainnet) | The chain ID is Grvt's own chain, used in every signature. The Ethereum chain ID is the network Grvt settles to; you need it only for wallet transactions on Ethereum itself. | SDK | Testnet | Production | By name (e.g. from `GRVT_ENV`) | |---|---|---|---| | Python | `Grvt(env="testnet")` | `Grvt(env="prod")` | `Grvt(env=os.environ["GRVT_ENV"])` | | TypeScript | `new Grvt({ env: "testnet" })` | `new Grvt({ env: "prod" })` | `new Grvt({ env: process.env.GRVT_ENV! })` | | Go | `grvt.Config{Env: grvt.Testnet()}` | `grvt.Config{Env: grvt.Prod()}` | `grvt.EnvironmentNamed(os.Getenv("GRVT_ENV"))` | | Rust | `Config::testnet()` | `Config::prod()` | `Config::named(&std::env::var("GRVT_ENV")?)?` | **Watch out:** the chain ID is part of every signature, so a signature made for testnet is not valid on production. In a request, `signature.chain_id` `"0"` means "this environment's chain ID". ## Hosts ```sh export GRVT_DOMAIN=testnet.grvt.io ``` | Service | URL | |---|---| | Market data (HTTP) | `https://market-data.$GRVT_DOMAIN` | | Market data (WebSocket) | `wss://market-data.$GRVT_DOMAIN/ws/full` | | Trading (HTTP) | `https://trades.$GRVT_DOMAIN` | | Trading (WebSocket) | `wss://trades.$GRVT_DOMAIN/ws/full` | | Edge (login) | `https://edge.$GRVT_DOMAIN` | | Server time | `GET https://market-data.$GRVT_DOMAIN/time` returns `{"server_time": }` | Production runs in AWS Tokyo (`ap-northeast-1`). Run latency-sensitive apps close to it. ## Encoding: full or lite Every gateway speaks two JSON encodings. They are the same API: same calls, routes, stream channels, values and enums. Only the field names differ. | | Full | Lite (SDK default) | |---|---|---| | HTTP | `/full/v1/` | `/lite/v1/` | | WebSocket | `/ws/full` | `/ws/lite` | | Field names | `{"instrument": "BTC_USDT_Perp"}` | `{"i": "BTC_USDT_Perp"}` | Lite messages are smaller: order book stream messages are about 30% smaller. HTTP responses are already gzipped, so lite saves much less there. - **With an SDK**, you get lite by default. Your code doesn't change: models, field names, errors and signing stay as on these pages, and the SDK renames fields on the wire. To see full names on the wire (for example while debugging raw messages), set the client's encoding to full (`encoding="full"` in Python, `encoding: "full"` in TypeScript, `Encoding: grvt.EncodingFull` in Go, `.encoding(Encoding::Full)` in Rust). - **By hand**, each field's lite name is fixed per type. The same short name can mean different things in different types (`s` is the stream in a stream message and the size in a book level), so rename per type. Errors are lite too: `{"c": 1003, "m": "...", "s": 400}` over HTTP. - **Don't mix encodings.** A full field name sent to a lite path is ignored, not rejected: the call runs without that field and can fail with an unrelated error such as `1004 Data Not Found`. - Login (edge) and `GET /time` have one encoding only. They are the same for full and lite clients. The reference pages show each field's lite name next to its full name (`lite i`), and their raw examples come in Full and Lite versions. ## Get testnet funds 1. Open [testnet.grvt.io/exchange/deposit](https://testnet.grvt.io/exchange/deposit). 2. Click **Mint testnet tokens** (USDT, USDC or GRVT). They go to your Funding Account (main account). 3. **Move** them to the Trading Account (sub-account) you trade from. **Watch out:** without funds, orders fail with `2080 InsufficientMargin`. ===== guides/websocket.md # WebSocket One WebSocket per host carries both streams and RPC calls, on `/ws/full`. ## With an SDK The SDKs follow [the protocol](/guides/websocket.md#subscribe) for you: they reconnect, subscribe again and check sequence numbers. A connection that sends nothing, not even a ping or pong, for 30 s (`idle_timeout`) counts as dead: the SDK drops it and reconnects, so a silent network failure ends in a gap instead of a stream that waits forever. Leave `idle_timeout` at 30 s unless you need faster detection, and keep it well above 5 s: the server pings every 5 s, and the TypeScript SDK, which can't send pings of its own, relies on those to see that a quiet connection is alive. Whether a stream sends snapshots, deltas or events is explained in [Snapshots, deltas and events](/guides/websocket.md#snapshots-deltas-and-events). Names used in this part: | Python | TypeScript | Go | Rust | |---|---|---|---| | `on_event` | `onEvent` | `OnEvent` (`Config`) | `.on_event` (`Config`) | | `order_transport="ws"` | `orderTransport: "ws"` | `OrderTransport: grvt.OrderTransportWS` (`Config`) | `.order_transport(OrderTransport::Ws)` (`Config`) | | `EventKind.SESSION_ROTATED` | `type: "session_rotated"` | `grvt.EventSessionRotated` | `Event::SessionRotated` | | `websocket_reconnect_required` | `websocketReconnectRequired` | `WebsocketReconnectRequired` | `websocket_reconnect_required` | | `queue_size` | `queueSize` | `QueueSize` (`Config`) | `.queue_size` (`Config`) | | `idle_timeout` (seconds) | `idleTimeoutMs` | `IdleTimeout` (`Config`) | `.idle_timeout` (`Config`) | The recovery helpers (order lookup, local book, history paging) are on [Recovery recipes](/guides/recovery.md#sdk-helpers). ### Read a stream Every stream has a method ending in `_stream` (`Stream` in TypeScript and Go). It returns a subscription you iterate; closing it unsubscribes. ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.orderbook_snap_stream(instrument="BTC_USDT_Perp", rate=500, depth=10) as sub: seen = 0 async for frame in sub: print(frame.sequence_number, frame.feed.bids[:1], frame.feed.asks[:1]) seen += 1 if seen == 3: break # leaving the async with block unsubscribes asyncio.run(main()) ``` ```typescript import { Grvt } from "grvt"; const client = new Grvt({ env: "testnet" }); let seen = 0; for await (const frame of client.orderbookSnapStream({ instrument: "BTC_USDT_Perp", rate: 500, depth: 10 })) { console.log(frame.sequence_number, frame.feed.bids?.[0], frame.feed.asks?.[0]); if (++seen === 3) break; // leaving the loop unsubscribes } await client.close(); ``` ```go sub, err := client.OrderbookSnapStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{ Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500), Depth: grvt.Ptr[uint32](10)}) if err != nil { return err } defer sub.Close() // unsubscribes seen := 0 for frame, err := range sub.All() { if err != nil { continue } fmt.Println(frame.SequenceNumber, len(frame.Feed.Bids), len(frame.Feed.Asks)) if seen++; seen == 3 { break } } ``` ```rust use futures::StreamExt; let mut sub = client.orderbook_snap_stream().instrument("BTC_USDT_Perp").rate(500).depth(10).await?; let mut seen = 0; while let Some(frame) = sub.next().await { let Ok(frame) = frame else { continue }; // the subscription carries on after an error println!("{} {:?}", frame.sequence_number, frame.feed.bids.as_ref().and_then(|b| b.first())); seen += 1; if seen == 3 { break; } } drop(sub); // unsubscribes ``` Reading a subscription can give an error in place of a frame. The subscription carries on after it: - **Overflow.** Each subscription queues up to 4096 frames (client option `queue_size`). If your code falls behind, a `.s` stream drops its oldest frame. Any other stream empties its queue, re-syncs and gives you a stream-overflow error; the frames in between are lost. - **A frame that can't be decoded** is skipped, with no gap event. If you build state from the stream, such as a book, treat it as a gap. - **A failed re-subscribe.** A fatal error (the socket can't connect for a reason retrying won't fix, such as a rejected API key or an invalid configuration) ends every subscription on that socket, after you read it. When the sequence chain breaks, the SDK reports a **gap event** through the client's event hook ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). ### Send orders over WebSocket 1. Set the order transport to WebSocket when you create the client, for example `AsyncGrvt(..., order_transport="ws")` (names in [With an SDK](/guides/websocket.md#with-an-sdk)). Create and cancel then go over the trading socket; everything else stays on HTTP. 2. Wait for a create's reply before cancelling that order ([why](/guides/websocket.md#calling-rpcs-over-websocket)). In C++, your app builds the WebSocket frames and manages the connection. **Watch out:** if the socket drops or the call times out after an order was sent, the SDK raises the outcome-unknown error and doesn't resend ([When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). ### Session renewal With an API key, the SDK logs in again at 80% of the session cookie's lifetime. It reads the lifetime from the cookie's `Expires`, and assumes one hour if the cookie has none. 1. When the new login succeeds, the SDK sends a `session_rotated` event with `websocket_reconnect_required` set to true: open sockets still use the old cookie. 2. Each socket waits until none of its writes is still waiting for a reply, then reconnects with the new cookie and subscribes again. WebSocket writes sent meanwhile wait for the new socket. **Watch out:** - Renewal reconnects every socket of that client, public market data included, so every subscription gets a gap event. To record public market data without these gaps, use a separate client with no API key. - Private streams can't be replayed across the reconnect. Treat it like any other gap ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). ## Connect without an SDK The sections from here to [Unpublished limits](/guides/websocket.md#unpublished-limits) describe the wire protocol, for apps without an SDK. | Host | URL | Headers on the upgrade request | |---|---|---| | Market data | `wss://market-data./ws/full` | none | | Trading | `wss://trades./ws/full` | `Cookie: gravity=...` and `X-Grvt-Account-Id` ([Authentication](/guides/authentication.md)) | The upgrade request is the HTTP request that opens the WebSocket, and the only place you authenticate. Messages are JSON-RPC 2.0 text frames: a request has a `method`, `params` and an `id`; its reply has the same `id` and a `result` or an `error`. ## Subscribe Send: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.ticker.d", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` The reply's `result` is `{stream, subs, unsubs, num_snapshots, first_sequence_number, latest_sequence_number}`. `subs` lists the selectors you are now subscribed to. The last three are arrays with one entry per selector, in the same order as `subs`. After the reply, data frames arrive with no JSON-RPC envelope: ```json { "stream": "v1.ticker.d", "selector": "BTC_USDT_Perp@500", "sequence_number": "0", "prev_sequence_number": "0", "feed": { "...": "..." } } ``` A **selector** names what you want. Fields before `@` pick the feed, fields after it set options, and several fields are joined with `-`: - `BTC_USDT_Perp@500`: one instrument at a 500 ms rate. - `BTC_USDT_Perp@500-50`: an order book at a 500 ms rate, 50 levels deep. - `-BTC_USDT_Perp`: a private stream for one sub-account and instrument. Each stream's reference page gives its exact format, for example [orderbook_snap](/reference/streams/orderbook_snap.md) and [orderbook_delta](/reference/streams/orderbook_delta.md); [All calls](/reference/index.md) lists every stream. `unsubscribe` takes the same `{stream, selectors}`. Subscribing again to a selector you have sends a new snapshot, on streams that have one. On one socket, each stream has one subscription per primary selector (the part before `@`). Subscribing with the same primary selector and different options replaces the old subscription, and the reply lists the old selector in `unsubs`. For example, with `BTC_USDT_Perp@500-10` on `v1.book.s`, subscribing to `BTC_USDT_Perp@500-50` replies `"subs": ["BTC_USDT_Perp@500-50"], "unsubs": ["BTC_USDT_Perp@500-10"]`. **Watch out:** after you re-subscribe on the same socket, update frames from the earlier subscription can still arrive after the new reply. The [sequence rules](/guides/websocket.md#sequence-numbers-and-gaps) drop them. Don't assume the first frame after a reply belongs to the new subscription. ## Snapshots, deltas and events The stream name's suffix says what a frame holds: - `.s` (snapshot): every frame is complete, so a missed frame costs nothing. Frames are still numbered, so you can see the gap. - `.d` (delta): the first frame after subscribing is a full snapshot. After that, frames hold only what changed, and you must apply every one in order. - no suffix (event): one frame per event, such as a fill or an order update. ## Sequence numbers and gaps Subscribe with `use_global_sequence_number: true`. Then every frame carries `sequence_number` and `prev_sequence_number`: unsigned 64-bit integers sent as decimal strings. Compare them as integers (`BigInt` in JavaScript), never as text or floating-point numbers. Each SDK page gives the types its frames use. For each selector, the frames form a chain: - The snapshot sent right after subscribing has `sequence_number` `"0"`. Every later frame is an update, on `.s` streams too. - The first update after the subscribe reply has a `prev_sequence_number` at or below that selector's `latest_sequence_number` from the reply. Accept any such value, including `"0"`: after a re-subscribe on the same socket it is often lower. Only a higher value is a gap. - Every later update has `prev_sequence_number` equal to the previous update's `sequence_number`. - An update whose `sequence_number` is at or below the last one you accepted (for the first update, at or below `latest_sequence_number`) is a duplicate. Drop it. Three frames from a testnet `v1.book.d` subscription (feeds shortened), after a reply with `"latest_sequence_number": ["8087017689000000"]`: ```json {"sequence_number": "0", "prev_sequence_number": "0", "feed": {"bids": [4 levels], "asks": [4 levels]}} {"sequence_number": "8087021381100000", "prev_sequence_number": "8087017689000000", "feed": {"bids": [], "asks": [...]}} {"sequence_number": "8087021632000000", "prev_sequence_number": "8087021381100000", "feed": {"bids": [...], "asks": [...]}} ``` **When:** the chain breaks, which means you missed a frame. What to do depends on the stream kind: - `.s` streams: nothing. The next frame is complete and current. - `.d` streams: drop frames for that subscription, subscribe again with the same selector, wait for the new snapshot (`sequence_number` `"0"`) and replace your state with it. - Event streams (fills, orders, positions, transfers, deposits, withdrawals, ...): subscribe again. There is no snapshot, so fetch what you missed over HTTP, for example [open_orders](/reference/rpc/open_orders.md), [positions](/reference/rpc/positions.md) or [fill_history](/reference/rpc/fill_history.md). Each stream page names the calls. **Watch out:** a snapshot restores current state. It doesn't recover missed private events. ## Applying book deltas On `v1.book.d`, the snapshot gives every price level. Each later frame lists only the levels that changed: - A level's size is the new total at that price, not an amount to add. - A size of zero removes the level. Compare it as a number: it can arrive as `"0"` or `"0.0"`. - An empty `bids` or `asks` list means that side did not change. For example, this testnet frame removes four ask levels and sets four bid levels: ```json {"bids": [{"price": "76869.0", "size": "4.96", "num_orders": 3}, ...], "asks": [{"price": "76866.0", "size": "0.0", "num_orders": 0}, ...]} ``` ## Calling RPCs over WebSocket Any RPC works over the socket: `method` is the RPC's WebSocket method (on its reference page), `params` the request body, `result` the response body. ```json { "jsonrpc": "2.0", "method": "v1/create_order", "params": { "order": { "...": "..." } }, "id": 7 } ``` A `result` means the same as an HTTP 200 for that call, with the same body. For `create_order`, the exchange received the order; it may not rest on the book ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). Errors come back as `{"jsonrpc": "2.0", "id": 7, "error": {"code": 2000, "message": "..."}}`. **Watch out:** the server doesn't promise to process requests in the order you sent them, on one socket or across HTTP connections. A cancel can overtake the create it refers to, so wait for a create's reply before cancelling that order. ## Reconnect On any disconnect: 1. Reconnect with backoff: wait a little longer after each failed attempt, with some randomness, so clients don't all retry at once. 2. Send the upgrade headers again. 3. Subscribe to everything again. 4. Treat each stream as after a gap ([Sequence numbers and gaps](/guides/websocket.md#sequence-numbers-and-gaps)). After a new login, open the new socket with the new cookie. You can't log in again inside an open socket. ## Unpublished limits The heartbeat interval, maximum frame size, subscriptions per socket and per-stream rates are not published. Treat them as unknown ([Rate limits](/guides/rate-limits.md)). ## Cancel orders if your app stops The cancel-on-disconnect countdown is a timer on the server. If it runs out, the exchange cancels all of the sub-account's open orders, with reject reason `CLIENT_CANCEL_ON_DISCONNECT_TRIGGERED`. Trigger orders (take-profit and stop-loss orders waiting for their price) that haven't triggered yet are not cancelled. It fires once, then stays off until you arm it again. 1. Choose one component, in one process, to refresh the countdown for each sub-account. 2. Arm the countdown with `refresh_cancel_countdown`, in whole seconds (1 to 300). Then call it again on a schedule, well before the time runs out. 3. Stop refreshing when your app can no longer manage its orders, for example when it loses its trading connection or can't tell which orders are open. The countdown then runs out and cancels them. 4. After recovery, check which orders exist and in what state, then refresh the countdown before allowing new orders. For example, every 30 seconds: ```python from grvt import refresh_cancel_countdown await refresh_cancel_countdown(client, sub_account_id=sub_account_id, countdown_seconds=120) ``` ```typescript import { refreshCancelCountdown } from "grvt"; await refreshCancelCountdown(client, subAccountId, 120); ``` ```go _, err := grvt.RefreshCancelCountdown(ctx, client, subAccountID, 120) ``` ```rust grvt::refresh_cancel_countdown(&client, sub_account_id, 120).await?; ``` To turn the countdown off, call [cancel_on_disconnect](/reference/rpc/cancel_on_disconnect.md) with `countdown_time` `"0"`; the helper only arms it. Without an SDK, call that RPC to arm it too. Its `countdown_time` is in milliseconds, as a string, for example `"120000"`. The server rounds it down to whole seconds, so anything below `"1000"` turns the countdown off. It rejects more than 300 s with error `6000`. The helpers reject anything outside 1 to 300 s before sending. **Watch out:** - The countdown belongs to the sub-account, not to a socket or session, despite the RPC's name. Anyone who can trade on the sub-account replaces the same timer: two processes refreshing it overwrite each other, and a successful reply doesn't prove your timer is still the active one. - `refresh_cancel_countdown` sends once and never retries. A timeout raises the outcome-unknown error ([When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). - The SDK never refreshes the countdown on reconnect and never turns it off when the client closes. ## Shut down cleanly **When:** your app stops on purpose. 1. Stop placing new orders. 2. If you don't want orders left on the book, cancel them with [cancel_all_orders](/reference/rpc/cancel_all_orders.md), then check [open_orders](/reference/rpc/open_orders.md) until they are gone. An accepted cancel doesn't prove an order was cancelled: it may have filled. 3. If you armed the countdown, turn it off (`countdown_time` `"0"`) or let it run out, which cancels anything still open. 4. Close your subscriptions and wait for the writes you sent to return. 5. Close the client. ===== guides/errors-and-retries.md # Errors and retries When a call fails, the SDK raises one of a few errors. This page says what each one means, what the SDK has already retried, and what your app does next. The costly case is a write whose result is unknown: [look it up, don't resend it](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## What an error looks like | Where | Shape | |---|---| | HTTP | non-2xx status, body `{"code": 2000, "message": "...", "status": 403}` | | WebSocket | `{"jsonrpc": "2.0", "id": 7, "error": {"code": 2000, "message": "..."}}` | | Edge (login) | `{"status": "failure", "error": "..."}` or plain text, with the HTTP status | `code` is stable; `message` is for humans. [Error codes](/reference/errors.md) lists every code with its HTTP status, and each reference page lists the codes of that call. ## Errors the SDK raises | Error | Means | What to do | |---|---|---| | API error | The server answered with an error code. | Fix the request. If a retry could help, a read was already retried. | | Rate limit | Code `1006`. It is also an API error, so code that handles API errors catches it. | Slow down. Reads were already retried. A write was rejected before it ran and is not resent. | | Transport | No usable answer: the connection failed, the reply timed out, or the socket closed. | Reads were already retried. On a write, the SDK raises this only when the request never left your process, so nothing happened. | | Outcome unknown | A write may or may not have happened. | [Look it up](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). | | Order out of bounds | An order breaks its instrument's limits. Nothing was sent. | Pick one of the nearest valid values ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). | Other 429s, such as `2090` (too many open orders), are plain API errors. What each error carries: - **API error:** the code, the server's message, the HTTP status (none over WebSocket), the call, and `retryable` (whether a retry can help). - **Transport error:** the call, and `sent`: whether the request may have left your process. On a write it is always false. - **Outcome unknown:** the client order ID (every ID, for a bulk call), and the original failure as its cause. Cancelling a call follows each language's own rules. The class and field names in each language are on the SDK pages: [Python](/sdks/python.md#errors), [TypeScript](/sdks/typescript.md#errors), [Go](/sdks/go.md#errors), [Rust](/sdks/rust.md#errors). In C++, your app handles server errors, retries and order lookups; the signing core reports only local input and signing failures. ## What the SDK retries - **Reads** (lookups, history, market data): the SDK tries a read up to 3 times in all. Between tries it waits a random delay that grows each time (backoff with jitter). It retries when there was no answer, on `1006` and the other codes marked retryable on [Error codes](/reference/errors.md), and on HTTP `502`, `503` or `504`. Other errors come back at once. - **Timeouts:** the call timeout (30 s by default) bounds the whole call, including login and read retries. Each HTTP attempt also has its own limit (10 s), and so does each WebSocket request (5 s). - **Writes** (create and cancel orders, transfers, withdrawals, settings): the SDK sends them exactly once, whatever happens. Each reference page says which kind a call is. - **Redirects:** the SDK never follows one, for a call or a WebSocket handshake. Following it would send a second request, which can carry your session cookie to another host or replay a signed write. A redirected write's outcome is unknown. A custom HTTP transport must do the same: no redirects, no retries of its own. Why: a write that timed out may already have happened, and sending it again can be a second trade ([Why not resend](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). Errors that aren't retryable are about your request or account: a bad signature, not enough margin, too many open orders (`2090`: a 429, but waiting won't fix it). Change the request instead. ### When a write's outcome is unknown **When:** a write failed and you can't tell whether it happened. The SDK raises the outcome-unknown error when: - the request was sent, then the reply timed out or the connection dropped; - the HTTP status isn't a 4xx (for example `500` or `502` to `504`), even if the body says `1006`; - the code is a server error, one whose HTTP status on [Error codes](/reference/errors.md) is 5xx, such as `1002` (internal error) or `1005` (unknown error), over WebSocket too; - the code is one the SDK doesn't know, or a success reply can't be read. Cancels count too; a timed-out `cancel_order` carries no client order ID. For a transfer, `1002` means the exchange didn't confirm it within 30 s, and some rejections (such as a failed risk check) come back as `1005` instead of their own code. Either way the transfer may have happened. Not unknown: a rate-limit reply (`1006` with HTTP 429, or over WebSocket) was rejected before it ran, and a transport error on a write was never sent. **Why not resend.** The exchange rejects a repeated client order ID only while an order with that ID is open (`2012`), or when it is the sub-account's last client order ID (`2013`). Beyond that: - An order signed again (new nonce and expiration, which the SDKs do on every call) is a new order. It can fill again, in full. - An exact resend of the same signed order is blocked while the first order is open (`2012`) or while its ID is still the sub-account's last client order ID (`2013`). After the first order has closed and another order has used a new ID, the resend can be accepted and rest on the book. All copies together never fill more than the signed size, and a repeated IOC (immediate-or-cancel) order is rejected. - An exact resend of a signed transfer fails with `4007` ([Nonce](/guides/signing.md#rules-that-cause-most-rejections)). 1. Keep the request details. For an order, that is the client order ID you saved before sending it ([Client order ID](/guides/signing.md#rules-that-cause-most-rejections)). 2. Look for its result: - **Orders:** look it up by client order ID with the SDK's `resolve_order` (`resolve_order_sync` in blocking Python; it only reads) or [get_order](/reference/rpc/get_order.md), a set number of times, as below. - **Transfers and withdrawals:** read every relevant page of [transfer_history](/reference/rpc/transfer_history.md) or [withdrawal_history](/reference/rpc/withdrawal_history.md) for the submitted signature and details. 3. If the order is found, it exists, in the state it had when you looked ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). Manage it like any order. To remove it, cancel it once, then keep looking until it is final: a cancel that fails or times out may still have reached the exchange. 4. If it filled, check order history, fill history and positions before placing another trade. 5. If the lookups run out, save the sub-account and client order ID (or the transfer details), stop trading in that workflow and investigate. 6. Never resend automatically. "Not found", an empty history or running out of lookups all leave the outcome unknown: reads can lag behind an accepted write. A newly signed request is a new action, not a retry. The [quickstart examples](/guides/quickstart.md) follow these steps with one testnet order. They only check that the order ends cancelled; they don't reverse fills or restore positions. Catch the error and look the order up once: ```python from grvt import OrderStateUnknown, resolve_order sub = os.environ["GRVT_SUB_ACCOUNT_ID"] try: resp = await client.create_order(order=order) print(resp.result.metadata.client_order_id) except OrderStateUnknown as e: if e.client_order_id is None: raise result = await resolve_order(client, sub_account_id=sub, client_order_id=e.client_order_id) if result.status == "found": print(result.order.order_id) else: print("still unknown, not resending:", e.client_order_id) ``` ```typescript import { OrderStateUnknown, resolveOrder } from "grvt"; const sub = process.env.GRVT_SUB_ACCOUNT_ID!; try { const resp = await client.createOrder({ order }); console.log(resp.result.metadata.client_order_id); } catch (e) { if (!(e instanceof OrderStateUnknown) || e.clientOrderId === undefined) throw e; const result = await resolveOrder(client, { sub_account_id: sub, client_order_id: e.clientOrderId }); if (result.status === "found") console.log(result.order.order_id); else console.log("still unknown, not resending:", e.clientOrderId); } ``` ```go resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) var unknown *grvt.OrderStateUnknownError switch { case err == nil: fmt.Println(resp.Result.Metadata.ClientOrderID) case errors.As(err, &unknown) && unknown.ClientOrderID != 0: result, err := grvt.ResolveOrder(ctx, client, sub, unknown.ClientOrderID) if err != nil { return err } if result.Status == grvt.OrderFound { fmt.Println(result.Order.OrderID) } else { log.Print("still unknown, not resending: ", unknown.ClientOrderID) } default: return err } ``` ```rust use grvt::{Error, OrderResolution}; match client.create_order().order(order).await { Ok(resp) => println!("{}", resp.result.metadata.client_order_id), Err(Error::OrderStateUnknown { client_order_id: Some(id), .. }) => { match grvt::resolve_order(&client, sub, id).await? { OrderResolution::Found(found) => println!("{:?}", found.order_id), OrderResolution::StillUnknown => eprintln!("still unknown, not resending: {id}"), } } Err(e) => return Err(e.into()), } ``` On success it prints the client order ID: a create reply's `order_id` is always zero ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). The error's client order ID is empty (`None`, `undefined` or `0`) when the write carried no order ID. A bulk call lists every ID in `client_order_ids` (names in [Errors the SDK raises](/guides/errors-and-retries.md#errors-the-sdk-raises)). To look up a set number of times, this helper tries up to five times, one second apart: [Download this example](/downloads/examples/python/examples/reconcile_order.py) ```python import time from grvt import resolve_order_sync def reconcile_order(client, sub_account_id, client_order_id): for attempt in range(5): result = resolve_order_sync( client, sub_account_id=sub_account_id, client_order_id=client_order_id, ) if result.status == "found": return result # Inspect the observed order; PENDING is not final. if attempt < 4: time.sleep(1) return result # Still unknown. Save the ids for investigation; do not resend. ``` ```typescript import { Grvt, resolveOrder } from "grvt"; async function reconcileOrder(client: Grvt, subAccountId: string, clientOrderId: string) { const ids = { sub_account_id: subAccountId, client_order_id: clientOrderId }; let result = await resolveOrder(client, ids); for (let attempt = 1; attempt < 5 && result.status !== "found"; attempt++) { await new Promise((resolve) => setTimeout(resolve, 1000)); result = await resolveOrder(client, ids); } return result; // "found": inspect result.order. "still_unknown": save the ids; do not resend. } ``` ```go func reconcileOrder(ctx context.Context, client *grvt.Client, subAccountID, clientOrderID uint64) (grvt.OrderResolution, error) { for attempt := 1; ; attempt++ { result, err := grvt.ResolveOrder(ctx, client, subAccountID, clientOrderID) if err != nil || result.Status == grvt.OrderFound || attempt == 5 { return result, err // grvt.OrderStillUnknown: save the ids; do not resend. } select { case <-ctx.Done(): return result, ctx.Err() case <-time.After(time.Second): } } } ``` ```rust use grvt::{resolve_order, Grvt, OrderResolution, Result}; use std::time::Duration; async fn reconcile_order(client: &Grvt, sub_account_id: u64, client_order_id: u64) -> Result { let mut result = resolve_order(client, sub_account_id, client_order_id).await?; for _ in 1..5 { if matches!(result, OrderResolution::Found(_)) { break; } tokio::time::sleep(Duration::from_secs(1)).await; result = resolve_order(client, sub_account_id, client_order_id).await?; } Ok(result) // StillUnknown: save the ids; do not resend. } ``` Five attempts is an example, not a promise about when an order becomes visible. Each lookup is a read, so it uses the client's timeout and read retries. Other errors reach the caller. **Watch out:** a lookup by a reused client order ID can find a different submission's order ([Client order ID](/guides/signing.md#rules-that-cause-most-rejections)). ## What a create reply means A `200` on `create_order` (or a WebSocket `result`) means the exchange received the order, not that it rests on the book. Follow it by its client order ID on the [order stream](/reference/streams/order.md) or with [get_order](/reference/rpc/get_order.md), and read its `state.status`: | Status | Final? | |---|---| | `PENDING` | No: received, not on the book yet | | `OPEN` | No: on the book, possibly partly filled | | `FILLED`, `REJECTED`, `CANCELLED` | Yes. `reject_reason` says why it was rejected or cancelled | - Open the order stream before you place the order, so you don't miss its first updates. - Match updates by `metadata.client_order_id`: you know it before sending, and the create reply returns it. - A create reply (and each order in a `bulk_orders` reply) always has `order_id` zero, because the reply comes before the exchange assigns one. Read `order_id` from the order stream or `get_order`. - A rejection arrives on the order stream and in `get_order`, not as an error on the create. - Orders placed by an algo order also appear on the order and [order state](/reference/streams/order_state.md) streams, in open orders and in order history, marked by `metadata.algo_order_id`. - An accepted cancel doesn't mean the order was cancelled: it may already have filled. Wait for a final status. - An order still open when its signature expires is cancelled ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). ## Orders checked before sending The SDKs check every order leg against its instrument (from [get_instrument](/reference/rpc/get_instrument.md)) before signing, so the most common rejections never reach the exchange: | Rule | Skipped for | Server code | |---|---|---| | `size` at least `min_size` | reduce-only orders (orders that can only shrink a position) | `2062` | | `limit_price` a multiple of `tick_size` | market orders | `2064` | | `limit_price * size` at least `min_notional` | market, reduce-only and close-position orders | `2066` | | `size` a multiple of `min_size` | reduce-only orders | `2065` | A miss raises the order-out-of-bounds error with the nearest valid values, for example `BTC_USDT_Perp: limit_price 60000.03 isn't a multiple of tick_size 0.1 (nearest: 60000 or 60000.1)`. Nothing is sent, and the SDK never rounds your order. If the exchange still answers `2062`, `2064`, `2065`, `2066` or `2067` (say the limits changed), the SDK forgets that instrument's cached limits so the next order uses fresh ones. It does not resend. ## Doing it yourself **Advanced.** Without an SDK (or in C++), follow the same rules. Treat a failed write as outcome unknown unless you know the request never left your process, for example because the connection failed before you sent it: ```text on error from a read: if no answer, or code is 1006 or another retryable code, or HTTP status is 502, 503 or 504: wait (backoff with jitter), then try again; stop after a few tries else: fix the request; do not retry on error from a write: if it was sent and no reply came (timeout, dropped connection) or the HTTP status is not a 4xx or the code is a server error (1002, 1005, ...) or one you don't know: outcome unknown: reconcile; never resend automatically else: rejected before it ran: fix the request (for 1006, slow down) ``` ===== guides/recovery.md # Recovery recipes **Advanced.** Use these recipes after a lost connection or a sequence gap, so you don't trade on a stale view of the market or miss your own fills. For a write timeout, see [When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). The SDK gives you order lookup, a checked order book and history paging. Your app decides when to stop trading, how far back to look, how to store and de-duplicate what it finds, and when its state is safe to use again. ## What happens after a gap A **gap event** says which sequence numbers you may have missed: everything after `after_sequence` (exclusive) through `through_sequence` (inclusive). A missing bound means the SDK doesn't know it. The range is not a REST time window or a replay cursor ([sequence rules](/guides/websocket.md#sequence-numbers-and-gaps)). What the SDK does next depends on the [stream kind](/guides/websocket.md#snapshots-deltas-and-events): | Stream | After a gap, the SDK | |---|---| | `.s` (every frame complete) | carries on: the next frame is current. | | `.d` (a snapshot, then deltas) | re-subscribes and waits for a fresh snapshot, then reconnects if none arrives within 5 s (the client's resync timeout option). | | Events (fills, orders, ...) | re-subscribes. Missed events are not replayed. | - Gap events arrive only through the client's event hook ([`on_event`](/guides/recovery.md#sdk-helpers)), never in a subscription's frames. If you record frames, record the gap events too: they are the only record of missing data. - Frames from before the gap can still be queued ahead of the new ones, with no marker in between. Don't treat the next frame as fresh ([Rebuild a book after a gap](/guides/recovery.md#rebuild-a-book-after-a-gap)). - A new snapshot gives you current state, not the private events you missed (fills, order updates). Fill them from history ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). ## SDK helpers | Python | TypeScript | Go | Rust | |---|---|---|---| | `resolve_order` | `resolveOrder` | `ResolveOrder` | `resolve_order` | | `on_event` (client option) | `onEvent` | `OnEvent` (`Config`) | `.on_event` (`Config`) | | `after_sequence`, `through_sequence` | `afterSequence`, `throughSequence` | `AfterSequence`, `ThroughSequence` | `after_sequence`, `through_sequence` | | `OrderBook.on_event`, `.apply`, `.reset` | `OrderBook.onEvent`, `.apply`, `.reset` | `OrderBook.OnEvent`, `.Apply`, `.Reset` | `OrderBook::on_event`, `apply`, `reset` | | `backfill_pages` | `backfillPages` | `BackfillPages` | `backfill_pages` | | `continuity` | `continuity` | `Continuity()` | `continuity()` | Gap bounds are `int` in Python, strings in TypeScript, `*uint64` in Go and `Option` in Rust. **`OrderBook`** keeps a local book from one subscription's frames. It merges exact price levels, removes zero-size levels, and sorts bids high to low and asks low to high. The levels it returns are copies. Give it the mode of the stream you feed it; it never guesses from the stream name: | Stream | Python | TypeScript | Go | Rust | |---|---|---|---|---| | `orderbook_delta_stream` | `OrderBook(instrument)` | `new OrderBook(instrument)` | `grvt.NewOrderBook(instrument, grvt.BookDelta)` | `OrderBook::new(instrument, BookMode::Delta)` | | `orderbook_snapshot_stream` | `OrderBook(instrument, mode="snapshot")` | `new OrderBook(instrument, "snapshot")` | `grvt.NewOrderBook(instrument, grvt.BookSnapshots)` | `OrderBook::new(instrument, BookMode::Snapshot)` | - **Delta mode:** after a gap event it refuses reads and updates until you `reset` it ([Rebuild a book after a gap](/guides/recovery.md#rebuild-a-book-after-a-gap)). Its `BookError` gives the reason and the gap range when known. - **Snapshot mode:** every frame replaces the whole book, so a gap needs no reset. The book is the last complete snapshot received, not a promise that it is live: judge freshness from connection events and the snapshot's timestamp. - The first frame binds the book to its stream and selector: it then rejects other subscriptions' frames and ignores their gap events. Before that frame, a delta book takes any gap as its own, so when one client has several streams, pass the book only its subscription's events. - Python and Go books lock internally. In Rust, share one through `Arc>` and keep the event callback short. **`backfill_pages`** pages through REST history after a gap. Your callback picks the endpoint and time window. Each page carries the gap and a `continuity` field that is always `unproven`: the SDK can't prove the history covers everything you missed ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). **`resolve_order`** looks up an order whose write outcome is unknown, by its client order ID ([When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). ## Rebuild a book after a gap **When:** you keep a local order book and the SDK reports a gap on its subscription. 1. Pass the client's events to the book's `on_event`. After a gap on its subscription, a book built from delta frames refuses reads and updates. 2. Feed each frame to `apply`. When it fails, or reading the subscription gives an error, stop using the book's prices and close the subscription. 3. Open a new subscription and `reset` the book from its first frame, the snapshot. ```python from grvt import AsyncGrvt, BookError, OrderBook, StreamOverflow book = OrderBook("BTC_USDT_Perp") async def keep_book(): async with AsyncGrvt(env="testnet", on_event=book.on_event) as client: while True: async with client.orderbook_delta_stream(instrument="BTC_USDT_Perp", rate=500) as sub: # a fresh subscription frames = aiter(sub) try: book.reset(await anext(frames)) # the fresh subscription's snapshot async for frame in frames: book.apply(frame) print(book.snapshot().bids[:1]) except (BookError, StreamOverflow): pass # a gap: leaving the block unsubscribes; open a fresh subscription ``` ```typescript import { BookError, Grvt, OrderBook, StreamOverflow } from "grvt"; const book = new OrderBook("BTC_USDT_Perp"); const client = new Grvt({ env: "testnet", onEvent: (e) => book.onEvent(e) }); for (;;) { const sub = client.orderbookDeltaStream({ instrument: "BTC_USDT_Perp", rate: 500 }); // a fresh subscription let first = true; try { for await (const frame of sub) { if (first) book.reset(frame); // the fresh subscription's snapshot else book.apply(frame); first = false; console.log(book.snapshot().bids[0]); } } catch (e) { if (!(e instanceof BookError || e instanceof StreamOverflow)) throw e; // a gap: open a fresh subscription } finally { await sub.close(); } } ``` ```go book, err := grvt.NewOrderBook("BTC_USDT_Perp", grvt.BookDelta) if err != nil { return err } client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), OnEvent: book.OnEvent}) if err != nil { return err } defer client.Close() for ctx.Err() == nil { sub, err := client.OrderbookDeltaStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{ Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500)}) // a fresh subscription if err != nil { return err } first := true for frame, err := range sub.All() { if err != nil { break // overflow or a frame that couldn't be decoded: open a fresh subscription } if first { err = book.Reset(*frame) // the fresh subscription's snapshot } else { err = book.Apply(*frame) } first = false if err != nil { break // a gap: open a fresh subscription } if snap, err := book.Snapshot(); err == nil { fmt.Println(len(snap.Bids), len(snap.Asks)) } } sub.Close() } ``` ```rust use futures::StreamExt; use grvt::{BookMode, Config, Grvt, OrderBook}; use std::sync::{Arc, Mutex}; let book = Arc::new(Mutex::new(OrderBook::new("BTC_USDT_Perp", BookMode::Delta))); let hook = book.clone(); let client = Grvt::new(Config::testnet().on_event(move |ev| hook.lock().unwrap().on_event(ev)))?; loop { let mut sub = client.orderbook_delta_stream().instrument("BTC_USDT_Perp").rate(500).await?; // a fresh subscription let mut first = true; while let Some(frame) = sub.next().await { let Ok(frame) = frame else { break }; // overflow or a frame that couldn't be decoded: open a fresh subscription let mut book = book.lock().unwrap(); let applied = if first { book.reset(&frame) } else { book.apply(&frame) }; // first: the snapshot first = false; if applied.is_err() { break; // a gap: dropping `sub` unsubscribes; open a fresh subscription } if let Ok(snap) = book.snapshot() { println!("{:?}", snap.bids.first()); } } } ``` **Watch out:** - Reset only from a new subscription's first frame. The old subscription's queue can still hold frames from before the gap, even a snapshot, and the helper can't tell where a snapshot came from. - A frame that can't be decoded is skipped with an error but no gap event. `apply` notices the missing delta on the next frame, except right after the snapshot, so treat any read error as a gap. - A restored book shows current price levels only, not missed fills or other private events. ## Fill missed events from history **When:** you missed events and want to fill the gap from REST history. 1. Pick the history call and a time window that overlaps your checkpoint: the last point up to which you processed every event. | Missed | History call | Drop duplicates by | |---|---|---| | Fills | [fill_history](/reference/rpc/fill_history.md) | `trade_id` | | Closed orders | [order_history](/reference/rpc/order_history.md) | `order_id` | | Transfers | [transfer_history](/reference/rpc/transfer_history.md) | `tx_id` | 2. Page through it with `backfill_pages`, which follows the cursors for you. Your callback makes one call per cursor. 3. Skip anything whose ID you already handled. 4. Compare the result with current [open_orders](/reference/rpc/open_orders.md) and [positions](/reference/rpc/positions.md). 5. If the history can't account for the gap, don't move your checkpoint past it: treat the gap as unresolved. ```python from grvt import backfill_pages # gap: the gap event's ev.gap. checkpoint: a Timestamp. seen: the trade IDs you already handled. async for result in backfill_pages( lambda cursor: client.fill_history(sub_account_id=sub_account_id, start_time=checkpoint, cursor=cursor), gap=gap, ): for fill in result.page.result or []: if fill.trade_id not in seen: seen.add(fill.trade_id) handle(fill) ``` ```typescript import { backfillPages } from "grvt"; // gap: the gap event's e.gap. checkpoint: a Timestamp. seen: the trade IDs you already handled. for await (const { page } of backfillPages( (cursor) => client.fillHistory({ sub_account_id: subAccountId, start_time: checkpoint, cursor }), gap, )) { for (const fill of page.result ?? []) { if (seen.has(fill.trade_id)) continue; seen.add(fill.trade_id); handle(fill); } } ``` ```go // gap: the gap event's *e.Gap. checkpoint: a time.Time. seen: the trade IDs you already handled. fetch := func(ctx context.Context, cursor string) (models.ApiFillHistoryResponse, error) { resp, err := client.FillHistory(ctx, &models.ApiFillHistoryRequest{ SubAccountID: subAccountID, StartTime: &checkpoint, Cursor: cursor}) if err != nil { return models.ApiFillHistoryResponse{}, err } return *resp, nil } for result, err := range grvt.BackfillPages(ctx, fetch, gap) { if err != nil { return err } for _, fill := range result.Page.Result { if !seen[fill.TradeID] { seen[fill.TradeID] = true handle(fill) } } } ``` ```rust use futures::StreamExt; use grvt::backfill_pages; // gap: the gap event's gap. checkpoint: a grvt::Timestamp. seen: the trade IDs you already handled. let pages = backfill_pages( |cursor: Option| { let call = client.fill_history().sub_account_id(sub_account_id).start_time(checkpoint); let call = match cursor { Some(cursor) => call.cursor(cursor), None => call, }; async move { call.await } }, gap, ); futures::pin_mut!(pages); while let Some(result) = pages.next().await { for fill in result?.page.result.unwrap_or_default() { if seen.insert(fill.trade_id.clone()) { handle(fill); } } } ``` **Watch out:** - `backfill_pages` marks every page `continuity="unproven"`, even an empty last page. Running out of cursors only means this pass has no more pages; delayed history may still appear. Don't wait for "proven". - A WebSocket sequence number is not a REST cursor or a timestamp. Don't use it to page history. ## Run the recovery walkthrough 1. Install the Python SDK ([installation instructions](/sdks/python.md)). 2. Download this example. 3. Run `python recovery.py`. It runs offline on recorded frames and pages, not against the exchange. It shows that a book with a gap refuses reads and queued frames, that a new snapshot restores the book, and that history with no more pages still can't prove it covers every missed event. [Download this example](/downloads/examples/python/examples/recovery.py) ```python """Offline recovery walkthrough. Run with the installed grvt package; no keys needed.""" from dataclasses import dataclass from decimal import Decimal from grvt import BookError, Event, EventKind, GapRange, OrderBook, Timestamp, backfill_pages_sync, models def snapshot(price: str) -> models.WSOrderbookLevelsFeedDataV1: # A fixture stands in for a snapshot from a newly opened subscription. return models.WSOrderbookLevelsFeedDataV1( stream="v1.book.d", selector="BTC_USDT_Perp@500", sequence_number="0", prev_sequence_number="0", feed=models.OrderbookLevels( event_time=Timestamp(0), instrument="BTC_USDT_Perp", bids=[models.OrderbookLevel(price=Decimal(price), size=Decimal("1"), num_orders=1)], asks=[], ), ) def recover_book() -> None: book = OrderBook("BTC_USDT_Perp") old_snapshot = snapshot("100") book.apply(old_snapshot) gap = GapRange(after_sequence=10, through_sequence=None, reason="disconnect") # Forward the hook event before consuming more frames from the subscription. book.on_event(Event(kind=EventKind.GAP, stream=old_snapshot.stream, selector=old_snapshot.selector, gap=gap)) for operation in (book.snapshot, lambda: book.apply(old_snapshot)): try: operation() except BookError: pass else: raise AssertionError("a gapped book must reject reads and queued frames") # In a live application: close the old subscription, open a fresh one, then # read its snapshot. Do not use reset to accept a frame from the old queue. fresh_snapshot = snapshot("101") book.reset(fresh_snapshot) assert book.snapshot().bids[0].price == Decimal("101") print("fresh snapshot restored book; missed private events remain unresolved") @dataclass class HistoryPage: next: str | None events: tuple[str, ...] def inspect_history() -> None: gap = GapRange(after_sequence=10, through_sequence=None, reason="disconnect") pages = {None: HistoryPage("second-page", ("fill-1",)), "second-page": HistoryPage(None, ())} calls: list[str | None] = [] def fetch(cursor: str | None) -> HistoryPage: # In a live application this callback chooses the history endpoint, # account and overlapping time window. A sequence is not a REST cursor. calls.append(cursor) return pages[cursor] for result in backfill_pages_sync(fetch, gap=gap): assert result.continuity == "unproven" print("history", result.page.events, "exhausted", result.history_exhausted, result.continuity) assert calls == [None, "second-page"] # An empty final page is not proof that delayed events cannot appear later. assert result.history_exhausted and result.continuity == "unproven" if __name__ == "__main__": recover_book() inspect_history() ``` ===== guides/rate-limits.md # Rate limits Grvt limits how often you can call the API. Every HTTP response says which limit applied and how much of it is left, so read it from there instead of hard-coding numbers. ## Reading your limit - `X-RateLimit-Limit` and `X-RateLimit-Remaining` on each HTTP response show the limit that applied. - Over the limit, a call fails with error `1006` (HTTP 429). Wait, then retry. ## What your limit depends on - **Account tier.** Limits follow your main account's `tier`, returned by [funding_account_summary](/reference/rpc/funding_account_summary.md). Calls without a session get tier 1. - **IP address, for market data.** Market-data limits are per IP. [ticker](/reference/rpc/ticker.md) calls for stable funding perps (`_SFP` instruments) can have their own per-IP budget, shared by all stable funding perps. ## Staying under the limit - Subscribe to a stream instead of polling for prices. - Use the SDK: it retries reads after a `1006` with backoff (3 tries, within the call timeout of 30 s by default, login included). Writes are never retried, so you see the error ([What the SDK retries](/guides/errors-and-retries.md#what-the-sdk-retries)). Each retry shows up in `on_event`. ## Not documented yet Exact numbers per endpoint and tier, and WebSocket limits (messages per second, subscriptions and sockets per account), including whether WebSocket and HTTP order entry share a budget. Until then, go by the response headers. ===== guides/migrating.md # Migrating from grvt-pysdk The old SDKs (`grvt-pysdk`, `@grvt/client`, `@grvt/sdk`) are replaced, not wrapped. The new SDK is generated from the same contract as these docs, so every method name matches a reference page. ## What changes | | Old | New | |---|---|---| | Client | `GrvtRawSync(config)`, `GrvtRawAsync`, `GrvtCcxt`, `GrvtCcxtPro` | `Grvt(env)` (blocking) or `AsyncGrvt(env)` | | Method names | `get_all_instruments_v1(ApiGetAllInstrumentsRequest(...))`, ccxt `fetch_ticker("BTC_USDT_Perp")` | `client.get_all_instruments(...)`: `client.`, request fields as keyword args | | Environment | `GrvtEnv.TESTNET` + endpoint config | `env="testnet"` (or your own `Environment`) | | Signing | `grvt_raw_signing` / ccxt utils, called by you | automatic for signed calls when you pass `signer=PrivateKeySigner(key)` | | Field names | full names, plus a lite variant | full names in your code; lite on the wire by default (`encoding`) | | Numbers | floats in places (ccxt) | decimal strings and quoted 64-bit ints, as on the wire | | Errors | `GrvtError` dataclass returned in place of a result | exceptions: `ApiError`, `RateLimitError`, `TransportError`, `OrderStateUnknown` | | Retries | varied | reads retried, writes never ([why](/guides/errors-and-retries.md)) | | Streams | `GrvtCcxtWS.subscribe(stream, callback)` | `async with client._stream(...) as sub: async for frame in sub` | | Sequence gaps | handled by you | detected and re-synced by the SDK | ## Side by side Old (raw, sync): ```python nocheck api = GrvtRawSync(GrvtApiConfig(env=GrvtEnv.TESTNET, trading_account_id=..., private_key=..., api_key=...)) resp = api.get_all_instruments_v1(types.ApiGetAllInstrumentsRequest(is_active=True)) ``` New: ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_all_instruments(is_active=True) print(len(resp.result or [])) ``` Old (ccxt-style order): ```python nocheck api = GrvtCcxt(env=GrvtEnv.TESTNET, parameters={"api_key": ..., "trading_account_id": ..., "private_key": ...}) api.create_order(symbol="BTC_USDT_Perp", order_type="limit", side="buy", amount=0.01, price=64000) ``` New: build the order with the wire fields (`time_in_force`, `legs[].size`, `legs[].limit_price`, `legs[].is_buying_asset`) as in [create_order](/reference/rpc/create_order.md). There is no ccxt layer; use CCXT itself if you want one. ## Method name lookup The old raw method `foo_v1` usually becomes `client.foo`. When it does not, search [llms.txt](/llms.txt) or the [API reference](/reference/index.md) for the HTTP path you used (e.g. `/full/v1/all_instruments`); each page shows its SDK method. ## From the old JS client `@grvt/client` and `@grvt/sdk` had two clients: `new GRVT.MDG({host})` for market data and `new GRVT.TDG(...)` for trading. The [TypeScript SDK](/sdks/typescript.md) replaces both with one client, `new Grvt({ env: "testnet" })`. Its methods follow the same reference pages as the Python names above, in camelCase. ===== sdks/python.md # Python SDK > [!WARNING] > **Preview.** Any 0.x release can change the API, so pin the exact version you install ([Install](/sdks/python.md#install)). The Python SDK has a method for every call and stream in the [API reference](/reference/index.md). 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](/sdks/python.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/python.md#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. ```sh 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. ```python 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`: ```python 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`. - `env` is `"testnet"`, or `"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="full"` 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). - Client settings are keyword arguments, typed by `ClientOptions`, so a type checker catches unknown names. - `transport=` takes your own `HttpTransport` for HTTP calls. WebSockets always use aiohttp. - A custom `Environment` with `encoding="lite"` uses `md_ws_url` / `td_ws_url` with the ending `/ws/full` swapped for `/ws/lite`. Set `md_ws_lite_url` / `td_ws_lite_url` only when its URLs don't end in `/ws/full`. ## Call an RPC Every call is a method on the client, `client.(...)`, named exactly as on its reference page. Pass the request fields as keyword arguments; you get back a typed model. ```python 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](/guides/errors-and-retries.md#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_timeout` limits the whole call: login, instrument lookup, signing, retries and the response. `http_attempt_timeout` caps each HTTP attempt within what's left. - For one call, pass `options=CallOptions(timeout=...)`. It replaces `call_timeout` for that call; the blocking client takes it too. ```python 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`. ```python 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_orders` 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.trade_stream(...)`. 1. Open the stream with `async with`. 2. Read frames with `async for`. 3. Leave the `async with` block to unsubscribe. ```python 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](/guides/recovery.md#what-happens-after-a-gap)). - Each subscription queues up to 4096 frames (client option `queue_size`, at least 1). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others raise `StreamOverflow` out of your `async for`: catch it and loop again ([stream errors](/guides/websocket.md#read-a-stream)). ## Place an order 1. Build an `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](/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. It works on a copy, so your `OrderInput` 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). ```python 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](/guides/signing.md#rules-that-cause-most-rejections): ```python 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](/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 the same `OrderInput` again places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits raises `OrderOutOfBounds` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). `check_orders=False` on 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 `address` property: the signing wallet's address; - an async `sign_typed(domain, primary_type, message)` method that returns a `grvt.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: - `r` and `s` are 32 bytes of hex and `v` is 27 or 28; - `s` is low-s ([Signing, step 5](/guides/signing.md#the-steps)). Some KMS backends, AWS KMS for one, return a high `s`: replace it with n - s (n is the secp256k1 curve order) and flip `v` between 27 and 28; - the signature recovers to `address`; - the `signer` field is empty or equal to `address`. 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. 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: `enums.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. ```python 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](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are imports from `grvt`, not client methods. Blocking versions end in `_sync`. ```python from grvt import OrderBook, backfill_pages, refresh_cancel_countdown, resolve_order ``` | Helper | What it does | |---|---| | `resolve_order(client, sub_account_id=..., client_order_id=...)` | Looks up an order whose write outcome is unknown. It never resends. | | `OrderBook(instrument)` | Keeps a local book from order-book stream frames. | | `backfill_pages(fetch, gap=...)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `refresh_cancel_countdown(client, sub_account_id=..., countdown_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 `gap` and `session_rotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#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.ws_max_frame_bytes`; 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](/reference/errors.md). ## Hooks and logging - `GRVT_LOG=debug` prints 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](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): 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 and `None` otherwise. `frame` events carry the raw bytes sent and received, **not redacted**. ```python 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 UTC `datetime`, cut to the microsecond. `Timestamp.from_datetime()` needs a `datetime` with 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 be `None` 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. - Enums are generated string enums. A value added by a newer server decodes as an extra member, so give your `match` a 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](/guides/recovery.md#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](/guides/websocket.md#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](/guides/websocket.md#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. ===== sdks/typescript.md # TypeScript SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. [Install](/sdks/typescript.md#install) says what to pin. The TypeScript SDK has a method for every call and stream in the [API reference](/reference/index.md). 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](/sdks/typescript.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/typescript.md#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. ```sh 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#` (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: ```yaml allowBuilds: "grvt@#": true ``` - **bun** hasn't been tested. ## Create a client ```ts 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](/guides/environments.md)). - 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](/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). **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.(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. ```ts 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](/guides/errors-and-retries.md#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. ```ts 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. ```ts // 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](/guides/recovery.md#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](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others throw `StreamOverflow` out of your `for await`: catch it and loop again ([stream errors](/guides/websocket.md#read-a-stream)). ## 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](/reference/enums.md)). 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). ```ts 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](/guides/signing.md#rules-that-cause-most-rejections): ```ts 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](/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 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](/guides/errors-and-retries.md#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](/guides/signing.md#the-steps)). 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](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `cancelOrder` with `sub_account_id` and `client_order_id` (or `order_id`), after the create has replied. ```ts 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](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are imports from `grvt`, not client methods. ```ts import { OrderBook, backfillPages, refreshCancelCountdown, resolveOrder } from "grvt"; ``` | Helper | What 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](/guides/websocket.md#cancel-orders-if-your-app-stops) 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](/guides/recovery.md#sdk-helpers). ## Errors | Class | When | |---|---| | `ApiError` | the server answered with an error code; has `code`, `serverMessage` (`message` is the full text), `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 throws `OrderStateUnknown` instead | | `OrderStateUnknown` | a write may or may not have happened; look it up by `clientOrderId` (`clientOrderIds` for a bulk call). The original failure is its `cause` | | `OrderOutOfBounds` | an order breaks its instrument's limits; nothing was sent; has `nearest` and `serverCode` | | `StreamOverflow` | your 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`, `ClosedError` | local 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](/reference/errors.md). ## 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](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): 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. ```ts 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](/guides/recovery.md#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](/sdks/typescript.md#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. ===== sdks/go.md # Go SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. Your `go.mod` pins the version you get. The Go SDK has a method for every call and stream in the [API reference](/reference/index.md). 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). Every call takes a `context.Context`. New here? [Install](/sdks/go.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/go.md#track-and-cancel-an-order). Later sections are for when you need them. ## Install ```sh go get github.com/gravity-technologies/grvt-sdk-go ``` The SDK is in preview: any 0.x release can change the API, and your `go.mod` pins the version you get. It needs Go 1.27.4 or newer. ## Create a client ```go package main import ( "context" "fmt" "log" "os" grvt "github.com/gravity-technologies/grvt-sdk-go" "github.com/gravity-technologies/grvt-sdk-go/models" ) func main() { ctx := context.Background() // The API key logs in; the signer signs orders with your signing key. Leave both out for public data only. signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY")) if err != nil { log.Fatal(err) } client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer}) if err != nil { log.Fatal(err) } defer client.Close() t, err := client.Ticker(ctx, &models.ApiTickerRequest{Instrument: "BTC_USDT_Perp"}) if err != nil { log.Fatal(err) } fmt.Println(t.Result.MarkPrice) // the exchange's fair price, used for margin } ``` - Use `grvt.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.EncodingFull` in the `Config` switches to full names ([Encoding](/guides/environments.md#encoding-full-or-lite)). On a custom `Environment`, lite WebSocket URLs are the full ones with `/ws/full` swapped for `/ws/lite`; set `MarketDataWSLite` and `TradingWSLite` only when your URLs don't end in `/ws/full`. - 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.(ctx, *Request) (*Response, error)`: the name on its reference page in Go style (`create_order` is `client.CreateOrder`). Request and response types keep the contract names, and their JSON tags are the wire field names. ```go inst, err := client.GetInstrument(ctx, &models.ApiGetInstrumentRequest{Instrument: "BTC_USDT_Perp"}) if err != nil { return err } fmt.Println(inst.Result.TickSize, inst.Result.MinSize) ``` - 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, in the `Config`: `CallTimeout` (30 s), `HTTPAttemptTimeout` (10 s), `WSRequestTimeout` (5 s), `ResyncTimeout` (5 s), `IdleTimeout` (30 s). A shorter deadline on the `ctx` you pass also applies. `CallTimeout` covers the whole call: login, instrument lookups, signing, retries and the reply; `HTTPAttemptTimeout` caps each HTTP try within it. - `Config.HTTPClient` replaces the default HTTP client, for REST and the WebSocket handshake. The SDK copies it and never follows redirects; a `Timeout` on it is one more cap per attempt. ## Pagination `grvt.Pages` follows a history call's cursors one page at a time, without fetching ahead. Pass an empty starting cursor for the first page, and keep the filters fixed inside your callback. ```go fetch := func(ctx context.Context, cursor string) (*models.ApiTradeHistoryResponse, error) { return client.TradeHistory(ctx, &models.ApiTradeHistoryRequest{ Instrument: "BTC_USDT_Perp", Cursor: cursor, }) } for page, err := range grvt.Pages(ctx, fetch, "") { if err != nil { return err } for _, trade := range page.Result { fmt.Println(trade) } } ``` - An empty page can still have a next cursor. - Breaking out of the loop stops further calls; the `ctx` cancels a fetch in progress. - A cursor seen twice returns `*grvt.PaginationCycleError`. Fetch errors pass through, with no extra retries. - Cursors don't give a stable snapshot while records change. ## Default sub-account Set `SubAccountID` in the `Config` to fill in the account on requests and stream selectors that leave it out. - Zero in the `Config` means no default. Zero in a request or selector means "not set"; in an `OrderInput`, `nil` means not set. - An account you set yourself always wins. - Bulk orders take the request's account first, then the client default. - Transfers never get a default: source and destination stay explicit. - Defaults are applied to a copy of your request, before signing. - Without a default, a call that needs an account fails unless the request names one. ## Stream data Every stream method ends in `Stream`, for example `client.TradeStream`. 1. Call the stream method to get a subscription. 2. Range over `All()` to read frames, or call `Next(ctx)` to stop when a context ends. 3. Call `Close()` to unsubscribe. Breaking out of the loop doesn't unsubscribe. ```go book, err := client.OrderbookDeltaStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{ Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500)}) // Rate: update interval in ms if err != nil { return err } defer book.Close() for frame, err := range book.All() { if err != nil { log.Print(err) // the loop goes on after an error continue } fmt.Println(frame.SequenceNumber) } ``` `frame.SequenceNumber` is a `uint64`. It is a string on the wire; the SDK decodes it for you. A gap event's bounds are `*uint64`. **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 (`QueueSize` in the `Config`, at least 1). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others yield `*grvt.StreamOverflowError` ([stream errors](/guides/websocket.md#read-a-stream)). ## Place an order 1. Build a `models.OrderInput` with `models.Decimal` price and size. `IsBuyingAsset` is true to buy, false to sell. `TimeInForceGoodTillTime` (GTT) rests until filled, cancelled or expired; `PostOnly` rejects the order rather than let it trade at once ([TimeInForce](/reference/enums.md)). 2. Call `CreateOrder`. The SDK fills in the signature and a `client_order_id`, and looks up the instrument details it needs to sign (once per instrument, then cached). It works on a copy, so your request struct is not changed. 3. Save the `client_order_id`: you follow the order by it, because the reply's `OrderID` 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). ```go package main import ( "context" "fmt" "log" "os" "strconv" grvt "github.com/gravity-technologies/grvt-sdk-go" "github.com/gravity-technologies/grvt-sdk-go/models" ) func main() { ctx := context.Background() signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY")) if err != nil { log.Fatal(err) } client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer}) if err != nil { log.Fatal(err) } defer client.Close() sub, err := strconv.ParseUint(os.Getenv("GRVT_SUB_ACCOUNT_ID"), 10, 64) if err != nil { log.Fatal(err) } order := models.OrderInput{ SubAccountID: &sub, TimeInForce: models.TimeInForceGoodTillTime, PostOnly: grvt.Ptr(true), Legs: []models.OrderLeg{{Instrument: "BTC_USDT_Perp", Size: models.MustParseDecimal("0.01"), LimitPrice: grvt.Ptr(models.MustParseDecimal("60000")), IsBuyingAsset: true}}, } resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) if err != nil { log.Fatal(err) } fmt.Println(resp.Result.Metadata.ClientOrderID) } ``` 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): ```go order.Metadata = &models.OrderMetadataInput{ClientOrderID: grvt.Ptr(1<<63 | rand.Uint64())} // math/rand/v2 ``` Orders go over HTTP by default. Set `OrderTransport: grvt.OrderTransportWS` in 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 the same request struct again places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits returns `*grvt.OrderOutOfBoundsError` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). `CheckOrders: grvt.Ptr(false)` in the `Config` turns the check off and leaves the limits to the exchange. - A decimal with more digits than its signed field allows fails with `*grvt.SigningError` before anything is sent. The SDK never rounds. ## 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` before you place the order. 2. Match updates by `Metadata.ClientOrderID`. The updates also carry the `OrderID`. 3. Stop at a final status: `models.OrderStatusFilled`, `OrderStatusRejected` or `OrderStatusCancelled` ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `CancelOrder` with `SubAccountID` and `ClientOrderID` (or `OrderID`), after the create has replied. ```go orders, err := client.OrderStream(ctx, &models.WSOrderFeedSelectorV1{SubAccountID: sub}) if err != nil { return err } defer orders.Close() resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) if err != nil { return err } id := resp.Result.Metadata.ClientOrderID if _, err := client.CancelOrder(ctx, &models.ApiCancelOrderRequest{SubAccountID: sub, ClientOrderID: &id}); err != nil { return err } for { frame, err := orders.Next(ctx) if ctx.Err() != nil { return ctx.Err() } if errors.Is(err, grvt.ErrClosed) { return err } if err != nil || frame.Feed.Metadata.ClientOrderID != id || frame.Feed.State == nil { continue } switch s := frame.Feed.State; s.Status { case models.OrderStatusFilled, models.OrderStatusRejected, models.OrderStatusCancelled: fmt.Println(frame.Feed.OrderID, s.Status, s.RejectReason) return nil } } ``` ## Recover a lost order response **When:** a write times out or the socket drops before the response arrives. You get `*grvt.OrderStateUnknownError`. Look the order up with `grvt.ResolveOrder`; 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 functions and types in package `grvt`, not client methods. Pass the client in where they need it. ```go import grvt "github.com/gravity-technologies/grvt-sdk-go" // grvt.ResolveOrder, grvt.NewOrderBook, grvt.BackfillPages, grvt.RefreshCancelCountdown ``` | Helper | What it does | |---|---| | `grvt.ResolveOrder(ctx, client, subAccountID, clientOrderID)` | Looks up an order whose write outcome is unknown. It never resends. | | `grvt.NewOrderBook(instrument, grvt.BookDelta)` | Keeps a local book from order-book stream frames. | | `grvt.BackfillPages(ctx, fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `grvt.RefreshCancelCountdown(ctx, client, subAccountID, 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 `OnEvent` hook gets the `grvt.EventGap` and `grvt.EventSessionRotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#sdk-helpers). ## Errors Check errors with `errors.As`: | Type | When | |---|---| | `*grvt.APIError` | the server answered with an error code; has `Code`, `Message`, `Status` (0 over WebSocket), `RPC`, `Retryable` | | `*grvt.RateLimitError` | code `1006` (HTTP 429); `errors.As` also finds it as `*APIError`; reads were already retried | | `*grvt.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 returns `*grvt.OrderStateUnknownError` instead | | `*grvt.OrderStateUnknownError` | a write may or may not have happened; look it up by `ClientOrderID` (`ClientOrderIDs` for a bulk call). It wraps the original failure (`errors.Unwrap`), such as a `*grvt.TransportError`, so check for it first | | `*grvt.OrderOutOfBoundsError` | an order breaks its instrument's limits; nothing was sent; has `Nearest` and `ServerCode` | | `*grvt.StreamOverflowError` | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced | | `*grvt.SigningError`, `*grvt.DecodeError`, `*grvt.ConfigError`, `*grvt.FrameTooLargeError`, `grvt.ErrClosed` | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed | `*grvt.FrameTooLargeError` comes only when you set `Environment.WSMaxFrameBytes`: the named environments don't check frame size. An oversized frame is not sent over HTTP instead. Error code constants are `grvt.Code`, for example `grvt.CodeSignatureExpired`. The full list is on [Error codes](/reference/errors.md). Handle a create like this. Check for `*grvt.OrderStateUnknownError` first, because it wraps the original failure: ```go resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) var unknown *grvt.OrderStateUnknownError var bounds *grvt.OrderOutOfBoundsError var apiErr *grvt.APIError switch { case errors.As(err, &unknown): // The order may or may not exist. Look it up; never resend it. _, err = grvt.ResolveOrder(ctx, client, sub, unknown.ClientOrderID) return err case errors.As(err, &bounds): return fmt.Errorf("not sent, breaks %s: %w", bounds.Limit, err) case errors.As(err, &apiErr): return fmt.Errorf("rejected with code %d: %w", apiErr.Code, err) case err != nil: return err } fmt.Println("placed", resp.Result.Metadata.ClientOrderID) ``` ## Hooks and logging - `GRVT_LOG=debug` logs every request and frame to stderr, with the session cookie, API key, private keys and signatures redacted. Set `Logger` (a `*slog.Logger`) in the `Config` to send the logs elsewhere. - `BeforeSend` in the `Config` runs before each RPC is signed and may change the typed request in place (`call.Params`). 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. - `OnEvent` gets connect, disconnect, reconnect, subscribe, gap, retry, frame, session_rotated and error events. It runs on the socket's read goroutine, so it must return quickly: while it blocks, no frame on that socket is read. ```go client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), OnEvent: func(e grvt.Event) { if e.Kind == grvt.EventGap { log.Printf("re-syncing %s %s", e.Stream, e.Selector) } }}) ``` ## Running in production - **Concurrency.** One `*grvt.Client` is safe for concurrent use: share it across goroutines. Calls that need a login at the same time share one login. - **Context.** Cancelling the `ctx` of a read returns the context's error. Cancelling a write after it may have left returns `*grvt.OrderStateUnknownError`. Cancelling never closes the shared WebSocket. `Next(ctx)` returns the context's error and the subscription stays open; `All()` takes no context and ends only after `Close`. - **`Close()`.** Ends every subscription (`Next` returns `grvt.ErrClosed`, `All` stops) and fails WebSocket calls still waiting for a reply: writes with `*grvt.OrderStateUnknownError`. Later calls return `grvt.ErrClosed`. An HTTP call already running is bounded by its own `ctx`, not by `Close`. - **Reconnects.** Each socket reconnects on its own with full-jitter backoff: a random wait between 0 and 250 ms × 2^attempt, never more than 30 s. The backoff resets once a connection has stayed up for 10 s. Each connect (login and handshake) gets 10 s. The client reconnects when nothing arrives for 30 s, and pings three times in that window. A refused login or a handshake rejected with 401 or 403 stops that socket for good: its subscriptions and calls return the error. - **Rate limits.** The SDK has no client-side rate limiter and doesn't read `Retry-After`. A read that gets `1006` is retried (3 tries in all, waits of up to 100 ms, then twice that). A write returns `*grvt.RateLimitError` at once. Pace your own requests ([Rate limits](/guides/rate-limits.md)). - **Client order IDs.** Set your own per order ([Place an order](/sdks/go.md#place-an-order)) or plug in a `grvt.ClientOrderIDProvider` as `ClientOrderIDs` in the `Config`. The default is `1<<63 | seconds<<31 | counter`, from the wall clock (not `Config.Clock`). Its counter starts at a random value in each process, so IDs are unique within a process; two processes rarely collide, but can. - **Session renewal.** After the client logs in again, each socket closes once none of its writes is waiting for a reply (it checks every 500 ms), then reconnects with the new cookie, usually after a wait of up to 250 ms. WebSocket calls made in between wait up to 10 s for the new socket. HTTP calls, including orders on the default transport, are not interrupted. A failed re-login is retried after 5 s ([Session renewal](/guides/websocket.md#session-renewal)). ## Data types - Decimals use `models.Decimal`. Parse exact text with `models.ParseDecimal`; use `MustParseDecimal` only for constants. `Rat()` gives an exact `*big.Rat` for arithmetic. - Nanosecond timestamps use `time.Time`. Values outside the wire range are rejected. - IDs are `uint64` and travel as JSON strings; a single ID must arrive as a string. Lists of IDs (`models.Uint64s`) accept numbers too. - Required fields use plain values. Optional strings and enums use `""` for absent. Other optional fields (numbers, bools, decimals, nested types) are pointers, so `0` and `false` can be sent: use `grvt.Ptr(...)`. - 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. - Enums are string types with constants for the known values. A value added by a newer server arrives as its plain string, so give your `switch` a `default` case. - 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 `grvt.BackfillPages` ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). - **Wallet login.** The client logs in with an API key only. ===== sdks/rust.md # Rust SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. [Install](/sdks/rust.md#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](/sdks/rust.md#without-the-client). New here? [Install](/sdks/rust.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/rust.md#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 = "="`). For the crate [without the client](/sdks/rust.md#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> { // 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.()`, 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`. **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> { 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_(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](/sdks/rust.md#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::(&env, &req, Some(&session))?; // method, url, headers, body let (status, body) = send(&http); // send: your HTTP client let reply = grvt::rest_response::(status, &body, &ids); ``` - **Signing** is synchronous. `metadata` holds the instruments and currencies that `signing::needs_` 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::(&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::(&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::(..)`, `.ws_request::(..)`, `.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](/sdks/rust.md#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](/sdks/rust.md#without-the-client). ===== guides/stable-perps.md # Stable funding perps (SFP) A stable funding perp (SFP) is a perpetual on a traditional market such as gold or crude oil. Its instruments end in `_SFP` (for example `XAU_USDC_SFP`) and have `kind` `STABLE_PERP`. It differs from a crypto perpetual in four ways: - It trades only while its underlying market is open ([Trading hours](/guides/stable-perps.md#trading-hours)). - It has no mark price (the fair-value price crypto perpetuals use for margin). Margin, PnL (profit and loss) and liquidation use the index price, the underlying market's spot price ([Prices](/guides/stable-perps.md#prices)). - Funding is charged once a day, at separate rates for longs and shorts, quoted as an annual percentage ([Funding](/guides/stable-perps.md#funding)). - Only qualified makers (market makers approved by Grvt) rest orders on the book. Everyone else trades against them as a taker, and takers pay no trading fee ([Placing orders](/guides/stable-perps.md#placing-orders)). The calls are under [RFQ](/reference/index.md#rfq) (request for quote) and [Trading hours](/reference/index.md#trading-hours) in the reference. Most other calls work as usual, with the differences on this page. ## Finding them [get_all_instruments](/reference/rpc/get_all_instruments.md) returns perpetuals only unless you ask for other kinds: ```json {"kinds": ["STABLE_PERP"], "is_active": true} ``` [get_filtered_instruments](/reference/rpc/get_filtered_instruments.md) with `"kind": ["STABLE_PERP"]` works too. Fields that matter here: | Field | Meaning | |---|---| | `asset_class` | Picks the trading schedule, for example `COMMODITY_CME` | | `triple_swap_day` | Stable funding perps only. The weekday whose funding charge covers 3 days (the weekend). It differs by instrument | | `spread_penalty_tolerance` | Stable funding perps only. For makers: how far from the index price a fill can happen before the maker pays a fee penalty ([Fees](/guides/stable-perps.md#placing-orders)) | ## Before you trade The sub-account must be in **multi-asset mode**, where it can hold several currencies as collateral. Otherwise orders and RFQs fail with `2147 StablePerpRequiresMultiAssetMode`. While it holds a stable funding perp position or open order, it can't switch back to single-asset mode. ## Trading hours [get_sfp_trading_schedule](/reference/rpc/get_sfp_trading_schedule.md) returns this week's sessions and this year's holidays for each asset class (and for instrument groups with their own hours). For example, CME commodities trade from Sunday 18:00 to Friday 17:00 New York time, with a break from 17:00 to 18:00 each day. A holiday can close a market early or for the whole day. [ticker](/reference/rpc/ticker.md) shows the current `session` (`REGULAR`, `PRE_MARKET`, `AFTER_MARKET`, `OVERNIGHT` or `CLOSE`). During `CLOSE`, `status` is `CLOSED` and: - new orders and [create_rfq](/reference/rpc/create_rfq.md) fail with `7726 ErrSfpMarketClosed`; cancels still work; - the index price is frozen until the market opens again; - liquidation continues. ## Prices The **index price** values positions for margin, PnL and liquidation. It also triggers take-profit and stop-loss orders with `trigger_by` `INDEX` or `MID` (others get `2111 UnsupportedTriggerBy`). Market data differs from perpetuals: | Call | For stable funding perps | |---|---| | [ticker](/reference/rpc/ticker.md), `v1.ticker.s` / `v1.ticker.d` | No `mark_price`, `funding_rate*`, `best_bid_size`, `best_ask_size`, `last_size` or `long_short_ratio`. Adds `funding_rate_long_apr_pct`, `funding_rate_short_apr_pct` and `session`. Stream `rate` must be 5000 ms or more. REST calls can have their own per-IP budget, shared by all stable funding perps ([Rate limits](/guides/rate-limits.md)) | | [candlestick](/reference/rpc/candlestick.md), `v1.candle` | `INDEX` candles only (`3043` for other types) | | [mini_ticker](/reference/rpc/mini_ticker.md), [trade](/reference/rpc/trade.md), [trade_history](/reference/rpc/trade_history.md), and their streams | Not available: `7725 ErrSfpEndpointNotSupported`. Your own fills are in [fill_history](/reference/rpc/fill_history.md) | | [orderbook_levels](/reference/rpc/orderbook_levels.md), `v1.book.*` | As usual. The book holds qualified makers' orders | ## Funding Each trading day, at the close of the regular session, every open position pays or receives funding. Longs and shorts have separate rates, each an annual percentage. For both, positive means that side receives and negative means it pays. **How much**, for one position: ``` amount = abs(size) × index price × abs(rate) / 100 × days / 365 ``` - `size` is the position size, without its sign: the side decides which rate applies. (Qualified makers are paid differently.) - `index price` is the index when the charge runs, within a minute after the charge time. [funding_rate](/reference/rpc/funding_rate.md) records it as `mark_price`. - `days` is 3 on the instrument's `triple_swap_day` (covering the weekend) and 1 on other days. There is no charge on Saturday or Sunday. - On a weekday holiday the charge runs once as usual: at the early close if the market closes early, otherwise at its regular close time. [ticker](/reference/rpc/ticker.md)'s `next_funding_time` is the exact time of the next charge. - Amounts are rounded in the exchange's favour: up when you pay, down when you receive. For example, a long of 10 `XAU_USDC_SFP` at an index of 3,880 and a long rate of `-5.44` pays about 5.78 USDC a day, and about 17.35 USDC on its triple day. | Where to read it | What | |---|---| | [ticker](/reference/rpc/ticker.md) | The rates for the next charge (`funding_rate_long_apr_pct`, `funding_rate_short_apr_pct`) and `next_funding_time`. The rates come from qualified makers and can change until the charge | | [funding_rate](/reference/rpc/funding_rate.md) | Past charges: both rates, `funding_multiplier` (`days` in the formula) and `mark_price` (the index used). Hourly aggregation is rejected (`3008`) | | [funding_payment_history](/reference/rpc/funding_payment_history.md) | What each of your positions paid or received: `amount` is positive when it paid, negative when it received |
Guarantees and edge cases - Each side's rate is the lowest maker rate minus a spread. - With no maker rates, the rate is 0.
## Placing orders | Rule | Error | |---|---| | Limit orders only. To buy "at market", send an IOC order with `limit_price` set to the worst price you accept | `7711` | | Time in force is `GOOD_TILL_TIME` (GTT: rests until filled, cancelled or expired) or `IMMEDIATE_OR_CANCEL` (IOC: fills what it can at once, cancels the rest). No fill-or-kill | `7709` | | Post-only orders (rejected rather than trade at once) are for qualified makers only | `7724` | | No private quotes (`metadata.is_private`) | `7706` | A `GOOD_TILL_TIME` limit order from an account that is not a qualified maker doesn't rest on the public book. It waits off the book and fills, as a taker, when a maker order on the book crosses its price. **Fees.** Takers pay no trading fee. Makers pay their tier's maker fee, plus a penalty on fills more than `spread_penalty_tolerance` (a percentage) from the index price, in the maker's favour. ## Trading a large size: RFQ When the book is too thin for your size, ask for quotes: 1. Call [create_rfq](/reference/rpc/create_rfq.md) with the instrument, `size` and optionally `side` (leave it out to ask both ways). It lives until `expiry`: 60 s by default, at most 300 s. A sub-account can have one open RFQ per instrument (`2146` for a second). 2. Qualified makers see it, with an anonymous ID instead of your account and without your side, and can add orders for it. 3. [v1.quote](/reference/streams/rfq_quote.md) sends you, for each side, the average price for your size and how much of it the book can fill, updated as the book changes (at most every 500 ms). 4. To trade, send an IOC limit order with `metadata.rfq_id` set, on the RFQ's instrument (`7705` otherwise), while the RFQ is open (`7707`). Its side must match the RFQ's side if you gave one; its size can differ. One order per RFQ (`7708` for a second). Or let it expire, or [cancel_rfq](/reference/rpc/cancel_rfq.md). Fills from an RFQ carry `rfq_id` and `counterparty_type`. ## Errors [Error codes](/reference/errors.md) lists every stable funding perp error (codes `77xx` and `78xx`, plus `2111`, `2146`, `2147`, `3008` and `3043`). Two need context their messages don't give: | Code | Name | What it means | |---|---|---| | 7704 | `ErrSfpOrderNotSupported` | Stable funding perp orders are switched off in this environment | | 7701 | `ErrSfpIndicativeNotQualifiedMaker` | A maker-only action (indicative prices or ECN orders) from an account that is not a qualified maker for the instrument | ===== reference/rpc/get_all_instruments.md # Get all instruments | | | |---|---| | SDK | `client.get_all_instruments(...)` | | HTTP | `POST https://market-data./full/v1/all_instruments`, or `/lite/v1/all_instruments` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/all_instruments` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_all_instruments` (`RPCGetAllInstrumentsV1`) | ## Request Body type `ApiGetAllInstrumentsRequest`. Fields the server fills are left out. - `is_active` · lite `ia` · bool · optional, default `false` — Fetch only active instruments - `kinds` · lite `k` · enum Kind[] · optional, default `['PERPETUAL']` — The kind filter to apply. If empty, this defaults to PERPETUAL only. Otherwise, only entries matching the filter will be returned Values: `PERPETUAL`, `FUTURE`, `CALL`, `PUT`, `SPOT_SWAP`, `STABLE_PERP` ([details](/reference/enums.md#kind)). ## Response Body type `ApiGetAllInstrumentsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object InstrumentDisplay[] · required — List of instruments - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result[].instrument_hash` · lite `ih` · string (uint256) · required — The asset ID used for instrument signing. - `result[].base` · lite `b` · string · required — The base currency - `result[].quote` · lite `q` · string · required — The quote currency - `result[].kind` · lite `k` · enum Kind · required — The kind of instrument Values: `PERPETUAL`, `FUTURE`, `CALL`, `PUT`, `SPOT_SWAP`, `STABLE_PERP` ([details](/reference/enums.md#kind)). - `result[].venues` · lite `v` · enum Venue[] · required — Venues that this instrument can be traded at Values: `ORDERBOOK`, `RFQ` ([details](/reference/enums.md#venue)). - `result[].settlement_period` · lite `sp1` · enum InstrumentSettlementPeriod · optional — The settlement period of the instrument Values: `PERPETUAL`, `DAILY`, `WEEKLY`, `MONTHLY`, `QUARTERLY` ([details](/reference/enums.md#instrumentsettlementperiod)). - `result[].base_decimals` · lite `bd` · integer (int8) · required — The smallest denomination of the base asset supported by Grvt (+3 represents 0.001, -3 represents 1000, 0 represents 1) - `result[].quote_decimals` · lite `qd` · integer (int8) · required — The smallest denomination of the quote asset supported by Grvt (+3 represents 0.001, -3 represents 1000, 0 represents 1) - `result[].tick_size` · lite `ts` · string · required — The size of a single tick. Decimal string, e.g. "0.1"; up to 9 decimals. - `result[].min_size` · lite `ms` · string · required — The minimum contract size. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result[].create_time` · lite `ct` · string (int64 unix ns) · required — Creation time in unix nanoseconds - `result[].max_position_size` · lite `mp` · string · optional — The maximum position size. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result[].funding_interval_hours` · lite `fi` · integer (uint8) · optional — Defines the funding interval to be applied. - `result[].adjusted_funding_rate_cap` · lite `af` · string · optional — Funding rate cap over the defined `intervalHours`. - `result[].adjusted_funding_rate_floor` · lite `af1` · string · optional — Funding rate floor over the defined `intervalHours`. - `result[].min_notional` · lite `mn` · string · required — The minimum order notional value, in the quote asset. Decimal string, e.g. "12.5". - `result[].asset_class` · lite `ac` · enum AssetClass · optional — The asset class of the underlying the instrument tracks Values: `CRYPTO`, `EQUITY`, `COMMODITY`, `FX`, `INDEX`, `EQUITY_NASDAQ`, `EQUITY_NYSE`, `EQUITY_KRX`, `COMMODITY_CME`, `PRE_IPO` ([details](/reference/enums.md#assetclass)). - `result[].status` · lite `s` · enum InstrumentStatus · optional — The current lifecycle/trading status of the instrument Values: `ACTIVE`, `REDUCE_ONLY`, `MAINTENANCE`, `HALTED`, `CLOSED`, `PENDING`, `DELISTED` ([details](/reference/enums.md#instrumentstatus)). - `result[].guaranteed_exit_band` · lite `ge` · string · optional — The guaranteed exit band, expressed in percentage points - `result[].spread_penalty_tolerance` · lite `sp2` · string · optional — The spread penalty tolerance, expressed in percentage points - `result[].funding_cap_adjustment_time` · lite `fc` · string (int64 unix ns) · optional — Timestamp in unix nanoseconds at which the funding cap adjustment applies - `result[].funding_cap_adjustment_value` · lite `fc1` · string · optional — The funding cap adjustment value, expressed as a decimal daily rate - `result[].triple_swap_day` · lite `ts2` · enum DayOfWeek · optional — Stable perps only: the weekday whose daily funding charge covers 3 days (the weekend) Values: `MONDAY`, `TUESDAY`, `WEDNESDAY`, `THURSDAY`, `FRIDAY`, `SATURDAY`, `SUNDAY` ([details](/reference/enums.md#dayofweek)). ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_all_instruments() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/all_instruments" \ -H "Content-Type: application/json" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/lite/v1/all_instruments" \ -H "Content-Type: application/json" \ --data '{}' ``` ===== reference/rpc/get_filtered_instruments.md # Get filtered instruments | | | |---|---| | SDK | `client.get_filtered_instruments(...)` | | HTTP | `POST https://market-data./full/v1/instruments`, or `/lite/v1/instruments` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/instruments` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_filtered_instruments` (`RPCGetFilteredInstrumentsV1`) | ## Request Body type `ApiGetFilteredInstrumentsRequest`. Fields the server fills are left out. - `kind` · lite `k` · enum Kind[] · optional, default `all` — The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only entries matching the filter will be returned Values: `PERPETUAL`, `FUTURE`, `CALL`, `PUT`, `SPOT_SWAP`, `STABLE_PERP` ([details](/reference/enums.md#kind)). - `base` · lite `b` · string[] · optional, default `all` — The base filter to apply. If nil, this defaults to all bases. Otherwise, only entries matching the filter will be returned - `quote` · lite `q` · string[] · optional, default `all` — The quote filter to apply. If nil, this defaults to all quotes. Otherwise, only entries matching the filter will be returned - `is_active` · lite `ia` · bool · optional, default `false` — Request for active instruments only - `limit` · lite `l` · integer (uint32) · optional, default `500` — The limit to query for. Defaults to 500; Max 100000 ## Response Body type `ApiGetFilteredInstrumentsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object InstrumentDisplay[] · required — The instruments matching the request filter Fields: see [InstrumentDisplay](/reference/types.md#instrumentdisplay); listed in full under `result[]` on reference/rpc/get_all_instruments.md, earlier in this file. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_filtered_instruments( limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/instruments" \ -H "Content-Type: application/json" \ --data @- </full/v1/instrument`, or `/lite/v1/instrument` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/instrument` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_instrument` (`RPCGetInstrumentV1`) | ## Request Body type `ApiGetInstrumentRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). ## Response Body type `ApiGetInstrumentResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object InstrumentDisplay · required — The instrument matching the request asset Fields: see [InstrumentDisplay](/reference/types.md#instrumentdisplay); listed in full under `result[]` on reference/rpc/get_all_instruments.md, earlier in this file. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_instrument( instrument="BTC_USDT_Perp", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/instrument" \ -H "Content-Type: application/json" \ --data @- </full/v1/currency`, or `/lite/v1/currency` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/currency` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_currency` (`RPCGetCurrencyV1`) | ## Request Body type `ApiGetCurrencyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiGetCurrencyResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object CurrencyDetail[] · required — The list of currencies - `result[].id` · lite `i` · integer (uint16) · required — The integer value of the currency - `result[].symbol` · lite `s` · string · required — The name of the currency - `result[].balance_decimals` · lite `bd` · integer (int8) · required — The balance decimals of the currency - `result[].quantity_multiplier` · lite `qm` · string (uint64) · required — The quantity multiplier of the currency ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_currency() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/currency" \ -H "Content-Type: application/json" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/lite/v1/currency" \ -H "Content-Type: application/json" \ --data '{}' ``` ===== reference/rpc/get_supported_assets.md # Get supported assets | | | |---|---| | SDK | `client.get_supported_assets(...)` | | HTTP | `POST https://market-data./full/v1/supported_assets`, or `/lite/v1/supported_assets` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/supported_assets` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_supported_assets` (`RPCGetSupportedAssetsV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiGetSupportedAssetsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `funding` · lite `f` · object SupportedAsset[] · required — Assets supported in funding wallets - `funding[].asset_id` · lite `ai` · integer (uint16) · required — The currency ID of the asset - `funding[].asset_code` · lite `ac` · string · required — The readable currency code of the asset - `funding[].balance_decimals` · lite `bd` · integer (int8) · required — The number of decimals used for balance representation - `funding[].transfer_disabled` · lite `td` · bool · required — The asset cannot be transferred between wallets - `spot` · lite `s` · object SupportedAsset[] · required — Assets supported in spot wallets Fields: same as `funding[]` above. - `futures` · lite `f1` · object FuturesWalletAssets[] · required — Assets supported in futures wallets, grouped by mode - `futures[].mode` · lite `m` · enum SubAccountMode · required — The sub-account mode Values: `SINGLE_ASSET_MODE` ([details](/reference/enums.md#subaccountmode)). - `futures[].supported_assets` · lite `sa` · object SupportedAsset[] · required — Assets supported under this futures mode Fields: same as `funding[]` above. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_supported_assets() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/supported_assets" \ -H "Content-Type: application/json" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/lite/v1/supported_assets" \ -H "Content-Type: application/json" \ --data '{}' ``` ===== reference/rpc/mini_ticker.md # Mini ticker Please do not use this to repeatedly poll for data -- a websocket subscription is much more performant, and useful. | | | |---|---| | SDK | `client.mini_ticker(...)` | | HTTP | `POST https://market-data./full/v1/mini`, or `/lite/v1/mini` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/mini` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `ticker.mini_ticker` (`RPCMiniTickerV1`) | ## Request Body type `ApiMiniTickerRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). ## Response Body type `ApiMiniTickerResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object MiniTicker · required — The mini ticker matching the request asset - `result.event_time` · lite `et` · string (int64 unix ns) · optional — Time at which the event was emitted in unix nanoseconds - `result.instrument` · lite `i` · string (instrument name) · optional — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result.mark_price` · lite `mp` · string · optional — The mark price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.index_price` · lite `ip` · string · optional — The index price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.last_price` · lite `lp` · string · optional — The last traded price of the instrument (also close price). Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.last_size` · lite `ls` · string · optional — The number of assets traded in the last trade. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.mid_price` · lite `mp1` · string · optional — The mid price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_bid_price` · lite `bb` · string · optional — The best bid price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_bid_size` · lite `bb1` · string · optional — The number of assets offered on the best bid price of the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.best_ask_price` · lite `ba` · string · optional — The best ask price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_ask_size` · lite `ba1` · string · optional — The number of assets offered on the best ask price of the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `7725` SfpEndpointNotSupported (403) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.mini_ticker( instrument="BTC_USDT_Perp", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/mini" \ -H "Content-Type: application/json" \ --data @- </full/v1/ticker`, or `/lite/v1/ticker` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/ticker` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `ticker.ticker` (`RPCTickerV1`) | ## Request Body type `ApiTickerRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). ## Response Body type `ApiTickerResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ticker · required — The mini ticker matching the request asset - `result.event_time` · lite `et` · string (int64 unix ns) · optional — Time at which the event was emitted in unix nanoseconds - `result.instrument` · lite `i` · string (instrument name) · optional — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result.mark_price` · lite `mp` · string · optional — The mark price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.index_price` · lite `ip` · string · optional — The index price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.last_price` · lite `lp` · string · optional — The price of the last trade (the close price). Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.last_size` · lite `ls` · string · optional — The number of assets traded in the last trade. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.mid_price` · lite `mp1` · string · optional — The mid price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_bid_price` · lite `bb` · string · optional — The best bid price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_bid_size` · lite `bb1` · string · optional — The number of assets offered on the best bid price of the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.best_ask_price` · lite `ba` · string · optional — The best ask price of the instrument. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.best_ask_size` · lite `ba1` · string · optional — The number of assets offered on the best ask price of the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.funding_rate_8h_curr` · lite `fr` · string · optional — Deprecated and will be removed. Use `funding_rate`. - `result.funding_rate_8h_avg` · lite `fr1` · string · optional — Deprecated and will be removed. Use `funding_rate`. - `result.interest_rate` · lite `ir` · string · optional — The interest rate of the underlying, in percent (`"0.01"` = 0.01%). - `result.forward_price` · lite `fp` · string · optional — [Options] The forward price of the option. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.buy_volume_24h_b` · lite `bv` · string · optional — Taker buy volume over the last 24 hours, in the base asset. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.sell_volume_24h_b` · lite `sv` · string · optional — Taker sell volume over the last 24 hours, in the base asset. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.buy_volume_24h_q` · lite `bv1` · string · optional — Taker buy volume over the last 24 hours, in the quote asset. Decimal string, e.g. "12.5". - `result.sell_volume_24h_q` · lite `sv1` · string · optional — Taker sell volume over the last 24 hours, in the quote asset. Decimal string, e.g. "12.5". - `result.high_price` · lite `hp` · string · optional — The highest trade price of the last 24 hours. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.low_price` · lite `lp1` · string · optional — The lowest trade price of the last 24 hours. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.open_price` · lite `op` · string · optional — The first trade price of the last 24 hours. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.open_interest` · lite `oi` · string · optional — The open interest in the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.long_short_ratio` · lite `ls1` · string · optional — The ratio of accounts that are net long to accounts that are net short on this instrument. - `result.funding_rate` · lite `fr2` · string · optional — The indicative funding rate for the current funding interval, in percent (`"0.01"` = 0.01%). Absent for stable funding perps, which have `funding_rate_long_apr_pct` and `funding_rate_short_apr_pct` instead. - `result.next_funding_time` · lite `nf` · string (int64 unix ns) · optional — When the current funding interval ends, in unix nanoseconds. - `result.status` · lite `s` · enum InstrumentStatus · optional — The current status of the instrument Values: `ACTIVE`, `REDUCE_ONLY`, `MAINTENANCE`, `HALTED`, `CLOSED`, `PENDING`, `DELISTED` ([details](/reference/enums.md#instrumentstatus)). - `result.session` · lite `s1` · enum TradingSessionType · optional — The current trading session of the instrument's underlying market Values: `REGULAR`, `PRE_MARKET`, `AFTER_MARKET`, `OVERNIGHT`, `CLOSE` ([details](/reference/enums.md#tradingsessiontype)). - `result.long_open_interest` · lite `lo` · string · optional — The long open interest in the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. Excludes qualified-maker and DMM open interest. - `result.short_open_interest` · lite `so` · string · optional — The short open interest in the instrument. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. Excludes qualified-maker and DMM open interest. - `result.funding_rate_long_apr_pct` · lite `fr3` · string · optional — Stable perps only: the indicative annual rate for retail longs at the next charge, in percent a year (`'-5.5'` = retail longs pay 5.5%; positive = retail receives, negative = retail pays). Updated when the rates change. Absent for other kinds. - `result.funding_rate_short_apr_pct` · lite `fr4` · string · optional — Stable perps only: the indicative annual rate for retail shorts at the next charge, in percent a year (`'-5'` = retail shorts pay 5%; positive = retail receives, negative = retail pays). Updated when the rates change. Absent for other kinds. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.ticker( instrument="BTC_USDT_Perp", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/ticker" \ -H "Content-Type: application/json" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@]` | | Auth | None (public) | | Kind | `snapshot`. Every frame is a full snapshot. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Contract id | `ticker.mini_ticker_snap` (`StreamMiniTickerSnapV1`) | ## Selector Grammar `[@]`, e.g. `BTC_USDT_Perp@500`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (0 - `raw`, 50, 100, 200, 500, 1000, 5000) Snapshot (200, 500, 1000, 5000) ## Frame Type `WSMiniTickerFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.mini.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object MiniTicker · required — A mini ticker matching the request filter Fields: see [MiniTicker](/reference/types.md#miniticker); listed in full under `result` on reference/rpc/mini_ticker.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.mini_ticker_snap_stream(instrument="BTC_USDT_Perp", rate=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.mini.s", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.mini.s", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/streams/mini_ticker_delta.md # Mini ticker delta stream | | | |---|---| | SDK | `client.mini_ticker_delta_stream(...)` | | Channel | `v1.mini.d` on `wss://market-data./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@]` | | Auth | None (public) | | Kind | `delta`. The first frame after subscribing is a full snapshot (`sequence_number` `"0"`); later frames carry only what changed. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Contract id | `ticker.mini_ticker_delta` (`StreamMiniTickerDeltaV1`) | ## Selector Grammar `[@]`, e.g. `BTC_USDT_Perp@500`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (0 - `raw`, 50, 100, 200, 500, 1000, 5000) Snapshot (200, 500, 1000, 5000) ## Frame Type `WSMiniTickerFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.mini.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object MiniTicker · required — A mini ticker matching the request filter Fields: see [MiniTicker](/reference/types.md#miniticker); listed in full under `result` on reference/rpc/mini_ticker.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.mini_ticker_delta_stream(instrument="BTC_USDT_Perp", rate=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.mini.d", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.mini.d", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/streams/ticker_snap.md # Ticker snapshot stream Payload: Prices, 24-hour statistics, open interest and funding for one instrument. Figures that can be worked out from these fields are not sent. For example the 24-hour volume is `buy_volume_24h_b + sell_volume_24h_b`. | | | |---|---| | SDK | `client.ticker_snap_stream(...)` | | Channel | `v1.ticker.s` on `wss://market-data./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@]` | | Auth | None (public) | | Kind | `snapshot`. Every frame is a full snapshot. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Contract id | `ticker.ticker_snap` (`StreamTickerSnapV1`) | ## Selector Grammar `[@]`, e.g. `BTC_USDT_Perp@500`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (100, 200, 500, 1000, 5000) Snapshot (500, 1000, 5000) ## Frame Type `WSTickerFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.ticker.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object Ticker · required — A ticker matching the request filter Fields: see [Ticker](/reference/types.md#ticker); listed in full under `result` on reference/rpc/ticker.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.ticker_snap_stream(instrument="BTC_USDT_Perp", rate=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.ticker.s", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.ticker.s", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/streams/ticker_delta.md # Ticker delta stream Payload: Prices, 24-hour statistics, open interest and funding for one instrument. Figures that can be worked out from these fields are not sent. For example the 24-hour volume is `buy_volume_24h_b + sell_volume_24h_b`. | | | |---|---| | SDK | `client.ticker_delta_stream(...)` | | Channel | `v1.ticker.d` on `wss://market-data./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@]` | | Auth | None (public) | | Kind | `delta`. The first frame after subscribing is a full snapshot (`sequence_number` `"0"`); later frames carry only what changed. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Contract id | `ticker.ticker_delta` (`StreamTickerDeltaV1`) | ## Selector Grammar `[@]`, e.g. `BTC_USDT_Perp@500`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (100, 200, 500, 1000, 5000) Snapshot (500, 1000, 5000) ## Frame Type `WSTickerFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.ticker.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object Ticker · required — A ticker matching the request filter Fields: see [Ticker](/reference/types.md#ticker); listed in full under `result` on reference/rpc/ticker.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.ticker_delta_stream(instrument="BTC_USDT_Perp", rate=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.ticker.d", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.ticker.d", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/rpc/orderbook_levels.md # Order book levels Do not use this to poll for data -- a websocket subscription is much more performant, and useful. | | | |---|---| | SDK | `client.orderbook_levels(...)` | | HTTP | `POST https://market-data./full/v1/book`, or `/lite/v1/book` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/book` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `orderbook.orderbook_levels` (`RPCOrderbookLevelsV1`) | ## Request Body type `ApiOrderbookLevelsRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `depth` · lite `d` · integer (uint32) · required — Depth of the order book to be retrieved (10, 50, 100, 500) ## Response Body type `ApiOrderbookLevelsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object OrderbookLevels · required — The orderbook levels objects matching the request asset - `result.event_time` · lite `et` · string (int64 unix ns) · required — Time at which the event was emitted in unix nanoseconds - `result.instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result.bids` · lite `b` · object OrderbookLevel[] · required — The list of best bids up till query depth - `result.bids[].price` · lite `p` · string · required — The price of the level. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.bids[].size` · lite `s` · string · required — The number of assets offered. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.bids[].num_orders` · lite `no` · integer (uint32) · required — The number of open orders at this level - `result.asks` · lite `a` · object OrderbookLevel[] · required — The list of best asks up till query depth Fields: same as `result.bids[]` above. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `3000` InvalidInstrument (400) · `3031` InvalidDepth (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.orderbook_levels( instrument="BTC_USDT_Perp", depth=50, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/book" \ -H "Content-Type: application/json" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@-]` | | Auth | None (public) | | Kind | `snapshot`. Every frame is a full snapshot. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Contract id | `orderbook.orderbook_snap` (`StreamOrderbookSnapV1`) | ## Selector Grammar `[@-]`, e.g. `BTC_USDT_Perp@500-50`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (50, 100, 500, 1000) Snapshot (500, 1000) - `depth` · uint32, optional — Depth of the order book to be retrieved Delta(0 - `unlimited`) Snapshot(10, 50, 100, 500) ## Frame Type `WSOrderbookLevelsFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.book.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object OrderbookLevels · required — An orderbook levels object matching the request filter Fields: see [OrderbookLevels](/reference/types.md#orderbooklevels); listed in full under `result` on reference/rpc/orderbook_levels.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) · `3031` InvalidDepth (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.orderbook_snap_stream(instrument="BTC_USDT_Perp", rate=500, depth=50) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.book.s", "selectors": ["BTC_USDT_Perp@500-50"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.book.s", "s1": ["BTC_USDT_Perp@500-50"], "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. ===== reference/streams/orderbook_delta.md # Order book delta stream | | | |---|---| | SDK | `client.orderbook_delta_stream(...)` | | Channel | `v1.book.d` on `wss://market-data./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@-]` | | Auth | None (public) | | Kind | `delta`. The first frame after subscribing is a full snapshot (`sequence_number` `"0"`); later frames carry only what changed. | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe; the next frame is a fresh snapshot. | | Applying deltas | Replace the size at each price; size `"0"` removes the level ([how](/guides/websocket.md#applying-book-deltas)) | | Contract id | `orderbook.orderbook_delta` (`StreamOrderbookDeltaV1`) | ## Selector Grammar `[@-]`, e.g. `BTC_USDT_Perp@500-50`. Parts: > Testnet currently rejects a depth on this stream (`BTC_USDT_Perp@500-50` fails with error 1103); send `@` only. The contract grammar does not reflect this yet. - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `rate` · uint32 — The minimal rate at which we publish feeds (in milliseconds) Delta (50, 100, 500, 1000) Snapshot (500, 1000) - `depth` · uint32, optional — Depth of the order book to be retrieved Delta(0 - `unlimited`) Snapshot(10, 50, 100, 500) ## Frame Type `WSOrderbookLevelsFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.book.s`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object OrderbookLevels · required — An orderbook levels object matching the request filter Fields: see [OrderbookLevels](/reference/types.md#orderbooklevels); listed in full under `result` on reference/rpc/orderbook_levels.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1004` NotFound (404) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3030` InvalidFeedRate (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.orderbook_delta_stream(instrument="BTC_USDT_Perp", rate=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.book.d", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.book.d", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/rpc/trade.md # Trade Do not use this to poll for data -- a websocket subscription is much more performant, and useful. This endpoint offers public trading data, use the Trading APIs instead to query for your personalized trade tape. | | | |---|---| | SDK | `client.trade(...)` | | HTTP | `POST https://market-data./full/v1/trade`, or `/lite/v1/trade` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/trade` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `trade.trade` (`RPCTradeV1`) | ## Request Body type `ApiTradeRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `limit` · lite `l` · integer (uint32) · required — The limit to query for. Defaults to 500; Max 1000 ## Response Body type `ApiTradeResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Trade[] · required — The public trades matching the request asset - `result[].event_time` · lite `et` · string (int64 unix ns) · required — Time at which the event was emitted in unix nanoseconds - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result[].is_taker_buyer` · lite `it` · bool · required — If taker was the buyer on the trade - `result[].size` · lite `s` · string · required — The number of assets being traded. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result[].price` · lite `p` · string · required — The traded price. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result[].mark_price` · lite `mp` · string · optional — The mark price of the instrument at point of trade. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result[].index_price` · lite `ip` · string · required — The index price of the instrument at point of trade. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result[].interest_rate` · lite `ir` · string · required — The interest rate of the underlying when the trade happened, in percent (`"0.01"` = 0.01%). - `result[].forward_price` · lite `fp` · string · optional — [Options] The forward price of the option at point of trade. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result[].trade_id` · lite `ti` · string · required — A trade identifier, globally unique, and monotonically increasing (not by `1`). All trades sharing a single taker execution share the same first component (before `-`), and `event_time`. `trade_id` is guaranteed to be consistent across MarketData `Trade` and Trading `Fill`. - `result[].venue` · lite `v` · enum Venue · required — The venue where the trade occurred Values: `ORDERBOOK`, `RFQ` ([details](/reference/enums.md#venue)). - `result[].is_rpi` · lite `ir1` · bool · required — If the trade is a RPI trade ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `7725` SfpEndpointNotSupported (403) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.trade( instrument="BTC_USDT_Perp", limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/trade" \ -H "Content-Type: application/json" \ --data @- </full/v1/trade_history`, or `/lite/v1/trade_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/trade_history` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `trade.trade_history` (`RPCTradeHistoryV1`) | ## Request Body type `ApiTradeHistoryRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — The start time to apply in nanoseconds. If nil, this defaults to all start times. Otherwise, only entries matching the filter will be returned - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — The end time to apply in nanoseconds. If nil, this defaults to all end times. Otherwise, only entries matching the filter will be returned - `limit` · lite `l` · integer (uint32) · optional, default `500` — The limit to query for. Defaults to 500; Max 1000 - `cursor` · lite `c` · string · optional — The cursor to indicate when to start the query from ## Response Body type `ApiTradeHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Trade[] · required — The public trades matching the request asset Fields: see [Trade](/reference/types.md#trade); listed in full under `result[]` on reference/rpc/trade.md, earlier in this file. - `next` · lite `n` · string · optional — The cursor to indicate when to start the next query from ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `7725` SfpEndpointNotSupported (403) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.trade_history( instrument="BTC_USDT_Perp", limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/trade_history" \ -H "Content-Type: application/json" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@]` | | Auth | None (public) | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe, then fetch current state over HTTP ([`trade_history`](/reference/rpc/trade_history.md)) for what you missed. | | Contract id | `trade.trade` (`StreamTradeV1`) | ## Selector Grammar `[@]`, e.g. `BTC_USDT_Perp@500`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `limit` · uint32 — The limit to query for. Valid values are (50, 200, 500, 1000). Default is 50 ## Frame Type `WSTradeFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.trade`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object Trade · required — A public trade matching the request filter Fields: see [Trade](/reference/types.md#trade); listed in full under `result[]` on reference/rpc/trade.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3011` InvalidLimit (400) · `3013` ExactLimitNotSupported (400) · `7725` SfpEndpointNotSupported (403) ## Example ```python import asyncio from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env="testnet") as client: async with client.trade_stream(instrument="BTC_USDT_Perp", limit=500) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.trade", "selectors": ["BTC_USDT_Perp@500"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.trade", "s1": ["BTC_USDT_Perp@500"], "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. ===== reference/rpc/candlestick.md # Candlestick Klines are uniquely identified by their instrument, type, interval, and open time. Pagination works as follows: - We perform a reverse chronological lookup, starting from `end_time`. If `end_time` is not set, we start from the most recent data. - The lookup is limited to `limit` records. If more data is requested, the response will contain a `next` cursor for you to query the next page. - If a `cursor` is provided, it will be used to fetch results from that point onwards. - Pagination will continue until the `start_time` is reached. If `start_time` is not set, pagination will continue as far back as our data retention policy allows. | | | |---|---| | SDK | `client.candlestick(...)` | | HTTP | `POST https://market-data./full/v1/kline`, or `/lite/v1/kline` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/kline` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `candlestick.candlestick` (`RPCCandlestickV1`) | ## Request Body type `ApiCandlestickRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `interval` · lite `i1` · enum CandlestickInterval · required — The interval of each candlestick Values: `CI_1_M`, `CI_3_M`, `CI_5_M`, `CI_15_M`, `CI_30_M`, `CI_1_H`, `CI_2_H`, `CI_4_H`, `CI_6_H`, `CI_8_H`, `CI_12_H`, `CI_1_D`, `CI_3_D`, `CI_5_D`, `CI_1_W`, `CI_2_W`, `CI_3_W`, `CI_4_W` ([details](/reference/enums.md#candlestickinterval)). - `type` · lite `t` · enum CandlestickType · required — The type of candlestick data to retrieve. Note: For spot instruments, only `trade` and `mid` are available Values: `TRADE`, `MARK`, `INDEX`, `MID` ([details](/reference/enums.md#candlesticktype)). - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — Start time of kline data in unix nanoseconds - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — End time of kline data in unix nanoseconds - `limit` · lite `l` · integer (uint32) · optional, default `500` — The limit to query for. Defaults to 500; Max 1000 - `cursor` · lite `c` · string · optional — The cursor to indicate when to start the query from ## Response Body type `ApiCandlestickResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Candlestick[] · required — The candlestick result set for given interval - `result[].open_time` · lite `ot` · string (int64 unix ns) · required — Open time of kline bar in unix nanoseconds - `result[].close_time` · lite `ct` · string (int64 unix ns) · required — Close time of kline bar in unix nanosecond - `result[].open` · lite `o` · string · required — The open price, expressed in underlying currency resolution units - `result[].close` · lite `c` · string · required — The close price, expressed in underlying currency resolution units - `result[].high` · lite `h` · string · required — The high price, expressed in underlying currency resolution units - `result[].low` · lite `l` · string · required — The low price, expressed in underlying currency resolution units - `result[].volume_b` · lite `vb` · string · required — The underlying volume transacted. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result[].volume_q` · lite `vq` · string · required — The quote volume transacted, in the quote asset. Decimal string, e.g. "12.5". - `result[].trades` · lite `t` · integer (uint32) · required — The number of trades transacted - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `next` · lite `n` · string · optional — The cursor to indicate when to start the next query from ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `3042` InvalidCandlestickTypeForSpot (400) · `3043` InvalidCandlestickTypeForStablePerp (400) ## Example ```python from grvt import Grvt, enums as e with Grvt(env="testnet") as client: resp = client.candlestick( instrument="BTC_USDT_Perp", interval=e.CandlestickInterval("CI_1_M"), type=e.CandlestickType("TRADE"), limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/kline" \ -H "Content-Type: application/json" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[@-]` | | Auth | None (public) | | 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](/guides/websocket.md#sequence-numbers-and-gaps)). On a gap, re-subscribe, then fetch current state over HTTP ([`candlestick`](/reference/rpc/candlestick.md)) for what you missed. | | Contract id | `candlestick.candlestick` (`StreamCandlestickV1`) | ## Selector Grammar `[@-]`, e.g. `BTC_USDT_Perp@CI_1_M-TRADE`. Parts: - `instrument` · asset — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `interval` · WsCandlestickInterval — The interval of each candlestick Values: `CI_1_M`, `CI_3_M`, `CI_5_M`, `CI_15_M`, `CI_30_M`, `CI_1_H`, `CI_2_H`, `CI_4_H`, `CI_6_H`, `CI_8_H`, `CI_12_H`, `CI_1_D`, `CI_3_D`, `CI_5_D`, `CI_1_W`, `CI_2_W`, `CI_3_W`, `CI_4_W`. - `type` · CandlestickType — The type of candlestick data to retrieve Values: `TRADE`, `MARK`, `INDEX`, `MID`. ## Frame Type `WSCandlestickFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.candle`. - `selector` · lite `s1` · string · required — The selector this frame is for, as you subscribed with it. - `sequence_number` · lite `sn` · string (uint64) · required — 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 is `event number × 10^5 + a counter` that 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. - `feed` · lite `f` · object Candlestick · required — A candlestick entry matching the request filters Fields: see [Candlestick](/reference/types.md#candlestick); listed in full under `result[]` on reference/rpc/candlestick.md, earlier in this file. - `prev_sequence_number` · lite `ps` · string (uint64) · required — The `sequence_number` of 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](/reference/errors.md)): `1002` InternalServer (500) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3040` InvalidCandlestickInterval (400) · `3041` InvalidCandlestickType (400) · `3042` InvalidCandlestickTypeForSpot (400) · `3043` InvalidCandlestickTypeForStablePerp (400) ## Example ```python import asyncio from grvt import AsyncGrvt, enums as e async def main(): async with AsyncGrvt(env="testnet") as client: async with client.candlestick_stream(instrument="BTC_USDT_Perp", interval=e.WsCandlestickInterval("CI_1_M"), type=e.CandlestickType("TRADE")) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://market-data.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.candle", "selectors": ["BTC_USDT_Perp@CI_1_M-TRADE"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.candle", "s1": ["BTC_USDT_Perp@CI_1_M-TRADE"], "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. ===== reference/rpc/funding_rate.md # Funding rate Pagination works as follows: - We perform a reverse chronological lookup, starting from `end_time`. If `end_time` is not set, we start from the most recent data. - The lookup is limited to `limit` records. If more data is requested, the response will contain a `next` cursor for you to query the next page. - If a `cursor` is provided, it will be used to fetch results from that point onwards. - Pagination will continue until the `start_time` is reached. If `start_time` is not set, pagination will continue as far back as our data retention policy allows. | | | |---|---| | SDK | `client.funding_rate(...)` | | HTTP | `POST https://market-data./full/v1/funding`, or `/lite/v1/funding` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/funding` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `settlement.funding_rate` (`RPCFundingRateV1`) | ## Request Body type `ApiFundingRateRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — Start time of funding rate in unix nanoseconds - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — End time of funding rate in unix nanoseconds - `limit` · lite `l` · integer (uint32) · optional, default `500` — The limit to query for. Defaults to 500; Max 1000 - `cursor` · lite `c` · string · optional — The cursor to indicate when to start the query from - `agg_type` · lite `at` · enum FundingRateAggregationType · optional, default `FUNDING_INTERVAL` — Aggregation method for historical funding rate observations. Defaults to using the instrument-specific funding interval. Values: `FUNDING_INTERVAL`, `ONE_HOURLY`, `FOUR_HOURLY`, `EIGHT_HOURLY` ([details](/reference/enums.md#fundingrateaggregationtype)). ## Response Body type `ApiFundingRateResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object ApiFundingRate[] · required — The funding rate result set for given interval - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument name, e.g. `BTC_USDT_Perp` (perpetual), `BTC_USDT_SFP` (stable funding perp) or `BTC_USDT_SpotSwap` (spot swap). - `result[].funding_rate` · lite `fr` · string · optional — The funding rate of the instrument, expressed in percentage points. Absent for stable perps, which have `funding_rate_long_apr_pct` and `funding_rate_short_apr_pct` instead. - `result[].funding_time` · lite `ft` · string (int64 unix ns) · required — The funding timestamp of the funding rate, expressed in unix nanoseconds - `result[].mark_price` · lite `mp` · string · required — The mark price of the instrument at funding timestamp. Decimal string, e.g. "65000.5"; up to 9 decimals. For stable perps, the index price the charge used. - `result[].funding_rate_8_h_avg` · lite `fr1` · string · optional — Deprecated: Refer to `funding_rate` instead. Will be removed in a future release. Absent for stable perps. - `result[].funding_interval_hours` · lite `fi` · integer (uint8) · required — Funding interval in hours (e.g. 1/4/8/etc). - `result[].funding_rate_long_apr_pct` · lite `fr2` · string · optional — Stable perps only: the annual rate for retail longs at this charge, in percent a year (`'-5.5'` = retail longs paid 5.5%; positive = retail receives, negative = retail pays). Absent for other kinds. - `result[].funding_rate_short_apr_pct` · lite `fr3` · string · optional — Stable perps only: the annual rate for retail shorts at this charge, in percent a year (`'-5'` = retail shorts paid 5%; positive = retail receives, negative = retail pays). Absent for other kinds. - `result[].funding_multiplier` · lite `fm` · integer (uint8) · optional — Stable perps only: days of funding the charge covered, 3 on the triple day, else 1. Absent for other kinds. - `next` · lite `n` · string · optional — The cursor to indicate when to start the next query from ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `3007` NotApplicableForSpotInstrument (400) · `3008` InvalidFundingAggregationTypeForStablePerp (400) · `3012` InvalidCursor (400) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.funding_rate( instrument="BTC_USDT_Perp", limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/funding" \ -H "Content-Type: application/json" \ --data @- </full/v1/sfp_trading_schedule`, or `/lite/v1/sfp_trading_schedule` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/sfp_trading_schedule` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `sfp_trading_schedule.get_sfp_trading_schedule` (`RPCGetSfpTradingSchedule`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiSfpTradingScheduleResponse` (the same object is the JSON-RPC `result` over WebSocket). - `update_time` · lite `ut` · string (int64) · required — Session data update timestamp in milliseconds - `equity` · lite `e` · object SfpMarketSchedule · optional — Legacy: use `schedules` instead. Schedule for the `EQUITY` asset class - `equity.sessions` · lite `s` · object TradingSession[] · required — Trading sessions for the current calendar week (Sunday to Saturday in the exchange's local time). The sessions are contiguous with no gaps, and any period when the market is not open, including holidays falling in this week, is returned as a `CLOSE` session - `equity.sessions[].start_time` · lite `st` · string (int64) · required — Trading session start time timestamp in milliseconds - `equity.sessions[].end_time` · lite `et` · string (int64) · required — Trading session end time timestamp in milliseconds - `equity.sessions[].type` · lite `t` · enum TradingSessionType · required — Trading session type Values: `REGULAR`, `PRE_MARKET`, `AFTER_MARKET`, `OVERNIGHT`, `CLOSE` ([details](/reference/enums.md#tradingsessiontype)). - `equity.holidays` · lite `h` · object TradingHolidaySchedule[] · required — Market holidays and early closes, past and upcoming, sorted by start time. The market is closed from the start time to the end time of each entry. Empty when there are none - `equity.holidays[].name` · lite `n` · string · required — Holiday name - `equity.holidays[].close_type` · lite `ct` · enum TradingScheduleCloseType · required — `FULL_DAY`: the market is closed for the whole day. `EARLY_CLOSE`: the market trades as normal until the start time, then is closed until the end time Values: `FULL_DAY`, `EARLY_CLOSE` ([details](/reference/enums.md#tradingscheduleclosetype)). - `equity.holidays[].start_time` · lite `st` · string (int64) · required — When the closure begins, as a Unix timestamp in milliseconds. For `FULL_DAY` this is when the closed trading day's session would have opened (the evening before for a session that opens before midnight); for `EARLY_CLOSE` it is the moment the market closes early - `equity.holidays[].end_time` · lite `et` · string (int64) · required — When the closed or shortened trading day's session would have closed, as a Unix timestamp in milliseconds. The closure covers the start time up to, but not including, the end time - `equity_nyse` · lite `en` · object SfpMarketSchedule · optional — Legacy: use `schedules` instead. Schedule for the `EQUITY_NYSE` asset class Fields: same as `equity` above. - `equity_nasdaq` · lite `en1` · object SfpMarketSchedule · optional — Legacy: use `schedules` instead. Schedule for the `EQUITY_NASDAQ` asset class Fields: same as `equity` above. - `commodity` · lite `c` · object SfpMarketSchedule · optional — Legacy: use `schedules` instead. Schedule for the `COMMODITY` asset class Fields: same as `equity` above. - `commodity_cme` · lite `cc` · object SfpMarketSchedule · optional — Legacy: use `schedules` instead. Schedule for the `COMMODITY_CME` asset class Fields: same as `equity` above. - `schedules` · lite `s` · object SfpTradingScheduleGroup[] · required — Trading hours, as groups of stable funding perps that share them: one group per asset class, named after it, then one per instrument schedule, named by the exchange. Each stable funding perp with a schedule is in exactly one group. - `schedules[].name` · lite `n` · string · required — The group name. For stable perps on their asset class hours, the asset class (for example `COMMODITY_CME`) - `schedules[].asset_class` · lite `ac` · enum AssetClass · required — The instruments' asset class. Its holiday calendar sets the group's holidays Values: `CRYPTO`, `EQUITY`, `COMMODITY`, `FX`, `INDEX`, `EQUITY_NASDAQ`, `EQUITY_NYSE`, `EQUITY_KRX`, `COMMODITY_CME`, `PRE_IPO` ([details](/reference/enums.md#assetclass)). - `schedules[].instruments` · lite `i` · string (instrument name)[] · required — The stable perps trading these hours, sorted. Each stable perp with a schedule is in exactly one group - `schedules[].sessions` · lite `s` · object TradingSession[] · required — Trading sessions for the current calendar week (Sunday to Saturday in the exchange's local time). The sessions are contiguous with no gaps, and any period when the market is not open, including holidays falling in this week, is returned as a `CLOSE` session Fields: same as `equity.sessions[]` above. - `schedules[].holidays` · lite `h` · object TradingHolidaySchedule[] · required — Market holidays and early closes, past and upcoming, sorted by start time. The market is closed from the start time to the end time of each entry. Empty when there are none Fields: same as `equity.holidays[]` above. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_sfp_trading_schedule() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/sfp_trading_schedule" \ -H "Content-Type: application/json" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/lite/v1/sfp_trading_schedule" \ -H "Content-Type: application/json" \ --data '{}' ``` ===== reference/rpc/get_margin_rules.md # Get margin rules | | | |---|---| | SDK | `client.get_margin_rules(...)` | | HTTP | `POST https://market-data./full/v1/margin_rules`, or `/lite/v1/margin_rules` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/margin_rules` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_margin_rules` (`RPCGetMarginRulesV1`) | ## Request Body type `ApiGetMarginRulesRequest`. Fields the server fills are left out. - `instrument` · lite `i` · string (instrument name) · required — The instrument to query margin rules for ## Response Body type `ApiGetMarginRulesResponse` (the same object is the JSON-RPC `result` over WebSocket). - `instrument` · lite `i` · string (instrument name) · required — The instrument name - `max_position_size` · lite `mp` · string · required — The maximum position size. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `risk_brackets` · lite `rb` · object RiskBracket[] · required — List of risk brackets defining margin requirements at different notional tiers - `risk_brackets[].tier` · lite `t` · integer (uint32) · required — 1-indexed tier number - `risk_brackets[].notional_floor` · lite `nf` · string · required — Lower bound of notional value (inclusive) in quote currency - `risk_brackets[].notional_cap` · lite `nc` · string · optional — Upper bound of notional value (exclusive) in quote currency, omitted for last tier - `risk_brackets[].maintenance_margin_rate` · lite `mm` · string · required — Maintenance margin rate as a decimal (e.g., '0.01' for 1%) - `risk_brackets[].initial_margin_rate` · lite `im` · string · required — Initial margin rate as a decimal (e.g., '0.02' for 2%) - `risk_brackets[].max_leverage` · lite `ml` · integer (uint32) · required — Maximum leverage allowed at this tier (floor of 1 / initial_margin_rate) - `risk_brackets[].cumulative_maintenance_amount` · lite `cm` · string · required — Cumulative maintenance margin amount in quote currency ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `3000` InvalidInstrument (400) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_margin_rules( instrument="BTC_USDT_Perp", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/margin_rules" \ -H "Content-Type: application/json" \ --data @- </full/v1/get_all_collateral_asset_info`, or `/lite/v1/get_all_collateral_asset_info` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_all_collateral_asset_info` on `wss://market-data./ws/full`, or `/ws/lite` for lite names | | Auth | None (public) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `instrument.get_all_collateral_asset_info` (`RPCGetAllCollateralAssetInfoV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiGetAllCollateralAssetInfoResponse` (the same object is the JSON-RPC `result` over WebSocket). - `assets` · lite `a` · object ApiCollateralAssetInfo[] · required — Collateral configuration for every collateral-eligible asset (CVR > 0) - `assets[].currency` · lite `c` · string · required — The asset - `assets[].collateral_value_ratio` · lite `cv` · string · required — CVR, expressed in percentage points. 0 = not usable as collateral. - `assets[].collateral_deposit_cap` · lite `cd` · string · required — CDC limit, native units. 0 = untracked / unlimited. - `assets[].max_borrow_rate` · lite `mb` · string · required — MBR - per-asset ceiling on the annual borrow rate, expressed in percentage points; the tier borrow rate never exceeds this. - `assets[].manual_repayment_fee_rate` · lite `mr` · string · required — Effective manual-repay/convert fee = max((1-CVR)/MRR, RFR), expressed in percentage points. - `assets[].cdc_status` · lite `cs` · enum CDCStatus · required — Collateral-deposit-cap utilization status: normal / reduceOnly / autoExchange. Values: `NORMAL`, `REDUCE_ONLY`, `AUTO_EXCHANGE` ([details](/reference/enums.md#cdcstatus)). - `assets[].show_only_when_held` · lite `so` · bool · required — Show this currency only when the sub-account holds a balance of it - `assets[].vault_id` · lite `vi` · string (uint64) · required — The vault whose shares this currency is; 0 for an ordinary currency. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) ## Example ```python from grvt import Grvt with Grvt(env="testnet") as client: resp = client.get_all_collateral_asset_info() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md)): With full field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/full/v1/get_all_collateral_asset_info" \ -H "Content-Type: application/json" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://market-data.$GRVT_DOMAIN/lite/v1/get_all_collateral_asset_info" \ -H "Content-Type: application/json" \ --data '{}' ```