# For AI agents How an agent should use this API without doing harm, the Idempotency-Key it sends on every trade, the trail it reads back, and how to read these docs without filling its context. Termless was built to be driven by scripts and agents as much as by people. This page is written for an agent (or the person wiring one up): the shortest safe path through the API, and how to read the documentation without filling the context. ## Load the docs Start with [`/llms.txt`](/llms.txt), then fetch only the pages the task needs. It is small (a few thousand tokens), lists every page with a one-line summary and its size in tokens, and its **Read first** list covers a bot that reads prices and trades in five pages. The whole documentation is well over 100,000 tokens: loading it into a working context leaves little room for the work and buries the part that matters. | File | What it is | When to load it | |---|---|---| | [`/llms.txt`](/llms.txt) | An index in the [llmstxt.org](https://llmstxt.org) shape: a summary, then each page as a link to its Markdown with a one-line description and its size. | First, every session. | | `/docs/.md` | Any single page as Markdown, for example [`/docs/trading.md`](/docs/trading.md) or [`/docs/reference/trading.md`](/docs/reference/trading.md) (a group of routes, field by field). | The ones the task needs. | | [`/api/openapi.json`](/api/openapi.json) | The API as OpenAPI 3.1: every route, parameter, JSON Schema, example and error, plus `x-scope` per route and `x-retcodes`. | To generate a client or validate requests by code; read a route's reference page instead. | | [`/llms-full.txt`](/llms-full.txt) | Every page of these docs as one Markdown file, in reading order. | For a search index or an offline copy, not a model's working context. | All four are served by the same binary, so they always describe the server that serves them. If a client builds requests from the OpenAPI document, it should prefer `x-scope` to work out which key it needs and `x-retcodes` to explain a refusal. ## Start every session the same way 1. `GET /api/v1/me`. It returns the key's `scopes` and `accounts`. If `scopes` is `["read"]`, do not plan any trade. If `accounts` is a list, those ids are the only ones that will work. 2. `GET /api/v1/accounts`. Note each account's `status.connected`. A disconnected account answers `503` to market and trade routes until it reconnects on its own. 3. `GET /api/v1/accounts/{id}/summary`. Keep `server_offset` (to turn market times into UTC), `currency`, `hedging`, `margin_free` and `trade_allowed`. 4. For any symbol you will touch, `GET /api/v1/accounts/{id}/symbols/{symbol}`. Keep `digits`, `volume_min`, `volume_step`, `stops_level`, `point`, `sessions.trade`. Everything after that is reading prices and, with permission, trading. ## Rules for trading - **Read before you trade.** A trade request is only right in the light of the spec and the summary read in this session, not from memory. - **Small, demo, explicit.** Trade at `volume_min` on a demo account until a person has looked at the results. Never scale up on your own. On an account the broker reports as real money, trading answers `403 real_account` until an admin turns it on; never ask for that yourself or work around it. - **Every market order carries a stop loss** unless the person asked otherwise. - **Always send an `Idempotency-Key`** on every trade call (`POST /orders`, `POST /order_send`, `PATCH` and `DELETE` on orders and positions): a new key per intended trade, the **same key on every retry**. A retry then replays the first answer (`Idempotent-Replayed: true`) and the broker never sees the trade twice. After a `502`, `503`, `504` or a client timeout, retry with the same key; if the replayed answer is still an error, `GET /positions`, `GET /orders` and `GET /deals` before you decide to send it again under a new key. Never retry with a new key or without one. Put an id of your own in `comment` (up to 255 characters; the broker keeps 31, Termless the rest) or a number in `magic`, so you can find your fill. Read `warnings` in every trade result: it says what was cut, swapped or kept. - **Send your own `X-Request-Id`** (up to 64 characters) and keep it in your log. The server echoes it, writes it on every log line of the request and on the audit row the trade caused, so a person can line your log up with the server's. - **Read the trail, not your memory.** `GET /api/v1/audit?kind=trade&account={id}` (admin) is the authoritative record of every trade call: the request, the retcode, the result, the broker latency, the request id. Prefer it to your own notes when they disagree. With a `read` or `trade` key, `GET /deals` and a stream with `events=trades` are the record you can reach. - **A `422` is an answer, not an outage.** Read `retcode` and `retcode_text`, fix the request (volume, price, stops, market hours) and try again only if the fix is clear, under a new key. Never loop on it. - **Treat `ok: false` as not done**, whatever the HTTP status. - **Prefer the plain routes** (`/orders`, `/positions/{ticket}`) over `/order_send`; they refuse malformed requests before they reach the broker. - **Do not change accounts, keys or the server** unless that is the task. An `admin` key in an agent is a mistake unless the agent administers the server. ## Rules for reading - For prices as they happen, open one stream (SSE) with every symbol you need instead of polling `GET /quotes`. Watch the `status` events: `connected: false` means silence is a broken link, not a quiet market. - For your own trades, ask the same stream for `events=trades,account`: a `trade` event names every fill, stop hit and cancel as the broker applies it, and `account` keeps `margin_free` and `equity` current. Do not poll `GET /positions` in a loop. Keep the `id` of the last event you handled; after a drop, reconnect with `?after=` and the missed events come first. A `resync` event means: read positions, orders and deals again. An agent that cannot hold a stream asks `GET /accounts/{id}/trades?after=` instead. - A deal's `reason` says why it happened: `sl` or `tp` is a stop hit, `stop_out` a margin close, `web` a trade sent through Termless. Read it, not the comment. - Market times (`time`, `time_msc`) are the trade server's clock. Subtract `server_offset` for UTC before reasoning about hours or comparing with other sources. `server_offset` is the offset now; times from before the broker's last summer-time switch were stamped with the old one. Termless's own times (`created_at`, `since`, `last_used_at`) are already UTC. - Each candle in `GET /candles` has `complete`: use the bars where it is `true`. Do not just drop the last bar; at a weekend or a daily break it is closed too. - `tradeable` on a quote says whether a trade can be opened now (trade mode and today's sessions); `false` means a trade would be refused with `10018 Market is closed` or a trade-mode code. - `null` prices mean the symbol has no quote yet (a closed market), not zero. ## Rules for errors - `401` and `403` (`forbidden`, or `real_account` on a trade): stop and report. Retrying cannot help. - `409` on a trade: an `Idempotency-Key` problem (reused with a different body or query string, or the first request did not finish, perhaps because the server restarted). Check positions and orders, then use a new key. It is never a sign that a second trade went out. - `429`: wait exactly `Retry-After` seconds. It is a lockout or a stream cap, and more requests make it longer. - `503 disconnected`: the account is reconnecting. Back off (1 s, 2, 4, up to 30 s) and read again. `status.retry_at` on the account says when the next attempt is. - `503 busy`: the request waited its whole turn behind others of its kind and was never sent. Send it again (a trade with the same `Idempotency-Key`: it is sent, not replayed). - `504` and `502` on a read: retry with backoff. On a trade: retry with the same `Idempotency-Key`, then look (above). - `500`: once is a retry; twice is a report to the person, with the `message` and the `X-Request-Id`. ## A minimal safe loop ```python import os, time, uuid, requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} me = requests.get(f"{base}/me", headers=auth).json() may_trade = "trade" in me["scopes"] or "admin" in me["scopes"] acc = (me["accounts"] or [a["id"] for a in requests.get(f"{base}/accounts", headers=auth).json()])[0] summary = requests.get(f"{base}/accounts/{acc}/summary", headers=auth).json() spec = requests.get(f"{base}/accounts/{acc}/symbols/XAUUSD", headers=auth).json() assert summary["demo"], "this loop is for demo accounts" quote = requests.get(f"{base}/accounts/{acc}/quotes", headers=auth, params={"symbols": "XAUUSD"}).json()[0] if quote["bid"] is None or quote["tradeable"] is False: raise SystemExit("no trading right now; the market is closed") if may_trade: tag = f"agent-{int(time.time())}" key = f"agent-{uuid.uuid4()}" # one key per intended trade stop = round(quote["bid"] - 1000 * spec["point"], spec["digits"]) # 1000 points below the bid order = {"symbol": "XAUUSD", "side": "buy", "volume": spec["volume_min"], "sl": stop, "comment": tag} for attempt in range(4): r = requests.post(f"{base}/accounts/{acc}/orders", json=order, timeout=35, headers={**auth, "Idempotency-Key": key, "X-Request-Id": f"{tag}-{attempt}"}) if r.status_code in (502, 503, 504) and r.headers.get("Idempotent-Replayed") != "true": time.sleep(2 * (attempt + 1)) # same key next time: never a second trade continue break result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) # fix the request; a new key for a new try elif r.status_code in (502, 503, 504): deals = requests.get(f"{base}/accounts/{acc}/deals", headers=auth).json() print("the broker never answered; my deals:", [d for d in deals if d["comment"] == tag]) else: r.raise_for_status() print("filled at", result["price"], "ticket", result["order"], "(replayed)" if r.headers.get("Idempotent-Replayed") == "true" else "", "request", r.headers["X-Request-Id"]) ``` ## Give the agent the right key The person wiring the agent up should create a key with the narrowest scope that does the job and limit it to the account the agent works on: `{"name": "research agent", "scopes": ["read"], "accounts": ["pepperstone-12345678"]}`. A `read` key cannot place an order no matter what the agent is asked. Revoke it in one call when the job is done. ## Setting up a server for a person When an agent installs Termless on someone's machine, follow these steps in order and check each one before the next. Ask the person before anything that opens the server to the internet. 1. **Pick the release.** `uname -m` on the machine: `x86_64`, or `aarch64` (also shown as `arm64`). Use `termless--linux-.tar.gz`, unpack it, and `cd` into its folder. 2. **Install.** With systemd and root: `sudo sh install.sh`. With Docker instead: `cp example.env .env && docker compose up -d --build`. Check: `curl -s http://127.0.0.1:8780/api/v1/health` answers `"status":"setup"` (its `version` is null without a key). 3. **Hand over the setup token, do not use it yourself.** It is in `/var/lib/termless/setup-token` (systemd) or in `docker compose logs termless`. The person enters it in the dashboard and chooses the admin password, so the password is never in your context. They reach the dashboard with `ssh -N -L 8780:127.0.0.1:8780 @` and `http://127.0.0.1:8780`. 4. **Check the box.** `termlessd doctor --data /var/lib/termless` (systemd) or `docker compose exec termless /termlessd doctor` (Docker). The verdict must be `ok`; every warning carries its fix. 5. **A domain, only if asked.** Follow [Your own domain](/docs/domains) for the way the person picks, then every step of [Check it worked](/docs/domains#check-it-worked). Never open port 8780 itself. 6. **Keys.** The person creates one key per app in **API keys**; the agent gets a key with the smallest scope it needs ([below](#give-the-agent-the-right-key)). ## Upgrading a server for a person Upgrades keep every account, key and setting: the data never lives in the release folder. 1. **Check what runs.** `termlessd version` (systemd) or `docker compose exec -T termless /termlessd version` (Docker, in the running release folder). Read the new release's changes (`CHANGES.md` in its folder, or [What's new](/docs/releases)) before going on. 2. **Unpack the new release** for the same processor, next to the old folder. 3. **Upgrade.** systemd: `sudo sh install.sh` in the new folder. Docker: `sh upgrade-docker.sh ` in the new folder. Both back up the data first and end with the line `running: termlessd `; anything else is a failure, and they print the log. 4. **Check.** `termlessd version` (or the Docker command in step 1, in the new folder) shows the new version, as does `GET /api/v1/health` with your key (`version` is null without one); the doctor (step 4 of the setup above) says `ok`; every account in `GET /api/v1/accounts` is `connected` again within a minute. 5. **If it went wrong:** systemd `sudo sh install.sh --rollback`; Docker, `docker compose up -d` in the old folder, after the steps in [Going back](/docs/docker#going-back) when the database changed. Tell the person what failed, with the log lines.