Skill: madeinusmate/grvt-markets-agent-skill (version 1.0.0)

--- name: grvt-exchange description: >- Trade on GRVT (Gravity Markets) derivatives exchange via the grvt-cli tool. Use when the user wants to trade crypto derivatives, place or cancel orders, check positions, view market data (orderbook, candles, tickers, funding rates), manage account balances, transfer funds between sub-accounts, withdraw to Ethereum, set leverage, query trade or order history, or interact with the GRVT API in any way. Covers perpetuals, futures, and options on GRVT. --- # GRVT Exchange CLI > **IMPORTANT: Community Project Disclaimer** > > `grvt-cli` is a **community hobby project**. It is **NOT** officially supported, endorsed, audited, or maintained by the GRVT team. No security audit or formal code review has been performed. > > **The code has not been audited for security vulnerabilities. By using this tool the user acknowledges and accepts the risk of total loss of funds.** > > The user is solely responsible for any financial losses, leaked credentials, or unintended trades that may result from using this software. > > This tool stores API keys and private keys in plaintext on disk (with `0600` file permissions). Keys should never be shared or used on untrusted machines. > > **Before using this CLI on behalf of the user, you MUST inform them of this disclaimer and get their explicit acknowledgment.** `grvt` is a CLI tool and Node.js library for trading on GRVT (Gravity Markets), a crypto derivatives exchange supporting perpetuals, futures, and options. Package: `@madeinusmate/grvt-cli` (npm). Binary: `grvt`. Requires Node.js >= 20. ## Safety Recommendations - Only use testnet until the user fully understands the CLI behavior. - Review the source code before trusting it with real funds. - Keep private keys out of shell history (use `grvt setup` which reads from stdin). - Rotate API keys regularly. - Never use the CLI with more funds than the user can afford to lose. ## Installation ```bash pnpm add -g @madeinusmate/grvt-cli ``` Verify: `grvt --version` ## First-Time Setup The interactive wizard handles everything: ```bash grvt setup ``` The setup wizard displays a disclaimer requiring explicit acceptance before proceeding. It is interactive and reads sensitive input from stdin (keeping keys out of shell history). It walks through: environment, API key, private key, and default sub-account ID, then authenticates automatically. **Note:** Because `grvt setup` is interactive and requires user input, agents cannot run it directly. Use the manual setup flow below instead. Manual setup (recommended for agents): ```bash grvt config set env testnet grvt auth login --api-key YOUR_API_KEY --private-key 0xYOUR_PRIVATE_KEY grvt config set subAccountId YOUR_SUB_ACCOUNT_ID ``` Verify setup: ```bash grvt auth status grvt config list ``` ## Configuration Config file: `~/.config/grvt/config.toml` (permissions `0600`). | Key | Type | Default | Description | |-----|------|---------|-------------| | `env` | `dev\|staging\|testnet\|prod` | `prod` | GRVT environment | | `apiKey` | string | - | GRVT API key | | `privateKey` | string | - | Ethereum private key (0x-prefixed) for EIP-712 signing | | `subAccountId` | string | - | Default sub-account for trading commands | | `accountId` | string | - | Main account ID (set automatically on login) | | `cookie` | string | - | Session cookie (set automatically on login) | | `outputDefaults.output` | `json\|ndjson\|table\|raw` | `table` | Default output format | | `outputDefaults.pretty` | boolean | `false` | Pretty-print JSON | | `outputDefaults.silent` | boolean | `false` | Suppress info logs | | `http.timeoutMs` | number | `10000` | Request timeout (ms) | | `http.retries` | number | `3` | Retry count | | `http.backoffMs` | number | `200` | Initial backoff (ms) | | `http.maxBackoffMs` | number | `10000` | Max backoff (ms) | Secret keys (`apiKey`, `privateKey`, `cookie`) are redacted in `config list` / `config get` output. Use `grvt config set <key> <value>` and `grvt config unset <key>` to modify. Use dot-notation for nested keys (e.g. `outputDefaults.output`). ## Authentication **Login** requires an API key. A private key is optional but required for write operations (orders, transfers, withdrawals, derisk). ```bash grvt auth login --api-key KEY --private-key 0xKEY ``` The session cookie is stored in config and sent automatically with authenticated requests. | Command | Description | |---------|-------------| | `grvt auth login` | Authenticate (stores session cookie + account ID) | | `grvt auth status` | Verify session is valid (calls API) | | `grvt auth whoami` | Show current auth state (local only, no API call) | | `grvt auth logout` | Clear all stored credentials | **EIP-712 signing** is used for: order creation, transfers, withdrawals, and derisk operations. The private key never leaves the local machine. ## Environments | Environment | Market Data | Trading | Edge (Auth) | |------------|------------|---------|-------------| | `dev` | `market-data.dev.gravitymarkets.io` | `trades.dev.gravitymarkets.io` | `edge.dev.gravitymarkets.io` | | `staging` | `market-data.staging.gravitymarkets.io` | `trades.staging.gravitymarkets.io` | `edge.staging.gravitymarkets.io` | | `testnet` | `market-data.testnet.grvt.io` | `trades.testnet.grvt.io` | `edge.testnet.grvt.io` | | `prod` | `market-data.grvt.io` | `trades.grvt.io` | `edge.grvt.io` | Switch with: `grvt config set env testnet` ## Global Options Available on every command: | Option | Description | Default | |--------|-------------|---------| | `--output <format>` | `json`, `ndjson`, `table`, `raw` | `table` (TTY) / `json` (piped) | | `--pretty` | Pretty-print JSON | `false` | | `--silent` | Suppress info logs | `false` | | `--no-color` | Disable colors | - | | `--yes` | Skip confirmation prompts | - | | `--retries <n>` | Retry count | `3` | | `--timeout-ms <n>` | Request timeout (ms) | `10000` | Write commands (`order create`, `order cancel`, `transfer create`, `withdraw create`, `derisk`) also support: | Option | Description | |--------|-------------| | `--dry-run` | Validate and show the signed payload without sending | | `--json <path>` | Read full request body from file (`@file.json`) or stdin (`-`) | ## Command Overview ``` grvt setup Interactive setup wizard config Manage local configuration path / get / set / unset / list / export / import auth Authentication and session login / status / whoami / logout market Market data (mostly unauthenticated) instruments / instrument / currency / orderbook / trades candles / funding-rate / ticker / mini-ticker / margin-rules account Account info (requires auth) funding / summary / aggregated / history trade Trading (requires auth; writes need private key) order create / order get / order open / order cancel / order cancel-all / order history fills / positions / funding-payments leverage get / leverage set cancel-on-disconnect / derisk funds Fund management (requires auth; writes need private key) deposit history transfer create / transfer history withdraw create / withdraw history ``` For full flag details on each command, read the corresponding reference file: - `references/commands-config.md` — config and auth commands - `references/commands-market.md` — market data commands - `references/commands-trade.md` — trading commands - `references/commands-account.md` — account commands - `references/commands-funds.md` — fund management commands - `references/errors.md` — error codes and troubleshooting ## Instrument Naming GRVT uses structured instrument symbols: | Type | Pattern | Example | |------|---------|---------| | Perpetual | `{BASE}_{QUOTE}_Perp` | `BTC_USDT_Perp` | | Future | `{BASE}_{QUOTE}_Fut_{DATE}` | `BTC_USDT_Fut_20Oct23` | | Call | `{BASE}_{QUOTE}_Call_{DATE}_{STRIKE}` | `ETH_USDT_Call_20Oct23_2800` | | Put | `{BASE}_{QUOTE}_Put_{DATE}_{STRIKE}` | `ETH_USDT_Put_20Oct23_2800` | Always discover available instruments before trading: ```bash grvt market instruments grvt market instruments --kind PERPETUAL --base BTC grvt market instrument --instrument BTC_USDT_Perp ``` ## Output Format Guide | Format | When to use | |--------|-------------| | `table` | Interactive display in terminal (default in TTY) | | `json` | Parsing output programmatically, piping to `jq` | | `ndjson` | Streaming large datasets with `--all` pagination | | `raw` | Debugging raw API responses | The CLI auto-detects: `table` when stdout is a TTY, `json` when piped. Override with `--output <format>`. When using `--all` with `ndjson`, records stream to stdout as they arrive (one JSON object per line), enabling efficient processing of large result sets without buffering everything in memory. ## Key Workflows ### Market Analysis ```bash grvt market instruments --kind PERPETUAL grvt market orderbook --instrument BTC_USDT_Perp --depth 50 grvt market ticker --instrument BTC_USDT_Perp --greeks --derived grvt market candles --instrument BTC_USDT_Perp --interval CI_1_H --limit 24 grvt market funding-rate --instrument BTC_USDT_Perp --limit 10 grvt market margin-rules --instrument BTC_USDT_Perp ``` ### Place and Manage Orders ```bash # Limit buy grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit --qty 0.01 --price 68000 # Market sell grvt trade order create --instrument BTC_USDT_Perp --side sell --type market --qty 0.01 # With options grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit \ --qty 0.01 --price 68000 --post-only --time-in-force IOC --expiration-seconds 60 # Monitor grvt trade order open grvt trade order get --order-id 0x123... # Cancel grvt trade order cancel --order-id 0x123... grvt trade order cancel-all grvt trade order cancel-all --instrument BTC_USDT_Perp ``` ### Portfolio Check ```bash grvt trade positions grvt account summary grvt account aggregated grvt account funding grvt account history --start-time 2025-01-01T00:00:00Z --limit 24 ``` ### Fund Management ```bash # Transfer between sub-accounts grvt funds transfer create \ --from-sub-account-id FROM_ID --to-sub-account-id TO_ID \ --currency USDT --amount 100 # Withdraw to Ethereum address grvt funds withdraw create \ --to-address 0xYOUR_ETH_ADDRESS --currency USDT --amount 50 # View history grvt funds deposit history --all grvt funds transfer history --start-time 2025-01-01T00:00:00Z grvt funds withdraw history --limit 10 ``` ### Leverage and Risk ```bash grvt trade leverage get grvt trade leverage set --instrument BTC_USDT_Perp --leverage 10 grvt trade cancel-on-disconnect --countdown 5000 grvt trade derisk --ratio 0.5 ``` ## Shell Patterns Pipe JSON output to `jq`: ```bash grvt market instruments --output json | jq '.[].instrument' grvt trade order open --output json | jq '.[] | {instrument, side: .legs[0].is_buying_asset, size: .legs[0].size}' ``` Stream paginated results: ```bash grvt trade fills --all --output ndjson | jq '.instrument' grvt trade order history --all --output ndjson > all_orders.jsonl ``` Read order payload from a file: ```bash grvt trade order create --json @order.json echo '{"order": {...}}' | grvt trade order create --json - ``` Skip confirmations for scripting: ```bash grvt trade order cancel-all --yes --silent grvt funds transfer create ... --yes --silent ``` Dry-run to preview: ```bash grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit --qty 0.01 --price 68000 --dry-run ``` ## Timestamp Formats All `--start-time` and `--end-time` flags accept: | Format | Example | |--------|---------| | Unix seconds | `1704067200` | | Unix milliseconds | `1704067200000` | | Unix nanoseconds | `1704067200000000000` | | ISO 8601 | `2025-01-01T00:00:00Z` | ## Error Handling | Exit Code | Meaning | |-----------|---------| | `0` | Success | | `2` | Usage / validation error (bad flags, missing required options) | | `3` | Authentication / permission error (expired session, invalid key) | | `4` | Partial failure (batch operations like cancel-all) | | `5` | API / network error (server errors, timeouts, rate limits) | Common recovery patterns: - Exit 3: Run `grvt auth login` to refresh session - Exit 5 with 429: Reduce request frequency; CLI retries automatically with exponential backoff - Exit 2: Check `grvt <command> --help` for required options For detailed error scenarios and troubleshooting, read `references/errors.md`. ## Library Usage `@madeinusmate/grvt-cli` can also be imported as a Node.js library: ```typescript import { createHttpClient, login, createOrder, getOpenOrders, getPositions } from "@madeinusmate/grvt-cli"; ``` See `src/index.ts` in the package source for all exported functions. ## Candle Intervals Valid values for `--interval` on `grvt market candles`: `CI_1_M`, `CI_5_M`, `CI_15_M`, `CI_30_M`, `CI_1_H`, `CI_2_H`, `CI_4_H`, `CI_6_H`, `CI_8_H`, `CI_12_H`, `CI_1_D`, `CI_1_W` ## Instrument Kind Filters Valid values for `--kind` filters (comma-separated): `PERPETUAL`, `FUTURE`, `CALL`, `PUT`

path: references/commands-account.md
content: # Account Commands

All account commands require authentication (`grvt auth login`).

---

## `grvt account funding`

Get the funding (main) account summary. Shows balances in the main account before allocation to sub-accounts.

No options required (beyond global options).

```bash
grvt account funding
grvt account funding --output json --pretty
```

---

## `grvt account summary`

Get the summary for a specific sub-account, including balances, margin usage, unrealized P&L, and positions.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |

```bash
grvt account summary
grvt account summary --sub-account-id 123456
grvt account summary --output json --pretty
```

---

## `grvt account aggregated`

Get an aggregated summary across all sub-accounts. Useful for a high-level portfolio view.

No options required (beyond global options).

```bash
grvt account aggregated
grvt account aggregated --output json --pretty
```

---

## `grvt account history`

Get hourly snapshots of sub-account state over time. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--start-time <time>` | No | Start time (unix s/ms/ns or ISO 8601) |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt account history
grvt account history --start-time 2025-01-01T00:00:00Z --limit 24
grvt account history --start-time 2025-01-01T00:00:00Z --end-time 2025-01-02T00:00:00Z --all --output ndjson
grvt account history --all --output json --pretty
```


path: references/commands-trade.md
content: # Trading Commands

All trading commands require authentication (`grvt auth login`). Commands that create or modify state (order create, order cancel, cancel-all, derisk) also require a private key for EIP-712 signing.

The `--sub-account-id` option is available on most commands and falls back to the value in config (`grvt config set subAccountId <id>`).

---

## `grvt trade order create`

Create a new order. Requires a private key for EIP-712 signing.

| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--instrument <name>` | **Yes** | - | Instrument symbol (e.g. `BTC_USDT_Perp`) |
| `--side <side>` | **Yes** | - | `buy` or `sell` |
| `--type <type>` | **Yes** | - | `market` or `limit` |
| `--qty <amount>` | **Yes** | - | Order quantity |
| `--price <price>` | **Yes** (limit orders) | - | Limit price |
| `--sub-account-id <id>` | No | config value | Sub-account ID |
| `--time-in-force <tif>` | No | `GTT` | `GTT` (Good Till Time), `IOC` (Immediate or Cancel), `AON` (All or None), `FOK` (Fill or Kill) |
| `--reduce-only` | No | `false` | Reduce-only order |
| `--post-only` | No | `false` | Post-only order |
| `--client-order-id <id>` | No | auto-generated | Custom numeric order ID |
| `--expiration-seconds <n>` | No | `3600` | Order expiration in seconds from now |
| `--json <path>` | No | - | Read full request body from file (`@file.json`) or stdin (`-`) |
| `--dry-run` | No | - | Show signed payload without sending |

```bash
# Simple limit buy
grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit --qty 0.01 --price 68000

# Market sell
grvt trade order create --instrument BTC_USDT_Perp --side sell --type market --qty 0.01

# Post-only limit with IOC and short expiration
grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit \
  --qty 0.5 --price 67500 --post-only --time-in-force IOC --expiration-seconds 60

# Reduce-only (close position only)
grvt trade order create --instrument BTC_USDT_Perp --side sell --type market --qty 0.01 --reduce-only

# Dry-run to preview the signed payload
grvt trade order create --instrument BTC_USDT_Perp --side buy --type limit \
  --qty 0.01 --price 68000 --dry-run

# From JSON file
grvt trade order create --json @order.json

# From stdin
echo '{"order": {...}}' | grvt trade order create --json -
```

**Time-in-force values** (case-insensitive, short or full form accepted):

| Short | Full | Description |
|-------|------|-------------|
| `GTT` | `GOOD_TILL_TIME` | Stays open until expiration |
| `IOC` | `IMMEDIATE_OR_CANCEL` | Fill immediately or cancel unfilled portion |
| `AON` | `ALL_OR_NONE` | Fill entirely or not at all |
| `FOK` | `FILL_OR_KILL` | Fill entirely immediately or cancel |

---

## `grvt trade order get`

Get details of a specific order by ID.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--order-id <id>` | One of these required | GRVT-assigned order ID |
| `--client-order-id <id>` | One of these required | Client-specified order ID |

```bash
grvt trade order get --order-id 0x123abc...
grvt trade order get --client-order-id 9876543210
grvt trade order get --order-id 0x123abc... --output json --pretty
```

---

## `grvt trade order open`

List all currently open orders.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--kind <kinds>` | No | Comma-separated filter: `PERPETUAL`, `FUTURE`, `CALL`, `PUT` |
| `--base <currencies>` | No | Base currency filter (comma-separated) |
| `--quote <currencies>` | No | Quote currency filter (comma-separated) |

```bash
grvt trade order open
grvt trade order open --kind PERPETUAL
grvt trade order open --base BTC --output json
```

---

## `grvt trade order cancel`

Cancel a single order. Requires either `--order-id` or `--client-order-id`.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--order-id <id>` | One of these required | Order ID to cancel |
| `--client-order-id <id>` | One of these required | Client order ID to cancel |
| `--dry-run` | No | Show payload without sending |

```bash
grvt trade order cancel --order-id 0x123abc...
grvt trade order cancel --client-order-id 9876543210
grvt trade order cancel --order-id 0x123abc... --dry-run
```

---

## `grvt trade order cancel-all`

Cancel all open orders. Prompts for confirmation unless `--yes` is passed.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--instrument <name>` | No | Only cancel orders for this instrument |
| `--dry-run` | No | Show payload without sending |

```bash
grvt trade order cancel-all
grvt trade order cancel-all --instrument BTC_USDT_Perp
grvt trade order cancel-all --yes --silent
```

---

## `grvt trade order history`

Get historical orders. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--kind <kinds>` | No | Comma-separated kind filter |
| `--base <currencies>` | No | Base currency filter |
| `--quote <currencies>` | No | Quote currency filter |
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt trade order history
grvt trade order history --kind PERPETUAL --start-time 2025-01-01T00:00:00Z
grvt trade order history --all --output ndjson > order_history.jsonl
```

---

## `grvt trade fills`

Get fill (trade execution) history. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--kind <kinds>` | No | Comma-separated kind filter |
| `--base <currencies>` | No | Base currency filter |
| `--quote <currencies>` | No | Quote currency filter |
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt trade fills
grvt trade fills --kind PERPETUAL --base BTC
grvt trade fills --start-time 2025-01-01T00:00:00Z --all --output ndjson
grvt trade fills --output json | jq '.[].price'
```

---

## `grvt trade positions`

Get current open positions.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--kind <kinds>` | No | Comma-separated kind filter |
| `--base <currencies>` | No | Base currency filter |
| `--quote <currencies>` | No | Quote currency filter |

```bash
grvt trade positions
grvt trade positions --kind PERPETUAL
grvt trade positions --base BTC --output json --pretty
```

---

## `grvt trade funding-payments`

Get funding payment history for perpetual positions. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--kind <kinds>` | No | Comma-separated kind filter |
| `--base <currencies>` | No | Base currency filter |
| `--quote <currencies>` | No | Quote currency filter |
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt trade funding-payments
grvt trade funding-payments --base BTC --start-time 2025-01-01T00:00:00Z --all
```

---

## `grvt trade leverage get`

Get initial leverage settings for all instruments (or filter to one).

| Option | Required | Description |
|--------|----------|-------------|
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--instrument <name>` | No | Filter to a single instrument (client-side filter) |

```bash
grvt trade leverage get
grvt trade leverage get --instrument BTC_USDT_Perp
grvt trade leverage get --output json --pretty
```

---

## `grvt trade leverage set`

Set initial leverage for a specific instrument.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |
| `--leverage <value>` | **Yes** | Leverage value (e.g. `10`, `20`) |
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |

```bash
grvt trade leverage set --instrument BTC_USDT_Perp --leverage 10
grvt trade leverage set --instrument ETH_USDT_Perp --leverage 5
```

---

## `grvt trade cancel-on-disconnect`

Set, refresh, or disable the cancel-on-disconnect countdown. When enabled, all open orders are canceled if the session disconnects for longer than the countdown.

| Option | Required | Description |
|--------|----------|-------------|
| `--countdown <ms>` | **Yes** | Countdown in milliseconds: `1000`-`300000`, or `0` to disable |
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |

```bash
# Enable with 5-second countdown
grvt trade cancel-on-disconnect --countdown 5000

# Refresh the countdown timer
grvt trade cancel-on-disconnect --countdown 5000

# Disable
grvt trade cancel-on-disconnect --countdown 0
```

---

## `grvt trade derisk`

Set the derisk-to-maintenance-margin ratio. Requires a private key for EIP-712 signing.

| Option | Required | Description |
|--------|----------|-------------|
| `--ratio <value>` | **Yes** | Derisk MM ratio as a decimal (e.g. `0.5`) |
| `--sub-account-id <id>` | No | Sub-account ID (falls back to config) |
| `--dry-run` | No | Show signed payload without sending |

```bash
grvt trade derisk --ratio 0.5
grvt trade derisk --ratio 0.8 --dry-run
```


path: references/errors.md
content: # Error Handling & Troubleshooting

## Exit Codes

| Code | Constant | Meaning |
|------|----------|---------|
| `0` | `EXIT_SUCCESS` | Command completed successfully |
| `2` | `EXIT_USAGE` | Usage or validation error (bad flags, missing required options, invalid values) |
| `3` | `EXIT_AUTH` | Authentication or permission error (expired session, missing/invalid API key or private key, 401/403 from API) |
| `4` | `EXIT_PARTIAL` | Partial failure in batch operations (e.g. `cancel-all` where some cancels failed) |
| `5` | `EXIT_API` | API or network error (server errors, timeouts, rate limits, connection failures) |

## Common Error Scenarios

### Authentication Errors (Exit 3)

**Session expired**
```
Error: HTTP 401: Unauthorized
```
Recovery: Run `grvt auth login` to get a fresh session cookie.

**API key not set**
```
Error: --api-key is required (or set apiKey in config)
```
Recovery: Run `grvt config set apiKey YOUR_KEY` or pass `--api-key` to the command.

**Private key missing (for write operations)**
```
Error: Private key required for order signing. Run `grvt config set privateKey <key>` or `grvt auth login --private-key <key>`.
```
Recovery: Set the private key with `grvt config set privateKey 0xKEY`.

**Invalid API key**
```
Error: Auth failed: invalid api key
```
Recovery: Verify your API key at https://grvt.io and re-set it with `grvt config set apiKey CORRECT_KEY`.

**Wrong environment**
```
Error: Auth failed: ...
```
Recovery: Check the current environment with `grvt config get env` and ensure your API key is valid for that environment. Different environments have separate API keys.

---

### Validation Errors (Exit 2)

**Missing required option**
```
Error: --instrument is required
Error: Either --order-id or --client-order-id is required
Error: --price is required for limit orders
```
Recovery: Add the missing required flag. Check `grvt <command> --help` for required options.

**Invalid instrument name**
```
Error: Instrument not found: BTCUSDT
```
Recovery: Use the correct naming convention (e.g. `BTC_USDT_Perp` not `BTCUSDT`). Discover valid instruments with `grvt market instruments`.

**Invalid sub-account ID**
```
Error: --sub-account-id is required (or set subAccountId in config)
```
Recovery: Set a default with `grvt config set subAccountId YOUR_ID` or pass `--sub-account-id`.

**Invalid time-in-force**
```
Error: Invalid time-in-force: XXX. Use GTT, IOC, AON, or FOK.
```
Recovery: Use one of the valid values: `GTT`, `IOC`, `AON`, `FOK` (or their full forms).

**Invalid Ethereum address**
```
Error: --to-address must be a valid Ethereum address (0x...)
```
Recovery: Provide a valid 42-character address starting with `0x`.

**Invalid countdown value**
```
Error: --countdown must be 0 (disable) or between 1000 and 300000 ms
```
Recovery: Use `0` to disable, or a value between `1000` and `300000`.

---

### API / Network Errors (Exit 5)

**Rate limiting**
```
Error: HTTP 429: Too Many Requests
```
Recovery: The CLI automatically retries with exponential backoff (configurable via `http.backoffMs`, `http.maxBackoffMs`, `http.retries`). If this persists, reduce request frequency or increase `http.maxBackoffMs`.

**Server error**
```
Error: HTTP 500: Internal Server Error
Error: HTTP 503: Service Unavailable
```
Recovery: The CLI automatically retries 5xx errors. If the issue persists, the GRVT API may be experiencing downtime. Wait and retry.

**Timeout**
```
Error: The operation was aborted
```
Recovery: Increase the timeout with `--timeout-ms 30000` or `grvt config set http.timeoutMs 30000`. Timeouts are also retried automatically.

**Connection failure**
```
Error: fetch failed
Error: ECONNREFUSED
```
Recovery: Check your network connectivity and verify the environment is correct (`grvt config get env`). Ensure the GRVT API is reachable.

**Insufficient balance**
```
Error: insufficient balance
```
Recovery: Check balances with `grvt account summary` and `grvt account funding`. Ensure the sub-account has enough funds for the operation.

**Order rejected**
```
Error: order rejected: ...
```
Recovery: Common causes include insufficient margin, invalid price (outside allowed range), or exceeding position limits. Check `grvt market margin-rules --instrument <name>` and `grvt account summary`.

---

### Partial Failures (Exit 4)

**cancel-all partial failure**
```
Error: Some orders could not be canceled
```
Recovery: Re-run `grvt trade order cancel-all` to retry remaining orders. Check `grvt trade order open` to see which orders are still open.

---

## Retry Behavior

The HTTP client automatically retries on:
- HTTP 429 (rate limiting)
- HTTP 5xx (server errors)
- Request timeouts (AbortError)

Retry configuration (via config or global flags):
- `retries`: Number of retry attempts (default: `3`)
- `backoffMs`: Initial backoff delay (default: `200ms`)
- `maxBackoffMs`: Maximum backoff delay (default: `10000ms`)

Backoff formula: `min(backoffMs * 2^attempt, maxBackoffMs)`

Non-retryable errors (4xx except 429) fail immediately.

---

## Debugging Tips

1. **Check auth state**: `grvt auth whoami` (local) or `grvt auth status` (API call)
2. **Verbose output**: Use `--output json --pretty` to see full response details
3. **Dry-run writes**: Always available on write commands to preview the signed payload
4. **Check config**: `grvt config list` to see all settings (secrets redacted)
5. **Raw API response**: Use `--output raw` to see the unprocessed API response
6. **Config file location**: `grvt config path` to find the config file for manual inspection


path: references/commands-market.md
content: # Market Data Commands

All market data commands are **unauthenticated** (no login required), except where noted.

---

## `grvt market instruments`

List available trading instruments. Uses a filtered endpoint when `--kind`, `--base`, or `--quote` are provided; otherwise returns all instruments.

| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--kind <kinds>` | No | - | Comma-separated: `PERPETUAL`, `FUTURE`, `CALL`, `PUT` |
| `--base <currencies>` | No | - | Comma-separated base currencies (e.g. `BTC,ETH`) |
| `--quote <currencies>` | No | - | Comma-separated quote currencies (e.g. `USDT`) |
| `--active` | No | `true` | Only return active instruments |
| `--limit <n>` | No | - | Max number of results |

```bash
grvt market instruments
grvt market instruments --kind PERPETUAL
grvt market instruments --kind PERPETUAL,FUTURE --base BTC,ETH
grvt market instruments --base ETH --quote USDT
grvt market instruments --kind CALL,PUT --base BTC --output json
```

---

## `grvt market instrument`

Get detailed metadata for a single instrument (tick size, lot size, decimals, instrument hash, etc.).

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol (e.g. `BTC_USDT_Perp`) |

```bash
grvt market instrument --instrument BTC_USDT_Perp
grvt market instrument --instrument ETH_USDT_Perp --output json --pretty
```

---

## `grvt market currency`

List all supported currencies with their IDs, symbols, and decimal precision. No options required.

```bash
grvt market currency
grvt market currency --output json
```

---

## `grvt market orderbook`

Get the order book (bids and asks) for an instrument.

| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--instrument <name>` | **Yes** | - | Instrument symbol |
| `--depth <n>` | No | `10` | Book depth: `10`, `50`, `100`, or `500` |

```bash
grvt market orderbook --instrument BTC_USDT_Perp
grvt market orderbook --instrument BTC_USDT_Perp --depth 50
grvt market orderbook --instrument ETH_USDT_Perp --depth 100 --output json
```

---

## `grvt market trades`

Get trade history for an instrument. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |
| `--start-time <time>` | No | Start time (unix s/ms/ns or ISO 8601) |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max trades per page |
| `--cursor <cursor>` | No | Pagination cursor from previous response |
| `--all` | No | Auto-paginate through all pages |

```bash
grvt market trades --instrument BTC_USDT_Perp
grvt market trades --instrument BTC_USDT_Perp --limit 100
grvt market trades --instrument BTC_USDT_Perp --start-time 2025-01-01T00:00:00Z --all --output ndjson
```

---

## `grvt market candles`

Get candlestick (OHLCV) data for an instrument. Supports pagination.

| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--instrument <name>` | **Yes** | - | Instrument symbol |
| `--interval <interval>` | **Yes** | - | Candle interval (see below) |
| `--type <type>` | No | `TRADE` | Price type: `TRADE`, `MARK`, `INDEX`, `MID` |
| `--start-time <time>` | No | - | Start time |
| `--end-time <time>` | No | - | End time |
| `--limit <n>` | No | - | Max candles per page |
| `--cursor <cursor>` | No | - | Pagination cursor |
| `--all` | No | - | Auto-paginate all results |

**Valid intervals:** `CI_1_M`, `CI_5_M`, `CI_15_M`, `CI_30_M`, `CI_1_H`, `CI_2_H`, `CI_4_H`, `CI_6_H`, `CI_8_H`, `CI_12_H`, `CI_1_D`, `CI_1_W`

```bash
grvt market candles --instrument BTC_USDT_Perp --interval CI_1_H
grvt market candles --instrument BTC_USDT_Perp --interval CI_1_D --limit 30
grvt market candles --instrument BTC_USDT_Perp --interval CI_5_M \
  --start-time 2025-01-01T00:00:00Z --end-time 2025-01-02T00:00:00Z --all --output ndjson
grvt market candles --instrument ETH_USDT_Perp --interval CI_1_H --type MARK
```

---

## `grvt market funding-rate`

Get funding rate history for an instrument. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max entries per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt market funding-rate --instrument BTC_USDT_Perp
grvt market funding-rate --instrument BTC_USDT_Perp --limit 10
grvt market funding-rate --instrument BTC_USDT_Perp --all --output ndjson
```

---

## `grvt market ticker`

Get full ticker data for an instrument. Optionally include greeks (for options) and derived statistics.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |
| `--greeks` | No | Include greeks data (for options) |
| `--derived` | No | Include derived statistics |

```bash
grvt market ticker --instrument BTC_USDT_Perp
grvt market ticker --instrument BTC_USDT_Perp --greeks --derived
grvt market ticker --instrument ETH_USDT_Call_20Oct23_2800 --greeks --output json --pretty
```

---

## `grvt market mini-ticker`

Get lightweight price info (last price, 24h change) for an instrument. Faster than full ticker.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |

```bash
grvt market mini-ticker --instrument BTC_USDT_Perp
grvt market mini-ticker --instrument ETH_USDT_Perp --output json
```

---

## `grvt market margin-rules`

Get margin rules (initial margin, maintenance margin tiers) for an instrument.

| Option | Required | Description |
|--------|----------|-------------|
| `--instrument <name>` | **Yes** | Instrument symbol |

```bash
grvt market margin-rules --instrument BTC_USDT_Perp
grvt market margin-rules --instrument BTC_USDT_Perp --output json --pretty
```


path: references/commands-funds.md
content: # Fund Management Commands

All fund commands require authentication (`grvt auth login`). Commands that move funds (transfer create, withdraw create) also require a private key for EIP-712 signing.

Deposits are made via the GRVT web interface, not the CLI. The CLI can only query deposit history.

---

## `grvt funds deposit history`

Get deposit history. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--start-time <time>` | No | Start time (unix s/ms/ns or ISO 8601) |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt funds deposit history
grvt funds deposit history --limit 10
grvt funds deposit history --start-time 2025-01-01T00:00:00Z --all --output ndjson
```

---

## `grvt funds transfer create`

Transfer funds between sub-accounts within the same main account. Requires a private key for EIP-712 signing. Prompts for confirmation unless `--yes` is passed.

| Option | Required | Description |
|--------|----------|-------------|
| `--from-sub-account-id <id>` | **Yes** | Source sub-account ID |
| `--to-sub-account-id <id>` | **Yes** | Destination sub-account ID |
| `--currency <symbol>` | **Yes** | Currency symbol (e.g. `USDT`, `BTC`) |
| `--amount <amount>` | **Yes** | Amount to transfer |
| `--json <path>` | No | Read full request body from file (`@path`) or stdin (`-`) |
| `--dry-run` | No | Show signed payload without sending |

```bash
grvt funds transfer create \
  --from-sub-account-id 111 --to-sub-account-id 222 \
  --currency USDT --amount 100

# Skip confirmation for scripting
grvt funds transfer create \
  --from-sub-account-id 111 --to-sub-account-id 222 \
  --currency USDT --amount 50 --yes

# Dry-run to preview
grvt funds transfer create \
  --from-sub-account-id 111 --to-sub-account-id 222 \
  --currency USDT --amount 100 --dry-run

# From JSON file
grvt funds transfer create --json @transfer.json
```

---

## `grvt funds transfer history`

Get transfer history. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt funds transfer history
grvt funds transfer history --limit 20
grvt funds transfer history --all --output ndjson
```

---

## `grvt funds withdraw create`

Withdraw funds from a sub-account to an Ethereum address. Requires a private key for EIP-712 signing. Prompts for confirmation unless `--yes` is passed.

| Option | Required | Description |
|--------|----------|-------------|
| `--to-address <address>` | **Yes** | Destination Ethereum address (`0x...`, 42 characters) |
| `--currency <symbol>` | **Yes** | Currency symbol (e.g. `USDT`) |
| `--amount <amount>` | **Yes** | Amount to withdraw |
| `--sub-account-id <id>` | No | Source sub-account ID (falls back to config) |
| `--main-account-id <id>` | No | Main account ID (falls back to current account) |
| `--json <path>` | No | Read full request body from file (`@path`) or stdin (`-`) |
| `--dry-run` | No | Show signed payload without sending |

```bash
grvt funds withdraw create \
  --to-address 0x1234567890abcdef1234567890abcdef12345678 \
  --currency USDT --amount 50

# Skip confirmation
grvt funds withdraw create \
  --to-address 0x1234...5678 --currency USDT --amount 50 --yes

# Dry-run
grvt funds withdraw create \
  --to-address 0x1234...5678 --currency USDT --amount 50 --dry-run

# Specify source sub-account
grvt funds withdraw create \
  --sub-account-id 123 --to-address 0x1234...5678 \
  --currency USDT --amount 50
```

**Validation:** `--to-address` must start with `0x` and be exactly 42 characters.

---

## `grvt funds withdraw history`

Get withdrawal history. Supports pagination.

| Option | Required | Description |
|--------|----------|-------------|
| `--start-time <time>` | No | Start time |
| `--end-time <time>` | No | End time |
| `--limit <n>` | No | Max results per page |
| `--cursor <cursor>` | No | Pagination cursor |
| `--all` | No | Auto-paginate all results |

```bash
grvt funds withdraw history
grvt funds withdraw history --limit 10
grvt funds withdraw history --start-time 2025-01-01T00:00:00Z --all --output ndjson
```


path: references/commands-config.md
content: # Config & Auth Commands

## `grvt setup`

Interactive setup wizard. Displays an ASCII banner and a full disclaimer box warning that this is a community project (not officially maintained by GRVT) with no security audit. The user must type `y` to accept the risks before the wizard proceeds.

After acceptance, it walks through: environment, API key, private key, and default sub-account ID, then authenticates automatically.

```bash
grvt setup
```

No options. All prompts are interactive (reads from stdin), which keeps sensitive values like private keys out of shell history.

**Not suitable for agents or non-interactive scripts** — use `config set` + `auth login` instead.

---

## `grvt config path`

Print the absolute path to the config file.

```bash
grvt config path
# Output: /Users/you/.config/grvt/config.toml
```

---

## `grvt config get [key]`

Get a config value. Without a key, prints the full config (secrets redacted).

| Argument | Required | Description |
|----------|----------|-------------|
| `key` | No | Config key, supports dot-notation (e.g. `http.timeoutMs`) |

```bash
grvt config get env
# Output: testnet

grvt config get outputDefaults.output
# Output: table

grvt config get
# Output: full config with secrets redacted
```

Secret keys (`apiKey`, `privateKey`, `cookie`) always print as `****`.

---

## `grvt config set <key> <value>`

Set a config value. The config is validated before saving.

| Argument | Required | Description |
|----------|----------|-------------|
| `key` | **Yes** | Config key (dot-notation) |
| `value` | **Yes** | Value to set |

Valid top-level keys: `env`, `apiKey`, `privateKey`, `subAccountId`, `accountId`, `cookie`.
Valid nested keys: `outputDefaults.output`, `outputDefaults.pretty`, `outputDefaults.silent`, `http.timeoutMs`, `http.retries`, `http.backoffMs`, `http.maxBackoffMs`.

```bash
grvt config set env testnet
grvt config set subAccountId 123456
grvt config set outputDefaults.output json
grvt config set http.timeoutMs 30000
grvt config set privateKey 0xYOUR_PRIVATE_KEY
```

---

## `grvt config unset <key>`

Remove a config value (resets to default).

| Argument | Required | Description |
|----------|----------|-------------|
| `key` | **Yes** | Config key to unset |

```bash
grvt config unset privateKey
grvt config unset http.timeoutMs
```

---

## `grvt config list`

Print the full config with secrets redacted. Equivalent to `grvt config get` with no key.

```bash
grvt config list
grvt config list --output json --pretty
```

---

## `grvt config export`

Export config to a TOML file.

| Option | Required | Description |
|--------|----------|-------------|
| `--file <path>` | **Yes** | Destination file path |
| `--include-secrets` | No | Include secret values (prompts for confirmation) |
| `--yes` | No | Skip confirmation prompt |

```bash
grvt config export --file backup.toml
grvt config export --file full-backup.toml --include-secrets --yes
```

---

## `grvt config import`

Import config from a TOML file. Overwrites all current config values.

| Option | Required | Description |
|--------|----------|-------------|
| `--file <path>` | **Yes** | Source file path |

```bash
grvt config import --file backup.toml
```

The file is validated against the config schema before saving.

---

## `grvt auth login`

Authenticate with GRVT API. Stores session cookie and account ID in config.

| Option | Required | Description |
|--------|----------|-------------|
| `--api-key <key>` | No (falls back to config) | GRVT API key |
| `--private-key <key>` | No | Ethereum private key for EIP-712 signing |
| `--env <env>` | No (falls back to config) | Environment override: `dev\|staging\|testnet\|prod` |

```bash
# Full login
grvt auth login --api-key YOUR_KEY --private-key 0xYOUR_KEY

# Using config values
grvt config set apiKey YOUR_KEY
grvt auth login

# Override environment for one login
grvt auth login --env testnet
```

On success, stores: `cookie` (session), `accountId`, and optionally `privateKey` in the config file.

---

## `grvt auth status`

Check if the current session is valid by making an API call.

```bash
grvt auth status
grvt auth status --output json
```

Returns session validity. If the session is expired, re-authenticate with `grvt auth login`.

---

## `grvt auth whoami`

Show current authentication state from local config. Does **not** make any API calls.

```bash
grvt auth whoami
grvt auth whoami --output json
```

Returns: `env`, `accountId`, `subAccountId`, `hasApiKey`, `hasPrivateKey`, `hasSession`.

---

## `grvt auth logout`

Clear all stored credentials (API key, private key, cookie, account ID) from config.

```bash
grvt auth logout
```


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (MEDIUM)