# Termless API documentation > Keep MetaTrader 5 accounts connected around the clock and use them over HTTP. This file is every page of the docs as one Markdown document, in reading order. Each page is also at its own URL (/docs/.md), and the machine-readable API description is /api/openapi.json. # Introduction MetaTrader 5 without the terminal. Termless keeps your MT5 accounts logged in on a Linux box and gives every app, script and AI agent one HTTP API for prices, candles, account state and trading. Termless is a server, `termlessd`: one static binary that speaks the MetaTrader 5 protocol straight to your broker, keeps each account connected around the clock, and serves everything over HTTP. There is no MetaTrader terminal, no Windows and no Wine anywhere. Your bots, scripts and agents talk to Termless; Termless talks to the broker. ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/quotes?symbols=XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import os, requests r = requests.get(os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/quotes", headers={"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}, params={"symbols": "XAUUSD"}) print(r.json()[0]) ``` ```javascript const res = await fetch(`${process.env.TERMLESS_URL}/api/v1/accounts/pepperstone-12345678/quotes?symbols=XAUUSD`, { headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }, }); console.log((await res.json())[0]); ``` ```json [{"symbol": "XAUUSD", "bid": 2391.42, "ask": 2391.6, "last": 0, "time": 1790981179, "time_msc": 1790981179473, "tradeable": true}] ``` ## What you get | | | |---|---| | **Market data** | Symbol search, full symbol specs (lot limits, stop levels, sessions, swaps, margin rates), quotes, candles on 21 timeframes (up to about 100,000 bars back on each; M1 reaches about three months), recent ticks and order books. | | **Live prices and events** | Every tick, pushed over Server-sent events or a WebSocket, and on the same stream every trade the broker applies, the account's money and the live P/L of its positions, so a bot never polls. One stream carries up to 200 symbols. | | **Account state** | Balance, equity, margin, open positions with live profit, pending orders and deal history, the same numbers MT5 shows. | | **Trading** | Market and pending orders, stop loss and take profit, partial closes, cancels, margin and profit worked out and orders checked before you send them, and a route that takes the official `MetaTrader5` `order_send` request unchanged. An `Idempotency-Key` on every call makes retries safe. | | **Trails** | An audit trail of every write with the request id that caused it, each account's connection history, and an equity curve. | | **Keys and scopes** | Each app gets its own key with one scope, `read`, `trade` or `admin`, optionally limited to some accounts. Revoke one without touching the rest. | | **A dashboard** | Accounts, a live tab with a chart and a ticket, keys, and diagnostics, at `/` on the same server. | ## The mental model Five ideas carry the whole API. Everything else is detail. ### Accounts An **account** is one MT5 login at one broker server. You add it once with its login, password and server name; Termless stores the password encrypted and keeps a session to the broker open. Every account has an **id** you choose (`pepperstone-12345678` by default: the server's first word and the login), and that id appears in every market and trading URL: `/api/v1/accounts/{id}/...`. ### Sessions Behind each account is a supervised session. It logs in, subscribes the watchlist, answers your requests, and when the link drops it reconnects on its own (1 s, then 2, 4, up to 30 s between tries). While it is reconnecting, routes that need the broker answer `503 disconnected`; nothing else changes. You never log in or out yourself. ### Two clocks Market and trade times (`time`, `time_msc` on ticks, candles, positions, orders and deals, and the `from` and `to` you send) are in the **trade server's clock**, exactly as MetaTrader reports them. Most brokers run UTC+2 or UTC+3. Each account's summary tells you the offset as `server_offset` (seconds east of UTC); subtract it to get UTC. Times about Termless itself (`created_at`, `status.since`, `last_used_at`) are plain UTC. The [conventions](/docs/conventions) page has the recipe. ### Lots Volumes are **lots**, as in MT5: `0.01` is the smallest order on most symbols, `1.00` is one standard lot (100,000 units of a currency pair, 100 ounces of gold). Each symbol's spec says its `volume_min`, `volume_max` and `volume_step`; read it before you size an order. ### Retcodes Every trade call returns a **trade result** with the broker's own return code. `10009` means done, `10008` means placed, `10010` means partly filled; those three set `ok: true` and answer `200`. A placed pending order is `10008` or `10009` depending on the broker, so read `ok`. Anything else is a refusal: the response is `422` with the same trade result (`ok: false`, the `retcode`, its text) so you can read why. [Trading safely](/docs/trading) explains how to act on them. ## Where to go next - [Quickstart](/docs/quickstart): a key, a quote, candles, a stream and a demo trade in under five minutes. - [API reference](/docs/reference): every route with every field, and copy-ready calls in curl, Python and JavaScript. - [For AI agents](/docs/agents): how an agent should use this API, and how to read these docs without filling its context: [llms.txt](/llms.txt) first, then only the pages it needs. - [The MetaTrader5 Python mapping](/docs/python-mapping): every official `MetaTrader5` call and the route that does the same, for porting a script. - [Running the server](/docs/running): install, settings, the data folder, upgrades, the doctor and diagnostics. - [Setting up a bot](/docs/bots): one login, one key per program, an Idempotency-Key per order, what an `unconfirmed` trade means, timeouts, and where to watch the link. - [Health checks for bots](/docs/health-checks): ask `/ready` before an order, read uptime, outages and order latency from `/status`, scrape `/metrics`. - [Activity and trails](/docs/trails): the audit trail, connection history and equity curve, and the request id that ties them to your own log. - [What's new](/docs/releases): what changed in each release, and when the database changed. > **Note: Demo first** > > The examples use a Pepperstone demo account. On an account the broker reports as real money, every route that trades answers `403 real_account` until an admin turns trading on for it (`trade_real`, in the account's settings); reading works either way, and `summary.demo` says which kind an account is. Prove your code on a demo before you point a key with the `trade` scope at money. --- # Quickstart From a fresh key to a live price stream and a demo trade in five short steps. You need a running Termless server with one account added (the [running the server](/docs/running) page covers that) and a terminal. Every example on this site reads two environment variables, so set them once. ## 1. Create a key Open the dashboard, go to **API keys** and create one. Pick the scope it needs: **read** to look at prices and accounts, **trade** if it will place orders. Limit it to the account it works with. The full key is shown once, so copy it then. Or do the same over the API with the admin cookie (see [authentication](/docs/authentication)): ```sh curl -s -X POST "$TERMLESS_URL/api/v1/keys" -b cookies.txt \ -H "Content-Type: application/json" \ -d '{"name": "quickstart", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]}' ``` Then put the address of your server and the key in your shell: ```sh export TERMLESS_URL="https://your-server" export TERMLESS_KEY="tl_paste_the_key_here" ``` ## 2. See what the key can reach `GET /api/v1/me` tells you the key's scope and accounts. `GET /api/v1/accounts` lists the accounts it may see, each with its connection status. ```sh curl -s "$TERMLESS_URL/api/v1/me" -H "Authorization: Bearer $TERMLESS_KEY" curl -s "$TERMLESS_URL/api/v1/accounts" -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} me = requests.get(f"{base}/me", headers=auth).json() print(me["scopes"], me["accounts"]) accounts = requests.get(f"{base}/accounts", headers=auth).json() acc = accounts[0]["id"] print(acc, "connected:", accounts[0]["status"]["connected"]) ``` ```javascript const base = `${process.env.TERMLESS_URL}/api/v1`; const headers = { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }; const get = async (path) => { const res = await fetch(base + path, { headers }); if (!res.ok) throw new Error((await res.json()).error.message); return res.json(); }; const me = await get("/me"); console.log(me.scopes, me.accounts); const [account] = await get("/accounts"); console.log(account.id, "connected:", account.status.connected); ``` ```json {"kind": "key", "name": "quickstart", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]} ``` ## 3. A quote and some candles Quotes are the latest bid and ask, and `tradeable` says whether a trade can be opened right now. The first request for a symbol subscribes it at the broker and waits up to three seconds for a price; later requests answer at once. Candles come oldest first, and each says whether it is `complete`: the newest is usually still forming. ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/quotes?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/candles?symbol=XAUUSD&timeframe=M5&count=100" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python quotes = requests.get(f"{base}/accounts/{acc}/quotes", headers=auth, params={"symbols": "XAUUSD,EURUSD"}).json() for q in quotes: print(q["symbol"], q["bid"], q["ask"]) bars = requests.get(f"{base}/accounts/{acc}/candles", headers=auth, params={"symbol": "XAUUSD", "timeframe": "M5", "count": 100}).json() print(len(bars["candles"]), "bars, last close", bars["candles"][-1]["close"]) ``` ```javascript const quotes = await get(`/accounts/${account.id}/quotes?symbols=XAUUSD,EURUSD`); for (const q of quotes) console.log(q.symbol, q.bid, q.ask); const { candles } = await get(`/accounts/${account.id}/candles?symbol=XAUUSD&timeframe=M5&count=100`); console.log(candles.length, "bars, last close", candles.at(-1).close); ``` If you would rather not install anything, Python's standard library is enough: ```python import json import os import urllib.request base = os.environ["TERMLESS_URL"] + "/api/v1" req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/quotes?symbols=XAUUSD", headers={"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}) with urllib.request.urlopen(req, timeout=10) as r: print(json.load(r)[0]) ``` ## 4. A live stream Polling quotes works, but a stream gives you every tick as it happens. The simplest is Server-sent events: plain HTTP, readable with `curl -N`. The first event is a `status` saying whether the account is connected; then each price change is a `tick`. ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import json with requests.get(f"{base}/accounts/{acc}/stream", headers=auth, params={"symbols": "XAUUSD,EURUSD"}, stream=True, timeout=(5, 30)) as r: r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line.startswith("event:"): event = line[6:].strip() elif line.startswith("data:") and event == "tick": t = json.loads(line[5:]) print(t["symbol"], t["bid"], t["ask"]) ``` ```javascript // In a browser (EventSource cannot send headers, so the key goes in the query) const url = new URL(`/api/v1/accounts/${account.id}/stream`, process.env.TERMLESS_URL); url.searchParams.set("symbols", "XAUUSD,EURUSD"); url.searchParams.set("key", process.env.TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("tick", (e) => { const t = JSON.parse(e.data); console.log(t.symbol, t.bid, t.ask); }); ``` ```sse event: status data: {"connected":true,"ping_ms":14.2} event: tick data: {"symbol":"XAUUSD","bid":2391.42,"ask":2391.6,"last":0,"time_msc":1790981179473} : heartbeat ``` The [streaming prices](/docs/streaming) page covers the WebSocket flavour, reconnects and what a `status` event means. ## 5. A demo trade Read the symbol's spec first: `volume_min` is the smallest order, `stops_level` the closest a stop may sit. Then place a market buy of 0.01 lots with a stop loss and take profit, look at the result, and close it. ```sh # the spec curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/symbols/XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" # buy 0.01 lots at market (the Idempotency-Key makes a retry of this exact call safe) curl -s -X POST "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders" \ -H "Authorization: Bearer $TERMLESS_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: quickstart-$(date +%s)" \ -d '{"symbol": "XAUUSD", "side": "buy", "volume": 0.01, "sl": 2380.0, "tp": 2420.0, "comment": "quickstart"}' # close it (the ticket is "order" in the result, also in GET .../positions) curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830031" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python spec = requests.get(f"{base}/accounts/{acc}/symbols/XAUUSD", headers=auth).json() print("smallest order", spec["volume_min"], "lots; stops at least", spec["stops_level"], "points away") import uuid r = requests.post(f"{base}/accounts/{acc}/orders", headers={**auth, "Idempotency-Key": f"quickstart-{uuid.uuid4()}"}, json={ "symbol": "XAUUSD", "side": "buy", "volume": spec["volume_min"], "sl": 2380.0, "tp": 2420.0, "comment": "quickstart"}) result = r.json() if r.status_code == 422: raise SystemExit(f"refused: {result['retcode']} {result['retcode_text']}") r.raise_for_status() print("filled", result["volume"], "lots at", result["price"], "ticket", result["order"]) r = requests.delete(f"{base}/accounts/{acc}/positions/{result['order']}", headers=auth) print("closed:", r.json()["retcode_text"]) ``` ```javascript const spec = await get(`/accounts/${account.id}/symbols/XAUUSD`); console.log("smallest order", spec.volume_min, "lots"); const place = await fetch(`${base}/accounts/${account.id}/orders`, { method: "POST", headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": `quickstart-${crypto.randomUUID()}` }, body: JSON.stringify({ symbol: "XAUUSD", side: "buy", volume: spec.volume_min, sl: 2380.0, tp: 2420.0, comment: "quickstart" }), }); const result = await place.json(); if (place.status === 422) throw new Error(`refused: ${result.retcode} ${result.retcode_text}`); console.log("filled", result.volume, "lots at", result.price, "ticket", result.order); const close = await fetch(`${base}/accounts/${account.id}/positions/${result.order}`, { method: "DELETE", headers }); console.log("closed:", (await close.json()).retcode_text); ``` ```json {"ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 81200131, "order": 51830031, "volume": 0.01, "price": 2391.6, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31} ``` ```json {"ok": false, "retcode": 10014, "retcode_text": "Invalid volume", "deal": 0, "order": 0, "volume": 0, "price": 0, "bid": 2391.42, "ask": 2391.6, "comment": "Invalid volume", "request_id": 32, "error": {"code": "rejected", "message": "the broker refused the request: Invalid volume (10014)"}} ``` > **Careful: Markets close** > > Forex and gold close on Friday evening and open on Sunday evening (broker time). A trade then is refused with `10018 Market is closed`, and a quote has `null` prices until the first tick. Pepperstone's crypto symbols trade through the weekend, so they are handy for a weekend test. ## Where to go next - [Trading safely](/docs/trading): market versus pending, stops, partial closes, reading a refusal, and the `Idempotency-Key` that makes a retry safe. - [Streaming prices](/docs/streaming): ticks, and the `trade`, `account`, `positions` and `orders` events a bot reads instead of polling. - [Errors and retries](/docs/errors): every status code and what to do about it. - [API reference](/docs/reference): every route, with its fields, errors and examples. --- # Finding your broker's server Where to find your MT5 server name and your broker's web terminal address, in the broker's client area, on its website or in a prop firm's dashboard, and how to add it to Termless. Termless connects to your broker the way MetaTrader's web terminal does, so it needs two things: your account's **server name** (for example `Pepperstone-Demo`) and the address of your broker's **MT5 web terminal** (for example `mt5-demo01.pepperstone.com`). For many brokers the second part is already known. ## 1. Search the directory first In the dashboard, **Accounts > Add account**, type your broker or your server name in **Search the directory**. Termless ships with a list of brokers whose web terminal it has checked. If yours is there, pick it, enter your login and password, and you are done. ## 2. Find your server name You need the exact name, capitals included. It is in any of these: - **MetaTrader 5 on a computer:** File, Login to Trade Account. The Server field shows it. - **MetaTrader 5 on a phone:** Settings, then tap your account at the top. The server is under your name and login. - **The broker's welcome email** for the account, next to the login number. - **The broker's client area**, on the account's details. Demo and live accounts are usually on different servers (`...-Demo` and `...-Live`, or `...-Server`), and many brokers have several live servers. ## 3. Find the web terminal's address The address is the page where you trade MT5 in a browser. Look for a button called **WebTrader**, **Web Terminal**, **Trade in browser** or **Open MT5 web**: - **In your broker's client area**, next to the account. This is where most brokers put it. Open it, and copy the address from the browser's address bar. - **On the broker's website**, usually under Platforms, then MetaTrader 5, then WebTrader. The Launch button opens the terminal. - **In the help centre**: search for "MT5 WebTrader" or "web terminal". - **In a prop firm's dashboard**, on the account's page, often called Trade or Launch platform. If the terminal opens inside the firm's own page instead of its own tab, right-click on the terminal and choose **View frame source** (Chrome, Edge, Brave) or **This Frame, Open Frame in New Tab** (Firefox); the address you need is the one that shows up there. The address you are after usually ends in `/terminal`, for example: ```text https://mt5-demo01.pepperstone.com/terminal https://webtrader.examplebroker.com/terminal?mode=demo&lang=en ``` The address is not secret. Copy it as it is; nothing in it logs you in. ## 4. Check it in Termless In **Add account**, switch to **Check a host** and paste the address. A whole link works, and so does just the host (`webtrader.examplebroker.com`, or with a port, `webtrader.examplebroker.com:443`). Termless opens the public terminal page, reads which servers it serves and which MT5 version it runs, and lists them. Pick your server name, then enter your login and password. The broker is remembered, so the next account on it is one search away. Over the API it is `POST /api/v1/servers/check` with `{"host": "..."}`; see [Accounts and servers](/docs/reference/accounts). ## When it does not work - **The broker has no MT5 web terminal.** Some brokers offer MetaTrader only as an app, and some brokers' "web trader" is their own platform rather than MetaTrader's. Termless needs MetaTrader's own web terminal; if the check says no terminal was found there, ask the broker whether it offers the MT5 WebTerminal for your server. - **The page lists other server names.** One terminal often serves several of a broker's servers, or a partner company's under another name. Pick the one that matches your account; if yours is missing, that terminal is not for your server. - **The certificate is for another name.** Some brokers' web terminals present a certificate made out to a different name. Termless shows the certificate's details, and an admin can choose to trust that exact certificate for that broker; it is refused if it ever changes. - **The login is refused.** Check the server name, the login and the password (MT5 passwords are case-sensitive). An investor (read-only) password logs in but cannot trade. --- # Authentication and scopes API keys with one scope each, limited to the accounts they need; the dashboard's own session; and how the two differ. Every API call carries a key in the `Authorization` header. A request without a valid key answers `401 unauthorized`; a key that may not do what was asked answers `403 forbidden`. ```sh curl -s "$TERMLESS_URL/api/v1/me" -H "Authorization: Bearer $TERMLESS_KEY" ``` ## Keys A key looks like `tl_` followed by 48 hex characters. Termless stores only its SHA-256 hash, so the full key appears exactly once: in the response that creates it. Lose it and you create a new one; the `prefix` (the first 12 characters) is what you see in lists afterwards, to tell keys apart. Create keys in the dashboard (**API keys**) or with `POST /api/v1/keys` using an admin key or the dashboard session: ```sh curl -s -X POST "$TERMLESS_URL/api/v1/keys" -b cookies.txt \ -H "Content-Type: application/json" \ -d '{"name": "EA bridge (gold)", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]}' ``` ```json {"id": "key_3f9a1c07", "name": "EA bridge (gold)", "prefix": "tl_4be1a09", "scopes": ["trade"], "accounts": ["pepperstone-12345678"], "created_at": 1790981179, "last_used_at": null, "key": "tl_4be1a09c7d2e5f8b1a3c6e9d0f2b4a7c8e1d3f5a7b9c0e2d"} ``` Revoke with `DELETE /api/v1/keys/{id}`; the key stops working at once. ## Scopes A key has exactly one scope. Each includes the one before it. | Scope | May | Give it to | |---|---|---| | `read` | List accounts and their status, balance and margin, symbols and specs, quotes, candles, streams, positions, orders and deals. | Dashboards, journals, backtests, analysis agents, anything that only looks. | | `trade` | Everything `read` may, plus place, modify, cancel and close. On an account the broker reports as real money, only once an admin has turned trading on for it (`trade_real`); until then those routes answer `403 real_account`. | Bots and agents that trade. Limit it to the accounts they trade. | | `admin` | Everything, including adding and changing accounts, creating keys, the server directory and diagnostics. | Your own tooling. Never an agent that does not need it. | Scopes apply per route; the reference shows the scope next to every route, and `GET /api/v1/me` shows what the key you hold may do. ## Limiting a key to some accounts A `read` or `trade` key can be created with `accounts: ["pepperstone-12345678"]`. It then sees only those accounts: others are left out of `GET /api/v1/accounts`, `GET /api/v1/health` lists only those, and any account URL outside the list answers `403`. An `admin` key cannot be limited (the request is `400`), because admin routes are not about one account. This is the main safety tool. A trading bot gets a `trade` key for its one demo account; it cannot touch anything else even if its code goes wrong. ## Streams take the key in the query Browsers cannot set headers on `EventSource` or `WebSocket`, so the two stream routes, `GET /api/v1/accounts/{id}/stream` and `GET /api/v1/accounts/{id}/ws`, also accept the key as `?key=tl_...`. No other route reads it (any route accepts `key=` in its query string and ignores it). Prefer the header wherever you can: query strings end up in proxy and browser logs. ## The dashboard session The dashboard does not use keys. It signs in with the admin password at `POST /api/v1/session` and receives `termless_session`, an HttpOnly, `SameSite=Strict` cookie that lasts 30 days and acts like an admin key. Three rules come with it: - A write or a WebSocket authenticated by the cookie whose `Origin` header is another site is refused with `403`. Keys are not affected. - `PUT /api/v1/admin/password` takes the cookie only; a key gets `403`. Changing the password signs out every other dashboard session. - Scripts should use keys, not the cookie. If you do script against the cookie (for example to create keys), sign in once with `curl -c cookies.txt` and send `-b cookies.txt` afterwards: ```sh curl -s -c cookies.txt -X POST "$TERMLESS_URL/api/v1/session" \ -H "Content-Type: application/json" -d '{"password": "your admin password"}' ``` ## First run and the setup token A new install has no admin password. The server prints a one-time **setup token** to its log and writes it to `/setup-token`; `POST /api/v1/setup` with that token and a new password (15 to 200 characters with a lowercase letter, a capital, a digit and a symbol) sets the password and signs you in. This stops anyone who reaches the port first from claiming the install. `GET /api/v1/setup` says whether this step is still pending, and `GET /api/v1/health` reports `status: "setup"` until it is done. (`/health` answers anyone, but gives its `version` and the accounts only to a caller with a valid key or the dashboard session.) Setting `TERMLESS_ADMIN_PASSWORD` in the environment on the first start skips the step. `termlessd passwd` resets the password later from the command line. ## Lockouts Wrong credentials are counted per client IP: - 5 wrong passwords or setup tokens in 15 minutes lock that IP out of sign-in for 15 minutes. - 30 unknown API keys in 15 minutes lock that IP out of key authentication for 15 minutes. A valid key from that IP still works (0.6.3): the lockout refuses unknown keys only, so one stale process polling with an old key cannot lock the other programs on its box out. A locked-out request answers `429 too_many_requests` with a `Retry-After` header. Every wrong password, every lockout and every sign-in is also a row in the [audit trail](/docs/trails) with the client IP. ### Behind a reverse proxy Without `--trust-proxy` every request appears to come from the proxy's address, so one person's wrong passwords lock everyone out, and the lockouts protect nothing. With `--trust-proxy` (`TERMLESS_TRUST_PROXY=1`) the server reads the client IP from **one** header, the one named by `--proxy-header` / `TERMLESS_PROXY_HEADER` (default `X-Forwarded-For`, whose last hop is the one your proxy appended; `X-Real-IP` is never a fallback), and https from `X-Forwarded-Proto`. Two conditions make that safe, and both are yours to meet: - The proxy must **set or overwrite** that header on every request it forwards. Caddy's `reverse_proxy` does for `X-Forwarded-For`; to use `X-Real-IP` instead, add `header_up X-Real-IP {remote_host}` and start with `--proxy-header X-Real-IP`. - Clients must not be able to reach termlessd's port directly (keep `--listen 127.0.0.1:8780`), or they choose their own address and the lockouts mean nothing. The headers are believed only on connections that come from `--trusted-proxies` / `TERMLESS_TRUSTED_PROXIES` (CIDRs; default `127.0.0.0/8,::1`, the machine itself). A program that `--allow-from` lets in directly, such as an app on a private network, is taken at its own address and cannot name another caller. When the proxy runs elsewhere (another machine, or a container: the Docker files set the compose network), list its address there. See [running the server](/docs/running#behind-a-reverse-proxy) for the Caddy snippet. ## Checking what a key may do ```sh curl -s "$TERMLESS_URL/api/v1/me" -H "Authorization: Bearer $TERMLESS_KEY" ``` ```json {"kind": "key", "name": "EA bridge (gold)", "scopes": ["trade"], "accounts": ["pepperstone-12345678"]} ``` `accounts` is `null` when the key may use every account. For the dashboard session `kind` is `"admin"`. --- # Conventions The rules every route follows: two clocks, lots, prices, symbols, timeframes, ids, request ids, cursors, why a trade happened and the one error shape. ## Base URL and format Every route lives under `/api/v1` on your server. Requests and responses are JSON (`Content-Type: application/json`); a successful delete answers `204` with no body; the log and crash reports are `text/plain`; the SSE stream is `text/event-stream`. Lists are plain JSON arrays, not wrapped in an object. ## Two clocks MetaTrader reports every market time in the **trade server's clock**, not UTC, and Termless passes them through unchanged so your numbers match the terminal and the broker's statements. That covers `time` and `time_msc` on ticks, candles, positions, orders and deals, `expiration` on pending orders, and the `from` and `to` you send to the candles and deals routes. Each account's summary carries `server_offset`, the trade server's clock in seconds east of UTC. Most brokers run UTC+2 in winter and UTC+3 in summer, so the value changes twice a year; read it, do not hard-code it. Termless reads it from the account record at least once an hour, so a switch shows up without a reconnect, and checks it against live ticks (a tick's server time minus the moment it arrived, to the nearest quarter hour). If the two disagree, the ticks win and the server log says so once. `server_offset` is the offset **now**. A bar, deal or order from before the broker's last clock change carries the offset of its own time: a summer bar on a UTC+3 broker is UTC+3 even when you read it in winter, at UTC+2. To turn old times into UTC, use the broker's summer-time dates. Most UTC+2/UTC+3 brokers switch on the US dates (the second Sunday of March and the first Sunday of November), so their clock is New York time plus seven hours. ```python from datetime import datetime, timezone summary = requests.get(f"{base}/accounts/{acc}/summary", headers=auth).json() offset = summary["server_offset"] # for example 10800 = UTC+3 utc = datetime.fromtimestamp(candle["time"] - offset, timezone.utc) # right since the broker's last clock change server_from = int(datetime(2026, 10, 1, tzinfo=timezone.utc).timestamp()) + offset # a UTC date as a query time ``` Times about Termless itself are plain UTC unix seconds: `status.since`, `status.retry_at`, `created_at`, `last_used_at`, `verified_at`, `started_at`, and `time` on diagnostics entries. | Field | Clock | Unit | |---|---|---| | `time` on a tick, candle, position, order, deal; `time_setup`, `time_done` on orders | trade server | unix seconds | | `time_msc`, `time_setup_msc`, `time_done_msc` | trade server | unix milliseconds | | `expiration` on a pending order | trade server | unix seconds, `0` = good till cancelled | | `from`, `to` query parameters | trade server | unix seconds | | `created_at`, `since`, `retry_at`, `last_used_at`, `verified_at`, `started_at` | UTC | unix seconds | | `last_tick_at_ms`, `last_frame_at_ms` in diagnostics | UTC | unix milliseconds | | `at` on audit rows, connection events and equity samples; `time_ms` on `account`, `positions` and `orders` events | UTC | unix milliseconds | ## Volumes are lots `volume` is always lots, as in MT5: `0.01` is a micro lot, `1.0` a standard lot. The symbol's spec gives `volume_min`, `volume_max` and `volume_step`, and `contract_size` says how many units one lot is (100,000 for most forex pairs, 100 for gold). A volume off the step is refused by the broker with `10014 Invalid volume`. ## Prices Prices are plain JSON numbers with the symbol's `digits` decimals (`2` for gold, `5` for EURUSD, `3` for yen pairs). `0` means none: a stop loss or take profit of `0` is no stop, and in a request `0` removes one. `last` is `0` for most forex and CFD symbols, which have no last-deal price. A quote whose symbol has not ticked yet (a closed market) has `null` prices. ## Sides and types `side` is `"buy"` or `"sell"` everywhere. Pending order `type` is `limit`, `stop` or `stop_limit` when you place one, and the full MetaTrader name (`buy_limit`, `sell_stop`, ...) when you read one back. Deal `type` and `entry` use MetaTrader's names in lowercase (`buy`, `sell`, `balance`; `in`, `out`, `inout`, `out_by`). Any enum value the server does not know comes back as `"unknown"` rather than failing the whole response. ## Symbols Symbol names are matched exactly first, then case-insensitively: `xauusd` finds `XAUUSD`. Responses always spell the name the broker's way. Brokers add suffixes (`EURUSD.a`, `XAUUSD.r`); search with `GET /api/v1/accounts/{id}/symbols?q=xau` when you are not sure. ## Timeframes `M1 M2 M3 M4 M5 M6 M10 M12 M15 M20 M30 H1 H2 H3 H4 H6 H8 H12 D1 W1 MN1`. The ones MetaTrader does not store natively (`M2`, `H3` and so on) are built from finer bars, the way the terminal does it. A candle's `time` is the bar's open time. ## Account ids An account id is yours: `a-z`, `0-9` and `-`, up to 48 characters, chosen when you add the account (default: the server's first word and the login, `pepperstone-12345678`). Tickets (`ticket`, `order`, `deal`, `position_id`, `identifier`) are MetaTrader's integers. ## Errors Every error has the same shape and an HTTP status that matches the code: ```json {"error": {"code": "not_found", "message": "no account with id pepperstone-live"}} ``` The one exception that adds to the shape rather than replacing it: a trade the broker refused answers `422` with the full trade result plus `error`. [Errors and retries](/docs/errors) lists every code. ## Query parameters Lists of symbols and event types are comma-separated (`?symbols=XAUUSD,EURUSD`, at most 200; `?events=ticks,trades`). Numbers are plain (`?count=100`, `?volume=0.1`). The one boolean, `bodies=1` on `/diagnostics/undecoded`, takes `1` or `true`. A query parameter the route does not take is `400`, never silently ignored, so a typo cannot turn a filtered request into an unfiltered one. The message names the parameter and the ones the route takes: ```json {"error": {"code": "bad_request", "message": "tickt: unknown query parameter `tickt`, expected one of `from`, `to`, `limit`, `before`, `position`, `ticket`, `symbol`"}} ``` A route that takes none says `this route takes no query parameters (got ...)`. `key=` is accepted on any route (only the two stream routes read it as a key). Routes that take a JSON body read nothing from the query string. ## Request ids Every response carries an `X-Request-Id` header. Send your own (1 to 64 characters of `A-Z a-z 0-9 - _ . :`) and it is kept; otherwise the server makes one of 16 hex characters. The same id is on every log line the request wrote and on every audit row it caused. It is the one thing to quote when you report a problem. ## Idempotency The trade routes that change something take an `Idempotency-Key` header (1 to 200 printable ASCII characters). The same key with the same body replays the first answer, with `Idempotent-Replayed: true`, instead of asking the broker again; the same key with a different body or query string is `409`. [Trading safely](/docs/trading#after-a-timeout-the-one-rule) has the rules; the short version is: always send one, retry with the same one. ## Lists and cursors Most lists come back whole: positions, orders, accounts, keys and symbols (bounded by `limit`, at most 10,000) are small. Candles are bounded by `count` (at most 50,000) or a `from`/`to` range. Four lists page with a cursor, newest first except deals and history orders: | Route | Page size | Cursor | Next page | |---|---|---|---| | `GET /accounts/{id}/deals` | `limit` (default and max 5,000), inside the `from`/`to` window (at most 10 years) | `before` = a `time_msc` | `before` = the first (oldest) deal's `time_msc` of the page you have; the page is oldest first | | `GET /accounts/{id}/orders/history` | `limit` (default and max 5,000), inside the `from`/`to` window on when each order was placed | `before` = a `time_setup_msc` | `before` = the first (oldest) order's `time_setup_msc` of the page you have; the page is oldest first | | `GET /audit` | `limit` (default 100, max 1,000) | `before` = an `id` | `before` = the `id` of the last row you have | | `GET /accounts/{id}/events` | `limit` (default 100, max 1,000) | `before` = an `id` | `before` = the `id` of the last row you have | `GET /accounts/{id}/equity` is bounded by `hours` (1 to 168) instead and comes back whole, oldest first. Trade events have a cursor of their own: an event id, `":"`. `GET /accounts/{id}/trades?after=` returns what came after it (oldest first) and the newest id to ask with next time; a stream takes the same id as `?after=` or `Last-Event-ID`. [Streaming](/docs/streaming#picking-up-where-you-left-off) has the details. ## Why a trade happened Positions, orders and deals carry `reason`, a word for what made them: `web` for anything sent through Termless, `client` for a desktop terminal, `mobile`, `expert` (an EA), `sl` and `tp` for a close at the stop loss or take profit, `stop_out`, and a few rarer ones (`rollover`, `vmargin`, `split`, `corporate_action`, `dealer`, `gateway`, `signal`, `settlement`, `transfer`, `sync`, `external_client`, `external_service`, `migration`, `unknown`). A closing deal with `reason: "sl"` is a stop hit, whatever its comment says. --- # Streaming prices Every tick pushed to you over Server-sent events or a WebSocket, the trade, account, positions and orders events a bot should read instead of polling, which trade events a UI should show, how a client that dropped picks up the trades it missed, what a status event means, how the stream ends, and what happens when you fall behind. Polling `GET /quotes` is fine for a glance. For prices as they happen, open a stream: Termless pushes every tick the broker sends for the symbols you asked for, for as long as the connection is open. Two flavours carry the same data. | | SSE: `GET /api/v1/accounts/{id}/stream` | WebSocket: `GET /api/v1/accounts/{id}/ws` | |---|---|---| | Transport | Plain HTTP, `text/event-stream`. Works with `curl -N`, `requests`, `EventSource`. | WebSocket upgrade. | | Changing symbols | Open another stream (or one stream for all of them). | Send `{"subscribe": [...]}` or `{"unsubscribe": [...]}` any time. | | Reconnect | `EventSource` does it by itself. | You reconnect. | | Liveness | A `: heartbeat` comment every 15 s. | A ping every 15 s. | | Key | Header, or `?key=` for browsers. | Header, or `?key=`. | Both default to the account's watchlist when `symbols` is left out. One stream carries up to 200 symbols, so open one stream with all of them rather than one per symbol. Both also carry more than prices: with `?events=` the same stream tells you about every trade the broker applies and keeps the account's money, the live P/L of its positions and its pending orders current, so a bot never polls (see [Events](#events-trades-account-positions-orders) below). ## Server-sent events ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```sse event: status data: {"connected":true,"ping_ms":14.2} event: tick data: {"symbol":"XAUUSD","bid":2391.42,"ask":2391.6,"last":0,"time_msc":1790981179473} event: tick data: {"symbol":"EURUSD","bid":1.08412,"ask":1.08418,"last":0,"time_msc":1790981179581} : heartbeat ``` Three kinds of line arrive: - `event: status` with `{connected, ping_ms}`. The first event on every stream, and again the moment `connected` changes. While `connected` is false no ticks come, because the account has no link to the broker; they resume on their own when it reconnects. - `event: tick` with `{symbol, bid, ask, last, time_msc}`. One per price change. `time_msc` is the trade server's clock in milliseconds. - `: heartbeat`, a comment line every 15 seconds while nothing else is sent. If a stream has been silent for a minute, the connection is dead: close it and open a new one. ```python import json import os import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} with requests.get(url, headers=auth, params={"symbols": "XAUUSD,EURUSD"}, stream=True, timeout=(5, 30)) as r: # a 30 s read timeout outlives two heartbeats r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line.startswith("event:"): event = line[6:].strip() elif line.startswith("data:"): data = json.loads(line[5:]) if event == "tick": print(data["symbol"], data["bid"], data["ask"]) elif event == "status": print("broker link up" if data["connected"] else "broker link down", data) ``` ```javascript // Browser: EventSource cannot send headers, so the key goes in the query. const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL); url.searchParams.set("symbols", "XAUUSD,EURUSD"); url.searchParams.set("key", TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("status", (e) => console.log("broker link", JSON.parse(e.data))); es.addEventListener("tick", (e) => { const t = JSON.parse(e.data); console.log(t.symbol, t.bid, t.ask); }); // When the stream ends or the network drops, EventSource reconnects by itself. ``` ### Batching By default every broker frame is written to you as it arrives, for the lowest latency. If you would rather have fewer, larger reads, add `&batch_ms=N` (1 to 100): after a tick the server gathers the ticks of the next N milliseconds into one write. Only ticks are batched; events go out as they happen. ## Events: trades, account, positions, orders `events=` on `/stream` and `/ws` picks what the stream carries, comma-separated. Absent means `ticks`, so existing clients see no change. Leave `ticks` out to get events only. An unknown name is `400`. | `events=` | Event | Data | When | |---|---|---|---| | `ticks` | `tick` | `{symbol, bid, ask, last, time_msc}` | Every price change (default). | | `trades` | `trade` | `{seq, id, what, kind, pending?, order?, state?, deal?, position?, positions?, balance?, credit?, caught_up?}` | One per broker trade push, as it is applied: an order placed, changed, filled or cancelled, a deal opening, reducing, closing or reversing a position, a position's stops moved, a balance operation. After a gap, the deals the broker made meanwhile, marked `caught_up`. Numbered, so a client that dropped can [pick up where it left off](#picking-up-where-you-left-off). | | `account` | `account` | the summary (`balance`, `equity`, `margin`, `margin_free`, `profit`, ...) plus `time_ms` | Right after the stream opens, then whenever a value changed, checked every 500 ms at most. | | `positions` | `positions` | `{positions: [position...], time_ms}` with live `profit` and `price_current` | On the same 500 ms rhythm, only when something changed. | | `orders` | `orders` | `{orders: [order...], time_ms}`: every pending order (limit, stop, stop limit) in the order shape of `GET /orders` | Once right after the first `status`, then whenever a trade push added, changed or removed a pending order (and after a reconnect, if the book changed meanwhile). Ticks never send one: an order has no live price. | ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?events=trades,account,positions,orders" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```sse event: status id: 1790968290117:40 data: {"connected":true,"ping_ms":14.2,"id":"1790968290117:40"} event: account data: {"login":12345678,"name":"Demo Trader","server":"Pepperstone-Demo","company":"Pepperstone Group Limited","currency":"USD","leverage":200,"balance":10412.58,"credit":0.0,"profit":238.11,"equity":10650.69,"margin":878.93,"margin_free":9771.76,"margin_level":1211.78,"margin_so_call":100.0,"margin_so_so":50.0,"trade_allowed":true,"demo":true,"hedging":true,"server_offset":10800,"positions":3,"orders":2,"time_ms":1790981179473} event: positions data: {"positions":[{"ticket":51830012,"symbol":"XAUUSD","side":"buy","volume":0.2,"price_open":2385.0,"price_current":2391.42,"sl":2380.0,"tp":2420.0,"profit":128.4,"swap":-1.12,"commission":-1.4,"comment":"breakout","magic":0,"reason":"web","identifier":51830012,"time":1790975498,"time_msc":1790975498123,"time_update":1790975498}],"time_ms":1790981179473} event: orders data: {"orders":[],"time_ms":1790981179473} event: trade id: 1790968290117:41 data: {"seq":41,"id":"1790968290117:41","what":"placed","kind":"order","pending":true,"order":{"ticket":51830020,"symbol":"XAUUSD","type":"buy_limit","side":"buy","volume":0.1,"volume_initial":0.1,"price":2365.0,"stop_limit":0,"sl":2350.0,"tp":2410.0,"expiration":0,"comment":"dip buy","magic":0,"reason":"web","time_setup":1790977698,"time_setup_msc":1790977698412},"state":"placed"} event: orders data: {"orders":[{"ticket":51830020,"symbol":"XAUUSD","type":"buy_limit","side":"buy","volume":0.1,"volume_initial":0.1,"price":2365.0,"stop_limit":0,"sl":2350.0,"tp":2410.0,"expiration":0,"comment":"dip buy","magic":0,"reason":"web","time_setup":1790977698,"time_setup_msc":1790977698412}],"time_ms":1790977698430} event: trade id: 1790968290117:42 data: {"seq":42,"id":"1790968290117:42","what":"opened","kind":"deal","deal":{"ticket":81200118,"order":51830012,"position_id":51830012,"symbol":"XAUUSD","type":"buy","entry":"in","volume":0.2,"price":2385.0,"profit":0.0,"commission":-0.7,"swap":0.0,"fee":0.0,"magic":0,"comment":"breakout","reason":"web","time":1790975498,"time_msc":1790975498123},"balance":10412.58,"credit":0.0,"position":{"ticket":51830012,"symbol":"XAUUSD","side":"buy","volume":0.2,"price_open":2385.0,"price_current":2385.0,"sl":2380.0,"tp":2420.0,"profit":0.0,"swap":0.0,"commission":-0.7,"comment":"breakout","magic":0,"reason":"web","identifier":51830012,"time":1790975498,"time_msc":1790975498123,"time_update":1790975498,"open":true}} event: trade id: 1790968290117:43 data: {"seq":43,"id":"1790968290117:43","what":"updated","kind":"position","position":{"ticket":51830012,"symbol":"XAUUSD","side":"buy","volume":0.2,"price_open":2385.0,"price_current":2391.42,"sl":2386.0,"tp":2420.0,"profit":128.4,"swap":0.0,"commission":-0.7,"comment":"breakout","magic":0,"reason":"web","identifier":51830012,"time":1790975498,"time_msc":1790975498123,"time_update":1790981102,"open":true}} ``` ### Reading a trade event `kind` says what the broker pushed, `what` says what it meant: - `kind: "order"` carries `order` (the order in its usual shape), `state` (`placed`, `partial`, `filled`, `cancelled`, `expired`, `rejected`, ...) and `pending`: `true` for a limit, stop or stop-limit order, `false` for a market buy or sell. `what` is `placed`, `modified` or `removed` while the order is live, and `filled`, `cancelled`, `expired` or `rejected` when it moves to history. On a filled order `volume` is what is left (`0`) and `volume_initial` is what was asked. - `kind: "deal"` carries `deal` (the deal in its usual shape), `balance` and `credit` (the account's, after the deal), and `position`: the position the deal touched, with an extra `open` that is `false` once it is closed. `what` is `opened`, `partial` (a partial close), `closed`, `reversed`, or `balance` for a balance, credit or commission deal (no `position` then). `positions` lists other positions the same push updated, which happens on a netting account. A closed position keeps its last known values (open price, stops, time, comment, magic) with `volume` 0, so you can still say which trade it was. `deal.reason` says why it closed: `sl` or `tp` for a stop, `stop_out`, `web` for a close sent through Termless. - `kind: "position"` with `what: "updated"`: the broker changed a position without a deal, because its stop loss or take profit moved or as the step just before a close. It carries `position` (with `open`) and sometimes `positions`, and no `deal`, `balance` or `credit`. - `caught_up: true` on a `kind: "deal"` event: a deal the broker made while the link was down, the server was stopped or the account's session was starting again, read back from the account's history afterwards (see [after a gap](#after-a-gap-the-deals-made-meanwhile)). It carries `what` and `deal` only: no `position`, `balance` or `credit`, because the history does not say them. `what` is `opened`, `partial` (its position is still open), `closed`, `reversed` or `balance`. Every `trade` event also carries `seq` (1, 2, 3, ... per account) and `id` (`":"`), the cursor for [picking up where you left off](#picking-up-where-you-left-off). ### What a UI should show A market order has a short life of its own at the broker: it is placed, taken off the book and filed as filled (some servers file it as cancelled) within the same moment, and each step is an order event, with `volume` 0 once it is done. Showing those as "Filled buy 0.00" next to the real fill only confuses. `what` keeps its values for code that already reads them; `pending` tells the two kinds apart: | The trade | Show | Skip | |---|---|---| | A market order (`POST /orders` with no `type`, a close, a partial close) | the deal event: `opened`, `partial`, `closed` or `reversed`, with its volume and price | every order event with `pending: false` | | A pending order (limit, stop, stop limit) | its order events (`pending: true`): `placed`, `modified`, `cancelled`, `expired`, `rejected`; when it fills, its `filled` event and then the deal event that opened the position | `removed` (the same moment as the move to history) | | A balance, credit or commission | the deal event with `what: "balance"` | | | A stop loss or take profit moved, or the moment before a close | nothing: redraw positions from the `positions` event | the `kind: "position"` event with `what: "updated"` | | A close at the stop loss or take profit | the deal event `closed` (or `partial`), worded from `deal.reason`: "closed by stop loss" for `sl`, "closed by take profit" for `tp`, "stopped out" for `stop_out` | | The list of pending orders is easier still: ask for `events=orders` and redraw from each `orders` event, which never lists a market order. Events are per account, not per symbol, so a stream opened with `events=trades` and no `symbols` still hears every trade on the account. They are not coalesced like ticks: a slow client misses none until it falls more than 1,024 events behind, and then it gets a `resync` event (below) instead of a silent gap. An `orders` event is a snapshot, so nothing is lost if one is skipped: a stream that fell behind sends a fresh one if the book changed. ```python import json import os import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} with requests.get(url, headers=auth, params={"events": "trades,account"}, stream=True, timeout=(5, 30)) as r: r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line.startswith("event:"): event = line[6:].strip() elif line.startswith("data:"): data = json.loads(line[5:]) if event == "trade" and data["kind"] == "deal": p = data.get("position") print(data["what"], data["deal"]["symbol"], data["deal"]["volume"], "position open" if p and p["open"] else "position closed", "balance", data["balance"]) elif event == "account": print("equity", data["equity"], "free margin", data["margin_free"]) ``` ```javascript const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL); url.searchParams.set("events", "trades,account,positions"); url.searchParams.set("key", TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("trade", (e) => { const t = JSON.parse(e.data); console.log(t.what, t.kind, t.kind === "deal" ? t.deal.symbol : t.order.symbol); }); es.addEventListener("account", (e) => console.log("equity", JSON.parse(e.data).equity)); es.addEventListener("positions", (e) => console.log("open positions", JSON.parse(e.data).positions.length)); ``` Which to ask for: a trading bot wants `trades` (to learn its fills and stops hit without polling `GET /deals`) and `account` (free margin before the next order); a UI wants `account`, `positions` and `orders` and never computes P/L or keeps its own order book; a price study wants `ticks` alone. ## Picking up where you left off A connection drops, a laptop sleeps, a bot restarts. Trade events are numbered so a client can come back and get the ones it missed instead of guessing. - Every `trade` event has `seq` (1, 2, 3, ... per account) and `id`, `":"`. `epoch` is when the server began this account's numbering (unix ms). The newest 1,024 events are kept in the server's database, so the numbering and the epoch carry on across a restart or an upgrade of the server, a changed password and turning the account off and on: an id you saw before any of those still resumes. A new numbering, with a new epoch, starts only when the account is added again or logs in to another broker account (another login or server). - A stream that follows `trades` or `orders` starts with a `status` that carries an `id` too: the newest id at that moment (`:0` before the first event), so you hold a cursor before any trade happens. Later `status` events carry none. - On SSE, the first `status` and every `trade` and `resync` event have an `id:` line. A browser's `EventSource` remembers the last one and sends it back as `Last-Event-ID` when it reconnects, so a page that uses `EventSource` resumes with no code at all. - Any client can resume by hand: open the stream with `?after=` (SSE and WebSocket). A malformed id is `400`. A resumed stream sends the first `status` (whose `id` is your cursor), then the events after your cursor, oldest first, without gaps, from the last 1,024 the server keeps for the account, then carries on live. On a WebSocket they come after `subscribed`. When the missed events cannot be replayed, you get one `resync` event instead (`type: "resync"` on a WebSocket), and the stream goes on live from the newest id: ```sse event: resync id: 1791012001502:3 data: {"seq":3,"id":"1791012001502:3","reason":"that id is from another numbering (the account now logs in to another broker account, or its kept events were lost)"} ``` A `resync` means one thing: read positions, orders and deals again (`GET /positions`, `GET /orders`, `GET /deals`), then trust the events that follow. It comes when your id is from another epoch, is newer than anything the account has sent, or is older than the 1,024 kept events, and when your own stream fell more than 1,024 events behind. Other resyncs are part of the numbering themselves and are replayed like trade events: after a gap (below) and when the server fell behind the broker's pushes (`"the server fell behind the broker's trade pushes"`). ### After a gap: the deals made meanwhile The broker never resends what it pushed while its link was down, and nothing reaches a server that is stopped. After such a gap the server reads the deals the broker made meanwhile from the account's history and sends each as a `trade` event with `caught_up: true`, oldest first, then a `resync` that says which gap it was: | Gap | `reason` | |---|---| | The broker link came back | `the broker link came back; its trade pushes sent while it was down are not replayed (the deals made meanwhile came first, marked caught_up)` | | The server restarted | `the server restarted; trade pushes sent while it was stopped are not replayed (the deals made meanwhile came first, marked caught_up)` | | The account's session started again (a changed password, turned off and on) | `the account's session started again; trade pushes sent in between are not replayed (the deals made meanwhile came first, marked caught_up)` | ```sse event: trade id: 1790968290117:48 data: {"seq":48,"id":"1790968290117:48","what":"closed","kind":"deal","deal":{"ticket":81200152,"order":51830050,"position_id":51830012,"symbol":"XAUUSD","type":"sell","entry":"out","volume":0.2,"price":2380.0,"profit":-100.0,"commission":-0.7,"swap":-1.12,"fee":0.0,"magic":0,"comment":"[sl 2380.00]","reason":"sl","time":1790990841,"time_msc":1790990841207},"caught_up":true} event: resync id: 1790968290117:49 data: {"seq":49,"id":"1790968290117:49","reason":"the server restarted; trade pushes sent while it was stopped are not replayed (the deals made meanwhile came first, marked caught_up)"} ``` A deal already sent is never sent again, and nothing older than the account's kept events is sent. A catch-up looks back at most 7 days and sends at most 500 deals (more than that: only the `resync`). Pending orders placed or removed and stops moved during the gap have no history, so the `resync` still follows: read positions and orders again. A client that only shows fills can show the caught-up deals as they come. ```python import json import os import time import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} cursor = None # keep it on disk to survive a restart of the bot def resync(): print("reading positions, orders and deals again") # your own reload here while True: params = {"events": "trades"} if cursor: params["after"] = cursor try: with requests.get(url, headers=auth, params=params, stream=True, timeout=(5, 30)) as r: r.raise_for_status() event = None for line in r.iter_lines(decode_unicode=True): if line.startswith("event:"): event = line[6:].strip() elif line.startswith("data:"): data = json.loads(line[5:]) if event == "resync": resync() elif event == "trade": print(data["seq"], data["what"], data["kind"]) if data.get("id"): # status, trade and resync carry one cursor = data["id"] except requests.RequestException as e: print("stream dropped:", e) time.sleep(2) ``` ```javascript // EventSource resumes by itself: it sends the last id back as Last-Event-ID. const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL); url.searchParams.set("events", "trades"); url.searchParams.set("key", TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("trade", (e) => console.log(e.lastEventId, JSON.parse(e.data).what)); es.addEventListener("resync", () => reloadPositionsOrdersAndDeals()); ``` ### Polling instead of streaming A client that would rather ask now and then than hold a stream open reads the same numbering from `GET /api/v1/accounts/{id}/trades?after=`: ```json {"id": "1790968290117:44", "events": [{"event": "trade", "seq": 44, "id": "1790968290117:44", "what": "cancelled", "kind": "order", "pending": true, "order": {"ticket": 51830020, "symbol": "XAUUSD", "type": "buy_limit", "side": "buy", "volume": 0.1, "volume_initial": 0.1, "price": 2365.0, "stop_limit": 0, "sl": 2350.0, "tp": 2410.0, "expiration": 0, "comment": "dip buy", "magic": 0, "reason": "web", "time_setup": 1790977698, "time_setup_msc": 1790977698412}, "state": "cancelled"}], "resync": null} ``` `id` is the newest event's id: send it as `after` next time. `events` are the events after `after`, oldest first, each with `event` (`trade` or `resync`) beside its own fields. `resync` is null, or a sentence saying why the events since `after` cannot be given; then read the account again and carry on from `id`. Without `after` you get every event the server keeps (up to 1,024). It needs a `read` key, and answers `503` while the account is turned off. ## WebSocket ```javascript const url = new URL("/api/v1/accounts/pepperstone-12345678/ws", TERMLESS_URL.replace(/^http/, "ws")); url.searchParams.set("symbols", "XAUUSD"); url.searchParams.set("key", TERMLESS_KEY); const ws = new WebSocket(url); ws.onopen = () => ws.send(JSON.stringify({ subscribe: ["EURUSD", "GBPUSD"] })); ws.onmessage = (e) => { const msg = JSON.parse(e.data); switch (msg.type) { case "status": console.log("broker link", msg.connected, msg.ping_ms); break; case "subscribed": console.log("now streaming", msg.symbols); break; case "tick": console.log(msg.symbol, msg.bid, msg.ask); break; case "error": console.warn(msg.message); break; } }; ``` Messages are JSON objects told apart by `type`: | `type` | Fields | When | |---|---|---| | `status` | `connected`, `ping_ms`, sometimes `reason`; on the first one `id` when the socket follows `trades` or `orders` | First message; again whenever `connected` changes; once more just before the socket closes. | | `subscribed` | `symbols` | After the open and after every `subscribe` or `unsubscribe`, with the whole current list. | | `tick` | `symbol`, `bid`, `ask`, `last`, `time_msc` | Every price change. | | `trade`, `account`, `positions`, `orders` | the same fields as the SSE events above | Only when asked for with `?events=`. Events replayed for `?after=` come right after `subscribed`, then an `orders` message. | | `resync` | `seq`, `id`, `reason` | When missed trade events cannot be replayed, or after a gap (the broker link came back, the server restarted, the account's session started again): read positions, orders and deals again. | | `error` | `message` | A command the server could not act on (an unknown symbol, more than 200 symbols). | You send `{"subscribe": ["GBPUSD"]}` or `{"unsubscribe": ["EURUSD"]}` (both in one message is fine; unsubscribe is applied first). The server pings every 15 seconds; most WebSocket libraries answer pongs for you. `?events=` works the same as on the SSE stream and cannot be changed after the open. A WebSocket has no `Last-Event-ID`: to resume, keep the last `id` you handled and reconnect with `?after=`. ## Bars Since 0.7.0 a stream can carry candles as they form, so a chart never polls `/candles`. Ask with `events=bars&bars=XAUUSD:M1,EURUSD:H1` (any official timeframe, at most 100 series a stream; add `ticks` to `events` for ticks too). On a WebSocket opened that way, `{"bars": ["GBPUSD:M5"]}` and `{"unbars": [...]}` add and remove series, answered by `{"type": "bars", "series": [...]}`. ```text event: bar data: {"symbol":"XAUUSD","timeframe":"M1","time":1790981160,"open":2391.2,"high":2391.9,"low":2391.1,"close":2391.42,"tick_volume":112,"real_volume":0,"state":"forming"} ``` - `state: "forming"`: the bar being built from the bids, as MetaTrader builds it, at most four a second per series (a slow stream keeps the newest). A series starts from the broker's own forming bar, so the first one is right. - `state: "closed"`: once the period ends by the server's clock (plus 2 s), the bar as the **broker** has it: one M1 read per symbol covers the closed minutes, every timeframe up to H12 is built from those, D1 and up are read directly. Use the closed bar, not your last forming one: they differ when ticks were missed. A period with no broker bar (no tick in it, a weekend) sends nothing. A trading symbol's minutes are read at their close even when none of their ticks reached the server, and a tick that turns up late for a closed period has it read again (0.7.1), so bars do not always arrive in time order: place each by its `time`. - `state: "corrected"`: a minute after a bar closed it is read again; if the broker changed it, it comes again. Replace the bar with the same `time`. After the autumn clock change on a New York + 7 server (Sunday 08:00 to 09:00 there happens twice), the repeated hour's bars that changed come again as corrected (0.7.1). - `event: bars_gap` with `{symbol, timeframe, from, to}`: bars this series cannot send (more than 500 missed while the link was down, a stream that fell far behind, a bar that could not be read again, or a minute of failed reads). Read that range with `GET /candles?from=&to=`. After a reconnect each series reads what it missed (up to 500 bars) and sends it in order before the forming bar. Series are shared: two streams asking for `XAUUSD:M1` cost one series on the account, which follows at most 200 symbols and 1,000 series across its streams (0.7.1). A symbol whose ticks the account cannot take still gets its closed bars, read from the broker each period. Names given while the account is down are checked when it comes up (see Names, in the API reference). ## When the stream ends A stream is tied to the account's current login. It ends, after one last `status` with `connected: false` and a `reason`, when: - the account is deleted, or logs in with new details (a changed password, server, host or port): `reason: "account changed"`; - the server is shutting down: `reason: "server stopping"`; - the key that opened it is deleted (`reason: "key revoked"`) or changed so it may no longer read this account (`reason: "key changed"`), or the dashboard session that opened it signs out (`reason: "signed out"`). Changes to other keys never end it. Reconnect to follow the account. `EventSource` does this on its own; a WebSocket client should reconnect with a short backoff (a second, doubling to about 30 s). Nothing is lost that matters: a new stream begins with the current status, a fresh `account`, `positions` and `orders` snapshot if you asked for them, and the next ticks. Trade events you missed come first when you reconnect with your last id ([above](#picking-up-where-you-left-off)), then the deals made while the account logged in again, marked `caught_up`, and a `resync`. Only when the account was deleted and added again, or now logs in to another broker account, does the numbering start again: then expect a `resync` for your old id and read the account again. ## Falling behind Streams carry every tick while you keep up. A client that reads slowly (a weak link, a background browser tab) gets the **latest tick per symbol** once it reads again: older ticks of that symbol are dropped, a tick is never delivered after a newer one of the same symbol, and the server never buffers more than 1,024 ticks for one stream. If you need every tick for a study, read quickly and write to disk; a stream is a price feed, not a recording. Trade events are never dropped that way. A stream that falls more than 1,024 trade events behind gets a `resync` event (`"this stream fell behind; read the account again"`) and, with `events=orders`, a fresh `orders` snapshot. Since 0.7.0 the stream says so: a `gap` event before what follows, `{reason, symbols, dropped, from_msc, to_msc}` on the ticks' own clock. `reason` is `behind` (you read too slowly: `symbols` lost `dropped` ticks between `from_msc` and `to_msc`), `reconnect` (the broker link was down) or `fanout` (the server's own fan-out fell behind); for the last two, every symbol of the stream may have missed ticks between your last tick (`from_msc`) and the next (`to_msc`, which follows the gap). Ticks are never replayed, the broker keeps no tick history; a chart can read the candles of that window instead. ```text event: gap data: {"reason":"reconnect","symbols":["XAUUSD"],"dropped":null,"from_msc":1790981170212,"to_msc":1790981191408} ``` `ticks_coalesced` in `GET /api/v1/diagnostics` counts how many ticks were dropped this way across all streams. ## Caps At most **1,024 streams** may be open on one server and **256 per key** (or per dashboard session), SSE and WebSocket together. Past that a new stream answers `429 too_many_requests` with `Retry-After` and a message saying which cap was hit. One stream can carry 200 symbols, 100 bar series and every event type, so this is rarely a constraint for one app; it is there so a reconnect loop gone wrong cannot take the server down. `streams` in `GET /api/v1/diagnostics` shows how many are open and the caps. ## What is not in a tick Ticks have no `time` in seconds (use `time_msc / 1000`), no volume and no flags. Candles carry `tick_volume`; `GET /quotes` carries both `time` and `time_msc`. `GET /ticks` returns the recent ticks the server kept for a symbol, with `time`, `volume` and `flags`: since 0.7.0 from the symbol's first `/ticks` read on (so the first answer is often empty), the newest 1,000 by default (a reconnect starts them again). It is a short look back, not a recording; to keep every tick, write them down from the stream. --- # Trading safely Market and pending orders, stops and trailing them, partial closes, comments and magic numbers, the history of deals and orders, how to read a refusal, real-money accounts, and the Idempotency-Key that lets a bot retry without ever doubling a position. Every call that changes something at the broker is one HTTP request and one broker request, and every one of them answers with the same **trade result**. Learn that shape once and the whole trading surface is small. ## The trade result ```json {"ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 81200131, "order": 51830031, "volume": 0.1, "price": 2391.6, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31} ``` | Field | Meaning | |---|---| | `ok` | `true` when the broker placed (`10008`), did (`10009`) or partly did (`10010`) what you asked. Test `ok`, not one code: brokers answer a placed pending order with `10008` or `10009` (IC Markets answers `10009`). | | `retcode`, `retcode_text` | MetaTrader's return code and its words. The full list is on the [errors](/docs/errors#retcodes) page. | | `deal` | The deal ticket when a fill happened; `0` for a pending order or a modification. | | `order` | The order ticket. For a market order this is also the new position's ticket on a hedging account. | | `volume`, `price` | What was done, at what price. On a partial fill `volume` is less than you asked. | | `bid`, `ask` | The market when the broker handled the request, useful to see slippage. | | `request_id` | The broker's id for the request. | | `warnings` | Present only when something in your request was changed or cannot be kept: a comment cut for the broker, a magic number the broker never sees, a filling mode swapped, an expiry rounded to the minute. A list of sentences, on a `200` and a `422` alike. | When `ok` is true the HTTP status is `200`. When the broker refuses, the status is **`422`** and the body is the same trade result with `ok: false` plus an `error` object with code `rejected`: ```json {"ok": false, "retcode": 10014, "retcode_text": "Invalid volume", "deal": 0, "order": 0, "volume": 0, "price": 0, "bid": 2391.42, "ask": 2391.6, "comment": "Invalid volume", "request_id": 32, "error": {"code": "rejected", "message": "the broker refused the request: Invalid volume (10014)"}} ``` Handle both statuses on every trade call. A refusal is normal operation, not an outage: fix the request (the volume, the price, the stops) rather than retrying it unchanged. Every trade call also takes an `Idempotency-Key` header. Send one on every call that changes something (below, [the one rule](#after-a-timeout-the-one-rule)); it costs nothing and it is what makes a retry safe. ## Before you trade: the spec `GET /api/v1/accounts/{id}/symbols/{symbol}` returns everything the broker will check your order against: - `volume_min`, `volume_max`, `volume_step`: the lots you may send. `0.013` on a `0.01` step is `10014 Invalid volume`. - `stops_level`: the closest a stop loss or take profit may sit to the current price, in points. `point` is the price of one point. Too close is `10016 Invalid stops`. - `freeze_level`: inside this distance of the price a pending order or stop cannot be changed (`10029`). - `trade_mode`: `full`, `long_only`, `short_only`, `close_only` or `disabled`. A buy on a `short_only` symbol is `10043`. - `filling`: the filling modes the symbol allows. Termless picks one for you (see below), so this is informational. - `sessions.trade`: when the symbol can be traded, as minutes from midnight in server time, Sunday first. Outside them a trade is `10018 Market is closed`. The spec and `GET /quotes` do that arithmetic for you: `tradeable` is `true` when the trade mode allows opening and a trade session is open right now by the server's clock (`null` when the broker sent no sessions). - `contract_size`, `tick_size`, `tick_value`, `currency_profit`: for sizing and risk arithmetic. `tick_value` is what one `tick_size` move is worth on one lot in your account currency: the broker's figure, or worked out the terminal's way when the broker sends none (Pepperstone sends none), and `null` for futures and index CFDs whose value only the broker knows. - `swap_long`, `swap_short` in the unit `swap_mode` names (`points`, `deposit_currency`, `interest_current`, ...), charged three times on `swap_3day` (`wednesday` on most forex; `null` for none). - `margin_initial`, `margin_maintenance`, `margin_hedged`, `margin_rate_buy`, `margin_rate_sell`: the symbol's margin settings. `margin_rates` has every order type's rate as the broker sends it (`buy`, `sell`, `buy_limit`, ..., `sell_stop_limit`): a pending type's rate is what the broker holds while such an order waits, and brokers send `0` there, so a waiting order holds no margin until it fills. - `expiration`: the expiry modes a pending order may use (`gtc`, `day`, `specified`, `specified_day`); `order_types`: the order types the symbol takes (`market`, `limit`, `stop`, `stop_limit`, `sl`, `tp`, `close_by`). And `GET /api/v1/accounts/{id}/summary` for `margin_free`, `trade_allowed`, `hedging` (whether opposite positions on one symbol can coexist) and `server_offset`. Two routes do the arithmetic for you and never send an order; a `read` key may call both: - `GET /api/v1/accounts/{id}/calc?symbol=XAUUSD&side=buy&volume=0.1` answers the margin the trade needs once it is open, in your account currency (the official `order_calc_margin`), at the current price or at `price=`; add `close=` for the profit from `price` to `close` (`order_calc_profit`). With `type=limit`, `stop` or `stop_limit`, `margin` is what the position needs when the order fills, and `margin_pending` what the broker holds while it waits (usually `0`). - `POST /api/v1/accounts/{id}/order_check` takes the [order_send](/docs/order-send) request and answers what sending it would do: `retcode` `0` when it would pass, else the first check that failed: `10014` (volume), `10017` (trading disabled), `10042`, `10043` or `10044` (the symbol takes only buys, only sells, or only closes), `10018` (market closed), `10015` (a pending order's price on the wrong side of the market, or closer to it than `stops_level`), `10016` (a stop loss or take profit on the wrong side of the price, or closer than `stops_level`) or `10019` (not enough free margin), with the margin, free margin and margin level the account would have. A stop change (`TRADE_ACTION_SLTP`) or an order change (`TRADE_ACTION_MODIFY`) is checked against the market too. A pending order only needs what it holds while it waits, so it is not refused for the margin of its fill. The freeze level is not checked, and an opening order counts its whole margin even when an opposite position would hedge or net it. ## Market orders `POST /api/v1/accounts/{id}/orders` with no `type` field (or `type: "market"`) opens a position at market. ```json {"symbol": "XAUUSD", "side": "buy", "volume": 0.1, "sl": 2380.0, "tp": 2420.0, "deviation": 20, "comment": "breakout"} ``` - `sl` and `tp` are prices, optional; leave them out for none. - `deviation` is the largest slippage you accept, in points (default 20). On a symbol with `execution: "market"` the broker fills at its price regardless; the field matters for `instant` execution. - `price` may be sent (the price you saw); leave it out to fill at market. - `comment` takes up to 255 characters (more is `400`). The broker keeps the first 31; Termless keeps the whole text for the order and puts it back on its position, its opening deal and its stream events. The answer's `warnings` says so. - `magic` works as in MetaTrader, with one difference under the hood: the MT5 web protocol has no field for it, so the broker stores `0`. Termless keeps your number for the order and puts it back on the position, the order, both deals (the closing one too, even a close at the stop loss) and the stream events. The answer's `warnings` says so. What Termless keeps (magic, and a comment past 31 characters) lives in its own database for 400 days (the newest 100,000 orders), tied to the login at its trade server. The broker, and MetaTrader's own apps looking at the same account, still show `magic: 0` and 31 characters. The broker's own magic wins when it is not 0, and the full comment replaces the broker's only when the broker's is its first 31 characters, so a comment the broker wrote itself is left alone. ## Pending orders The same route with `type` set to `limit`, `stop` or `stop_limit` and a `price` places a pending order. The side and type together make the MetaTrader order type: | `side` + `type` | MetaTrader order | Fills when | |---|---|---| | `buy` + `limit` | buy limit | ask falls to `price` | | `sell` + `limit` | sell limit | bid rises to `price` | | `buy` + `stop` | buy stop | ask rises to `price` | | `sell` + `stop` | sell stop | bid falls to `price` | | `buy` + `stop_limit` | buy stop limit | ask reaches `price`, then a buy limit at `stop_limit` is placed | | `sell` + `stop_limit` | sell stop limit | bid reaches `price`, then a sell limit at `stop_limit` is placed | ```json {"symbol": "XAUUSD", "side": "buy", "volume": 0.1, "type": "limit", "price": 2365.0, "sl": 2350.0, "tp": 2410.0, "expiration": 1791068400} ``` `expiration` is unix seconds in the trade server's clock; omit it (or send `0`) for good till cancelled. The broker keeps expiry times to the whole minute: send one with seconds and the answer's `warnings` names the minute it becomes. A pending order that was placed answers `200` with `ok: true`, `retcode` `10008` or `10009` depending on the broker, and `deal: 0`; its ticket is `order`. Later, `GET /orders` lists it (pending orders only: a market order is never listed, not even in the instant between its placement and its fill), `PATCH /orders/{ticket}` moves its price, stop limit, stops or expiry (omitted fields keep their value), and `DELETE /orders/{ticket}` cancels it. A stream with `events=orders` sends the new list after each of these, without polling. ## Stops on an open position `PATCH /api/v1/accounts/{id}/positions/{ticket}` with `sl`, `tp` or both. An omitted one keeps its value; `0` removes it. ```json {"sl": 2386.0, "tp": 2425.0} ``` Stops are prices, not distances. For a buy the stop loss sits below the current bid and the take profit above; for a sell the stop loss sits above the current ask and the take profit below. The broker checks `stops_level` and `freeze_level`; `POST /order_check` with a `TRADE_ACTION_SLTP` request checks `stops_level` (not the freeze level) before you send. ## Trailing a stop MetaTrader's trailing stop is not kept at the broker: the desktop terminal moves the stop while it runs, and stops moving it when it closes. Termless does not trail stops either. A bot trails a stop by moving it with `PATCH /api/v1/accounts/{id}/positions/{ticket}` and `{"sl": ...}`, which changes only the stop loss (the take profit keeps its value), and only ever in the profitable direction. As with the terminal, it works only while the bot runs: if the bot stops, the stop stays where it was last moved. ```python import os, time, uuid, requests base = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} def trail(ticket, distance, step): """Keep the stop `distance` behind the price, moving it by at least `step`, until the position closes.""" digits = None while True: r = requests.get(f"{base}/positions/{ticket}", headers=auth, timeout=35) if r.status_code == 404: return # closed: nothing left to trail p = r.json() if digits is None: digits = requests.get(f"{base}/symbols/{p['symbol']}", headers=auth, timeout=35).json()["digits"] q = requests.get(f"{base}/quotes", headers=auth, params={"symbols": p["symbol"]}, timeout=35).json()[0] if q["bid"] is not None: if p["side"] == "buy": # a buy closes at the bid: the stop follows it up new = round(q["bid"] - distance, digits) better = p["sl"] == 0 or new >= p["sl"] + step else: # a sell closes at the ask: the stop follows it down new = round(q["ask"] + distance, digits) better = p["sl"] == 0 or new <= p["sl"] - step if better: r = requests.patch(f"{base}/positions/{ticket}", json={"sl": new}, timeout=35, headers={**auth, "Idempotency-Key": f"trail-{uuid.uuid4()}"}) if r.status_code == 422: print("refused:", r.json()["retcode_text"]) # 10016: closer than stops_level; trail further back time.sleep(1) trail(51830012, distance=5.0, step=0.5) # gold: 5.00 behind the price, in steps of 0.50 ``` Moving a stop to a price it already has changes nothing, so the loop reads the position again rather than retrying a failed move; the next pass sends the stop the price calls for then. Keep `distance` beyond the symbol's `stops_level` (in points: `stops_level * point` in price), or the broker refuses the move with `10016`. ## Closing, whole or in part `DELETE /api/v1/accounts/{id}/positions/{ticket}` closes the whole position at market. Add `?volume=0.1` to close only that many lots; the rest stays open under the same ticket. More than the position holds is `400`. The result's `deal` is the closing deal, and `price` what you got. On a hedging account each position is independent. On a netting account (`summary.hedging: false`) a market order in the opposite direction reduces or reverses the existing position instead of opening a second one; the deal's `entry` tells you which (`out`, `inout`). ## What happened afterwards Two history routes answer "what became of it", both oldest first with the same window (`from` and `to` in server time, the last 8 days by default) and the same page size (up to 5,000, `before` for the next, older page): - `GET /api/v1/accounts/{id}/deals`: every fill, close and balance operation. - `GET /api/v1/accounts/{id}/orders/history`: every order that left the book, market orders included, with `state` (`filled`, `cancelled`, `expired`, `rejected`, ...), `time_done` and `position_id` (the position it opened or closed). The place to see a pending order that expired or was cancelled, which leaves no deal behind. Both take `position=` (everything of one position: its opening and closing deals, or the orders that opened and closed it), `ticket=` (the deals an order made, or that one order) and `symbol=`. The filters combine. With `position=` or `ticket=` and no `from`, the window reaches 10 years back, so an old position is found without a date. While it is still open or waiting, `GET /positions/{ticket}` and `GET /orders/{ticket}` return one position or one pending order (`404` once it is gone). Each position, order and deal carries `reason`: `web` for what you sent through Termless, `sl` and `tp` for a close at the stop loss or take profit, `stop_out` when the broker closed it for margin, `client`, `mobile` or `expert` for trades from MetaTrader's own apps. Read `reason`, not the comment: IC Markets and Pepperstone also write `[sl 4129.45]` or `[tp ...]` into the closing deal's comment, but not every broker does. ## Reading a refusal The `retcode` says why. The ones you will meet: | Code | Means | Do | |---|---|---| | `10014` Invalid volume | Off the step, below the minimum or above the maximum. | Read the spec; round to `volume_step`. | | `10015` Invalid price | A pending price on the wrong side of the market, or off the tick size. | Compare with the current quote and `tick_size`. | | `10016` Invalid stops | SL or TP too close, or on the wrong side. | Respect `stops_level`; check buy/sell direction. | | `10018` Market is closed | Outside the symbol's trade sessions. | Wait; check `sessions.trade`. | | `10019` Not enough money | Margin would exceed `margin_free`. | Smaller volume. | | `10004` Requote, `10020` Prices changed | The market moved more than `deviation`. | Re-read the quote and send again with the new price, once. | | `10021` No quotes | The symbol has no price yet. | Subscribe (any quote request) and wait a moment. | | `10027` Autotrading disabled by client, `10026` by server | Trading is off for this account. | Check `summary.trade_allowed`; ask the broker. | | `10030` Unsupported filling mode | Should not happen: Termless swaps a filling mode the symbol does not allow for one it does (IOC, then FOK, then return), and when you named one in `order_send` the answer's `warnings` says which it sent. | Report it with the symbol's `filling` list. | | `10036` Position already closed, `10038` Close volume exceeds the position | Stale state on your side. | Re-list positions. | ## After a timeout: the one rule A trade request that answers `504 unconfirmed`, `504 timeout` or `502 broker_error`, or that your own client gave up waiting for, leaves you not knowing whether the broker acted. The rule is: **retry with the same `Idempotency-Key`**, never with a new one and never without one. Five answers say the broker was **not** asked, so retrying them with the same key sends the trade: `503 busy` (it waited its whole turn behind earlier requests of the same kind, or behind another change to the same position or order), `503 stopping` (Termless is restarting), `503 disconnected` (the link was down), `403 trading_paused` (new trades are paused on the account) and `403`/`429 key_limit` (the key's limits). Since 0.6.0 a trade whose link dropped after it was sent answers `504 unconfirmed`, never `503 disconnected`: a `503 disconnected` on a trade means the link was down before anything left. `Idempotency-Key` is a header you put on `POST /orders`, `POST /order_send`, and the `PATCH` and `DELETE` on `/orders/{ticket}` and `/positions/{ticket}`: 1 to 200 printable ASCII characters of your choosing, unique per intended trade (`order-2026-10-03-0001`, a UUID, your own order id). What the server does with it: - The **first** request with a key is executed and its whole response (status, body) is kept for 24 hours. - A **repeat** with the same key and the same body gets that response back with the header `Idempotent-Replayed: true`, and never reaches the broker. This is the retry. - The same key with a **different body or query string** is `409 conflict`: the key names one trade, so use a new key for a new request. - Two requests **in flight** with one key: the second waits for the first's result (up to 30 s) and replays it, so the broker sees the trade once. - An **error** result is kept too: a `422` refusal, a `502`, `503` or `504` when the broker did not answer. The retry replays that answer instead of sending the trade again blind. The exceptions are the not-sent answers above (`503 busy`, `503 stopping`, `503 disconnected`, `trading_paused`, `key_limit`): those requests never left the server, so their key is let go and the retry with it is sent to the broker. So after a replayed `504`, look (`GET /positions`, `GET /orders`, `GET /deals`) and, if the trade is not there, send it again under a new key. One `504` deserves a word: `504 unconfirmed` means the broker took the trade (often it said "in process", `retcode` 10003) but its final result did not come within 25 s of sending. The broker may well have filled it. Termless keeps listening on that link for 2 minutes, and if the result comes, it is audited and **the stored answer for your key becomes the real one**: a retry with the same key a little later gets the `200` (or the `422`) instead of the `504`. Otherwise `GET /positions` tells you. - The key is **reserved before the broker is asked**. A first request that never got an answer at all (cut by the 30 s bound, the server killed or restarted, power lost) is therefore not forgotten: its retry is `409` ("did not finish; check the account's positions and orders, then use a new key"), never a second blind send. If the reservation itself cannot be written (database read-only or locked, disk full) the request is refused with `500` and not sent. The key is scoped to the caller, the method and the path, so two keys or two accounts never collide. Without the header nothing changes (and nothing protects you). A key on a read route is ignored. ```http POST /api/v1/accounts/pepperstone-12345678/orders HTTP/1.1 Authorization: Bearer tl_... Content-Type: application/json Idempotency-Key: order-2026-10-03-0001 {"symbol": "XAUUSD", "side": "buy", "volume": 0.1, "sl": 2380.0, "comment": "breakout"} ``` The retry, a few seconds later, with the same key and body: ```http HTTP/1.1 200 OK Content-Type: application/json Idempotent-Replayed: true X-Request-Id: 7c1e2a9f4b3d8e60 {"ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 81200131, "order": 51830031, "volume": 0.1, "price": 2391.6, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31} ``` ```python import uuid def place(acc, order, key=None): """Place once. Call again with the same key to retry: the answer is replayed, the broker is not asked twice.""" key = key or f"order-{uuid.uuid4()}" r = requests.post(f"{base}/accounts/{acc}/orders", headers={**auth, "Idempotency-Key": key}, json=order, timeout=35) replayed = r.headers.get("Idempotent-Replayed") == "true" if r.status_code == 422: return None, r.json(), key # refused: fix the request, use a new key if r.status_code in (502, 503, 504): return None, r.json(), key # unknown outcome: retry with this same key, then look r.raise_for_status() return r.json(), None, key result, err, key = place(acc, order) for _ in range(3): if result or (err and err.get("retcode")): # done, or refused break time.sleep(2) result, err, key = place(acc, order, key) # same key: a replay or the stored error, never a second trade ``` Two habits still help. Put your own id in `comment` (or a number in `magic`) so a fill is easy to find in `GET /deals` and on a `trade` stream event; keep it within 31 characters if MetaTrader's own apps should show all of it. And send your own `X-Request-Id` (up to 64 characters) on each call: the same id appears on the server's log lines and on the [audit trail](/docs/trails) row the trade wrote, so when something is unclear, one id finds everything. ## Real-money accounts Trading is on from the start for a demo or contest account. On an account the broker reports as real money (or as preliminary), every route that trades (`POST /orders`, `POST /order_send`, and the `PATCH` and `DELETE` on `/orders/{ticket}` and `/positions/{ticket}`) answers `403` with code `real_account` until an admin allows it, and nothing reaches the broker: ```json {"error": {"code": "real_account", "message": "pepperstone-12345678 is a real-money account and trading on it is off; an admin turns it on in the account's settings (PATCH /api/v1/accounts/pepperstone-12345678 with trade_real: true)"}} ``` An admin turns it on in the dashboard (the account's **Settings**, **Trade on a real-money account**, behind a confirm) or with `PATCH /api/v1/accounts/{id}` and `{"trade_real": true}` (or `trade_real` when adding the account); `false` turns it off again. It takes effect at once, without logging in again, for the dashboard and for every key allowed to trade the account. Reading (quotes, positions, deals, `GET /calc`, `POST /order_check`) is never affected. The account object shows the setting as `trade_real`. ## Pausing new trades, and a key's limits An admin can **pause new trades** on an account (the account's **Settings**, **Pause new trades**, behind a confirm, or `PATCH /api/v1/accounts/{id}` with `{"new_trades_paused": true}`). From then on an order that would open something answers `403 trading_paused` and is never sent, from the dashboard and from every key, while closing positions, moving stops and cancelling orders still work. It is the one switch that stops every bot opening anything at once without logging the account out. `/ready` says `new_trades_paused` (it blocks `trade`). A key can carry **limits** on the orders that open something: `max_volume` (the most lots per order: a bigger one is `403 key_limit`) and `max_open_per_min` (the most in 60 s: past it `429 key_limit` with `Retry-After`). Set them when making the key or later with `PATCH /api/v1/keys/{id}` (`null` lifts one). They catch a bot that goes wrong: a lot size typed as 10 instead of 0.10, a loop that keeps sending. Closing and changing stops are never limited, and nothing refused is sent. ## Small habits that prevent big mistakes - Trade with a `trade` key limited to the one account the bot is for. A `read` key cannot place anything. - Ask `GET /api/v1/accounts/{id}/ready?symbols=...` before each order: it answers from memory in well under a millisecond and says whether the link is up and the market open, and why not, with each symbol's price age for your bot to judge ([health checks](/docs/health-checks)). - Read the spec and the summary at start-up, not from memory. `volume_step`, `stops_level` and `server_offset` differ per broker and change. - Always send a stop loss on a market order unless you have a reason not to. It costs nothing and it caps the damage of a bug. - Check `ok` and keep the whole trade result in your log. `retcode_text` is for people; `retcode` is for code. - Send an `Idempotency-Key` on every trade call and retry with the same key. The server keeps the authoritative record in the audit trail (`GET /api/v1/audit?kind=trade`), one row per broker call with the request, the retcode and the broker's latency. - Listen instead of polling: a stream with `events=trades,account` tells you about every fill, stop hit and balance change as the broker applies it ([streaming](/docs/streaming#events-trades-account-positions-orders)). A UI that lists pending orders asks for `events=orders` and redraws from each snapshot; on `trade` events it shows the deal for a market order and skips the order events marked `pending: false` ([what a UI should show](/docs/streaming#what-a-ui-should-show)). - Prove the flow on a demo account first, at `volume_min`. Pepperstone's demo behaves like its live servers. - Keep positions small while the code is new: apart from the real-money switch above, Termless does not impose risk limits; it is a faithful pipe to the broker. --- # Setting up a bot How to wire a trading bot to Termless so it stays right when the broker link blips: one login for prices and orders, one key per program, an Idempotency-Key per order, what to do with an unconfirmed trade, timeouts, and where to watch the link. This page is the short list of choices that keep a bot correct when something goes wrong: the broker's server goes quiet for a few seconds, the link drops and comes back, or Termless restarts under it. Read [Trading safely](/docs/trading) and [Health checks for bots](/docs/health-checks) for the details behind each one. ## One login is enough A bot can read bars and prices and place orders through the same account. You do not need a second MT5 login for data. Each kind of request has its own queue per account. The broker serves one candle read at a time, so candle reads wait for each other, but an order never waits behind a candle read: orders have their own queue. All of them share one connection to the broker, so a very large download can slow everything a little while it arrives; ask for the bars you need, not years of them on every tick. A second login only pays when you want two things kept fully apart, for example test scripts that must never touch the account your bot trades on. ## One key per program Give each program its own key, so you can see what each one does in the [activity trail](/docs/trails) and cut one off without touching the others. - A program that only reads (a dashboard, a price recorder, a bar collector) gets a `read` key limited to the accounts it needs. A bug in it then cannot place an order. - The program that trades gets a `trade` key, limited to its account. - An admin can change a key's name, scope and accounts in place (`PATCH /api/v1/keys/{id}`): the key itself stays the same, so nothing that holds it has to change. A stream the key opened on an account it may no longer read ends at once. ## One Idempotency-Key per order Send an `Idempotency-Key` header with every order, and make it name the decision, not the attempt: the same key every time you retry the same order, a new key only for a new order. Then a retry can never open the trade twice. A random key made fresh on each attempt gives you none of this. ## Read the answer before you send again | Answer | What happened | What to do | |---|---|---| | `200` | The broker placed or filled it (`ok: true`). | Nothing more. | | `422 rejected` | The broker refused it; `retcode` says why. | Fix the request, then use a new key. | | `503 busy`, `503 stopping`, `503 disconnected` | It was **not sent**: it waited too long for its turn, Termless is restarting, or the link was down. | Send it again with the same key once things are back. | | `504 unconfirmed` | The broker **took** it but its final result did not come. It may have been filled. | Do not send a new order. Retry with the **same key** after a few seconds: if the result came late (Termless keeps listening for 2 minutes), the retry returns it. Otherwise check positions and orders, then decide. | | `504 timeout` | No answer within the request's time. | Check positions and orders before sending again. | ## Timeouts Give reads and orders at least **35 seconds** before your own HTTP client gives up. Termless answers every request within 30 seconds, and inside that it does useful waiting for you: a read whose link dropped while it was in flight is asked again once the link is back (within 28 seconds), and a read that arrives while the link is coming back from a drop waits up to 10 seconds for it. A client that gives up at 15 seconds throws that work away and turns a blip into an error. During a long outage (a broker's weekend maintenance) reads answer `503` in about 2 seconds, so a bot polling every second is not held up. ## Poll less: read from the stream A bot that polls `/summary` and `/positions` a few times a second asks for what the server already pushes. One stream with `events=account,positions,orders,trades` (`/stream` or `/ws`) carries the account every 500 ms and the positions and pending orders whenever they changed, plus every trade push numbered, so the bot reads from its own memory and sends nothing. On the box this guide was written on, three bots polled about 2.5 million requests a day for what four streams carry. Keep polling for what a stream does not carry (candles, history), and read `/ready` before an order. Candles: ask for the bars you need (`count=3`), not a window. Since 0.6.3 a count read starts narrow and from the newest bar it already knows for the symbol and timeframe, so a 3-bar read costs the broker a few bars, not four days of them. ## A safety switch and limits - **Pause new trades** on an account (its settings in the dashboard, or `PATCH /api/v1/accounts/{id}` with `new_trades_paused`) to stop every bot opening anything at once, without logging the account out. Closing and moving stops still work. Your bot sees `403 trading_paused` (not sent) and `/ready` says `new_trades_paused`. - Give a trading key **limits**: `max_volume` (the most lots per order) and `max_open_per_min` (the most new orders a minute). A bug that sends 10 lots instead of 0.10, or a loop that keeps sending, is refused before anything reaches the broker (`403` or `429 key_limit`). ## Watch the link, not the clock - Before an order, ask `GET /api/v1/accounts/{id}/ready`. It answers from memory in well under a millisecond. Since 0.6.0 it also warns (`ping_overdue`, blocks nothing) when a ping to the broker has waited more than 2 seconds: the link may be cut within seconds, and holding the order that long is cheap. - To hear about drops as they happen, keep a stream open (`/stream` or `/ws`): its `status` events say when the link goes down and comes back. - For history, read `GET /api/v1/accounts/{id}/events` (every drop with its cause) or the outages in `GET /api/v1/status`. An outage cut for missed pings starts at the first unanswered ping, marked `start_estimated`, so its length is the real gap, not just the seconds after Termless gave up on the link. Polling a "connected" flag once a minute misses most short drops. A drop that heals itself in a few seconds usually needs no alert at all: alert when the link stays down, or when an order comes back `unconfirmed`. --- # Health checks for bots Ask /ready before you send an order and act on what it says, read /status for uptime, outages and order latency over time, scrape /metrics with Prometheus, and watch it all on the dashboard's Health page. A trading bot needs two answers before it acts: can I trust what this account shows me right now, and will an order I send now reach the broker. Termless answers both per account with `GET /api/v1/accounts/{id}/ready`, and keeps the long view (how often each link dropped, why, and for how long) in `GET /api/v1/status`. Both work with any key that can see the account, a `read` key included. ## Check /ready before you send an order `/ready` is answered from memory, with no round trip to the broker, so it costs well under a millisecond: call it before every order, and at start-up before the bot does anything. Name the symbols you are about to trade in `symbols=`; the broker must know them and their market must be open for `ready_to_trade` (an old price is a note, not a block: each one's age is in `prices`). ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/ready?symbols=XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import os, requests base = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} ready = requests.get(f"{base}/ready", headers=auth, params={"symbols": "XAUUSD"}, timeout=5).json() if not ready["ready_to_trade"]: for r in ready["reasons"]: if r["blocks"] != "none": print("not trading:", r["code"], r["message"]) else: pass # send the order ``` ```javascript const base = `${process.env.TERMLESS_URL}/api/v1/accounts/pepperstone-12345678`; const auth = { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }; const ready = await (await fetch(`${base}/ready?symbols=XAUUSD`, { headers: auth })).json(); if (!ready.ready_to_trade) { for (const r of ready.reasons) if (r.blocks !== 'none') console.log('not trading:', r.code, r.message); } else { // send the order } ``` ```json {"account": "pepperstone-12345678", "checked_at": 1792300000123, "ready_to_read": true, "ready_to_trade": true, "reasons": [], "link": {"connected": true, "since": 1792290000, "connected_for_s": 10000, "ping_ms": 12.4, "reconnects": 2, "last_frame_age_ms": 800, "last_error": null, "retry_at": null}, "login": {"logged_in": true, "rejected": false}, "server": {"build": 6090, "build_verified": true, "verified_builds": [6090, 6182, 6230]}, "trading": {"allowed": true, "account_trade_allowed": true, "investor": false, "demo": true, "real_money": "demo", "key_can_trade": true}, "prices": [{"symbol": "XAUUSD", "watched": true, "asked": true, "last_tick_age_ms": 812, "market_open": true, "market_source": "sessions", "fresh": true}], "undecoded_last_hour": 0} ``` A not-ready account is still a `200`: the answer is the reasons. The status codes mean what they mean everywhere else (`404` an unknown account, `403` a key that may not use it, `400` a parameter the route does not take or more than 50 symbols). `ready_to_read` is false when a reason blocks `read`; `ready_to_trade` is false when one blocks `read` or `trade`. Reasons that block `none` are notes: they never turn a check false, but they are worth a line in the bot's log. `ready_to_trade` is false only for what makes an order certain to fail. An old price is not one of them (since 0.5.1): a market can go quiet for minutes, most of all right after it opens at 17:00 New York time, while a market order still fills at the broker's price. How old a price your strategy accepts is your bot's call; each asked symbol's `last_tick_age_ms` is in `prices`. ### What each reason means, and what to do | `code` | Blocks | What happened | What the bot should do | |---|---|---|---| | `disconnected` | read | The link to the broker is down and Termless is reconnecting on its own (`link.retry_at` is the next try). | Wait and check again; do not trade on prices you read before the drop. Usually back in seconds. | | `login_rejected` | read | The broker refused the login details. After a drop this is often the broker restarting (it refuses logins with code 2 for a moment) and Termless tries again after 10, 20, 30 and 60 s; otherwise it retries every 5 minutes. | Wait a few minutes. If it lasts, alert a person: the password may have changed. | | `turned_off` | read | An admin turned the account off. | Stop and alert a person. | | `trade_disabled` | trade | The broker turned trading off for this account. | Stop trading and alert a person; reading still works. | | `investor_login` | trade | The account is logged in with its investor (read-only) password. | Stop trading; an admin must set the trading password. | | `real_account_blocked` | trade | A real-money account whose `trade_real` is off. | Stop; an admin decides whether to turn it on ([real-money accounts](/docs/trading#real-money-accounts)). | | `key_read_only` | trade | Your key has the `read` scope only. | Use a `trade` key for the bot. | | `account_not_loaded` | trade | Connected, but the account record has not been read yet. | Check again in a second. | | `market_closed` | trade | An asked symbol's market is closed now (its trading sessions say so). | Wait for the session to open; an order now would be refused with `10018`. | | `unknown_symbol` | trade | The broker does not have an asked symbol. | Fix the name (`GET /symbols?q=` finds it). | | `price_stale` | none | An asked symbol's market is open but no tick came for 120 s: a quiet market, often right after it opens. | Your call: a market order still fills at the broker's price; if your strategy needs a fresh price, wait for one. | | `no_price` | none | An asked symbol has had no tick since connecting: nothing streams it. | Put it on the account's watchlist (or open a stream for it) if you want its price here; an order still goes through. | | `connected_recently` | none | Connected less than 10 s ago. | Fine to go on; positions and specs may still be loading for a moment. | | `link_quiet` | none | Connected, but nothing came from the broker for 15 s. | Hold new orders a few seconds: the heartbeat either hears from the broker or reconnects. | | `ping_overdue` | none | (0.6.0) A ping to the broker has had no answer for 2 s or more. Prices may still be arriving: a broker can push ticks and stop answering. | Hold new orders a few seconds: the link is cut when two pings in a row go unanswered (12 to 17 s after the broker went quiet) and comes back on its own. | | `new_trades_paused` | trade | (0.6.0) An admin paused new trades on the account. | Do not open anything; closing and moving stops still work. Alert a person if it was not you. | | `build_unverified` | none | The broker runs a server build Termless has not been checked against. | Usually fine; watch `undecoded_last_hour`. | | `undecoded_frames` | none | Frames from the broker could not be decoded in the last hour. | Usually harmless; if it keeps growing, tell whoever runs Termless (the frames are in `GET /diagnostics/undecoded`). | A simple rule that works: trade only when `ready_to_trade` is true; when a `read` reason shows, wait and check again every few seconds; when a `trade` reason other than `market_closed` shows, stop and tell a person. `prices` lists the account's watched symbols, then the asked ones that are not watched. `market_open` comes from the symbol's quote sessions on the broker's clock (`market_source: "sessions"`); until the spec is loaded (it is read right after each connect) Termless falls back to the forex week, open from Sunday 17:00 to Friday 17:00 New York time (`"heuristic"`). A closed market is never stale, so a Saturday is not an alarm. `/ready` is a check, not a promise: the broker can still refuse an order for its own reasons (volume, stops, margin). Read the trade result as [Trading safely](/docs/trading#the-trade-result) explains, and send an `Idempotency-Key` on every order. ## Read /status for the long view `GET /api/v1/status` says how well things have been going: a `verdict` (`healthy`, `degraded`, `down`) and a one-line `summary` at the top, the process, and for each account its uptime, outages, prices, order latency and protocol drift. ```sh curl -s "$TERMLESS_URL/api/v1/status" -H "Authorization: Bearer $TERMLESS_KEY" ``` ```python import os, requests status = requests.get(os.environ["TERMLESS_URL"] + "/api/v1/status", headers={"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}, timeout=10).json() print(status["verdict"], "-", status["summary"]) for a in status["accounts"]: up = a["uptime"]["24h"]["percent"] print(a["id"], a["verdict"], f"{up}% up in 24 h", a["uptime"]["24h"]["reconnects"], "reconnects") for o in a["outages"][:3]: print(" ", o["cause"], o["message"]) ``` ```javascript const res = await fetch(`${process.env.TERMLESS_URL}/api/v1/status`, { headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }, }); const status = await res.json(); console.log(status.verdict, status.summary); for (const a of status.accounts) { console.log(a.id, a.verdict, `${a.uptime['24h'].percent}% up in 24 h`); for (const o of a.outages.slice(0, 3)) console.log(' ', o.cause, o.message); } ``` - **Verdicts.** An account is `down` when it is enabled and not connected, `degraded` when it is connected but something is off (a server build Termless has not been checked against, undecoded frames in the last hour, its price feed stopped, a ping over a second, or under 99% up over the last hour), `off` when an admin turned it off, and `healthy` otherwise. The feed has stopped (`ticks.feed_quiet`) when every watched symbol whose market is open has gone over 2 minutes without a tick; one quiet symbol is just the market. The top verdict is `down` when every enabled account is down, `degraded` when any account is down or degraded, or when Termless wrote a crash report in the last 24 hours (`termless.crash_reports_24h`: it kept running, and the report is on the Health page's Troubleshoot tab). - **Uptime.** `uptime` has four windows ending now, `1h`, `24h`, `7d` and `30d`, each with `percent`, `up_ms`, `down_ms`, `measured_ms`, `reconnects`, `outages` and `longest_outage_ms`. Time before the account was added and time it was turned off are left out of `measured_ms`, so a new account is not penalised; Termless's own downtime (stopped, upgrading, killed) counts as down. `days` splits the last 30 UTC days the same way, one entry per day, for a status-page strip. - **Outages.** Newest first, with `from`, `to` (null while it lasts), `duration_ms`, a `cause` and a plain `message` such as "Pepperstone restarted its servers; back after 2 min.": An outage cut for missed pings starts at the first unanswered ping (the broker went quiet then, 12 to 17 s before Termless cut the link): `start_estimated` is true and `detected_at` is when the cut came, so `duration_ms` is the real gap. The account also counts, since Termless started, `pings_missed`, `trades_unconfirmed`, `trades_late` and the waits for a command's turn (`command_waits`, `command_wait_ms`); `/metrics` has them as counters. | `cause` | Means | |---|---| | `broker_maintenance` | The broker was restarting: it refused logins with code 2 right after the drop, or it happened in the forex weekend break. | | `broker_unreachable` | Termless could not reach the broker's server (TCP, TLS or WebSocket timed out or failed). | | `broker_unresponsive` | Connected, but the broker stopped answering (pings or requests went unanswered). | | `termless_restart` | Termless itself was stopped, restarted, upgraded or killed. | | `network` | The network on Termless's side (name lookups, no route, connections reset). | | `login_refused` | The broker refused the login details. | | `unknown` | Not enough was recorded to tell. | - **Order latency.** `orders` counts the trade requests sent through this server in the last 24 hours (`done`, `rejected`, `timeout`, `failed`) and gives the broker round trip as `latency_ms.p50`, `p95` and `max` over the ones the broker answered. It comes from the audit trail, so it survives a restart. - **Protocol drift.** `protocol` has the broker's `build`, whether it is `build_verified`, and the frames that could not be decoded in the last hour and day, by command. A broker that ships a new build shows here first. ## Scrape /metrics with Prometheus `GET /api/v1/metrics` gives the same numbers in the Prometheus text format: `termless_up`, `termless_uptime_seconds`, and per account `termless_account_connected`, `termless_account_ready{kind="read|trade"}`, `termless_account_ping_seconds`, `termless_account_uptime_ratio{window="1h|24h|7d|30d"}`, `termless_account_last_tick_age_seconds`, `termless_account_orders_total{result=...}` and more ([the full list](/docs/reference/health)). Give the scraper a `read` key of its own: ```yaml scrape_configs: - job_name: termless metrics_path: /api/v1/metrics scrape_interval: 30s authorization: credentials_file: /etc/prometheus/termless.key # one line: tl_... static_configs: - targets: ["127.0.0.1:8780"] ``` Two alerts cover most of it: `termless_account_connected == 0` for 2 minutes, and `termless_account_ready{kind="trade"} == 0` for 5 minutes during market hours. ## The Health page The dashboard's **Health** page (in the sidebar, under Monitor) has two tabs. **Status** shows the same report for people: one line at the top that says whether all is well, then a card per account with its status dot, uptime over 24 hours, 7 days and 30 days, a 30-day strip with one bar per day (hover a bar for that day's uptime and outages), ping, the last tick's age (with any quiet symbols named, calmly), the build with a light for protocol drift, the recent outages in plain words, and order latency with the counts. **Troubleshoot** has the evidence behind it: the process, the doctor (the same checks as `termlessd doctor`), each session, recent warnings and errors, undecoded frames, crash reports and the log. Its tab carries a dot while there is something to read there: red for a crash report in the last 24 hours, amber for errors in the last hour. Both refresh on their own while open. --- # Errors and retries Every HTTP status and error code the API answers with, what each one means, which ones to retry (and how a trade is retried safely), request ids, and the full list of MetaTrader return codes. ## One shape Every error is a JSON object with `error.code` (machine-readable, matching the HTTP status) and `error.message` (a sentence a person can read, often naming the field or the thing that was wrong): ```json {"error": {"code": "forbidden", "message": "this needs the trade scope; this key has read"}} ``` The only addition to that shape is a refused trade (`422`), whose body is the trade result plus `error`; see [trading safely](/docs/trading#the-trade-result). ## Request ids Every response, success or error, carries an `X-Request-Id` header. Send your own (1 to 64 characters of `A-Z a-z 0-9 - _ . :`) and the server keeps it; otherwise it makes one (16 hex characters). The same id is on every log line the request wrote (`req{id=...}`) and on every [audit trail](/docs/trails) row it caused, so your log, the server log and the trail line up on one id. Log it with every error you report. ```sh curl -si "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/summary" \ -H "Authorization: Bearer $TERMLESS_KEY" -H "X-Request-Id: bot-20261003-0042" | grep -i x-request-id # X-Request-Id: bot-20261003-0042 ``` ## Every status | Status | `code` | Means | What to do | |---|---|---|---| | `400` | `bad_request` | A field is missing or not valid: a volume that is not a number, an unknown timeframe, a candle range over 100,000 bars, a comment over 255 characters, an `after` that is not an event id, a `max_age_ms` outside 100 to 60,000, an admin key with an account limit. Or a query parameter the route does not take (a typo such as `tickt=`): the message names it and the parameters the route takes. | Fix the request. `message` names the problem. Do not retry unchanged. | | `401` | `unauthorized` | No key, a key that does not exist, a wrong password or setup token. | Check the `Authorization` header. Not a reason to retry. | | `403` | `forbidden` | The key lacks the scope, or may not use this account, or a cookie-authenticated write came from another site. | Use a key with the right scope and accounts. | | `403` | `trading_paused` | (0.6.0) New trades are paused on the account: an order that would open something was refused. Nothing was sent. | Closing and changing stops still work. An admin turns it off in the account's settings. | | `403` | `key_limit` | (0.6.0) The order is bigger than the key's `max_volume`. Nothing was sent. | Send a smaller order, or have an admin change the key's limit. | | `403` | `real_account` | A trade on an account the broker reports as real money, while trading on it is off (the default). Nothing was sent. | An admin turns it on with `PATCH /api/v1/accounts/{id}` and `{"trade_real": true}`, or in the account's settings. Not a reason to retry. | | `404` | `not_found` | No such account, symbol, ticket, key or route. For a ticket: it is not open (already closed or filled). | Check the id. For tickets, re-list positions or orders. | | `405` | `method_not_allowed` | The path exists but not with this method. | Check the reference. | | `409` | `conflict` | Already exists (an account id, or the same login on the same host), the state forbids it (setup already done, sign-in before setup), or an `Idempotency-Key` problem: the key was already used with a different body or query string, the first request with it did not finish (cut off, or the server restarted: the key is reserved before the broker is asked, so this is never a second blind send), or it is still running after 30 s. | Pick another id, or sign in. For a key: check positions and orders, then use a new key. | | `422` | `rejected` | The broker refused a trade. The body is the trade result; `retcode` says why. | Fix volume, price or stops. Never resend as is. | | `429` | `too_many_requests` | This IP is locked out (5 wrong passwords or 30 unknown keys in 15 minutes; a valid key is never refused by it), or the stream cap was hit (1,024 per server, 256 per key). `Retry-After` has the seconds. | Wait for `Retry-After`. Fix the key or the reconnect loop that caused it. | | `429` | `key_limit` | (0.6.0) The key sent its `max_open_per_min` orders that open something in the last 60 s. Nothing was sent. `Retry-After` has the seconds. | Wait for `Retry-After`. If your bot meant to send that many, have an admin raise the limit. | | `500` | `internal` | A bug in the server (if it was a panic, a crash report was saved), or on a trade route the `Idempotency-Key` could not be recorded (database read-only or locked, disk full): the trade was not sent. | Retry once. Tell the admin the `X-Request-Id`; the report is in diagnostics. | | `502` | `broker_error` | The broker's server failed, or answered something the client could not read. | Retry reads with backoff. For a trade, retry with the same `Idempotency-Key`. | | `502` | `untrusted_certificate`, `certificate_changed` | Only from checking a host: its certificate could not be verified, or a pinned host now shows another key. The body's `certificate` says what it is. | Make sure it is the broker's real address; an admin may pin the key (see [Brokers with broken certificates](/docs/running#brokers-with-broken-certificates)). | | `502` | `browser_only` | Only from checking a host: its web terminal lets only browsers in (a Cloudflare challenge). | Nothing to do from Termless; use another of the broker's hosts, if it has one. | | `503` | `disconnected` | The account has no link to the broker right now (it reconnects on its own; the route already waited up to 2 s, or up to 10 s for a read when the link dropped in the last minute), or it is turned off. A read whose link dropped while it was in flight was already asked once more after the reconnect. On a trade it means nothing was sent (a trade sent before the drop answers `504 unconfirmed`). | Retry with backoff. For a trade, retry with the same `Idempotency-Key` when it comes back. | | `503` | `stopping` | (0.6.0) Termless is stopping or restarting; the trade was not sent. Trades already sent get up to 10 s for their answer first; one still waiting then answers `504 unconfirmed`. | Send it again once Termless is back; the same `Idempotency-Key` is fine. | | `503` | `busy` | Requests of one kind go to the broker one at a time per account, and this one waited its whole turn (20 s; for a trade, until a second before the 30 s bound) behind earlier ones, or behind another change to the same position or order, without being sent. The broker was not asked. | Send it again; it is safe. A trade's `Idempotency-Key` is not kept for it, so the retry with the same key is sent. | | `504` | `timeout` | The broker did not answer a request that was sent (one broker call is given 20 s), or the whole request ran past 30 s. | Retry reads. For a trade, retry with the same `Idempotency-Key`, then check positions and orders. | | `504` | `unconfirmed` | (0.6.0) A trade the broker took whose final result did not come: it **may have been carried out**. The body has `request_id` and `retcode` (null, or the last in-between state, such as 10003 "in process"). | Do not send a new order. Retry with the same `Idempotency-Key` after a few seconds: if the result came late, the retry returns it. Otherwise check positions and orders. | ## Which to retry | Kind of call | `503`, `504`, `502` | `429` | `4xx` other than 429 | |---|---|---|---| | Reads (`GET`) | Retry with backoff: 1 s, 2, 4, up to 30 s. | Wait `Retry-After`. | Fix the request. | | Trades (`POST`, `PATCH`, `DELETE` on orders and positions) | **Retry with the same `Idempotency-Key`**: the stored answer is replayed (`Idempotent-Replayed: true`), the broker is never asked twice. Then look (`GET /positions`, `GET /orders`, `GET /deals`) before a new key. Without a key: look first, then decide. | Wait `Retry-After`. | Fix the request. `422`: read the `retcode`. `409`: a key problem, see above. | | Account and key admin | Safe to retry: adding an account twice is `409`, which you can treat as done. | Wait. | Fix. | ### Retrying a trade Put an `Idempotency-Key` on every trade call, and on a retry send the same key with the same body. The first request's answer, whatever it was (a `200`, a `422`, even a `504`), is stored for 24 hours and replayed; a replayed `504` means the broker never answered the first time, so check positions and orders before you send the trade again under a new key. The answers that are not stored are the ones that say the trade was never sent (`503 busy`, `503 stopping`, `503 disconnected`, `403 trading_paused`, `403`/`429 key_limit`): the retry with the same key goes to the broker. [Trading safely](/docs/trading#after-a-timeout-the-one-rule) has the full rules and a code sample. ```python def trade_with_retry(method, url, key, **kw): """One intended trade. Retries carry the same key; a replay never reaches the broker.""" for delay in (0, 2, 4, 8): time.sleep(delay) r = requests.request(method, url, headers={**auth, "Idempotency-Key": key}, timeout=35, **kw) if r.status_code in (502, 503, 504) and r.headers.get("Idempotent-Replayed") != "true": continue # the broker did not answer; ask again with the same key return r # 200, 422, or a replayed error: now look before a new key return r ``` A `503` while an account reconnects usually clears within a few seconds; the account's `status.retry_at` (UTC) in `GET /api/v1/accounts/{id}` says when the next attempt is. If `status.login_rejected` is true the broker refused the login. Right after a working connection that is usually the broker restarting (it refuses logins for a few seconds), so the account tries again after 10, 20, 30 and 60 seconds; after that, or when the login never worked, it retries only every five minutes. If it keeps failing, fix the password with `PATCH /api/v1/accounts/{id}` rather than waiting. ```python import time def get_with_backoff(url, **kw): delay = 1 while True: r = requests.get(url, headers=auth, timeout=35, **kw) if r.status_code in (502, 503, 504): time.sleep(delay) delay = min(delay * 2, 30) continue if r.status_code == 429: time.sleep(int(r.headers.get("Retry-After", "60"))) continue r.raise_for_status() return r.json() ``` ## Timeouts, from the inside One call to the broker is given 20 seconds. Calls of one kind (candles, history, trades) go to the broker one at a time per account, because its replies carry no request id; a call that waits its whole 20 seconds for its turn is `503 busy` and was never sent, while `504 timeout` means a call that was sent got no answer. A route that chains several (a quote for a symbol that was not subscribed yet, a trade) is given up with `504` after 30 seconds in total (`TERMLESS_REQUEST_TIMEOUT` on the server changes it; `0` removes the bound). Set your own client timeout a little above that (35 s) so you see the server's answer rather than your own exception. Streams are the exception: they stay open as long as you read. ## Retcodes MetaTrader's return codes, as `retcode` in every trade result. `10008`, `10009` and `10010` set `ok: true`; every other code is a refusal and comes with HTTP `422`. Test `ok` rather than one code: a placed pending order comes back as `10008` from some brokers and `10009` from others (IC Markets). | Code | Meaning | |---|---| | `10004` | Requote | | `10006` | Request rejected | | `10007` | Request cancelled by trader | | `10008` | Order placed | | `10009` | Request completed | | `10010` | Only part of the request was completed | | `10011` | Request processing error | | `10012` | Request cancelled by timeout | | `10013` | Invalid request | | `10014` | Invalid volume | | `10015` | Invalid price | | `10016` | Invalid stops | | `10017` | Trade disabled | | `10018` | Market is closed | | `10019` | Not enough money | | `10020` | Prices changed | | `10021` | No quotes to process the request | | `10022` | Invalid order expiration date | | `10023` | Order state changed | | `10024` | Too frequent requests | | `10025` | No changes in request | | `10026` | Autotrading disabled by server | | `10027` | Autotrading disabled by client | | `10028` | Request locked for processing | | `10029` | Order or position frozen | | `10030` | Unsupported filling mode | | `10031` | No connection with the trade server | | `10032` | Operation allowed only for live accounts | | `10033` | Pending order limit reached | | `10034` | Volume limit reached | | `10035` | Incorrect or prohibited order type | | `10036` | Position already closed | | `10038` | Close volume exceeds the position volume | | `10039` | A close order already exists for this position | | `10040` | Position limit reached | | `10041` | Pending order activation request rejected, order cancelled | | `10042` | Only long positions are allowed | | `10043` | Only short positions are allowed | | `10044` | Only position closing is allowed | | `10045` | Position closing allowed only by FIFO rule | | `10046` | Opposite positions on one symbol are not allowed | ## Connection status in responses Errors are not the only signal. `GET /api/v1/health` answers `degraded` when an enabled account is not connected. Every account object carries `status`: `connected`, `since`, `reconnects`, `ping_ms`, `last_error`, `login_rejected`, `retry_at`. Every stream starts with a `status` event and sends another whenever the link changes, so a streaming client always knows whether silence means a quiet market or a broken link. And `GET /api/v1/accounts/{id}/events` is the account's connection history (connected, lost with the reason, reconnected), when you want to know what happened while you were not looking. --- # Limits and lockouts Every cap in the API in one place: request sizes, stream counts, timeouts, lockouts and the broker's own limits. Termless does not rate-limit ordinary API calls: it is your server, and the broker's own limits apply behind it. The caps below exist to keep one misbehaving client from harming the rest. ## Requests | What | Limit | |---|---| | Symbols per quote or stream request | 200 (`?symbols=`) | | `GET /trades` without `after` | the newest `limit` events, default 100, at most 1,024 (0.6.3) | | Candles per request | 50,000 by `count` (`count` plus `offset`); a `from`/`to` range over 100,000 bars is `400`, one over 50,000 keeps the latest 50,000 | | Big candle requests (over 10,000 bars) | one at a time per account; the account's others wait their turn (within the 30 s route bound) | | Batch candle reads (`POST /candles/batch`) | 1 to 20 ranges, at most 200,000 bars in all (each range's whole span counts); a bad range refuses the batch (0.7.0) | | Specs per request (`GET /specs`) | 200 names (0.7.0) | | Statistics (`GET /stats`) | a range of at most 366 days; `days` 1 to 366 (default 30) (0.7.0) | | How long a `/quotes` read keeps its symbols | `hold` 0 to 3,600 s (default 600); `0` subscribes nothing (0.7.0) | | Ticks per request (`GET /ticks`) | `count` 1 to 20,000 (default 1,000), from what the server kept (below) | | Deals or history orders per request | a `from`/`to` range of at most 10 years; default the last 8 days up to tomorrow, or 10 years back with `position` or `ticket` | | Order books (`GET /book`) | 32 per account (one more is `400`; `DELETE /book` releases one); a book older than `max_age_ms` (100 to 60,000, default 1,000; outside that is `400`) is asked for again, waiting up to 3 s; a symbol that brought no fresh book is not asked again for 30 s, one the broker never sent a book for (`time: 0`) for 5 minutes | | Symbol search | `limit` up to 10,000 (default 50) | | Server directory search | `limit` up to 200 (default 20) | | Deals page, history orders page | `limit` up to 5,000 (the default), `before` cursor | | Trade events kept for resuming | the last 1,024 per account (`GET /trades?after=`, `?after=` or `Last-Event-ID` on a stream); older is a `resync` | | Audit trail page | `limit` up to 1,000 (default 100), `before` cursor | | Connection history page | `limit` up to 1,000 (default 100), `before` cursor | | Equity curve | `hours` 1 to 168 (default 24) | | Undecoded frames | `limit` up to 200 (default 50); `body_hex` cut to 128 bytes unless `bodies=1` (then up to 64 KB a frame) | | Log lines | `lines` up to 5,000 (default 200) | | Request body | 1 MB | | `Idempotency-Key` | 1 to 200 printable ASCII characters; reserved before the broker is asked; results kept 24 hours; a concurrent repeat waits up to 30 s | | `X-Request-Id` | 1 to 64 characters of `A-Z a-z 0-9 - _ . :` (anything else is replaced) | | `comment` on an order | up to 255 characters (more is `400`); the broker keeps 31, Termless keeps the whole text for a market or pending order | | Key name | up to 80 characters | | Account id | `a-z`, `0-9`, `-`, up to 48 characters | | Query parameters | one a route does not take is `400`, naming the ones it takes; `key=` is accepted anywhere | | Admin password | 15 to 200 characters with a lowercase letter, a capital, a digit and a symbol (anything but a letter or a digit is a symbol, a space too). Checked when a password is set; one set before the rule keeps working until it is changed. | ## Streams | What | Limit | |---|---| | Open streams per server | 1,024 (SSE and WebSocket together) | | Open streams per key or dashboard session | 256 | | Symbols per stream | 200 | | Symbols streamed per account beyond its watchlist (every stream's, quotes read's and ticks read's symbols; a stream's leave when its last stream closes, a read's when its lease ends, 0.7.0; before, a read's stayed until a restart) | 1,000 (0.6.3; a stream or read past it is refused with 400; the watchlist is never counted, never refused, and a symbol taken off it stops streaming unless a stream holds it) | | Buffered ticks per stream | 1,024; beyond that a slow client gets the latest tick per symbol and a `gap` event (0.7.0) | | Bar series per stream | 100 (`bars=`, 0.7.0); buffered bar events 1,024, beyond that a slow stream gets a `bars_gap` per series | | Bar series per account, across its streams | 200 symbols and 1,000 series (0.7.1); past either a stream's series are refused with `429` and a message naming the cap | | `batch_ms` | 0 to 100 | | Heartbeat | every 15 s (SSE comment, WebSocket ping) | A stream over either count answers `429 too_many_requests` with `Retry-After` and a message naming the cap. ## Time | What | Value | |---|---| | One broker request | 20 s before it is given up (`504 timeout`) | | Waiting for a turn (requests of one command go to the broker one at a time per account, candles from many callers included) | up to 20 s, then `503 busy`: the request was not sent, so sending it again is safe | | A request the broker did not answer in time | keeps its kind's turn up to 40 s more for its late reply; if none comes, the link is closed and the account reconnects | | One API route (except streams) | `504 timeout` after 30 s in total (`TERMLESS_REQUEST_TIMEOUT` seconds; `0` = no bound) | | A trade's result push after the broker queued it | 25 s, then `504` from the trade route itself (the audit row and the idempotency result are still written; the position may have opened) | | Waiting for a reconnecting account before `503` | up to 2 s | | Waiting for a first price on a newly subscribed symbol | up to 3 s | | A quote lease (`/quotes`, `/ticks`) | 600 s after the caller's last read by default; ended leases are let go every 30 s (0.7.0) | | A bar's close (bar streams) | read from the broker 2 s after its period ends; read again a minute later (0.7.0), and so is a period that closed with no bar while its symbol was trading (0.7.1) | | A cached symbol spec | read again once it is a day old (`TERMLESS_SPEC_MAX_AGE_S`, 0.7.0), off the trade path: a trade, a position read or a margin check uses the spec it has and never waits on that read | | A symbol subscribed for the server's own use (a `/calc` price, a conversion, a position's price) | kept 10 minutes after its last use (`TERMLESS_OWN_SUB_HOLD_MS`), at most 200 per account, then let go (0.7.0) | | A trade still waiting for its turn when its deadline passes | never sent: `503 busy`, so sending it again is safe (0.7.0) | | A tick subscription the broker refused or never confirmed | sent again at the next sweep, every 30 s (0.7.0) | | A candle in the cache | only once it closed at least 15 minutes ago; younger bars always come from the broker (0.7.0) | | Reconnect backoff | 1 s, doubling to 30 s, with about 20 % jitter | | Retry after the broker rejected the login | after 10, 20, 30 and 60 s when the login worked within the last hour (a broker restarting refuses logins with code 2 for seconds to minutes), then every minute for code 2 until an hour after the loss (0.6.3), then every 5 minutes; any other code, or no recent working login, every 5 minutes | | Dead-link detection | a ping every 5 s must be answered within 6 s; the second miss in a row closes the link (12 to 17 s after the broker went quiet), the fifth while a big reply is still arriving (about 30 s) | | Dashboard session | 30 days | ## Retention | What | Kept | |---|---| | Audit trail | 90 days or 200,000 rows, whichever is hit first | | Connection history | 90 days or 50,000 rows | | Equity samples | 7 days (one a minute while connected) | | Idempotency results | 24 hours | | Magic numbers and long comments kept for orders sent through Termless | 400 days, the newest 100,000 orders | | Trade events kept for resuming | the last 1,024 per account, in memory and in the database, so the numbering carries on across a restart or an upgrade | | Ticks kept for `GET /ticks` | since 0.7.0 only for symbols read through `/ticks` (from the first read on): the newest 1,000 per symbol (`TERMLESS_TICK_HISTORY`, at most 100,000; `0` keeps none) and 100,000 over all of an account's symbols, shared evenly (500 symbols keep 200 each); in memory, about 7 MB an account at most; a reconnect starts them again | | Settled candles (the candle cache) | 32 MB over every account (`TERMLESS_CANDLE_CACHE_MB`, `0` keeps none), least recently used out first; a new broker connection starts an account afresh (0.7.0) | | Log files | 14 days, one file a day | | Undecoded frames | 200 in memory, read back from the end of `captures/undecoded.jsonl` at start; at most 5 bodies an hour per (account, command, kind) appended to that file | Pruning runs at start and then hourly, off the request path. ## Lockouts Counted per caller, each lasting 15 minutes. A caller is its IPv4 address, or for IPv6 its /64 (the block one home or server is normally given), so stepping through the addresses of one block does not reset the count: | Trigger | Locked out of | |---|---| | 5 wrong admin passwords or setup tokens in 15 minutes | sign-in (`POST /session`, `POST /setup`, `PUT /admin/password`) | | 30 unknown API keys in 15 minutes | key authentication on every route | Password checks have two more limits, so that sign-in cannot be used to wear the server down or to slip extra guesses past the lockout: | Limit | What happens past it | |---|---| | One password check at a time per IP (sign-in and password change) | Another attempt from the same IP while one is being checked answers `429` with `Retry-After: 1`. It is not a guess: nothing is checked or counted. | | Two password checks at a time on the whole server (each takes 19 MiB, by design of the hash) | Further checks wait their turn, up to 10 seconds, then answer `429` with `Retry-After: 5`. At most 64 wait at once; one more is refused at once the same way. | A locked-out request answers `429` with `Retry-After`. The lockout is in memory and clears when the server restarts; the lockout tables remember at most 50,000 addresses, past which everything but live lockouts is forgotten. Each lockout is also a row in the audit trail (`kind: "lockout"`, with the IP). > **Note: Behind a reverse proxy** > > Without `--trust-proxy` (or `TERMLESS_TRUST_PROXY=1`) every request appears to come from the proxy's address, so one person's wrong passwords lock everyone out. With it, the server reads the client address from one header only, `--proxy-header` / `TERMLESS_PROXY_HEADER` (default `X-Forwarded-For`, last hop; `X-Real-IP` is never a fallback), and the scheme from `X-Forwarded-Proto`. The proxy must overwrite that header on every request, and clients must not be able to reach the port directly; otherwise a client chooses its own address. [Authentication](/docs/authentication#behind-a-reverse-proxy) has the details. ## Broker gateways Gateways must be on the public internet. A host that resolves to loopback, link-local (cloud metadata), private (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`), carrier-grade NAT (`100.64/10`), multicast or documentation space is refused with `400` by `POST /servers/check` and when adding or changing an account, unless termlessd runs with `TERMLESS_ALLOW_PRIVATE_GATEWAYS=1` (implied by `TERMLESS_ALLOW_INSECURE_GATEWAYS=1`, which a plain `ws://` test broker needs). A failed check answers one generic `502` whatever went wrong; the reason is in the server log and the audit trail. ## The broker's limits These are not Termless's and vary per broker and symbol: - `volume_min`, `volume_max`, `volume_step`, `volume_limit` (the largest total open in one direction) in the symbol spec. - `stops_level` and `freeze_level` in points. - Pending order count (`10033`) and position count (`10040`) per account. - `10024 Too frequent requests` when a bot hammers the trade server; back off for a few seconds. - Candle history reaches about 100,000 bars back per timeframe through the web protocol (M1 about three months); older bars are not served. - Brokers serve no tick history through the web protocol. `GET /ticks` has only what Termless kept since subscribing a symbol (above), so record ticks from a stream if you need every one. - Brokers must have web access turned on for their MT5 servers; `POST /api/v1/servers/check` tells you whether a host has it. ## Events on a stream Trade, account and positions events are not coalesced like ticks: a slow client misses none until it falls more than 1,024 events behind, and then it gets a `resync` event. `account` and `positions` are computed every 500 ms at most and sent only when something changed. --- # Activity and trails The audit trail of every write and security event, each account's connection history, the equity curve, who is connected and what they receive right now, and the request id that ties a bot's log, the server log and the trail together. Termless keeps a record of what happened so that nobody has to reconstruct it from memory: every trade call with the broker's answer, every change to accounts and keys, every sign-in and wrong password, every time an account connected or lost its link, and the account's money once a minute. Rows are written off the request path (a batch writer), so recording never slows a trade, and pruned hourly so the database stays small. | | Route | Scope | Kept | |---|---|---|---| | Audit trail | `GET /api/v1/audit` | admin | 90 days or 200,000 rows | | Connection history | `GET /api/v1/accounts/{id}/events` | read | 90 days or 50,000 rows | | Equity curve | `GET /api/v1/accounts/{id}/equity` | read | 7 days | | Who is connected | `GET /api/v1/connections`, `GET /api/v1/keys/{id}/traffic` | admin | in memory, since the server started | ## Request ids tie it together Every response carries an `X-Request-Id` header. Send your own (1 to 64 characters of `A-Z a-z 0-9 - _ . :`) and it is kept; otherwise the server makes one of 16 hex characters. The same id is on every log line the request wrote (`req{id=...}`) and on every audit row it caused. So when a bot says "I placed order 42 at 09:14 and got a timeout", its request id finds the audit row (what the broker actually answered, in how many milliseconds) and the server log lines (what the session was doing) in one search. ## The audit trail `GET /api/v1/audit` (admin) returns rows newest first. Filter with `account`, `kind` and `actor`; page with `before` = the `id` of the last row you have and `limit` (default 100, at most 1,000). Every filter given must match; an empty one is ignored. ```sh curl -s "$TERMLESS_URL/api/v1/audit?kind=trade&account=pepperstone-12345678&limit=20" \ -H "Authorization: Bearer $TERMLESS_ADMIN_KEY" ``` Two more filters find a row without paging through the trail: - `request_id=bot-20261003-0042`: the rows one request caused, an exact match (indexed, so instant at any size). - `q=xauusd`: a case-insensitive piece of text anywhere in the row's `request_id`, `actor`, `account`, `route`, `summary` or `result` (up to 200 characters; `%` and `_` are plain characters). It reads from the newest row down and stops at `limit` matches, so a common word answers at once and a rare one reads the whole trail: 40 to 60 ms at the 200,000-row cap on a laptop. `before` pages a search like any other list. ```sh curl -s "$TERMLESS_URL/api/v1/audit?q=not%20enough%20money&limit=50" -H "Authorization: Bearer $TERMLESS_ADMIN_KEY" curl -s "$TERMLESS_URL/api/v1/audit?request_id=bot-20261003-0042" -H "Authorization: Bearer $TERMLESS_ADMIN_KEY" ``` ```json [{"id": 4821, "at": 1790981179473, "kind": "trade", "actor": "key_3f9a1c07", "actor_kind": "key", "account": "pepperstone-12345678", "route": "market order", "summary": "market buy 0.10 XAUUSD", "request": "{\"symbol\":\"XAUUSD\",\"volume\":0.1,\"type\":0,\"price\":0.0,\"sl\":2380.0,\"tp\":2420.0,\"order\":0,\"position\":0,\"comment\":\"breakout\"}", "status": 200, "retcode": 10009, "result": "Request completed order 51830031 deal 81200131", "latency_ms": 212, "request_id": "bot-20261003-0042", "ip": null}] ``` | Field | Meaning | |---|---| | `at` | When, unix milliseconds UTC. | | `kind` | `trade`, `account`, `key`, `signin`, `auth_failed`, `lockout`, `password`, `setup`, `server_check`, `server_trust`, `start`. | | `actor`, `actor_kind` | Who: a key id (`key`), `admin` (the dashboard), the client IP before sign-in (`anonymous`), or `termlessd` itself (`system`). | | `account` | The account concerned, when one was. | | `route` | What was done. For a trade: `market order`, `pending order`, `order change`, `order cancel`, `SL/TP change`, `close`, `partial close`, `order_send`. For an account: `add`, `update`, `delete`. For a key: `create`, `delete`. | | `summary` | One line a person can read. | | `request` | For a trade: the request sent to the broker, in short JSON (cut to 400 characters). | | `status` | The HTTP status the caller got. | | `retcode`, `result`, `latency_ms` | For a trade: the broker's return code, its answer in words with the order and deal tickets (or the error when it did not answer), and the broker round trip. | | `request_id` | The `X-Request-Id` of the request that caused the row. | | `ip` | The client IP, on sign-ins, wrong passwords and lockouts. | A trade is one row per broker call, with `status` 200, 422 or 502 to 504 (a `503` whose result says it "was not sent" waited its whole turn and never reached the broker). An idempotent replay writes no row: the broker was not asked, so there is nothing new to record. Wrong passwords and setup tokens are `auth_failed` with the IP; the fifth in 15 minutes adds a `lockout`. `server_check` records every `POST /servers/check`, including the failures the route itself only reports as one generic `502`; `server_trust` every certificate key an admin pinned or unpinned. A trade's `summary` names the side (`market buy 0.10 XAUUSD`, `buy limit 0.10 EURUSD at 1.07800`, `close 0.10 of buy #51830031 XAUUSD`), so a search for `buy` or `sell` finds it. `start` marks each server start with the version and the account count. ```python def my_trades_since(ts_ms): """Every trade call on the account since ts_ms, oldest first, by paging the trail.""" rows, before = [], None while True: page = requests.get(f"{base}/audit", headers=admin, params={"kind": "trade", "account": acc, "limit": 1000, **({"before": before} if before else {})}).json() rows += [r for r in page if r["at"] >= ts_ms] if not page or page[-1]["at"] < ts_ms: return rows[::-1] before = page[-1]["id"] ``` The trail wants an `admin` key. A bot with a `trade` key does not read it; the person running the bot does, and the bot's own `X-Request-Id`s are the join. ## Connection history `GET /api/v1/accounts/{id}/events` (read) is the account's link to the broker over time, newest first, paged like the audit trail (`before` = an `id`, `limit` at most 1,000). ```json [{"id": 310, "at": 1790968298412, "account": "pepperstone-12345678", "kind": "connected", "reason": "build 6090", "duration_ms": 1840}, {"id": 309, "at": 1790968296572, "account": "pepperstone-12345678", "kind": "lost", "reason": "connection lost: 2 pings unanswered in a row (the broker keeps the socket open but has stopped answering)", "duration_ms": 73284110}] ``` | `kind` | `reason` | `duration_ms` | |---|---|---| | `started` | | | | `connected` (the first login), `reconnected` (every later one) | `build N`, the broker's build | how long the account had been disconnected | | `lost` | why the link was lost: `connection lost: ...` with the cause (`2 pings unanswered in a row ...`, `command 5 was never answered ...`, `the broker closed the connection`) | how long it had been connected | | `connect_failed` | the error | | | `login_rejected` | the broker's refusal; the account retries after 10, 20, 30 and 60 s when the login worked within the last hour, then every minute for the restart code (2) until an hour after the loss, else every 5 minutes | | | `stopped` | | how long it had been connected | Read it when a stream went quiet, when `reconnects` in the account's status climbed, or when a trade answered `503` and you want to know how long the gap was. `GET /api/v1/status` turns the same history into uptime over 1 hour to 30 days and a list of outages with their causes ([health checks](/docs/health-checks#read-status-for-the-long-view)). ## Equity curve `GET /api/v1/accounts/{id}/equity?hours=24` (read; 1 to 168 hours) returns balance, equity, margin and profit about once a minute while the account was connected, oldest first, the first sample right after each connect, and `gaps`: the periods inside the window when the account was not connected, as `{from, to}` in unix milliseconds UTC, oldest first, with `to: null` while it still is not. They come from the connection history above, so nothing extra is stored. ```json {"account": "pepperstone-12345678", "hours": 24, "every_s": 60, "samples": [{"at": 1790977560000, "balance": 10412.58, "equity": 10641.2, "margin": 878.93, "profit": 228.62}, {"at": 1790977620000, "balance": 10412.58, "equity": 10650.69, "margin": 878.93, "profit": 238.11}], "gaps": [{"from": 1790968296572, "to": 1790968298412}]} ``` Draw a break over each gap instead of a straight line from the last sample before it to the first after: the account's money was not being watched then, and a trade may have happened in between. A gap opens at a `lost` or `stopped` event and closes at the next `connected` or `reconnected`; a server that was killed rather than stopped leaves no `stopped`, so that gap opens at the account's last sample before the restart. The route reads only the database, so an account that is turned off or disconnected still shows its stored curve, with an open gap at the end. It is a week of context for a chart or a drawdown check, not a tick record: for the account's money as it changes, ask a stream for `events=account`. ## Who is connected The trails above say what happened. `GET /api/v1/connections` (admin) says what is going out right now and to whom: when you hand an app a key (a trade journal, a bot, an agent), this is where you see what it receives, how often and how live. ```sh curl -s "$TERMLESS_URL/api/v1/connections" -H "Authorization: Bearer $TERMLESS_ADMIN_KEY" ``` ```json {"time_ms": 1790981179473, "since_ms": 1790968290000, "streams": [{"id": 12, "kind": "sse", "who": {"kind": "key", "key_id": "key_3f9a1c07", "name": "Price board"}, "ip": "203.0.113.7", "user_agent": "python-requests/2.32", "account": "pepperstone-12345678", "symbols": ["XAUUSD", "EURUSD"], "events": ["ticks", "trades", "account"], "batch_ms": 0, "opened_at": 1790977520000, "sent": {"messages": 52811, "bytes": 6203417, "ticks": 52102, "events": 708}, "last_sent_at": 1790981179401, "rate_per_s": 14.6, "coalesced": 0}], "keys": [{"key_id": "key_3f9a1c07", "name": "Price board", "scope": "read", "accounts": ["pepperstone-12345678"], "streams_open": 1, "stream_bytes": 6203417, "requests_1h": 120, "requests_24h": 2211, "errors_1h": 0, "bytes_out_1h": 48210, "last_request_at": 1790981175002, "last_ip": "203.0.113.7", "top_routes_1h": [{"route": "GET /api/v1/accounts/{id}/deals", "count": 60}, {"route": "GET /api/v1/accounts/{id}/positions", "count": 60}]}], "dashboard": {"sessions_active": 1, "streams_open": 0, "stream_bytes": 0, "requests_1h": 340, "requests_24h": 1902, "errors_1h": 0, "bytes_out_1h": 912044, "last_request_at": 1790981179470}} ``` - **Streams**: every open stream, the key (or the dashboard) that opened it, from which address and program, for which account, symbols and events, and what it has sent so far: messages (ticks, events, the rest), bytes, the last one's time, and the rate over the last 10 seconds. A stream leaves the list when it closes. - **Keys**: every key, with zeros until it is used: streams open, requests in the last hour and day, errors, bytes, its last request and address, and its busiest routes. - **Dashboard**: the dashboard's own sessions, streams and requests, counted apart from the keys. `GET /api/v1/keys/{id}/traffic?limit=100` is one key's last requests (up to 500 are kept), newest first, each with its time, route, path (with the query; `key=` is removed), status, time taken, bytes and address, plus its open streams. It is the place to see what an app actually asks for, and when. All of this is in memory: it starts empty when termlessd starts (`since_ms`), and nothing of it is written to disk. A key's secret never appears in it. ## From the box The trails live in `termless.db` beside the accounts and keys; `sqlite3` reads them directly, and the request id in a row finds the matching log lines: ```sh sqlite3 /var/lib/termless/termless.db \ 'select at, kind, actor, route, summary, status, retcode, latency_ms, request_id from audit order by id desc limit 50' grep 'id=bot-20261003-0042' /var/lib/termless/logs/termlessd.2026-10-03.log ``` `TERMLESS_ADMIN_KEY` in the examples above is a key with the `admin` scope; the trail is for the person running the server, not for the bot. --- # Running the server Installing termlessd on Linux as a system service, its settings, running it behind a proxy, the data folder, adding an account, upgrading, the doctor, and reading diagnostics, the trails, crash reports and undecoded frames. `termlessd` is one static binary (about 14 MB, musl, no dependencies) for `x86_64` and `aarch64` Linux. It needs a data folder it owns and a port to listen on; everything else is optional. This page installs it as a systemd service; to run it as a container instead, see [Running in Docker](/docs/docker). ## Install Releases come as one archive per processor: `termless--linux-x86_64.tar.gz` for most PCs and cloud servers, `termless--linux-aarch64.tar.gz` for ARM machines (Ampere and Graviton servers, a 64-bit Raspberry Pi). `uname -m` on the box tells you which (`arm64` is `aarch64`). Each archive holds one folder with the server, `install.sh`, `termlessd.service`, the Docker files and a README. On the box: ```sh tar xzf termless--linux-x86_64.tar.gz cd termless--linux-x86_64 sudo sh install.sh ``` The script creates the system user `termless`, installs the binary to `/usr/local/bin/termlessd`, installs and enables the hardened systemd unit (own user, `ProtectSystem=strict`, a 512 MB memory cap, no capabilities), and starts it with its data in `/var/lib/termless`, listening on `127.0.0.1:8780`. Running it again upgrades in place and restarts the service. ```sh sudo cat /var/lib/termless/setup-token # the one-time setup token, on a first run journalctl -u termlessd -n 50 # the log curl -s http://127.0.0.1:8780/api/v1/health # "version" is null without a key, so the version stays private ``` ### Reaching it The service listens on localhost only. Reach the dashboard over an SSH tunnel (`ssh -N -L 8780:127.0.0.1:8780 you@your-box`, then `http://127.0.0.1:8780`), or put it on your own domain with Caddy, nginx, a Cloudflare Tunnel or Tailscale ([Your own domain](/docs/domains)). Never open the port itself to the internet: API keys and the password would travel unencrypted, and a caller could pick its own address. The ways to reach it from elsewhere (a tunnel, a VPN, a proxy) and what each one costs: [Remote access](/docs/remote-access). ### Behind a reverse proxy Start with `--trust-proxy` (`TERMLESS_TRUST_PROXY=1`) so lockouts and the `Secure` cookie flag use the real client address and scheme. The server then reads the client IP from **one** header, `--proxy-header` / `TERMLESS_PROXY_HEADER` (default `X-Forwarded-For`, its last hop; `X-Real-IP` is never a fallback), and https from `X-Forwarded-Proto`. Two rules, both yours: the proxy must set or overwrite that header on every request it forwards, and nothing but the proxy may reach termlessd's port (keep `--listen 127.0.0.1:8780`). Otherwise a client picks its own address and the lockouts protect nothing. Without `--trust-proxy` every such header is ignored. ```text termless.example.com { reverse_proxy 127.0.0.1:8780 { header_up X-Forwarded-For {remote_host} } } ``` `header_up` replaces whatever the caller sent with the address Caddy sees, and Caddy sets `X-Forwarded-Proto` itself. To use `X-Real-IP` instead, write `header_up X-Real-IP {remote_host}` and start termlessd with `--proxy-header X-Real-IP`. nginx, a Cloudflare Tunnel and the checks that prove it works: [Your own domain](/docs/domains). ### First run With no admin password set, the server prints a one-time setup token to its log and writes it to `/setup-token` (`sudo cat /var/lib/termless/setup-token`). Open the dashboard; it asks for the token and a new password (15 to 200 characters with a lowercase letter, a capital, a digit and a symbol). Do this before you put the server on a domain: until then, whoever holds the token sets the password. Or set `TERMLESS_ADMIN_PASSWORD` in the service's environment before the first start to skip that step. `sudo sh install.sh --password` (or `termlessd passwd`) sets a new password later, from the box, and signs every dashboard session out. ## Settings Each setting is a flag or an environment variable; the flag wins. | Flag | Variable | Default | What | |---|---|---|---| | `--data DIR` | `TERMLESS_DATA` | `~/.local/share/termless` (`/var/lib/termless` under systemd) | The data folder. | | `--listen ADDR` | `TERMLESS_LISTEN` | `127.0.0.1:8780` | Address and port. | | `--trust-proxy` | `TERMLESS_TRUST_PROXY=1` | off | Take the client IP from the proxy header and https from `X-Forwarded-Proto`. Only behind a proxy you control that overwrites that header. | | `--proxy-header H` | `TERMLESS_PROXY_HEADER` | `X-Forwarded-For` | The one header carrying the client IP when `--trust-proxy` is on (last hop). `X-Real-IP` is never a fallback. | | `--trusted-proxies LIST` | `TERMLESS_TRUSTED_PROXIES` | `127.0.0.0/8,::1` | Where the proxy's connection comes from, as CIDRs. Forwarding headers from any other peer are ignored, even with `--trust-proxy`. Set it when the proxy runs on another machine or in a container. | | `--cookie-secure` | `TERMLESS_COOKIE_SECURE=1` | off (on when the request is https) | Always mark the session cookie `Secure`. | | `--web-dir DIR` | `TERMLESS_WEB` | built in | Serve the dashboard and docs from a folder instead of the embedded copy, for editing them. | | | `TERMLESS_LOG` | `info` | Log filter, for example `info,termless=debug`. | | | `TERMLESS_THREADS` | `2` | Async worker threads. Two carry 400,000 ticks a second to 200 clients at under 60 % of a core; raise it only for a measured reason (`docs/architecture.md` in the repository explains why more is slower). | | | `TERMLESS_REQUEST_TIMEOUT` | `30` | Seconds before a request (other than a stream) is given up with `504`. `0` removes the bound. | | | `TERMLESS_BROKER_TIMEOUT_MS` | `20000` | Milliseconds one call to the broker may take before it is `504 timeout` (1,000 to 120,000). A call that is never answered closes the broker link after three times this, so no late reply is taken for another call's. | | | `TERMLESS_TRADE_RESULT_TIMEOUT_MS` | `25000` | Milliseconds a trade waits for its final result once the broker took it (1,000 to 25,000, so the trade answers itself inside the 30 s request bound). Without one it is `504 unconfirmed`; a result that comes later, within 120 s, still settles its Idempotency-Key. | | | `TERMLESS_CATCH_UP_RETRY_S` | `60,120,300,600,900` | Seconds to wait before reading again the deals made during a gap when the broker's history did not answer the last read; the last value repeats. | | | `TERMLESS_TICK_HISTORY` | `1000` | Ticks kept per streaming symbol for `GET /ticks`, at most `100000`; `0` keeps none. An account keeps at most 100,000 over all its symbols together, whatever this says. | | | `TERMLESS_ADMIN_PASSWORD` | | Sets the admin password on the first start only. | | | `TERMLESS_ALLOW_PRIVATE_GATEWAYS=1` | off | Lets an account's gateway resolve to a loopback, link-local, private or carrier-grade NAT address. Refused with `400` otherwise. | | | `TERMLESS_ALLOW_INSECURE_GATEWAYS=1` | off | Lets an account use a plain `ws://` host (the fake broker used in tests); implies the private-gateways setting. Never in production. | | | `TERMLESS_TEST_PANIC_ROUTE=1` | off | Adds `GET /api/v1/test/panic`, which panics, so the tests can check what a panic is answered with (0.7.1). It writes a crash report like any panic. Never in production. | Commands: `termlessd serve` (the default), `termlessd passwd`, `termlessd doctor` (below), `termlessd crash-test --data /tmp/x` (panics on purpose to prove crash reports work on this box; give it a throwaway `--data`, since a report in the live data folder makes `/status` say `degraded` for 24 hours), `termlessd --version`. ## The doctor `termlessd doctor [--data DIR]` checks a box and prints one report with a verdict (`ok`, `warnings` or `problems`; exit code 0, 1 or 2). It works offline, before or beside a running server, and `GET /api/v1/diagnostics/doctor` (admin) runs the same checks against the live server and returns them as JSON. ```sh termlessd doctor --data /var/lib/termless ``` ```text termlessd 0.1.0 doctor: warnings data folder: /var/lib/termless ok data folder /var/lib/termless exists and is writable ok master.key /var/lib/termless/master.key present (owner-only) ok database /var/lib/termless/termless.db (132 KB) integrity ok; rows: accounts 1, keys 2, audit 4821, account_events 310, equity_samples 1440 ok listen serving on http://127.0.0.1:8780 ok gateway pepperstone-12345678: mt5-demo01.pepperstone.com:443 is Pepperstone Group Limited build 6090 (2 servers); connected, build 6090 WARN clock 7 s off the broker's clock fix: enable NTP (timedatectl set-ntp true); candle times and expirations depend on it ok disk 18240 MB free; termless uses 3 MB ``` | Check | What it looks at | |---|---| | `data folder` | Exists, is writable, is owner-only (mode `0700`). | | `master.key`, `setup-token` | Present and owner-only; the token only until setup is done. | | `database` | Opens, passes `PRAGMA integrity_check`, with row counts per table. A running server holds the lock; the doctor says so rather than failing. | | `listen` | The address is serving, free, or cannot be bound. | | `gateway` (one per account) | DNS, then TLS and the web terminal page with its build (or a TCP connect for a plain `ws://` test gateway), plus the session's live state when the server is running. | | `clock` | The box against the first connected broker; warns past 5 s, because candle times and expirations depend on it. | | `disk` | Free space and what termless uses; fails under 200 MB, warns under 1 GB. | Every `warn` and `fail` carries a `fix`: what to do, in one line. Startup errors do the same: a port in use, an unwritable data folder and a damaged `master.key` each name the fix. ## The data folder Created with mode `0700`; every file inside is owner-only. | Path | What | Back up? | |---|---|---| | `termless.db` | SQLite: settings, accounts (passwords sealed with AES-256-GCM), keys (hashes only), sessions, the server directory, the trails (audit, connection events, equity samples, idempotency results), the magic numbers and long comments kept for orders, and each account's newest 1,024 trade events (so their numbering carries on across a restart). | Yes. | | `master.key` | The key that seals account passwords. Losing it makes every stored MT5 password unreadable: you would add the accounts again. | Yes, separately from the database. | | `setup-token` | The one-time token, present until setup is done. | No. | | `termlessd.pid` | Written at start, removed at a clean exit. Present at start = the last run ended uncleanly, and a report is written. | No. | | `termlessd.lock` | Held locked while termlessd runs (0.6.3): a second termlessd started on the same folder is refused before it touches anything, with a message naming the folder and the live pid. | No. | | `logs/termlessd..log` | One log file per day, 14 kept. | As you like. | | `crashes/` | Crash reports, one text file per panic or unclean exit. | For a bug report. | | `captures/undecoded.jsonl` | Frames from the broker the client could not decode (below). | For a bug report. | ## Adding an account In the dashboard, **Accounts > Add account**: pick the server, enter the login and password, choose the symbols to keep streaming. The directory has 57 servers built in, from these brokers: MetaQuotes (demo), Pepperstone, Fusion Markets, IC Markets, Exness (and its Expert Execution servers), Admirals, BlackBull Markets, Deriv, Key to Markets, Fxview, Errante, Axi, Octa, OANDA, FBS (Tradestone), PU Prime, Headway and Taurex; prop firms: FTMO, The5ers, E8 Markets, FundingPips, FundedNext, Maven, Audacity, Funded Trading Plus, AquaFunded, FXIFY, BrightFunded, OANDA Prop Trader and For Traders. Search it by broker, server name or host; spaces, dashes and dots don't matter. For any other broker, **Check a host** with its web terminal's host reads that page and adds its servers ([Find your server](/docs/find-your-server) shows where to find the server name and that address). Or over the API: ```sh curl -s -X POST "$TERMLESS_URL/api/v1/accounts" -b cookies.txt -H "Content-Type: application/json" \ -d '{"label": "Pepperstone demo", "login": 12345678, "password": "your MT5 password", "server": "Pepperstone-Demo", "symbols": ["XAUUSD", "EURUSD"]}' ``` The account connects in the background; poll `GET /api/v1/accounts/{id}` until `status.connected` is true. A refused login shows as `status.login_rejected: true` with `last_error`, and the account then retries only every five minutes so a wrong password cannot get it locked at the broker. Fix it with `PATCH /api/v1/accounts/{id}` and a new `password`. A login refused within a minute of losing a working connection is different: brokers refuse logins for a few seconds while their server restarts (often at weekends), so that one is tried again after 10, 20, 30 and 60 seconds before the five-minute wait. Brokers must have web access turned on for the server (the same thing that lets their web terminal work). The host you connect to decides which trade servers you can reach; `POST /api/v1/servers/check` with a host reports its company, build and servers. Gateways must be on the public internet: a host that resolves to a loopback, link-local, private or carrier-grade NAT address is refused with `400` (by the check and when adding or changing an account) unless the server runs with `TERMLESS_ALLOW_PRIVATE_GATEWAYS=1`. A failed check answers one generic `502`; the reason is in the log and in the audit trail (`kind: "server_check"`). ### Brokers with broken certificates Termless always checks a broker's certificate, the way a browser does, and never turns that check off. Some brokers set theirs up badly; three cases are handled: - **The broker leaves out a certificate in the middle** (IC Markets does). Browsers fetch the missing one from the address written in the broker's certificate; Termless does the same (only from a public address, at most 16 KB, then the whole chain must still lead to a trusted authority), keeps it in memory, and ships the one IC Markets needs in case the fetch is blocked. Nothing to do; the log says once that the broker's chain is incomplete. - **The address is a bare IP** (Exness's servers). Add the name on its certificate as `tls_name` (the directory already knows Exness's: `exwebterm.com`); Termless connects to the IP and checks the certificate for that name. - **The certificate is for another name, or from a private authority** (Alpari, `mt5.deriv.com`, Blueberry Funded). **Check a host** answers `untrusted_certificate` and shows the certificate: its names, who issued it, when it expires, and its key fingerprint (`spki_sha256`). If you are sure it is the broker's real address, pin that key: check again with `fingerprint` set to it (or `POST /api/v1/servers/{server}/trust`). From then on that host is accepted with that key only, and refused with `certificate_changed` if the key ever changes; `DELETE` the trust to undo it. Pins and unpins are in the audit trail. A broker whose web terminal only lets browsers in (a Cloudflare challenge, as FxPro and AvaTrade do) answers `browser_only`: Termless cannot reach it, and pinning does not change that. ## Upgrading Your accounts, keys, settings and history live in `/var/lib/termless`, never in the release folder, so an upgrade only swaps the program. Unpack the new release anywhere and run its installer: ```sh tar xzf termless--linux-x86_64.tar.gz cd termless--linux-x86_64 sudo sh install.sh ``` ```text upgrading: termlessd 0.1.0 (x86_64-unknown-linux-musl) -> termlessd 0.2.0 (x86_64-unknown-linux-musl) data backed up to /var/lib/termless/backups/20261007-174512 running: termlessd 0.2.0 (x86_64-unknown-linux-musl) ``` Step by step, the installer: 1. stops the service, so nothing writes to the data while it is copied; 2. copies `termless.db` and `master.key` to `/var/lib/termless/backups/