Guides
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):
{"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.
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 row it caused, so your log, the server log and the trail line up on one id. Log it with every error you report.
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-0042Every 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). |
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 has the full rules and a code sample.
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 rA 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.
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.