# Grvt API — account: login, accounts and sub-accounts, transfers, withdrawals, vaults, the error code table 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/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/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) ``` ===== sdks/python.md # Python SDK > [!WARNING] > **Preview.** Any 0.x release can change the API, so pin the exact version you install ([Install](/sdks/python.md#install)). The Python SDK has a method for every call and stream in the [API reference](/reference/index.md). It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). New here? [Install](/sdks/python.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/python.md#track-and-cancel-an-order). Later sections are for when you need them. ## Install The package is `grvt` on PyPI. It needs Python 3.11 or newer. ```sh pip install grvt ``` Preview: any 0.x release can change the API, so pin the exact version you install (for example in requirements.txt). ## Create a client `AsyncGrvt` is the client for asyncio code. Every example on this page uses it. ```python import asyncio import os from grvt import AsyncGrvt, PrivateKeySigner async def main(): # The API key logs in; the signer signs orders with your signing key. Leave both out for public data only. async with AsyncGrvt( env="testnet", api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: t = await client.ticker(instrument="BTC_USDT_Perp") print(t.result.mark_price) # the exchange's fair price, used for margin asyncio.run(main()) ``` `Grvt` is the blocking version, for scripts and notebooks. It takes the same arguments and has the same methods, without `await`: ```python from grvt import Grvt with Grvt(env="testnet") as client: print(client.ticker(instrument="BTC_USDT_Perp").result.mark_price) ``` `Grvt` runs its own event loop on a background thread, so it also works in Jupyter. Each call blocks the cell until it returns. To run calls side by side in a notebook, use `AsyncGrvt` with top-level `await`. - `env` is `"testnet"`, or `"prod"` for production ([Environments](/guides/environments.md)). - The client sends short (lite) field names on the wire by default; your code still uses the full names. `encoding="full"` switches to full names ([Encoding](/guides/environments.md#encoding-full-or-lite)). - The client logs in on the first private call and renews the session before it expires ([Authentication](/guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream gets a gap ([Session renewal](/guides/websocket.md#session-renewal)). - To stop, follow [Shut down cleanly](/guides/websocket.md#shut-down-cleanly). - Client settings are keyword arguments, typed by `ClientOptions`, so a type checker catches unknown names. - `transport=` takes your own `HttpTransport` for HTTP calls. WebSockets always use aiohttp. - A custom `Environment` with `encoding="lite"` uses `md_ws_url` / `td_ws_url` with the ending `/ws/full` swapped for `/ws/lite`. Set `md_ws_lite_url` / `td_ws_lite_url` only when its URLs don't end in `/ws/full`. ## Call an RPC Every call is a method on the client, `client.(...)`, named exactly as on its reference page. Pass the request fields as keyword arguments; you get back a typed model. ```python inst = await client.get_instrument(instrument="BTC_USDT_Perp") print(inst.result.tick_size, inst.result.min_size) ``` - Reads are tried up to 3 times; writes are sent once ([What the SDK retries](/guides/errors-and-retries.md#what-the-sdk-retries)). - Timeouts, as client options in seconds: `call_timeout` (30 s), `http_attempt_timeout` (10 s), `ws_request_timeout` (5 s), `resync_timeout` (5 s), `idle_timeout` (30 s). `call_timeout` limits the whole call: login, instrument lookup, signing, retries and the response. `http_attempt_timeout` caps each HTTP attempt within what's left. - For one call, pass `options=CallOptions(timeout=...)`. It replaces `call_timeout` for that call; the blocking client takes it too. ```python from grvt import CallOptions inst = await client.get_instrument(instrument="BTC_USDT_Perp", options=CallOptions(timeout=2.0)) ``` ## Pagination `pages` follows the `next` cursor of a history call, one page at a time, and never fetches ahead. Your callback gets the cursor; keep its other filters fixed. With `Grvt`, use `pages_sync`. ```python from grvt import pages async for page in pages(lambda cursor: client.trade_history(instrument="BTC_USDT_Perp", cursor=cursor)): for trade in page.result or []: print(trade) ``` - An empty page can still have a next cursor. Leaving the loop stops further calls. - A repeated cursor raises `PaginationCycle`. Fetch errors pass through, with no retries beyond the call's own. - Cursors don't give a stable snapshot while records change. ## Default sub-account Pass `sub_account_id="123"` to `AsyncGrvt` or `Grvt` to fill in the account ID wherever a request or stream leaves it out. - An ID you pass explicitly wins. - An order in `bulk_orders` takes the request's account first, then the client default. - Transfer source and destination IDs are never filled in. - The default is applied to a copy, before signing. - Without a default, calls that need an account still require one. ## Stream data Every stream method ends in `_stream`, for example `client.trade_stream(...)`. 1. Open the stream with `async with`. 2. Read frames with `async for`. 3. Leave the `async with` block to unsubscribe. ```python async with client.orderbook_delta_stream(instrument="BTC_USDT_Perp", rate=500) as book: # rate: interval in ms async for frame in book: print(frame.sequence_number, frame.feed) ``` `frame.sequence_number` is a `str`, as on the wire. Convert it with `int()` before you compare it, for example with a gap event's bounds, which are `int`. **Watch out:** - After a gap, older frames can still come first and missed private events aren't replayed ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). - Each subscription queues up to 4096 frames (client option `queue_size`, at least 1). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others raise `StreamOverflow` out of your `async for`: catch it and loop again ([stream errors](/guides/websocket.md#read-a-stream)). ## Place an order 1. Build an `OrderInput` with `Decimal` price and size. `is_buying_asset` is true to buy, false to sell. `GOOD_TILL_TIME` (GTT) rests until filled, cancelled or expired; `post_only` rejects the order rather than let it trade at once ([TimeInForce](/reference/enums.md)). 2. Call `create_order`. The SDK fills in the signature and a `client_order_id`, and looks up the instrument details it needs to sign. It works on a copy, so your `OrderInput` is not changed. 3. Save the `client_order_id`: you follow the order by it, because the reply's `order_id` is always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below). ```python import asyncio import os from decimal import Decimal from grvt import AsyncGrvt, PrivateKeySigner, enums, models as m async def main(): async with AsyncGrvt( env="testnet", api_key=os.environ["GRVT_API_KEY"], signer=PrivateKeySigner(os.environ["GRVT_PRIVATE_KEY"]), ) as client: order = m.OrderInput( sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], time_in_force=enums.TimeInForce.GOOD_TILL_TIME, post_only=True, legs=[ m.OrderLeg( instrument="BTC_USDT_Perp", size=Decimal("0.01"), limit_price=Decimal("60000"), is_buying_asset=True ) ], ) resp = await client.create_order(order=order) print(resp.result.metadata.client_order_id) asyncio.run(main()) ``` To choose the `client_order_id` yourself, set it before you send the order, following the [client order ID rules](/guides/signing.md#rules-that-cause-most-rejections): ```python import secrets order.metadata = m.OrderMetadataInput(client_order_id=str(2**63 | secrets.randbits(63))) ``` `bulk_orders` signs each order on its own, with its own nonce and expiration, by the same rules as `create_order`. Both fill in a missing `client_order_id` on each order. Bulk calls and their models use `order_ids` and `client_order_ids`; the SDK sends them as the server's `order_i_ds` and `client_order_i_ds` JSON keys. Orders go over HTTP by default. Pass `order_transport="ws"` to the client to send them over the trading WebSocket instead. **Watch out:** - A reply means the exchange received the order, not that it rests on the book ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). - An order still open 24 hours after signing expires ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Sending the same `OrderInput` again places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits raises `OrderOutOfBounds` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). `check_orders=False` on the client turns the check off and leaves the limits to the exchange. ## Sign with a wallet or KMS `PrivateKeySigner` signs in your process. To sign with a hardware wallet or a key service (KMS) instead, pass your own object as `signer=`. It needs: - an `address` property: the signing wallet's address; - an async `sign_typed(domain, primary_type, message)` method that returns a `grvt.Signature` (`signer`, `r`, `s`, `v`). If your backend wants EIP-712 typed data, `primary_type.to_typed_data(domain, message)` builds it. The SDK checks every returned signature against its own digest, and raises `SigningError` unless: - `r` and `s` are 32 bytes of hex and `v` is 27 or 28; - `s` is low-s ([Signing, step 5](/guides/signing.md#the-steps)). Some KMS backends, AWS KMS for one, return a high `s`: replace it with n - s (n is the secp256k1 curve order) and flip `v` between 27 and 28; - the signature recovers to `address`; - the `signer` field is empty or equal to `address`. The SDK signs Grvt's own message types only; there is no API for custom EIP-712 types. ## Track and cancel an order Private streams need a client with an API key. `order_stream` sends every change to your orders, rejections included; `fill_stream` sends each fill, with its trade ID and client order ID. 1. Open `order_stream` before you place the order. 2. Match updates by `metadata.client_order_id`. The updates also carry the `order_id`. 3. Stop at a final status: `enums.OrderStatus.FILLED`, `REJECTED` or `CANCELLED` ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `cancel_order` with `sub_account_id` and `client_order_id` (or `order_id`), after the create has replied. ```python from grvt import enums sub = os.environ["GRVT_SUB_ACCOUNT_ID"] FINAL = {enums.OrderStatus.FILLED, enums.OrderStatus.REJECTED, enums.OrderStatus.CANCELLED} async with client.order_stream(sub_account_id=sub) as orders: resp = await client.create_order(order=order) coid = resp.result.metadata.client_order_id await client.cancel_order(sub_account_id=sub, client_order_id=coid) async for frame in orders: o = frame.feed if o.metadata.client_order_id == coid and o.state and o.state.status in FINAL: print(o.order_id, o.state.status, o.state.reject_reason) break ``` ## Recover a lost order response **When:** a write times out or the socket drops before the response arrives. The call raises `OrderStateUnknown`. Look the order up with `resolve_order`; don't resend it. Steps and code: [When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are imports from `grvt`, not client methods. Blocking versions end in `_sync`. ```python from grvt import OrderBook, backfill_pages, refresh_cancel_countdown, resolve_order ``` | Helper | What it does | |---|---| | `resolve_order(client, sub_account_id=..., client_order_id=...)` | Looks up an order whose write outcome is unknown. It never resends. | | `OrderBook(instrument)` | Keeps a local book from order-book stream frames. | | `backfill_pages(fetch, gap=...)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `refresh_cancel_countdown(client, sub_account_id=..., countdown_seconds=...)` | Arms or refreshes the [cancel-on-disconnect countdown](/guides/websocket.md#cancel-orders-if-your-app-stops) once (1 to 300 seconds). The SDK never does this for you. | Your `on_event` hook gets the `gap` and `session_rotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#sdk-helpers). ## Errors | Exception | When | |---|---| | `ApiError` | the server answered with an error code; has `code`, `message`, `status`, `rpc`, `retryable` | | `RateLimitError` | code `1006` (HTTP 429); a subclass of `ApiError`; reads were already retried | | `TransportError` | no usable answer (connection failed, read timed out, socket closed); has `rpc`, and `sent` (whether the request may have left). A write that may have left raises `OrderStateUnknown` instead | | `OrderStateUnknown` | a write may or may not have happened; look it up by `client_order_id` (`client_order_ids` for a bulk call). The original failure is its `__cause__` | | `OrderOutOfBounds` | an order breaks its instrument's limits; nothing was sent; has `nearest` and `server_code` | | `StreamOverflow` (`stream`, `selector`, `capacity`) | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced | | `FrameTooLarge` (`size`, `limit`) | a WebSocket request is bigger than `Environment.ws_max_frame_bytes`; nothing was sent. The check is off unless you set that limit | | `DecodeError` | a response or stream frame did not match its type; the original error is its `__cause__` | | `SigningError`, `ConfigError`, `ClosedError` | local problems: a request that can't be signed, a bad option or a missing signer or API key, a closed client. `SigningError` and `ConfigError` are also `ValueError` | All of them extend `GrvtError`. A wrong argument type still raises `TypeError`. Every error code also has its own class in `grvt.api_errors`. The full list is on [Error codes](/reference/errors.md). ## Hooks and logging - `GRVT_LOG=debug` prints every request and frame to stderr, with keys and signatures redacted. - `before_send=` runs before each RPC is signed and may change the request. It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an [unknown outcome](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config error before anything is sent. - `on_event=` gets connection and stream events: connect, reconnect, gap, retry and more. Each event's details are attributes (`ev.code`, `ev.attempt`, `ev.error`, ...), set for its kind and `None` otherwise. `frame` events carry the raw bytes sent and received, **not redacted**. ```python def on_event(ev): if ev.kind.value == "gap": print("re-syncing", ev.stream, ev.selector) client = AsyncGrvt(env="testnet", on_event=on_event) ``` ## Data types - Decimals use `decimal.Decimal`. - Nanosecond timestamps use `grvt.Timestamp`. `to_datetime()` gives a UTC `datetime`, cut to the microsecond. `Timestamp.from_datetime()` needs a `datetime` with a timezone. - IDs in models are strings. Top-level ID arguments accept `int | str`. - Constructors and decoding reject a missing required field. Optional fields default to `None`. Some list fields can be `None` instead of empty: check before you iterate. - Signed requests use `Input` models, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield `Partial` models: every feed field is optional. - Enums are generated string enums. A value added by a newer server decodes as an extra member, so give your `match` a default case. - Millisecond schedule fields stay plain integers. - Response fields the SDK doesn't know are dropped. ## Not supported yet - **Resuming a private stream from a sequence number.** After a gap, fill missed events from history with `backfill_pages` ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). - **Logging in again after a WebSocket auth failure.** A subscribe rejected for auth raises to your code. A rejected handshake (401/403) or a failed API-key login stops the socket reconnecting for good. - **Keeping streams open across session renewal.** Renewal reconnects every socket, so every stream gets a gap ([Session renewal](/guides/websocket.md#session-renewal)). - **Ordered requests on one WebSocket.** The server can process a cancel before its create; wait for the create's reply ([Calling RPCs over WebSocket](/guides/websocket.md#calling-rpcs-over-websocket)). - **Wallet login.** The client manages API-key sessions only. - **Keeping response fields the SDK doesn't know.** A field the server adds after your SDK version is dropped when the reply is decoded. Update the SDK to read it. ===== sdks/typescript.md # TypeScript SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. [Install](/sdks/typescript.md#install) says what to pin. The TypeScript SDK has a method for every call and stream in the [API reference](/reference/index.md). It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). It runs on Node.js 24+ and in modern browsers. New here? [Install](/sdks/typescript.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/typescript.md#track-and-cancel-an-order). Later sections are for when you need them. ## Install Not on the npm registry yet. Install it from its public GitHub repository; npm builds it during the install. It needs Node.js 24 or newer. ```sh npm install github:gravity-technologies/grvt-sdk-typescript ``` Then import it as `grvt`. The repository has no version tags yet and its `main` branch moves, so pin the commit you tested: `npm install github:gravity-technologies/grvt-sdk-typescript#` (your `package-lock.json` also records the exact commit). With other package managers, pin the commit too: - **yarn 1** installs and builds it. - **pnpm** (tested with pnpm 12) stops with `ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`, because the package builds itself on install. Allow that build in your project's `pnpm-workspace.yaml`, keyed by the package's exact Git address and commit; a wildcard such as `grvt@*` is not accepted: ```yaml allowBuilds: "grvt@#": true ``` - **bun** hasn't been tested. ## Create a client ```ts import { Grvt, PrivateKeySigner } from "grvt"; // The API key logs in; the signer signs orders with your signing key. Leave both out for public data only. const client = new Grvt({ env: "testnet", apiKey: process.env.GRVT_API_KEY, signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!), }); const t = await client.ticker({ instrument: "BTC_USDT_Perp" }); console.log(t.result.mark_price); // the exchange's fair price, used for margin await client.close(); ``` - `env` is `"testnet"`, or `"prod"` for production ([Environments](/guides/environments.md)). - The client sends short (lite) field names on the wire by default; your code still uses the full names. `encoding: "full"` switches to full names ([Encoding](/guides/environments.md#encoding-full-or-lite)). - The client logs in on the first private call and renews the session before it expires ([Authentication](/guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream gets a gap ([Session renewal](/guides/websocket.md#session-renewal)). - To stop, follow [Shut down cleanly](/guides/websocket.md#shut-down-cleanly). **Watch out:** in the browser, only public calls and streams work. Anything that needs a session (private calls and streams, orders) is Node-only for now: browsers don't let code read the login cookie or send it on a WebSocket. ## Call an RPC Every call is a method on the client, `client.(request)`. Method names are the reference page's name in camelCase, with no exceptions: `create_order` is `client.createOrder`, `trade_stream` is `client.tradeStream`. Request and response fields stay snake_case, exactly as on the reference pages (for example `mark_price`), because they are the JSON sent and received. ```ts const inst = await client.getInstrument({ instrument: "BTC_USDT_Perp" }); console.log(inst.result.tick_size, inst.result.min_size); ``` - Reads are tried up to 3 times; writes are sent once ([What the SDK retries](/guides/errors-and-retries.md#what-the-sdk-retries)). - Timeouts, as client options in milliseconds: `callTimeoutMs` (30000), `httpAttemptTimeoutMs` (10000), `wsRequestTimeoutMs` (5000), `resyncTimeoutMs` (5000), `idleTimeoutMs` (30000). `callTimeoutMs` covers the whole call: login, instrument lookup, signing, retries and the reply. `httpAttemptTimeoutMs` caps each HTTP attempt within what is left of it. For one call, pass `{ timeoutMs }` as the second argument; an earlier abort `signal` there still wins. ## Pagination History calls return one page and a `next` cursor. `pages` follows the cursors, fetching the next page only when your loop asks for it. Put the filters and call options in the callback. ```ts import { pages } from "grvt"; for await (const page of pages((cursor) => client.tradeHistory({ instrument: "BTC_USDT_Perp", cursor }))) { for (const trade of page.result ?? []) console.log(trade); } ``` - An empty page can still have a next cursor. Breaking out of the loop stops further calls. - A repeated cursor throws `PaginationCycle`. Fetch errors pass through, with no extra retries. - Cursors are not a stable snapshot: records can change while you page. ## Default sub-account Pass `subAccountId: "123"` to `new Grvt` to fill in `sub_account_id` wherever a request or stream leaves it out. - An ID you pass explicitly wins. - An order in `bulkOrders` takes the request's account first, then the client default. - Transfer source and destination IDs are never filled in. - The default is applied to a copy, before signing. - Without a default, calls that need an account still require one. ## Stream data Every stream method ends in `Stream`, for example `client.tradeStream`. 1. Call the stream method to get a subscription. 2. Read frames with `for await`. 3. Break out of the loop or call `close()` to unsubscribe. ```ts // rate: update interval in ms for await (const frame of client.orderbookDeltaStream({ instrument: "BTC_USDT_Perp", rate: 500 })) { console.log(frame.sequence_number, frame.feed); } ``` `frame.sequence_number` is a `string`, as on the wire, and so are a gap event's bounds. Compare them as `BigInt(...)`, not as strings. **Watch out:** - After a gap, older frames can still come first and missed private events aren't replayed ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). - Each subscription queues up to 4096 frames (client option `queueSize`, at least 1). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others throw `StreamOverflow` out of your `for await`: catch it and loop again ([stream errors](/guides/websocket.md#read-a-stream)). ## Place an order 1. Build a `models.OrderInput` with `Decimal` price and size. `is_buying_asset` is true to buy, false to sell. `GOOD_TILL_TIME` (GTT) rests until filled, cancelled or expired; `post_only` rejects the order rather than let it trade at once ([TimeInForce](/reference/enums.md)). 2. Call `createOrder`. The SDK fills in the signature and a `client_order_id`, and looks up the instrument details it needs to sign. It works on a copy, so your `order` object is not changed. 3. Save the `client_order_id`: you follow the order by it, because the reply's `order_id` is always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below). ```ts import { Decimal, Grvt, PrivateKeySigner, type models } from "grvt"; const client = new Grvt({ env: "testnet", apiKey: process.env.GRVT_API_KEY, signer: new PrivateKeySigner(process.env.GRVT_PRIVATE_KEY!), }); const order: models.OrderInput = { sub_account_id: process.env.GRVT_SUB_ACCOUNT_ID!, time_in_force: "GOOD_TILL_TIME", post_only: true, legs: [{ instrument: "BTC_USDT_Perp", size: new Decimal("0.01"), limit_price: new Decimal("60000"), is_buying_asset: true }], }; const resp = await client.createOrder({ order }); console.log(resp.result.metadata.client_order_id); await client.close(); ``` To choose the `client_order_id` yourself, set it before you send the order, following the [client order ID rules](/guides/signing.md#rules-that-cause-most-rejections): ```ts order.metadata = { client_order_id: (2n ** 63n | crypto.getRandomValues(new BigUint64Array(1))[0]!).toString() }; ``` Orders go over HTTP by default. Pass `orderTransport: "ws"` to the client to send them over the trading WebSocket instead. **Watch out:** - A reply means the exchange received the order, not that it rests on the book ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). - An order still open 24 hours after signing expires ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Sending the same `order` again places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits throws `OrderOutOfBounds` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). If the exchange still rejects an order for these limits, the SDK drops its cached instrument details and fetches them again for the next order. `checkOrders: false` on the client turns the check off. ## Sign with a wallet or KMS `PrivateKeySigner` keeps the key in your process. To sign elsewhere (a wallet, or a key management service (KMS) such as AWS KMS), pass your own `Signer`: an object with `address` (lowercase `0x` address) and `signTyped(domain, type, message)`. Inside it, `type.toTypedData(domain, message)` gives the JSON to hand to `eth_signTypedData_v4`. Return `{ signer, r, s, v }`. The SDK checks every signature it gets back and throws `SigningError` unless: - `r` and `s` are 32 bytes of `0x` hex and `v` is 27 or 28; - `s` is low-s ([Signing](/guides/signing.md#the-steps)). Some KMS backends return a high s: replace it with n - s and flip `v`; - it recovers to `signer.address`, and its `signer` field is empty or equal to it. ## Track and cancel an order Private streams need a client with an API key. `orderStream` sends every change to your orders, rejections included; `fillStream` sends each fill, with its trade ID and client order ID. 1. Open `orderStream` and `await` its `subscribe()` before you place the order. 2. Match updates by `metadata.client_order_id`. The updates also carry the `order_id`. 3. Stop at a final status: `"FILLED"`, `"REJECTED"` or `"CANCELLED"` ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `cancelOrder` with `sub_account_id` and `client_order_id` (or `order_id`), after the create has replied. ```ts const sub = process.env.GRVT_SUB_ACCOUNT_ID!; const orders = await client.orderStream({ sub_account_id: sub }).subscribe(); const resp = await client.createOrder({ order }); const id = resp.result.metadata.client_order_id; await client.cancelOrder({ sub_account_id: sub, client_order_id: id }); for await (const { feed } of orders) { const status = feed.state?.status; if (feed.metadata.client_order_id !== id) continue; if (status === "FILLED" || status === "REJECTED" || status === "CANCELLED") { console.log(feed.order_id, status, feed.state?.reject_reason); break; // leaving the loop unsubscribes } } ``` ## Recover a lost order response **When:** a write times out or the socket drops before the response arrives. The call throws `OrderStateUnknown`. Look the order up with `resolveOrder`; don't resend it. Steps and code: [When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are imports from `grvt`, not client methods. ```ts import { OrderBook, backfillPages, refreshCancelCountdown, resolveOrder } from "grvt"; ``` | Helper | What it does | |---|---| | `resolveOrder(client, { sub_account_id, client_order_id })` | Looks up an order whose write outcome is unknown. It never resends. | | `new OrderBook(instrument)` | Keeps a local book from order-book stream frames. | | `backfillPages(fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `refreshCancelCountdown(client, subAccountId, seconds)` | Arms or refreshes the [cancel-on-disconnect countdown](/guides/websocket.md#cancel-orders-if-your-app-stops) once (1 to 300 seconds). The SDK never does this for you. | Your `onEvent` hook gets the `gap` and `session_rotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#sdk-helpers). ## Errors | Class | When | |---|---| | `ApiError` | the server answered with an error code; has `code`, `serverMessage` (`message` is the full text), `status`, `rpc`, `retryable` | | `RateLimitError` | code `1006` (HTTP 429); a subclass of `ApiError`; reads were already retried | | `TransportError` | no usable answer (connection failed, read timed out, socket closed); has `rpc`, and `sent` (whether the request may have left). A write that may have left throws `OrderStateUnknown` instead | | `OrderStateUnknown` | a write may or may not have happened; look it up by `clientOrderId` (`clientOrderIds` for a bulk call). The original failure is its `cause` | | `OrderOutOfBounds` | an order breaks its instrument's limits; nothing was sent; has `nearest` and `serverCode` | | `StreamOverflow` | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced | | `SigningError`, `DecodeError`, `ConfigError`, `FrameTooLarge`, `ClosedError` | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed | All of them extend `GrvtError`. Error code constants are in `ErrorCode`. The full list is on [Error codes](/reference/errors.md). ## Hooks and logging - `GRVT_LOG=debug` logs every request and frame to stderr, with keys and signatures redacted. `setLogLevel()` changes the level at runtime. - `beforeSend` runs before each RPC is signed and may change `call.params` (or return new params). It sees the wire names: bulk order fields `order_ids` and `client_order_ids` appear as `order_i_ds` and `client_order_i_ds`. It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an [unknown outcome](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config error before anything is sent. - `onEvent` gets typed events: `connect`, `disconnect`, `reconnect`, `subscribe`, `gap`, `retry`, `frame`, `session_rotated` and `error`. Keep it fast. ```ts const client = new Grvt({ env: "testnet", onEvent: (e) => { if (e.type === "gap") console.warn("re-syncing", e.stream, e.selector); }, }); ``` ## Data types - Decimals use the SDK's `Decimal` wrapper. It checks for exact text and needs no arithmetic library. A value with more decimal places than the field allows throws `SigningError`; nothing is rounded. - Nanosecond timestamps use `Timestamp` over `bigint`. `toDate()` drops sub-millisecond precision. - IDs are strings. - Optional fields can be missing (`undefined`). Some list fields can be `null` instead of empty: check before you iterate. - Signed requests use `Input` models, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield `Partial` models: every feed field is optional. - Enum types accept any string. A value added by a newer server arrives as its plain string, so give your `switch` a `default` branch. - Millisecond schedule fields stay plain integers. ## Not supported yet - **Resuming a private stream from a sequence number.** After a gap, fill missed events from history with `backfillPages` ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). - **Private calls, private streams and orders in the browser.** Meanwhile, make them from a Node server and use the browser for public data ([Create a client](/sdks/typescript.md#create-a-client)). - **Logging in with a wallet.** The client logs in with an API key only. - **A client heartbeat.** The global `WebSocket` has no ping API. On Node 24 and later the SDK still sees the server's pings, so a connection silent for `idleTimeoutMs` is dropped and reconnected. In browsers it can't tell a quiet connection from a dead one, so a dead one is noticed only when TCP gives up. A custom `webSocket` factory that sees ping frames can call the socket's `onheartbeat` to turn the check on. - **Telling a rejected WebSocket handshake from a network error.** The global `WebSocket` hides the HTTP status, so a 401 or 403 is retried with backoff. A custom `webSocket` factory that knows the status can set `status` on the close event to stop for good. ===== sdks/go.md # Go SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. Your `go.mod` pins the version you get. The Go SDK has a method for every call and stream in the [API reference](/reference/index.md). It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). Every call takes a `context.Context`. New here? [Install](/sdks/go.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/go.md#track-and-cancel-an-order). Later sections are for when you need them. ## Install ```sh go get github.com/gravity-technologies/grvt-sdk-go ``` The SDK is in preview: any 0.x release can change the API, and your `go.mod` pins the version you get. It needs Go 1.27.4 or newer. ## Create a client ```go package main import ( "context" "fmt" "log" "os" grvt "github.com/gravity-technologies/grvt-sdk-go" "github.com/gravity-technologies/grvt-sdk-go/models" ) func main() { ctx := context.Background() // The API key logs in; the signer signs orders with your signing key. Leave both out for public data only. signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY")) if err != nil { log.Fatal(err) } client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer}) if err != nil { log.Fatal(err) } defer client.Close() t, err := client.Ticker(ctx, &models.ApiTickerRequest{Instrument: "BTC_USDT_Perp"}) if err != nil { log.Fatal(err) } fmt.Println(t.Result.MarkPrice) // the exchange's fair price, used for margin } ``` - Use `grvt.Prod()` for production ([Environments](/guides/environments.md)). - The client sends short (lite) field names on the wire by default; your code still uses the full names. `Encoding: grvt.EncodingFull` in the `Config` switches to full names ([Encoding](/guides/environments.md#encoding-full-or-lite)). On a custom `Environment`, lite WebSocket URLs are the full ones with `/ws/full` swapped for `/ws/lite`; set `MarketDataWSLite` and `TradingWSLite` only when your URLs don't end in `/ws/full`. - The client logs in on the first private call and renews the session before it expires ([Authentication](/guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream gets a gap ([Session renewal](/guides/websocket.md#session-renewal)). - To stop, follow [Shut down cleanly](/guides/websocket.md#shut-down-cleanly). ## Call an RPC Every call is a method on the client, `client.(ctx, *Request) (*Response, error)`: the name on its reference page in Go style (`create_order` is `client.CreateOrder`). Request and response types keep the contract names, and their JSON tags are the wire field names. ```go inst, err := client.GetInstrument(ctx, &models.ApiGetInstrumentRequest{Instrument: "BTC_USDT_Perp"}) if err != nil { return err } fmt.Println(inst.Result.TickSize, inst.Result.MinSize) ``` - Reads are tried up to 3 times; writes are sent once ([What the SDK retries](/guides/errors-and-retries.md#what-the-sdk-retries)). - Timeouts, in the `Config`: `CallTimeout` (30 s), `HTTPAttemptTimeout` (10 s), `WSRequestTimeout` (5 s), `ResyncTimeout` (5 s), `IdleTimeout` (30 s). A shorter deadline on the `ctx` you pass also applies. `CallTimeout` covers the whole call: login, instrument lookups, signing, retries and the reply; `HTTPAttemptTimeout` caps each HTTP try within it. - `Config.HTTPClient` replaces the default HTTP client, for REST and the WebSocket handshake. The SDK copies it and never follows redirects; a `Timeout` on it is one more cap per attempt. ## Pagination `grvt.Pages` follows a history call's cursors one page at a time, without fetching ahead. Pass an empty starting cursor for the first page, and keep the filters fixed inside your callback. ```go fetch := func(ctx context.Context, cursor string) (*models.ApiTradeHistoryResponse, error) { return client.TradeHistory(ctx, &models.ApiTradeHistoryRequest{ Instrument: "BTC_USDT_Perp", Cursor: cursor, }) } for page, err := range grvt.Pages(ctx, fetch, "") { if err != nil { return err } for _, trade := range page.Result { fmt.Println(trade) } } ``` - An empty page can still have a next cursor. - Breaking out of the loop stops further calls; the `ctx` cancels a fetch in progress. - A cursor seen twice returns `*grvt.PaginationCycleError`. Fetch errors pass through, with no extra retries. - Cursors don't give a stable snapshot while records change. ## Default sub-account Set `SubAccountID` in the `Config` to fill in the account on requests and stream selectors that leave it out. - Zero in the `Config` means no default. Zero in a request or selector means "not set"; in an `OrderInput`, `nil` means not set. - An account you set yourself always wins. - Bulk orders take the request's account first, then the client default. - Transfers never get a default: source and destination stay explicit. - Defaults are applied to a copy of your request, before signing. - Without a default, a call that needs an account fails unless the request names one. ## Stream data Every stream method ends in `Stream`, for example `client.TradeStream`. 1. Call the stream method to get a subscription. 2. Range over `All()` to read frames, or call `Next(ctx)` to stop when a context ends. 3. Call `Close()` to unsubscribe. Breaking out of the loop doesn't unsubscribe. ```go book, err := client.OrderbookDeltaStream(ctx, &models.WSOrderbookLevelsFeedSelectorV1{ Instrument: "BTC_USDT_Perp", Rate: grvt.Ptr[uint32](500)}) // Rate: update interval in ms if err != nil { return err } defer book.Close() for frame, err := range book.All() { if err != nil { log.Print(err) // the loop goes on after an error continue } fmt.Println(frame.SequenceNumber) } ``` `frame.SequenceNumber` is a `uint64`. It is a string on the wire; the SDK decodes it for you. A gap event's bounds are `*uint64`. **Watch out:** - After a gap, older frames can still come first and missed private events aren't replayed ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). - Each subscription queues up to 4096 frames (`QueueSize` in the `Config`, at least 1). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others yield `*grvt.StreamOverflowError` ([stream errors](/guides/websocket.md#read-a-stream)). ## Place an order 1. Build a `models.OrderInput` with `models.Decimal` price and size. `IsBuyingAsset` is true to buy, false to sell. `TimeInForceGoodTillTime` (GTT) rests until filled, cancelled or expired; `PostOnly` rejects the order rather than let it trade at once ([TimeInForce](/reference/enums.md)). 2. Call `CreateOrder`. The SDK fills in the signature and a `client_order_id`, and looks up the instrument details it needs to sign (once per instrument, then cached). It works on a copy, so your request struct is not changed. 3. Save the `client_order_id`: you follow the order by it, because the reply's `OrderID` is always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below). ```go package main import ( "context" "fmt" "log" "os" "strconv" grvt "github.com/gravity-technologies/grvt-sdk-go" "github.com/gravity-technologies/grvt-sdk-go/models" ) func main() { ctx := context.Background() signer, err := grvt.NewPrivateKeySigner(os.Getenv("GRVT_PRIVATE_KEY")) if err != nil { log.Fatal(err) } client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), APIKey: os.Getenv("GRVT_API_KEY"), Signer: signer}) if err != nil { log.Fatal(err) } defer client.Close() sub, err := strconv.ParseUint(os.Getenv("GRVT_SUB_ACCOUNT_ID"), 10, 64) if err != nil { log.Fatal(err) } order := models.OrderInput{ SubAccountID: &sub, TimeInForce: models.TimeInForceGoodTillTime, PostOnly: grvt.Ptr(true), Legs: []models.OrderLeg{{Instrument: "BTC_USDT_Perp", Size: models.MustParseDecimal("0.01"), LimitPrice: grvt.Ptr(models.MustParseDecimal("60000")), IsBuyingAsset: true}}, } resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) if err != nil { log.Fatal(err) } fmt.Println(resp.Result.Metadata.ClientOrderID) } ``` To choose the `client_order_id` yourself, set it before you send the order, following the [client order ID rules](/guides/signing.md#rules-that-cause-most-rejections): ```go order.Metadata = &models.OrderMetadataInput{ClientOrderID: grvt.Ptr(1<<63 | rand.Uint64())} // math/rand/v2 ``` Orders go over HTTP by default. Set `OrderTransport: grvt.OrderTransportWS` in the `Config` to send them over the trading WebSocket instead. **Watch out:** - A reply means the exchange received the order, not that it rests on the book ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). - An order still open 24 hours after signing expires ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Sending the same request struct again places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits returns `*grvt.OrderOutOfBoundsError` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). `CheckOrders: grvt.Ptr(false)` in the `Config` turns the check off and leaves the limits to the exchange. - A decimal with more digits than its signed field allows fails with `*grvt.SigningError` before anything is sent. The SDK never rounds. ## Track and cancel an order Private streams need a client with an API key. `OrderStream` sends every change to your orders, rejections included; `FillStream` sends each fill, with its trade ID and client order ID. 1. Open `OrderStream` before you place the order. 2. Match updates by `Metadata.ClientOrderID`. The updates also carry the `OrderID`. 3. Stop at a final status: `models.OrderStatusFilled`, `OrderStatusRejected` or `OrderStatusCancelled` ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `CancelOrder` with `SubAccountID` and `ClientOrderID` (or `OrderID`), after the create has replied. ```go orders, err := client.OrderStream(ctx, &models.WSOrderFeedSelectorV1{SubAccountID: sub}) if err != nil { return err } defer orders.Close() resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) if err != nil { return err } id := resp.Result.Metadata.ClientOrderID if _, err := client.CancelOrder(ctx, &models.ApiCancelOrderRequest{SubAccountID: sub, ClientOrderID: &id}); err != nil { return err } for { frame, err := orders.Next(ctx) if ctx.Err() != nil { return ctx.Err() } if errors.Is(err, grvt.ErrClosed) { return err } if err != nil || frame.Feed.Metadata.ClientOrderID != id || frame.Feed.State == nil { continue } switch s := frame.Feed.State; s.Status { case models.OrderStatusFilled, models.OrderStatusRejected, models.OrderStatusCancelled: fmt.Println(frame.Feed.OrderID, s.Status, s.RejectReason) return nil } } ``` ## Recover a lost order response **When:** a write times out or the socket drops before the response arrives. You get `*grvt.OrderStateUnknownError`. Look the order up with `grvt.ResolveOrder`; don't resend it. Steps and code: [When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are functions and types in package `grvt`, not client methods. Pass the client in where they need it. ```go import grvt "github.com/gravity-technologies/grvt-sdk-go" // grvt.ResolveOrder, grvt.NewOrderBook, grvt.BackfillPages, grvt.RefreshCancelCountdown ``` | Helper | What it does | |---|---| | `grvt.ResolveOrder(ctx, client, subAccountID, clientOrderID)` | Looks up an order whose write outcome is unknown. It never resends. | | `grvt.NewOrderBook(instrument, grvt.BookDelta)` | Keeps a local book from order-book stream frames. | | `grvt.BackfillPages(ctx, fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `grvt.RefreshCancelCountdown(ctx, client, subAccountID, seconds)` | Arms or refreshes the [cancel-on-disconnect countdown](/guides/websocket.md#cancel-orders-if-your-app-stops) once (1 to 300 seconds). The SDK never does this for you. | Your `OnEvent` hook gets the `grvt.EventGap` and `grvt.EventSessionRotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#sdk-helpers). ## Errors Check errors with `errors.As`: | Type | When | |---|---| | `*grvt.APIError` | the server answered with an error code; has `Code`, `Message`, `Status` (0 over WebSocket), `RPC`, `Retryable` | | `*grvt.RateLimitError` | code `1006` (HTTP 429); `errors.As` also finds it as `*APIError`; reads were already retried | | `*grvt.TransportError` | no usable answer (connection failed, read timed out, socket closed); has `RPC`, and `Sent` (whether the request may have left). A write that may have left returns `*grvt.OrderStateUnknownError` instead | | `*grvt.OrderStateUnknownError` | a write may or may not have happened; look it up by `ClientOrderID` (`ClientOrderIDs` for a bulk call). It wraps the original failure (`errors.Unwrap`), such as a `*grvt.TransportError`, so check for it first | | `*grvt.OrderOutOfBoundsError` | an order breaks its instrument's limits; nothing was sent; has `Nearest` and `ServerCode` | | `*grvt.StreamOverflowError` | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced | | `*grvt.SigningError`, `*grvt.DecodeError`, `*grvt.ConfigError`, `*grvt.FrameTooLargeError`, `grvt.ErrClosed` | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed | `*grvt.FrameTooLargeError` comes only when you set `Environment.WSMaxFrameBytes`: the named environments don't check frame size. An oversized frame is not sent over HTTP instead. Error code constants are `grvt.Code`, for example `grvt.CodeSignatureExpired`. The full list is on [Error codes](/reference/errors.md). Handle a create like this. Check for `*grvt.OrderStateUnknownError` first, because it wraps the original failure: ```go resp, err := client.CreateOrder(ctx, &models.ApiCreateOrderRequestInput{Order: order}) var unknown *grvt.OrderStateUnknownError var bounds *grvt.OrderOutOfBoundsError var apiErr *grvt.APIError switch { case errors.As(err, &unknown): // The order may or may not exist. Look it up; never resend it. _, err = grvt.ResolveOrder(ctx, client, sub, unknown.ClientOrderID) return err case errors.As(err, &bounds): return fmt.Errorf("not sent, breaks %s: %w", bounds.Limit, err) case errors.As(err, &apiErr): return fmt.Errorf("rejected with code %d: %w", apiErr.Code, err) case err != nil: return err } fmt.Println("placed", resp.Result.Metadata.ClientOrderID) ``` ## Hooks and logging - `GRVT_LOG=debug` logs every request and frame to stderr, with the session cookie, API key, private keys and signatures redacted. Set `Logger` (a `*slog.Logger`) in the `Config` to send the logs elsewhere. - `BeforeSend` in the `Config` runs before each RPC is signed and may change the typed request in place (`call.Params`). It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an [unknown outcome](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config error before anything is sent. - `OnEvent` gets connect, disconnect, reconnect, subscribe, gap, retry, frame, session_rotated and error events. It runs on the socket's read goroutine, so it must return quickly: while it blocks, no frame on that socket is read. ```go client, err := grvt.New(grvt.Config{Env: grvt.Testnet(), OnEvent: func(e grvt.Event) { if e.Kind == grvt.EventGap { log.Printf("re-syncing %s %s", e.Stream, e.Selector) } }}) ``` ## Running in production - **Concurrency.** One `*grvt.Client` is safe for concurrent use: share it across goroutines. Calls that need a login at the same time share one login. - **Context.** Cancelling the `ctx` of a read returns the context's error. Cancelling a write after it may have left returns `*grvt.OrderStateUnknownError`. Cancelling never closes the shared WebSocket. `Next(ctx)` returns the context's error and the subscription stays open; `All()` takes no context and ends only after `Close`. - **`Close()`.** Ends every subscription (`Next` returns `grvt.ErrClosed`, `All` stops) and fails WebSocket calls still waiting for a reply: writes with `*grvt.OrderStateUnknownError`. Later calls return `grvt.ErrClosed`. An HTTP call already running is bounded by its own `ctx`, not by `Close`. - **Reconnects.** Each socket reconnects on its own with full-jitter backoff: a random wait between 0 and 250 ms × 2^attempt, never more than 30 s. The backoff resets once a connection has stayed up for 10 s. Each connect (login and handshake) gets 10 s. The client reconnects when nothing arrives for 30 s, and pings three times in that window. A refused login or a handshake rejected with 401 or 403 stops that socket for good: its subscriptions and calls return the error. - **Rate limits.** The SDK has no client-side rate limiter and doesn't read `Retry-After`. A read that gets `1006` is retried (3 tries in all, waits of up to 100 ms, then twice that). A write returns `*grvt.RateLimitError` at once. Pace your own requests ([Rate limits](/guides/rate-limits.md)). - **Client order IDs.** Set your own per order ([Place an order](/sdks/go.md#place-an-order)) or plug in a `grvt.ClientOrderIDProvider` as `ClientOrderIDs` in the `Config`. The default is `1<<63 | seconds<<31 | counter`, from the wall clock (not `Config.Clock`). Its counter starts at a random value in each process, so IDs are unique within a process; two processes rarely collide, but can. - **Session renewal.** After the client logs in again, each socket closes once none of its writes is waiting for a reply (it checks every 500 ms), then reconnects with the new cookie, usually after a wait of up to 250 ms. WebSocket calls made in between wait up to 10 s for the new socket. HTTP calls, including orders on the default transport, are not interrupted. A failed re-login is retried after 5 s ([Session renewal](/guides/websocket.md#session-renewal)). ## Data types - Decimals use `models.Decimal`. Parse exact text with `models.ParseDecimal`; use `MustParseDecimal` only for constants. `Rat()` gives an exact `*big.Rat` for arithmetic. - Nanosecond timestamps use `time.Time`. Values outside the wire range are rejected. - IDs are `uint64` and travel as JSON strings; a single ID must arrive as a string. Lists of IDs (`models.Uint64s`) accept numbers too. - Required fields use plain values. Optional strings and enums use `""` for absent. Other optional fields (numbers, bools, decimals, nested types) are pointers, so `0` and `false` can be sent: use `grvt.Ptr(...)`. - Signed requests use `Input` models, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield `Partial` models: every feed field is optional. - Enums are string types with constants for the known values. A value added by a newer server arrives as its plain string, so give your `switch` a `default` case. - Millisecond schedule fields stay plain integers. ## Not supported yet - **Resuming a private stream from a sequence number.** After a gap, fill missed events from history with `grvt.BackfillPages` ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). - **Wallet login.** The client logs in with an API key only. ===== sdks/rust.md # Rust SDK > [!WARNING] > **Preview.** Any 0.x release can change the API. [Install](/sdks/rust.md#install) says what to pin. The Rust SDK has a method for every call and stream in the [API reference](/reference/index.md), named as there. It signs every call that needs a signature (filling in the nonce, expiration and client order ID) and re-syncs streams after a gap (when frames were missed, it subscribes again to get current data). Its client is async (tokio). If your engine runs its own sockets and event loop, use the crate [without the client](/sdks/rust.md#without-the-client). New here? [Install](/sdks/rust.md#install) the SDK and run the [Quickstart](/guides/quickstart.md), then read this page down to [Track and cancel an order](/sdks/rust.md#track-and-cancel-an-order). Later sections are for when you need them. ## Install The crate is `grvt` on crates.io and needs Rust 1.88 or newer. Add it with its async dependencies and `rust_decimal`, which the SDK uses for prices and sizes: ```sh cargo add grvt cargo add tokio --features full cargo add futures cargo add rust_decimal ``` In preview, any 0.x release can change the API, so pin an exact version: change the `grvt` line in `Cargo.toml` to an `=` requirement (`grvt = "="`). For the crate [without the client](/sdks/rust.md#without-the-client), add `--no-default-features` to the first `cargo add` and skip `tokio` and `futures`. ## Create a client ```rust use grvt::{Config, Grvt, PrivateKeySigner}; #[tokio::main] async fn main() -> Result<(), Box> { // The API key logs in; the signer signs orders with your signing key. Leave both out for public data only. let client = Grvt::new( Config::testnet() .api_key(std::env::var("GRVT_API_KEY")?) .signer(PrivateKeySigner::new(&std::env::var("GRVT_PRIVATE_KEY")?)?), )?; let t = client.ticker().instrument("BTC_USDT_Perp").await?; println!("{:?}", t.result.mark_price); // the exchange's fair price, used for margin client.close().await; Ok(()) } ``` - Use `Config::prod()` for production ([Environments](/guides/environments.md)). - The client sends short (lite) field names on the wire by default; your code still uses the full names. `.encoding(grvt::Encoding::Full)` on the `Config` switches to full names ([Encoding](/guides/environments.md#encoding-full-or-lite)). - The client logs in on the first private call and renews the session before it expires ([Authentication](/guides/authentication.md)). Renewal reconnects the client's WebSockets, so every stream gets a gap ([Session renewal](/guides/websocket.md#session-renewal)). - To stop, follow [Shut down cleanly](/guides/websocket.md#shut-down-cleanly). ## Call an RPC Every call is a method on the client, `client.()`, named exactly as on its reference page. 1. Call the method to get a request builder. 2. Set request fields with setters named like the wire fields. 3. `.await` the builder to send it. ```rust let inst = client.get_instrument().instrument("BTC_USDT_Perp").await?; println!("{:?}", inst.result); ``` If you leave out a required field, you get an error before anything is signed or sent. - Reads are tried up to 3 times; writes are sent once ([What the SDK retries](/guides/errors-and-retries.md#what-the-sdk-retries)). - Timeouts, on the `Config`: `.call_timeout(...)` (30 s), `.http_attempt_timeout(...)` (10 s), `.ws_request_timeout(...)` (5 s), `.resync_timeout(...)` (5 s), `.idle_timeout(...)` (30 s). For one call, add `.timeout(...)` to its builder. `.call_timeout` covers the whole call (login, metadata, signing, retries and the response); `.http_attempt_timeout` caps each HTTP attempt within what is left of it. - To send a complete request instead of setting fields one by one, use `.with_request(req)` on the builder. ## Pagination `grvt::pages` follows cursors one page at a time, only as you read. Keep the filters fixed inside the callback. ```rust use futures::{pin_mut, StreamExt}; use grvt::pages; let history = pages(|cursor| { let mut call = client.trade_history().instrument("BTC_USDT_Perp"); if let Some(cursor) = cursor { call = call.cursor(cursor); } async move { call.await } }, None); pin_mut!(history); while let Some(page) = history.next().await { for trade in page?.result.unwrap_or_default() { println!("{trade:?}"); } } ``` - An empty page can still have a next cursor. - Dropping the stream stops further calls. - A cursor seen twice returns `Error::PaginationCycle`. Fetch errors pass through, with no extra retries. - Cursors don't promise a stable snapshot while records change. ## Default sub-account `Config::testnet().sub_account_id(123)` fills in omitted account IDs on requests and streams. - An ID you set yourself wins. In a request passed to `.with_request`, a zero account counts as omitted; in `OrderInput`, `None` does. - Bulk orders take the request's account first, then the client default. - Transfer source and destination IDs are never filled in. - The default is applied before signing. Without one, calls that need an account still require it. ## Stream data Every stream method ends in `_stream`, for example `client.trade_stream()`. 1. Build the stream like any call and `.await` it. You get a `Subscription`, which is a `futures::Stream`. 2. Read frames with `next().await`. 3. Drop the subscription to unsubscribe. ```rust use futures::StreamExt; let mut book = client.orderbook_delta_stream().instrument("BTC_USDT_Perp").rate(500).await?; // rate: interval in ms while let Some(frame) = book.next().await { match frame { Ok(frame) => println!("{:?} {:?}", frame.sequence_number, frame.feed), Err(e) => eprintln!("{e}"), // the subscription carries on; it ends with None } } ``` `frame.sequence_number` is a `u64`. It is a string on the wire; the SDK decodes it for you. A gap event's bounds are `Option`. **Watch out:** - After a gap, older frames can still come first and missed private events aren't replayed ([What happens after a gap](/guides/recovery.md#what-happens-after-a-gap)). - Each subscription queues up to 4096 frames, at least 1 (`.queue_size(...)` on the `Config`). If your code falls behind, [`.s` streams](/guides/websocket.md#snapshots-deltas-and-events) (every frame complete) drop their oldest frame and others yield `Err(Error::StreamOverflow { .. })` ([stream errors](/guides/websocket.md#read-a-stream)). Handle the `Err` and keep reading; `frame?` would stop your loop. ## Place an order 1. Build each input model with `Type::new(required_fields...)`, then add optional values with the typed `with_*` setters. `is_buying_asset` is true to buy, false to sell. `TimeInForce::GoodTillTime` (GTT) rests until filled, cancelled or expired; `with_post_only(true)` rejects the order rather than let it trade at once ([TimeInForce](/reference/enums.md)). 2. Call `create_order`. The SDK fills in the signature and a `client_order_id`, and looks up the instrument details it needs to sign. `.order(...)` takes the order by value, so the example sends a clone to keep `order` for later. 3. Save the `client_order_id`: you follow the order by it, because the reply's `order_id` is always zero. The SDK fills it in, so read it from the reply. If the reply is lost, the outcome-unknown error carries it. To know it before sending, set your own (below). ```rust use grvt::{enums::TimeInForce, models as m, Config, Grvt, PrivateKeySigner}; use rust_decimal::Decimal; #[tokio::main] async fn main() -> Result<(), Box> { let client = Grvt::new( Config::testnet() .api_key(std::env::var("GRVT_API_KEY")?) .signer(PrivateKeySigner::new(&std::env::var("GRVT_PRIVATE_KEY")?)?), )?; let is_buying_asset = true; let leg = m::OrderLeg::new("BTC_USDT_Perp", Decimal::new(1, 2), is_buying_asset) // size 0.01 .with_limit_price(Decimal::from(60000)); let sub: u64 = std::env::var("GRVT_SUB_ACCOUNT_ID")?.parse()?; let order = m::OrderInput::new(TimeInForce::GoodTillTime, Some(vec![leg])) .with_sub_account_id(sub) .with_post_only(true); let resp = client.create_order().order(order.clone()).await?; println!("{}", resp.result.metadata.client_order_id); client.close().await; Ok(()) } ``` To choose the `client_order_id` yourself, set it before you send the order, following the [client order ID rules](/guides/signing.md#rules-that-cause-most-rejections). This example draws the random bits from the standard library: ```rust use std::hash::{BuildHasher, RandomState}; let id = 1 << 63 | RandomState::new().hash_one(()); let order = order.with_metadata(m::OrderMetadataInput::new().with_client_order_id(id)); ``` Orders go over HTTP by default. Use `.order_transport(grvt::OrderTransport::Ws)` on the `Config` to send them over the trading WebSocket instead. **Watch out:** - A reply means the exchange received the order, not that it rests on the book ([What a create reply means](/guides/errors-and-retries.md#what-a-create-reply-means)). - An order still open 24 hours after signing expires ([Expiration](/guides/signing.md#rules-that-cause-most-rejections)). - Sending a clone of the same order places a second order, with a new `client_order_id` unless you set one. - An order that breaks its instrument's limits returns `Error::OrderOutOfBounds` and is not sent ([Orders checked before sending](/guides/errors-and-retries.md#orders-checked-before-sending)). `.check_orders(false)` on the `Config` turns the check off and leaves the limits to the exchange. To sign without sending, call `client.sign_(req).await`, for example `client.sign_order_create_order(req)`. It signs the way the RPC method does and returns the signed request. ## Track and cancel an order Private streams need a client with an API key. `order_stream` sends every change to your orders, rejections included; `fill_stream` sends each fill, with its trade ID and client order ID. 1. Open `order_stream` before you place the order. 2. Match updates by `metadata.client_order_id`. The updates also carry the `order_id`. 3. Stop at a final status: `OrderStatus::Filled`, `Rejected` or `Cancelled` ([order states](/guides/errors-and-retries.md#what-a-create-reply-means)). 4. To cancel, call `cancel_order` with `sub_account_id` and `client_order_id` (or `order_id`), after the create has replied. ```rust use futures::StreamExt; use grvt::enums::OrderStatus; let mut orders = client.order_stream().sub_account_id(sub).await?; let resp = client.create_order().order(order).await?; let id = resp.result.metadata.client_order_id; client.cancel_order().sub_account_id(sub).client_order_id(id).await?; while let Some(frame) = orders.next().await { let Ok(frame) = frame else { continue }; let Some(state) = frame.feed.state.filter(|_| frame.feed.metadata.client_order_id == id) else { continue }; if matches!(state.status, OrderStatus::Filled | OrderStatus::Rejected | OrderStatus::Cancelled) { println!("{:?} {:?} {:?}", frame.feed.order_id, state.status, state.reject_reason); break; // dropping `orders` unsubscribes } } ``` ## Recover a lost order response **When:** a write times out or the socket drops before the response arrives. You get `Error::OrderStateUnknown`. Look the order up with `grvt::resolve_order`; don't resend it. Steps and code: [When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown). ## Recovery helpers These are items in the `grvt` crate, not client methods. Pass the client in where they need it. ```rust use grvt::{backfill_pages, refresh_cancel_countdown, resolve_order, OrderBook}; ``` | Helper | What it does | |---|---| | `grvt::resolve_order(&client, sub_account_id, client_order_id)` | Looks up an order whose write outcome is unknown. It never resends. | | `grvt::OrderBook::new(instrument, grvt::BookMode::Delta)` | Keeps a local book from order-book stream frames. | | `grvt::backfill_pages(fetch, gap)` | Pages through REST history after a gap. Your callback picks the call and time window. | | `grvt::refresh_cancel_countdown(&client, sub_account_id, seconds)` | Arms or refreshes the [cancel-on-disconnect countdown](/guides/websocket.md#cancel-orders-if-your-app-stops) once (1 to 300 seconds). The SDK never does this for you. | Your `.on_event(...)` hook gets the `Event::Gap` and `Event::SessionRotated` events they use. How to use them: [SDK helpers](/guides/recovery.md#sdk-helpers). ## Errors Every error is one enum, `grvt::Error`: | Variant | When | |---|---| | `Api { code, message, status, rpc, retryable }` | the server answered with an error code | | `RateLimit { message, status, rpc }` | code `1006` (HTTP 429); `err.code()` returns `Some(1006)`; reads were already retried | | `Transport { message, rpc, sent }` | no usable answer (connection failed, read timed out, socket closed); `sent` says whether the request may have left. A write that may have left returns `OrderStateUnknown` instead | | `OrderStateUnknown { client_order_id, client_order_ids, .. }` | a write may or may not have happened; look it up (`client_order_ids` for a bulk call). The original failure is its `source()` | | `OrderOutOfBounds(..)` | an order breaks its instrument's limits; nothing was sent; has `nearest` and `server_code` | | `StreamOverflow { stream, selector, capacity }` | your code fell behind a stream that may not drop frames; the frames in between are lost and the stream re-synced | | `Signing`, `Decode`, `Config`, `FrameTooLarge`, `Closed` | local problems: bad key or value, unexpected response or frame, bad setup, oversized frame, client closed | Error code constants are in `grvt::error_codes`. The full list is on [Error codes](/reference/errors.md). ## Hooks and logging - `GRVT_LOG=debug` logs every request and frame through `tracing` (target `grvt`), with the cookie, API key, private keys and signatures redacted. If your app has no `tracing` subscriber, the SDK installs one that writes to stderr. With lite encoding, wire logs and raw `Event::Frame` bytes show the short field names. - `.before_send(|call| ...)` on the `Config` is a plain (not async) closure. It runs before each RPC is signed and may change `call.params` (the request as JSON). It must not add, remove or reorder orders, or change their client order IDs, since those are how you look up an [unknown outcome](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown): that fails with a config error before anything is sent. - `.on_event(|ev| ...)` gets connection and stream events: connect, reconnect, gap, retry and more. ```rust let config = Config::testnet().on_event(|ev| { if let grvt::Event::Gap { stream, selector, .. } = ev { eprintln!("re-syncing {stream} {selector}"); } }); ``` ## Data types - Decimals use `rust_decimal::Decimal`. Values with too many decimal places are rejected, not rounded. - Nanosecond timestamps use `grvt::Timestamp` over `i64`. - IDs are `u64`. - Required fields use plain values. Optional and nullable fields use `Option`; set one to `None` to clear it. Decoding rejects a missing required key, even a nullable one. - Signed requests use `Input` models, so the SDK can fill in signatures and metadata. - Ticker and mini-ticker delta streams yield `Partial` models: every feed field is optional. - Models and enums are non-exhaustive. Use the typed `with_*` setters, and add a wildcard arm when you match a generated enum. A value added by a newer server arrives as `Unknown(String)`. - `Default` on a model is for test fixtures; it doesn't make a valid request. Build requests with `Type::new(required_fields...)` or the client's call builder, which checks required fields before sending. - Bulk order models use `order_ids` and `client_order_ids`; on the wire they are `order_i_ds` and `client_order_i_ds`. - Millisecond schedule fields stay plain integers. ## Without the client **Advanced.** With default features turned off ([Install](/sdks/rust.md#install)), the crate has no client and no I/O: no tokio, no HTTP or WebSocket library. It builds every request as plain data, signs it, and reads the replies and stream frames you hand back. Your code owns the sockets, threads and timers. Every call and stream has a descriptor in `grvt::ops`, named like the client method (`ops::CreateOrder`, `ops::OrderbookDeltaStream`): ```rust use grvt::{models as m, ops, signing, Environment, RequestDefaults, RpcOp, SignContext}; let env = Environment::testnet(); let defaults = RequestDefaults { sub_account_id: Some(sub_account_id), client_order_ids: None }; let ids = grvt::prepare_request(ops::CreateOrder::SPEC, &mut req, &defaults)?; // fills client_order_id signing::sign_order_create_order(&mut req, &SignContext::new(&key, &metadata, env.chain_id))?; let http = grvt::rest_request::(&env, &req, Some(&session))?; // method, url, headers, body let (status, body) = send(&http); // send: your HTTP client let reply = grvt::rest_response::(status, &body, &ids); ``` - **Signing** is synchronous. `metadata` holds the instruments and currencies that `signing::needs_` names, loaded once. `signing::instrument_meta` turns a `get_instrument` reply into it. `SignContext` also takes an optional clock and nonce source (by default the system clock and the OS random source), turns order checks on or off, and with `recover_signer` checks each signature against the signer's address (about the cost of one more signature). - **Bulk orders.** `signing::digests_order_bulk_orders` returns one digest per order, so you can sign on any thread or in a key management service (KMS). `attach_order_bulk_orders` checks each signature against its own order before writing it in. - **Wallet signers** implement `grvt::SyncSigner` and read `SigningRequest::typed_data()`. - **Lost answers.** If a write's reply never comes, `grvt::transport_failure(ops::CreateOrder::SPEC, sent, why, ids)` gives you `OrderStateUnknown`. Look the order up with `grvt::resolve_order_request` and `grvt::resolve_order_result` ([When a write's outcome is unknown](/guides/errors-and-retries.md#when-a-writes-outcome-is-unknown)). `grvt::may_retry` says whether a failed read may be sent again. - **WebSocket.** `grvt::ws_request::(&req, id)` builds the JSON-RPC frame; `grvt::ws_request_into` and `grvt::encode_request_into` write into a buffer you keep. `grvt::parse_ws_message` reads a frame once. Route replies by `id` (`grvt::RequestTable`) and stream frames by stream and selector, run `grvt::Sequencer::on_frame`, then `grvt::decode_feed::(&msg)` decodes only the payload. `grvt::subscribe_frame` and `grvt::parse_subscribe_result` handle subscriptions; `grvt::Backoff` paces reconnects. - **Session.** `grvt::api_key_login_request(&env, api_key)` is the login request, and `SessionState::on_login_response` reads the reply. `session.headers()` gives the headers to send and `session.refresh_due()` says when to renew. Log in again when `!session.fresh(now)`. - **Lite encoding.** Call the same functions on `grvt::Encoding::Lite`, for example `Encoding::Lite.rest_request::(..)`, `.ws_request::(..)`, `.parse_ws_message(..)` and `.subscribe_frame(..)`. `ws_response` and `decode_feed` follow the parsed message's encoding. `Environment::ws_url_for(gateway, Encoding::Lite)` gives the lite URL; it swaps `/ws/full` for `/ws/lite`, so a custom `Environment` needs WebSocket URLs ending in `/ws/full`. - **Recovery steps.** `grvt::cancel_countdown_request`, `grvt::backfill_status`, `grvt::PageCursor` and `OrderBook::on_gap` are the no-I/O parts of the [recovery helpers](/sdks/rust.md#recovery-helpers). The crate's `examples/order_and_subscribe.rs` runs an order and an order-book subscription this way against a fake transport. ## Not supported yet - **Resuming a private stream from a sequence number.** After a gap, fill missed events from history with `grvt::backfill_pages` ([Fill missed events from history](/guides/recovery.md#fill-missed-events-from-history)). - **Wallet session login.** Log in with an API key (`.api_key(...)` on the `Config`). - **A blocking client.** Meanwhile, call the client from async code (for example inside a tokio runtime's `block_on`), or use the crate [without the client](/sdks/rust.md#without-the-client). ===== guides/strategies.md # Strategies A strategy is a trading sub-account that other people invest in. Investors get shares; the manager trades the strategy's money. The API and the SDKs call strategies **vaults**: the calls are `vault_*`, the signed types `VaultInvestV3`, `VaultRedeemV3` and `VaultBurnLpToken`, and fields such as `vault_id`. This page is for managers who run their strategy through the API. The calls are under [Strategies](/reference/index.md#strategies) in the reference. ## Creating one 1. In the Grvt web app, open Invest → Become a Strategy Manager. This is open to approved accounts only. 2. Seed the strategy with at least 1,000 USD in its quote currency. 3. Switch to the strategy sub-account, log in with an API key for it, and trade as you would on any sub-account. A strategy differs from a normal sub-account in three ways: - **Fixed leverage.** Every position opens at the strategy's fixed initial leverage (5x), and `set_initial_leverage` is rejected. The de-risk level, where Grvt starts reducing positions before liquidation, is also fixed, at 2x maintenance margin (the minimum margin before liquidation). - **No transfers.** [transfer](/reference/rpc/transfer.md) to or from a strategy fails. Money comes in only through [vault_invest](/reference/rpc/vault_invest.md) and leaves only through redemptions. - **Extra margin for urgent redemptions.** When the strategy places orders, the value of its urgent redemption requests ([How redemptions are paid](/guides/strategies.md#how-redemptions-are-paid)) is added to its initial margin (the margin needed to hold its positions and orders). [sub_account_summary](/reference/rpc/sub_account_summary.md) shows this as `vault_im_additions`. If it pushes the requirement above equity, the strategy can only place orders that reduce risk. ## Shares and share price ``` share price = strategy equity (USD) / shares outstanding ``` Strategy equity is the strategy's balances plus its positions at mark price, so it includes unrealized profit and loss. Investing buys shares at the current price. Redeeming sells them back at the price when the redemption is paid, not when it was requested; the investor then pays the strategy's performance fee on their profit (the manager's own shares pay none). The manager can invest and redeem in their own strategy, and can burn their own shares with [vault_burn_tokens](/reference/rpc/vault_burn_tokens.md), which raises the price for everyone else. Investing ([vault_invest](/reference/rpc/vault_invest.md)) needs the **vault investor** (or admin) permission on the investor's main account; investing from a sub-account also needs the transfer permission there. See [Accounts and permissions](/guides/accounts.md). ## How redemptions are paid An investor asks to redeem with [vault_redeem](/reference/rpc/vault_redeem.md), and the request joins the strategy's redemption queue. Grvt pays from the queue automatically. As manager, you keep enough free money in the strategy for it to do so. Each strategy has a minimum and a maximum redemption period, set by the manager (up to 7 and 28 days). A request's age decides its category, shown as `age_category` in [vault_redemption_queue](/reference/rpc/vault_redemption_queue.md): | Category | Age | What happens | |---|---|---| | `PRE_MIN` | under the minimum period | Waits. Listed separately under `pre_min`, not paid yet. | | `NORMAL` | past the minimum period | Paid automatically when the strategy has room. | | `URGENT` | 90% or more of the maximum period | Paid before every normal request; adds to the strategy's margin. | | `OVERDUE` | past the maximum period | Force-redeemed ([Forced redemption](/guides/strategies.md#forced-redemption)). | Urgent requests are paid first, then normal ones, each oldest first. One exception: among normal requests, when the smallest one is at most a fifth of the oldest one, the smallest goes first. The queue response is already in payment order. On every mark-price update, Grvt pays the request at the head of the queue if the strategy's auto-redeemable balance covers it: ``` auto-redeemable = available balance − barrier × initial margin available balance = margin balance − initial margin − max(unrealized PnL, 0) ``` Unrealized PnL is the profit or loss on open positions. Initial margin counts twice, so Grvt keeps back (1 + barrier) × initial margin in total, plus any unrealized profit. The barrier is a multiplier you set, between 0.8 and 2.0: a higher barrier keeps more money back for open positions. The queue response gives the current `auto_redeemable_balance`, `share_price`, and the share counts waiting (`pending_redemption_token_count`) and urgent (`urgent_redemption_token_count`). **Watch out:** if the head request is bigger than the auto-redeemable balance, nothing behind it is paid either.
Example: small requests jumping ahead Normal requests of 1k, 50k, 100k, 20k, 10k and 25k (oldest first) are paid 1k, 10k, 50k, 20k, 100k, 25k. After 1k, the 10k is a fifth of the 50k at the head, so it jumps ahead. Then the 20k is a fifth of the 100k, so it jumps ahead too.
## Forced redemption A request past the maximum period is paid even if the auto-redeemable balance does not cover it, one request per strategy at a time. Grvt only does this if the strategy's equity stays above its maintenance margin with a safety buffer, so the payment can't put the strategy in danger of liquidation. When it can't pay, the request stays in the queue, and the manager and investor are notified about once an hour until it is paid. To unblock it, raise equity (invest more, take profit) or lower margin (close positions). ## Delisting Grvt delists a strategy automatically when its share price falls below a minimum, for example after a liquidation. A delisted strategy: - takes no new investment and cannot change its settings, including the redemption periods; - can only place orders that reduce risk; - stops automatic redemption; forced redemption continues, so investors are paid out over time. Delisting cannot be undone. To keep the share price up, invest more or burn shares. ## Permissions on business accounts | Who | Can | |---|---| | Admin on the strategy sub-account (Trading Admin, shown as "Strategy Admin" on a strategy) | trade, add users, change strategy settings | | Trade on the strategy sub-account | trade | | Admin on the main account ("Funding Admin") | everything above, plus invest, redeem and burn shares | | Vault investor on the main account ("Strategy Investor") | invest and redeem from the main account | No transfer or withdraw permission lets you [transfer](/reference/rpc/transfer.md) in or out of a strategy: money moves only through investing and redemptions. Investing from a sub-account needs both the vault investor permission and that sub-account's transfer permission ([Shares and share price](/guides/strategies.md#shares-and-share-price)). ===== 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. ===== guides/deposits-and-withdrawals.md # Deposits and withdrawals Use this page to move funds between Grvt and wallets on other chains from code: - **Deposits:** each main account has a deposit address on every supported chain. Tokens sent there are bridged to Grvt and credited to your main account. - **Withdrawals to other chains** go through Grvt's bridge partner: get a quote, sign a transfer, then track the payout. - **Withdrawals to Ethereum** use the [withdrawal](/reference/rpc/withdrawal.md) call instead, which the SDKs have. The deposit address and bridge calls are on the edge host and have no SDK methods yet. Send them over HTTP as shown here. ## Authenticate edge calls - **Deposit addresses:** send your API key in an `X-API-Key` header. A session cookie from a login works too. - **Bridge withdrawals:** send the session cookie, `Cookie: gravity=...`, from a login ([Authentication](/guides/authentication.md#by-hand)). The API key header alone gets HTTP 401 (`err_auth_user_not_logged_in`). Errors come back with an HTTP status and a body like `{"code": "err_withdrawal_quote_expired", "message": "withdrawal quote has expired", "params": {}}`. Match on `code`. ## Get your deposit addresses ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/api/v1/deposit/addresses" \ -H "X-API-Key: $GRVT_API_KEY" ``` The response lists one entry per chain: ```json nocheck { "chains": [ { "chain": "BASE_SEPOLIA", "chain_id": "84532", "deposit_address": "0x...", "supported_tokens": [{"name": "USDT", "contract_address": "0x..."}] }, { "chain": "SOLANA_TEST", "chain_id": "solana_test", "deposit_address": "", "supported_tokens": [{"name": "USDT", "contract_address": "..."}] } ] } ``` | Field | Meaning | |---|---| | `chain` | The chain's name. Pass it back exactly as returned. | | `chain_id` | The EVM chain ID, or a name for chains without one, such as `"solana"` and `"tron"` (`"solana_test"` and `"tron_test"` on testnet). | | `deposit_address` | Send tokens here. Empty when the address doesn't exist yet ([Create an address](/guides/deposits-and-withdrawals.md#create-an-address-on-another-chain)). | | `supported_tokens` | The tokens you can deposit on this chain, with their contract addresses. | | `token_out` | Present only when deposits are credited as a different token, which it names. | **Watch out:** - The chains and tokens differ by environment and change over time. Read them from this call; don't hard-code them. - A `contract_address` can be empty when Grvt couldn't look it up. Call again before you send that token. - A new account fails with `err_chain_account_not_setup` ("funding account is not set up") until its main account is set up. ### Create an address on another chain **When:** a chain is listed with an empty `deposit_address`. ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/deposit/generate-address" \ -H "X-API-Key: $GRVT_API_KEY" \ -H "Content-Type: application/json" \ --data '{"chain": "SOLANA_TEST"}' ``` It returns one entry in the same shape, with the new `deposit_address`. The chain name is not case-sensitive. An unknown chain fails with `err_deposit_chain_not_supported`, and a chain that isn't open to your account with `err_deposit_chain_not_available`. ### Track deposits A bridged deposit arrives in your main account as a transfer with `transfer_type` `NON_NATIVE_BRIDGE_DEPOSIT`. Find it with [transfer_history](/reference/rpc/transfer_history.md). ## Withdraw to another chain **When:** you send USDT from your main account to a wallet on another chain. Before you start: - The destination address must be in your main account's withdrawal address book. - The signing wallet needs the **External Transfer** (or Admin) permission on the main account ([Permissions](/guides/accounts.md#permissions)). The withdrawal is a transfer to the bridge partner's Grvt account. - The funds must be in the main account. Move them from a sub-account with [transfer](/reference/rpc/transfer.md) first. 1. Read the routes and the bridge partner's account: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-info" -H "Cookie: gravity=$GRVT_COOKIE" ``` ```json nocheck { "provider": "RHINO", "funding_address": "0x...", "route": { "USDT": [{"chain": "BASE_SEPOLIA", "chain_id": "84532", "chain_type": "evm", "tokens_out": ["USDT"]}], "USDC": [] } } ``` `route` maps each token you can send (`token_in`) to the chains and tokens it can arrive as. Only USDT can be withdrawn this way today. 2. Get a quote. Nothing moves yet. ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-quote" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "Content-Type: application/json" \ --data '{"to_address": "0x...", "chain": "BASE_SEPOLIA", "token_in": "USDT", "token_out": "USDT", "amount": "100"}' ``` The reply has `quote_id`, `pay_amount` (what leaves your main account), `receive_amount` (what arrives), `fee` (in `token_in`), `fee_usd`, `speed` and `expires_at`. All amounts are decimal strings. 3. Sign a [Transfer](/reference/signing/Transfer.md) from your main account to the bridge partner, with the quote's amount: | Field | Value | |---|---| | `fromAccount` | your main account ID | | `fromSubAccount` | `0` | | `toAccount` | `funding_address` from step 1 | | `toSubAccount` | `0` | | `tokenCurrency` | the `id` of USDT from [get_currency](/reference/rpc/get_currency.md) | | `numTokens` | `pay_amount` × 10^`balance_decimals` of USDT | | `nonce`, `expiration` | a random uint32; unix nanoseconds, at most 30 days ahead | [Signing](/guides/signing.md) explains the domain and the hashing. 4. Send the quote ID and the signature before `expires_at`: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdraw" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "Content-Type: application/json" \ --data @- <<'EOF' { "quote_id": "...", "signature": {"signer": "0x...", "r": "0x...", "s": "0x...", "v": 28, "expiration": "1767225600000000000", "nonce": 1002, "chain_id": 326} } EOF ``` Here `chain_id` is a number, not a string as in other signed requests. You can leave it out: Grvt then uses its own chain ID. HTTP 202 means the transfer was sent: `{"quote_id", "tx_id", "state": "SUBMITTED", "receive_amount", "fee", "fee_usd"}`. 5. Check progress until the state is final: ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/bridge/withdrawal-status?quote_id=$QUOTE_ID" \ -H "Cookie: gravity=$GRVT_COOKIE" ``` The reply has `state`, `chain`, `token_out`, `receive_amount` and, once paid, `withdraw_tx_hash` on the destination chain. | State | Meaning | |---|---| | `CREATED` | Quoted, not sent. | | `SUBMITTED` | Sent to the bridge partner; payout not started. | | `SENDING` | The bridge partner is paying out. | | `COMPLETED` | Paid out. Final. | | `REFUNDED` | Not paid out; the funds were returned. Final. | | `FAILED` | Not paid out. Final. | **Watch out:** - If step 4 times out or returns a 5xx, the withdrawal may still go through. Check the status, or send the same request again with the same signature: if it went through, you get the first reply back. A quote can be sent only once, so retrying it can't withdraw twice. - Don't get a new quote and sign again until the status of the first one is final, or you may withdraw twice. - A quote past `expires_at` fails with `err_withdrawal_quote_expired` (HTTP 410). Get a new one.
Errors | Status | Code | Cause | |---|---|---| | 404 | `err_withdrawal_address_not_in_address_book` | `to_address` isn't in the withdrawal address book for this chain type. | | 422 | `err_withdrawal_token_not_supported` | `token_in` isn't USDT. | | 422 | `err_withdrawal_route_not_supported` | This chain and `token_out` aren't a route right now. | | 422 | `err_withdrawal_amount_below_fee` | The amount doesn't cover the fee. | | 422 | `err_withdrawal_limit_exceeded` | A daily limit or the bridge's available funds would be exceeded. | | 422 | `err_withdrawal_insufficient_balance` | The main account doesn't hold `pay_amount`. | | 400 | `err_withdrawal_signature_invalid` | The signature doesn't match the quote, or has expired. | | 403 | `err_withdrawal_address_rejected` | The destination failed screening or can't be used. | | 403 | `err_user_has_insufficient_permissions` | The signing wallet lacks External Transfer. | | 409 | `err_withdrawal_already_executed` | This quote was already sent. | | 410 | `err_withdrawal_quote_expired` | Get a new quote. | | 404 | `err_withdrawal_not_found` | No withdrawal with this `quote_id` for your account. |
===== guides/referrals.md # Referrals Use these calls to build reports for the people you referred to Grvt: their trading volume and fees, what you earned from them, and your points. They read data only. The calls are on the edge host and have no SDK methods yet. Send them over HTTP. | Call | Returns | |---|---| | `GET /api/v1/referral/epochs` | the reward epochs so far | | `GET /api/v1/referral/points` | your points | | `GET /api/v1/referral/data` | your direct referrals, with totals per referral | | `POST /api/v1/referral/daily_data` | one direct referral, day by day | | `GET /api/v1/referral/indirect_data` | referrals of your referrals | ## Before you call - **Authenticate** with your API key in an `X-API-Key` header, or with the session cookie from a login ([Authentication](/guides/authentication.md#by-hand)). The data is for the account the key or session belongs to. Without either, calls fail with HTTP 401. - **Account IDs** in these calls are off-chain account IDs, such as `"ACC:..."`, not `0x` addresses. Each referral also has its `funding_account_address`, its main account ID. - **Numbers** in responses are JSON numbers, not decimal strings, rounded to 4 decimals. `total` is a string. - **Errors** come back as `{"code": "err_...", "message": "...", "params": {...}}` with an HTTP status. ```sh export GRVT_DOMAIN=testnet.grvt.io curl -sS "https://edge.$GRVT_DOMAIN/api/v1/referral/epochs" -H "X-API-Key: $GRVT_API_KEY" ``` ```json nocheck {"epochs": [{"epoch": 1, "start_time": "", "end_time": ""}]} ``` Epochs that have started are listed, oldest first. Use their numbers as `from_epoch` and `to_epoch` below. ## Your points `GET /api/v1/referral/points?from_epoch=10&to_epoch=12` returns `{"total_points": 1520.5, "community_referral_points": 230.25}`. Leave out an epoch bound (or send `0`) for no limit on that side. ## Your direct referrals **When:** you want totals per referral over a range of epochs or days. ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/referral/data?from_date=2026-11-01&to_date=2026-11-07&page_size=50" \ -H "X-API-Key: $GRVT_API_KEY" ``` Query parameters, all optional: | Parameter | Meaning | |---|---| | `from_epoch`, `to_epoch` | Epoch range. `0` or left out means no limit. | | `from_date`, `to_date` | Day range, `YYYY-MM-DD` in UTC, both days included. Don't combine with epochs. | | `account_id` | Only this referral. | | `page_number`, `page_size` | Paging. Pages start at 1; the default size is 100. | | `include_all_referrals` | `true` also lists referrals with no activity in the range, with zeros. Default `false`. | The response has `referrals`, `total` (how many referrals match), `page_number`, `page_size` and `total_trading_volume`, your own trading volume over the same range. Each referral has: | Field | Meaning | |---|---| | `account_id`, `username`, `funding_account_address` | Who they are | | `referral_join_time` | When they last became your referral | | `trade_type` | Always `"Perpetual"`: the program pays on perpetuals | | `total_trading_volume`, `total_trading_fee` | Their volume and the fees they paid | | `total_eligible_trading_fee` | The part of their fees your earnings are based on | | `earning_from_referral` | What you earned from them | | `cashback_earning` | The cashback they earned | **Watch out:** with dates, only completed UTC days are served. `to_date` defaults to yesterday, and `from_date` to the first day with daily data. A range outside that fails with `err_referral_date_out_of_range`, whose `params` give `earliest_date` and `latest_date`. ## One referral, day by day ```sh curl -sS "https://edge.$GRVT_DOMAIN/api/v1/referral/daily_data" \ -H "X-API-Key: $GRVT_API_KEY" \ -H "Content-Type: application/json" \ --data '{"account_id": "ACC:...", "from_date": "2026-10-01", "to_date": "2026-10-31"}' ``` - `account_id` is required and must be your direct referral; otherwise the call fails with `err_referral_account_not_found` (HTTP 404). - `to_date` defaults to yesterday and `from_date` to 89 days before it (90 days in all), but no earlier than the first day with data. The range can be at most 300 days (`err_referral_date_range_too_large`). The response repeats the referral's `account_id`, `username`, `funding_account_address`, `referral_join_time` and the resolved `from_date` and `to_date`. `days` has one entry per day with activity: `date`, `trade_type`, `total_trading_volume`, `total_trading_fee`, `total_eligible_trading_fee`, `earning_from_referral` and `cashback_earning`. ## Referrals of your referrals `GET /api/v1/referral/indirect_data` takes `from_epoch`, `to_epoch`, `page_number`, `page_size` and `include_all_referrals`, as above (no dates). Each entry has `account_id`, `username`, `funding_account_address`, `total_trading_volume`, `total_trading_fee`, `total_eligible_trading_fee` and `earning_from_referral`; the response adds `total`, `page_number` and `page_size`.
Errors | Status | Code | Cause | |---|---|---| | 400 | `err_invalid_query_params` | A bad query parameter, or `to_epoch` below `from_epoch`. `params.reason` says which. | | 400 | `err_referral_date_with_epoch` | Dates and epochs in one request. | | 400 | `err_validation_invalid_date_format` | A date that isn't `YYYY-MM-DD`. | | 400 | `err_referral_date_out_of_range` | Outside `params.earliest_date` to `params.latest_date`, or `to_date` before `from_date`. | | 400 | `err_referral_daily_data_unavailable` | No daily data yet. | | 400 | `err_referral_date_range_too_large` | More than `params.max_days` days. | | 400 | `err_invalid_request_body` / `err_missing_required_fields` | `daily_data` body is not valid JSON, or has no `account_id`. | | 404 | `err_referral_account_not_found` | `account_id` is not your direct referral. |
===== reference/rpc/login_api_key.md # Login API key The response sets the `gravity` cookie and the `X-Grvt-Account-Id` header; send both on every authenticated call and on the WebSocket upgrade. | | | |---|---| | SDK | Configure the client with an API key; raw edge login is not a generated client method | | HTTP | `POST https://edge./auth/api_key/login` (login is served by the edge host, not the trading gateway) | | WebSocket | not available (edge is HTTP only) | | Auth | None | | Contract id | `edge.api_key_login` | ## Request Body type `EdgeApiKeyLoginRequest`. - `api_key` · string · required — The API key created in the Grvt UI. ## Response Body type `EdgeLoginResponse`. - `status` · string · required — "success" on success. - `location` · string · required — Always empty for API callers. - `funding_account_address` · string (0x address) · required — Funding (main) account the key belongs to. - `sub_account_id` · uint64 · optional — Set only when the key was created for a trading (sub) account. ## Errors Edge errors are not gateway error codes. Body: EdgeLoginError. | HTTP | Meaning | |---|---| | 400 | invalid request body | | 401 | Invalid Credentials | | 403 | IP not whitelisted, country restricted, or account deactivated, closed or on hold | | 500 | Internal Server Error | ## Example ```python import os from grvt import Grvt # Login happens on the first authenticated call and is renewed before the cookie expires. with Grvt(env=os.environ.get("GRVT_ENV", "testnet"), api_key=os.environ["GRVT_API_KEY"]) as client: print(client.get_sub_accounts()) ``` Raw HTTP. `-D -` prints the response headers, which carry the cookie and account id: ```sh curl -sS -D - "https://edge.$GRVT_DOMAIN/auth/api_key/login" \ -H "Content-Type: application/json" \ --data @- </auth/wallet/login` (login is served by the edge host, not the trading gateway) | | WebSocket | not available (edge is HTTP only) | | Auth | None | | Signed | `signature` is a [`WalletLogin`](/reference/signing/WalletLogin.md) signature. signer must equal address; expiration at most 5 minutes ahead of server time; (address, nonce) is single-use | | Contract id | `edge.wallet_login` | ## Request Body type `EdgeWalletLoginRequest`. - `address` · string (0x address) · required — Wallet address being logged in. - `signature` · object Signature · required — WalletLogin EIP-712 signature by that wallet. - `signature.signer` · 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. - `signature.r` · string (uint256) · required — The signature's `r`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `signature.s` · string (uint256) · required — The signature's `s`, as `0x` + 64 hex characters. Without the `0x` the signature fails to verify. - `signature.v` · integer (uint8) · required — The signature's `v`, 27 or 28. - `signature.expiration` · 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. - `signature.nonce` · 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. - `signature.chain_id` · 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. ## Response Body type `EdgeWalletLoginResponse`. - `funding_account_address` · string (0x address) · required — Funding (main) account linked to the wallet. Note: the public docs show the API-key response shape here; the code returns only this field. ## Errors Edge errors are not gateway error codes. Body: plain text (httputil.WriteError). | HTTP | Meaning | |---|---| | 400 | invalid request body \| invalid wallet address \| signature expiration exceeds maximum allowed window | | 401 | signature expired \| invalid signature \| signature already used \| wallet address not registered \| user not found | | 500 | Internal Server Error | ## Example The SDK clients use API-key sessions; they do not expose wallet login as a client method. Raw HTTP; the body is the `wallet_login` signing case (public test key, chain id 326), so it fails with 401 *wallet address not registered*. In your own body `signature.expiration` is unix nanoseconds, at most 5 minutes ahead (the signing case uses 2100-01-01 so it never expires): ```sh curl -sS -D - "https://edge.$GRVT_DOMAIN/auth/wallet/login" \ -H "Content-Type: application/json" \ --data @- </full/v1/get_sub_accounts`, or `/lite/v1/get_sub_accounts` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/get_sub_accounts` 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 | `account.get_sub_accounts` (`RPCGetSubAccountsV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiGetSubAccountsResponse` (the same object is the JSON-RPC `result` over WebSocket). - `sub_account_ids` · lite `sa` · string (uint64)[] · required — List of sub-account IDs accessible to the session ## 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) · `1002` InternalServer (500) · `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_sub_accounts() 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_sub_accounts" \ -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_sub_accounts" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` ===== reference/rpc/aggregated_account_summary.md # Aggregated account summary | | | |---|---| | SDK | `client.aggregated_account_summary(...)` | | HTTP | `POST https://trades./full/v1/aggregated_account_summary`, or `/lite/v1/aggregated_account_summary` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/aggregated_account_summary` 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 | `account.aggregated_account_summary` (`RPCAggregatedAccountSummaryV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiAggregatedAccountSummaryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object AggregatedAccountSummary · required — The aggregated account summary - `result.main_account_id` · lite `ma` · string (0x address) · required — The main account ID of the account to which the summary belongs - `result.total_equity` · lite `te` · string · required — Total equity of the main (+ sub) account, denominated in USD - `result.spot_balances` · lite `sb` · object SpotBalance[] · required — The list of spot assets owned by this main (+ sub) account, and their balances - `result.spot_balances[].currency` · lite `c` · string · required — The currency you hold a spot balance in - `result.spot_balances[].balance` · lite `b` · string · required — This currency's balance in this sub-account. - `result.spot_balances[].index_price` · lite `ip` · string · required — The index price of this currency. (reported in `USD`) - `result.spot_balances[].entry_price` · lite `ep` · string · required — The entry price of this spot currency. (reported in `USD`) - `result.spot_balances[].realized_pnl` · lite `rp` · string · required — The realized PnL of this spot currency. (reported in `USD`) - `result.spot_balances[].unrealized_pnl` · lite `up` · string · required — The unrealized PnL of this spot currency. (reported in `USD`) - `result.spot_balances[].available_to_transfer` · lite `at` · string · required — The available to transfer amount of this spot currency. - `result.spot_balances[].borrowed_amount` · lite `ba` · string · optional — The amount borrowed in this currency, inclusive of accrued interest. Only reported by `account_summary`, and only for multi-asset-mode sub-accounts - `result.vault_investments` · lite `vi` · object VaultInvestment[] · required — The list of vault investments held by this main account - `result.vault_investments[].vault_id` · lite `vi` · string (uint64) · required — The sub-account ID of the vault invested in. - `result.vault_investments[].num_lp_tokens` · lite `nl` · string · required — The number of shares held by the investor. - `result.vault_investments[].share_price` · lite `sp` · string · required — The current share price (in USD) of this vault investment. - `result.vault_investments[].usd_notional_invested` · lite `un` · string · required — The USD notional invested in this vault investment. - `result.vault_investments[].share_balances` · lite `sb` · object VaultShareBalances · optional — The owner's Funding, trading and reserved vault shares. Absent on older snapshots. - `result.vault_investments[].share_balances.funding_lp_token_balance` · lite `fl` · string · required — The vault LP tokens in the funding account, including those a pending redemption reserves. - `result.vault_investments[].share_balances.trading_lp_token_balance` · lite `tl` · string · required — The vault LP tokens across all sub-accounts: the sum of tradingBalances. - `result.vault_investments[].share_balances.pending_redemption_lp_token_balance` · lite `pr` · string · required — The funding account's vault LP tokens a pending redemption reserves. - `result.vault_investments[].share_balances.available_to_transfer` · lite `at` · string · required — The funding account's vault LP tokens that can move to a sub-account now: fundingLpTokenBalance less pendingRedemptionLpTokenBalance. The minimum investment period does not block transfers. The destination's own checks still apply. - `result.vault_investments[].share_balances.currency` · lite `c` · string · optional — The vault's share currency, used to transfer its LP tokens. Omitted when the vault has none. - `result.total_sub_account_balance` · lite `ts` · string · required — Deprecated: Use totalSubAccountEquity instead - `result.total_sub_account_equity` · lite `ts1` · string · required — Total equity of the sub-accounts, denominated in USD - `result.total_vault_investments_balance` · lite `tv` · string · required — Total amount of the vault investments, denominated in USD - `result.total_sub_account_available_balance` · lite `ts2` · string · required — Total available balance of the main account, denominated in USD - `result.total_usd_notional_invested` · lite `tu` · string · required — Total entry (initial investment) amount of the open investments, denominated in USD ## 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)): `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.aggregated_account_summary() 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/aggregated_account_summary" \ -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/aggregated_account_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` ===== reference/rpc/funding_account_summary.md # Funding account summary | | | |---|---| | SDK | `client.funding_account_summary(...)` | | HTTP | `POST https://trades./full/v1/funding_account_summary`, or `/lite/v1/funding_account_summary` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/funding_account_summary` 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 | `account.funding_account_summary` (`RPCFundingAccountSummaryV1`) | ## Request Body type `EmptyRequest`. Fields the server fills are left out. No fields. ## Response Body type `ApiFundingAccountSummaryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object FundingAccountSummary · required — The funding account summary - `result.main_account_id` · lite `ma` · string (0x address) · required — The main account ID of the account to which the summary belongs - `result.total_equity` · lite `te` · string · required — Total equity of the main account, denominated in USD - `result.spot_balances` · lite `sb` · object SpotBalance[] · required — The list of spot assets owned by this main account, and their balances Fields: see [SpotBalance](/reference/types.md#spotbalance); listed in full under `result.spot_balances[]` on reference/rpc/aggregated_account_summary.md, earlier in this file. - `result.vault_investments` · lite `vi` · object VaultInvestment[] · required — The list of vault investments held by this main account Fields: see [VaultInvestment](/reference/types.md#vaultinvestment); listed in full under `result.vault_investments[]` on reference/rpc/aggregated_account_summary.md, earlier in this file. - `result.total_cash_balance` · lite `tc` · string · required — Total balance of cash (stablecoin) currencies, denominated in USD - `result.total_spot_asset_balance` · lite `ts` · string · required — Total balance of non-cash spot currencies, denominated in USD - `tier` · lite `t` · object ClientTier · required — Client fee tier at the time of query - `tier.tier` · lite `t` · integer (uint8) · required - `tier.futures_taker_fee` · lite `ft` · integer (int32) · required - `tier.futures_maker_fee` · lite `fm` · integer (int32) · required - `tier.options_taker_fee` · lite `ot` · integer (int32) · required - `tier.options_maker_fee` · lite `om` · integer (int32) · required - `tier.spot_taker_fee` · lite `st` · integer (int32) · required - `tier.spot_maker_fee` · lite `sm` · integer (int32) · required - `tier.spot_borrow_configs` · lite `sb` · object ApiSpotBorrowConfig[] · required — Per-currency borrow & collateral limits for this tier. Populated only in the funding_account_summary response; empty in raw config contexts. - `tier.spot_borrow_configs[].currency` · lite `c` · string · required - `tier.spot_borrow_configs[].borrow_limit` · lite `bl` · string · required — BL — max borrowable amount, denominated in the asset. 0 = not borrowable. - `tier.spot_borrow_configs[].borrow_rate` · lite `br` · string · required — BR — annual borrow interest rate at this tier. Never exceeds the asset's maxBorrowRate. - `tier.spot_borrow_configs[].collateral_limit` · lite `cl` · string · required — CL — max amount counted as collateral, denominated in the asset. 0 = unlimited. ## 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)): `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.funding_account_summary() 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/funding_account_summary" \ -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/funding_account_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` ===== reference/rpc/sub_account_summary.md # Sub account summary | | | |---|---| | SDK | `client.sub_account_summary(...)` | | HTTP | `POST https://trades./full/v1/account_summary`, or `/lite/v1/account_summary` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/account_summary` 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 | `account.sub_account_summary` (`RPCSubAccountSummaryV1`) | ## Request Body type `ApiSubAccountSummaryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by ## Response Body type `ApiSubAccountSummaryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object SubAccount · required — The sub-account matching the request sub-account - `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 this entry refers to - `result.margin_type` · lite `mt` · enum MarginType · required — The type of margin algorithm this sub-account uses Values: `SIMPLE_CROSS_MARGIN`, `PORTFOLIO_CROSS_MARGIN` ([details](/reference/enums.md#margintype)). - `result.settle_currency` · lite `sc` · string · required — The settlement, margin, and reporting currency of this account. This sub-account can only open positions quoted in this currency In the future, when users select a Multi-Currency Margin Type, this will be USD All other assets are converted to this currency for the purpose of calculating margin - `result.unrealized_pnl` · lite `up` · string · required — The total unrealized PnL of all positions owned by this sub-account, in the quote asset. Decimal string, e.g. "12.5". `unrealized_pnl = sum(position.unrealized_pnl * position.quote_index_price) / settle_index_price` - `result.total_equity` · lite `te` · string · required — The notional value of your account if all positions are closed, excluding trading fees (reported in `settle_currency`). `total_equity = sum(spot_balance.balance * spot_balance.index_price) / settle_index_price + unrealized_pnl` - `result.initial_margin` · lite `im` · string · required — The `total_equity` required to open positions in the account (reported in `settle_currency`). Computation is different depending on account's `margin_type` - `result.maintenance_margin` · lite `mm` · string · required — The `total_equity` required to avoid liquidation of positions in the account (reported in `settle_currency`). Computation is different depending on account's `margin_type` - `result.available_balance` · lite `ab` · string · required — DEPRECATED: use the per-currency `availableToTransfer` of the quote-currency entry in `spotBalances` instead. The notional value available to transfer out of the sub-account into the funding account (reported in `settle_currency`). `available_balance = total_equity - initial_margin - min(unrealized_pnl, 0)` - `result.spot_balances` · lite `sb` · object SpotBalance[] · required — The list of spot assets owned by this sub-account, and their balances Fields: see [SpotBalance](/reference/types.md#spotbalance); listed in full under `result.spot_balances[]` on reference/rpc/aggregated_account_summary.md, earlier in this file. - `result.positions` · lite `p` · object Positions[] · required — The list of positions owned by this sub-account - `result.positions[].event_time` · lite `et` · string (int64 unix ns) · required — Time at which the event was emitted in unix nanoseconds - `result.positions[].sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID that participated in the trade - `result.positions[].instrument` · lite `i` · string (instrument name) · required — The instrument being represented - `result.positions[].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.positions[].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.positions[].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.positions[].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.positions[].mark_price` · lite `mp` · string · required — The mark price of the position. Decimal string, e.g. "65000.5"; up to 9 decimals. - `result.positions[].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.positions[].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.positions[].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.positions[].roi` · lite `r` · string · required — The ROI of the position, expressed as a percentage `roi = (total_pnl / (entry_price * abs(size))) * 100^` - `result.positions[].quote_index_price` · lite `qi` · string · required — The index price of the quote currency. (reported in `USD`) - `result.positions[].est_liquidation_price` · lite `el` · string · required — The estimated liquidation price - `result.positions[].leverage` · lite `l` · string · required — The current leverage value for this position - `result.positions[].cumulative_fee` · lite `cf` · string · required — The cumulative fee paid on the position, in the quote asset. Decimal string, e.g. "12.5". - `result.positions[].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.positions[].margin_type` · lite `mt` · enum PositionMarginType · required — The margin type of the position Values: `ISOLATED`, `CROSS` ([details](/reference/enums.md#positionmargintype)). - `result.positions[].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.positions[].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.positions[].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 - `result.settle_index_price` · lite `si` · string · required — The index price of the settle currency. (reported in `USD`) - `result.is_vault` · lite `iv` · bool · optional — Whether this sub-account is a vault - `result.vault_im_additions` · lite `vi` · string · optional — Total amount of IM (reported in `settle_currency`) deducted from the vault due to redemptions nearing the end of their redemption period - `result.derisk_margin` · lite `dm` · string · required — The derisk margin of this sub-account - `result.derisk_to_maintenance_margin_ratio` · lite `dt` · string · required — The derisk margin to maintenance margin ratio of this sub-account - `result.total_cross_equity` · lite `tc` · string · required — The total equity of this sub-account for cross margin - `result.cross_unrealized_pnl` · lite `cu` · string · required — The unrealized PnL of this sub-account for cross margin - `result.sub_account_mode` · lite `sa1` · enum SubAccountMode · required — The mode of the sub-account Values: `SINGLE_ASSET_MODE` ([details](/reference/enums.md#subaccountmode)). - `result.margin_balance` · lite `mb` · string · required — The margin balance of this sub-account for cross margin - `result.algo_trading_enabled` · lite `at` · bool · required — Whether algo trading is enabled for this sub-account ## 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.sub_account_summary( 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/account_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/spot_account_summary`, or `/lite/v1/spot_account_summary` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/spot_account_summary` 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 | `account.spot_account_summary` (`RPCSpotAccountSummaryV1`) | ## Request Body type `ApiSpotSubAccountSummaryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to filter by ## Response Body type `ApiSpotSubAccountSummaryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object SpotSubAccount · required — The spot sub-account summary - `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 this entry refers to - `result.total_equity` · lite `te` · string · required — Total equity of the spot sub-account, denominated USD - `result.spot_balances` · lite `sb` · object SpotBalance[] · required — The list of spot assets owned by this spot sub-account, and their balances Fields: see [SpotBalance](/reference/types.md#spotbalance); listed in full under `result.spot_balances[]` on reference/rpc/aggregated_account_summary.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.spot_account_summary( 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/spot_account_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/funding_payment_history`, or `/lite/v1/funding_payment_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/funding_payment_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.funding_payment_history` (`RPCFundingPaymentHistoryV1`) | ## Request Body type `ApiFundingPaymentHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to request for - `instrument` · lite `i` · string (instrument name) · optional, default `all` — The perpetual instrument to filter for - `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 - `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 `ApiFundingPaymentHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object FundingPayment[] · required — The funding payments 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 made the funding payment - `result[].instrument` · lite `i` · string (instrument name) · required — The instrument being funded (perpetual or stable perp) - `result[].currency` · lite `c` · string · required — The currency of the funding payment - `result[].amount` · lite `a` · string · required — The amount of the funding payment. Positive if paid, negative if received - `result[].tx_id` · lite `ti` · string (uint64) · required — The transaction ID of the funding payment. Funding payments can be triggered by a trade, transfer, or liquidation. The `tx_id` will match the corresponding `trade_id` or `tx_id`. - `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.funding_payment_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/funding_payment_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/interest_payment_history`, or `/lite/v1/interest_payment_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/interest_payment_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.interest_payment_history` (`RPCInterestPaymentHistoryV1`) | ## Request Body type `ApiInterestPaymentHistoryRequest`. Fields the server fills are left out. - `sub_account_id` · lite `sa` · string (uint64) · required — The sub-account ID to request for - `currency` · lite `c` · string[] · optional, default `all` — The currency filter to apply. If nil, this defaults to all currencies. 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 `c1` · string · optional — The cursor to indicate when to start the query from ## Response Body type `ApiInterestPaymentHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object InterestPayment[] · required — The interest payments matching the request - `result[].event_time` · lite `et` · string (int64 unix ns) · required — Time at which the interest charge was computed in unix nanoseconds - `result[].sub_account_id` · lite `sa` · string (uint64) · required — The sub-account being charged interest - `result[].currency` · lite `c` · string · required — The currency the interest is charged in - `result[].amount` · lite `a` · string · required — The interest charged for this hour. - `result[].charge_time` · lite `ct` · string (int64 unix ns) · required — The last interest charge time accumulated to this amount (HH:05 tick). - `result[].borrowed_amount` · lite `ba` · string · required — The borrowed principal in this currency that the hourly interest was computed on. - `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.interest_payment_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/interest_payment_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/deposit_history`, or `/lite/v1/deposit_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/deposit_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 | `transfer.deposit_history` (`RPCDepositHistoryV1`) | ## Request Body type `ApiDepositHistoryRequest`. Fields the server fills are left out. - `currency` · lite `c` · string[] · required — The token currency to query for, if nil or empty, return all deposits. Otherwise, only entries matching the filter will be returned - `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 page size for a single response. Defaults to 500; Max 1000. This caps one page only — omitting it does NOT return everything, it applies the 500 default. To get the full result set, follow the `next` cursor until it is empty. - `cursor` · lite `c1` · string · optional — The cursor to indicate when to start the next query from - `main_account_id` · lite `ma` · string (0x address) · optional — Main account ID being queried. By default, applies the requestor's main account ID. ## Response Body type `ApiDepositHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object DepositHistory[] · required — The deposit history matching the request account - `result[].l_1_hash` · lite `l1` · string (uint256) · required — The L1 txHash of the deposit - `result[].l_2_hash` · lite `l2` · string (uint256) · required — The L2 txHash of the deposit - `result[].to_account_id` · lite `ta` · string (0x address) · required — The account to deposit into - `result[].currency` · lite `c` · string · required — The token currency to deposit - `result[].num_tokens` · lite `nt` · string · required — The number of tokens to deposit - `result[].initiated_time` · lite `it` · string (int64 unix ns) · required — The timestamp when the deposit was initiated on L1 in unix nanoseconds - `result[].confirmed_time` · lite `ct` · string (int64 unix ns) · required — The timestamp when the deposit was confirmed on L2 in unix nanoseconds, empty if the deposit is pending. - `result[].from_address` · lite `fa` · string (0x address) · required — The address of the sender - `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.deposit_history( currency=[ "USDT", "USDC", ], 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/deposit_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/transfer`, or `/lite/v1/transfer` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/transfer` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`Transfer`](/reference/signing/Transfer.md) / [`TransferV2`](/reference/signing/TransferV2.md) / [`TransferV3`](/reference/signing/TransferV3.md). If from_wallet_type and to_wallet_type are both set: TransferV2 when the currency id fits uint8 (\<= 255), else TransferV3. If neither is set: Transfer (only for currency ids \<= 255). Setting only one is rejected. Sign TransferV3 only for currency ids above 255. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `transfer.transfer` (`RPCTransferV1`) | ## Request Body type `ApiTransferRequest`. Fields the server fills are left out. - `from_account_id` · lite `fa` · string (0x address) · required — The main account to transfer from - `from_sub_account_id` · lite `fs` · string (uint64) · required — The sub-account to transfer from (0 if transferring from main account) - `to_account_id` · lite `ta` · string (0x address) · required — The main account to deposit into - `to_sub_account_id` · lite `ts` · string (uint64) · required — The sub-account to transfer to (0 if transferring to main account) - `currency` · lite `c` · string · required — The token currency to transfer - `num_tokens` · lite `nt` · string · required — The number of tokens to transfer. Decimal string, e.g. "1500.0"; up to the currency's balance_decimals. Scaled to an integer only inside the signature. - `signature` · lite `s` · object Signature · required — The signature of the transfer Fields: see [Signature](/reference/types.md#signature); listed in full under `signature` on reference/rpc/login_wallet.md, earlier in this file. - `transfer_type` · lite `tt` · enum TransferType · required — The type of transfer Values: `UNSPECIFIED`, `STANDARD`, `FAST_ARB_DEPOSIT`, `FAST_ARB_WITHDRAWAL`, `NON_NATIVE_BRIDGE_DEPOSIT`, `NON_NATIVE_BRIDGE_WITHDRAWAL`, `ADHOC_INCENTIVE`, `REFERRAL_INCENTIVE`, `TRADING_DEPOSIT_YIELD_INCENTIVE`, `TGE_VESTING`, `TGE_AIRDROP`, `FEEDBACK_REWARD` ([details](/reference/enums.md#transfertype)). - `transfer_metadata` · lite `tm` · string · optional — The metadata of the transfer - `from_wallet_type` · lite `fw` · enum WalletType · optional — The wallet type of the from account or sub-account Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). - `to_wallet_type` · lite `tw` · enum WalletType · optional — The wallet type of the to account or sub-account Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). ## Response Body type `ApiTransferResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object ApiTransferAck · required — The Transfer response object - `result.ack` · lite `a` · bool · required — True when the exchange has processed the transfer. If true, a `tx_id` will be returned. If false, an error will be returned. - `result.tx_id` · lite `ti` · string (uint64) · required — The transaction ID of the transfer. This is only returned if the transfer is successful. ## 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) · `4000` InsufficientBalanceToTransfer (400) · `4002` TransferFailedReasonUnrefined (400) · `4004` BothTransferWalletTypeMustBeProvided (400) · `4005` InvalidWalletTypeForFundingAccount (400) · `4006` InvalidWalletTypeForSubAccount (400) · `4007` DuplicatedTransfer (400) · `4008` CurrencyNotAllowedInWallet (400) · `4009` UnspecifiedTransferType (400) · `4010` WithdrawalWalletNotSupported (400) · `4011` CVRZeroNotAllowedInFuturesWallet (400) · `4012` CollateralLimitExceeded (400) · `4014` CurrencyTransferNotAllowed (400) · `4015` NoTransferPermission (403) · `4016` TransferWithdrawalBlocked (403) · `4018` GrvtExternalTransferNotAllowed (400) · `4019` WithdrawalWalletUnderReview (400) · `4020` CurrencyNotEnabledAsCollateral (400) · `4021` InsufficientFundingVaultShares (400) · `4022` InsufficientTradingVaultShares (400) · `4023` VaultShareTransferRoute (400) · `5000` InvalidTransferMetadata (400) · `5001` InvalidTransferProvider (400) · `5002` InvalidDirection (400) · `5003` InvalidEndpoint (400) · `5004` FundingAccountDoesntExist (400) · `5005` InvalidChainID (400) · `7100` UnknownTransactionType (500) · `7101` TransferAccountNotFound (400) · `7102` TransferSubAccountNotFound (400) · `7103` ChargedTradingFeeBelowConfigMinimum (500) · `7104` TransferSubAccountNotUnderAccount (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.transfer( from_account_id=os.environ["GRVT_MAIN_ACCOUNT_ID"], from_sub_account_id="0", to_account_id=os.environ["GRVT_MAIN_ACCOUNT_ID"], to_sub_account_id=os.environ["GRVT_SUB_ACCOUNT_ID"], currency="USDT", num_tokens=Decimal("1500.25"), transfer_type=e.TransferType("STANDARD"), ) 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 `transfer` 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/transfer" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/transfer_history`, or `/lite/v1/transfer_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/transfer_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 | `transfer.transfer_history` (`RPCTransferHistoryV1`) | ## Request Body type `ApiTransferHistoryRequest`. Fields the server fills are left out. - `currency` · lite `c` · string[] · required — The token currency to query for, if nil or empty, return all transfers. Otherwise, only entries matching the filter will be returned - `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 page size for a single response. Defaults to 500; Max 1000. This caps one page only — omitting it does NOT return everything, it applies the 500 default. To get the full result set, follow the `next` cursor until it is empty. - `cursor` · lite `c1` · string · optional — The cursor to indicate when to start the next query from - `tx_id` · lite `ti` · string (uint64) · optional, default `0` — The transaction ID to query for - `main_account_id` · lite `ma` · string (0x address) · optional — Main account ID being queried. By default, applies the requestor's main account ID. - `transfer_types` · lite `tt` · enum TransferType[] · optional, default `[]` — The transfer type to filters for. If the list is empty, return all transfer types. Values: `UNSPECIFIED`, `STANDARD`, `FAST_ARB_DEPOSIT`, `FAST_ARB_WITHDRAWAL`, `NON_NATIVE_BRIDGE_DEPOSIT`, `NON_NATIVE_BRIDGE_WITHDRAWAL`, `ADHOC_INCENTIVE`, `REFERRAL_INCENTIVE`, `TRADING_DEPOSIT_YIELD_INCENTIVE`, `TGE_VESTING`, `TGE_AIRDROP`, `FEEDBACK_REWARD` ([details](/reference/enums.md#transfertype)). ## Response Body type `ApiTransferHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object TransferHistory[] · required — The transfer history matching the request account - `result[].tx_id` · lite `ti` · string (uint64) · required — The transaction ID of the transfer - `result[].from_account_id` · lite `fa` · string (0x address) · required — The account to transfer from - `result[].from_sub_account_id` · lite `fs` · string (uint64) · required — The sub-account to transfer from (0 if transferring from main account) - `result[].to_account_id` · lite `ta` · string (0x address) · required — The account to deposit into - `result[].to_sub_account_id` · lite `ts` · string (uint64) · required — The sub-account to transfer to (0 if transferring to main account) - `result[].currency` · lite `c` · string · required — The token currency to transfer - `result[].num_tokens` · lite `nt` · string · required — The number of tokens to transfer - `result[].signature` · lite `s` · object Signature · required — The signature of the transfer - `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[].event_time` · lite `et` · string (int64 unix ns) · required — The timestamp of the transfer in unix nanoseconds - `result[].transfer_type` · lite `tt` · enum TransferType · required — The type of transfer Values: `UNSPECIFIED`, `STANDARD`, `FAST_ARB_DEPOSIT`, `FAST_ARB_WITHDRAWAL`, `NON_NATIVE_BRIDGE_DEPOSIT`, `NON_NATIVE_BRIDGE_WITHDRAWAL`, `ADHOC_INCENTIVE`, `REFERRAL_INCENTIVE`, `TRADING_DEPOSIT_YIELD_INCENTIVE`, `TGE_VESTING`, `TGE_AIRDROP`, `FEEDBACK_REWARD` ([details](/reference/enums.md#transfertype)). - `result[].transfer_metadata` · lite `tm` · string · required — The metadata of the transfer - `result[].from_wallet_type` · lite `fw` · enum WalletType · required — The wallet type of the from account or sub-account Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). - `result[].to_wallet_type` · lite `tw` · enum WalletType · required — The wallet type of the to account or sub-account Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). - `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.transfer_history( currency=[ "USDT", "USDC", ], 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/transfer_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/withdrawal_fee`, or `/lite/v1/withdrawal_fee` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/withdrawal_fee` 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 | `transfer.get_withdrawal_fee` (`RPCGetWithdrawalFeeV1`) | ## Request Body type `ApiWithdrawalFeeRequest`. Fields the server fills are left out. - `token_currency` · lite `tc` · integer (uint16) · required — Currency ID to express the withdrawal fee in (e.g. USDT id 3). ## Response Body type `ApiWithdrawalFeeResponse` (the same object is the JSON-RPC `result` over WebSocket). - `withdrawal_fee` · lite `wf` · string · required — The withdrawal fee. Decimal string, e.g. "1500.0"; up to the currency's balance_decimals. - `token_currency` · lite `tc` · string · required — The currency the withdrawal fee is expressed in. ## Errors Errors come back as `{"code", "message", "status"}` (lite `{"c", "m", "s"}`) with the HTTP status. Codes this call can return, as code, name (HTTP status) ([all error codes](/reference/errors.md)): `1002` InternalServer (500) · `1003` InvalidRequest (400) · `1006` RateLimit (429, retryable) · `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_withdrawal_fee( token_currency=3, ) 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/withdrawal_fee" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/withdrawal`, or `/lite/v1/withdrawal` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/withdrawal` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`Withdrawal`](/reference/signing/Withdrawal.md) / [`WithdrawalV2`](/reference/signing/WithdrawalV2.md). Withdrawal when the currency id fits uint8 (\<= 255), else WithdrawalV2. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `transfer.withdrawal` (`RPCWithdrawalV1`) | ## Request Body type `ApiWithdrawalRequest`. Fields the server fills are left out. - `from_account_id` · lite `fa` · string (0x address) · required — The main account to withdraw from - `to_eth_address` · lite `te` · string (0x address) · required — The Ethereum wallet to withdraw into - `currency` · lite `c` · string · required — The token currency to withdraw - `num_tokens` · lite `nt` · string · required — The number of tokens to withdraw. Decimal string, e.g. "1500.0"; up to the currency's balance_decimals. Scaled to an integer only inside the signature. - `signature` · lite `s` · object Signature · required — The signature of the withdrawal Fields: see [Signature](/reference/types.md#signature); listed in full under `signature` on reference/rpc/login_wallet.md, earlier in this file. ## Response Body type `AckResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object Ack · required — The Ack Object - `result.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) · `1006` RateLimit (429, retryable) · `1008` IPNotWhitelisted (401) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `4010` WithdrawalWalletNotSupported (400) · `4014` CurrencyTransferNotAllowed (400) · `4016` TransferWithdrawalBlocked (403) · `4019` WithdrawalWalletUnderReview (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.withdrawal( from_account_id=os.environ["GRVT_MAIN_ACCOUNT_ID"], to_eth_address="0x1111111111111111111111111111111111111111", currency="USDT", num_tokens=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 `withdrawal` 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/withdrawal" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/withdrawal_history`, or `/lite/v1/withdrawal_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/withdrawal_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 | `transfer.withdrawal_history` (`RPCWithdrawalHistoryV1`) | ## Request Body type `ApiWithdrawalHistoryRequest`. Fields the server fills are left out. - `currency` · lite `c` · string[] · required — The token currency to query for, if nil or empty, return all withdrawals. Otherwise, only entries matching the filter will be returned - `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 page size for a single response. Defaults to 500; Max 1000. This caps one page only — omitting it does NOT return everything, it applies the 500 default. To get the full result set, follow the `next` cursor until it is empty. - `cursor` · lite `c1` · string · optional — The cursor to indicate when to start the next query from - `main_account_id` · lite `ma` · string (0x address) · optional — Main account ID being queried. By default, applies the requestor's main account ID. ## Response Body type `ApiWithdrawalHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object WithdrawalHistory[] · required — The withdrawals history matching the request account - `result[].tx_id` · lite `ti` · string (uint64) · required — The transaction ID of the withdrawal - `result[].from_account_id` · lite `fa` · string (0x address) · required — The sub-account to withdraw from - `result[].to_eth_address` · lite `te` · string (0x address) · required — The ethereum address to withdraw to - `result[].currency` · lite `c` · string · required — The token currency to withdraw - `result[].num_tokens` · lite `nt` · string · required — The number of tokens to withdraw - `result[].signature` · lite `s` · object Signature · required — The signature of the withdrawal Fields: see [Signature](/reference/types.md#signature); listed in full under `result[].signature` on reference/rpc/transfer_history.md, earlier in this file. - `result[].event_time` · lite `et` · string (int64 unix ns) · required — The timestamp of the withdrawal in unix nanoseconds - `result[].l_1_hash` · lite `l1` · string · optional — The finalized withdrawal transaction hash on L1, empty if the withdrawal is 'pending'. - `result[].l_2_hash` · lite `l2` · string · required — The transaction hash on L2 - `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.withdrawal_history( currency=[ "USDT", "USDC", ], 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/withdrawal_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 ([`deposit_history`](/reference/rpc/deposit_history.md)) for what you missed. | | Contract id | `transfer.deposit` (`StreamDepositV1`) | ## Selector Grammar ``, e.g. ``. Parts: - `main_account_id` · address — The main account ID to request for ## Frame Type `WSDepositFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.deposit`. - `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 Deposit · required — The Deposit object - `feed.tx_hash` · lite `th` · string (uint256) · required — The hash of the bridgemint event producing the deposit - `feed.to_account_id` · lite `ta` · string (0x address) · required — The account to deposit into - `feed.currency` · lite `c` · string · required — The token currency to deposit - `feed.num_tokens` · lite `nt` · string · required — The number of tokens to deposit - `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)): `1001` Forbidden (403) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (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.deposit_stream(main_account_id=os.environ["GRVT_MAIN_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.deposit", "selectors": ["$GRVT_MAIN_ACCOUNT_ID"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.deposit", "s1": ["$GRVT_MAIN_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/streams/transfer.md # Transfer stream | | | |---|---| | SDK | `client.transfer_stream(...)` | | Channel | `v1.transfer` 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 ([`transfer_history`](/reference/rpc/transfer_history.md)) for what you missed. | | Contract id | `transfer.transfer` (`StreamTransferV1`) | ## Selector Grammar `[-]`, e.g. `-`. Parts: - `main_account_id` · address — The main account ID to request for - `sub_account_id` · uint64, optional — The sub-account ID to request for ## Frame Type `WSTransferFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.transfer`. - `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 TransferHistory · required — The transfer history matching the requested filters Fields: see [TransferHistory](/reference/types.md#transferhistory); listed in full under `result[]` on reference/rpc/transfer_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)): `1001` Forbidden (403) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (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.transfer_stream(main_account_id=os.environ["GRVT_MAIN_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.transfer", "selectors": ["$GRVT_MAIN_ACCOUNT_ID"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.transfer", "s1": ["$GRVT_MAIN_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/streams/withdrawal.md # Withdrawal stream | | | |---|---| | SDK | `client.withdrawal_stream(...)` | | Channel | `v1.withdrawal` 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 ([`withdrawal_history`](/reference/rpc/withdrawal_history.md)) for what you missed. | | Contract id | `transfer.withdrawal` (`StreamWithdrawalV1`) | ## Selector Grammar ``, e.g. ``. Parts: - `main_account_id` · address — The main account ID to request for ## Frame Type `WSWithdrawalFeedDataV1`. - `stream` · lite `s` · string · required — The stream this frame belongs to, e.g. `v1.withdrawal`. - `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 Withdrawal · required — The Withdrawal object - `feed.from_account_id` · lite `fa` · string (0x address) · required — The sub-account to withdraw from - `feed.to_eth_address` · lite `te` · string (0x address) · required — The ethereum address to withdraw to - `feed.currency` · lite `c` · string · required — The token currency to withdraw - `feed.num_tokens` · lite `nt` · string · required — The number of tokens to withdraw - `feed.signature` · lite `s` · object Signature · required — The signature of the withdrawal Fields: see [Signature](/reference/types.md#signature); listed in full under `result[].signature` on reference/rpc/transfer_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)): `1001` Forbidden (403) · `1008` IPNotWhitelisted (401) · `1101` InvalidFeedFormat (400) · `1102` PrimarySelectorParts (400) · `1103` SecondarySelectorParts (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.withdrawal_stream(main_account_id=os.environ["GRVT_MAIN_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.withdrawal", "selectors": ["$GRVT_MAIN_ACCOUNT_ID"], "use_global_sequence_number": true }, "id": 1 } ``` With lite field names: ```json { "j": "2.0", "m": "subscribe", "p": { "s": "v1.withdrawal", "s1": ["$GRVT_MAIN_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/vault_investor_summary.md # Vault investor summary | | | |---|---| | SDK | `client.vault_investor_summary(...)` | | HTTP | `POST https://trades./full/v1/vault_investor_summary`, or `/lite/v1/vault_investor_summary` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_investor_summary` 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 | `vault.vault_investor_summary` (`RPCVaultInvestorSummaryV1`) | ## Request Body type `ApiVaultInvestorSummaryRequest`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · optional — The unique identifier of the vault to fetch the summary for. ## Response Body type `ApiVaultInvestorSummaryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `vault_investor_summary` · lite `vi` · object VaultInvestorSummary[] · required — The summary of investments in the vault. - `vault_investor_summary[].sub_account_id` · lite `sa` · string (uint64) · required — The unique identifier of the vault sub-account. - `vault_investor_summary[].num_lp_tokens` · lite `nl` · string · required — The number of vault LP tokens the investor holds: those in the funding account plus those in every sub-account. - `vault_investor_summary[].avg_entry_price` · lite `ae` · string · required — The average entry price (in USD) of the investor's vault LP tokens: the investor's invested notional divided by numLPTokens. - `vault_investor_summary[].current_price` · lite `cp` · string · required — The current price (in USD) of the vault LP tokens. - `vault_investor_summary[].total_equity` · lite `te` · string · required — The vault's total equity (in USD). The investor's holding is investorEquity. - `vault_investor_summary[].all_time_realized_pnl` · lite `at` · string · required — The all-time realized PnL (in USD) that the investor has received from the vault. - `vault_investor_summary[].pending_redemption` · lite `pr` · object VaultRedemption · optional — The singleton pending redemption (omitted if none). - `vault_investor_summary[].pending_redemption.num_lp_tokens` · lite `nl` · string · required — The number of LP Tokens requested for redemption. - `vault_investor_summary[].pending_redemption.request_valuation` · lite `rv` · string · required — The valuation (in USD) of the redemption request. - `vault_investor_summary[].pending_redemption.request_time` · lite `rt` · string (int64 unix ns) · required — Set by the server. Time at which the redemption request was received by Grvt in unix nanoseconds - `vault_investor_summary[].pending_redemption.max_redemption_period_timestamp` · lite `mr` · string (int64 unix ns) · required — Set by the server. Time in unix nanoseconds, beyond which the request will be force-redeemed. - `vault_investor_summary[].pending_redemption.cancel_blocked` · lite `cb` · bool · optional, default `true` — Omitted for redemption requests to non-cross exchange vaults. True if cancellation is blocked within the CEV allocation allowance for the user's current tier (e.g. because the user has already transferred out the spot balance underlying the redemption request). - `vault_investor_summary[].pending_redemption.to_currency` · lite `tc` · string · required — The currency the request pays into the investor's funding account: the vault's investment currency, unless the request converts. - `vault_investor_summary[].pending_redemption.exchange_rate` · lite `er` · string · required — The signed rate the request is paid at, `to_currency` per unit of the vault's investment currency. 1 when the request does not convert. - `vault_investor_summary[].can_burn` · lite `cb` · bool · optional, default `true` — True if the requesting account is authorized to burn tokens on this vault, omitted otherwise. - `vault_investor_summary[].num_lp_tokens_locked` · lite `nl1` · string · required — The number of the investor's vault LP tokens still within the vault's minimum investment period. - `vault_investor_summary[].num_lp_tokens_redeemable` · lite `nl2` · string · required — The number of vault LP tokens the investor can request to redeem now: those past the minimum investment period, less any pending redemption. - `vault_investor_summary[].locked_lots` · lite `ll` · object VaultLpLotView[] · required — The investor's vault LP tokens within the minimum investment period, by the time they unlock (earliest first). - `vault_investor_summary[].locked_lots[].unlock_time` · lite `ut` · string (int64 unix ns) · required — Time in unix nanoseconds from which these LP tokens can be redeemed. - `vault_investor_summary[].locked_lots[].num_lp_tokens` · lite `nl` · string · required — The number of LP tokens in the lot. - `vault_investor_summary[].share_balances` · lite `sb` · object VaultShareBalances · required — Where the investor's vault LP tokens sit: the funding account and the sub-accounts. Fields: see [VaultShareBalances](/reference/types.md#vaultsharebalances); listed in full under `result.vault_investments[].share_balances` on reference/rpc/aggregated_account_summary.md, earlier in this file. - `vault_investor_summary[].trading_balances` · lite `tb` · object VaultShareTradingBalance[] · required — One entry per sub-account holding the vault's LP tokens. Empty when no sub-account holds any. - `vault_investor_summary[].trading_balances[].sub_account_id` · lite `sa` · string (uint64) · required — The sub-account. - `vault_investor_summary[].trading_balances[].num_lp_tokens` · lite `nl` · string · required — The vault LP tokens in the sub-account. - `vault_investor_summary[].trading_balances[].equity` · lite `e` · string · required — The current valuation (in USD) of the sub-account's vault LP tokens. - `vault_investor_summary[].trading_balances[].available_to_transfer` · lite `at` · string · required — An estimate of the vault LP tokens that can move back to the funding account without failing the sub-account's withdrawal checks. - `vault_investor_summary[].trading_balances[].margin_balance_usd` · lite `mb` · string · required — What the vault LP tokens add to the sub-account's margin (in USD): equity times the collateral value ratio. 0 when they don't count as collateral. - `vault_investor_summary[].investor_equity` · lite `ie` · string · required — The current valuation (in USD) of all the investor's vault LP tokens: numLPTokens times currentPrice. - `vault_investor_summary[].unrealized_pnl` · lite `up` · string · required — The investor's unrealized PnL (in USD): investorEquity less the investor's invested notional. ## 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) · `7000` InvalidVaultID (400) · `7007` InvestorNotVaultLP (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.vault_investor_summary() 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/vault_investor_summary" \ -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/vault_investor_summary" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data '{}' ``` ===== reference/rpc/vault_conversion_rate.md # Vault conversion rate Sign this rate as `exchange_rate`: any rate at or below it passes while the quote is valid. | | | |---|---| | SDK | `client.vault_conversion_rate(...)` | | HTTP | `POST https://trades./full/v1/vault_conversion_rate`, or `/lite/v1/vault_conversion_rate` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_conversion_rate` 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 | `vault.vault_conversion_rate` (`RPCVaultConversionRateV1`) | ## Request Body type `ApiVaultConversionRateRequest`. Fields the server fills are left out. - `from_currency` · lite `fc` · string · required — The currency converted from. - `to_currency` · lite `tc` · string · required — The currency converted into. - `from_num_tokens` · lite `fn` · string · optional, default `0` — Optional amount of `fromCurrency`. When set, the response estimates what it converts into. ## Response Body type `ApiVaultConversionRateResponse` (the same object is the JSON-RPC `result` over WebSocket). - `from_currency` · lite `fc` · string · required — The currency converted from. - `to_currency` · lite `tc` · string · required — The currency converted into. - `exchange_rate` · lite `er` · string · required — The highest rate accepted now, `toCurrency` per unit of `fromCurrency`, floored to 9 decimal places. It is 1 when both currencies are the same. - `spot_rate` · lite `sr` · string · required — The current spot rate from the latest oracle prices, 9 decimal places. - `fee_rate_centi_beeps` · lite `fr` · integer (uint32) · required — The conversion fee configured for the pair, in centibeeps (1 = 0.0001%). - `window_seconds` · lite `ws` · integer (uint32) · required — The length of the window the rate is the highest of, in seconds. - `valid_until` · lite `vu` · string (int64 unix ns) · required — When the price sample the rate comes from leaves the window, in unix nanoseconds. Show a validity no longer than this. - `event_time` · lite `et` · string (int64 unix ns) · required — The time of the newest oracle price the rate uses, in unix nanoseconds. - `from_num_tokens` · lite `fn` · string · optional — The amount of `fromCurrency` the request named, if any. - `to_num_tokens` · lite `tn` · string · optional — What `fromNumTokens` converts into at `exchangeRate`, floored to `toCurrency` decimals. Omitted without `fromNumTokens`. ## 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) · `1007` UnsupportedCurrency (404) · `1008` IPNotWhitelisted (401) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `7019` VaultConversionPriceStale (400) · `7801` CurrencyNotConvertible (400) · `7802` PriceOutOfConvertBand (400) · `7805` InexactConversion (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.vault_conversion_rate( from_currency="USDT", to_currency="USDC", ) 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/vault_conversion_rate" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v2/vault_invest`, or `/lite/v2/vault_invest` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v2/vault_invest` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`VaultInvestV3`](/reference/signing/VaultInvestV3.md). always VaultInvestV3. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `vault.vault_invest` (`RPCVaultInvestV2`) | ## Request Body type `ApiVaultInvestV2Request`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to invest in. - `from_sub_account_id` · lite `fs` · string (uint64) · required — The sub-account to invest from. 0 means the funding account. - `from_wallet_type` · lite `fw` · enum WalletType · required — FUNDING when `fromSubAccountID` is 0, otherwise SPOT or FUTURES. Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). - `from_currency` · lite `fc` · string · required — The currency debited from the source wallet. - `from_num_tokens` · lite `fn` · string · required — The amount debited from the source wallet, in `fromCurrency`. - `to_currency` · lite `tc` · string · required — The currency the vault receives. This must be the vault's investment currency. - `exchange_rate` · lite `er` · string · required — The signed rate, `toCurrency` per unit of `fromCurrency`, up to 9 decimal places. Exactly 1 when both currencies are the same. - `signature` · lite `s` · object Signature · required — The `VaultInvestV3` signature of the investing account. The signer needs the vault investor permission on the main account and, for a sub-account source, the transfer permission on that sub-account. Fields: see [Signature](/reference/types.md#signature); listed in full under `signature` on reference/rpc/login_wallet.md, earlier in this file. ## Response Body type `ApiVaultInvestV2Response` (the same object is the JSON-RPC `result` over WebSocket). - `ack` · lite `a` · bool · required — Whether the investment was accepted. - `tx_id` · lite `ti` · string (uint64) · required — The transaction ID of the investment once risk confirmed it. 0 when the investment was queued. - `enqueued` · lite `e` · bool · optional — Cross-exchange vaults only: true when the vault was locked and the investment was queued. ## 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) · `1007` UnsupportedCurrency (404) · `1008` IPNotWhitelisted (401) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `1012` InvalidSignatureChainID (400) · `1014` GatewayTimeout (504, retryable) · `2000` SignerUnauthorized (403) · `2001` SignatureExpired (403) · `2002` SignatureDoesNotMatchPayload (403) · `2004` SessionKeySignerExpired (403) · `2005` SignatureInvalidV (403) · `2006` SignatureInvalidRSLength (403) · `2007` SignatureSIsNotCurveLowerHalf (403) · `2008` SignatureExpirationTooLong (403) · `4000` InsufficientBalanceToTransfer (400) · `4008` CurrencyNotAllowedInWallet (400) · `7000` InvalidVaultID (400) · `7003` VaultNotActive (400) · `7004` InvestmentExceedsCap (400) · `7012` InvalidVaultInvestorID (400) · `7013` CrossExchangeVaultNotSupported (400) · `7014` OnlyAllowedToInvestInVaultInvestmentCurrency (400) · `7017` VaultConversionRateNotAllowed (400) · `7018` VaultInvalidInvestSource (400) · `7019` VaultConversionPriceStale (400) · `7027` VaultConversionZeroOutput (400) · `7028` VaultInvestAlreadyExecuted (400) · `7035` VaultInvestSourceNeedsSpotTransfers (400) · `7101` TransferAccountNotFound (400) · `7102` TransferSubAccountNotFound (400) · `7801` CurrencyNotConvertible (400) · `7802` PriceOutOfConvertBand (400) · `7803` MissingIndexPrice (400) · `7805` InexactConversion (400) · `7811` NegativeBalance (400) · `7812` ValueOverflow (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.vault_invest( vault_id="4211543862", from_sub_account_id="0", from_wallet_type=e.WalletType("FUNDING"), from_currency="USDT", from_num_tokens=Decimal("1000.5"), to_currency="USDC", exchange_rate=Decimal("0.9998"), ) 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 `vault_invest` 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/vault_invest" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v2/vault_redeem`, or `/lite/v2/vault_redeem` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v2/vault_redeem` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`VaultRedeemV3`](/reference/signing/VaultRedeemV3.md). always VaultRedeemV3. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `vault.vault_redeem` (`RPCVaultRedeemV2`) | ## Request Body type `ApiVaultRedeemV2Request`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to redeem from. - `from_currency` · lite `fc` · string · required — The currency the vault pays. This must be the vault's investment currency. - `to_currency` · lite `tc` · string · required — The currency paid into the funding account: the investment currency, or another currency converted at `exchangeRate`. - `num_tokens` · lite `nt` · string · required — The number of shares to redeem. - `exchange_rate` · lite `er` · string · required — The signed rate, `toCurrency` per unit of `fromCurrency`, up to 9 decimal places. Exactly 1 when both currencies are the same. - `signature` · lite `s` · object Signature · required — The `VaultRedeemV3` signature of the redeeming account. The signer needs the vault investor permission on the main account. Fields: see [Signature](/reference/types.md#signature); listed in full under `signature` on reference/rpc/login_wallet.md, earlier in this file. ## 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 `result` on reference/rpc/withdrawal.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) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `1012` InvalidSignatureChainID (400) · `2000` SignerUnauthorized (403) · `2001` SignatureExpired (403) · `2002` SignatureDoesNotMatchPayload (403) · `2004` SessionKeySignerExpired (403) · `2005` SignatureInvalidV (403) · `2006` SignatureInvalidRSLength (403) · `2007` SignatureSIsNotCurveLowerHalf (403) · `2008` SignatureExpirationTooLong (403) · `7000` InvalidVaultID (400) · `7001` InsufficientVaultLPToken (400) · `7002` OngoingRedemption (400) · `7007` InvestorNotVaultLP (400) · `7008` OnlyAllowedToRedeemInVaultInvestmentCurrency (400) · `7009` InsufficientInvestorTokenBalanceForRedemption (400) · `7015` VaultLpTokensLocked (400) · `7017` VaultConversionRateNotAllowed (400) · `7019` VaultConversionPriceStale (400) · `7027` VaultConversionZeroOutput (400) · `7801` CurrencyNotConvertible (400) · `7802` PriceOutOfConvertBand (400) · `7803` MissingIndexPrice (400) · `7805` InexactConversion (400) · `7812` ValueOverflow (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.vault_redeem( vault_id="4211543862", from_currency="USDC", to_currency="USDT", num_tokens=Decimal("12.345678"), exchange_rate=Decimal("1.0001"), ) 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 `vault_redeem` 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/vault_redeem" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- </full/v1/vault_redeem_cancel`, or `/lite/v1/vault_redeem_cancel` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_redeem_cancel` 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 | `vault.vault_redeem_cancel` (`RPCVaultRedeemCancelV1`) | ## Request Body type `ApiVaultRedeemCancelRequest`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to cancel the redemption from. ## 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 `result` on reference/rpc/withdrawal.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) · `1014` GatewayTimeout (504, retryable) · `1015` ServiceUnavailable (503, retryable) · `7000` InvalidVaultID (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.vault_redeem_cancel( vault_id="3477045127917224", ) 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/vault_redeem_cancel" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- < Only for vault managers. Other accounts get error 1001. | | | |---|---| | SDK | `client.vault_manager_investment_history(...)` | | HTTP | `POST https://trades./full/v1/vault_manager_investor_history`, or `/lite/v1/vault_manager_investor_history` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_manager_investor_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 | `vault.vault_manager_investment_history` (`RPCVaultManagerInvestmentHistoryV1`) | ## Request Body type `ApiQueryVaultManagerInvestorHistoryRequest`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to filter by - `only_own_investments` · lite `oo` · bool · required — Whether to only return investments made by the manager - `start_time` · lite `st` · string (int64 unix ns) · optional, default `0` — Optional. Start time in unix nanoseconds - `end_time` · lite `et` · string (int64 unix ns) · optional, default `now()` — Optional. End time in unix nanoseconds ## Response Body type `ApiQueryVaultManagerInvestorHistoryResponse` (the same object is the JSON-RPC `result` over WebSocket). - `result` · lite `r` · object ApiVaultInvestorHistory[] · required — The list of vault investor history belong to the manager - `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 of the investor, only visible to the manager - `result[].vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault. - `result[].type` · lite `t` · enum VaultInvestorAction · required — The type of transaction that occurred. List of types: vaultInvest, vaultBurnLpToken, vaultRedeem Values: `UNSPECIFIED`, `VAULT_INVEST`, `VAULT_BURN_LP_TOKEN`, `VAULT_REDEEM` ([details](/reference/enums.md#vaultinvestoraction)). - `result[].price` · lite `p` · string · required — The price of the vault LP tokens at the time of the event. - `result[].size` · lite `s` · string · required — The amount of Vault LP tokens invested or redeemed. - `result[].realized_pnl` · lite `rp` · string · required — The realized PnL of the vault. - `result[].performance_fee` · lite `pf` · string · required — The performance fee of the vault. - `result[].token_currency` · lite `tc` · string · required — The vault leg's currency: the vault's investment currency, which the vault received or paid. Empty on a burn, which moves no tokens. - `result[].num_tokens` · lite `nt` · string · required — The vault leg: the tokens of tokenCurrency the vault received on an invest or paid on a redemption. 0 on a burn, and on a vaultRedeem recorded before its results carried the amount. - `result[].from_currency` · lite `fc` · string · required — The currency that left its owner: on an invest the investor's source currency (the user leg), on a redemption tokenCurrency. A row without conversion has the vault leg's currency. Empty on a burn. - `result[].from_num_tokens` · lite `fn` · string · required — The tokens of fromCurrency that left their owner: on an invest what the investor paid (the user leg), on a redemption numTokens. 0 on a burn, and on a vaultRedeem recorded before its results carried the amount. - `result[].to_currency` · lite `tc1` · string · required — The currency that reached its owner: on a redemption the investor's payout currency (the user leg), on an invest tokenCurrency. A row without conversion has the vault leg's currency. Empty on a burn. - `result[].to_num_tokens` · lite `tn` · string · required — The tokens of toCurrency that reached their owner: on a redemption what the investor received (the user leg), on an invest numTokens. 0 on a burn, and on a vaultRedeem recorded before its results carried the amount. - `result[].conversion_fee_num_tokens` · lite `cf` · string · required — The conversion fee in toCurrency: the difference between the two legs of a converting invest or redemption. 0 without conversion. - `result[].from_sub_account_id` · lite `fs` · string (uint64) · required — The trading sub-account an invest was paid from. 0 for the funding account and on other rows. - `result[].from_wallet_type` · lite `fw` · enum WalletType · required — The wallet an invest was paid from: FUNDING for the funding account, otherwise SPOT or FUTURES. Unspecified on redemptions and burns. Values: `FUNDING`, `SPOT`, `FUTURES` ([details](/reference/enums.md#wallettype)). - `result[].request_time` · lite `rt` · string (int64 unix ns) · required — On a redemption, when its redemption request was made, in unix nanoseconds. 0 when unknown and on other rows. ## 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.vault_manager_investment_history( vault_id="2312134", only_own_investments=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)): With full field names: ```sh curl -sS "https://trades.$GRVT_DOMAIN/full/v1/vault_manager_investor_history" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- < Only for vault managers. Other accounts get error 1001. Fetches the redemption queue for a vault, ordered by descending priority. **Urgent** redemption requests, defined as having been pending >90% of the manager-defined maximum redemption period, have top priority (following insertion order). **Non-urgent** redemption requests are otherwise prioritized by insertion order, **unless** they are >5x the size of the smallest redemption request. E.g., If FIFO ordering (all non-urgent) is 1k -> 50k -> 100k -> 20k -> 10k -> 25k, then priority ordering is 1k -> 10k -> 50k -> 20k -> 100k -> 25k. Only displays redemption requests that are eligible for automated redemption, i.e., have been pending for the manager-defined minimum redemption period. | | | |---|---| | SDK | `client.vault_redemption_queue(...)` | | HTTP | `POST https://trades./full/v1/vault_view_redemption_queue`, or `/lite/v1/vault_view_redemption_queue` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_view_redemption_queue` 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 | `vault.vault_redemption_queue` (`RPCVaultRedemptionQueueV1`) | ## Request Body type `ApiVaultViewRedemptionQueueRequest`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to fetch the redemption queue for. ## Response Body type `ApiVaultViewRedemptionQueueResponse` (the same object is the JSON-RPC `result` over WebSocket). - `redemption_queue` · lite `rq` · object VaultRedemptionRequest[] · required — Outstanding vault redemption requests, ordered by descending priority. Excludes requests that have not yet aged past the minimum redemption period. - `redemption_queue[].request_time` · lite `rt` · string (int64 unix ns) · required — Set by the server. Time at which the redemption request was received by Grvt in unix nanoseconds - `redemption_queue[].num_lp_tokens` · lite `nl` · string · required — The number of shares to redeem - `redemption_queue[].max_redemption_period_timestamp` · lite `mr` · string (int64 unix ns) · required — Set by the server. Time in unix nanoseconds, beyond which the request will be force-redeemed. - `redemption_queue[].age_category` · lite `ac` · enum VaultRedemptionReqAgeCategory · required — Age category of this redemption request. Values: `NORMAL`, `URGENT`, `OVERDUE`, `PRE_MIN` ([details](/reference/enums.md#vaultredemptionreqagecategory)). - `redemption_queue[].is_manager` · lite `im` · bool · optional — `true` if this request belongs to the vault manager, omitted otherwise. - `redemption_queue[].eligible_for_auto_redemption_timestamp` · lite `ef` · string (int64 unix ns) · required — Set by the server. Time in unix nanoseconds, beyond which the request will be eligible for automated redemption. - `redemption_queue[].from_currency` · lite `fc` · string · required — The currency the vault pays: the vault's investment currency. - `redemption_queue[].to_currency` · lite `tc` · string · required — The currency paid into the investor's funding account. Equal to `from_currency` when the request does not convert. - `redemption_queue[].exchange_rate` · lite `er` · string · required — The signed rate the request is paid at, `to_currency` per unit of `from_currency`. 1 when the request does not convert. - `pending_redemption_token_count` · lite `pr` · string · required — Number of shares eligible for automated redemption (held in queue for at least the minimum redemption period). - `urgent_redemption_token_count` · lite `ur` · string · required — Number of shares nearing the maximum redemption period (>= 90% of maximum redemption period). - `auto_redeemable_balance` · lite `ar` · string · required — Amount available for automated redemption request servicing (in USD). - `share_price` · lite `sp` · string · required — Current share price (in USD). - `pre_min` · lite `pm` · object PreMinRedemptions · required — Dedicated section for requests yet to wait at least the minimum redemption period. - `pre_min.requests` · lite `r` · object VaultRedemptionRequest[] · required — Pre-minimum-age redemption requests, ordered by age (first element is the oldest request that is pre-minimum-age). Fields: same as `redemption_queue[]` above. - `pre_min.token_count` · lite `tc` · string · required — Number of shares in the pre-minimum-age section of the vault's redemption queue. ## 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) · `7000` InvalidVaultID (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.vault_redemption_queue( vault_id="3477045127917224", ) 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/vault_view_redemption_queue" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- < Only for vault managers. Other accounts get error 1001. | | | |---|---| | SDK | `client.vault_burn_tokens(...)` | | HTTP | `POST https://trades./full/v1/vault_burn_tokens`, or `/lite/v1/vault_burn_tokens` for [lite names](/guides/environments.md#encoding-full-or-lite) (the SDKs' default) | | WebSocket | method `v1/vault_burn_tokens` on `wss://trades./ws/full`, or `/ws/lite` for lite names | | Auth | Session required ([Authentication](/guides/authentication.md)) | | Signed | `signature` is signed: [`VaultBurnLpToken`](/reference/signing/VaultBurnLpToken.md). always VaultBurnLpToken. ([Signing](/guides/signing.md)) | | Retries | Write: never retried automatically ([why](/guides/errors-and-retries.md)) | | Contract id | `vault.vault_burn_tokens` (`RPCVaultBurnTokensV1`) | ## Request Body type `ApiVaultBurnTokensRequest`. Fields the server fills are left out. - `vault_id` · lite `vi` · string (uint64) · required — The unique identifier of the vault to burn tokens from. - `currency` · lite `c` · string · required — The currency used for the burn. This should be the vault's quote currency. - `num_tokens` · lite `nt` · string · required — The number of tokens to burn. - `signature` · lite `s` · object Signature · required — The digital signature from the investing account. This signature must be generated by the main account ID and is used to verify the authenticity of the request. The signature must comply with AccountPermExternalTransfer permission. Fields: see [Signature](/reference/types.md#signature); listed in full under `signature` on reference/rpc/login_wallet.md, earlier in this file. ## 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 `result` on reference/rpc/withdrawal.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) · `1009` APIEndpointTemporarilyDeactivated (503, retryable) · `2000` SignerUnauthorized (403) · `2001` SignatureExpired (403) · `2002` SignatureDoesNotMatchPayload (403) · `2004` SessionKeySignerExpired (403) · `2005` SignatureInvalidV (403) · `2006` SignatureInvalidRSLength (403) · `2007` SignatureSIsNotCurveLowerHalf (403) · `2008` SignatureExpirationTooLong (403) · `7000` InvalidVaultID (400) · `7005` BurningMoreVaultTokensThanOwned (400) · `7006` BurningTokenWhileActiveRedemption (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.vault_burn_tokens( vault_id="4211543862", currency="USDT", num_tokens=Decimal("100.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 `vault_burn_tokens` 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/vault_burn_tokens" \ -H "Content-Type: application/json" \ -H "Cookie: gravity=$GRVT_COOKIE" \ -H "X-Grvt-Account-Id: $GRVT_ACCOUNT_ID" \ --data @- <@\ | | 1102 | `ErrPrimarySelectorParts` | 400 | no | Wrong number of primary selectors | | 1103 | `ErrSecondarySelectorParts` | 400 | no | Wrong number of secondary selectors | | 1104 | `ErrDuplicatePrimarySelector` | 400 | no | Attempted to subscribe to same primary selector twice, in same request | | 1105 | `ErrInvalidSubscribeParams` | 400 | no | Subscribe params are invalid | | 1106 | `ErrInvalidUnsubscribeParams` | 400 | no | Unsubscribe params are invalid | | 1107 | `ErrInvalidJSONRPCVersion` | 400 | no | JSON RPC version must be 2.0 | | 1200 | `ErrRPCMethodNotFound` | 404 | no | RPC method not found | | 1300 | `ErrJSONRPCIDExceedsUint32` | 400 | no | JSON RPC ID exceeds uint32 | ## Permissions and account IDs (1400–1500) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 1400 | `ErrNoTradePermission` | 403 | no | Signer does not have trade permission | | 1500 | `ErrMainAccIDInvalid` | 400 | no | Request must contain a valid main account ID | ## Signatures and order ownership (2000–2008) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2000 | `SignerUnauthorized` | 403 | no | Signature is from an unauthorized signer | | 2001 | `SignatureExpired` | 403 | no | Signature has expired | | 2002 | `SignatureDoesNotMatchPayload` | 403 | no | Signature does not match payload | | 2003 | `OrderSubAccountDoesNotMatchLoggedInUser` | 403 | no | Order sub account does not match logged in user | | 2004 | `SessionKeySignerExpired` | 403 | no | Signature is from an expired session key | | 2005 | `SignatureInvalidV` | 403 | no | Signature V must be 27/28 | | 2006 | `SignatureInvalidRSLength` | 403 | no | Signature R/S must have exactly 64 characters long without 0x prefix **Note:** The message is misleading: send r and s as "0x" + 64 hex characters. Without 0x the server reads them as 0 and the signature fails to verify. | | 2007 | `SignatureSIsNotCurveLowerHalf` | 403 | no | Signature S must be in the lower half of the curve | | 2008 | `SignatureExpirationTooLong` | 403 | no | Signature exceeds maximum allowed duration. | ## Orders (2010–2091) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2010 | `OrderIDShouldBeEmpty` | 400 | no | Order ID should be empty when creating an order | | 2011 | `ClientOrderIDShouldBeSupplied` | 400 | no | Client Order ID should be supplied when creating an order | | 2012 | `ClientOrderIDOverlaps` | 400 | no | Client Order ID overlaps with existing active order | | 2013 | `ClientOrderIDRepeats` | 400 | no | Client Order ID repeats with the last order | | 2020 | `MarketOrderWithLimitPrice` | 400 | no | Market Order must always be supplied without a limit price | | 2021 | `LimitOrderWithoutLimitPrice` | 400 | no | Limit Order must always be supplied with a limit price | | 2030 | `InvalidTimeInForceOrderbook` | 400 | no | Orderbook Orders must have a TimeInForce of GTT/IOC/FOK | | 2031 | `InvalidTimeInForceRFQ` | 400 | no | RFQ Orders must have a TimeInForce of GTT/AON/IOC/FOK | | 2032 | `PostOnlyWhenTakerOrder` | 400 | no | Post Only can only be set to true for GTT/AON orders | | 2040 | `LegsEmpty` | 400 | no | Order must contain at least one leg | | 2041 | `LegsNotSorted` | 400 | no | Order Legs must be sorted by Derivative.Instrument/Underlying/BaseCurrency/Expiration/StrikePrice | | 2042 | `LegsMultipleOrderbook` | 400 | no | Orderbook Orders must contain only one leg | | 2050 | `NonEmptyState` | 400 | no | Order state must be empty upon creation | | 2051 | `ExecutionMetadataShouldBeEmpty` | 400 | no | Order execution metadata must be empty upon creation | | 2060 | `InactiveDerivative` | 400 | no | Order Legs contain one or more inactive derivative | | 2061 | `InstrumentNotSupported` | 400 | no | Unsupported Instrument Requested | | 2062 | `NumContractsUnderMinSize` | 400 | no | Order size smaller than min size | | 2063 | `NumContractsUnderMinBlockSize` | 400 | no | Order size smaller than min block size in block trade venue | | 2064 | `InvalidLimitPriceTick` | 400 | no | Invalid limit price tick | | 2065 | `InvalidContractGrainSize` | 400 | no | Order size too granular | | 2066 | `NotionalBelowMinimum` | 400 | no | Order below minimum notional. Please try again with a higher price or size. | | 2067 | `PositionClosingNotionalBelowMinimum` | 400 | no | Order below minimum notional. Please try reducing your position again with a higher price or size. | | 2070 | `LiquidationOrderNotSupported` | 400 | no | Liquidation Order is not supported | | 2080 | `InsufficientMargin` | 400 | no | Insufficient margin to create order | | 2081 | `MaximumPositionSizeExceeded` | 400 | no | Order Fill would result in exceeding maximum position size | | 2082 | `ErrFailedPreOrderCheck` | 400 | no | Pre-order check failed | | 2083 | `MaximumLeverageConfigPositionSizeExceeded` | 400 | no | Order Fill would result in exceeding maximum position size under current configurable leverage tier | | 2084 | `ErrFailedPostOrderCheck` | 400 | no | Post-order check failed | | 2090 | `MaxOpenOrdersExceeded` | 429 | no | Max open orders exceeded | | 2091 | `ErrSessionOrderReduceOnlyRequired` | 403 | no | As a precaution, only position-reducing (`reduce_only` as true) orders are currently allowed on your account. Please contact support so we can help complete the necessary checks. | ## Leverage and margin type (2100–2108) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2100 | `InvalidInitialLeverage` | 400 | no | Invalid initial leverage | | 2101 | `VaultsCannotConfigureLeverage` | 400 | no | Vaults cannot configure leverage | | 2102 | `MarginTypeChangeFailedHasOpenPosition` | 400 | no | Margin type change failed, has open position for this instrument | | 2103 | `MarginTypeChangeFailedHasOpenOrders` | 400 | no | Margin type change failed, has open orders for this instrument | | 2104 | `MarginTypeNotSupported` | 400 | no | Margin type not supported | | 2105 | `MarginTypeChangeFailed` | 400 | no | Margin type change failed | | 2107 | `NewLeverageBelowMinimum` | 400 | no | Attempted to set leverage below minimum | | 2108 | `NewLeverageAboveMaximum` | 400 | no | Attempted to set leverage above maximum | ## Trigger, RPI, ECN and RFQ orders (2110–2148) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2110 | `InvalidTriggerBy` | 400 | no | Invalid trigger by | | 2111 | `UnsupportedTriggerBy` | 400 | no | Unsupported trigger by | | 2112 | `InvalidTriggerOrder` | 400 | no | Invalid trigger order | | 2113 | `EmptyTriggerPrice` | 400 | no | Trigger price must be non-zero | | 2114 | `ErrInvalidPTPSLReduceOnly` | 400 | no | Invalid position linked TPSL orders, position linked TPSL must be a reduce-only order | | 2115 | `ErrInvalidPTPSLSize` | 400 | no | Invalid position linked TPSL orders, position linked TPSL must not have smaller size than the position | | 2116 | `ErrPTPSLOrderAlreadyExists` | 400 | no | Position linked TPSL order for this asset already exists | | 2117 | `ErrPTPSLMustBeFromWebOrMobile` | 400 | no | Position linked TPSL orders must be created from web or mobile clients | | 2118 | `InvalidTriggerPriceTick` | 400 | no | Invalid trigger price tick | | 2120 | `RPIOrderNotSupported` | 400 | no | RPI orders are not supported yet | | 2121 | `RPIOrderMustBeLimit` | 400 | no | RPI order must be a limit order | | 2122 | `RPIOrderMustBePostOnly` | 400 | no | RPI order must be post-only | | 2123 | `RPIOrderMustBeFromApiSource` | 400 | no | RPI order must be from API source | | 2130 | `ECNOrderNotSupported` | 400 | no | ECN orders are not supported yet | | 2131 | `ECNOrderMustBeGTT` | 400 | no | ECN order must be a GTT order | | 2132 | `ECNOrderMustBeLimit` | 400 | no | ECN order must be a limit order | | 2133 | `ECNOrderMustBePostOnly` | 400 | no | ECN order must be post-only | | 2134 | `ECNOrderMustBeFromApiSource` | 400 | no | ECN order must be from API source | | 2135 | `ECNOrderMustNotBeReduceOnly` | 400 | no | ECN order must not be a reduce-only order | | 2136 | `ECNOrderMustNotBeConditional` | 400 | no | ECN order must not be a conditional order | | 2141 | `RfqSubAccountDoesNotMatchLoggedInUser` | 403 | no | RFQ sub account does not match logged in user | | 2142 | `RfqInstrumentNotStablePerp` | 400 | no | RFQ instrument must be a stable perpetual | | 2143 | `RfqSizeBelowMinimum` | 400 | no | RFQ size is below the instrument minimum size | | 2144 | `RfqSizeAboveMaximum` | 400 | no | RFQ size exceeds the instrument maximum position size | | 2145 | `RfqInvalidExpiry` | 400 | no | RFQ expiry is invalid | | 2146 | `RfqAlreadyExistsForAsset` | 400 | no | An open RFQ already exists for this sub account and instrument | | 2147 | `StablePerpRequiresMultiAssetMode` | 400 | no | stable perp orders require a multi-asset-mode sub-account | | 2148 | `ErrVaultCannotTrade` | 400 | no | a vault whose investment currency is not its quote currency cannot trade | ## Bulk orders and TP/SL (2220–2246) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2220 | `ErrNoOrdersProvided` | 400 | no | No orders provided | | 2222 | `ErrNotTPSLOrder` | 400 | no | Order is not a TPSL order | | 2223 | `ErrUnsupportedBulkOrders` | 400 | no | Unsupported bulk orders type | | 2224 | `ErrInvalidOCO` | 400 | no | Invalid OCO orders | | 2225 | `ErrInvalidOCOInvalidLeg` | 400 | no | OCO orders have invalid legs | | 2226 | `ErrInvalidOCOMismatchedLegs` | 400 | no | OCO order take profit and stop loss legs must share the same instrument, size and direction | | 2227 | `ErrInvalidOSO` | 400 | no | Invalid OSO orders | | 2228 | `ErrInvalidOSOInvalidLeg` | 400 | no | OSO orders have invalid legs | | 2229 | `ErrInvalidOSOMismatchedLegs` | 400 | no | OSO orders must share the same instrument and size, with main order direction opposite to TPSL orders | | 2230 | `ErrInvalidOSOTriggerPrice` | 400 | no | OSO orders has invalid trigger price | | 2231 | `ErrInvalidPTPSL` | 400 | no | Invalid position linked TPSL orders | | 2232 | `ErrInvalidPTPSLOrderLinkage` | 400 | no | Invalid position linked TPSL orders, position linked TPSL must not have order linkage | | 2233 | `ErrBothOrderIDAndClientOrderIDProvided` | 400 | no | Both order ID and client order ID cannot be provided | | 2234 | `ErrInvalidBulkOrdersAssetMismatch` | 400 | no | Bulk create orders must have the same instrument | | 2235 | `ErrBulkOrdersMaxCountExceeded` | 400 | no | Bulk orders count exceeds the maximum allowed | | 2236 | `ErrBulkOrdersNotSupportTriggerOrder` | 400 | no | Bulk orders does not support trigger order | | 2237 | `ErrBulkOrdersNotFromApiSource` | 400 | no | Bulk orders must be from API source | | 2238 | `ErrSplitTPSLMustNotBePositionLinkedTPSL` | 400 | no | Split TPSL orders must not be position-linked TPSL | | 2239 | `ErrSplitTPSLMustBeReduceOnly` | 400 | no | Split TPSL orders must be reduce-only | | 2240 | `ErrSplitTPSLCreatesMustNotContainNonSplit` | 400 | no | If creating split TPSL orders, can only specify split TPSL orders in the creation array | | 2241 | `ErrSplitTPSLCreatesExceedsSetSize` | 400 | no | Split TPSL order count exceeds maximum allowed set size | | 2242 | `ErrSplitTPSLNotSupported` | 400 | no | Split TPSL functionality not supported; you may be using a deprecated API, or this functionality is temporarily disabled | | 2243 | `ErrSplitTPSLSetAlreadyExists` | 400 | no | Split TPSL set already exists for this asset. Please modify the existing set of split TPSL orders. | | 2244 | `ErrCreatingSplitTPSLWithoutExistingPosition` | 400 | no | Split TPSL creation only allowed for instruments with already-existing positions. | | 2245 | `ErrCreatingSplitTPSLExceedingPositionSize` | 400 | no | Split TPSL creation exceeds position size. | | 2246 | `ErrModifyingSplitTPSLMismatchedCancels` | 400 | no | Split TPSL modification requires all existing split TPSL orders to be cancelled | ## Cancel countdown, reduce-only, replace and spot orders (2300–2453) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 2300 | `CancelTTLDisabled` | 400 | no | Order cancel time-to-live settings currently disabled. | | 2301 | `CancelTTLMaxExceeded` | 400 | no | Order cancel time-to-live exceeds maximum allowed value. | | 2400 | `ReduceOnlyOrderWithNoPosition` | 400 | no | Reduce only order with no position | | 2401 | `ReduceOnlyOrderIncreaseSize` | 400 | no | Reduce only order must not increase position size | | 2402 | `ReduceOnlyOrderSizeExceeded` | 400 | no | Reduce only order size exceeds maximum allowed value | | 2413 | `ErrReplaceOrderNumOrdersMismatch` | 400 | no | Replace order failed, number of orders provided does not match the number of orders to replace | | 2450 | `ErrSpotOrderNotSupported` | 400 | no | Spot order is not supported | | 2451 | `ErrSpotOrderReduceOnlyNotSupported` | 400 | no | Spot order must not be a reduce-only order | | 2452 | `ErrSpotOrderTPSLNotSupported` | 400 | no | Spot order must not be a TPSL order | | 2453 | `ErrSpotTradingBlockedDuringSocializedLoss` | 400 | no | Spot trading is blocked during socialized loss | ## Request parameters (3000–3043) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 3000 | `ErrInvalidInstrument` | 400 | no | Instrument is invalid | | 3004 | `ErrMMConfigNotFound` | 500 | no | Instrument does not have a valid maintenance margin configuration | | 3005 | `ErrAssetUnderlyingBalDecConfigNotFound` | 500 | no | Instrument's underlying currency does not have a valid balance decimal configuration | | 3006 | `ErrAssetQuoteBalDecConfigNotFound` | 500 | no | Instrument's quote currency does not have a valid balance decimal configuration | | 3007 | `ErrNotApplicableForSpotInstrument` | 400 | no | API is not applicable for spot instruments | | 3008 | `ErrInvalidFundingAggregationTypeForStablePerp` | 400 | no | Funding rate aggregation type is not applicable for stable perp instruments | | 3011 | `ErrInvalidLimit` | 400 | no | Limit exceeds min or max value | | 3012 | `ErrInvalidCursor` | 400 | no | Cursor is invalid | | 3013 | `ErrExactLimitNotSupported` | 400 | no | Exact limit value is not supported | | 3020 | `ErrInvalidSubAccountID` | 400 | no | Sub account ID must be an uint64 integer | | 3021 | `ErrInvalidOrderID` | 400 | no | Either order ID or client order ID must be supplied | | 3030 | `ErrInvalidFeedRate` | 400 | no | Feed rate is invalid | | 3031 | `ErrInvalidDepth` | 400 | no | Depth is invalid | | 3040 | `ErrInvalidCandlestickInterval` | 400 | no | Candlestick interval is invalid | | 3041 | `ErrInvalidCandlestickType` | 400 | no | Candlestick type is invalid | | 3042 | `ErrInvalidCandlestickTypeForSpot` | 400 | no | Candlestick type is not applicable for spot instruments | | 3043 | `ErrInvalidCandlestickTypeForStablePerp` | 400 | no | Candlestick type not supported for this instrument | ## Transfers and withdrawals (4000–4023) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 4000 | `ErrInsufficientBalanceToTransfer` | 400 | no | Insufficient balance to complete transfer | | 4002 | `ErrTransferFailedReasonUnrefined` | 400 | no | Transfer failed with an unrefined failure reason, please report to GRVT | | 4004 | `ErrBothTransferWalletTypeMustBeProvided` | 400 | no | Both transfer wallet types must be provided | | 4005 | `ErrInvalidWalletTypeForFundingAccount` | 400 | no | Invalid wallet type for funding account | | 4006 | `ErrInvalidWalletTypeForSubAccount` | 400 | no | Invalid wallet type for sub account | | 4007 | `ErrDuplicatedTransfer` | 400 | no | Transfer failed because signature is an exact duplicate of another recently-observed transfer. | | 4008 | `ErrCurrencyNotAllowedInWallet` | 400 | no | Currency is not allowed in the target wallet type | | 4009 | `ErrUnspecifiedTransferType` | 400 | no | Please specify the transfer type | | 4010 | `ErrWithdrawalWalletNotSupported` | 400 | no | This wallet is not supported. Please try another wallet. | | 4011 | `ErrCVRZeroNotAllowedInFuturesWallet` | 400 | no | This currency cannot be used as collateral in a multi-asset margin futures wallet. | | 4012 | `ErrCollateralLimitExceeded` | 400 | no | Transfer would push your holdings of this currency above the per-user collateral limit. | | 4014 | `ErrCurrencyTransferNotAllowed` | 400 | no | This currency has been disabled for transfers and withdrawals. | | 4015 | `ErrNoTransferPermission` | 403 | no | Signer does not have transfer permission | | 4016 | `ErrTransferWithdrawalBlocked` | 403 | no | As a precaution, funds movements on your account are temporarily unavailable. Please contact support so we can help complete the necessary checks. | | 4018 | `ErrGrvtExternalTransferNotAllowed` | 400 | no | $GRVT is disabled for external transfer | | 4019 | `ErrWithdrawalWalletUnderReview` | 400 | no | Your wallet has been put under review. Please reach out to kyc@grvt.io for any questions. | | 4020 | `ErrCurrencyNotEnabledAsCollateral` | 400 | no | This currency is not enabled as collateral for the destination sub account. Enable it in your collateral preferences first. | | 4021 | `ErrInsufficientFundingVaultShares` | 400 | no | The funding account has fewer vault shares than requested, after reserving any pending redemption. | | 4022 | `ErrInsufficientTradingVaultShares` | 400 | no | The trading account has fewer vault shares than requested. | | 4023 | `ErrVaultShareTransferRoute` | 400 | no | Vault shares move only between your own funding account and your own multi-asset trading accounts. | ## Transfer metadata (5000–5005) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 5000 | `ErrInvalidTransferMetadata` | 400 | no | Transfer Metadata does not match the expected structure. | | 5001 | `ErrInvalidTransferProvider` | 400 | no | Transfer Provider does not match the expected provider. | | 5002 | `ErrInvalidDirection` | 400 | no | Direction of the transfer does not match the expected direction. | | 5003 | `ErrInvalidEndpoint` | 400 | no | Endpoint account ID is invalid. | | 5004 | `ErrFundingAccountDoesntExist` | 400 | no | Funding account does not exist in our system. | | 5005 | `ErrInvalidChainID` | 400 | no | Invalid ChainID for the transfer request. | ## Account settings (6000–6100) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 6000 | `ErrLongCancelOnDisconnectCountdown` | 400 | no | Countdown time is bigger than 300s supported | | 6100 | `ErrDeriskMMRatioOutOfRange` | 400 | no | Derisk MM Ratio is out of range | ## Vaults (7000–7035) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7000 | `ErrInvalidVaultID` | 400 | no | Vault ID provided is invalid and does not belong to any vault | | 7001 | `ErrInsufficientVaultLPToken` | 400 | no | Vault does not have sufficient LP token balance | | 7002 | `ErrOngoingRedemption` | 400 | no | User has an ongoing redemption | | 7003 | `ErrVaultNotActive` | 400 | no | This vault has been delisted/closed. | | 7004 | `ErrInvestmentExceedsCap` | 400 | no | This investment would cause the vault to exceed its valuation cap. | | 7005 | `ErrBurningMoreVaultTokensThanOwned` | 400 | no | You are attempting to burn more vault tokens than you own. | | 7006 | `ErrBurningTokenWhileActiveRedemption` | 400 | no | You are attempting to burn vault tokens whilst having an active redemption request. | | 7007 | `ErrInvestorNotVaultLP` | 400 | no | The investor is not an LP for this vault. | | 7008 | `ErrOnlyAllowedToRedeemInVaultInvestmentCurrency` | 400 | no | Vault redemption requests may only be submitted in the vault's investment currency. | | 7009 | `ErrInsufficientInvestorTokenBalanceForRedemption` | 400 | no | Vault Investor does not have enough LP tokens to redeem. | | 7012 | `ErrInvalidVaultInvestorID` | 400 | no | Vault investor ID provided is invalid. | | 7013 | `ErrCrossExchangeVaultNotSupported` | 400 | no | Cross-exchange vaults not supported | | 7014 | `ErrOnlyAllowedToInvestInVaultInvestmentCurrency` | 400 | no | Only allowed to invest in vault's investment currency | | 7015 | `ErrVaultLpTokensLocked` | 400 | no | Some of these vault shares are still within the vault's minimum investment period and cannot be redeemed yet. | | 7017 | `ErrVaultConversionRateNotAllowed` | 400 | no | The exchange rate is not allowed: it must be exactly 1 when both currencies are the same, and at most the current conversion rate otherwise. | | 7018 | `ErrVaultInvalidInvestSource` | 400 | no | Invalid invest source: use the funding account with the funding wallet, or a spot or futures wallet of one of your own trading accounts that is not a vault. | | 7019 | `ErrVaultConversionPriceStale` | 400 | no | A price this conversion needs is stale or not available yet. Please try again later. | | 7027 | `ErrVaultConversionZeroOutput` | 400 | no | The conversion would pay out nothing: the exchange rate or the amount is too small. | | 7028 | `ErrVaultInvestAlreadyExecuted` | 400 | no | This signed vault investment has already been executed. Sign a new one to invest again. | | 7035 | `ErrVaultInvestSourceNeedsSpotTransfers` | 400 | no | Spot transfers are not enabled, so only the funding account or the futures wallet of a trading account, in USDT, can pay this investment. | ## Transfer and fee checks (7100–7105) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7100 | `ErrUnknownTransactionType` | 500 | no | Unknown transaction type | | 7101 | `ErrTransferAccountNotFound` | 400 | no | Transfer account not found | | 7102 | `ErrTransferSubAccountNotFound` | 400 | no | Transfer sub-account not found | | 7103 | `ErrChargedTradingFeeBelowConfigMinimum` | 500 | no | Charged trading fee below the config minimum | | 7104 | `ErrTransferSubAccountNotUnderAccount` | 400 | no | Transfer sub-account doesn't belong to the transfer main account | | 7105 | `ErrTransferBetweenSubAccOfDifferentAccount` | 400 | no | Transfer between subaccounts of different accounts | ## Delisting and maintenance (7303–7306) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7303 | `ErrDelistCreateOrderBlocked` | 400 | no | Order creations have been blocked for this delisted asset. | | 7304 | `ErrDelistPositionOpenBlocked` | 400 | no | Only position-reducing orders (`reduce_only` as true) allowed for this asset right now. | | 7306 | `ErrMaintenanceCreateOrderBlocked` | 400 | no | Order creation is temporarily blocked during the corporate action / maintenance window | ## Isolated margin (7450–7455) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7450 | `AddMarginFailed` | 400 | no | Add margin failed | | 7451 | `AddMarginToEmptyPosition` | 400 | no | Add margin to empty position | | 7452 | `AddMarginToNonIsolatedPosition` | 400 | no | Add margin to non isolated position | | 7453 | `MaxAddableAmountExceeded` | 400 | no | Max addable amount exceeded | | 7454 | `MaxRemovableAmountExceeded` | 400 | no | Max removable amount exceeded | | 7455 | `NotIsolatedMarginPosition` | 400 | no | Not isolated margin position | ## Builder fees (7501–7506) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7501 | `ErrBuilderFeeNegative` | 400 | no | Builder Fee can't be negative. | | 7504 | `ErrBuilderNotAuthorized` | 400 | no | Builder is not authorized for the specified user. | | 7505 | `ErrBuilderFeeExceedsAuthorizationLimit` | 400 | no | Builder Fee exceeds authorized limit. | | 7506 | `ErrBuilderMissing` | 400 | no | Builder Account is missing but builder fee is provided. | ## Slippage (7600–7603) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7600 | `ErrSlippageFeatureDisabled` | 400 | no | Order slippage protection is not enabled. | | 7601 | `ErrSlippageRequiresIOCLimitOrder` | 400 | no | Slippage protection is only supported on IOC limit orders. | | 7602 | `ErrSlippageBelowMinimum` | 400 | no | Slippage is below the minimum allowed value. | | 7603 | `ErrSlippageExceedsPriceProtectionBand` | 400 | no | Slippage exceeds the asset's price protection band. | ## Stable funding perps (7701–7726) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7701 | `ErrSfpIndicativeNotQualifiedMaker` | 403 | no | You are not a qualified market maker or designated market maker for this instrument. | | 7704 | `ErrSfpOrderNotSupported` | 400 | no | Stable Funding Perpetual orders are not yet supported. | | 7705 | `ErrSfpInstrumentMismatch` | 400 | no | The order's instrument does not match the referenced RFQ's instrument. | | 7706 | `ErrSfpPrivateQuoteNotSupported` | 400 | no | Private maker quotes are not yet supported. | | 7707 | `ErrSfpRfqNotLive` | 400 | no | The referenced RFQ is not open. | | 7708 | `ErrSfpRfqAlreadyHasTakerOrder` | 400 | no | The referenced RFQ already has a taker order. | | 7709 | `ErrSfpTakerInvalidTimeInForce` | 400 | no | Invalid time in force for a Stable Funding Perpetual taker order. | | 7711 | `ErrSfpMarketOrderNotAllowed` | 400 | no | Market orders are not allowed for Stable Funding Perpetual taker orders; a market-order slippage bound must be set. | | 7712 | `ErrRfqIDNotAllowedForNonSFP` | 400 | no | Non-Stable-Funding-Perpetual orders must always be supplied without rfq_id. | | 7723 | `ErrUsdcCollateralDisabled` | 400 | no | USDC must be enabled as collateral on this sub account to trade USDC-quoted instruments. | | 7724 | `ErrSfpPostOnlyNotAllowedForRetail` | 400 | no | Post-only orders are not allowed on Stable Funding Perpetuals. | | 7725 | `ErrSfpEndpointNotSupported` | 403 | no | This endpoint is not supported for stable funding. | | 7726 | `ErrSfpMarketClosed` | 400 | no | The Stable Funding Perpetual market is closed. | ## Currency conversion (7801–7812) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7801 | `ErrCurrencyNotConvertible` | 400 | no | This currency is not enabled for stable coin convert. | | 7802 | `ErrPriceOutOfConvertBand` | 400 | no | The index price of one of the currencies is outside the permitted convert band. Please try again later. | | 7803 | `ErrMissingIndexPrice` | 400 | no | An index price required for this conversion is unavailable. Please try again later. | | 7805 | `ErrInexactConversion` | 400 | no | This amount cannot be converted exactly between the two currencies’ decimals. Please adjust the amount. | | 7811 | `ErrNegativeBalance` | 400 | no | This conversion would leave a negative balance. | | 7812 | `ErrValueOverflow` | 400 | no | The convert amount is too large to be represented. Please use a smaller amount. | ## Trading coupons (7901) | Code | Name | HTTP | Retryable | Message | |---|---|---|---|---| | 7901 | `ErrTradingCouponNotTransferable` | 400 | no | Trading coupons move only by an adjustment or a liquidation. |