Reference
Streaming
Live prices pushed to you. Server-sent events for browsers and simple scripts, a WebSocket when you want to change symbols on the fly. Both end when the account is deleted or logs in with new details; reconnect to follow it. Trade events are numbered per account, and the numbering survives a restart: a client that dropped resumes with Last-Event-ID or ?after=<id> and gets what it missed first (from the last 1,024), or a resync when that cannot be done. After a gap (the broker link was down, the server stopped, the account's session started again) the deals made meanwhile come as trade events marked caught_up, then a resync. GET /trades?after= serves the same numbering to clients that poll.
Stream prices and events (SSE)
/api/v1/accounts/{id}/streamServer-sent events. event: status (a StreamStatus, {connected, ping_ms}) arrives first and again whenever the account connects or drops. Each price change arrives as event: tick with a Tick as data. A comment line (: heartbeat) arrives every 15 s so you can spot a dead connection. events= picks what the stream carries: ticks (the default), trades (event: trade, a TradeEvent per broker trade push), account (event: account, an AccountSnapshot when a value changed, every 500 ms at most), positions (event: positions, a PositionsSnapshot with live P/L on the same rhythm) and orders (event: orders, an OrdersSnapshot right after the first status and whenever a trade push changed the pending orders); leave ticks out for events only. An unknown name is 400. Trade events are numbered (seq, and id = <epoch>:<seq>). trade and resync events and the first status carry an id: line, so EventSource sends the last one back as Last-Event-ID when it reconnects; ?after=<id> does the same by hand. The first status's data has id too when the stream follows trades or orders (the client's cursor when it resumes, else the newest id). A resumed stream gets the events after its cursor first, in order, from the last 1,024 kept per account (kept in the database too, so an id from before a restart resumes); when that cannot be done (an id from another epoch: the account was added again or logs in to another broker account; an id from the future; too much happened) it gets event: resync (a Resync) instead: read positions, orders and deals again. After a gap (the broker link came back, the server restarted, the account's session started again) the deals the broker made meanwhile come as trade events marked caught_up, then a resync; a stream that fell 1,024 events behind gets a resync too. The stream ends after a last status with reason (account changed when the account is deleted or logs in with new details, server stopping on shutdown, key revoked or key changed when its key is deleted or may no longer read the account, signed out for a dashboard session); EventSource reconnects by itself. At most 1,024 streams per server and 256 per key (429 with Retry-After past that). Browsers cannot set headers on EventSource, so this route also accepts ?key=. Since 0.7.0 a stream with ticks gets gap events (a Gap) when it missed some: it fell behind, the broker link came back, or the fan-out fell behind. events=bars&bars=EURUSD:M1,XAUUSD:H1 adds bar series (at most 100): bar events (a Bar) forming from the bids and closed from the broker's own bars, corrected if the broker changes one within a minute, and bars_gap (a BarsGap) when bars cannot be sent.
?key=Path parameters
idstring requiredAccount id.
Query parameters
symbolsstringComma-separated symbols, at most 200. Defaults to the account's watchlist.
eventsstring default"ticks"Comma-separated event types: ticks, bars, trades, account, positions, orders. Absent means ticks.
barsstringWith events=bars: comma-separated series, SYMBOL:TF, at most 100 (0.7.0).
batch_msinteger default0min 0, max 1000 writes every broker frame as it arrives. N gathers the ticks of the next N ms after a tick into one write, for clients that prefer fewer, larger reads over the last millisecond.
afterstringResume after this trade event id (<epoch>:<seq>, from a trade or resync event or the first status). The events after it come first, from the last 1,024 kept per account, or a resync when that cannot be done. A malformed id is 400.
keystringAPI key, for clients that cannot send headers.
Headers
Last-Event-IDstringWhat EventSource sends by itself when it reconnects: the id of the last event it saw. Works like after= (which wins when both are sent).
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 An open text/event-stream.
An open text/event-stream. Events: status (StreamStatus), tick (Tick), and with events= also trade (TradeEvent), account (AccountSnapshot), positions (PositionsSnapshot) and orders (OrdersSnapshot), and resync (Resync) for a stream that follows trades; a : heartbeat comment every 15 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
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 -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?symbols=XAUUSD,EURUSD&events=ticks,trades,orders&bars=XAUUSD:M1,EURUSD:H1" \
-H "Authorization: Bearer $TERMLESS_KEY"import os
import json
import requests
base = os.environ["TERMLESS_URL"] + "/api/v1"
auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]}
with requests.get(f"{base}/accounts/pepperstone-12345678/stream", headers=auth,
params={"symbols": "XAUUSD,EURUSD"}, stream=True, timeout=(5, 30)) as r:
r.raise_for_status()
event = None
for line in r.iter_lines(decode_unicode=True):
if line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:"):
data = json.loads(line[5:])
if event == "tick":
print(data["symbol"], data["bid"], data["ask"])
elif event == "status":
print("broker link", data)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/stream?symbols=XAUUSD,EURUSD", headers=headers)
with urllib.request.urlopen(req, timeout=30) as r: # 30 s outlives two heartbeats
event = None
for raw in r:
line = raw.decode().rstrip("\n")
if line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:") and event == "tick":
t = json.loads(line[5:])
print(t["symbol"], t["bid"], t["ask"])// In a browser: EventSource cannot send headers, so the key goes in the query.
// In Node 22+, fetch the same URL with the Authorization header and read the body as a stream.
const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL);
url.searchParams.set("symbols", "XAUUSD,EURUSD");
url.searchParams.set("key", TERMLESS_KEY);
const es = new EventSource(url);
es.addEventListener("status", (e) => console.log("broker link", JSON.parse(e.data)));
es.addEventListener("tick", (e) => {
const t = JSON.parse(e.data);
console.log(t.symbol, t.bid, t.ask);
});
// EventSource reconnects by itself when the stream ends.event: status
id: 1790968290117:40
data: {"connected":true,"ping_ms":14.2,"id":"1790968290117:40"}
event: tick
data: {"symbol":"XAUUSD","bid":2391.42,"ask":2391.6,"last":0,"time_msc":1790981179473}
event: trade
id: 1790968290117:43
data: {"seq":43,"id":"1790968290117:43","what":"updated","kind":"position","position":{"ticket":51830012,"symbol":"XAUUSD","side":"buy","volume":0.2,"price_open":2385.0,"price_current":2391.42,"sl":2386.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":1790981102,"open":true}}
: heartbeatStream prices and events (WebSocket)
/api/v1/accounts/{id}/wsA WebSocket of JSON messages told apart by type (WsMessage): first {"type": "status", "connected", "ping_ms"}, then {"type": "subscribed", "symbols"}, then {"type": "tick", "symbol", "bid", "ask", "last", "time_msc"} for each price change, and status again whenever the account connects or drops. With events=, trade, resync, account, positions and orders messages arrive too (orders right after subscribed), with the same type field and the shapes of the SSE events. ?after=<id> resumes the trade events as on SSE: the missed ones come right after subscribed (or a resync), and the first status carries id. Send {"subscribe": ["GBPUSD"]} or {"unsubscribe": [...]} (WsCommand) at any time; the answer is subscribed with the whole list or {"type": "error", "message"}. The server pings every 15 s. The socket closes after a last status with reason (account changed, server stopping, key revoked, key changed or signed out), like the SSE stream, and counts against the same caps. Accepts ?key= because browsers cannot set headers on a WebSocket either. Since 0.7.0 a stream with ticks gets gap events (a Gap) when it missed some: it fell behind, the broker link came back, or the fan-out fell behind. events=bars&bars=EURUSD:M1,XAUUSD:H1 adds bar series (at most 100): bar events (a Bar) forming from the bids and closed from the broker's own bars, corrected if the broker changes one within a minute, and bars_gap (a BarsGap) when bars cannot be sent. On a socket opened with events=bars, {"bars": [...]} and {"unbars": [...]} add and remove series; the answer is {"type": "bars", "series"}.
?key=Path parameters
idstring requiredAccount id.
Query parameters
symbolsstringComma-separated symbols to start with, at most 200. Defaults to the account's watchlist.
eventsstring default"ticks"Comma-separated event types: ticks, bars, trades, account, positions, orders. Absent means ticks.
barsstringWith events=bars: comma-separated series, SYMBOL:TF, at most 100 (0.7.0).
afterstringResume after this trade event id (<epoch>:<seq>, from a trade or resync event or the first status). The events after it come first, from the last 1,024 kept per account, or a resync when that cannot be done. A malformed id is 400.
keystringAPI key, for clients that cannot send headers.
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 101 Switching protocols. The socket is open; messages are WsMessage.
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 cannot speak WebSocket; websocat (https://github.com/vi/websocat) can:
websocat "${TERMLESS_URL/http/ws}/api/v1/accounts/pepperstone-12345678/ws?symbols=XAUUSD,EURUSD&key=$TERMLESS_KEY"
# then type a line to change symbols:
# {"subscribe": ["GBPUSD"]}import asyncio
import json
import os
import websockets # pip install websockets
ws_base = os.environ["TERMLESS_URL"].replace("http", "ws", 1) + "/api/v1"
key = os.environ["TERMLESS_KEY"]
async def main():
url = f"{ws_base}/accounts/pepperstone-12345678/ws?symbols=XAUUSD,EURUSD&key={key}"
async with websockets.connect(url) as ws:
await ws.send(json.dumps({"subscribe": ["GBPUSD"]}))
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "tick":
print(msg["symbol"], msg["bid"], msg["ask"])
else:
print(msg)
asyncio.run(main())# The standard library has no WebSocket client; use the Python tab (websockets) or the SSE stream,
# which plain urllib can read line by line.const url = new URL("/api/v1/accounts/pepperstone-12345678/ws", TERMLESS_URL.replace(/^http/, "ws"));
url.searchParams.set("symbols", "XAUUSD,EURUSD");
url.searchParams.set("key", TERMLESS_KEY);
const ws = new WebSocket(url);
ws.onopen = () => ws.send(JSON.stringify({ subscribe: ["GBPUSD"] }));
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === "tick") console.log(msg.symbol, msg.bid, msg.ask);
else console.log(msg); // status, subscribed, error
};
ws.onclose = () => console.log("closed; reconnect to keep following the account");Read trade events since an id
/api/v1/accounts/{id}/tradesThe account's numbered trade events, for a client that polls instead of holding a stream open: the same trade and resync events, seq and id as on /stream?events=trades. id in the answer is the newest event's id: send it as after next time. events are the ones after after, oldest first, each with event (trade or resync) beside its fields. resync is null, or why the events since after cannot be given (an id from another epoch: the account was added again or logs in to another broker account; an id newer than anything sent; more happened than the server keeps): then read positions, orders and deals again and carry on from id. The events are kept in the database, so an id from before a restart still resumes; the deals made while the server was stopped or the broker link was down come as trade events marked caught_up, before that gap's resync event. Without after, the newest limit events kept (default 100, at most 1,024; 0.6.3). 503 while the account is turned off.
Path parameters
idstring requiredAccount id.
Query parameters
afterstringThe last event id you handled (<epoch>:<seq>). Leave it out for every kept event. A malformed id is 400.
limitinteger min 0, max 1024Without after: how many of the newest kept events to return (default 100, at most 1,024; 0.6.3).
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 events since after.
A TradesSince object.
idstring requiredThe newest event's id (<epoch>:0 before the first). Ask again with after=<this>.
eventsarray of object requiredThe events after
after, oldest first: each a TradeEvent or a Resync witheventbeside its fields. Without after: every event kept (up to 1,024). Empty when resync is set.Fields
eventstring requiredtrade or resync: which of the two the rest of the object is.
traderesync
resyncstring or null requirednull, or why the events since after cannot be given (another epoch: the account was added again or logs in to another broker account; an id newer than anything sent; more happened than the server keeps). Then read positions, orders and deals again and carry on from id. A restart of the server does not change the epoch: an id from before it still resumes.
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. - 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).
curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/trades?after=1790968290117:41&limit=100" \
-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/trades", headers=auth, params={"after": "1790968290117:41", "limit": 100})
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/trades?after=1790968290117:41&limit=100", 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/trades?after=1790968290117:41&limit=100`, {
headers: { Authorization: `Bearer ${process.env.TERMLESS_KEY}` }
});
if (!res.ok) throw new Error((await res.json()).error.message);
console.log(await res.json());{
"id": "1790968290117:43",
"events": [
{
"event": "trade",
"seq": 42,
"id": "1790968290117:42",
"what": "opened",
"kind": "deal",
"deal": {
"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
},
"balance": 10412.58,
"credit": 0.0,
"position": {
"ticket": 51830012,
"symbol": "XAUUSD",
"side": "buy",
"volume": 0.2,
"price_open": 2385.0,
"price_current": 2385.0,
"sl": 2380.0,
"tp": 2420.0,
"profit": 0.0,
"swap": 0.0,
"commission": -0.7,
"comment": "breakout",
"magic": 0,
"reason": "web",
"identifier": 51830012,
"time": 1790975498,
"time_msc": 1790975498123,
"time_update": 1790975498,
"open": true
}
},
{
"event": "trade",
"seq": 43,
"id": "1790968290117:43",
"what": "updated",
"kind": "position",
"position": {
"ticket": 51830012,
"symbol": "XAUUSD",
"side": "buy",
"volume": 0.2,
"price_open": 2385.0,
"price_current": 2391.42,
"sl": 2386.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": 1790981102,
"open": true
}
}
],
"resync": null
}