# 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.