TermlessDocs

Reference

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

Open positions with live profit.

Scope read

Path parameters

  • id string required

    Account id.

Query parameters

  • symbol string

    Only this symbol (any case).

Headers

  • X-Request-Id string

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

  • ticket integer required

    Position ticket.

  • symbol string required

    Symbol name.

  • side string required

    Direction.

    buysell
  • volume number required

    Lots.

  • price_open number required

    Open price.

  • price_current number required

    Current close price (bid for a buy, ask for a sell).

  • sl number required

    Stop loss price, 0 when none.

  • tp number required

    Take profit price, 0 when none.

  • profit number required

    Floating profit in the deposit currency, live.

  • swap number required

    Swap so far.

  • commission number required

    Commission so far.

  • comment string required

    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.

  • magic integer required

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

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • identifier integer required

    Position id; the deals of this position carry it as position_id.

  • time integer required

    Open time, unix seconds, trade server clock.

  • time_msc integer required

    Open time, unix milliseconds, trade server clock.

  • time_update integer required

    Last change, unix seconds, trade server clock.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions?symbol=XAUUSD" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/positions?symbol=XAUUSD", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/positions?symbol=XAUUSD`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
[
  {
    "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
  }
]

List pending orders

GET/api/v1/accounts/{id}/orders

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.

Scope read

Path parameters

  • id string required

    Account id.

Query parameters

  • symbol string

    Only this symbol (any case).

Headers

  • X-Request-Id string

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

  • ticket integer required

    Order ticket.

  • symbol string required

    Symbol name.

  • type string required

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

    buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_by
  • side string required

    Direction.

    buysell
  • volume number required

    Lots still to fill.

  • volume_initial number required

    Lots when placed.

  • price number required

    Trigger price.

  • stop_limit number required

    Limit price for stop limit orders, 0 otherwise.

  • sl number required

    Stop loss price, 0 when none.

  • tp number required

    Take profit price, 0 when none.

  • expiration integer required

    Expiry, unix seconds, trade server clock. 0 = good till cancelled.

  • comment string required

    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.

  • magic integer required

    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.

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • time_setup integer required

    When the order was placed, unix seconds, trade server clock.

  • time_setup_msc integer required

    When the order was placed, unix milliseconds, trade server clock.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders?symbol=XAUUSD" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders?symbol=XAUUSD", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders?symbol=XAUUSD`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
[
  {
    "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
  }
]

Place an order

POST/api/v1/accounts/{id}/orders

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.

Scope trade

Path parameters

  • id string required

    Account id.

Headers

  • Idempotency-Key string

    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

    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 one of

Market order Opens a position at market.
  • symbol string required

    Symbol name.

  • side string required

    Direction.

    buysell
  • volume number required

    Lots, for example 0.10.

  • 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 default 20

    Largest slippage you accept, in points.

  • 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.
  • symbol string required

    Symbol name.

  • side string required

    Direction.

    buysell
  • volume number required

    Lots.

  • type string required

    limit, stop or stop_limit. Its presence makes the order pending.

    limitstopstop_limit
  • price number required

    Trigger price.

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

Response 200 Done. ok is true.

A TradeResult object.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
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
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

payload = {
    "symbol": "XAUUSD",
    "side": "buy",
    "volume": 0.1,
    "sl": 2380.0,
    "tp": 2420.0,
    "comment": "breakout"
}

headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders", data=json.dumps(payload).encode(), headers=headers, method="POST")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    "symbol": "XAUUSD",
    "side": "buy",
    "volume": 0.1,
    "sl": 2380.0,
    "tp": 2420.0,
    "comment": "breakout"
  })
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}

List past orders

GET/api/v1/accounts/{id}/orders/history

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.

Scope read

Path parameters

  • id string required

    Account id.

Query parameters

  • from integer

    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

    End, unix seconds, trade server time. Defaults to tomorrow (now + 1 day).

  • limit integer default 5000 min 1, max 5000

    Page size: the newest N orders in the window (before the cursor), at most 5000.

  • before integer

    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

    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

    Only the orders that opened or closed this position (their position_id).

  • ticket integer

    Only the order with this ticket.

  • symbol string

    Only this symbol (exact name, any case).

Headers

  • X-Request-Id string

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

  • ticket integer required

    Order ticket.

  • symbol string required

    Symbol name.

  • type string required

    Order type. Market orders are filed here too: buy, sell or close_by.

    buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_by
  • side string required

    Direction.

    buysell
  • volume number required

    Lots left unfilled when it left the book (0 for a filled order).

  • volume_initial number required

    Lots when placed.

  • price number required

    Trigger price.

  • stop_limit number required

    Limit price for stop limit orders, 0 otherwise.

  • sl number required

    Stop loss price, 0 when none.

  • tp number required

    Take profit price, 0 when none.

  • expiration integer required

    Expiry, unix seconds, trade server clock. 0 = good till cancelled.

  • comment string required

    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.

  • magic integer required

    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.

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • time_setup integer required

    When the order was placed, unix seconds, trade server clock.

  • time_setup_msc integer required

    When the order was placed, unix milliseconds, trade server clock.

  • state string required

    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.

    startedplacedcancelledpartialfilledrejectedexpiredrequestunknown
  • time_done integer required

    When it left the book, unix seconds, trade server clock.

  • time_done_msc integer required

    When it left the book, unix milliseconds, trade server clock.

  • position_id integer required

    The position it opened or closed; 0 for an order that never filled.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/history?from=1790376379" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders/history?from=1790376379", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders/history?from=1790376379`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
[
  {
    "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
  }
]

Get one pending order

GET/api/v1/accounts/{id}/orders/{ticket}

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=).

Scope read

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Pending order ticket.

Headers

  • X-Request-Id string

    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.

  • ticket integer required

    Order ticket.

  • symbol string required

    Symbol name.

  • type string required

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

    buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_by
  • side string required

    Direction.

    buysell
  • volume number required

    Lots still to fill.

  • volume_initial number required

    Lots when placed.

  • price number required

    Trigger price.

  • stop_limit number required

    Limit price for stop limit orders, 0 otherwise.

  • sl number required

    Stop loss price, 0 when none.

  • tp number required

    Take profit price, 0 when none.

  • expiration integer required

    Expiry, unix seconds, trade server clock. 0 = good till cancelled.

  • comment string required

    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.

  • magic integer required

    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.

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • time_setup integer required

    When the order was placed, unix seconds, trade server clock.

  • time_setup_msc integer required

    When the order was placed, unix milliseconds, trade server clock.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders/51830020", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders/51830020`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
{
  "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
}

Modify a pending order

PATCH/api/v1/accounts/{id}/orders/{ticket}

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.

Scope trade

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Pending order ticket.

Headers

  • Idempotency-Key string

    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

    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.

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

Response 200 Done.

A TradeResult object.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
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
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

payload = {
    "price": 2360.0,
    "sl": 2345.0
}

headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders/51830020", data=json.dumps(payload).encode(), headers=headers, method="PATCH")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders/51830020`, {
  method: "PATCH",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    "price": 2360.0,
    "sl": 2345.0
  })
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}

Cancel a pending order

DELETE/api/v1/accounts/{id}/orders/{ticket}

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.

Scope trade

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Pending order ticket.

Headers

  • Idempotency-Key string

    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

    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.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/orders/51830020", data=None, headers=headers, method="DELETE")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/orders/51830020`, {
  method: "DELETE",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}

Get one open position

GET/api/v1/accounts/{id}/positions/{ticket}

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=).

Scope read

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Position ticket.

Headers

  • X-Request-Id string

    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.

  • ticket integer required

    Position ticket.

  • symbol string required

    Symbol name.

  • side string required

    Direction.

    buysell
  • volume number required

    Lots.

  • price_open number required

    Open price.

  • price_current number required

    Current close price (bid for a buy, ask for a sell).

  • sl number required

    Stop loss price, 0 when none.

  • tp number required

    Take profit price, 0 when none.

  • profit number required

    Floating profit in the deposit currency, live.

  • swap number required

    Swap so far.

  • commission number required

    Commission so far.

  • comment string required

    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.

  • magic integer required

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

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • identifier integer required

    Position id; the deals of this position carry it as position_id.

  • time integer required

    Open time, unix seconds, trade server clock.

  • time_msc integer required

    Open time, unix milliseconds, trade server clock.

  • time_update integer required

    Last change, unix seconds, trade server clock.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/positions/51830012", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/positions/51830012`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
{
  "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
}

Set SL and TP

PATCH/api/v1/accounts/{id}/positions/{ticket}

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.

Scope trade

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Position ticket.

Headers

  • Idempotency-Key string

    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

    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.

  • sl number

    New stop loss, 0 removes it.

  • tp number

    New take profit, 0 removes it.

Response 200 Done.

A TradeResult object.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
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
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

payload = {
    "sl": 2386.0,
    "tp": 2425.0
}

headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/positions/51830012", data=json.dumps(payload).encode(), headers=headers, method="PATCH")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/positions/51830012`, {
  method: "PATCH",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    "sl": 2386.0,
    "tp": 2425.0
  })
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}

Close a position

DELETE/api/v1/accounts/{id}/positions/{ticket}

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.

Scope trade

Path parameters

  • id string required

    Account id.

  • ticket integer required

    Position ticket.

Query parameters

  • volume number

    Lots to close. Omit to close all of it; more than the position is 400.

  • deviation integer default 20 min 0

    Largest slippage you accept, in points.

Headers

  • Idempotency-Key string

    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

    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.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
curl -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012?volume=0.1" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/positions/51830012?volume=0.1", data=None, headers=headers, method="DELETE")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/positions/51830012?volume=0.1`, {
  method: "DELETE",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}

List deals

GET/api/v1/accounts/{id}/deals

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.

Scope read

Path parameters

  • id string required

    Account id.

Query parameters

  • from integer

    Start, unix seconds, trade server time. Defaults to 8 days before to (10 years with position or ticket).

  • to integer

    End, unix seconds, trade server time. Defaults to tomorrow (now + 1 day).

  • limit integer default 5000 min 1, max 5000

    Page size: the newest N deals in the window (before the cursor), at most 5000.

  • before integer

    Cursor: only deals with time_msc below this. Send the first deal's time_msc of the page you have.

  • before_ticket integer

    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

    Only the deals of this position (their position_id), like history_deals_get(position=).

  • ticket integer

    Only the deals this order made (their order field), like history_deals_get(ticket=).

  • symbol string

    Only this symbol (exact name, any case).

Headers

  • X-Request-Id string

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

  • ticket integer required

    Deal ticket.

  • order integer required

    Order that made the deal.

  • position_id integer required

    Position the deal belongs to (its identifier).

  • symbol string required

    Symbol name. Empty for balance operations.

  • type string required

    The MetaTrader deal type, lowercase. unknown only for a value MetaTrader does not define.

    buysellbalancecreditchargecorrectionbonuscommissioncommission_dailycommission_monthlycommission_agent_dailycommission_agent_monthlyinterestbuy_canceledsell_canceleddividenddividend_frankedtaxunknown
  • entry string required

    in opens, out closes, inout reverses, out_by closes by an opposite position. unknown only for a value MetaTrader does not define.

    inoutinoutout_byunknown
  • volume number required

    Lots.

  • price number required

    Deal price.

  • profit number required

    Realised profit in the deposit currency.

  • commission number required

    Commission.

  • swap number required

    Swap.

  • fee number required

    Fee.

  • magic integer required

    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.

  • comment string required

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

  • reason string required

    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.

    clientmobilewebexpertsltpstop_outrollovervmarginsplitcorporate_actiondealergatewaysignalsettlementtransfersyncexternal_clientexternal_servicemigrationunknown
  • time integer required

    Unix seconds, trade server clock.

  • time_msc integer required

    Unix milliseconds, trade server clock.

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
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/deals?from=1790376379" \
  -H "Authorization: Bearer $TERMLESS_KEY"
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/deals?from=1790376379", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/deals?from=1790376379`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
[
  {
    "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
  }
]

Work out margin and profit

GET/api/v1/accounts/{id}/calc

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.

Scope read

Path parameters

  • id string required

    Account id.

Query parameters

  • symbol string required

    Symbol name.

  • side string required

    Direction.

    buysell
  • volume number required

    Lots, more than 0.

  • type string default "market"

    Order type. For a pending type the answer also says what the order holds while it waits (margin_pending).

    marketlimitstopstop_limit
  • price number

    Open price. Omit (or 0) for the current ask for a buy, bid for a sell.

  • close number

    Closing price: also work out the profit from price to close. More than 0.

Headers

  • X-Request-Id string

    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.

  • symbol string required

    Symbol name, as the broker spells it.

  • side string required

    Direction.

    buysell
  • type string required

    The MetaTrader order type the side and type make.

    buysellbuy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limit
  • volume number required

    Lots.

  • price number required

    The open price used: the one asked for, else the current ask for a buy and bid for a sell.

  • margin number or null required

    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.

  • margin_pending number or null required

    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.

  • close number or null required

    The closing price asked for; null without one.

  • profit number or null required

    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.

  • currency string required

    The account currency the numbers are in.

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
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
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/calc?symbol=XAUUSD&side=buy&volume=0.1&price=2391.6&close=2400.0", data=None, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/calc?symbol=XAUUSD&side=buy&volume=0.1&price=2391.6&close=2400.0`, {
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
{
  "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"
}

Check an order without sending it

POST/api/v1/accounts/{id}/order_check

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.

Scope read

Path parameters

  • id string required

    Account id.

Headers

  • X-Request-Id string

    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.

  • action integer or string required

    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.

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

Response 200 The check.

A OrderCheck object.

  • ok boolean required

    True when retcode is 0: sent now, the order would pass these checks.

  • retcode integer required

    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.

    0100141001710042100431004410018100151001610019
  • comment string required

    The result in words.

    DoneInvalid volumeTrade disabledOnly position closing is allowedOnly long positions are allowedOnly short positions are allowedMarket closedInvalid priceInvalid stopsNo money
  • balance number required

    Balance now.

  • equity number required

    Equity now, live.

  • profit number required

    Floating profit now, live.

  • margin number required

    Margin in use with the order (includes request_margin).

  • margin_free number required

    equity - margin, with the order. Below 0 is 10019 for an order that opens something.

  • margin_level number required

    equity / margin x 100 with the order, in percent. 0 with no margin.

  • request_margin number required

    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.

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
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
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())
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

payload = {
    "action": "TRADE_ACTION_DEAL",
    "symbol": "XAUUSD",
    "volume": 0.1,
    "type": "ORDER_TYPE_BUY"
}

headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/order_check", data=json.dumps(payload).encode(), headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=35) as r:
    print(json.load(r))
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/order_check`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    "action": "TRADE_ACTION_DEAL",
    "symbol": "XAUUSD",
    "volume": 0.1,
    "type": "ORDER_TYPE_BUY"
  })
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());
Response 200
{
  "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
}

Send a raw MetaTrader request

POST/api/v1/accounts/{id}/order_send

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.

Scope trade

Path parameters

  • id string required

    Account id.

Headers

  • Idempotency-Key string

    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

    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.

  • action integer or string required

    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.

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

Response 200 Done.

A TradeResult object.

  • ok boolean required

    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.

  • retcode integer required

    MetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.

  • retcode_text string required

    The return code in words.

  • deal integer required

    Deal ticket, 0 when no deal was made.

  • order integer required

    Order ticket.

  • volume number required

    Lots done.

  • price number required

    Price done.

  • bid number required

    Bid when the broker handled the request.

  • ask number required

    Ask when the broker handled the request.

  • comment string required

    Broker's comment.

  • request_id integer required

    The broker's id for the request.

  • 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: <unix s>").

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
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
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"])
Python, stdlib
import json
import os
import urllib.error
import urllib.request

base = os.environ["TERMLESS_URL"] + "/api/v1"
headers = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}

payload = {
    "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
}

headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/accounts/pepperstone-12345678/order_send", data=json.dumps(payload).encode(), headers=headers, method="POST")
try:
    with urllib.request.urlopen(req, timeout=35) as r:
        result = json.load(r)
        print("done:", result["retcode_text"], "deal", result["deal"], "at", result["price"])
except urllib.error.HTTPError as e:
    body = json.load(e)
    if e.code == 422:
        print("refused:", body["retcode"], body["retcode_text"])
    else:
        raise SystemExit(f"{e.code} {body['error']['code']}: {body['error']['message']}")
JavaScript
const base = `${process.env.TERMLESS_URL}/api/v1`;

const res = await fetch(`${base}/accounts/pepperstone-12345678/order_send`, {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    "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
  })
});
const result = await res.json();
if (res.status === 422) console.log("refused:", result.retcode, result.retcode_text);
else if (!res.ok) throw new Error(result.error.message);
else console.log("done:", result.retcode_text, "deal", result.deal, "at", result.price);
Response 200
{
  "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
}
Response 422 · the broker refused it
{
  "ok": false,
  "retcode": 10014,
  "retcode_text": "Invalid volume",
  "deal": 0,
  "order": 0,
  "volume": 0,
  "price": 0,
  "bid": 2391.42,
  "ask": 2391.6,
  "comment": "Invalid volume",
  "request_id": 32,
  "error": {
    "code": "rejected",
    "message": "the broker refused the request: Invalid volume (10014)"
  }
}