# 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=` 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) `GET /api/v1/accounts/{id}/stream` Scope: read. The stream routes also accept `?key=`. Server-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` = `:`). `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=` 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. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `symbols` | string | no | Comma-separated symbols, at most 200. Defaults to the account's watchlist. | | `events` | string | no | Comma-separated event types: ticks, bars, trades, account, positions, orders. Absent means ticks. (default "ticks") | | `bars` | string | no | With events=bars: comma-separated series, SYMBOL:TF, at most 100 (0.7.0). | | `batch_ms` | integer | no | 0 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. (default 0; 0 to 100) | | `after` | string | no | Resume after this trade event id (:, 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. | | `key` | string | no | API key, for clients that cannot send headers. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `Last-Event-ID` | string | no | What 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-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: An open text/event-stream. Example: ```text 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}} : heartbeat ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: timeout: the broker did not answer a request that was sent (one broker call is given 20 s), or the whole request ran past 30 s (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh curl -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" ``` **Python (requests)** ```python 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) ``` ### Stream prices and events (WebSocket) `GET /api/v1/accounts/{id}/ws` Scope: read. The stream routes also accept `?key=`. A 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=` 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"}`. **Path parameters** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `symbols` | string | no | Comma-separated symbols to start with, at most 200. Defaults to the account's watchlist. | | `events` | string | no | Comma-separated event types: ticks, bars, trades, account, positions, orders. Absent means ticks. (default "ticks") | | `bars` | string | no | With events=bars: comma-separated series, SYMBOL:TF, at most 100 (0.7.0). | | `after` | string | no | Resume after this trade event id (:, 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. | | `key` | string | no | API key, for clients that cannot send headers. | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 101**: Switching protocols. The socket is open; messages are WsMessage. **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `502 broker_error`: The broker's server failed or answered with something unexpected. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). - `504 timeout, unconfirmed`: timeout: the broker did not answer a request that was sent (one broker call is given 20 s), or the whole request ran past 30 s (TERMLESS_REQUEST_TIMEOUT). unconfirmed (trades, since 0.6.0): the broker took the trade but its final result did not come, so it may have been carried out; the body adds request_id, retcode (null or the last in-between state, 10001 to 10003) and retcode_text. Retry with the same Idempotency-Key: the stored answer is replayed (the real result once it came late), so the broker never sees it twice; then check positions and orders. **curl** ```sh # curl 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"]} ``` **Python (requests)** ```python 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()) ``` ### Read trade events since an id `GET /api/v1/accounts/{id}/trades` Scope: read. The 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** | Name | Type | Required | Description | |---|---|---|---| | `id` | string | yes | Account id. | **Query parameters** | Name | Type | Required | Description | |---|---|---|---| | `after` | string | no | The last event id you handled (:). Leave it out for every kept event. A malformed id is 400. | | `limit` | integer | no | Without after: how many of the newest kept events to return (default 100, at most 1,024; 0.6.3). (0 to 1024) | **Headers** | Name | Type | Required | Description | |---|---|---|---| | `X-Request-Id` | string | no | Your own id for the request, kept and echoed in the response header of the same name (and written on every log line and audit row of the request). Anything else is replaced by one the server makes. | **Response 200**: The events since after. A TradesSince object. | Field | Type | Description | |---|---|---| | `id` | string | The newest event's id (:0 before the first). Ask again with after=. (required) | | `events` | array of object | The events after `after`, oldest first: each a TradeEvent or a Resync with `event` beside its fields. Without after: every event kept (up to 1,024). Empty when resync is set. (required; object: event) | | `resync` | string or null | null, 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. (required) | Example: ```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 } ``` **Errors** - `400 bad_request`: A field is missing or not valid, or the query string has a parameter the route does not take (the message names the ones it takes; `key=` is accepted anywhere). - `401 unauthorized`: No valid API key or session. - `403 forbidden`: The key lacks the scope, or may not use this account, or a cookie request came from another site. - `404 not_found`: No such account, symbol, ticket, key or route. - `429 too_many_requests`: This IP is locked out for 15 minutes (5 wrong passwords or setup tokens lock it out of sign-in, 30 unknown API keys in 15 minutes lock it out of key auth), or a stream cap was hit (1,024 open streams per server, 256 per key or dashboard session), or a password check could not start (one at a time per IP, two at a time per server). Retry-After has the seconds to wait. - `503 disconnected, busy, stopping`: disconnected: the account is not connected (it reconnects on its own; the route waits up to 2 s first) or is turned off; retry with backoff (on a trade route it was never sent: a trade's Idempotency-Key is let go). busy: requests of one command go to the broker one at a time per account, and this one waited its whole turn (20 s) behind earlier ones and was never sent, so sending it again is safe (a trade's Idempotency-Key is let go, so the retry with the same key is sent). **curl** ```sh curl -s "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/trades?after=1790968290117:41&limit=100" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` **Python (requests)** ```python import os import requests base = os.environ["TERMLESS_URL"] + "/api/v1" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} r = requests.get(f"{base}/accounts/pepperstone-12345678/trades", headers=auth, params={"after": "1790968290117:41", "limit": 100}) r.raise_for_status() print(r.json()) ```