> For the complete documentation index, see [llms.txt](https://thegrid.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://thegrid.ai/docs/integrations-and-best-practices/trading-bot-safety.md).

# Trading bot safety patterns

Use these patterns when you automate Advanced Mode trading. The goal is simple: check account mode, balances, market controls, and rate limits before placing an order; make retries explicit; and fail closed when the API says the request is invalid.

This applies equally to bots that [resell unused inventory](/docs/concepts/reselling.md). A sell against your Trading account balance is the same order flow as a buy, so the same checks and the same stop signals below apply.

## Minimum viable safe bot loop

1. Call `GET /v1/health` without auth. This only proves the Trading API is reachable.
2. Call signed `GET /v1/me`. Continue only when `account_mode` is `advanced` and the account has the capability you need.
3. Call signed `GET /v1/markets`. Select a market by returned `market_id`, not by transforming a symbol. Use the market's top-level `instrument_id` when you need to join to balances.
4. Call signed `GET /v1/account/limits?market_id=...`. Use `order_rate_limits.max_orders_per_second` and the `retry-after` header from 429 responses to pace order submission.
5. Call signed `GET /v1/trading-accounts` and `GET /v1/currency-trading-accounts`. Confirm you have inventory for sells and USD for buys.
6. Build the order body. For limit orders, `price` must be a decimal string such as `"0.68"`, and `quantity` must be a whole integer lot count.
7. Submit one order with a unique `client_order_id`.
8. Confirm the result with `GET /v1/orders?status=open` and, after fills, `GET /v1/trades?order_id=...`.

## Treat these responses as stop signals

`403 auto_mode_trading_restricted` means the account is still in Auto Mode. Do not retry order mutations until the account is switched to Advanced Mode.

`422 validation_error` means the request shape is wrong. Fix the request before retrying. Common causes are numeric JSON prices, unsupported `time_in_force`, invalid status filters, or fractional quantities.

`422 quantity_below_min_order_size`, `lot_size_violation`, or `tick_size_violation` means the order does not match market controls. Read `errors.context.limits`, round the order, and submit a new `client_order_id`.

`429` means you hit an order submission limit. Sleep for the `retry-after` header when present; otherwise use exponential backoff with jitter.

## Small Python skeleton

```python
import time
import uuid

def place_once(client, market_id, side, price, quantity):
    me = client.get("/v1/me")
    if me["data"]["account_mode"] != "advanced":
        raise RuntimeError("Switch to Advanced Mode before placing manual orders.")

    market = client.get(f"/v1/markets/{market_id}")["data"]
    limits = client.get(f"/v1/account/limits?market_id={market_id}")["data"]

    body = {
        "market_id": market["market_id"],
        "type": "limit",
        "side": side,
        "price": str(price),
        "quantity": int(quantity),
        "time_in_force": "gtc",
        "client_order_id": str(uuid.uuid4()),
    }

    try:
        return client.post("/v1/orders", body)
    except RateLimitError as exc:
        time.sleep(exc.retry_after or max(1 / limits["order_rate_limits"]["max_orders_per_second"], 1))
        raise
    except ValidationError as exc:
        # Surface errors.context to logs. Do not blindly retry invalid orders.
        raise
```

Run real-order scripts with unbuffered logging, for example `python3 -u bot.py`, so fills, retries, and stop signals are visible immediately.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://thegrid.ai/docs/integrations-and-best-practices/trading-bot-safety.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
