---
title: "Errors and retries"
description: "Error shapes, which errors are worth retrying, and why writes are never retried automatically."
order: 7
llms: trading, account, market-data
---

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](#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](#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](#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](#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](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](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](#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](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](#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](#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<OrderResolution> {
    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](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](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)
```
