Guides
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, 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 | An index in the 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/<page>.md | Any single page as Markdown, for example /docs/trading.md or /docs/reference/trading.md (a group of routes, field by field). | The ones the task needs. |
/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 | 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#
GET /api/v1/me. It returns the key'sscopesandaccounts. Ifscopesis["read"], do not plan any trade. Ifaccountsis a list, those ids are the only ones that will work.GET /api/v1/accounts. Note each account'sstatus.connected. A disconnected account answers503to market and trade routes until it reconnects on its own.GET /api/v1/accounts/{id}/summary. Keepserver_offset(to turn market times into UTC),currency,hedging,margin_freeandtrade_allowed.- For any symbol you will touch,
GET /api/v1/accounts/{id}/symbols/{symbol}. Keepdigits,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_minon 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 answers403 real_accountuntil 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-Keyon every trade call (POST /orders,POST /order_send,PATCHandDELETEon 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 a502,503,504or a client timeout, retry with the same key; if the replayed answer is still an error,GET /positions,GET /ordersandGET /dealsbefore 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 incomment(up to 255 characters; the broker keeps 31, Termless the rest) or a number inmagic, so you can find your fill. Readwarningsin 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 areadortradekey,GET /dealsand a stream withevents=tradesare the record you can reach. - A
422is an answer, not an outage. Readretcodeandretcode_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: falseas 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
adminkey 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 thestatusevents:connected: falsemeans silence is a broken link, not a quiet market. - For your own trades, ask the same stream for
events=trades,account: atradeevent names every fill, stop hit and cancel as the broker applies it, andaccountkeepsmargin_freeandequitycurrent. Do not pollGET /positionsin a loop. Keep theidof the last event you handled; after a drop, reconnect with?after=<id>and the missed events come first. Aresyncevent means: read positions, orders and deals again. An agent that cannot hold a stream asksGET /accounts/{id}/trades?after=<id>instead. - A deal's
reasonsays why it happened:slortpis a stop hit,stop_outa margin close,weba trade sent through Termless. Read it, not the comment. - Market times (
time,time_msc) are the trade server's clock. Subtractserver_offsetfor UTC before reasoning about hours or comparing with other sources.server_offsetis 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 /candleshascomplete: use the bars where it istrue. Do not just drop the last bar; at a weekend or a daily break it is closed too. tradeableon a quote says whether a trade can be opened now (trade mode and today's sessions);falsemeans a trade would be refused with10018 Market is closedor a trade-mode code.nullprices mean the symbol has no quote yet (a closed market), not zero.
Rules for errors#
401and403(forbidden, orreal_accounton a trade): stop and report. Retrying cannot help.409on a trade: anIdempotency-Keyproblem (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 exactlyRetry-Afterseconds. 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_aton 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 sameIdempotency-Key: it is sent, not replayed).504and502on a read: retry with backoff. On a trade: retry with the sameIdempotency-Key, then look (above).500: once is a retry; twice is a report to the person, with themessageand theX-Request-Id.
A minimal safe loop#
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.
- Pick the release.
uname -mon the machine:x86_64, oraarch64(also shown asarm64). Usetermless-<version>-linux-<that>.tar.gz, unpack it, andcdinto its folder. - 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/healthanswers"status":"setup"(itsversionis null without a key). - Hand over the setup token, do not use it yourself. It is in
/var/lib/termless/setup-token(systemd) or indocker 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 withssh -N -L 8780:127.0.0.1:8780 <user>@<host>andhttp://127.0.0.1:8780. - Check the box.
termlessd doctor --data /var/lib/termless(systemd) ordocker compose exec termless /termlessd doctor(Docker). The verdict must beok; every warning carries its fix. - A domain, only if asked. Follow Your own domain for the way the person picks, then every step of Check it worked. Never open port 8780 itself.
- Keys. The person creates one key per app in API keys; the agent gets a key with the smallest scope it needs (below).
Upgrading a server for a person#
Upgrades keep every account, key and setting: the data never lives in the release folder.
- Check what runs.
termlessd version(systemd) ordocker compose exec -T termless /termlessd version(Docker, in the running release folder). Read the new release's changes (CHANGES.mdin its folder, or What's new) before going on. - Unpack the new release for the same processor, next to the old folder.
- Upgrade. systemd:
sudo sh install.shin the new folder. Docker:sh upgrade-docker.sh <old folder>in the new folder. Both back up the data first and end with the linerunning: termlessd <version>; anything else is a failure, and they print the log. - Check.
termlessd version(or the Docker command in step 1, in the new folder) shows the new version, as doesGET /api/v1/healthwith your key (versionis null without one); the doctor (step 4 of the setup above) saysok; every account inGET /api/v1/accountsisconnectedagain within a minute. - If it went wrong: systemd
sudo sh install.sh --rollback; Docker,docker compose up -din the old folder, after the steps in Going back when the database changed. Tell the person what failed, with the log lines.