TermlessDocs

Guides

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}
FieldMeaning
oktrue 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_textMetaTrader's return code and its words. The full list is on the errors page.
dealThe deal ticket when a fill happened; 0 for a pending order or a modification.
orderThe order ticket. For a market order this is also the new position's ticket on a hedging account.
volume, priceWhat was done, at what price. On a partial fill volume is less than you asked.
bid, askThe market when the broker handled the request, useful to see slippage.
request_idThe broker's id for the request.
warningsPresent 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); 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 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 + typeMetaTrader orderFills when
buy + limitbuy limitask falls to price
sell + limitsell limitbid rises to price
buy + stopbuy stopask rises to price
sell + stopsell stopbid falls to price
buy + stop_limitbuy stop limitask reaches price, then a buy limit at stop_limit is placed
sell + stop_limitsell stop limitbid 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:

CodeMeansDo
10014 Invalid volumeOff the step, below the minimum or above the maximum.Read the spec; round to volume_step.
10015 Invalid priceA pending price on the wrong side of the market, or off the tick size.Compare with the current quote and tick_size.
10016 Invalid stopsSL or TP too close, or on the wrong side.Respect stops_level; check buy/sell direction.
10018 Market is closedOutside the symbol's trade sessions.Wait; check sessions.trade.
10019 Not enough moneyMargin would exceed margin_free.Smaller volume.
10004 Requote, 10020 Prices changedThe market moved more than deviation.Re-read the quote and send again with the new price, once.
10021 No quotesThe symbol has no price yet.Subscribe (any quote request) and wait a moment.
10027 Autotrading disabled by client, 10026 by serverTrading is off for this account.Check summary.trade_allowed; ask the broker.
10030 Unsupported filling modeShould 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 positionStale 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 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).
  • 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). 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).
  • 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.