# Grvt API — trading: orders, algo orders, fills, positions, leverage, RFQ and their private 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/accounts.md # Accounts and permissions Most "not allowed" errors (`2000 SignerUnauthorized`, `1400 ErrNoTradePermission`, `4015 ErrNoTransferPermission`) mean a key or wallet is missing a permission. This page shows how accounts, wallets and permissions fit together. ## Two levels of account | Account | Grvt web app name | Identified by | Holds | |---|---|---|---| | Main account | Funding Account | `main_account_id`, a `0x` address | deposits and withdrawals; moves funds to its sub-accounts | | Sub-account | Trading Account | `sub_account_id`, a number | orders, positions and margin | A main account has any number of sub-accounts. Its ID is the address of the wallet that created it. To trade, move funds to a sub-account with [transfer](/reference/rpc/transfer.md). Each main account also has an off-chain account ID that starts with `ACC:`. A login returns it without the `ACC:` prefix in the `X-Grvt-Account-Id` header ([Authentication](/guides/authentication.md#by-hand)), and the [referral calls](/guides/referrals.md) show it with the prefix. ## Users and wallets Each person on Grvt has two credentials: - **An email login** (password or Google/Microsoft), for everything that doesn't move money: KYC (identity checks), referrals, viewing the portfolio. Referral data can also be read with an API key ([Referrals](/guides/referrals.md)). - **A registered wallet.** Anything that moves money or trades must be signed by a wallet registered on the account, with the right permission. Grvt never holds the wallet's private key. A personal account has one user. A business account can have several, each with their own wallet and permissions. ## API keys An API key belongs to one account (usually a sub-account) and is tied to one wallet address. The key gets you a session ([Authentication](/guides/authentication.md)); that wallet's private key, the [signing key](/guides/authentication.md#two-keys-two-jobs), signs the writes. The API key has that wallet's permissions: - A sub-account key is either read-only (no permissions) or has **Trade**, optionally with **Transfer**. - A main-account key can have the main-account permissions below. - Every key can read, whatever its permissions. To create a key in the Grvt web app, paste the address of a wallet you own, or let the browser generate a key pair and copy the signing key. **Watch out:** if the browser generates the key pair, save the signing key right away. Grvt doesn't keep it. ## Permissions Permissions belong to a wallet on an account. **Admin** includes every other permission on the same account, and an admin of the main account has every permission on all its sub-accounts. **Main account** | Permission | Grvt web app name | Allows | |---|---|---| | `ADMIN` | Funding Admin | everything; creates sub-accounts, adds users, approves the actions below | | `INTERNAL_TRANSFER` | Internal Transfer | moving funds between the main account and its sub-accounts | | `EXTERNAL_TRANSFER` | External Transfer | moving funds to other Grvt main accounts in the transfer address book | | `WITHDRAW` | Withdrawal | withdrawing to wallets in the withdrawal address book | | `VAULT_INVESTOR` | Strategy Investor | investing in and redeeming from [strategies](/guides/strategies.md) | | `TRADE` | Trade | trading on all the sub-accounts, where Grvt has enabled it | **Sub-account** | Permission | Grvt web app name | Allows | |---|---|---| | `ADMIN` | Trading Admin ("Strategy Admin" on a strategy) | everything on this sub-account; adds users to it | | `TRADE` | Trade | placing and cancelling orders | | `TRANSFER` | Transfer | moving funds out of this sub-account | ## Approvals by several admins Some changes to a main account need signatures from several admins, up to the account's threshold (such as 2 of 3). Admins set the threshold, between one and the number of admins. It applies to: - adding or removing a user of the main account; - changing the threshold; - adding or removing wallets in the withdrawal address book; - adding or removing accounts in the transfer address book. Adding a user to a single sub-account needs only that sub-account's admin. ===== guides/authentication.md # Authentication and sessions Public market data needs no login. Every call to the trading host, and every private stream, needs a **session**: a `gravity` cookie plus an `X-Grvt-Account-Id` header. You get both by logging in with your API key. Reference pages that need a session say `Auth: Session required`. ## With an SDK Pass your API key to the client. It logs in on the first private call, and again at 80% of the cookie's lifetime. | Python | TypeScript | Go | Rust | |---|---|---|---| | `api_key` | `apiKey` | `APIKey` in `Config` | `.api_key(...)` | ```python import os from grvt import Grvt with Grvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: print(client.get_sub_accounts()) ``` ## By hand **Advanced.** **When:** you call HTTP or WebSocket without an SDK, or you write C++ ([C++ guide](/sdks/cpp.md)). 1. Log in: `POST https://edge./auth/api_key/login` with `{"api_key": "..."}`. ```sh curl -sS -D - "https://edge.$GRVT_DOMAIN/auth/api_key/login" \ -H "Content-Type: application/json" \ --data @- <; Expires=...`: the session cookie. - `X-Grvt-Account-Id: `: a response header. ```sh export GRVT_COOKIE= # the value after gravity=, without the attributes export GRVT_ACCOUNT_ID= ``` 3. Send both on every trading call. ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/sub_account_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </ws/full`. 5. Log in again before the cookie's `Expires` time. The session lifetime is not published, so read it from `Expires`. If the cookie has none, log in again within an hour, as the SDKs do. **Watch out:** - A call without a valid session fails with error `1000` (HTTP 401). - After you log in again, open a new socket with the new cookie. There is no login message inside the socket. - A new login doesn't end your other sessions (unless the account goes over its session limit), so the old socket keeps working while you open the new one. Close it once the new one is subscribed. - Send the login request without your current `gravity` cookie: a login that carries it replaces that session. - The server checks the session when a socket opens. An open socket isn't closed at the cookie's `Expires` time, but it can be closed later if the session ends. ## Wallet login **Advanced.** **When:** you log in with a wallet signature instead of an API key, over raw HTTP. 1. Sign a `WalletLogin` EIP-712 message with `signer`, `nonce` and `expiration` (at most 5 minutes ahead of server time). 2. `POST /auth/wallet/login` with `{address, signature}`. The response body holds only `funding_account_address`. [Login wallet](/reference/rpc/login_wallet.md) and the `wallet_login` signing case show the raw HTTP flow. **Watch out:** the SDK clients don't support wallet login. They manage API-key sessions only. ## Two keys, two jobs | Key | Used for | Where it goes | |---|---|---| | API key | Getting a session | Sent to edge once per login | | Signing key (the private key of the wallet registered for the API key) | Signing orders, transfers, withdrawals | Never sent; only signatures leave your machine | An API key alone can read your account but can't place an order. Orders need a signature from the signing key. In the SDKs, the **signer** is the object that holds the signing key (for example `PrivateKeySigner`). ===== guides/signing.md # Signing Orders, transfers, withdrawals, wallet login, vault, position margin and qualified maker calls carry an [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signature made with your [signing key](/guides/authentication.md#two-keys-two-jobs). **With an SDK**, the SDK signs for you: read only [Rules that cause most rejections](/guides/signing.md#rules-that-cause-most-rejections). **Advanced:** the rest of this page is for signing in another language. It walks through the `limit_order` test signing case from [signing.json](/downloads/signing.json): if your code prints the same digest and `r`/`s`/`v`, it is right. ## The steps To sign an order, transfer or withdrawal yourself with EIP-712: 1. **Start from the request JSON** you will send, with a `signature` object that has `signer`, `nonce`, `expiration` and `chain_id` but no `r`/`s`/`v` yet. 2. **Look up metadata**: per instrument, `instrument_hash` and `base_decimals`, plus `quote_decimals` for position margin calls ([get_instrument](/reference/rpc/get_instrument.md)); per currency, `id` and `balance_decimals` ([get_currency](/reference/rpc/get_currency.md)) for transfers, withdrawals and strategies; for vault calls, your main account (see [Main account](/guides/signing.md#main-account)). 3. **Map wire fields to the EIP-712 message** using the signed type's table ([Order](/reference/signing/Order.md)). Each field has one transform: | Transform | What it does | Example (`limit_order`) | |---|---|---| | `copy` | value as is; 64-bit ints arrive as strings | `sub_account_id` `"8289849667772468"` → `8289849667772468` | | `enumCode` | enum name → its integer ([Enums](/reference/enums.md)) | `GOOD_TILL_TIME` → `1` | | `assetKey` | instrument → `instrument_hash` as uint256 | `BTC_USDT_Perp` → `0x030501` = `197889` | | `scaled` | decimal string × 10^decimals, exact | size `"0.01"` × 10^9 → `10000000`; price `"60000"` × 10^9 → `60000000000000` | | `sig.nonce`, `sig.expiration` | copied from the signature object | `1001`, `4102444800000000000` (unix **ns**; the SDKs use now + 1 day) | | `sig.chainId` | domain chain ID; `"0"` = the environment's | `326` (testnet) | 4. **Hash**: `digest = keccak256(0x19 0x01 ‖ domainSeparator ‖ structHash)`, with domain `{name: "GRVT Exchange", version: "0", chainId}` (no `verifyingContract`). 5. **Sign** the digest with secp256k1, keeping `s` in the lower half of the curve order ("low-s"), and write into the signature object: `r` and `s` as `0x` + 64 hex chars, `v` as `27` or `28`. ## The code Runnable as is (`pip install coincurve pycryptodome`). It prints the intermediate values and checks them against the signing case: [Download this example](/downloads/examples/python/examples/manual_signing.py) ```python from decimal import Decimal from coincurve import PrivateKey from Crypto.Hash import keccak def keccak256(data: bytes) -> bytes: return keccak.new(digest_bits=256, data=data).digest() def word(n: int) -> bytes: """One EIP-712 32-byte word. Negative ints are two's complement.""" return (n % 2**256).to_bytes(32, "big") def scaled(value: str, decimals: int) -> int: """Decimal string -> integer. More fractional digits than `decimals` is an error, never rounded.""" n = Decimal(value).scaleb(decimals) if n != n.to_integral_value(): raise ValueError(f"{value} has more than {decimals} decimals") return int(n) # Step 1: the request you want to send (signature without r, s, v yet). request = { "order": { "sub_account_id": "8289849667772468", "is_market": False, "time_in_force": "GOOD_TILL_TIME", "post_only": True, "reduce_only": False, "legs": [{"instrument": "BTC_USDT_Perp", "size": "0.01", "limit_price": "60000", "is_buying_asset": True}], # expiration: unix nanoseconds. The SDKs use now + 1 day (at most 30 days; 180 for take-profit and # stop-loss orders); this signing test case uses 2100-01-01 so its digest never changes. "signature": { "signer": "0x1267c6181aee40f5ddbd70c56ecf4613117326b5", "expiration": "4102444800000000000", "nonce": 1001, "chain_id": "326", }, "metadata": {"client_order_id": "1001"}, } } # Step 2: instrument metadata, from get_instrument / get_all_instruments. instruments = {"BTC_USDT_Perp": {"instrument_hash": "0x030501", "base_decimals": 9}} TIME_IN_FORCE = {"GOOD_TILL_TIME": 1, "ALL_OR_NONE": 2, "IMMEDIATE_OR_CANCEL": 3, "FILL_OR_KILL": 4} # Step 3: map wire fields to the EIP-712 message. o, sig = request["order"], request["order"]["signature"] legs = [ { "assetID": int(instruments[leg["instrument"]]["instrument_hash"], 16), "contractSize": scaled(leg["size"], instruments[leg["instrument"]]["base_decimals"]), "limitPrice": scaled(leg.get("limit_price", "0"), 9), "isBuyingContract": leg["is_buying_asset"], } for leg in o["legs"] ] message = { "subAccountID": int(o["sub_account_id"]), "isMarket": o.get("is_market", False), "timeInForce": TIME_IN_FORCE[o["time_in_force"]], "postOnly": o.get("post_only", False), "reduceOnly": o.get("reduce_only", False), "legs": legs, "nonce": sig["nonce"], "expiration": int(sig["expiration"]), } # Step 4: hash. structHash = keccak(typeHash || encoded fields); an array is the keccak of its element hashes. LEG_TYPE = b"OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract)" ORDER_TYPE = ( b"Order(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly," b"OrderLeg[] legs,uint32 nonce,int64 expiration)" ) + LEG_TYPE def leg_hash(leg: dict) -> bytes: return keccak256( keccak256(LEG_TYPE) + word(leg["assetID"]) + word(leg["contractSize"]) + word(leg["limitPrice"]) + word(leg["isBuyingContract"]) ) struct_hash = keccak256( keccak256(ORDER_TYPE) + word(message["subAccountID"]) + word(message["isMarket"]) + word(message["timeInForce"]) + word(message["postOnly"]) + word(message["reduceOnly"]) + keccak256(b"".join(leg_hash(leg) for leg in message["legs"])) + word(message["nonce"]) + word(message["expiration"]) ) chain_id = int(sig["chain_id"]) or 326 # "0" means the environment's chain ID domain_separator = keccak256( keccak256(b"EIP712Domain(string name,string version,uint256 chainId)") + keccak256(b"GRVT Exchange") + keccak256(b"0") + word(chain_id) ) digest = keccak256(b"\x19\x01" + domain_separator + struct_hash) print("domain_separator 0x" + domain_separator.hex()) print("struct_hash 0x" + struct_hash.hex()) print("digest 0x" + digest.hex()) # Step 5: sign the digest (secp256k1, low-s) and fill in r, s, v. key = PrivateKey(bytes.fromhex("bfe25ff07bd38cb3fbc28a2a296d41aabd68a78c929d257935906489fc9c6d89")) # public TEST key raw = key.sign_recoverable(digest, hasher=None) # 65 bytes: r || s || recovery id sig["r"] = "0x" + raw[:32].hex() sig["s"] = "0x" + raw[32:64].hex() sig["v"] = raw[64] + 27 print(sig) assert digest.hex() == "7f8fecb8997024f85a5a9a44730f79d2cef290688d6a022d8e98e95ccc1f98c9" assert sig["r"] == "0x62b6d0047530e701aa06d4b7de9dca76916219b8561424bd246a519bdc31bf7d" assert sig["s"] == "0x2447b83565fa6cac90c607e5c4a3f96cda386f92d7fb51f45dea12c2f8e09904" assert sig["v"] == 27 ``` Expected output: ```text domain_separator 0x1254f97f8495f704630a238cbcd898a4b8ab20d77bb93e17049d3445f4f81f16 struct_hash 0x0248f8af0c644bb95dfe45feed4897e787765ca0fb1bece6dd5e9e016feceee8 digest 0x7f8fecb8997024f85a5a9a44730f79d2cef290688d6a022d8e98e95ccc1f98c9 ``` The key is a published test key (`keccak256("GRVT SDK TEST KEY - PUBLIC - NEVER FUND")`). Never fund its address. ## Rules that cause most rejections - **Precision.** Reject a value with more fractional digits than its scale allows, before signing; don't round it. BTC has 9 base decimals, so size `"1.1234567891"` is an error (signing case `order_over_precision`). Check this yourself: today the exchange accepts such a value and drops the extra digits, so it acts on a different number than the one you meant. - **Expiration.** `expiration` is unix **nanoseconds**, at most 30 days ahead (take-profit and stop-loss orders may be accepted up to 180 days ahead). It is measured on the exchange's clock with no allowance for skew: one already past fails with `2001`, and one too far ahead is rejected with reason `EXCEED_MAX_SIGNATURE_EXPIRATION`. If your clock may drift, use the exchange's [server time](/guides/environments.md#hosts). On an order it is also the order's lifetime: an order still open at that time is cancelled with reject reason `EXPIRED`. The SDKs set it 24 hours ahead unless you set `signature.expiration` yourself, so give orders that should rest longer a later expiration. - **Units.** Prices always use 9 decimals. Sizes use the instrument's `base_decimals`. Transfer and withdrawal amounts use the currency's `balance_decimals`. Position margin amounts use the instrument's `quote_decimals`. Each signed type page gives the scale of every field. - **Negative values.** Signed fields (`int64`, `int32`) can be negative and are encoded as two's complement: `add_position_margin` with amount `"-100.25"` signs `-100250000` (signing case `remove_position_margin`). - **`r`, `s`, `v` format.** `r` and `s` are `0x` plus 64 hex characters each; `v` is 27 or 28. Keep the `0x`: without it the signature fails to verify, although error `2006`'s message says "without 0x prefix". - **Nonce.** A random uint32, new for each new instruction. An exact repeat of a signed transfer fails with `4007 ErrDuplicatedTransfer`. Orders are told apart by client order ID instead (next rule); what a repeated order does is in [Why not resend](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). - **Client order ID.** `metadata.client_order_id` is not signed. Use any non-zero uint64 that none of the sub-account's open orders uses, trigger orders included (take-profit and stop-loss orders waiting for their price): `0` fails with `2011`, a duplicate with `2012`, and the sub-account's last client order ID again with `2013`. Use a new ID for each order: once an order closes, its ID is accepted again. A lookup by client order ID returns the open order with that ID or, if none is open, any closed order that used it, not necessarily the latest. - **ID ranges.** The Grvt web app picks IDs below 2^63. The SDKs make IDs from 2^63 up (2^63 plus Unix seconds × 2^31 plus a counter), so they never clash with the web app's and are unique within one process. Each process starts its counter at a random 31-bit value, so two processes on one sub-account rarely pick the same ID: in a given second, each pair of their orders has about a 1 in 2^31 (2 billion) chance of matching. If you pick your own and the web app also trades the sub-account, pick from 2^63 up too. If many processes trade the sub-account at once and even that chance is too much, give each process its own IDs. - **Chain ID.** Testnet 326, production 325; `"0"` means the environment's chain ID. Put the same value you signed with in the request. - **Signer address.** `signature.signer` is the address of the key that signed. That wallet must be allowed to trade for the sub-account. ## Builder fee orders When `order.builder` is set to a non-zero address, sign `OrderWithBuilderFee` instead of `Order`. It adds two fields between `legs` and `nonce`: ```text OrderWithBuilderFee(uint64 subAccountID,bool isMarket,uint8 timeInForce,bool postOnly,bool reduceOnly,OrderLeg[] legs,address builder,uint32 builderFee,uint32 nonce,int64 expiration)OrderLeg(uint256 assetID,uint64 contractSize,uint64 limitPrice,bool isBuyingContract) ``` - `builder`: the builder's address (`address` transform, 20 bytes, left-padded in the word). - `builderFee`: `builder_fee` is a **percentage** string; signed value = `builder_fee` × 10^4. `"0.001"` (0.001%) → `10`. Signing case `order_with_builder_fee`, digest `0x09b6c3c367b5641f38ab3750d2f5dc45325f3e46c15a3b6fe03e92b3ca7942af`. ## Main account **When:** you sign `VaultInvestV3`, `VaultRedeemV3` or `VaultBurnLpToken`. These sign `accountID`, which is not in the request: the server uses your session's main account. 1. Call [funding_account_summary](/reference/rpc/funding_account_summary.md) once and read `result.main_account_id`. 2. Sign that address as `accountID`. The SDKs do this for you on the first vault call. In C++, `needs_` reports that the call needs it, and your app passes it in. ## Other signed types | Type | Used by | Notes | |---|---|---| | [Transfer](/reference/signing/Transfer.md), [TransferV2](/reference/signing/TransferV2.md), [TransferV3](/reference/signing/TransferV3.md) | [transfer](/reference/rpc/transfer.md) | V2 when wallet types are set; V3 for currency ids above 255 | | [Withdrawal](/reference/signing/Withdrawal.md), [WithdrawalV2](/reference/signing/WithdrawalV2.md) | [withdrawal](/reference/rpc/withdrawal.md) | V2 for currency ids above 255 | | [WalletLogin](/reference/signing/WalletLogin.md) | [wallet login](/reference/rpc/login_wallet.md) | expiration at most 5 minutes ahead | | [VaultInvestV3](/reference/signing/VaultInvestV3.md) | [vault_invest](/reference/rpc/vault_invest.md) | signs your main account | | [VaultRedeemV3](/reference/signing/VaultRedeemV3.md) | [vault_redeem](/reference/rpc/vault_redeem.md) | signs your main account | | [VaultBurnLpToken](/reference/signing/VaultBurnLpToken.md) | [vault_burn_tokens](/reference/rpc/vault_burn_tokens.md) | signs your main account; `currency` is not signed | | [AddIsolatedPositionMargin](/reference/signing/AddIsolatedPositionMargin.md) | [add_position_margin](/reference/rpc/add_position_margin.md) | negative `amount` removes margin | | [SetSubAccountPositionMarginConfig](/reference/signing/SetSubAccountPositionMarginConfig.md) | [set_position_config](/reference/rpc/set_position_config.md) | | | [SetDeriskToMaintenanceMarginRatio](/reference/signing/SetDeriskToMaintenanceMarginRatio.md) | [set_derisk_mm_ratio](/reference/rpc/set_derisk_mm_ratio.md) | | Each type page lists its fields, type hash, where every field comes from, and its signing cases. The same data is under `signed` in [contract.json](/downloads/contract.json). ===== 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). ===== sdks/cpp.md # C++ signing core and reference > [!WARNING] > **Preview.** Any 0.x release can change the API. Pin the commit you build from. **Advanced.** The C++ signing core is for apps that already have their own networking and event loop. It signs requests and encodes them as JSON; your code does the rest. For a full client, use another SDK. | What you get | What you build yourself | |---|---| | Exact decimal values | HTTP and WebSocket clients | | EIP-712 encoding and hashing | Login, session renewal and the cancel-on-disconnect countdown | | An optional libsecp256k1 signer for private keys in the same process | Timers, streams and order books | | Executable reference examples | Recovery after lost answers and stream gaps | | | Loading metadata, choosing the environment, nonce and expiration | | | Business checks: tick size, minimum size, minimum notional | There is no client and no wrapper for each RPC or stream. ## Build the core **Not published as a package yet:** build it from source, from its public repository [grvt-signing-cpp](https://github.com/gravity-technologies/grvt-signing-cpp), and pin the commit you build from. 1. Install CMake 3.24+ and GCC or Clang with C++20 or newer, on Linux or macOS. MSVC isn't supported, because the core uses `__int128` arithmetic. 2. Clone, build and install: ```sh git clone https://github.com/gravity-technologies/grvt-signing-cpp cd grvt-signing-cpp cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build cmake --install build --prefix /opt/grvt ``` 3. Optional, for private keys in the same process: install libsecp256k1 with its recovery module (`apt install libsecp256k1-dev` or `brew install secp256k1`). Then configure with `-DGRVT_SIGNING_WITH_SECP256K1=ON`. The default build doesn't need it. 4. Link the package from your CMake project: ```cmake find_package(grvt_signing REQUIRED) target_link_libraries(app PRIVATE grvt::signing) # Also link grvt::signer when using the optional private-key signer. ``` 5. Optional: run `ctest --test-dir build --output-on-failure`. It checks the signing cases, the installed package (the digest path and the optional signer separately) and the reference. Test your own integration against [signing.json](/downloads/signing.json) too; an installed build has it at `share/grvt_signing/signing.json`. **Errors.** Every function that can fail returns `grvt::Result`: the value, or a `grvt::Error` with a `kind` (`signing`, `decode` or `config`) and a `message`. Encoding and signing failures are returned, not thrown. ## Run the reference **When:** you want to see the whole signing flow before writing your own transport. From the source directory, build with examples turned on and run `grvt_signing_reference`: ```sh cmake -S . -B build -DGRVT_SDK_BUILD_EXAMPLES=ON cmake --build build --target grvt_signing_reference ./build/grvt_signing_reference ``` The source below keeps signing separate from the transport, which your code supplies. It uses fixed inputs and made-up host data and makes no network calls, so it doesn't prove that login, networking or order recovery work against the exchange. [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; } ``` **Watch out:** don't submit its recorded request as a new order. It uses fixed test values, not a live nonce or expiration. ## Connect a live application **When:** you are ready to send real requests. Start on testnet. 1. Pick the [environment URLs and chain ID](/guides/environments.md) for one environment, and use them together. 2. Log in with your API key over HTTP ([Authentication](/guides/authentication.md#by-hand)). 3. Save the returned `gravity` cookie and `X-Grvt-Account-Id`. Send both on private requests and on the WebSocket upgrade. 4. Load current instrument and currency metadata from the API into a `grvt::SigningMetadata` (`instrument_hash`, `base_decimals` and `quote_decimals` per instrument; `id` and `balance_decimals` per currency; your `main_account` for vault calls), and point `SignContext::metadata` at it. `grvt::signing::needs_` says which entries a request needs. 5. Set these yourself, and use exact decimal text for every price, size and amount: - Chain ID: `SignContext::chain_id`. A request whose `signature.chain_id` is `"0"` (the environment's) is signed with it; a call fails with a `config` error if both are 0. - Nonce: a fresh uint32 from an OS secure random source, for each new signed action. - Expiration: a future Unix timestamp in nanoseconds, at most 30 days ahead (180 for take-profit and stop-loss orders) ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Client order ID: your own, saved before you send, so you can [look the order up](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown) if its response is lost. 6. Sign. Call `grvt::signing::digest_` to get a digest for an external signer, or `grvt::signing::sign_` with a signer. An order with `builder` set is signed as `OrderWithBuilderFee` ([Builder fee orders](/guides/signing.md#builder-fee-orders)). Bulk orders have separate functions to make the digests (`digests_order_bulk_orders`) and to attach the signatures (`attach_order_bulk_orders`). 7. Encode the signed request with `grvt::encode(request)`, which writes the wire JSON, and send it with your own HTTP or WebSocket client. Your app also checks stream sequence numbers, reconnects and recovers state ([WebSocket](/guides/websocket.md), [Errors and retries](/guides/errors-and-retries.md)). [Signing](/guides/signing.md) has the signing details. **Watch out:** - Read credentials from environment variables or your secret store. Keep signing keys out of request bodies and logs. - Turn off redirects, including during WebSocket handshakes. A followed redirect sends a second request, which can forward your credentials or replay a signed write. - Keep metadata, chain ID, nonce and expiration consistent with the environment and account you send to. The core doesn't load or choose any of them for you. - `attach_order_bulk_orders` requires `SignContext::verify`. Your callback must check that each digest and signature recover to the expected address: returning success without checking proves nothing about the signing key. The optional adapter provides `grvt::verify_signature` for this.
Guarantees and edge cases - Inside a `Signer` callback, `SigningRequest::typed_data()` gives you the typed data, for wallets that need it. Digest results and their copies don't keep the typed data. - Before your verifier runs, the core checks the signature shape, low-s ([Signing](/guides/signing.md#the-steps)) and the signer field. - The sign and digest functions only read the `SignContext`. Threads can share one while each signs its own request, if your `Signer` is safe to call from several threads at once (`PrivateKeySigner` is) and nothing changes the metadata meanwhile. - `digest_order_create_order`, and `sign_order_create_order` with `PrivateKeySigner`, allocate no memory after the first few calls when you reuse the same request object. Errors and `typed_data()` do allocate.
## What the core checks - It validates encoding inputs and the signing metadata it needs. - It rejects any value it can't represent exactly at the required scale. It never rounds. A valid digest doesn't mean the exchange will accept the order. ## Not supported yet - **A client.** The core has no HTTP, WebSocket, login, session renewal or recovery, on purpose: your application owns them, as the table at the top of this page lists. - **MSVC.** The core uses `__int128` arithmetic; build with GCC or Clang ([Build the core](/sdks/cpp.md#build-the-core)). ===== 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 | ===== guides/builders.md # Builders A builder is a Grvt account, usually an app or a bot, that places orders for its users and earns its own fee on them. Use this page if you run such an app. How it fits together: - **Builder account**: your own Grvt main account. Builder fees are paid into it. - **Authorization**: each user signs once, naming your builder account and the highest builder fee they accept, one cap for futures (perpetuals included) and one for spot. - **Builder order**: an order with `builder` and `builder_fee` set. The user pays the builder fee on each fill, on top of the trading fee. The calls for orders and builder fees are under [Builders](/reference/index.md#builders) in the reference. Authorizing a builder has no SDK method yet: send it over HTTP as shown below. ## Authorize a builder **When:** a user connects your app for the first time, or you want to change their fee caps. One call, `POST /auth/builder/authorize` on the edge host, works in two modes. What you send picks the mode: | Mode | Use it when | The user signs | Response | |---|---|---|---| | **With an API key** | your app trades for the user with its own key | `AddAccountSignerWithBuilder` | `{"api_key": "..."}` | | **[Authorize only](/guides/builders.md#authorize-only)** | your app already has a key, or the user changes their caps | `AuthorizeBuilder` | `{}` | Sending `builder_api_key_signer` and `builder_api_key_permissions` picks the first mode; leaving both out picks the second. The steps below are for the first. 1. Get two main account IDs (`0x` addresses): the user's and your builder account's. [funding_account_summary](/reference/rpc/funding_account_summary.md) returns `main_account_id` for the account you are logged in to. 2. Choose the caps, `max_futures_fee_rate` and `max_spot_fee_rate`. Each is a **percentage** string with at most 4 decimals: `"0.1"` means 0.1%. 3. Generate a key pair in your app. Its address is the **builder signer**; it must not already be a signer on Grvt. 4. Choose the key's permissions on the user's main account: names joined with `&` in this order: `Admin`, `InternalTransfer`, `ExternalTransfer`, `Withdraw`, `VaultInvestor`, `Trade`. For example `"Trade"` or `"InternalTransfer&Trade"`. Ask only for what you need, usually `Trade`. 5. Have the user sign `AddAccountSignerWithBuilder` ([below](/guides/builders.md#the-signed-message)) with an admin wallet of their main account (Funding Admin). 6. Send it to the edge host. It needs no session: the signature authenticates it. ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/auth/builder/authorize" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "main_account_id": "0x1111111111111111111111111111111111111111", "builder_account_id": "0x2222222222222222222222222222222222222222", "max_futures_fee_rate": "0.1", "max_spot_fee_rate": "0.05", "builder_api_key_signer": "0x4444444444444444444444444444444444444444", "builder_api_key_permissions": "Trade", "builder_api_key_label": "My trading app", "signature": { "signer": "0x3333333333333333333333333333333333333333", "r": "0x...", "s": "0x...", "v": 27, "expiration": "1767225600000000000", "nonce": 1001, "chain_id": "326" } } EOF ``` A success returns HTTP 200 and `{"api_key": "..."}`: an API key on the user's main account, tied to the builder signer. Log in with it ([Authentication](/guides/authentication.md)) and sign the user's orders with the builder signer's key. [Permissions](/guides/accounts.md#permissions) explains what each permission allows on a main account. [get_authorized_builders](/reference/rpc/get_authorized_builders.md), called on the user's session, lists your builder account with its caps. **Watch out:** - Grvt keeps only a hash of the API key, so this response is the only time you see it. Store it right away. - To change the caps, use [Authorize only](/guides/builders.md#authorize-only) with the new values; the first mode would add another API key. Authorizing again with the same caps fails with "the builder is already authorized for this main account". - Grvt sets a maximum for the caps. A cap above it, or a negative one, fails with "invalid builder fee rate". - Permission names out of order (`"Trade&Admin"`) or unknown names fail with HTTP 400. ### Authorize only **When:** your app already has a way to trade for the user, or the user changes the caps of a builder they authorized before. This mode only records your builder account and its caps on the user's main account. It creates no API key. 1. Get the two main account IDs and choose the caps, as in steps 1 and 2 above. 2. Have the user sign `AuthorizeBuilder` ([below](/guides/builders.md#the-signed-message)) with an admin wallet of their main account. 3. Send it to the same route, without the `builder_api_key_*` fields. ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/auth/builder/authorize" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "main_account_id": "0x1111111111111111111111111111111111111111", "builder_account_id": "0x2222222222222222222222222222222222222222", "max_futures_fee_rate": "0.2", "max_spot_fee_rate": "0.05", "signature": { "signer": "0x3333333333333333333333333333333333333333", "r": "0x...", "s": "0x...", "v": 27, "expiration": "1767225600000000000", "nonce": 1002, "chain_id": "326" } } EOF ``` A success returns HTTP 200 and `{}`. The new caps apply to the user's next orders with your builder account. The cap, signature and same-caps errors are the same as in the first mode. ### The signed message The domain is the same as for every Grvt signature: `{name: "GRVT Exchange", version: "0", chainId}`, with the environment's chain ID (326 on testnet, 325 on production). [Signing](/guides/signing.md) walks through the hashing. With an API key, the user signs: ```text AddAccountSignerWithBuilder(address accountID,address signer,string permissions,address builderAccountID,uint32 maxFutureFeeRate,uint32 maxSpotFeeRate,uint32 nonce,int64 expiration) ``` | Field | From the request | |---|---| | `accountID` | `main_account_id` | | `signer` | `builder_api_key_signer` | | `permissions` | `builder_api_key_permissions`, the same string (an EIP-712 `string`: its keccak256 hash is encoded) | | `builderAccountID` | `builder_account_id` | | `maxFutureFeeRate` | `max_futures_fee_rate` × 10^4: `"0.1"` → `1000`, `"0.001"` → `10` | | `maxSpotFeeRate` | `max_spot_fee_rate` × 10^4 | | `nonce` | `signature.nonce`, a random uint32 | | `expiration` | `signature.expiration`, unix nanoseconds, in the future and at most 30 days ahead | Authorize only, the user signs: ```text AuthorizeBuilder(address mainAccountID,address builderAccountID,uint32 maxFutureFeeRate,uint32 maxSpotFeeRate,uint32 nonce,int64 expiration) ``` The fields come from the request the same way: `mainAccountID` is `main_account_id`, and the rest match the table above.
Errors Errors come back with an HTTP status and a message: | Status | Message | Fix | |---|---|---| | 400 | `invalid main account ID` / `invalid builder account ID` | Use existing main account IDs (`0x` addresses). | | 400 | `builder account ID cannot be the same as main account ID` | Use a separate builder account. | | 400 | `invalid signature` / `signature has expired` / `signature expiration exceeds the maximum of 30 days` | Check the signed fields, the chain ID and `expiration`. | | 400 | `signature nonce has already been used` | Sign again with a new nonce. | | 400 | `the main account requires more signatures than provided` | The account needs approvals from several admins ([Approvals by several admins](/guides/accounts.md#approvals-by-several-admins)). | | 400 | `the signer wallet is already in use; please choose a different one` | Generate a new builder signer. | | 400 | `API key label cannot be empty when permissions or signer are provided` | Set `builder_api_key_label`. | | 401 | `the signer in the signature is not authorized to represent the main account` | Sign with an admin wallet of the user's main account. |
## Place builder orders **When:** your app places an order for a user who has authorized your builder account. 1. Set `order.builder` to your builder main account ID. 2. Set `order.builder_fee` to your fee for this order, a percentage string such as `"0.05"` (0.05%). It must be at most the user's cap for this market: the futures cap for perpetuals, the spot cap for spot swaps. 3. Sign and send the order as usual. The SDKs sign `OrderWithBuilderFee` when `builder` is set; by hand, see [Builder fee orders](/guides/signing.md#builder-fee-orders). The builder fee is the order's builder fee rate times the trade's notional value, in the quote currency. It is charged on each fill and paid into your builder account. Spot buys carry no builder fee; spot sells do. **Watch out:** these errors mean the order was rejected, not placed: | Code | Name | Cause | |---|---|---| | `7504` | `ErrBuilderNotAuthorized` | The user hasn't authorized this builder account. | | `7505` | `ErrBuilderFeeExceedsAuthorizationLimit` | `builder_fee` is above the user's cap. | | `7506` | `ErrBuilderMissing` | `builder_fee` is set without `builder`. | | `7501` | `ErrBuilderFeeNegative` | `builder_fee` is negative. | ## See your builder fees - On the user's side, each fill has `builder`, `builder_fee_rate` and `builder_fee` (the amount paid, in the quote currency): [fill_history](/reference/rpc/fill_history.md). - On your side, [builder_fill_history](/reference/rpc/builder_fill_history.md) lists the fills where your account was the builder. Call it with a session for your builder account; other accounts get an empty list. ===== reference/rpc/create_order.md # Create order STABLE_PERP orders require the sub-account to be in multi-asset mode. | | | |---|---| | SDK | `client.create_order(...)` | | HTTP | `POST https://trades./full/v1/create_order`, or `/lite/v1/create_order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/create_order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `order.signature` is signed: [`Order`](/reference/signing/Order.md) / [`OrderWithBuilderFee`](/reference/signing/OrderWithBuilderFee.md). Use OrderWithBuilderFee when order.builder is set to a non-zero address, otherwise Order. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `order.create_order` (`RPCCreateOrderV1`) | ## Request Body type `ApiCreateOrderRequest`. Fields the server fills are left out. - `order` · lite `o` · object Order · required — The order to create - `order.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account placing the order. - `order.is_market` · lite `im` · bool · optional, default `false` — True for a market order. A market order has no limit price, never rests on the book and fills at the prices of the resting orders it meets. On STABLE_PERP a slippage bound is mandatory: `limit_price` must carry the signed bound (reference price ± the chosen slippage), or the order is rejected (`STABLE_PERP_REQUIRES_PRICE_BOUND`). There, `is_market` = false with a limit price behaves the same; the flag only records intent. - `order.time_in_force` · lite `ti` · enum TimeInForce · required — How long the order stays open and whether it may fill partly. The order book takes `GOOD_TILL_TIME`, `IMMEDIATE_OR_CANCEL`, `FILL_OR_KILL` and `RETAIL_PRICE_IMPROVEMENT`. An RFQ maker quote uses `GOOD_TILL_TIME` or `ALL_OR_NONE`; an RFQ taker uses `IMMEDIATE_OR_CANCEL` or `FILL_OR_KILL`. Values: `GOOD_TILL_TIME`, `ALL_OR_NONE`, `IMMEDIATE_OR_CANCEL`, `FILL_OR_KILL`, `RETAIL_PRICE_IMPROVEMENT` ([details](/reference/enums.md#timeinforce)). - `order.post_only` · lite `po` · bool · optional, default `false` — If true, the order must rest on the book as a maker order: if it would match at once, it is rejected (`FAIL_POST_ONLY`). A market, `IMMEDIATE_OR_CANCEL` or `FILL_OR_KILL` order cannot be post-only. If false, the order may take or make liquidity. Such orders can be held for a short speed bump before matching, so they meet up-to-date quotes; the exchange sets the delay, and it can differ per instrument. - `order.reduce_only` · lite `ro` · bool · optional, default `false` — If true, the order may only reduce your position; the part that would increase it is cancelled. - `order.legs` · lite `l` · object OrderLeg[] · required — What to trade. Send exactly one leg: the order book rejects orders with more than one (`MULTI_LEGGED_ORDER`). - `order.legs[].instrument` · lite `i` · string (instrument name) · required — The instrument to trade, e.g. `BTC_USDT_Perp`. - `order.legs[].size` · lite `s` · string · required — How much to trade, in the base asset. Decimal string, e.g. "0.01"; up to the instrument's base_decimals and a multiple of its minimum size. Scaled to an integer only inside the signature. - `order.legs[].limit_price` · lite `lp` · string · optional, default `0` — The worst price you accept, in the quote currency per unit. Decimal string, e.g. "65000.5"; up to 9 decimals and a multiple of the instrument's tick size. Scaled to an integer only inside the signature. Leave it out (or `"0"`) on a market order. Exception: a STABLE_PERP market order must carry the signed slippage bound (reference price ± the chosen slippage) here. - `order.legs[].is_buying_asset` · lite `ib` · bool · required — True to buy, false to sell. - `order.signature` · lite `s` · object Signature · required — The EIP-712 signature that authorises this order. The SDKs fill it in; the Signing guide shows how to build it yourself. - `order.signature.signer` · lite `s` · string (uint256) · required — The address of the wallet that signed (`0x` + 40 hex characters). That wallet must be allowed to act for the account; for an order, to trade for the sub-account. - `order.signature.r` · lite `r` · string (uint256) · required — The signature's `r`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `order.signature.s` · lite `s1` · string (uint256) · required — The signature's `s`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `order.signature.v` · lite `v` · integer (uint8) · required — The signature's `v`, 27 or 28. - `order.signature.expiration` · lite `e` · string (int64 unix ns) · required — When the signature stops being valid, in unix nanoseconds, measured on the exchange's clock. At most 30 days ahead (take-profit and stop-loss orders may be accepted up to 180 days ahead); one already past fails with `2001`. On an order it is also the order's lifetime: an order still open then is cancelled with reason `EXPIRED`. The SDKs use now + 24 hours. - `order.signature.nonce` · lite `n` · integer (uint32) · required — A number you choose, 0 to 4,294,967,295 (uint32), so that two otherwise identical requests have different signatures. Use a new random one for each request you sign. A transfer whose signed fields (nonce and expiration included) exactly repeat an earlier one is rejected, not ignored: it fails with `4007`. Orders are different. An exact resend of a signed order can be accepted and rest on the book, but the exchange counts fills per signed order, so all copies together never fill more than the signed size, and a resent `IMMEDIATE_OR_CANCEL` order whose first copy already filled is rejected. An order signed again (new nonce or expiration) is a new order and can fill in full again. - `order.signature.chain_id` · lite `ci` · string (uint64) · required — The chain id in the signed EIP-712 domain, as a string. Testnet 326, production 325; `"0"` means the environment's chain id. - `order.metadata` · lite `m` · object OrderMetadata · required — Unsigned data the exchange uses but the chain never sees, such as your `client_order_id`. - `order.metadata.client_order_id` · lite `co` · string (uint64) · required — Your own id for the order, to find or cancel it later. Any non-zero uint64 (`0` fails with `2011`) that none of the sub-account's open orders uses, take-profit and stop-loss orders waiting for their price included: a duplicate fails with `2012` (or is rejected with `OVERLAPPING_CLIENT_ORDER_ID`), and repeating the sub-account's last client order id fails with `2013`. After an order closes, its id is accepted again, so use a new id for each order. The Grvt web app picks ids below 2^63, so ids from 2^63 up never clash with orders placed there. That is a convention, not a rule the exchange checks. The SDKs set one for you when you leave it out. Not signed and not sent on chain. - `order.metadata.trigger` · lite `t` · object TriggerOrderMetadata · optional — Trigger fields are used to support any type of trigger order such as TP/SL - `order.metadata.trigger.trigger_type` · lite `tt` · enum TriggerType · required — Type of the trigger order. eg: Take Profit, Stop Loss, etc Values: `UNSPECIFIED`, `TAKE_PROFIT`, `STOP_LOSS` ([details](/reference/enums.md#triggertype)). - `order.metadata.trigger.tpsl` · lite `t` · object TPSLOrderMetadata · required — Contains metadata for Take Profit (TP) and Stop Loss (SL) trigger orders. Fields: see [TPSLOrderMetadata](/reference/types.md#tpslordermetadata). - `order.metadata.broker` · lite `b` · enum BrokerTag · optional — Specifies the broker who brokered the order Values: `UNSPECIFIED`, `COIN_ROUTES`, `ALERTATRON`, `ORIGAMI` ([details](/reference/enums.md#brokertag)). - `order.metadata.is_ecn` · lite `ie` · bool · optional, default `false` — Marks an ECN order, eligible for market maker last look. Only on STABLE_PERP instruments, for qualified market makers. - `order.metadata.slippage_bps` · lite `sb` · integer (uint16) · optional, default `0` — Maximum slippage from the mark price for an `IMMEDIATE_OR_CANCEL` limit order, in basis points (800 = 8%). Only valid on IOC limit orders; 0 means no slippage protection. - `order.metadata.rfq_id` · lite `ri` · string (uint128) · optional — Binds this order to an RFQ (see ApiCreateRfqRequest and the `v1.rfq` / `v1.quote` streams). Optional. As a taker acceptance: unlocks that RFQ's private quote pool, so the order matches across the private pool merged with the public book (firm resting liquidity + public quotes). The acceptance must be a single-leg order with time_in_force = IOC or FOK. Setting `rfq_id` on a non-ECN GTT order is rejected. If the referenced RFQ has expired, been cancelled, or is unknown, the order is rejected. As a maker quote (is_ecn = true): identifies which RFQ the quote is responding to. Omit `rfq_id` to match the public book only — private RFQ liquidity requires an RFQ. - `order.metadata.is_private` · lite `ip1` · bool · optional, default `false` — Maker quotes only. true = a private quote delivered to a single RFQ's taker (appears only on that taker's `v1.quote` book); false = a public quote resting on the order book, visible to all. When true, `rfq_id` is required. - `order.metadata.algo_order_id` · lite `ao` · string (uint128) · optional — The algo order that placed this order as a sub-order; zero for an ordinary order. - `order.builder` · lite `b` · string (0x address) · optional — The main account id of a builder (a third party that routes your order and charges a fee on it). Leave it out unless you trade through a builder: setting it switches the signature to `OrderWithBuilderFee`. - `order.builder_fee` · lite `bf` · string · optional — The builder's fee for this order, as a percentage: `"0.001"` means 0.001%. Only with `builder`. ## Response Body type `ApiCreateOrderResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Order · required — The created order - `result.order_id` · lite `oi` · string (uint128) · optional, default `0` — Set by the server. The exchange's 128-bit id for the order. The reply to `create_order` or `bulk_orders` comes before the id is assigned, so it is zero there; the order stream and `get_order` carry it. Every replace creates a new order with a new `order_id`. - `result.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account placing the order. - `result.is_market` · lite `im` · bool · optional, default `false` — True for a market order. A market order has no limit price, never rests on the book and fills at the prices of the resting orders it meets. On STABLE_PERP a slippage bound is mandatory: `limit_price` must carry the signed bound (reference price ± the chosen slippage), or the order is rejected (`STABLE_PERP_REQUIRES_PRICE_BOUND`). There, `is_market` = false with a limit price behaves the same; the flag only records intent. - `result.time_in_force` · lite `ti` · enum TimeInForce · required — How long the order stays open and whether it may fill partly. The order book takes `GOOD_TILL_TIME`, `IMMEDIATE_OR_CANCEL`, `FILL_OR_KILL` and `RETAIL_PRICE_IMPROVEMENT`. An RFQ maker quote uses `GOOD_TILL_TIME` or `ALL_OR_NONE`; an RFQ taker uses `IMMEDIATE_OR_CANCEL` or `FILL_OR_KILL`. Values: `GOOD_TILL_TIME`, `ALL_OR_NONE`, `IMMEDIATE_OR_CANCEL`, `FILL_OR_KILL`, `RETAIL_PRICE_IMPROVEMENT` ([details](/reference/enums.md#timeinforce)). - `result.post_only` · lite `po` · bool · optional, default `false` — If true, the order must rest on the book as a maker order: if it would match at once, it is rejected (`FAIL_POST_ONLY`). A market, `IMMEDIATE_OR_CANCEL` or `FILL_OR_KILL` order cannot be post-only. If false, the order may take or make liquidity. Such orders can be held for a short speed bump before matching, so they meet up-to-date quotes; the exchange sets the delay, and it can differ per instrument. - `result.reduce_only` · lite `ro` · bool · optional, default `false` — If true, the order may only reduce your position; the part that would increase it is cancelled. - `result.legs` · lite `l` · object OrderLeg[] · required — What to trade. Send exactly one leg: the order book rejects orders with more than one (`MULTI_LEGGED_ORDER`). - `result.legs[].instrument` · lite `i` · string (instrument name) · required — The instrument to trade, e.g. `BTC_USDT_Perp`. - `result.legs[].size` · lite `s` · string · required — How much to trade, in the base asset. Decimal string, e.g. "0.01"; up to the instrument's base_decimals and a multiple of its minimum size. Scaled to an integer only inside the signature. - `result.legs[].limit_price` · lite `lp` · string · optional, default `0` — The worst price you accept, in the quote currency per unit. Decimal string, e.g. "65000.5"; up to 9 decimals and a multiple of the instrument's tick size. Scaled to an integer only inside the signature. Leave it out (or `"0"`) on a market order. Exception: a STABLE_PERP market order must carry the signed slippage bound (reference price ± the chosen slippage) here. - `result.legs[].is_buying_asset` · lite `ib` · bool · required — True to buy, false to sell. - `result.signature` · lite `s` · object Signature · required — The EIP-712 signature that authorises this order. The SDKs fill it in; the Signing guide shows how to build it yourself. - `result.signature.signer` · lite `s` · string (uint256) · required — The address of the wallet that signed (`0x` + 40 hex characters). That wallet must be allowed to act for the account; for an order, to trade for the sub-account. - `result.signature.r` · lite `r` · string (uint256) · required — The signature's `r`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `result.signature.s` · lite `s1` · string (uint256) · required — The signature's `s`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `result.signature.v` · lite `v` · integer (uint8) · required — The signature's `v`, 27 or 28. - `result.signature.expiration` · lite `e` · string (int64 unix ns) · required — When the signature stops being valid, in unix nanoseconds, measured on the exchange's clock. At most 30 days ahead (take-profit and stop-loss orders may be accepted up to 180 days ahead); one already past fails with `2001`. On an order it is also the order's lifetime: an order still open then is cancelled with reason `EXPIRED`. The SDKs use now + 24 hours. - `result.signature.nonce` · lite `n` · integer (uint32) · required — A number you choose, 0 to 4,294,967,295 (uint32), so that two otherwise identical requests have different signatures. Use a new random one for each request you sign. A transfer whose signed fields (nonce and expiration included) exactly repeat an earlier one is rejected, not ignored: it fails with `4007`. Orders are different. An exact resend of a signed order can be accepted and rest on the book, but the exchange counts fills per signed order, so all copies together never fill more than the signed size, and a resent `IMMEDIATE_OR_CANCEL` order whose first copy already filled is rejected. An order signed again (new nonce or expiration) is a new order and can fill in full again. - `result.signature.chain_id` · lite `ci` · string (uint64) · required — The chain id in the signed EIP-712 domain, as a string. Testnet 326, production 325; `"0"` means the environment's chain id. - `result.metadata` · lite `m` · object OrderMetadata · required — Unsigned data the exchange uses but the chain never sees, such as your `client_order_id`. - `result.metadata.client_order_id` · lite `co` · string (uint64) · required — Your own id for the order, to find or cancel it later. Any non-zero uint64 (`0` fails with `2011`) that none of the sub-account's open orders uses, take-profit and stop-loss orders waiting for their price included: a duplicate fails with `2012` (or is rejected with `OVERLAPPING_CLIENT_ORDER_ID`), and repeating the sub-account's last client order id fails with `2013`. After an order closes, its id is accepted again, so use a new id for each order. The Grvt web app picks ids below 2^63, so ids from 2^63 up never clash with orders placed there. That is a convention, not a rule the exchange checks. The SDKs set one for you when you leave it out. Not signed and not sent on chain. - `result.metadata.create_time` · lite `ct` · string (int64 unix ns) · optional, default `0` — Set by the server. When the exchange received the order, in unix nanoseconds. - `result.metadata.trigger` · lite `t` · object TriggerOrderMetadata · optional — Trigger fields are used to support any type of trigger order such as TP/SL - `result.metadata.trigger.trigger_type` · lite `tt` · enum TriggerType · required — Type of the trigger order. eg: Take Profit, Stop Loss, etc Values: `UNSPECIFIED`, `TAKE_PROFIT`, `STOP_LOSS` ([details](/reference/enums.md#triggertype)). - `result.metadata.trigger.tpsl` · lite `t` · object TPSLOrderMetadata · required — Contains metadata for Take Profit (TP) and Stop Loss (SL) trigger orders. Fields: see [TPSLOrderMetadata](/reference/types.md#tpslordermetadata). - `result.metadata.broker` · lite `b` · enum BrokerTag · optional — Specifies the broker who brokered the order Values: `UNSPECIFIED`, `COIN_ROUTES`, `ALERTATRON`, `ORIGAMI` ([details](/reference/enums.md#brokertag)). - `result.metadata.is_ecn` · lite `ie` · bool · optional, default `false` — Marks an ECN order, eligible for market maker last look. Only on STABLE_PERP instruments, for qualified market makers. - `result.metadata.slippage_bps` · lite `sb` · integer (uint16) · optional, default `0` — Maximum slippage from the mark price for an `IMMEDIATE_OR_CANCEL` limit order, in basis points (800 = 8%). Only valid on IOC limit orders; 0 means no slippage protection. - `result.metadata.rfq_id` · lite `ri` · string (uint128) · optional — Binds this order to an RFQ (see ApiCreateRfqRequest and the `v1.rfq` / `v1.quote` streams). Optional. As a taker acceptance: unlocks that RFQ's private quote pool, so the order matches across the private pool merged with the public book (firm resting liquidity + public quotes). The acceptance must be a single-leg order with time_in_force = IOC or FOK. Setting `rfq_id` on a non-ECN GTT order is rejected. If the referenced RFQ has expired, been cancelled, or is unknown, the order is rejected. As a maker quote (is_ecn = true): identifies which RFQ the quote is responding to. Omit `rfq_id` to match the public book only — private RFQ liquidity requires an RFQ. - `result.metadata.is_private` · lite `ip1` · bool · optional, default `false` — Maker quotes only. true = a private quote delivered to a single RFQ's taker (appears only on that taker's `v1.quote` book); false = a public quote resting on the order book, visible to all. When true, `rfq_id` is required. - `result.metadata.algo_order_id` · lite `ao` · string (uint128) · optional — The algo order that placed this order as a sub-order; zero for an ordinary order. - `result.state` · lite `s1` · object OrderState · optional — Set by the server. The order's status, filled size and average fill price; not signed. - `result.state.status` · lite `s` · enum OrderStatus · required — The order's status. `FILLED`, `REJECTED` and `CANCELLED` are final. Values: `PENDING`, `OPEN`, `FILLED`, `REJECTED`, `CANCELLED` ([details](/reference/enums.md#orderstatus)). - `result.state.reject_reason` · lite `rr` · enum OrderRejectReason · required — Why the order was rejected or cancelled. `UNSPECIFIED` while it is not. Values: `UNSPECIFIED`, `CLIENT_CANCEL`, `CLIENT_BULK_CANCEL`, `CLIENT_SESSION_END`, `MARKET_CANCEL`, `IOC_CANCEL`, `AON_CANCEL`, `FOK_CANCEL`, `EXPIRED`, `FAIL_POST_ONLY`, `FAIL_REDUCE_ONLY`, `MM_PROTECTION`, `SELF_TRADE_PROTECTION`, `SELF_MATCHED_SUBACCOUNT`, `OVERLAPPING_CLIENT_ORDER_ID`, `BELOW_MARGIN`, `LIQUIDATION`, `INSTRUMENT_INVALID`, `INSTRUMENT_DEACTIVATED`, `SYSTEM_FAILOVER`, `UNAUTHORISED`, `SESSION_KEY_EXPIRED`, `SUB_ACCOUNT_NOT_FOUND`, `NO_TRADE_PERMISSION`, `UNSUPPORTED_TIME_IN_FORCE`, `MULTI_LEGGED_ORDER`, `EXCEED_MAX_POSITION_SIZE`, `EXCEED_MAX_SIGNATURE_EXPIRATION`, `MARKET_ORDER_WITH_LIMIT_PRICE`, `CLIENT_CANCEL_ON_DISCONNECT_TRIGGERED`, `OCO_COUNTER_PART_TRIGGERED`, `REDUCE_ONLY_LIMIT`, `CLIENT_REPLACE`, `DERISK_MUST_BE_IOC`, `DERISK_MUST_BE_REDUCE_ONLY`, `DERISK_NOT_SUPPORTED`, `INVALID_ORDER_TYPE`, `CURRENCY_NOT_DEFINED`, `INVALID_CHAIN_ID`, `BUILDER_ORDER_FEE_EXCEED`, `BUILDER_ORDER_FEE_NEGATIVE`, `BUILDER_ORDER_BUILDER_NOT_AUTHORIZED`, `BUILDER_ORDER_BUILDER_NOT_EXIST`, `TRADE_PRICE_WORSE_THAN_BANKRUPTCY_PRICE`, `TOO_MANY_MAKER_ORDERS`, `REDUCE_ONLY_NOT_SUPPORTED_FOR_SPOT_ORDER`, `TPSL_NOT_SUPPORTED_FOR_SPOT_ORDER`, `SPOT_ORDER_NOT_SUPPORTED`, `INSUFFICIENT_BALANCE`, `SPOT_TRADING_BLOCKED_DURING_SOCIALIZED_LOSS`, `BELOW_MARGIN_WITH_PENALTY_DEVIATION`, `CORPORATE_ACTION`, `NOT_QUALIFIED_MAKER`, `PRIVATE_QUOTE_REQUIRES_RFQ`, `STABLE_PERP_REQUIRES_PRICE_BOUND`, `UNSUPPORTED_TRIGGER_BY`, `RFQ_NOT_FOUND`, `RESTING_ORDER_WOULD_CROSS`, `SESSION_CLOSED`, `RFQ_TERMINATED`, `STABLE_PERP_REQUIRES_MULTI_ASSET_MODE`, `BORROW_LIMIT_EXCEEDED_AFTER_TRADE`, `UNDEPLOYED_LOAN_AUTO_EXCHANGE`, `LIQUIDATION_AUTO_EXCHANGE`, `USDC_COLLATERAL_DISABLED`, `SFP_POST_ONLY_NOT_ALLOWED`, `VAULT_NON_QUOTE_INVESTMENT_CURRENCY`, `RFQ_ID_REQUIRES_STABLE_PERP`, `RFQ_PRIVATE_POOL_NOT_SUPPORTED`, `RFQ_REQUIRES_IOC`, `RFQ_MISMATCH`, `RFQ_ALREADY_BOUND`, `RFQ_MAKER_MUST_BE_ECN`, `FOK_NOT_SUPPORTED`, `MARKET_ORDER_NOT_SUPPORTED`, `STABLE_PERP_ORDER_NOT_SUPPORTED` ([details](/reference/enums.md#orderrejectreason)). - `result.state.book_size` · lite `bs` · string[] · required — The size still open to fill, per leg (same order as `legs`), in the base asset. - `result.state.traded_size` · lite `ts` · string[] · required — The size filled so far, per leg (same order as `legs`), in the base asset. - `result.state.update_time` · lite `ut` · string (int64 unix ns) · required — When the order last changed, in unix nanoseconds. - `result.state.avg_fill_price` · lite `af` · string[] · required — The average price of the fills so far, per leg (same order as `legs`); 0 before the first fill. - `result.builder` · lite `b` · string (0x address) · optional — The main account id of a builder (a third party that routes your order and charges a fee on it). Leave it out unless you trade through a builder: setting it switches the signature to `OrderWithBuilderFee`. - `result.builder_fee` · lite `bf` · string · optional — The builder's fee for this order, as a percentage: `"0.001"` means 0.001%. Only with `builder`. ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1005` UnknownErr (500) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `1012` InvalidSignatureChainID (400) · `1400` NoTradePermission (403) · `2000` SignerUnauthorized (403) · `2001` SignatureExpired (403) · `2002` SignatureDoesNotMatchPayload (403) · `2003` OrderSubAccountDoesNotMatchLoggedInUser (403) · `2004` SessionKeySignerExpired (403) · `2005` SignatureInvalidV (403) · `2006` SignatureInvalidRSLength (403) · `2007` SignatureSIsNotCurveLowerHalf (403) · `2010` OrderIDShouldBeEmpty (400) · `2011` ClientOrderIDShouldBeSupplied (400) · `2012` ClientOrderIDOverlaps (400) · `2020` MarketOrderWithLimitPrice (400) · `2021` LimitOrderWithoutLimitPrice (400) · `2030` InvalidTimeInForceOrderbook (400) · `2031` InvalidTimeInForceRFQ (400) · `2032` PostOnlyWhenTakerOrder (400) · `2040` LegsEmpty (400) · `2041` LegsNotSorted (400) · `2042` LegsMultipleOrderbook (400) · `2050` NonEmptyState (400) · `2051` ExecutionMetadataShouldBeEmpty (400) · `2060` InactiveDerivative (400) · `2061` InstrumentNotSupported (400) · `2062` NumContractsUnderMinSize (400) · `2063` NumContractsUnderMinBlockSize (400) · `2064` InvalidLimitPriceTick (400) · `2065` InvalidContractGrainSize (400) · `2066` NotionalBelowMinimum (400) · `2067` PositionClosingNotionalBelowMinimum (400) · `2070` LiquidationOrderNotSupported (400) · `2080` InsufficientMargin (400) · `2081` MaximumPositionSizeExceeded (400) · `2082` FailedPreOrderCheck (400) · `2083` MaximumLeverageConfigPositionSizeExceeded (400) · `2084` FailedPostOrderCheck (400) · `2090` MaxOpenOrdersExceeded (429) · `2091` SessionOrderReduceOnlyRequired (403) · `2110` InvalidTriggerBy (400) · `2111` UnsupportedTriggerBy (400) · `2112` InvalidTriggerOrder (400) · `2113` EmptyTriggerPrice (400) · `2114` InvalidPTPSLReduceOnly (400) · `2115` InvalidPTPSLSize (400) · `2116` PTPSLOrderAlreadyExists (400) · `2117` PTPSLMustBeFromWebOrMobile (400) · `2118` InvalidTriggerPriceTick (400) · `2147` StablePerpRequiresMultiAssetMode (400) · `2148` VaultCannotTrade (400) · `2242` SplitTPSLNotSupported (400) · `2400` ReduceOnlyOrderWithNoPosition (400) · `2401` ReduceOnlyOrderIncreaseSize (400) · `2402` ReduceOnlyOrderSizeExceeded (400) · `2450` SpotOrderNotSupported (400) · `2451` SpotOrderReduceOnlyNotSupported (400) · `2452` SpotOrderTPSLNotSupported (400) · `2453` SpotTradingBlockedDuringSocializedLoss (400) · `3004` MMConfigNotFound (500) · `3005` AssetUnderlyingBalDecConfigNotFound (500) · `3006` AssetQuoteBalDecConfigNotFound (500) · `7303` DelistCreateOrderBlocked (400) · `7304` DelistPositionOpenBlocked (400) · `7600` SlippageFeatureDisabled (400) · `7601` SlippageRequiresIOCLimitOrder (400) · `7602` SlippageBelowMinimum (400) · `7603` SlippageExceedsPriceProtectionBand (400) · `7701` SfpIndicativeNotQualifiedMaker (403) · `7704` SfpOrderNotSupported (400) · `7705` SfpInstrumentMismatch (400) · `7706` SfpPrivateQuoteNotSupported (400) · `7707` SfpRfqNotLive (400) · `7708` SfpRfqAlreadyHasTakerOrder (400) · `7709` SfpTakerInvalidTimeInForce (400) · `7711` SfpMarketOrderNotAllowed (400) · `7712` RfqIDNotAllowedForNonSFP (400) · `7723` UsdcCollateralDisabled (400) · `7724` SfpPostOnlyNotAllowedForRetail (400) · `7726` SfpMarketClosed (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, enums as e, PrivateKeySigner, models as m with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: resp = client.create_order( order=m.OrderInput( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], is_market=False, time_in_force=e.TimeInForce("GOOD_TILL_TIME"), post_only=True, reduce_only=False, legs=[ m.OrderLeg( instrument="BTC_USDT_Perp", size=Decimal("0.01"), limit_price=Decimal("60000"), is_buying_asset=True, ), ], ), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): The body below is the `limit_order` signing case: a real signature by the public test key for chain id 326. Build your own with the [Signing guide](/guides/signing.md); the server will reject this one (unknown account). `signature.expiration` is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires). With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/create_order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v2/bulk_orders`, or `/lite/v2/bulk_orders` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v2/bulk_orders` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `orders[].signature` is signed: every element of `orders` separately, with its own nonce and expiration (the field tables' `order.` paths mean that element): [`Order`](/reference/signing/Order.md) / [`OrderWithBuilderFee`](/reference/signing/OrderWithBuilderFee.md). Each order is signed on its own, like create_order: OrderWithBuilderFee when that order's builder is set to a non-zero address, otherwise Order. The cancel lists and time_to_live_ms are not signed. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `order.bulk_orders` (`RPCBulkOrdersV2`) | ## Request Body type `ApiBulkOrdersRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID of the user creating the request - `orders` · lite `o` · object Order[] · optional — Orders to create or replace, supply up to 100 orders Fields: see [Order](/reference/types.md#order); listed in full under `order` on reference/rpc/create_order.md, earlier in this file. - `order_i_ds` · lite `oi` · string (uint128)[] · optional — The order IDs of the orders to cancel or replace, supply up to 100 orderIDs (a request with both `order_i_ds` and `client_order_i_ds` is rejected) - `client_order_i_ds` · lite `co` · string (uint64)[] · optional — The client order IDs of the orders to cancel or replace, supply up to 100 clientOrderIDs (a request with both `order_i_ds` and `client_order_i_ds` is rejected) - `time_to_live_ms` · lite `tt` · string (uint64) · optional, default `0` — How long a cancel by `client_order_id` keeps waiting, in milliseconds, for an order that hasn't arrived yet. A cancel can overtake the create it refers to; an order with that `client_order_id` that arrives within this time is cancelled instead of placed. A cancel by `order_id` ignores this field. Unlike `cancel_order`, `bulk_orders` doesn't check this value: it isn't rounded, has no minimum and no 5000 ms limit, and `'0'` or a missing value means the cancel doesn't wait. The wait ends at the next 100 ms boundary after it runs out. ## Response Body type `ApiBulkOrdersResponse` (the same object is the JSON-RPC `result` over WebSocket). - `orders` · lite `o` · object Order[] · required — The orders in same order as requested Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.md, earlier in this file. - `cancel_acks` · lite `ca` · object Ack[] · required — A list of acks for the cancelled orders - `cancel_acks[].ack` · lite `a` · bool · required — True when the exchange received the request and will process it. It doesn't mean the request has taken effect yet. ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1005` UnknownErr (500) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `1012` InvalidSignatureChainID (400) · `1400` NoTradePermission (403) · `2000` SignerUnauthorized (403) · `2001` SignatureExpired (403) · `2002` SignatureDoesNotMatchPayload (403) · `2003` OrderSubAccountDoesNotMatchLoggedInUser (403) · `2004` SessionKeySignerExpired (403) · `2005` SignatureInvalidV (403) · `2006` SignatureInvalidRSLength (403) · `2007` SignatureSIsNotCurveLowerHalf (403) · `2010` OrderIDShouldBeEmpty (400) · `2011` ClientOrderIDShouldBeSupplied (400) · `2012` ClientOrderIDOverlaps (400) · `2020` MarketOrderWithLimitPrice (400) · `2021` LimitOrderWithoutLimitPrice (400) · `2030` InvalidTimeInForceOrderbook (400) · `2031` InvalidTimeInForceRFQ (400) · `2032` PostOnlyWhenTakerOrder (400) · `2040` LegsEmpty (400) · `2041` LegsNotSorted (400) · `2042` LegsMultipleOrderbook (400) · `2050` NonEmptyState (400) · `2051` ExecutionMetadataShouldBeEmpty (400) · `2060` InactiveDerivative (400) · `2061` InstrumentNotSupported (400) · `2062` NumContractsUnderMinSize (400) · `2063` NumContractsUnderMinBlockSize (400) · `2064` InvalidLimitPriceTick (400) · `2065` InvalidContractGrainSize (400) · `2066` NotionalBelowMinimum (400) · `2067` PositionClosingNotionalBelowMinimum (400) · `2070` LiquidationOrderNotSupported (400) · `2080` InsufficientMargin (400) · `2081` MaximumPositionSizeExceeded (400) · `2082` FailedPreOrderCheck (400) · `2083` MaximumLeverageConfigPositionSizeExceeded (400) · `2084` FailedPostOrderCheck (400) · `2090` MaxOpenOrdersExceeded (429) · `2091` SessionOrderReduceOnlyRequired (403) · `2110` InvalidTriggerBy (400) · `2111` UnsupportedTriggerBy (400) · `2112` InvalidTriggerOrder (400) · `2113` EmptyTriggerPrice (400) · `2114` InvalidPTPSLReduceOnly (400) · `2115` InvalidPTPSLSize (400) · `2116` PTPSLOrderAlreadyExists (400) · `2117` PTPSLMustBeFromWebOrMobile (400) · `2118` InvalidTriggerPriceTick (400) · `2147` StablePerpRequiresMultiAssetMode (400) · `2148` VaultCannotTrade (400) · `2222` NotTPSLOrder (400) · `2230` InvalidOSOTriggerPrice (400) · `2232` InvalidPTPSLOrderLinkage (400) · `2233` BothOrderIDAndClientOrderIDProvided (400) · `2234` InvalidBulkOrdersAssetMismatch (400) · `2235` BulkOrdersMaxCountExceeded (400) · `2236` BulkOrdersNotSupportTriggerOrder (400) · `2237` BulkOrdersNotFromApiSource (400) · `2238` SplitTPSLMustNotBePositionLinkedTPSL (400) · `2239` SplitTPSLMustBeReduceOnly (400) · `2240` SplitTPSLCreatesMustNotContainNonSplit (400) · `2241` SplitTPSLCreatesExceedsSetSize (400) · `2242` SplitTPSLNotSupported (400) · `2243` SplitTPSLSetAlreadyExists (400) · `2244` CreatingSplitTPSLWithoutExistingPosition (400) · `2245` CreatingSplitTPSLExceedingPositionSize (400) · `2246` ModifyingSplitTPSLMismatchedCancels (400) · `2400` ReduceOnlyOrderWithNoPosition (400) · `2401` ReduceOnlyOrderIncreaseSize (400) · `2402` ReduceOnlyOrderSizeExceeded (400) · `2413` ReplaceOrderNumOrdersMismatch (400) · `2450` SpotOrderNotSupported (400) · `2451` SpotOrderReduceOnlyNotSupported (400) · `2452` SpotOrderTPSLNotSupported (400) · `2453` SpotTradingBlockedDuringSocializedLoss (400) · `3004` MMConfigNotFound (500) · `3005` AssetUnderlyingBalDecConfigNotFound (500) · `3006` AssetQuoteBalDecConfigNotFound (500) · `7303` DelistCreateOrderBlocked (400) · `7304` DelistPositionOpenBlocked (400) · `7600` SlippageFeatureDisabled (400) · `7601` SlippageRequiresIOCLimitOrder (400) · `7602` SlippageBelowMinimum (400) · `7603` SlippageExceedsPriceProtectionBand (400) · `7701` SfpIndicativeNotQualifiedMaker (403) · `7704` SfpOrderNotSupported (400) · `7705` SfpInstrumentMismatch (400) · `7706` SfpPrivateQuoteNotSupported (400) · `7707` SfpRfqNotLive (400) · `7708` SfpRfqAlreadyHasTakerOrder (400) · `7709` SfpTakerInvalidTimeInForce (400) · `7711` SfpMarketOrderNotAllowed (400) · `7712` RfqIDNotAllowedForNonSFP (400) · `7723` UsdcCollateralDisabled (400) · `7724` SfpPostOnlyNotAllowedForRetail (400) · `7726` SfpMarketClosed (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, enums as e, PrivateKeySigner, models as m with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: resp = client.bulk_orders( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], orders=[ m.OrderInput( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], is_market=False, time_in_force=e.TimeInForce("GOOD_TILL_TIME"), post_only=True, reduce_only=False, legs=[ m.OrderLeg( instrument="BTC_USDT_Perp", size=Decimal("0.5"), limit_price=Decimal("64000"), is_buying_asset=True, ), ], ), m.OrderInput( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], is_market=False, time_in_force=e.TimeInForce("GOOD_TILL_TIME"), post_only=False, reduce_only=False, legs=[ m.OrderLeg( instrument="BTC_USDT_Perp", size=Decimal("0.25"), limit_price=Decimal("66000.5"), is_buying_asset=False, ), ], builder="0x2222222222222222222222222222222222222222", builder_fee=Decimal("0.0005"), ), ], client_order_ids=[ "4001", ], time_to_live_ms="1000", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): The body below is the `bulk_orders` signing case: a real signature by the public test key for chain id 326. Build your own with the [Signing guide](/guides/signing.md); the server will reject this one (unknown account). `signature.expiration` is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires). With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v2/bulk_orders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/order`, or `/lite/v1/order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `order.get_order` (`RPCGetOrderV1`) | ## Request Body type `ApiGetOrderRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `order_id` · lite `oi` · string (uint128) · one of `order_id` / `client_order_id` required — Filter for `order_id` - `client_order_id` · lite `co` · string (uint64) · one of `order_id` / `client_order_id` required — Filter for `client_order_id` ## Response Body type `ApiGetOrderResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Order · required — The order object for the requested filter Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `3021` InvalidOrderID (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_order( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], client_order_id=os.environ["GRVT_CLIENT_ORDER_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/open_orders`, or `/lite/v1/open_orders` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/open_orders` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `order.open_orders` (`RPCOpenOrdersV1`) | ## Request Body type `ApiOpenOrdersRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `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 ## Response Body type `ApiOpenOrdersResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Order[] · required — The Open Orders matching the request filter Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.open_orders( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/open_orders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/cancel_order`, or `/lite/v1/cancel_order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/cancel_order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `order.cancel_order` (`RPCCancelOrderV1`) | ## Request Body type `ApiCancelOrderRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID cancelling the order - `order_id` · lite `oi` · string (uint128) · one of `order_id` / `client_order_id` required — Cancel the order with this `order_id` - `client_order_id` · lite `co` · string (uint64) · one of `order_id` / `client_order_id` required — Cancel the order with this `client_order_id` - `time_to_live_ms` · lite `tt` · string (uint64) · optional, default `100` — How long a cancel by `client_order_id` keeps waiting, in milliseconds, for an order that hasn't arrived yet. A cancel can overtake the create it refers to; an order with that `client_order_id` that arrives within this time is cancelled instead of placed. A cancel by `order_id` ignores this field, since an order only has an `order_id` once the exchange has it. The value is rounded down to a multiple of 100 ms (`"670"` becomes `"600"`). `"0"`, a missing value, or a value below the exchange's minimum gets the minimum. More than 5000 is rejected with `2301`. If several cancels for the same order overlap in time, only the first counts. ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object Fields: see [Ack](/reference/types.md#ack); listed in full under `cancel_acks[]` on reference/rpc/bulk_orders.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `2300` CancelTTLDisabled (400) · `2301` CancelTTLMaxExceeded (400) · `3021` InvalidOrderID (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.cancel_order( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], client_order_id=os.environ["GRVT_CLIENT_ORDER_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/cancel_order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/cancel_all_orders`, or `/lite/v1/cancel_all_orders` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/cancel_all_orders` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `order.cancel_all_orders` (`RPCCancelAllOrdersV1`) | ## Request Body type `ApiCancelAllOrdersRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID cancelling all orders - `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 cancelled 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 cancelled - `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 cancelled ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object Fields: see [Ack](/reference/types.md#ack); listed in full under `cancel_acks[]` on reference/rpc/bulk_orders.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.cancel_all_orders( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/cancel_all_orders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/cancel_on_disconnect`, or `/lite/v1/cancel_on_disconnect` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/cancel_on_disconnect` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `order.cancel_on_disconnect` (`RPCCancelOnDisconnectV1`) | ## Request Body type `ApiCancelOnDisconnectRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID cancelling the orders for - `countdown_time` · lite `ct` · string (uint64) · optional, default `0` — Countdown in milliseconds, as a string, e.g. "120000" (120 s). Omitted or under 1000 stops the countdown; above 300999 is rejected (error 6000). See the table in the call description. ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object Fields: see [Ack](/reference/types.md#ack); listed in full under `cancel_acks[]` on reference/rpc/bulk_orders.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `6000` LongCancelOnDisconnectCountdown (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.cancel_on_disconnect( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], countdown_time="120000", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/cancel_on_disconnect" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/order_history`, or `/lite/v1/order_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/order_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `order.order_history` (`RPCOrderHistoryV1`) | ## Request Body type `ApiOrderHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `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 - `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 `ApiOrderHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Order[] · required — The Open Orders matching the request filter Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.md, earlier in this file. - `next` · lite `n` · string · required — The cursor to indicate when to start the 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.order_history( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/order_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/fill_history`, or `/lite/v1/fill_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/fill_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `execution.fill_history` (`RPCFillHistoryV1`) | ## Request Body type `ApiFillHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to request for - `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 - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — The start time to apply in unix 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 unix 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 `ApiFillHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Fill[] · required — The private 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[].sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID that participated in the trade - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument being represented - `result[].is_buyer` · lite `ib` · bool · required — True if you bought in this trade, false if you sold. - `result[].is_taker` · lite `it` · bool · required — True if your order took liquidity (taker), false if it was resting on the book (maker). - `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[].realized_pnl` · lite `rp` · string · required — The realized PnL of the trade, in the quote asset. Decimal string, e.g. "12.5". (0 if increasing position size) - `result[].fee` · lite `f` · string · required — The fees paid on the trade, in the quote asset. Decimal string, e.g. "12.5". (negative if maker rebate applied) - `result[].fee_rate` · lite `fr` · string · required — The fee rate charged on this fill, in percent (`"0.02"` = 0.02%). - `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[].order_id` · lite `oi` · string (uint128) · required — The exchange's id of your order that filled. - `result[].venue` · lite `v` · enum Venue · required — The venue where the trade occurred Values: `ORDERBOOK`, `RFQ` ([details](/reference/enums.md#venue)). - `result[].is_liquidation` · lite `il` · bool · required — If the trade was a liquidation - `result[].client_order_id` · lite `co` · string (uint64) · required — The `client_order_id` of your order that filled. - `result[].signer` · lite `s1` · string (uint256) · required — The address of the wallet that signed the order. - `result[].broker` · lite `b` · enum BrokerTag · optional — Specifies the broker who brokered the order Values: `UNSPECIFIED`, `COIN_ROUTES`, `ALERTATRON`, `ORIGAMI` ([details](/reference/enums.md#brokertag)). - `result[].is_rpi` · lite `ir1` · bool · required — If the trade is a RPI trade - `result[].builder` · lite `b1` · string (0x address) · required — The main account id of the builder the order went through, if any. - `result[].builder_fee_rate` · lite `bf` · string · required — The builder's fee rate for this order, in percent (`"0.001"` = 0.001%), as set in the order's `builder_fee`. - `result[].builder_fee` · lite `bf1` · string · required — The builder fee paid on this trade, in the quote asset. Decimal string, e.g. "12.5". - `result[].fee_currency` · lite `fc` · string · required — The currency of the fee paid on the trade - `result[].repayment_scenario` · lite `rs` · enum RepaymentScenario · required — Set when this fill repaid a multi-asset-mode USDT loan, and says how; `UNSPECIFIED` for ordinary trades. Values: `MANUAL_REPAYMENT`, `AUTO_REPAYMENT`, `LIQUIDATION_REPAYMENT`, `AUTO_REPAY_BORROW_LIMIT`, `AUTO_REPAY_LTV`, `LIQUIDATION_REBALANCING` ([details](/reference/enums.md#repaymentscenario)). - `result[].rfq_id` · lite `ri` · string (uint128) · optional — The RFQ this fill was cleared against. Only set for RFQ venue fills; unset otherwise - `result[].counterparty_type` · lite `ct` · enum RfqCounterpartyType · optional — The type of counterparty this fill was matched against (maker quote / resting order / forced-exit netting). Only set for RFQ venue fills; unset otherwise Values: `MAKER_QUOTE`, `RESTING_ORDER`, `FORCED_EXIT_NETTING` ([details](/reference/enums.md#rfqcounterpartytype)). - `next` · lite `n` · string · required — The cursor to indicate when to start the 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.fill_history( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/fill_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`open_orders`](/reference/rpc/open_orders.md), [`order_history`](/reference/rpc/order_history.md)) for what you missed. | | Contract id | `order.order` (`StreamOrderV1`) | ## Selector Grammar `[-]`, e.g. `-BTC_USDT_Perp`. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSOrderFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.order`. - `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 Order · required — The order object being created or updated Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.order_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.order", "selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.order", "s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "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/order_state.md # Order state stream | | | |---|---| | SDK | `client.order_state_stream(...)` | | Channel | `v1.state` on `wss://trades./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`open_orders`](/reference/rpc/open_orders.md), [`order_history`](/reference/rpc/order_history.md)) for what you missed. | | Contract id | `order.order_state` (`StreamOrderStateV1`) | ## Selector Grammar `[-]`, e.g. `-BTC_USDT_Perp`. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSOrderStateFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.state`. - `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 OrderStateFeed · required — The Order State Feed - `feed.order_id` · lite `oi` · string (uint128) · required — The exchange's 128-bit id for the order. - `feed.client_order_id` · lite `co` · string (uint64) · required — A unique identifier for the active order within a sub-account, specified by the client - `feed.order_state` · lite `os` · object OrderState · required — The order state object being created or updated Fields: see [OrderState](/reference/types.md#orderstate); listed in full under `result.state` on reference/rpc/create_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.order_state_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.state", "selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.state", "s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "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/fill.md # Fill stream | | | |---|---| | SDK | `client.fill_stream(...)` | | Channel | `v1.fill` on `wss://trades./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`fill_history`](/reference/rpc/fill_history.md)) for what you missed. | | Contract id | `execution.fill` (`StreamFillV1`) | ## Selector Grammar `[-]`, e.g. `-BTC_USDT_Perp`. Parts: - `sub_account_id` · uint64 — The sub-account ID to request for - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSFillFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.fill`. - `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 Fill · required — A private trade matching the request filter Fields: see [Fill](/reference/types.md#fill); listed in full under `result[]` on reference/rpc/fill_history.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.fill_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.fill", "selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.fill", "s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "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/cancel_status.md # Cancel status stream | | | |---|---| | SDK | `client.cancel_status_stream(...)` | | Channel | `v1.cancel` on `wss://trades./ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`open_orders`](/reference/rpc/open_orders.md), [`order_history`](/reference/rpc/order_history.md)) for what you missed. | | Contract id | `order.cancel_status` (`StreamCancelStatusV1`) | ## Selector Grammar ``, e.g. ``. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by ## Frame Type `WSCancelFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.cancel`. - `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 CancelStatusFeed · required — Data relating to the status of the cancellation attempt - `feed.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID that requested the cancellation - `feed.client_order_id` · lite `co` · string (uint64) · required — A unique identifier for the active order within a sub-account, specified by the client - `feed.order_id` · lite `oi` · string (uint128) · required — The exchange's 128-bit id for the order. - `feed.reason` · lite `r` · enum OrderRejectReason · required — The user-provided reason for cancelling the order Values: `UNSPECIFIED`, `CLIENT_CANCEL`, `CLIENT_BULK_CANCEL`, `CLIENT_SESSION_END`, `MARKET_CANCEL`, `IOC_CANCEL`, `AON_CANCEL`, `FOK_CANCEL`, `EXPIRED`, `FAIL_POST_ONLY`, `FAIL_REDUCE_ONLY`, `MM_PROTECTION`, `SELF_TRADE_PROTECTION`, `SELF_MATCHED_SUBACCOUNT`, `OVERLAPPING_CLIENT_ORDER_ID`, `BELOW_MARGIN`, `LIQUIDATION`, `INSTRUMENT_INVALID`, `INSTRUMENT_DEACTIVATED`, `SYSTEM_FAILOVER`, `UNAUTHORISED`, `SESSION_KEY_EXPIRED`, `SUB_ACCOUNT_NOT_FOUND`, `NO_TRADE_PERMISSION`, `UNSUPPORTED_TIME_IN_FORCE`, `MULTI_LEGGED_ORDER`, `EXCEED_MAX_POSITION_SIZE`, `EXCEED_MAX_SIGNATURE_EXPIRATION`, `MARKET_ORDER_WITH_LIMIT_PRICE`, `CLIENT_CANCEL_ON_DISCONNECT_TRIGGERED`, `OCO_COUNTER_PART_TRIGGERED`, `REDUCE_ONLY_LIMIT`, `CLIENT_REPLACE`, `DERISK_MUST_BE_IOC`, `DERISK_MUST_BE_REDUCE_ONLY`, `DERISK_NOT_SUPPORTED`, `INVALID_ORDER_TYPE`, `CURRENCY_NOT_DEFINED`, `INVALID_CHAIN_ID`, `BUILDER_ORDER_FEE_EXCEED`, `BUILDER_ORDER_FEE_NEGATIVE`, `BUILDER_ORDER_BUILDER_NOT_AUTHORIZED`, `BUILDER_ORDER_BUILDER_NOT_EXIST`, `TRADE_PRICE_WORSE_THAN_BANKRUPTCY_PRICE`, `TOO_MANY_MAKER_ORDERS`, `REDUCE_ONLY_NOT_SUPPORTED_FOR_SPOT_ORDER`, `TPSL_NOT_SUPPORTED_FOR_SPOT_ORDER`, `SPOT_ORDER_NOT_SUPPORTED`, `INSUFFICIENT_BALANCE`, `SPOT_TRADING_BLOCKED_DURING_SOCIALIZED_LOSS`, `BELOW_MARGIN_WITH_PENALTY_DEVIATION`, `CORPORATE_ACTION`, `NOT_QUALIFIED_MAKER`, `PRIVATE_QUOTE_REQUIRES_RFQ`, `STABLE_PERP_REQUIRES_PRICE_BOUND`, `UNSUPPORTED_TRIGGER_BY`, `RFQ_NOT_FOUND`, `RESTING_ORDER_WOULD_CROSS`, `SESSION_CLOSED`, `RFQ_TERMINATED`, `STABLE_PERP_REQUIRES_MULTI_ASSET_MODE`, `BORROW_LIMIT_EXCEEDED_AFTER_TRADE`, `UNDEPLOYED_LOAN_AUTO_EXCHANGE`, `LIQUIDATION_AUTO_EXCHANGE`, `USDC_COLLATERAL_DISABLED`, `SFP_POST_ONLY_NOT_ALLOWED`, `VAULT_NON_QUOTE_INVESTMENT_CURRENCY`, `RFQ_ID_REQUIRES_STABLE_PERP`, `RFQ_PRIVATE_POOL_NOT_SUPPORTED`, `RFQ_REQUIRES_IOC`, `RFQ_MISMATCH`, `RFQ_ALREADY_BOUND`, `RFQ_MAKER_MUST_BE_ECN`, `FOK_NOT_SUPPORTED`, `MARKET_ORDER_NOT_SUPPORTED`, `STABLE_PERP_ORDER_NOT_SUPPORTED` ([details](/reference/enums.md#orderrejectreason)). - `feed.update_time` · lite `ut` · string (int64 unix ns) · optional, default `0` — Set by the server. Time at which the cancellation status was updated by Grvt in unix nanoseconds - `feed.cancel_status` · lite `cs` · enum CancelStatus · required — Status of the cancellation attempt Values: `EXPIRED`, `DROPPED_DUPLICATE` ([details](/reference/enums.md#cancelstatus)). - `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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.cancel_status_stream(sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.cancel", "selectors": ["$GRVT_SUB_ACCOUNT_ID"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.cancel", "s1": ["$GRVT_SUB_ACCOUNT_ID"], "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/create_algo_order.md # Create algo order Algo trading must be enabled for the sub-account first (`algo_trading_enabled` in [sub_account_summary](/reference/rpc/sub_account_summary.md)). You don't sign an algo order: the exchange signs and places its sub-orders for you. Only `CHASE` is supported. | | | |---|---| | SDK | `client.create_algo_order(...)` | | HTTP | `POST https://trades./full/v1/create_algo_order`, or `/lite/v1/create_algo_order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/create_algo_order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `algo_order.create_algo_order` (`RPCCreateAlgoOrderV1`) | ## Request Body type `ApiCreateAlgoOrderRequest`. Fields the server fills are left out. - `order` · lite `o` · object AlgoOrder · required — The algo order to create - `order.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account initiating the algo order - `order.type` · lite `t` · enum AlgoOrderType · required — The type of the algo order Values: `CHASE` ([details](/reference/enums.md#algoordertype)). - `order.post_only` · lite `po` · bool · optional, default `false` — If True, every sub-order must be a maker order. Chase orders are always post-only - `order.reduce_only` · lite `ro` · bool · optional, default `false` — If True, every sub-order must reduce the position size, or be cancelled - `order.leg` · lite `l` · object AlgoOrderLeg · required — The single leg traded by this algo order - `order.leg.instrument` · lite `i` · string (instrument name) · required — The instrument to trade - `order.leg.size` · lite `s` · string · required — The total number of assets to trade across all sub-orders. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `order.leg.is_buying_asset` · lite `ib` · bool · required — Specifies if the algo order is a buy or sell - `order.metadata` · lite `m` · object AlgoOrderMetadata · required — Algo order metadata, including the type-specific parameters - `order.metadata.client_order_id` · lite `co` · string (uint64) · required — Your own id for the algo order, unique among the sub-account's open algo orders. You can cancel the algo order by it. - `order.metadata.trigger` · lite `t` · object TriggerOrderMetadata · optional — Trigger fields. If set, the algo order stays pending until the trigger price is crossed Fields: see [TriggerOrderMetadata](/reference/types.md#triggerordermetadata); listed in full under `order.metadata.trigger` on reference/rpc/create_order.md, earlier in this file. - `order.metadata.broker` · lite `b` · enum BrokerTag · optional — Specifies the broker who brokered the algo order Values: `UNSPECIFIED`, `COIN_ROUTES`, `ALERTATRON`, `ORIGAMI` ([details](/reference/enums.md#brokertag)). - `order.metadata.expiry` · lite `e` · string (int64 unix ns) · optional, default `0` — Time at which the algo order expires, expressed in unix nanoseconds. Defaults to and must be capped at 90 days - `order.metadata.chase` · lite `c` · object ChaseAlgoOrderMetadata · optional — Chase order parameters. Set only when the algo order type is CHASE - `order.metadata.chase.chase_price_mode` · lite `cp` · enum ChasePriceMode · required — How the chase price is determined at each re-price tick Values: `BEST_BID_ASK` ([details](/reference/enums.md#chasepricemode)). - `order.metadata.chase.max_distance` · lite `md` · string · required — The maximum distance the chase price can move away from the reference price, as an absolute price distance in quote currency units. Decimal string, e.g. "65000.5"; up to 9 decimals. Always absolute: when the user picks a percentage, the client converts it and sends the result here. - `order.metadata.chase.max_distance_bps` · lite `md1` · integer (uint32) · optional, default `0` — The max distance as a percentage in basis points (1 bp = 0.01%, 100% = 10000), as the user entered it. `0` if the user entered an absolute distance. Informational only, for display and history. `maxDistance` is what is enforced. - `order.builder` · lite `b` · string (0x address) · required — The main account ID of the builder - `order.builder_fee` · lite `bf` · string · required — Builder fee charged for every sub-order, expressed as a percentage (e.g., 0.001 means 0.001%). ## Response Body type `ApiCreateAlgoOrderResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object AlgoOrder · required — The created algo order - `result.algo_order_id` · lite `ao` · string (uint128) · optional, default `0` — Set by the server. The exchange's 128-bit id for the algo order. - `result.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account initiating the algo order - `result.type` · lite `t` · enum AlgoOrderType · required — The type of the algo order Values: `CHASE` ([details](/reference/enums.md#algoordertype)). - `result.post_only` · lite `po` · bool · optional, default `false` — If True, every sub-order must be a maker order. Chase orders are always post-only - `result.reduce_only` · lite `ro` · bool · optional, default `false` — If True, every sub-order must reduce the position size, or be cancelled - `result.leg` · lite `l` · object AlgoOrderLeg · required — The single leg traded by this algo order - `result.leg.instrument` · lite `i` · string (instrument name) · required — The instrument to trade - `result.leg.size` · lite `s` · string · required — The total number of assets to trade across all sub-orders. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `result.leg.is_buying_asset` · lite `ib` · bool · required — Specifies if the algo order is a buy or sell - `result.metadata` · lite `m` · object AlgoOrderMetadata · required — Algo order metadata, including the type-specific parameters - `result.metadata.client_order_id` · lite `co` · string (uint64) · required — Your own id for the algo order, unique among the sub-account's open algo orders. You can cancel the algo order by it. - `result.metadata.create_time` · lite `ct` · string (int64 unix ns) · optional, default `0` — Set by the server. Time at which the algo order was received by Grvt in unix nanoseconds - `result.metadata.trigger` · lite `t` · object TriggerOrderMetadata · optional — Trigger fields. If set, the algo order stays pending until the trigger price is crossed Fields: see [TriggerOrderMetadata](/reference/types.md#triggerordermetadata); listed in full under `result.metadata.trigger` on reference/rpc/create_order.md, earlier in this file. - `result.metadata.broker` · lite `b` · enum BrokerTag · optional — Specifies the broker who brokered the algo order Values: `UNSPECIFIED`, `COIN_ROUTES`, `ALERTATRON`, `ORIGAMI` ([details](/reference/enums.md#brokertag)). - `result.metadata.expiry` · lite `e` · string (int64 unix ns) · optional, default `0` — Time at which the algo order expires, expressed in unix nanoseconds. Defaults to and must be capped at 90 days - `result.metadata.chase` · lite `c` · object ChaseAlgoOrderMetadata · optional — Chase order parameters. Set only when the algo order type is CHASE - `result.metadata.chase.chase_price_mode` · lite `cp` · enum ChasePriceMode · required — How the chase price is determined at each re-price tick Values: `BEST_BID_ASK` ([details](/reference/enums.md#chasepricemode)). - `result.metadata.chase.max_distance` · lite `md` · string · required — The maximum distance the chase price can move away from the reference price, as an absolute price distance in quote currency units. Decimal string, e.g. "65000.5"; up to 9 decimals. Always absolute: when the user picks a percentage, the client converts it and sends the result here. - `result.metadata.chase.max_distance_bps` · lite `md1` · integer (uint32) · optional, default `0` — The max distance as a percentage in basis points (1 bp = 0.01%, 100% = 10000), as the user entered it. `0` if the user entered an absolute distance. Informational only, for display and history. `maxDistance` is what is enforced. - `result.state` · lite `s` · object AlgoOrderState · optional — Set by the server. The current state of the algo order - `result.state.status` · lite `s` · enum OrderStatus · required — The status of the algo order Values: `PENDING`, `OPEN`, `FILLED`, `REJECTED`, `CANCELLED` ([details](/reference/enums.md#orderstatus)). - `result.state.reject_reason` · lite `rr` · enum OrderRejectReason · required — The reason for rejection or cancellation Values: `UNSPECIFIED`, `CLIENT_CANCEL`, `CLIENT_BULK_CANCEL`, `CLIENT_SESSION_END`, `MARKET_CANCEL`, `IOC_CANCEL`, `AON_CANCEL`, `FOK_CANCEL`, `EXPIRED`, `FAIL_POST_ONLY`, `FAIL_REDUCE_ONLY`, `MM_PROTECTION`, `SELF_TRADE_PROTECTION`, `SELF_MATCHED_SUBACCOUNT`, `OVERLAPPING_CLIENT_ORDER_ID`, `BELOW_MARGIN`, `LIQUIDATION`, `INSTRUMENT_INVALID`, `INSTRUMENT_DEACTIVATED`, `SYSTEM_FAILOVER`, `UNAUTHORISED`, `SESSION_KEY_EXPIRED`, `SUB_ACCOUNT_NOT_FOUND`, `NO_TRADE_PERMISSION`, `UNSUPPORTED_TIME_IN_FORCE`, `MULTI_LEGGED_ORDER`, `EXCEED_MAX_POSITION_SIZE`, `EXCEED_MAX_SIGNATURE_EXPIRATION`, `MARKET_ORDER_WITH_LIMIT_PRICE`, `CLIENT_CANCEL_ON_DISCONNECT_TRIGGERED`, `OCO_COUNTER_PART_TRIGGERED`, `REDUCE_ONLY_LIMIT`, `CLIENT_REPLACE`, `DERISK_MUST_BE_IOC`, `DERISK_MUST_BE_REDUCE_ONLY`, `DERISK_NOT_SUPPORTED`, `INVALID_ORDER_TYPE`, `CURRENCY_NOT_DEFINED`, `INVALID_CHAIN_ID`, `BUILDER_ORDER_FEE_EXCEED`, `BUILDER_ORDER_FEE_NEGATIVE`, `BUILDER_ORDER_BUILDER_NOT_AUTHORIZED`, `BUILDER_ORDER_BUILDER_NOT_EXIST`, `TRADE_PRICE_WORSE_THAN_BANKRUPTCY_PRICE`, `TOO_MANY_MAKER_ORDERS`, `REDUCE_ONLY_NOT_SUPPORTED_FOR_SPOT_ORDER`, `TPSL_NOT_SUPPORTED_FOR_SPOT_ORDER`, `SPOT_ORDER_NOT_SUPPORTED`, `INSUFFICIENT_BALANCE`, `SPOT_TRADING_BLOCKED_DURING_SOCIALIZED_LOSS`, `BELOW_MARGIN_WITH_PENALTY_DEVIATION`, `CORPORATE_ACTION`, `NOT_QUALIFIED_MAKER`, `PRIVATE_QUOTE_REQUIRES_RFQ`, `STABLE_PERP_REQUIRES_PRICE_BOUND`, `UNSUPPORTED_TRIGGER_BY`, `RFQ_NOT_FOUND`, `RESTING_ORDER_WOULD_CROSS`, `SESSION_CLOSED`, `RFQ_TERMINATED`, `STABLE_PERP_REQUIRES_MULTI_ASSET_MODE`, `BORROW_LIMIT_EXCEEDED_AFTER_TRADE`, `UNDEPLOYED_LOAN_AUTO_EXCHANGE`, `LIQUIDATION_AUTO_EXCHANGE`, `USDC_COLLATERAL_DISABLED`, `SFP_POST_ONLY_NOT_ALLOWED`, `VAULT_NON_QUOTE_INVESTMENT_CURRENCY`, `RFQ_ID_REQUIRES_STABLE_PERP`, `RFQ_PRIVATE_POOL_NOT_SUPPORTED`, `RFQ_REQUIRES_IOC`, `RFQ_MISMATCH`, `RFQ_ALREADY_BOUND`, `RFQ_MAKER_MUST_BE_ECN`, `FOK_NOT_SUPPORTED`, `MARKET_ORDER_NOT_SUPPORTED`, `STABLE_PERP_ORDER_NOT_SUPPORTED` ([details](/reference/enums.md#orderrejectreason)). - `result.state.traded_size` · lite `ts` · string · required — The total number of assets traded across all sub-orders - `result.state.avg_fill_price` · lite `af` · string · required — The average fill price across all sub-orders - `result.state.trigger_time` · lite `tt` · string (int64 unix ns) · optional, default `0` — Time at which the algo order was triggered in unix nanoseconds, 0 if not triggered yet - `result.state.update_time` · lite `ut` · string (int64 unix ns) · required — Time at which the algo order was updated by Grvt in unix nanoseconds - `result.state.chase` · lite `c` · object ChaseOrderState · optional — Chase order state. Set only when the algo order type is CHASE - `result.state.chase.reprice_count` · lite `rc` · integer (uint32) · required — The number of successful re-prices of this algo order's sub-orders - `result.state.last_sub_order_id` · lite `ls` · string (uint128) · required — The latest sub-order placed for this algo order, 0 until the first sub-order is placed - `result.builder` · lite `b` · string (0x address) · required — The main account ID of the builder - `result.builder_fee` · lite `bf` · string · required — Builder fee charged for every sub-order, expressed as a percentage (e.g., 0.001 means 0.001%). ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from decimal import Decimal from grvt import Grvt, enums as e, models as m with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.create_algo_order( order=m.AlgoOrder( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], type=e.AlgoOrderType("CHASE"), leg=m.AlgoOrderLeg( instrument="BTC_USDT_Perp", size=Decimal("10.5"), is_buying_asset=True, ), metadata=m.AlgoOrderMetadata( client_order_id="23042", ), builder=os.environ["GRVT_MAIN_ACCOUNT_ID"], builder_fee=Decimal("0.001"), ), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/create_algo_order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/get_algo_order`, or `/lite/v1/get_algo_order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_algo_order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `algo_order.get_algo_order` (`RPCGetAlgoOrderV1`) | ## Request Body type `ApiGetAlgoOrderRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `algo_order_id` · lite `ao` · string (uint128) · one of `algo_order_id` / `client_order_id` required — Filter for `algo_order_id` - `client_order_id` · lite `co` · string (uint64) · one of `algo_order_id` / `client_order_id` required — Filter for `client_order_id` ## Response Body type `ApiGetAlgoOrderResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object AlgoOrder · required — The algo order for the requested filter Fields: see [AlgoOrder](/reference/types.md#algoorder); listed in full under `result` on reference/rpc/create_algo_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_algo_order( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], client_order_id=os.environ["GRVT_CLIENT_ORDER_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/get_algo_order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/open_algo_orders`, or `/lite/v1/open_algo_orders` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/open_algo_orders` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `algo_order.open_algo_orders` (`RPCOpenAlgoOrdersV1`) | ## Request Body type `ApiOpenAlgoOrdersRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `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 - `type` · lite `t` · enum AlgoOrderType[] · optional, default `all` — The algo order type filter to apply. If nil, this defaults to all types. Otherwise, only entries matching the filter will be returned Values: `CHASE` ([details](/reference/enums.md#algoordertype)). - `trigger_filter` · lite `tf` · enum AlgoTriggerFilter · optional, default `all` — The trigger filter to apply. If nil, this defaults to all algo orders. Otherwise, `WITH_TRIGGER` returns only algo orders that carry a trigger, and `WITHOUT_TRIGGER` returns only those that do not Values: `WITH_TRIGGER`, `WITHOUT_TRIGGER` ([details](/reference/enums.md#algotriggerfilter)). ## Response Body type `ApiOpenAlgoOrdersResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object AlgoOrder[] · required — The open algo orders matching the request filter Fields: see [AlgoOrder](/reference/types.md#algoorder); listed in full under `result` on reference/rpc/create_algo_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.open_algo_orders( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/open_algo_orders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/cancel_algo_order`, or `/lite/v1/cancel_algo_order` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/cancel_algo_order` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `algo_order.cancel_algo_order` (`RPCCancelAlgoOrderV1`) | ## Request Body type `ApiCancelAlgoOrderRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID cancelling the algo order - `algo_order_id` · lite `ao` · string (uint128) · one of `algo_order_id` / `client_order_id` required — Cancel the algo order with this `algo_order_id` - `client_order_id` · lite `co` · string (uint64) · one of `algo_order_id` / `client_order_id` required — Cancel the algo order with this `client_order_id` ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object Fields: see [Ack](/reference/types.md#ack); listed in full under `cancel_acks[]` on reference/rpc/bulk_orders.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.cancel_algo_order( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], client_order_id=os.environ["GRVT_CLIENT_ORDER_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/cancel_algo_order" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/algo_order_history`, or `/lite/v1/algo_order_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/algo_order_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `algo_order.algo_order_history` (`RPCAlgoOrderHistoryV1`) | ## Request Body type `ApiAlgoOrderHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `type` · lite `t` · enum AlgoOrderType[] · optional, default `all` — The algo order type filter to apply. If nil, this defaults to all types. Otherwise, only entries matching the filter will be returned Values: `CHASE` ([details](/reference/enums.md#algoordertype)). - `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 `ApiAlgoOrderHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object AlgoOrder[] · required — The algo orders matching the request filter Fields: see [AlgoOrder](/reference/types.md#algoorder); listed in full under `result` on reference/rpc/create_algo_order.md, earlier in this file. - `next` · lite `n` · string · required — The cursor to indicate when to start the 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.algo_order_history( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/algo_order_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/algo_sub_order_history`, or `/lite/v1/algo_sub_order_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/algo_sub_order_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `algo_order.algo_sub_order_history` (`RPCAlgoSubOrderHistoryV1`) | ## Request Body type `ApiAlgoSubOrderHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by - `algo_order_id` · lite `ao` · string (uint128) · required — The `algo_order_id` whose sub-orders are retrieved ## Response Body type `ApiAlgoSubOrderHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Order[] · required — The sub-orders of the requested algo order Fields: see [Order](/reference/types.md#order); listed in full under `result` on reference/rpc/create_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.algo_sub_order_history( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], algo_order_id="0x1028403", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/algo_sub_order_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`open_algo_orders`](/reference/rpc/open_algo_orders.md), [`algo_order_history`](/reference/rpc/algo_order_history.md)) for what you missed. | | Contract id | `algo_order.algo_order` (`StreamAlgoOrderV1`) | ## Selector Grammar `[-]`, e.g. `-BTC_USDT_Perp`. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSAlgoOrderFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.algo.order`. - `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 AlgoOrder · required — The algo order object being created or updated Fields: see [AlgoOrder](/reference/types.md#algoorder); listed in full under `result` on reference/rpc/create_algo_order.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1015` ServiceUnavailable (503, retryable) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.algo_order_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.algo.order", "selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.algo.order", "s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "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/create_rfq.md # Create RFQ A taker solicits private quotes for one STABLE_PERP instrument by giving a size and, optionally, a direction (`rfq.side`; leave it out for a two-way request). The request is unsigned: creating an RFQ commits the taker to nothing. End-to-end flow: 1. The taker submits an RFQ here. (In the Grvt UI, entering a size on the trade page is the RFQ.) 2. Grvt broadcasts the RFQ to qualified makers on the `v1.rfq` stream, with an anonymous id instead of the taker's account and without its side. Makers can add ECN orders bound to it (`metadata.rfq_id`). 3. The `v1.quote` stream sends the taker, for each side of the book, the average fill price for the RFQ size and how much of it can fill, as the book changes. 4. The taker accepts by signing an IOC limit order with [create_order](/reference/rpc/create_order.md) and `metadata.rfq_id` set (one leg; its side must match `rfq.side` when that is set). Or the taker walks away and lets the RFQ expire. The created RFQ is returned in the response. A sub-account may hold at most one open RFQ per instrument. The RFQ lives until `rfq.expiry`; then Grvt expires it and cancels the makers' orders bound to it. The sub-account must be in multi-asset mode. | | | |---|---| | SDK | `client.create_rfq(...)` | | HTTP | `POST https://trades./full/v1/create_rfq`, or `/lite/v1/create_rfq` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/create_rfq` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `rfq.create_rfq` (`RPCCreateRfqV1`) | ## Request Body type `ApiCreateRfqRequest`. Fields the server fills are left out. - `rfq` · lite `r` · object Rfq · required — The RFQ to create - `rfq.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account initiating the RFQ - `rfq.expiry` · lite `e` · string (int64 unix ns) · required — When the RFQ expires, in unix nanoseconds. Default 60s, cap 300s (per-instrument config) - `rfq.instrument` · lite `i` · string (instrument name) · required — The instrument to trade. Must be kind = STABLE_PERP - `rfq.size` · lite `s` · string · required — Requested size (positive). Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `rfq.side` · lite `s1` · enum RfqSide · optional — Optional — omitted = two-way request. The Grvt UI always fills it; API takers may withhold direction and accept two-way quotes Values: `UNSPECIFIED`, `BUY`, `SELL` ([details](/reference/enums.md#rfqside)). ## Response Body type `ApiCreateRfqResponse` (the same object is the JSON-RPC `result` over WebSocket). - `rfq` · lite `r` · object Rfq · required — The created RFQ - `rfq.rfq_id` · lite `ri` · string (uint128) · required — Set by the server. The exchange's 128-bit id for the RFQ. - `rfq.sub_account_id` · lite `sa` · string (uint64) · required — The sub-account initiating the RFQ - `rfq.expiry` · lite `e` · string (int64 unix ns) · required — When the RFQ expires, in unix nanoseconds. Default 60s, cap 300s (per-instrument config) - `rfq.instrument` · lite `i` · string (instrument name) · required — The instrument to trade. Must be kind = STABLE_PERP - `rfq.size` · lite `s` · string · required — Requested size (positive). Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `rfq.side` · lite `s1` · enum RfqSide · optional — Optional — omitted = two-way request. The Grvt UI always fills it; API takers may withhold direction and accept two-way quotes Values: `UNSPECIFIED`, `BUY`, `SELL` ([details](/reference/enums.md#rfqside)). ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `2061` InstrumentNotSupported (400) · `2065` InvalidContractGrainSize (400) · `2141` RfqSubAccountDoesNotMatchLoggedInUser (403) · `2142` RfqInstrumentNotStablePerp (400) · `2143` RfqSizeBelowMinimum (400) · `2144` RfqSizeAboveMaximum (400) · `2145` RfqInvalidExpiry (400) · `2146` RfqAlreadyExistsForAsset (400) · `2147` StablePerpRequiresMultiAssetMode (400) · `7726` SfpMarketClosed (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, Timestamp, models as m with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.create_rfq( rfq=m.RfqInput( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], expiry=Timestamp(int("1697788800000000000")), instrument="AAPL_USDC_SFP", size=Decimal("10.5"), ), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/create_rfq" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/cancel_rfq`, or `/lite/v1/cancel_rfq` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/cancel_rfq` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `rfq.cancel_rfq` (`RPCCancelRfqV1`) | ## Request Body type `ApiCancelRfqRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID cancelling the RFQ - `rfq_id` · lite `ri` · string (uint128) · required — Cancel the RFQ with this `rfq_id` ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object Fields: see [Ack](/reference/types.md#ack); listed in full under `cancel_acks[]` on reference/rpc/bulk_orders.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.cancel_rfq( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], rfq_id=os.environ["GRVT_RFQ_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/cancel_rfq" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 for what you missed. | | Contract id | `rfq.rfq_quote` (`StreamRfqQuoteV1`) | ## Selector Grammar `[-]`, e.g. `-AAPL_USDC_SFP`. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSRfqQuoteFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.quote`. - `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 RfqQuoteFeed · required — The taker's private quote book for their open RFQ on this instrument - `feed.rfq_id` · lite `ri` · string (uint128) · required — The RFQ this estimate belongs to. A feed with no levels means the RFQ ended - `feed.best_bid` · lite `bb` · string · optional — Average fill price to sell the RFQ size. Decimal string, e.g. "65000.5"; up to 9 decimals. Omitted when the bid side is empty - `feed.best_ask` · lite `ba` · string · optional — Average fill price to buy the RFQ size. Decimal string, e.g. "65000.5"; up to 9 decimals. Omitted when the ask side is empty - `feed.bid_levels` · lite `bl` · object RfqQuoteLevel[] · required — The sell-side estimate (at most one level), from the bids - `feed.bid_levels[].price` · lite `p` · string · required — Average fill price for the size. Decimal string, e.g. "65000.5"; up to 9 decimals. Rounded against the taker: up for asks, down for bids - `feed.bid_levels[].size` · lite `s` · string · required — Fillable size, up to the RFQ size. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. - `feed.bid_levels[].maker_anon_account_id` · lite `ma` · string (uint128) · required — The maker's derived anonymous account id shown to the taker. Real maker identity is never exposed - `feed.bid_levels[].time_in_force` · lite `ti` · enum TimeInForce · required — Distinguishes an AON level (liftable only in full — POST-MVP) from a GTT level Values: `GOOD_TILL_TIME`, `ALL_OR_NONE`, `IMMEDIATE_OR_CANCEL`, `FILL_OR_KILL`, `RETAIL_PRICE_IMPROVEMENT` ([details](/reference/enums.md#timeinforce)). - `feed.ask_levels` · lite `al` · object RfqQuoteLevel[] · required — The buy-side estimate (at most one level), from the asks Fields: same as `feed.bid_levels[]` above. - `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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.rfq_quote_stream(instrument="AAPL_USDC_SFP", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.quote", "selectors": ["$GRVT_SUB_ACCOUNT_ID-AAPL_USDC_SFP"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.quote", "s1": ["$GRVT_SUB_ACCOUNT_ID-AAPL_USDC_SFP"], "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/positions.md # Positions | | | |---|---| | SDK | `client.positions(...)` | | HTTP | `POST https://trades./full/v1/positions`, or `/lite/v1/positions` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/positions` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `position.positions` (`RPCPositionsV1`) | ## Request Body type `ApiPositionsRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to request for - `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 ## Response Body type `ApiPositionsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Positions[] · required — The positions matching the request filter - `result[].event_time` · lite `et` · string (int64 unix ns) · required — Time at which the event was emitted in unix nanoseconds - `result[].sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID that participated in the trade - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument being represented - `result[].size` · lite `s` · string · required — The size of the position. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. Negative for short positions - `result[].notional` · lite `n` · string · required — The notional value of the position, negative for short assets, in the quote asset. Decimal string, e.g. "12.5". - `result[].entry_price` · lite `ep` · string · required — The entry price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. Whenever increasing the size of a position, the entry price is updated to the new average entry price `new_entry_price = (old_entry_price * old_size + trade_price * trade_size) / (old_size + trade_size)` - `result[].exit_price` · lite `ep1` · string · required — The exit price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. Whenever decreasing the size of a position, the exit price is updated to the new average exit price `new_exit_price = (old_exit_price * old_exit_trade_size + trade_price * trade_size) / (old_exit_trade_size + trade_size)` - `result[].mark_price` · lite `mp` · string · required — The mark price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result[].unrealized_pnl` · lite `up` · string · required — The unrealized PnL of the position, in the quote asset. Decimal string, e.g. "12.5". `unrealized_pnl = (mark_price - entry_price) * size` - `result[].realized_pnl` · lite `rp` · string · required — The realized PnL of the position, in the quote asset. Decimal string, e.g. "12.5". `realized_pnl = (exit_price - entry_price) * exit_trade_size` - `result[].total_pnl` · lite `tp` · string · required — The total PnL of the position, in the quote asset. Decimal string, e.g. "12.5". `total_pnl = realized_pnl + unrealized_pnl` - `result[].roi` · lite `r` · string · required — The ROI of the position, expressed as a percentage `roi = (total_pnl / (entry_price * abs(size))) * 100^` - `result[].quote_index_price` · lite `qi` · string · required — The index price of the quote currency. (reported in `USD`) - `result[].est_liquidation_price` · lite `el` · string · required — The estimated liquidation price - `result[].leverage` · lite `l` · string · required — The current leverage value for this position - `result[].cumulative_fee` · lite `cf` · string · required — The cumulative fee paid on the position, in the quote asset. Decimal string, e.g. "12.5". - `result[].cumulative_realized_funding_payment` · lite `cr` · string · required — The cumulative realized funding payment of the position, in the quote asset. Decimal string, e.g. "12.5". Positive if paid, negative if received - `result[].margin_type` · lite `mt` · enum PositionMarginType · required — The margin type of the position Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). - `result[].isolated_balance` · lite `ib` · string · optional — [IsolatedOnly] The wallet balance reserved for this isolated margin position, in the quote asset. Decimal string, e.g. "12.5". If this positions is liquidated, this is the maximal balance that can be lost - `result[].isolated_im` · lite `ii` · string · optional — [IsolatedOnly] The initial margin of the isolated margin position, in the quote asset. Decimal string, e.g. "12.5". The `total_equity` required to open more size in the position - `result[].isolated_mm` · lite `im` · string · optional — [IsolatedOnly] The maintenance margin of the isolated margin position, in the quote asset. Decimal string, e.g. "12.5". The `total_equity` required to avoid liquidation of the position ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `3007` NotApplicableForSpotInstrument (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.positions( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/positions" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/position_history`, or `/lite/v1/position_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/position_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `position.position_history` (`RPCPositionHistoryV1`) | ## Request Body type `ApiPositionHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to request for - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — Start of the close-time range in unix nanoseconds. If nil, defaults to no lower bound. Only positions with close_time >= start_time are returned. Does not apply to partially closed positions (they have no close time and will be excluded when this field is set) - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — End of the close-time range in unix nanoseconds. If nil, defaults to now. Only positions with close_time \<= end_time are returned. Does not apply to partially closed positions (they have no close time and will be excluded when this field is set) - `kind` · lite `k` · enum Kind[] · optional, default `all` — The kind filter to apply. If nil, this defaults to all kinds. Otherwise, only positions 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 positions 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 positions matching the filter will be returned - `limit` · lite `l` · integer (uint32) · optional, default `500` — The limit to query for. Defaults to 500; Max 1000. Applies to fully closed positions only; limit excludes any matching partially-closed positions - `cursor` · lite `c` · string · optional — The cursor to indicate when to start the next page query from. Partially closed positions are only returned on the initial page (when cursor is unset) - `status` · lite `s` · enum PositionCloseStatus[] · optional, default `all` — The status filter to apply. If nil, this defaults to all statuses. Otherwise, only positions matching the filter will be returned Values: `CLOSED`, `LIQUIDATED`, `SETTLED`, `PARTIALLY_CLOSED`, `SPLIT_CLOSED` ([details](/reference/enums.md#positionclosestatus)). - `is_long` · lite `il` · bool · optional, default `false` — Set to true to filter for long positions. If both is_long and is_short are false (default), positions of both directions are returned - `is_short` · lite `is` · bool · optional, default `false` — Set to true to filter for short positions. If both is_long and is_short are false (default), positions of both directions are returned - `margin_type` · lite `mt` · enum PositionMarginType[] · optional, default `all` — The margin type filter to apply. If nil, this defaults to all margin types. Otherwise, only positions matching the filter will be returned Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). ## Response Body type `ApiPositionHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object ApiPositionHistory[] · required — Position lifecycle records matching the request filters. Partially closed positions appear first (most recently opened first), followed by fully closed positions (most recently closed first) - `result[].sub_account_id` · lite `sa` · string (uint64) · required — Sub-account ID which held this position - `result[].instrument` · lite `i` · string (instrument name) · required — Asset this position was for - `result[].open_time` · lite `ot` · string (int64 unix ns) · required — Timestamp of first trade that opened this lifecycle - `result[].status` · lite `s` · enum PositionCloseStatus · required Values: `CLOSED`, `LIQUIDATED`, `SETTLED`, `PARTIALLY_CLOSED`, `SPLIT_CLOSED` ([details](/reference/enums.md#positionclosestatus)). - `result[].is_long` · lite `il` · bool · required — True if the closed position was long - `result[].margin_type` · lite `mt` · enum PositionMarginType · required Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). - `result[].close_time` · lite `ct` · string (int64 unix ns) · optional — Timestamp when the position lifecycle ended. Omitted when status is `PARTIALLY_CLOSED` - `result[].entry_price` · lite `ep` · string · required — Average entry price at 9 decimals - `result[].exit_price` · lite `ep1` · string · required — Average exit price at 9 decimals - `result[].position_close_mark_price` · lite `pc` · string · optional — Mark price at close. Omitted when status is `PARTIALLY_CLOSED` - `result[].realized_pnl` · lite `rp` · string · required — Cumulative realized PnL in quote currency - `result[].cumulative_fee` · lite `cf` · string · required — Cumulative fees in quote currency - `result[].cumulative_realized_funding_payment` · lite `cr` · string · required — Cumulative realized funding payment in quote currency - `result[].closed_volume_base` · lite `cv` · string · required — Sum of abs(reducingTradeSize) across all reducing trades - `result[].closed_volume_quote` · lite `cv1` · string · required — Sum of abs(reducingTradeSize) * tradePrice across all reducing trades - `result[].max_open_interest_base` · lite `mo` · string · required — Max absolute position size reached during lifecycle - `result[].max_open_interest_quote` · lite `mo1` · string · required — Max abs(size) * entryVWAP reached during lifecycle - `result[].cumulative_initial_margin` · lite `ci` · string · required — Sum of markPrice * abs(tradeSize) / leverage for position-increasing trades - `result[].max_initial_margin` · lite `mi` · string · required — High-water mark of cumulativeInitialMargin during lifecycle - `result[].leverage` · lite `l` · string · required — Leverage at time of close. When status is `PARTIALLY_CLOSED`, this is the current leverage - `result[].unrealized_pnl` · lite `up` · string · optional — The unrealized PnL of the position, in the quote asset. Decimal string, e.g. "12.5". `unrealized_pnl = (mark_price - entry_price) * size` where `size` is signed (negative for short positions) Only present when status is `PARTIALLY_CLOSED` - `result[].split_ratio_from` · lite `sr` · integer (int32) · optional — Stock split 'from' ratio (pre-split units); the position size scaled by to/from Only present when status is `SPLIT_CLOSED`. Example: `1` for a 1:4 split - `result[].split_ratio_to` · lite `sr1` · integer (int32) · optional — Stock split 'to' ratio (post-split units) Only present when status is `SPLIT_CLOSED`. Example: `4` for a 1:4 split - `result[].split_remaining_size` · lite `sr2` · string · optional — Signed position size. Decimal string, e.g. "0.01"; up to the instrument's base_decimals. immediately before the split Only present when status is `SPLIT_CLOSED` - `next` · lite `n` · string · required — The cursor to indicate when to start the 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `3007` NotApplicableForSpotInstrument (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.position_history( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/position_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- < 0), including USDT, which is always enabled and cannot be toggled off. | | | |---|---| | SDK | `client.get_collateral_preference(...)` | | HTTP | `POST https://trades./full/v1/get_collateral_preference`, or `/lite/v1/get_collateral_preference` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_collateral_preference` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `sub_account.get_collateral_preference` (`RPCGetCollateralPreferenceV1`) | ## Request Body type `ApiGetSubAccountCollateralPreferenceRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to fetch collateral preferences for ## Response Body type `ApiGetSubAccountCollateralPreferenceResponse` (the same object is the JSON-RPC `result` over WebSocket). - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID the preferences apply to - `preferences` · lite `p` · object ApiCollateralPreferenceStatus[] · required — One entry per collateral-eligible currency (CVR configured), with its current effective state. - `preferences[].currency` · lite `c` · string · required — The currency whose collateral state is being reported - `preferences[].enabled` · lite `e` · bool · required — Whether this currency currently counts as collateral for the sub-account - `preferences[].locked` · lite `l` · bool · required — The sub-account cannot turn this currency off as collateral ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_collateral_preference( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/get_collateral_preference" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/set_position_config`, or `/lite/v1/set_position_config` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/set_position_config` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`SetSubAccountPositionMarginConfig`](/reference/signing/SetSubAccountPositionMarginConfig.md). always SetSubAccountPositionMarginConfig. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `position.set_position_config` (`RPCSetPositionConfigV1`) | ## Request Body type `ApiSetSubAccountPositionMarginConfigRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to set the margin type and leverage for - `instrument` · lite `i` · string (instrument name) · required — The instrument of the position to set the margin type and leverage for - `margin_type` · lite `mt` · enum PositionMarginType · required — The margin type to set for the position Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). - `leverage` · lite `l` · string · required — The leverage to set for the position - `signature` · lite `s` · object Signature · required — The signature of this operation Fields: see [Signature](/reference/types.md#signature); listed in full under `order.signature` on reference/rpc/create_order.md, earlier in this file. ## Response Body type `ApiSetSubAccountPositionMarginConfigResponse` (the same object is the JSON-RPC `result` over WebSocket). - `ack` · lite `a` · bool · required — Whether the margin type and leverage was acked ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `2100` InvalidInitialLeverage (400) · `2101` VaultsCannotConfigureLeverage (400) · `2102` MarginTypeChangeFailedHasOpenPosition (400) · `2103` MarginTypeChangeFailedHasOpenOrders (400) · `2104` MarginTypeNotSupported (400) · `2105` MarginTypeChangeFailed (400) · `2107` NewLeverageBelowMinimum (400) · `2108` NewLeverageAboveMaximum (400) · `3007` NotApplicableForSpotInstrument (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, enums as e, PrivateKeySigner with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: resp = client.set_position_config( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], instrument="BTC_USDT_Perp", margin_type=e.PositionMarginType("ISOLATED"), leverage=Decimal("10"), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): The body below is the `set_position_config` signing case: a real signature by the public test key for chain id 326. Build your own with the [Signing guide](/guides/signing.md); the server will reject this one (unknown account). `signature.expiration` is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires). With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/set_position_config" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/get_all_initial_leverage`, or `/lite/v1/get_all_initial_leverage` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_all_initial_leverage` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `initial_leverage.get_all_initial_leverage` (`RPCGetAllInitialLeverageV1`) | ## Request Body type `ApiGetAllInitialLeverageRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to get the leverage for ## Response Body type `ApiGetAllInitialLeverageResponse` (the same object is the JSON-RPC `result` over WebSocket). - `results` · lite `r` · object InitialLeverageResult[] · required — The initial leverage of the sub-account - `results[].instrument` · lite `i` · string (instrument name) · required — The instrument to get the leverage for - `results[].leverage` · lite `l` · string · required — The initial leverage of this instrument - `results[].min_leverage` · lite `ml` · string · required — The min leverage user can set for this instrument - `results[].max_leverage` · lite `ml1` · string · required — The max leverage user can set for this instrument - `results[].margin_type` · lite `mt` · enum PositionMarginType · required — The margin type of this instrument Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_all_initial_leverage( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/get_all_initial_leverage" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/get_position_margin_limits`, or `/lite/v1/get_position_margin_limits` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_position_margin_limits` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `position.get_position_margin_limits` (`RPCGetPositionMarginLimitsV1`) | ## Request Body type `ApiGetIsolatedPositionMarginLimitsRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to get the margin limits for - `instrument` · lite `i` · string (instrument name) · required — The isolated position asset to get the margin limits for ## Response Body type `ApiGetIsolatedPositionMarginLimitsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `instrument` · lite `i` · string (instrument name) · required — The isolated position asset - `max_addable_amount` · lite `ma` · string · required — The max addable amount that can be added to the isolated position, in the quote asset. Decimal string, e.g. "12.5". - `max_removable_amount` · lite `mr` · string · required — The max removable amount that can be removed from the isolated position, in the quote asset. Decimal string, e.g. "12.5". ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `3007` NotApplicableForSpotInstrument (400) · `7455` NotIsolatedMarginPosition (400) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_position_margin_limits( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], instrument="BTC_USDT_Perp", ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/get_position_margin_limits" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/add_position_margin`, or `/lite/v1/add_position_margin` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/add_position_margin` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`AddIsolatedPositionMargin`](/reference/signing/AddIsolatedPositionMargin.md). always AddIsolatedPositionMargin. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `position.add_position_margin` (`RPCAddPositionMarginV1`) | ## Request Body type `ApiAddIsolatedPositionMarginRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to add isolated margin in or remove margin from - `instrument` · lite `i` · string (instrument name) · required — The instrument to add margin into, or remove margin from - `amount` · lite `a` · string · required — The amount of margin to add to the position, positive to add, negative to remove, in the quote asset. Decimal string, e.g. "12.5". Scaled to an integer only inside the signature. - `signature` · lite `s` · object Signature · required — The signature of this operation Fields: see [Signature](/reference/types.md#signature); listed in full under `order.signature` on reference/rpc/create_order.md, earlier in this file. ## Response Body type `ApiAddIsolatedPositionMarginResponse` (the same object is the JSON-RPC `result` over WebSocket). - `success` · lite `s` · bool · required — Whether the margin mode and leverage was set successfully ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `3007` NotApplicableForSpotInstrument (400) · `7450` AddMarginFailed (400) · `7451` AddMarginToEmptyPosition (400) · `7452` AddMarginToNonIsolatedPosition (400) · `7453` MaxAddableAmountExceeded (400) · `7454` MaxRemovableAmountExceeded (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, PrivateKeySigner with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: resp = client.add_position_margin( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], instrument="BTC_USDT_Perp", amount=Decimal("250.5"), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): The body below is the `add_position_margin` signing case: a real signature by the public test key for chain id 326. Build your own with the [Signing guide](/guides/signing.md); the server will reject this one (unknown account). `signature.expiration` is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires). With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/add_position_margin" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/set_derisk_mm_ratio`, or `/lite/v1/set_derisk_mm_ratio` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/set_derisk_mm_ratio` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`SetDeriskToMaintenanceMarginRatio`](/reference/signing/SetDeriskToMaintenanceMarginRatio.md). always SetDeriskToMaintenanceMarginRatio. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `derisk_mm_ratio.set_derisk_mm_ratio` (`RPCSetDeriskMMRatioV1`) | ## Request Body type `ApiSetDeriskToMaintenanceMarginRatioRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to set the leverage for - `ratio` · lite `r` · string · required — The derisk margin to maintenance margin ratio of this sub-account - `signature` · lite `s` · object Signature · required — The signature of this operation Fields: see [Signature](/reference/types.md#signature); listed in full under `order.signature` on reference/rpc/create_order.md, earlier in this file. ## Response Body type `ApiSetDeriskToMaintenanceMarginRatioResponse` (the same object is the JSON-RPC `result` over WebSocket). - `success` · lite `s` · bool · required — Whether the derisk margin to maintenance margin ratio was set successfully ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `6100` DeriskMMRatioOutOfRange (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt, PrivateKeySigner with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: resp = client.set_derisk_mm_ratio( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], ratio=Decimal("1.5"), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): The body below is the `set_derisk_mm_ratio` signing case: a real signature by the public test key for chain id 326. Build your own with the [Signing guide](/guides/signing.md); the server will reject this one (unknown account). `signature.expiration` is unix nanoseconds: use now + 1 day (the signing case uses 2100-01-01 so it never expires). With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/set_derisk_mm_ratio" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/set_initial_leverage`, or `/lite/v1/set_initial_leverage` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/set_initial_leverage` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `initial_leverage.set_initial_leverage` (`RPCSetInitialLeverageV1`) | ## Request Body type `ApiSetInitialLeverageRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to set the leverage for - `instrument` · lite `i` · string (instrument name) · required — The instrument to set the leverage for - `leverage` · lite `l` · string · required — The leverage to set for the sub-account ## Response Body type `ApiSetInitialLeverageResponse` (the same object is the JSON-RPC `result` over WebSocket). - `success` · lite `s` · bool · required — Whether the leverage was set successfully ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1004` NotFound (404) · `1006` RateLimit (429, retryable) · `2100` InvalidInitialLeverage (400) · `2101` VaultsCannotConfigureLeverage (400) · `3007` NotApplicableForSpotInstrument (400) ## Example ```python import os from decimal import Decimal from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.set_initial_leverage( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], instrument="BTC_USDT_Perp", leverage=Decimal("10"), ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/set_initial_leverage" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </ws/full`, or `/ws/lite` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | Selector | `[-]` | | Auth | Session required on the WebSocket upgrade ([Authentication](/guides/authentication.md)) | | 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 ([`positions`](/reference/rpc/positions.md)) for what you missed. | | Contract id | `execution.positions` (`StreamPositionsV1`) | ## Selector Grammar `[-]`, e.g. `-BTC_USDT_Perp`. Parts: - `sub_account_id` · uint64 — The sub-account ID to filter by - `instrument` · asset, optional — The instrument filter to apply. ## Frame Type `WSPositionsFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.position`. - `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 Positions · required — A Position being created or updated matching the request filter Fields: see [Positions](/reference/types.md#positions); listed in full under `result[]` on reference/rpc/positions.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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (400) · `3000` InvalidInstrument (400) · `3007` NotApplicableForSpotInstrument (400) · `3020` InvalidSubAccountID (400) ## Example ```python import asyncio import os from grvt import AsyncGrvt async def main(): async with AsyncGrvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: async with client.positions_stream(instrument="BTC_USDT_Perp", sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"]) as sub: async for frame in sub: print(frame.sequence_number, frame.feed) asyncio.run(main()) ``` Raw WebSocket: connect to `wss://trades.$GRVT_DOMAIN/ws/full` (`/ws/lite` for lite names) with the `Cookie: gravity=...` and `X-Grvt-Account-Id` headers and send: With full field names: ```json { "jsonrpc": "2.0", "method": "subscribe", "params": { "stream": "v1.position", "selectors": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.position", "s1": ["$GRVT_SUB_ACCOUNT_ID-BTC_USDT_Perp"], "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/get_authorized_builders.md # Get authorized builders | | | |---|---| | SDK | `client.get_authorized_builders(...)` | | HTTP | `POST https://trades./full/v1/get_authorized_builders`, or `/lite/v1/get_authorized_builders` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_authorized_builders` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `builder.get_authorized_builders` (`RPCGetAuthorizedBuildersV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiGetAuthorizedBuildersResponse` (the same object is the JSON-RPC `result` over WebSocket). - `results` · lite `r` · object ApiAuthorizedBuilder[] · required — The list of authorized builders - `results[].builder_account_id` · lite `ba` · string (0x address) · required — The main account ID of the builder - `results[].max_futures_fee_rate` · lite `mf` · string · required — The maximum fee rate for the authorized builder - `results[].max_spot_fee_rate` · lite `ms` · string · required — The maximum fee rate for the authorized builder ## 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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.get_authorized_builders() print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/get_authorized_builders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` With lite field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/lite/v1/get_authorized_builders" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` ===== reference/rpc/builder_fill_history.md # Builder fill history > Only for builders. Other accounts get an empty list. The history is returned in reverse chronological order 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.builder_fill_history(...)` | | HTTP | `POST https://trades./full/v1/builder_fill_history`, or `/lite/v1/builder_fill_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/builder_fill_history` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Retries | Read: the SDKs retry retryable errors ([rules](/guides/errors-and-retries.md)) | | Contract id | `execution.builder_fill_history` (`RPCBuilderFillHistoryV1`) | ## Request Body type `ApiBuilderFillHistoryRequest`. Fields the server fills are left out. - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — The start time to query for in unix nanoseconds - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — The end time to query for 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 next query from ## Response Body type `ApiBuilderFillHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object BuilderFillHistory[] · required — The builder fill history matching the request builder account - `result[].event_time` · lite `et` · string (int64 unix ns) · required — Time at which the event was emitted in unix nanoseconds - `result[].off_chain_account_id` · lite `oc` · string · required — The off chain account id - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument being represented - `result[].is_buyer` · lite `ib` · bool · required — The side that the sub-account took on the trade - `result[].is_taker` · lite `it` · bool · required — The role that the sub-account took 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 · required — 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[].fee_rate` · lite `fr` · string · required — Builder fee percentage charged for this order. referred to Order.builder builderFee - `result[].fee` · lite `f` · string (int64) · required — The builder fee paid on the trade, in the quote asset. Decimal string, e.g. "12.5". referred to Trade.builderFee - `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)): `1000` Unauthorized (401) · `1001` Forbidden (403) · `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) ## Example ```python import os from grvt import Grvt with Grvt( env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"], ) as client: resp = client.builder_fill_history( limit=500, ) print(resp) ``` Raw HTTP (set `GRVT_DOMAIN`, see [Environments](/guides/environments.md); `GRVT_COOKIE` and `GRVT_ACCOUNT_ID` come from [login](/guides/authentication.md)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/builder_fill_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- <