# Build an LLM trading bot for MetaTrader, safely

> Tickwire lets an LLM trading bot read and trade MT4 or MT5 through agent keys with scoped accounts, read-only mode, kill switches and an audit log of every order.

Source: https://tickwire.io/blog/llm-trading-bot-metatrader/

Tickwire blog, published 2026-11-02. General information, not investment advice.

An LLM trading bot for MetaTrader is a loop where a language model reads the account, decides, and calls a trade tool. Tickwire gives that loop a hosted MT4 or MT5 terminal and an agent API, with scoped keys, read-only mode, kill switches, an optional pre-trade hook and an audit log, so a confused model can't do more than you allow. This post shows the shape of such a bot in Python, and the checks to put around it.

A word first. A language model is good at reading, summarising and following rules you write down. It does not know where the market is going, and nothing here makes a strategy profitable. Treat the model as a careful assistant that can make mistakes, and build the bot so its mistakes are small.

## The parts of the bot

1. **A trading account on a hosted terminal.** The model needs a tool that holds the account. Tickwire runs the terminal in the cloud, so the bot can live on any server, a Mac or a laptop.
2. **An agent key.** A `twag_` key limited to the accounts the bot may use, read-only until you trust it.
3. **Tools for the model.** Either the MCP server at `https://api.tickwire.io/mcp`, for frameworks that speak MCP, or plain REST routes under `/v1/agent/…` for your own loop.
4. **Your rules, outside the model.** Size limits, daily loss limits and trading hours go in a pre-trade hook you run, not in the prompt.
5. **A way to stop it.** A kill switch you can reach from the dashboard.

## Create a scoped, read-only key

```bash
curl -s -X POST https://api.tickwire.io/v1/agent-keys \
  -H "Authorization: Bearer $TICKWIRE_API_KEY" \
  -H "content-type: application/json" -H "X-Reason: research agent" \
  -d '{"name": "research-agent", "account_ids": ["<ACCOUNT_ID>"], "read_only": true}'
```

The `twag_` key is shown once. Keep it in an environment variable. Start read-only: let the bot read and explain for a while before it may trade. Change it later in the dashboard.

## Give the model only the tools it needs

With an agent framework, point it at the MCP server and list the allowed tools. A bot that only reads should not even see `place_order`. The [AI agent guide](https://tickwire.io/docs/guides/ai-agent/) has full examples for the Claude Agent SDK and the OpenAI Agents SDK.

If you write your own loop, map each tool to a REST call:

| Tool | Route |
|---|---|
| list accounts | `GET /v1/agent/accounts` |
| health | `GET /v1/agent/accounts/{id}/health` |
| balance and equity | `GET /v1/agent/accounts/{id}/account-information` |
| positions, orders | `GET /v1/agent/accounts/{id}/positions` and `…/orders` |
| price | `GET /v1/agent/accounts/{id}/symbols/{symbol}/current-price` |
| trade | `POST /v1/agent/accounts/{id}/trade` |

## A trade call that can't trade twice

The most common way a bot loses money by accident is a retry. A request times out, the code sends it again, and now there are two positions. The fix is one idempotency key per decision, reused on every retry:

```python
import os, uuid, requests

API = "https://api.tickwire.io"
HEADERS = {"X-Tickwire-Agent-Key": os.environ["AGENT_KEY"]}

def trade(account_id: str, order: dict, reason: str, key: str | None = None) -> dict:
    """Send one order. Reuse `key` to repeat the same order safely."""
    key = key or str(uuid.uuid4())
    try:
        r = requests.post(f"{API}/v1/agent/accounts/{account_id}/trade", json=order, timeout=30,
                          headers={**HEADERS, "Idempotency-Key": key, "X-Reason": reason})
    except requests.RequestException:
        # No answer: the order may have gone. Ask, with the same key.
        return status(key)
    body = r.json()
    body["idempotency_key"] = key
    return body

def status(key: str) -> dict:
    r = requests.get(f"{API}/v1/agent/requests/{key}", headers=HEADERS, timeout=30)
    return r.json()
```

The `reason` is required. Ask the model to write one sentence on why it is trading, and pass it through. It goes into the audit log, so you can read later what the bot was thinking.

## Read the outcome, every time

Every answer has an `outcome`. Put this table in the model's instructions and in your code:

| `outcome` | Meaning | What the bot does |
|---|---|---|
| `applied` | The terminal confirmed it | Carry on |
| `no_change` | Nothing needed doing | Carry on |
| `rejected` | Not executed | Read `error`, don't loop on it |
| `held` | Your hook is holding it for approval | Wait, never resend |
| `unknown` | It may have executed | Call `status(key)`, then read positions |

`read_only_key`, `kill_switch_engaged` and `hook_denied` are your decisions as the owner. Tell the model to report them and stop, not to look for a way around them.

## Put your rules in a hook, not the prompt

A prompt is a suggestion. A model can misread it, forget it in a long chat, or be talked out of it by text inside a symbol comment or a news item. Rules that protect money belong in code the model can't change.

Tickwire's pre-trade hook posts each order, who asked and why, plus a fresh read of the account, to an HTTPS endpoint you run. The request is signed with HMAC-SHA256. Your code answers `allow`, `deny` or `hold`. If the hook can't be reached or its answer can't be verified, the order is not sent. Typical rules:

- a maximum volume per order and per symbol;
- a daily loss limit, measured on the broker's day, not UTC;
- trading hours, and no trading near the weekend close;
- hold anything above a size for a human to approve.

Tickwire sets no size or loss limits for you. See [Write a pre-trade hook](https://tickwire.io/blog/write-a-pre-trade-hook/) and [AI agent risk controls](https://tickwire.io/blog/ai-agent-risk-controls/).

## Check health before every decision

A bot that trades on a frozen price is guessing. Before each decision, read health. `connected` with evidence means the terminal is logged in and the account was read. `prices_live: false` means no price is moving, which usually means the market is closed. If the quote is stale, market orders answer `409 quote_stale` and nothing is sent. See [Is my bot really connected?](https://tickwire.io/blog/is-my-bot-really-connected/).

## Test the failures before the market does

The free [sandbox](https://tickwire.io/docs/sandbox/) has magic logins that act out the cases a bot gets wrong: `1032` gives an `unknown` outcome, `1019` a rejection for no money, `1040` a disconnect, `1050` frozen quotes. Run the bot against each one and read the audit log after. Then move to a demo account, and only then to real money, with a small size. The [MetaTrader MCP server](https://tickwire.io/metatrader-mcp-server/) page lists every tool such a bot can call.

## Frequently asked questions

### Can an LLM trade MetaTrader on its own?

Not without a tool that holds the account. Tickwire is that tool: it runs the MT4 or MT5 terminal and gives the model read and trade tools through MCP or REST, limited by the key you create.

### Which LLM should I use for a trading bot?

Any model that can call tools works. Tickwire's tools are plain MCP and HTTPS, so Claude, ChatGPT and other models can use them. Choose the model for how well it follows your rules, and keep the rules that protect money in a pre-trade hook.

### How do I stop an LLM bot from placing duplicate orders?

Use one Idempotency-Key per decision and reuse it on every retry. Tickwire returns the first answer for a repeated key, never a second order. After an unknown outcome, check the status and positions before anything else.

### How do I stop the bot at once?

Engage the kill switch for its agent key or for the account, in the dashboard or with the API. Every order it sends after that is refused with kill_switch_engaged and nothing reaches the broker.

### Will an LLM trading bot make money?

Nobody can promise that. A language model does not predict prices. Tickwire handles the connection, the safety checks and the records, but the strategy and its risk are yours. Trading carries risk, and you can lose money.

### Does this work on MT4?

Yes. The agent tools work on MT4 and MT5 accounts. A few MT5 features, such as market depth and tick history, answer not_supported_on_mt4. See [pricing](https://tickwire.io/pricing/) for the cost per account.
