# Trading Positions, pending orders, deal and order history, the calls that change them, and margin, profit and order checks that send nothing (GET /calc, POST /order_check). Every change returns a trade result with the broker's return code: 200 when placed or done, 422 when the broker refused it, with `warnings` when something in the request was changed or cannot be kept. `comment` takes up to 255 characters; the broker keeps 31. `magic` cannot be sent to the broker (the web protocol has no field for it). For a market or pending order, Termless keeps both and puts them back on its positions, orders, deals and stream events. Positions, orders and deals carry `reason` (web, sl, tp, stop_out, ...). On an account the broker reports as real money, the routes that trade answer 403 `real_account` until an admin sets `trade_real: true` on it. ### List open positions `GET /api/v1/accounts/{id}/positions` Scope: read. Open positions with live profit. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `symbol` | string | no | Only this symbol (any case). | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Positions. A JSON array of Position. | Field | Type | Description | |---|---|---| | `ticket` | integer | Position ticket. (required) | | `symbol` | string | Symbol name. (required) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots. (required) | | `price_open` | number | Open price. (required) | | `price_current` | number | Current close price (bid for a buy, ask for a sell). (required) | | `sl` | number | Stop loss price, 0 when none. (required) | | `tp` | number | Take profit price, 0 when none. (required) | | `profit` | number | Floating profit in the deposit currency, live. (required) | | `swap` | number | Swap so far. (required) | | `commission` | number | Commission so far. (required) | | `comment` | string | Comment. The broker keeps 31 characters; for an order sent through Termless with a longer comment, Termless keeps the full text and puts it back here when the broker's is its start. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `identifier` | integer | Position id; the deals of this position carry it as position_id. (required) | | `time` | integer | Open time, unix seconds, trade server clock. (required) | | `time_msc` | integer | Open time, unix milliseconds, trade server clock. (required) | | `time_update` | integer | Last change, unix seconds, trade server clock. (required) | Example: ```json [ { "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 } ] ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions?symbol=XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/positions", headers=auth, params={"symbol": "XAUUSD"}) r.raise_for_status() print(r.json()) ``` ### List pending orders `GET /api/v1/accounts/{id}/orders` Scope: read. Pending orders waiting to trigger (limit, stop, stop limit; a market order is never listed, not even in the instant between its placement and its fill). A stream with `events=orders` pushes this list whenever it changes. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `symbol` | string | no | Only this symbol (any case). | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Orders. A JSON array of Order. | Field | Type | Description | |---|---|---| | `ticket` | integer | Order ticket. (required) | | `symbol` | string | Symbol name. (required) | | `type` | string | Order type. `GET /orders` and `orders` events list pending orders only (limit, stop, stop limit); in a `trade` event a market order is `buy` or `sell` (with `pending: false`). (required; one of buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit, buy, sell, close_by) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots still to fill. (required) | | `volume_initial` | number | Lots when placed. (required) | | `price` | number | Trigger price. (required) | | `stop_limit` | number | Limit price for stop limit orders, 0 otherwise. (required) | | `sl` | number | Stop loss price, 0 when none. (required) | | `tp` | number | Take profit price, 0 when none. (required) | | `expiration` | integer | Expiry, unix seconds, trade server clock. 0 = good till cancelled. (required) | | `comment` | string | Comment. The broker keeps 31 characters; for an order sent through Termless with a longer comment, Termless keeps the full text and puts it back here when the broker's is its start. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). An order that closed a tagged position (its stop, its target) gets the magic but keeps its own comment. (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `time_setup` | integer | When the order was placed, unix seconds, trade server clock. (required) | | `time_setup_msc` | integer | When the order was placed, unix milliseconds, trade server clock. (required) | Example: ```json [ { "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 } ] ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders?symbol=XAUUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/orders", headers=auth, params={"symbol": "XAUUSD"}) r.raise_for_status() print(r.json()) ``` ### Place an order `POST /api/v1/accounts/{id}/orders` Scope: trade. A market order when there is no `type` field, a pending order when `type` is `limit`, `stop` or `stop_limit`. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Request body** *Market order*: Opens a position at market. | Field | Type | Description | |---|---|---| | `symbol` | string | Symbol name. (required) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots, for example 0.10. (required) | | `price` | number | Price sent with the request. Leave it out to fill at market. | | `sl` | number | Stop loss price. | | `tp` | number | Take profit price. | | `deviation` | integer | Largest slippage you accept, in points. (default 20) | | `comment` | string | Comment, up to 255 characters (more is 400). The broker keeps the first 31; for a market or pending order Termless keeps the full text and puts it back on the order, its position, its opening deal and the stream events. Longer than 31 adds a warning to the answer. | | `magic` | integer | Magic number. The web protocol's trade request has no field for it, so the broker stores 0; for a market or pending order Termless keeps it and puts it back on the order, its position, its deals and the stream events (MetaTrader's own apps still show 0). Sending one adds a warning to the answer. | *Pending order*: Places a pending order. | Field | Type | Description | |---|---|---| | `symbol` | string | Symbol name. (required) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots. (required) | | `type` | string | limit, stop or stop_limit. Its presence makes the order pending. (required; one of limit, stop, stop_limit) | | `price` | number | Trigger price. (required) | | `stop_limit` | number | Limit price, required for stop_limit only. | | `sl` | number | Stop loss price. | | `tp` | number | Take profit price. | | `expiration` | integer | Expiry, unix seconds, trade server clock. Omit (or 0) for good till cancelled. The broker keeps whole minutes; one with seconds gets a warning naming the minute. | | `comment` | string | Comment, up to 255 characters (more is 400). The broker keeps the first 31; for a market or pending order Termless keeps the full text and puts it back on the order, its position, its opening deal and the stream events. Longer than 31 adds a warning to the answer. | | `magic` | integer | Magic number. The web protocol's trade request has no field for it, so the broker stores 0; for a market or pending order Termless keeps it and puts it back on the order, its position, its deals and the stream events (MetaTrader's own apps still show 0). Sending one adds a warning to the answer. | Example: ```json { "symbol": "XAUUSD", "side": "buy", "volume": 0.1, "sl": 2380.0, "tp": 2420.0, "comment": "breakout" } ``` **Response 200**: Done. ok is true. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```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 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X POST "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders" \ -H "Authorization: Bearer $TERMLESS_KEY" \ -H "Content-Type: application/json" \ -d '{"symbol": "XAUUSD", "side": "buy", "volume": 0.1, "sl": 2380.0, "tp": 2420.0, "comment": "breakout"}' ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.post(f"{base}/accounts/pepperstone-12345678/orders", headers=auth, json={ "symbol": "XAUUSD", "side": "buy", "volume": 0.1, "sl": 2380.0, "tp": 2420.0, "comment": "breakout" }) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ``` ### List past orders `GET /api/v1/accounts/{id}/orders/history` Scope: read. Orders that left the book (filled, cancelled, expired, rejected), market orders included, oldest first by when they were placed, each with its `state`, `time_done` and the `position_id` it opened or closed. The place to see a pending order that expired or was cancelled, which leaves no deal behind. Defaults to the last 8 days up to tomorrow (trade server time, on when each order was placed); at most 10 years per request. A page is the newest `limit` orders in the window before the `before` cursor, still oldest first; for the next (older) page send `before` = the first order's `time_setup_msc`. `position`, `ticket` and `symbol` narrow it the way history_orders_get(position=, ticket=) does; they combine. With `position` or `ticket` and no `from`, the window reaches 10 years back instead of 8 days, as the official call searches all history. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `from` | integer | no | Start, unix seconds, trade server time, on when the orders were placed. Defaults to 8 days before to (10 years with position or ticket). | | `to` | integer | no | End, unix seconds, trade server time. Defaults to tomorrow (now + 1 day). | | `limit` | integer | no | Page size: the newest N orders in the window (before the cursor), at most 5000. (default 5000; 1 to 5000) | | `before` | integer | no | Cursor: only orders with time_setup_msc below this. Send the first order's time_setup_msc of the page you have. | | `before_ticket` | integer | no | With before: orders in that same millisecond with a smaller ticket come too. Send the first order's ticket, so a page boundary never cuts orders that share a millisecond (0.6.0). | | `position` | integer | no | Only the orders that opened or closed this position (their position_id). | | `ticket` | integer | no | Only the order with this ticket. | | `symbol` | string | no | Only this symbol (exact name, any case). | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Orders, oldest first. A JSON array of HistoryOrder. | Field | Type | Description | |---|---|---| | `ticket` | integer | Order ticket. (required) | | `symbol` | string | Symbol name. (required) | | `type` | string | Order type. Market orders are filed here too: buy, sell or close_by. (required; one of buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit, buy, sell, close_by) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots left unfilled when it left the book (0 for a filled order). (required) | | `volume_initial` | number | Lots when placed. (required) | | `price` | number | Trigger price. (required) | | `stop_limit` | number | Limit price for stop limit orders, 0 otherwise. (required) | | `sl` | number | Stop loss price, 0 when none. (required) | | `tp` | number | Take profit price, 0 when none. (required) | | `expiration` | integer | Expiry, unix seconds, trade server clock. 0 = good till cancelled. (required) | | `comment` | string | Comment. The broker keeps 31 characters; for an order sent through Termless with a longer comment, Termless keeps the full text and puts it back here when the broker's is its start. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). An order that closed a tagged position (its stop, its target) gets the magic but keeps its own comment. (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `time_setup` | integer | When the order was placed, unix seconds, trade server clock. (required) | | `time_setup_msc` | integer | When the order was placed, unix milliseconds, trade server clock. (required) | | `state` | string | The order's MetaTrader state when it left the book: filled, cancelled, expired, rejected or partial (partly filled); started, placed and request are states an order passes through on its way; unknown only for a value MetaTrader does not define. (required; one of started, placed, cancelled, partial, filled, rejected, expired, request, unknown) | | `time_done` | integer | When it left the book, unix seconds, trade server clock. (required) | | `time_done_msc` | integer | When it left the book, unix milliseconds, trade server clock. (required) | | `position_id` | integer | The position it opened or closed; 0 for an order that never filled. (required) | Example: ```json [ { "ticket": 51830007, "symbol": "XAUUSD", "type": "sell_stop", "side": "sell", "volume": 0.1, "volume_initial": 0.1, "price": 2371.5, "stop_limit": 0, "sl": 2380.0, "tp": 2350.0, "expiration": 0, "comment": "breakdown", "magic": 0, "reason": "web", "time_setup": 1790962100, "time_setup_msc": 1790962100544, "state": "cancelled", "time_done": 1790970120, "time_done_msc": 1790970120310, "position_id": 0 }, { "ticket": 51830012, "symbol": "XAUUSD", "type": "buy", "side": "buy", "volume": 0.0, "volume_initial": 0.2, "price": 2385.0, "stop_limit": 0, "sl": 2380.0, "tp": 2420.0, "expiration": 0, "comment": "breakout", "magic": 0, "reason": "web", "time_setup": 1790975498, "time_setup_msc": 1790975497981, "state": "filled", "time_done": 1790975498, "time_done_msc": 1790975498123, "position_id": 51830012 } ] ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/history?from=1790376379" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/orders/history", headers=auth, params={"from": 1790376379}) r.raise_for_status() print(r.json()) ``` ### Get one pending order `GET /api/v1/accounts/{id}/orders/{ticket}` Scope: read. One pending order, like orders_get(ticket=). 404 when no pending order has this ticket (a market order is never one; an order that left the book is in GET /orders/history?ticket=). **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Pending order ticket. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: The order. A Order object. | Field | Type | Description | |---|---|---| | `ticket` | integer | Order ticket. (required) | | `symbol` | string | Symbol name. (required) | | `type` | string | Order type. `GET /orders` and `orders` events list pending orders only (limit, stop, stop limit); in a `trade` event a market order is `buy` or `sell` (with `pending: false`). (required; one of buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit, buy, sell, close_by) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots still to fill. (required) | | `volume_initial` | number | Lots when placed. (required) | | `price` | number | Trigger price. (required) | | `stop_limit` | number | Limit price for stop limit orders, 0 otherwise. (required) | | `sl` | number | Stop loss price, 0 when none. (required) | | `tp` | number | Take profit price, 0 when none. (required) | | `expiration` | integer | Expiry, unix seconds, trade server clock. 0 = good till cancelled. (required) | | `comment` | string | Comment. The broker keeps 31 characters; for an order sent through Termless with a longer comment, Termless keeps the full text and puts it back here when the broker's is its start. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). An order that closed a tagged position (its stop, its target) gets the magic but keeps its own comment. (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `time_setup` | integer | When the order was placed, unix seconds, trade server clock. (required) | | `time_setup_msc` | integer | When the order was placed, unix milliseconds, trade server clock. (required) | Example: ```json { "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 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/orders/51830020", headers=auth) r.raise_for_status() print(r.json()) ``` ### Modify a pending order `PATCH /api/v1/accounts/{id}/orders/{ticket}` Scope: trade. Move the price, stop limit, SL, TP or expiry; omitted fields keep their value. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. 404 when no pending order has this ticket. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Pending order ticket. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Request body** (OrderModify) Send only what changes; omitted fields keep their value. | Field | Type | Description | |---|---|---| | `price` | number | New trigger price. | | `stop_limit` | number | New limit price (stop limit orders). | | `sl` | number | New stop loss, 0 removes it. | | `tp` | number | New take profit, 0 removes it. | | `expiration` | integer | New expiry, unix seconds, trade server clock. 0 = good till cancelled. | Example: ```json { "price": 2360.0, "sl": 2345.0 } ``` **Response 200**: Done. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```json { "ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 0, "order": 51830020, "volume": 0.1, "price": 2360.0, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X PATCH "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \ -H "Authorization: Bearer $TERMLESS_KEY" \ -H "Content-Type: application/json" \ -d '{"price": 2360.0, "sl": 2345.0}' ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.patch(f"{base}/accounts/pepperstone-12345678/orders/51830020", headers=auth, json={ "price": 2360.0, "sl": 2345.0 }) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ``` ### Cancel a pending order `DELETE /api/v1/accounts/{id}/orders/{ticket}` Scope: trade. Removes the order at the broker. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. 404 when no pending order has this ticket. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Pending order ticket. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Done. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```json { "ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 0, "order": 51830020, "volume": 0.1, "price": 0, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.delete(f"{base}/accounts/pepperstone-12345678/orders/51830020", headers=auth) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ``` ### Get one open position `GET /api/v1/accounts/{id}/positions/{ticket}` Scope: read. One open position with live profit, like positions_get(ticket=). 404 when no open position has this ticket (a closed one is in GET /deals?position=). **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Position ticket. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: The position. A Position object. | Field | Type | Description | |---|---|---| | `ticket` | integer | Position ticket. (required) | | `symbol` | string | Symbol name. (required) | | `side` | string | Direction. (required; one of buy, sell) | | `volume` | number | Lots. (required) | | `price_open` | number | Open price. (required) | | `price_current` | number | Current close price (bid for a buy, ask for a sell). (required) | | `sl` | number | Stop loss price, 0 when none. (required) | | `tp` | number | Take profit price, 0 when none. (required) | | `profit` | number | Floating profit in the deposit currency, live. (required) | | `swap` | number | Swap so far. (required) | | `commission` | number | Commission so far. (required) | | `comment` | string | Comment. The broker keeps 31 characters; for an order sent through Termless with a longer comment, Termless keeps the full text and puts it back here when the broker's is its start. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `identifier` | integer | Position id; the deals of this position carry it as position_id. (required) | | `time` | integer | Open time, unix seconds, trade server clock. (required) | | `time_msc` | integer | Open time, unix milliseconds, trade server clock. (required) | | `time_update` | integer | Last change, unix seconds, trade server clock. (required) | Example: ```json { "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 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/positions/51830012", headers=auth) r.raise_for_status() print(r.json()) ``` ### Set SL and TP `PATCH /api/v1/accounts/{id}/positions/{ticket}` Scope: trade. Change or remove a position's stop loss and take profit: an omitted one keeps its value, 0 removes it. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. 404 when no open position has this ticket. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Position ticket. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Request body** (PositionModify) Send sl, tp or both; an omitted one keeps its value, 0 removes it. | Field | Type | Description | |---|---|---| | `sl` | number | New stop loss, 0 removes it. | | `tp` | number | New take profit, 0 removes it. | Example: ```json { "sl": 2386.0, "tp": 2425.0 } ``` **Response 200**: Done. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```json { "ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 0, "order": 51830012, "volume": 0.1, "price": 0, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X PATCH "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012" \ -H "Authorization: Bearer $TERMLESS_KEY" \ -H "Content-Type: application/json" \ -d '{"sl": 2386.0, "tp": 2425.0}' ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.patch(f"{base}/accounts/pepperstone-12345678/positions/51830012", headers=auth, json={ "sl": 2386.0, "tp": 2425.0 }) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ``` ### Close a position `DELETE /api/v1/accounts/{id}/positions/{ticket}` Scope: trade. Closes the whole position at market, or part of it with `?volume=`. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. 404 when no open position has this ticket. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | | `ticket` | integer | yes | Position ticket. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `volume` | number | no | Lots to close. Omit to close all of it; more than the position is 400. | | `deviation` | integer | no | Largest slippage you accept, in points. (default 20; 0 to) | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Done. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```json { "ok": true, "retcode": 10009, "retcode_text": "Request completed", "deal": 81200140, "order": 51830044, "volume": 0.2, "price": 2391.42, "bid": 2391.42, "ask": 2391.6, "comment": "Request completed", "request_id": 31 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012?volume=0.1" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.delete(f"{base}/accounts/pepperstone-12345678/positions/51830012", headers=auth, params={"volume": 0.1}) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ``` ### List deals `GET /api/v1/accounts/{id}/deals` Scope: read. Deal history: fills, closes and balance operations, oldest first. Defaults to the last 8 days up to tomorrow (trade server time); at most 10 years per request. A page is the newest `limit` deals in the window before the `before` cursor, still oldest first; for the next (older) page send `before` = the first deal's `time_msc`. `position`, `ticket` and `symbol` narrow it the way history_deals_get(position=, ticket=) does: `ticket` is the order that made the deals (their `order`, DEAL_ORDER). They combine. With `position` or `ticket` and no `from`, the window reaches 10 years back instead of 8 days, as the official call searches all history. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `from` | integer | no | Start, unix seconds, trade server time. Defaults to 8 days before to (10 years with position or ticket). | | `to` | integer | no | End, unix seconds, trade server time. Defaults to tomorrow (now + 1 day). | | `limit` | integer | no | Page size: the newest N deals in the window (before the cursor), at most 5000. (default 5000; 1 to 5000) | | `before` | integer | no | Cursor: only deals with time_msc below this. Send the first deal's time_msc of the page you have. | | `before_ticket` | integer | no | With before: deals in that same millisecond with a smaller ticket come too. Send the first deal's ticket, so a page boundary never cuts deals that share a millisecond (0.6.0). | | `position` | integer | no | Only the deals of this position (their position_id), like history_deals_get(position=). | | `ticket` | integer | no | Only the deals this order made (their order field), like history_deals_get(ticket=). | | `symbol` | string | no | Only this symbol (exact name, any case). | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Deals. A JSON array of Deal. | Field | Type | Description | |---|---|---| | `ticket` | integer | Deal ticket. (required) | | `order` | integer | Order that made the deal. (required) | | `position_id` | integer | Position the deal belongs to (its identifier). (required) | | `symbol` | string | Symbol name. Empty for balance operations. (required) | | `type` | string | The MetaTrader deal type, lowercase. unknown only for a value MetaTrader does not define. (required; one of buy, sell, balance, credit, charge, correction, bonus, commission, commission_daily, commission_monthly, commission_agent_daily, commission_agent_monthly, interest, buy_canceled, sell_canceled, dividend, dividend_franked, tax, unknown) | | `entry` | string | in opens, out closes, inout reverses, out_by closes by an opposite position. unknown only for a value MetaTrader does not define. (required; one of in, out, inout, out_by, unknown) | | `volume` | number | Lots. (required) | | `price` | number | Deal price. (required) | | `profit` | number | Realised profit in the deposit currency. (required) | | `commission` | number | Commission. (required) | | `swap` | number | Swap. (required) | | `fee` | number | Fee. (required) | | `magic` | integer | Magic number. The web protocol cannot send one, so the broker stores 0; for an order sent through Termless with a magic number, Termless keeps it and puts it back here (the broker's own wins when it is not 0). A closing deal (a close at the stop loss or take profit included) gets the magic of the position it closed. (required) | | `comment` | string | Comment. The opening deal of an order sent through Termless with a comment past 31 characters gets the full text back; a closing deal keeps its own (IC Markets and Pepperstone write [sl 4129.45] or [tp ...] there on a close by stop, but read reason). (required) | | `reason` | string | Why it came about: client (a desktop terminal), mobile, web (anything sent through Termless), expert, sl and tp (closed at the stop loss or take profit), stop_out, and rarer ones. The wire carries the trade server's own numbers (web 17, SL 3, TP 4), not the official DEAL_REASON_* values, so read the word. (required; one of client, mobile, web, expert, sl, tp, stop_out, rollover, vmargin, split, corporate_action, dealer, gateway, signal, settlement, transfer, sync, external_client, external_service, migration, unknown) | | `time` | integer | Unix seconds, trade server clock. (required) | | `time_msc` | integer | Unix milliseconds, trade server clock. (required) | Example: ```json [ { "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 } ] ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/deals?from=1790376379" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/deals", headers=auth, params={"from": 1790376379}) r.raise_for_status() print(r.json()) ``` ### Work out margin and profit `GET /api/v1/accounts/{id}/calc` Scope: read. order_calc_margin and order_calc_profit in one call, in the account currency: the margin `volume` lots need once the trade is open at `price` (default the current ask for a buy, bid for a sell), and with `close` the profit from `price` to `close`. For a pending `type`, `margin` is what the position needs when the order fills (the market rate of its side) and `margin_pending` what the broker holds while it waits (the pending type's own rate: 0 at the brokers seen, so nothing); `margin_pending` is null for a market order. Worked out the way the terminal does it, from the symbol's spec, the account's leverage and the live prices of the symbols that convert currencies. A margin (or `profit`) is null when no symbol converts its currency to the account's. All are rounded to the account currency's digits. No order is sent. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `symbol` | string | yes | Symbol name. | | `side` | string | yes | Direction. (one of buy, sell) | | `volume` | number | yes | Lots, more than 0. | | `type` | string | no | Order type. For a pending type the answer also says what the order holds while it waits (margin_pending). (default "market"; one of market, limit, stop, stop_limit) | | `price` | number | no | Open price. Omit (or 0) for the current ask for a buy, bid for a sell. | | `close` | number | no | Closing price: also work out the profit from price to close. More than 0. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: Margin and profit. A Calc object. | Field | Type | Description | |---|---|---| | `symbol` | string | Symbol name, as the broker spells it. (required) | | `side` | string | Direction. (required; one of buy, sell) | | `type` | string | The MetaTrader order type the side and type make. (required; one of buy, sell, buy_limit, sell_limit, buy_stop, sell_stop, buy_stop_limit, sell_stop_limit) | | `volume` | number | Lots. (required) | | `price` | number | The open price used: the one asked for, else the current ask for a buy and bid for a sell. (required) | | `margin` | number or null | The margin the trade needs once it is open, at price, in the account currency, rounded to its digits (order_calc_margin with the market type of its side): for a pending type, what the position needs when the order fills. null when no symbol converts the margin currency to the account's. (required) | | `margin_pending` | number or null | For a pending type: what the broker holds while the order waits (its type's own rate, margin_rates in the spec; 0 at the brokers seen, so nothing). null for a market order, or when no symbol converts the margin currency. (required) | | `close` | number or null | The closing price asked for; null without one. (required) | | `profit` | number or null | What the order makes from price to close, in the account currency, rounded to its digits (order_calc_profit). null without close, or when no symbol converts the profit currency to the account's. (required) | | `currency` | string | The account currency the numbers are in. (required) | Example: ```json { "symbol": "XAUUSD", "side": "buy", "type": "buy", "volume": 0.1, "price": 2391.6, "margin": 119.58, "margin_pending": null, "close": 2400.0, "profit": 84.0, "currency": "USD" } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/calc?symbol=XAUUSD&side=buy&volume=0.1&price=2391.6&close=2400.0" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/calc", headers=auth, params={"symbol": "XAUUSD", "side": "buy", "volume": 0.1, "price": 2391.6, "close": 2400.0}) r.raise_for_status() print(r.json()) ``` ### Check an order without sending it `POST /api/v1/accounts/{id}/order_check` Scope: read. order_check: takes the same request as order_send and answers what sending it would do, without sending it. A read key is enough; nothing is audited and no Idempotency-Key is needed. For a deal or pending order that opens something (`position` 0) it checks, in order: the volume against the symbol's volume_min, volume_max and volume_step (10014); the symbol's trade mode (10017 disabled, 10044 close only, 10042 a sell on a long_only symbol, 10043 a buy on a short_only one); today's trade sessions by the server's clock (10018; skipped when the broker sent none); a pending order's price against the live quote (10015: a buy limit must sit below the ask, a buy stop above it, a sell limit above the bid, a sell stop below it, each at least `stops_level` points away; a stop limit's limit price below its stop price for a buy and above it for a sell; a pending order without a price); its stop-loss and take-profit (10016: on the losing and winning side of the price they are measured from, at least `stops_level` points away; a deal's from the price that would close it, the bid for a buy and the ask for a sell, a pending order's from its own price, a stop limit's from its limit price); then the margin the order needs at `price` (the current price when 0) against the free margin (10019; a pending order needs only what it holds while it waits, usually nothing). `TRADE_ACTION_SLTP` and `TRADE_ACTION_MODIFY` are checked against the market too (10016, and 10015 for an order's new price) when the position or order is open on the account. The first failing check sets `retcode` and `comment`; 0 and Done when all pass. Other actions, and a deal that closes a position, never get 10019: `request_margin` is 0 and the answer is the account as it is. The freeze level is not checked, and an opening order counts its whole margin even when an opposite position would hedge or net it. Always 200 when the request could be read; 400 when it cannot, or when no symbol converts the margin currency to the account's. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Request body** (OrderSendRequest) The request dict of the official MetaTrader5 Python package's order_send(), with the same field names. Enum fields take the integer constants or their names; numbers may also be sent as strings. | Field | Type | Description | |---|---|---| | `action` | integer or string | TRADE_ACTION_*: 1 deal (market), 5 pending, 6 sltp, 7 modify, 8 remove, 10 close_by. A number or the official name, for example TRADE_ACTION_DEAL. (required) | | `symbol` | string | Symbol name. | | `volume` | number | Lots. | | `type` | integer or string | ORDER_TYPE_*: 0 buy, 1 sell, 2 buy_limit, 3 sell_limit, 4 buy_stop, 5 sell_stop, 6 buy_stop_limit, 7 sell_stop_limit, 8 close_by. A number or the official name, for example ORDER_TYPE_SELL. | | `price` | number | Price. | | `stoplimit` | number | Limit price of a stop limit order. stop_limit also works. | | `sl` | number | Stop loss. | | `tp` | number | Take profit. | | `deviation` | integer | Largest slippage, in points. | | `type_filling` | integer or string | ORDER_FILLING_*: 0 FOK, 1 IOC, 2 return, 3 BOC. A number or the official name, for example ORDER_FILLING_IOC. A mode the symbol does not allow is replaced by one it does (IOC, then FOK, then return), as the web terminal does, and the answer's warnings name the mode sent. A pending order goes out as return unless the symbol is exchange-executed. | | `type_time` | integer or string | ORDER_TIME_*: 0 GTC, 1 day, 2 specified, 3 specified day. A number or the official name, for example ORDER_TIME_GTC. | | `expiration` | integer | Expiry, unix seconds, trade server clock. The broker keeps whole minutes; one with seconds gets a warning. | | `comment` | string | Comment, up to 255 characters (more is 400). The broker keeps the first 31; for a market or pending order Termless keeps the full text and puts it back on the order, its position, its opening deal and the stream events. Longer than 31 adds a warning to the answer. | | `magic` | integer | Magic number. The web protocol's trade request has no field for it, so the broker stores 0; for a market or pending order Termless keeps it and puts it back on the order, its position, its deals and the stream events (MetaTrader's own apps still show 0). Sending one adds a warning to the answer. | | `position` | integer | Position ticket, to close or modify a position. | | `position_by` | integer | Opposite position ticket, for close_by. | | `order` | integer | Order ticket, to modify or remove a pending order. | Example: ```json { "action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY" } ``` **Response 200**: The check. A OrderCheck object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when retcode is 0: sent now, the order would pass these checks. (required) | | `retcode` | integer | 0 when every check passes, else the first that failed: 10014 invalid volume, 10017 trading disabled, 10044 close only, 10042 long only, 10043 short only, 10018 market closed, 10015 invalid price (a pending price on the wrong side of the market), 10016 invalid stops (a stop-loss or take-profit on the wrong side of its price or closer than stops_level), 10019 not enough money. (required; one of 0, 10014, 10017, 10042, 10043, 10044, 10018, 10015, 10016, 10019) | | `comment` | string | The result in words. (required; one of Done, Invalid volume, Trade disabled, Only position closing is allowed, Only long positions are allowed, Only short positions are allowed, Market closed, Invalid price, Invalid stops, No money) | | `balance` | number | Balance now. (required) | | `equity` | number | Equity now, live. (required) | | `profit` | number | Floating profit now, live. (required) | | `margin` | number | Margin in use with the order (includes request_margin). (required) | | `margin_free` | number | equity - margin, with the order. Below 0 is 10019 for an order that opens something. (required) | | `margin_level` | number | equity / margin x 100 with the order, in percent. 0 with no margin. (required) | | `request_margin` | number | The margin the order itself needs: for a pending order what the broker holds while it waits (usually 0). 0 for an action that opens nothing, and when an earlier check failed. (required) | Example: ```json { "ok": true, "retcode": 0, "comment": "Done", "balance": 10412.58, "equity": 10650.69, "profit": 238.11, "margin": 998.51, "margin_free": 9652.18, "margin_level": 1066.66, "request_margin": 119.58 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X POST "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/order_check" \ -H "Authorization: Bearer $TERMLESS_KEY" \ -H "Content-Type: application/json" \ -d '{"action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY"}' ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.post(f"{base}/accounts/pepperstone-12345678/order_check", headers=auth, json={ "action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY" }) r.raise_for_status() print(r.json()) ``` ### Send a raw MetaTrader request `POST /api/v1/accounts/{id}/order_send` Scope: trade. Takes the same request dict as order_send() in the official MetaTrader5 Python package, so existing scripts port over unchanged. Enum fields take the numbers or the official names (`"TRADE_ACTION_DEAL"`, `"ORDER_TYPE_SELL"`, `"ORDER_FILLING_IOC"`). Any other field is 400 naming it, and TRADE_ACTION_SLTP without `position` works only when one position is open on the symbol. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus `error`, code `rejected`). Send an `Idempotency-Key` header and a retry with the same key and body replays the stored answer (with `Idempotent-Replayed: true`) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 `busy` or `stopping` was never sent and is not kept, so its retry is sent; a 504 `unconfirmed` whose result came late replays that result). On an account the broker reports as real money this answers 403 `real_account` until an admin sets `trade_real: true`. Prefer the routes above for new code. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Idempotency-Key` | string | no | A key of your choosing (1 to 200 printable ASCII characters) that makes this request safe to retry. The first request with a key is executed and its whole response kept for 24 hours; a repeat with the same key and body gets that response back with `Idempotent-Replayed: true` and never reaches the broker. The same key with a different body is 409. Two requests in flight with one key: the second waits for the first's result and replays it. An error result (422, 502, 503, 504) is replayed too, so a blind retry cannot double a trade; check positions and orders, then use a new key. The exceptions are 503 `busy` and 503 `stopping`: that request was never sent, so its key is let go and a retry with the same key is sent. A 504 `unconfirmed` trade whose final result comes later (within 120 s, on the same broker link) has its stored answer replaced by that result. The key is reserved in the database before the broker is asked, so a first request that never got an answer (cut by the 30 s bound, the server killed or restarted) is not forgotten: its retry is 409 (check positions and orders, then use a new key), never a second blind send; if the reservation cannot be written the request is 500 and not sent. Scoped to the caller, the method and the path. | | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Request body** (OrderSendRequest) The request dict of the official MetaTrader5 Python package's order_send(), with the same field names. Enum fields take the integer constants or their names; numbers may also be sent as strings. | Field | Type | Description | |---|---|---| | `action` | integer or string | TRADE_ACTION_*: 1 deal (market), 5 pending, 6 sltp, 7 modify, 8 remove, 10 close_by. A number or the official name, for example TRADE_ACTION_DEAL. (required) | | `symbol` | string | Symbol name. | | `volume` | number | Lots. | | `type` | integer or string | ORDER_TYPE_*: 0 buy, 1 sell, 2 buy_limit, 3 sell_limit, 4 buy_stop, 5 sell_stop, 6 buy_stop_limit, 7 sell_stop_limit, 8 close_by. A number or the official name, for example ORDER_TYPE_SELL. | | `price` | number | Price. | | `stoplimit` | number | Limit price of a stop limit order. stop_limit also works. | | `sl` | number | Stop loss. | | `tp` | number | Take profit. | | `deviation` | integer | Largest slippage, in points. | | `type_filling` | integer or string | ORDER_FILLING_*: 0 FOK, 1 IOC, 2 return, 3 BOC. A number or the official name, for example ORDER_FILLING_IOC. A mode the symbol does not allow is replaced by one it does (IOC, then FOK, then return), as the web terminal does, and the answer's warnings name the mode sent. A pending order goes out as return unless the symbol is exchange-executed. | | `type_time` | integer or string | ORDER_TIME_*: 0 GTC, 1 day, 2 specified, 3 specified day. A number or the official name, for example ORDER_TIME_GTC. | | `expiration` | integer | Expiry, unix seconds, trade server clock. The broker keeps whole minutes; one with seconds gets a warning. | | `comment` | string | Comment, up to 255 characters (more is 400). The broker keeps the first 31; for a market or pending order Termless keeps the full text and puts it back on the order, its position, its opening deal and the stream events. Longer than 31 adds a warning to the answer. | | `magic` | integer | Magic number. The web protocol's trade request has no field for it, so the broker stores 0; for a market or pending order Termless keeps it and puts it back on the order, its position, its deals and the stream events (MetaTrader's own apps still show 0). Sending one adds a warning to the answer. | | `position` | integer | Position ticket, to close or modify a position. | | `position_by` | integer | Opposite position ticket, for close_by. | | `order` | integer | Order ticket, to modify or remove a pending order. | Example: ```json { "action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY", "price": 2391.6, "sl": 2380.0, "tp": 2420.0, "deviation": 20, "type_filling": "ORDER_FILLING_IOC", "type_time": 0, "comment": "from mt5 script", "magic": 7 } ``` **Response 200**: Done. A TradeResult object. | Field | Type | Description | |---|---|---| | `ok` | boolean | True when the broker placed (10008), did (10009) or partly did (10010) the request. Test this, not one code: brokers answer a placed pending order with 10008 or 10009. (required) | | `retcode` | integer | MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest. (required) | | `retcode_text` | string | The return code in words. (required) | | `deal` | integer | Deal ticket, 0 when no deal was made. (required) | | `order` | integer | Order ticket. (required) | | `volume` | number | Lots done. (required) | | `price` | number | Price done. (required) | | `bid` | number | Bid when the broker handled the request. (required) | | `ask` | number | Ask when the broker handled the request. (required) | | `comment` | string | Broker's comment. (required) | | `request_id` | integer | The broker's id for the request. (required) | | `warnings` | array of string | Present only when something in the request was changed or cannot be kept, on a 200 and a 422 alike: a comment over 31 characters ("comment is N characters; the broker keeps the first 31, termlessd keeps the full text for this order", without the second half for an order that neither opens nor closes anything); a magic number on a market or pending order ("magic is not sent to the broker (MetaTrader's web protocol has no field for it); termlessd keeps it for this order"); a type_filling the symbol does not allow, when order_send named one ("ORDER_FILLING_FOK is not allowed for EURUSD; sent ORDER_FILLING_IOC"); an expiry with seconds ("the broker keeps expiry times to the whole minute: "). | Example: ```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 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden, real_account`: forbidden: the key lacks the trade scope, or may not use this account, or a cookie request came from another site. real_account: the broker reports this account as real money (or preliminary) and trading on it is off until an admin sets `trade_real: true` on the account; nothing was sent. Demo and contest accounts trade either way. - `404 not_found`: No such account, symbol, ticket, key or route. - `409 conflict`: The thing already exists or the state does not allow it. On a trade route with an Idempotency-Key: the key was already used with a different body or query string, or the first request with it did not finish (cut off, or the server restarted; check positions and orders, then use a new key), or it is still running after 30 s. - `422 rejected`: The broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: 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 (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -s -X POST "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/order_send" \ -H "Authorization: Bearer $TERMLESS_KEY" \ -H "Content-Type: application/json" \ -d '{"action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY", "price": 2391.6, "sl": 2380.0, "tp": 2420.0, "deviation": 20, "type_filling": "ORDER_FILLING_IOC", "type_time": 0, "comment": "from mt5 script", "magic": 7}' ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.post(f"{base}/accounts/pepperstone-12345678/order_send", headers=auth, json={ "action": "TRADE_ACTION_DEAL", "symbol": "XAUUSD", "volume": 0.1, "type": "ORDER_TYPE_BUY", "price": 2391.6, "sl": 2380.0, "tp": 2420.0, "deviation": 20, "type_filling": "ORDER_FILLING_IOC", "type_time": 0, "comment": "from mt5 script", "magic": 7 }) result = r.json() if r.status_code == 422: print("refused:", result["retcode"], result["retcode_text"]) else: r.raise_for_status() print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"]) ```