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
/api/v1/accounts/{id}/positionsOpen positions with live profit.
Path parameters
idstring requiredAccount id.
Query parameters
symbolstringOnly this symbol (any case).
Headers
X-Request-IdstringYour 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.
ticketinteger requiredPosition ticket.
symbolstring requiredSymbol name.
sidestring requiredDirection.
buysellvolumenumber requiredLots.
price_opennumber requiredOpen price.
price_currentnumber requiredCurrent close price (bid for a buy, ask for a sell).
slnumber requiredStop loss price, 0 when none.
tpnumber requiredTake profit price, 0 when none.
profitnumber requiredFloating profit in the deposit currency, live.
swapnumber requiredSwap so far.
commissionnumber requiredCommission so far.
commentstring requiredComment. 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.
magicinteger requiredMagic 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).
reasonstring requiredWhy 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_servicemigrationunknownidentifierinteger requiredPosition id; the deals of this position carry it as position_id.
timeinteger requiredOpen time, unix seconds, trade server clock.
time_mscinteger requiredOpen time, unix milliseconds, trade server clock.
time_updateinteger requiredLast change, unix seconds, trade server clock.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions?symbol=XAUUSD" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());[
{
"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
/api/v1/accounts/{id}/ordersPending orders waiting to trigger (limit, stop, stop limit; a market order is never listed, not even in the instant between its placement and its fill). A stream with events=orders pushes this list whenever it changes.
Path parameters
idstring requiredAccount id.
Query parameters
symbolstringOnly this symbol (any case).
Headers
X-Request-IdstringYour 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.
ticketinteger requiredOrder ticket.
symbolstring requiredSymbol name.
typestring requiredOrder type.
GET /ordersandordersevents list pending orders only (limit, stop, stop limit); in atradeevent a market order isbuyorsell(withpending: false).buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_bysidestring requiredDirection.
buysellvolumenumber requiredLots still to fill.
volume_initialnumber requiredLots when placed.
pricenumber requiredTrigger price.
stop_limitnumber requiredLimit price for stop limit orders, 0 otherwise.
slnumber requiredStop loss price, 0 when none.
tpnumber requiredTake profit price, 0 when none.
expirationinteger requiredExpiry, unix seconds, trade server clock. 0 = good till cancelled.
commentstring requiredComment. 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.
magicinteger requiredMagic 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.
reasonstring requiredWhy 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_servicemigrationunknowntime_setupinteger requiredWhen the order was placed, unix seconds, trade server clock.
time_setup_mscinteger requiredWhen the order was placed, unix milliseconds, trade server clock.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders?symbol=XAUUSD" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());[
{
"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
/api/v1/accounts/{id}/ordersA market order when there is no type field, a pending order when type is limit, stop or stop_limit. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus error, code rejected). Send an Idempotency-Key header and a retry with the same key and body replays the stored answer (with Idempotent-Replayed: true) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 busy or stopping was never sent and is not kept, so its retry is sent; a 504 unconfirmed whose result came late replays that result). On an account the broker reports as real money this answers 403 real_account until an admin sets trade_real: true.
Path parameters
idstring requiredAccount id.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
symbolstring requiredSymbol name.
sidestring requiredDirection.
buysellvolumenumber requiredLots, for example 0.10.
pricenumberPrice sent with the request. Leave it out to fill at market.
slnumberStop loss price.
tpnumberTake profit price.
deviationinteger default20Largest slippage you accept, in points.
commentstringComment, 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.
magicintegerMagic 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.
symbolstring requiredSymbol name.
sidestring requiredDirection.
buysellvolumenumber requiredLots.
typestring requiredlimit, stop or stop_limit. Its presence makes the order pending.
limitstopstop_limitpricenumber requiredTrigger price.
stop_limitnumberLimit price, required for stop_limit only.
slnumberStop loss price.
tpnumberTake profit price.
expirationintegerExpiry, 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.
commentstringComment, 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.
magicintegerMagic 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.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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"}'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"])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']}")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);{
"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
}{
"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
/api/v1/accounts/{id}/orders/historyOrders that left the book (filled, cancelled, expired, rejected), market orders included, oldest first by when they were placed, each with its state, time_done and the position_id it opened or closed. The place to see a pending order that expired or was cancelled, which leaves no deal behind. Defaults to the last 8 days up to tomorrow (trade server time, on when each order was placed); at most 10 years per request. A page is the newest limit orders in the window before the before cursor, still oldest first; for the next (older) page send before = the first order's time_setup_msc. position, ticket and symbol narrow it the way history_orders_get(position=, ticket=) does; they combine. With position or ticket and no from, the window reaches 10 years back instead of 8 days, as the official call searches all history.
Path parameters
idstring requiredAccount id.
Query parameters
fromintegerStart, unix seconds, trade server time, on when the orders were placed. Defaults to 8 days before to (10 years with position or ticket).
tointegerEnd, unix seconds, trade server time. Defaults to tomorrow (now + 1 day).
limitinteger default5000min 1, max 5000Page size: the newest N orders in the window (before the cursor), at most 5000.
beforeintegerCursor: only orders with time_setup_msc below this. Send the first order's time_setup_msc of the page you have.
before_ticketintegerWith 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).
positionintegerOnly the orders that opened or closed this position (their position_id).
ticketintegerOnly the order with this ticket.
symbolstringOnly this symbol (exact name, any case).
Headers
X-Request-IdstringYour 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.
ticketinteger requiredOrder ticket.
symbolstring requiredSymbol name.
typestring requiredOrder type. Market orders are filed here too: buy, sell or close_by.
buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_bysidestring requiredDirection.
buysellvolumenumber requiredLots left unfilled when it left the book (0 for a filled order).
volume_initialnumber requiredLots when placed.
pricenumber requiredTrigger price.
stop_limitnumber requiredLimit price for stop limit orders, 0 otherwise.
slnumber requiredStop loss price, 0 when none.
tpnumber requiredTake profit price, 0 when none.
expirationinteger requiredExpiry, unix seconds, trade server clock. 0 = good till cancelled.
commentstring requiredComment. 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.
magicinteger requiredMagic 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.
reasonstring requiredWhy 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_servicemigrationunknowntime_setupinteger requiredWhen the order was placed, unix seconds, trade server clock.
time_setup_mscinteger requiredWhen the order was placed, unix milliseconds, trade server clock.
statestring requiredThe 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.
startedplacedcancelledpartialfilledrejectedexpiredrequestunknowntime_doneinteger requiredWhen it left the book, unix seconds, trade server clock.
time_done_mscinteger requiredWhen it left the book, unix milliseconds, trade server clock.
position_idinteger requiredThe position it opened or closed; 0 for an order that never filled.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/history?from=1790376379" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());[
{
"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
/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=).
Path parameters
idstring requiredAccount id.
ticketinteger requiredPending order ticket.
Headers
X-Request-IdstringYour 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.
ticketinteger requiredOrder ticket.
symbolstring requiredSymbol name.
typestring requiredOrder type.
GET /ordersandordersevents list pending orders only (limit, stop, stop limit); in atradeevent a market order isbuyorsell(withpending: false).buy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitbuysellclose_bysidestring requiredDirection.
buysellvolumenumber requiredLots still to fill.
volume_initialnumber requiredLots when placed.
pricenumber requiredTrigger price.
stop_limitnumber requiredLimit price for stop limit orders, 0 otherwise.
slnumber requiredStop loss price, 0 when none.
tpnumber requiredTake profit price, 0 when none.
expirationinteger requiredExpiry, unix seconds, trade server clock. 0 = good till cancelled.
commentstring requiredComment. 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.
magicinteger requiredMagic 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.
reasonstring requiredWhy 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_servicemigrationunknowntime_setupinteger requiredWhen the order was placed, unix seconds, trade server clock.
time_setup_mscinteger requiredWhen the order was placed, unix milliseconds, trade server clock.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());{
"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
/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.
Path parameters
idstring requiredAccount id.
ticketinteger requiredPending order ticket.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
pricenumberNew trigger price.
stop_limitnumberNew limit price (stop limit orders).
slnumberNew stop loss, 0 removes it.
tpnumberNew take profit, 0 removes it.
expirationintegerNew expiry, unix seconds, trade server clock. 0 = good till cancelled.
Response 200 Done.
A TradeResult object.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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}'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"])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']}")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);{
"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
}{
"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
/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.
Path parameters
idstring requiredAccount id.
ticketinteger requiredPending order ticket.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/orders/51830020" \
-H "Authorization: Bearer $TERMLESS_KEY"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"])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']}")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);{
"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
}{
"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
/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=).
Path parameters
idstring requiredAccount id.
ticketinteger requiredPosition ticket.
Headers
X-Request-IdstringYour 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.
ticketinteger requiredPosition ticket.
symbolstring requiredSymbol name.
sidestring requiredDirection.
buysellvolumenumber requiredLots.
price_opennumber requiredOpen price.
price_currentnumber requiredCurrent close price (bid for a buy, ask for a sell).
slnumber requiredStop loss price, 0 when none.
tpnumber requiredTake profit price, 0 when none.
profitnumber requiredFloating profit in the deposit currency, live.
swapnumber requiredSwap so far.
commissionnumber requiredCommission so far.
commentstring requiredComment. 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.
magicinteger requiredMagic 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).
reasonstring requiredWhy 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_servicemigrationunknownidentifierinteger requiredPosition id; the deals of this position carry it as position_id.
timeinteger requiredOpen time, unix seconds, trade server clock.
time_mscinteger requiredOpen time, unix milliseconds, trade server clock.
time_updateinteger requiredLast change, unix seconds, trade server clock.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());{
"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
/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.
Path parameters
idstring requiredAccount id.
ticketinteger requiredPosition ticket.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
slnumberNew stop loss, 0 removes it.
tpnumberNew take profit, 0 removes it.
Response 200 Done.
A TradeResult object.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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}'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"])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']}")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);{
"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
}{
"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
/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.
Path parameters
idstring requiredAccount id.
ticketinteger requiredPosition ticket.
Query parameters
volumenumberLots to close. Omit to close all of it; more than the position is 400.
deviationinteger default20min 0Largest slippage you accept, in points.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s -X DELETE "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/positions/51830012?volume=0.1" \
-H "Authorization: Bearer $TERMLESS_KEY"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"])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']}")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);{
"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
}{
"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
/api/v1/accounts/{id}/dealsDeal history: fills, closes and balance operations, oldest first. Defaults to the last 8 days up to tomorrow (trade server time); at most 10 years per request. A page is the newest limit deals in the window before the before cursor, still oldest first; for the next (older) page send before = the first deal's time_msc. position, ticket and symbol narrow it the way history_deals_get(position=, ticket=) does: ticket is the order that made the deals (their order, DEAL_ORDER). They combine. With position or ticket and no from, the window reaches 10 years back instead of 8 days, as the official call searches all history.
Path parameters
idstring requiredAccount id.
Query parameters
fromintegerStart, unix seconds, trade server time. Defaults to 8 days before to (10 years with position or ticket).
tointegerEnd, unix seconds, trade server time. Defaults to tomorrow (now + 1 day).
limitinteger default5000min 1, max 5000Page size: the newest N deals in the window (before the cursor), at most 5000.
beforeintegerCursor: only deals with time_msc below this. Send the first deal's time_msc of the page you have.
before_ticketintegerWith 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).
positionintegerOnly the deals of this position (their position_id), like history_deals_get(position=).
ticketintegerOnly the deals this order made (their order field), like history_deals_get(ticket=).
symbolstringOnly this symbol (exact name, any case).
Headers
X-Request-IdstringYour 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.
ticketinteger requiredDeal ticket.
orderinteger requiredOrder that made the deal.
position_idinteger requiredPosition the deal belongs to (its identifier).
symbolstring requiredSymbol name. Empty for balance operations.
typestring requiredThe MetaTrader deal type, lowercase. unknown only for a value MetaTrader does not define.
buysellbalancecreditchargecorrectionbonuscommissioncommission_dailycommission_monthlycommission_agent_dailycommission_agent_monthlyinterestbuy_canceledsell_canceleddividenddividend_frankedtaxunknownentrystring requiredin opens, out closes, inout reverses, out_by closes by an opposite position. unknown only for a value MetaTrader does not define.
inoutinoutout_byunknownvolumenumber requiredLots.
pricenumber requiredDeal price.
profitnumber requiredRealised profit in the deposit currency.
commissionnumber requiredCommission.
swapnumber requiredSwap.
feenumber requiredFee.
magicinteger requiredMagic 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.
commentstring requiredComment. 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).
reasonstring requiredWhy 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_servicemigrationunknowntimeinteger requiredUnix seconds, trade server clock.
time_mscinteger requiredUnix milliseconds, trade server clock.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/deals?from=1790376379" \
-H "Authorization: Bearer $TERMLESS_KEY"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())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))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());[
{
"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
/api/v1/accounts/{id}/calcorder_calc_margin and order_calc_profit in one call, in the account currency: the margin volume lots need once the trade is open at price (default the current ask for a buy, bid for a sell), and with close the profit from price to close. For a pending type, margin is what the position needs when the order fills (the market rate of its side) and margin_pending what the broker holds while it waits (the pending type's own rate: 0 at the brokers seen, so nothing); margin_pending is null for a market order. Worked out the way the terminal does it, from the symbol's spec, the account's leverage and the live prices of the symbols that convert currencies. A margin (or profit) is null when no symbol converts its currency to the account's. All are rounded to the account currency's digits. No order is sent.
Path parameters
idstring requiredAccount id.
Query parameters
symbolstring requiredSymbol name.
sidestring requiredDirection.
buysellvolumenumber requiredLots, more than 0.
typestring default"market"Order type. For a pending type the answer also says what the order holds while it waits (margin_pending).
marketlimitstopstop_limitpricenumberOpen price. Omit (or 0) for the current ask for a buy, bid for a sell.
closenumberClosing price: also work out the profit from price to close. More than 0.
Headers
X-Request-IdstringYour 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.
symbolstring requiredSymbol name, as the broker spells it.
sidestring requiredDirection.
buyselltypestring requiredThe MetaTrader order type the side and type make.
buysellbuy_limitsell_limitbuy_stopsell_stopbuy_stop_limitsell_stop_limitvolumenumber requiredLots.
pricenumber requiredThe open price used: the one asked for, else the current ask for a buy and bid for a sell.
marginnumber or null requiredThe 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_pendingnumber or null requiredFor 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.
closenumber or null requiredThe closing price asked for; null without one.
profitnumber or null requiredWhat 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.
currencystring requiredThe account currency the numbers are in.
Errors
- 400
bad_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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"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())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))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());{
"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
/api/v1/accounts/{id}/order_checkorder_check: takes the same request as order_send and answers what sending it would do, without sending it. A read key is enough; nothing is audited and no Idempotency-Key is needed. For a deal or pending order that opens something (position 0) it checks, in order: the volume against the symbol's volume_min, volume_max and volume_step (10014); the symbol's trade mode (10017 disabled, 10044 close only, 10042 a sell on a long_only symbol, 10043 a buy on a short_only one); today's trade sessions by the server's clock (10018; skipped when the broker sent none); a pending order's price against the live quote (10015: a buy limit must sit below the ask, a buy stop above it, a sell limit above the bid, a sell stop below it, each at least stops_level points away; a stop limit's limit price below its stop price for a buy and above it for a sell; a pending order without a price); its stop-loss and take-profit (10016: on the losing and winning side of the price they are measured from, at least stops_level points away; a deal's from the price that would close it, the bid for a buy and the ask for a sell, a pending order's from its own price, a stop limit's from its limit price); then the margin the order needs at price (the current price when 0) against the free margin (10019; a pending order needs only what it holds while it waits, usually nothing). TRADE_ACTION_SLTP and TRADE_ACTION_MODIFY are checked against the market too (10016, and 10015 for an order's new price) when the position or order is open on the account. The first failing check sets retcode and comment; 0 and Done when all pass. Other actions, and a deal that closes a position, never get 10019: request_margin is 0 and the answer is the account as it is. The freeze level is not checked, and an opening order counts its whole margin even when an opposite position would hedge or net it. Always 200 when the request could be read; 400 when it cannot, or when no symbol converts the margin currency to the account's.
Path parameters
idstring requiredAccount id.
Headers
X-Request-IdstringYour 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.
actioninteger or string requiredTRADE_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.
symbolstringSymbol name.
volumenumberLots.
typeinteger or stringORDER_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.
pricenumberPrice.
stoplimitnumberLimit price of a stop limit order. stop_limit also works.
slnumberStop loss.
tpnumberTake profit.
deviationintegerLargest slippage, in points.
type_fillinginteger or stringORDER_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_timeinteger or stringORDER_TIME_*: 0 GTC, 1 day, 2 specified, 3 specified day. A number or the official name, for example ORDER_TIME_GTC.
expirationintegerExpiry, unix seconds, trade server clock. The broker keeps whole minutes; one with seconds gets a warning.
commentstringComment, 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.
magicintegerMagic 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.
positionintegerPosition ticket, to close or modify a position.
position_byintegerOpposite position ticket, for close_by.
orderintegerOrder ticket, to modify or remove a pending order.
Response 200 The check.
A OrderCheck object.
okboolean requiredTrue when retcode is 0: sent now, the order would pass these checks.
retcodeinteger required0 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.
0100141001710042100431004410018100151001610019commentstring requiredThe result in words.
DoneInvalid volumeTrade disabledOnly position closing is allowedOnly long positions are allowedOnly short positions are allowedMarket closedInvalid priceInvalid stopsNo moneybalancenumber requiredBalance now.
equitynumber requiredEquity now, live.
profitnumber requiredFloating profit now, live.
marginnumber requiredMargin in use with the order (includes request_margin).
margin_freenumber requiredequity - margin, with the order. Below 0 is 10019 for an order that opens something.
margin_levelnumber requiredequity / margin x 100 with the order, in percent. 0 with no margin.
request_marginnumber requiredThe 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenThe key lacks the scope, or may not use this account, or a cookie request came from another site. - 404
not_foundNo such account, symbol, ticket, key or route. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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"}'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())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))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());{
"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
/api/v1/accounts/{id}/order_sendTakes the same request dict as order_send() in the official MetaTrader5 Python package, so existing scripts port over unchanged. Enum fields take the numbers or the official names ("TRADE_ACTION_DEAL", "ORDER_TYPE_SELL", "ORDER_FILLING_IOC"). Any other field is 400 naming it, and TRADE_ACTION_SLTP without position works only when one position is open on the symbol. Answers 200 with the trade result when the broker placed or filled it, and 422 when the broker refused it (the body is the trade result plus error, code rejected). Send an Idempotency-Key header and a retry with the same key and body replays the stored answer (with Idempotent-Replayed: true) instead of reaching the broker again; after a 502, 503 or 504 retry with the same key, then check positions and orders (a 503 busy or stopping was never sent and is not kept, so its retry is sent; a 504 unconfirmed whose result came late replays that result). On an account the broker reports as real money this answers 403 real_account until an admin sets trade_real: true. Prefer the routes above for new code.
Path parameters
idstring requiredAccount id.
Headers
Idempotency-KeystringA 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: trueand 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 503busyand 503stopping: that request was never sent, so its key is let go and a retry with the same key is sent. A 504unconfirmedtrade 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-IdstringYour 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.
actioninteger or string requiredTRADE_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.
symbolstringSymbol name.
volumenumberLots.
typeinteger or stringORDER_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.
pricenumberPrice.
stoplimitnumberLimit price of a stop limit order. stop_limit also works.
slnumberStop loss.
tpnumberTake profit.
deviationintegerLargest slippage, in points.
type_fillinginteger or stringORDER_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_timeinteger or stringORDER_TIME_*: 0 GTC, 1 day, 2 specified, 3 specified day. A number or the official name, for example ORDER_TIME_GTC.
expirationintegerExpiry, unix seconds, trade server clock. The broker keeps whole minutes; one with seconds gets a warning.
commentstringComment, 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.
magicintegerMagic 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.
positionintegerPosition ticket, to close or modify a position.
position_byintegerOpposite position ticket, for close_by.
orderintegerOrder ticket, to modify or remove a pending order.
Response 200 Done.
A TradeResult object.
okboolean requiredTrue 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.
retcodeinteger requiredMetaTrader return code. 10009 = done, 10008 = placed. See x-retcodes for the rest.
retcode_textstring requiredThe return code in words.
dealinteger requiredDeal ticket, 0 when no deal was made.
orderinteger requiredOrder ticket.
volumenumber requiredLots done.
pricenumber requiredPrice done.
bidnumber requiredBid when the broker handled the request.
asknumber requiredAsk when the broker handled the request.
commentstring requiredBroker's comment.
request_idinteger requiredThe broker's id for the request.
warningsarray of stringPresent 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_requestA 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
unauthorizedNo valid API key or session. - 403
forbiddenreal_accountforbidden: 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 setstrade_real: trueon the account; nothing was sent. Demo and contest accounts trade either way. - 404
not_foundNo such account, symbol, ticket, key or route. - 409
conflictThe 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
rejectedThe broker refused the trade. The body is the trade result (ok false, the retcode) plus error. Do not resend it unchanged. - 429
too_many_requestsThis 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_errorThe broker's server failed or answered with something unexpected. - 503
disconnectedbusystoppingdisconnected: 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
timeoutunconfirmedtimeout: 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 -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}'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"])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']}")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);{
"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
}{
"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)"
}
}