# Streaming prices Every tick pushed to you over Server-sent events or a WebSocket, the trade, account, positions and orders events a bot should read instead of polling, which trade events a UI should show, how a client that dropped picks up the trades it missed, what a status event means, how the stream ends, and what happens when you fall behind. Polling `GET /quotes` is fine for a glance. For prices as they happen, open a stream: Termless pushes every tick the broker sends for the symbols you asked for, for as long as the connection is open. Two flavours carry the same data. | | SSE: `GET /api/v1/accounts/{id}/stream` | WebSocket: `GET /api/v1/accounts/{id}/ws` | |---|---|---| | Transport | Plain HTTP, `text/event-stream`. Works with `curl -N`, `requests`, `EventSource`. | WebSocket upgrade. | | Changing symbols | Open another stream (or one stream for all of them). | Send `{"subscribe": [...]}` or `{"unsubscribe": [...]}` any time. | | Reconnect | `EventSource` does it by itself. | You reconnect. | | Liveness | A `: heartbeat` comment every 15 s. | A ping every 15 s. | | Key | Header, or `?key=` for browsers. | Header, or `?key=`. | Both default to the account's watchlist when `symbols` is left out. One stream carries up to 200 symbols, so open one stream with all of them rather than one per symbol. Both also carry more than prices: with `?events=` the same stream tells you about every trade the broker applies and keeps the account's money, the live P/L of its positions and its pending orders current, so a bot never polls (see [Events](#events-trades-account-positions-orders) below). ## Server-sent events ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?symbols=XAUUSD,EURUSD" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```sse event: status data: {"connected":true,"ping_ms":14.2} event: tick data: {"symbol":"XAUUSD","bid":2391.42,"ask":2391.6,"last":0,"time_msc":1790981179473} event: tick data: {"symbol":"EURUSD","bid":1.08412,"ask":1.08418,"last":0,"time_msc":1790981179581} : heartbeat ``` Three kinds of line arrive: - `event: status` with `{connected, ping_ms}`. The first event on every stream, and again the moment `connected` changes. While `connected` is false no ticks come, because the account has no link to the broker; they resume on their own when it reconnects. - `event: tick` with `{symbol, bid, ask, last, time_msc}`. One per price change. `time_msc` is the trade server's clock in milliseconds. - `: heartbeat`, a comment line every 15 seconds while nothing else is sent. If a stream has been silent for a minute, the connection is dead: close it and open a new one. ```python import json import os import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} with requests.get(url, headers=auth, params={"symbols": "XAUUSD,EURUSD"}, stream=True, timeout=(5, 30)) as r: # a 30 s read timeout outlives two heartbeats 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 up" if data["connected"] else "broker link down", data) ``` ```javascript // Browser: EventSource cannot send headers, so the key goes in the query. 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); }); // When the stream ends or the network drops, EventSource reconnects by itself. ``` ### Batching By default every broker frame is written to you as it arrives, for the lowest latency. If you would rather have fewer, larger reads, add `&batch_ms=N` (1 to 100): after a tick the server gathers the ticks of the next N milliseconds into one write. Only ticks are batched; events go out as they happen. ## Events: trades, account, positions, orders `events=` on `/stream` and `/ws` picks what the stream carries, comma-separated. Absent means `ticks`, so existing clients see no change. Leave `ticks` out to get events only. An unknown name is `400`. | `events=` | Event | Data | When | |---|---|---|---| | `ticks` | `tick` | `{symbol, bid, ask, last, time_msc}` | Every price change (default). | | `trades` | `trade` | `{seq, id, what, kind, pending?, order?, state?, deal?, position?, positions?, balance?, credit?, caught_up?}` | One per broker trade push, as it is applied: an order placed, changed, filled or cancelled, a deal opening, reducing, closing or reversing a position, a position's stops moved, a balance operation. After a gap, the deals the broker made meanwhile, marked `caught_up`. Numbered, so a client that dropped can [pick up where it left off](#picking-up-where-you-left-off). | | `account` | `account` | the summary (`balance`, `equity`, `margin`, `margin_free`, `profit`, ...) plus `time_ms` | Right after the stream opens, then whenever a value changed, checked every 500 ms at most. | | `positions` | `positions` | `{positions: [position...], time_ms}` with live `profit` and `price_current` | On the same 500 ms rhythm, only when something changed. | | `orders` | `orders` | `{orders: [order...], time_ms}`: every pending order (limit, stop, stop limit) in the order shape of `GET /orders` | Once right after the first `status`, then whenever a trade push added, changed or removed a pending order (and after a reconnect, if the book changed meanwhile). Ticks never send one: an order has no live price. | ```sh curl -N "$TERMLESS_URL/api/v1/accounts/pepperstone-12345678/stream?events=trades,account,positions,orders" \ -H "Authorization: Bearer $TERMLESS_KEY" ``` ```sse event: status id: 1790968290117:40 data: {"connected":true,"ping_ms":14.2,"id":"1790968290117:40"} event: account data: {"login":12345678,"name":"Demo Trader","server":"Pepperstone-Demo","company":"Pepperstone Group Limited","currency":"USD","leverage":200,"balance":10412.58,"credit":0.0,"profit":238.11,"equity":10650.69,"margin":878.93,"margin_free":9771.76,"margin_level":1211.78,"margin_so_call":100.0,"margin_so_so":50.0,"trade_allowed":true,"demo":true,"hedging":true,"server_offset":10800,"positions":3,"orders":2,"time_ms":1790981179473} event: positions data: {"positions":[{"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}],"time_ms":1790981179473} event: orders data: {"orders":[],"time_ms":1790981179473} event: trade id: 1790968290117:41 data: {"seq":41,"id":"1790968290117:41","what":"placed","kind":"order","pending":true,"order":{"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},"state":"placed"} event: orders data: {"orders":[{"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}],"time_ms":1790977698430} event: trade id: 1790968290117:42 data: {"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 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":0.0,"commission":-0.7,"comment":"breakout","magic":0,"reason":"web","identifier":51830012,"time":1790975498,"time_msc":1790975498123,"time_update":1790981102,"open":true}} ``` ### Reading a trade event `kind` says what the broker pushed, `what` says what it meant: - `kind: "order"` carries `order` (the order in its usual shape), `state` (`placed`, `partial`, `filled`, `cancelled`, `expired`, `rejected`, ...) and `pending`: `true` for a limit, stop or stop-limit order, `false` for a market buy or sell. `what` is `placed`, `modified` or `removed` while the order is live, and `filled`, `cancelled`, `expired` or `rejected` when it moves to history. On a filled order `volume` is what is left (`0`) and `volume_initial` is what was asked. - `kind: "deal"` carries `deal` (the deal in its usual shape), `balance` and `credit` (the account's, after the deal), and `position`: the position the deal touched, with an extra `open` that is `false` once it is closed. `what` is `opened`, `partial` (a partial close), `closed`, `reversed`, or `balance` for a balance, credit or commission deal (no `position` then). `positions` lists other positions the same push updated, which happens on a netting account. A closed position keeps its last known values (open price, stops, time, comment, magic) with `volume` 0, so you can still say which trade it was. `deal.reason` says why it closed: `sl` or `tp` for a stop, `stop_out`, `web` for a close sent through Termless. - `kind: "position"` with `what: "updated"`: the broker changed a position without a deal, because its stop loss or take profit moved or as the step just before a close. It carries `position` (with `open`) and sometimes `positions`, and no `deal`, `balance` or `credit`. - `caught_up: true` on a `kind: "deal"` event: a deal the broker made while the link was down, the server was stopped or the account's session was starting again, read back from the account's history afterwards (see [after a gap](#after-a-gap-the-deals-made-meanwhile)). It carries `what` and `deal` only: no `position`, `balance` or `credit`, because the history does not say them. `what` is `opened`, `partial` (its position is still open), `closed`, `reversed` or `balance`. Every `trade` event also carries `seq` (1, 2, 3, ... per account) and `id` (`":"`), the cursor for [picking up where you left off](#picking-up-where-you-left-off). ### What a UI should show A market order has a short life of its own at the broker: it is placed, taken off the book and filed as filled (some servers file it as cancelled) within the same moment, and each step is an order event, with `volume` 0 once it is done. Showing those as "Filled buy 0.00" next to the real fill only confuses. `what` keeps its values for code that already reads them; `pending` tells the two kinds apart: | The trade | Show | Skip | |---|---|---| | A market order (`POST /orders` with no `type`, a close, a partial close) | the deal event: `opened`, `partial`, `closed` or `reversed`, with its volume and price | every order event with `pending: false` | | A pending order (limit, stop, stop limit) | its order events (`pending: true`): `placed`, `modified`, `cancelled`, `expired`, `rejected`; when it fills, its `filled` event and then the deal event that opened the position | `removed` (the same moment as the move to history) | | A balance, credit or commission | the deal event with `what: "balance"` | | | A stop loss or take profit moved, or the moment before a close | nothing: redraw positions from the `positions` event | the `kind: "position"` event with `what: "updated"` | | A close at the stop loss or take profit | the deal event `closed` (or `partial`), worded from `deal.reason`: "closed by stop loss" for `sl`, "closed by take profit" for `tp`, "stopped out" for `stop_out` | | The list of pending orders is easier still: ask for `events=orders` and redraw from each `orders` event, which never lists a market order. Events are per account, not per symbol, so a stream opened with `events=trades` and no `symbols` still hears every trade on the account. They are not coalesced like ticks: a slow client misses none until it falls more than 1,024 events behind, and then it gets a `resync` event (below) instead of a silent gap. An `orders` event is a snapshot, so nothing is lost if one is skipped: a stream that fell behind sends a fresh one if the book changed. ```python import json import os import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} with requests.get(url, headers=auth, params={"events": "trades,account"}, 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 == "trade" and data["kind"] == "deal": p = data.get("position") print(data["what"], data["deal"]["symbol"], data["deal"]["volume"], "position open" if p and p["open"] else "position closed", "balance", data["balance"]) elif event == "account": print("equity", data["equity"], "free margin", data["margin_free"]) ``` ```javascript const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL); url.searchParams.set("events", "trades,account,positions"); url.searchParams.set("key", TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("trade", (e) => { const t = JSON.parse(e.data); console.log(t.what, t.kind, t.kind === "deal" ? t.deal.symbol : t.order.symbol); }); es.addEventListener("account", (e) => console.log("equity", JSON.parse(e.data).equity)); es.addEventListener("positions", (e) => console.log("open positions", JSON.parse(e.data).positions.length)); ``` Which to ask for: a trading bot wants `trades` (to learn its fills and stops hit without polling `GET /deals`) and `account` (free margin before the next order); a UI wants `account`, `positions` and `orders` and never computes P/L or keeps its own order book; a price study wants `ticks` alone. ## Picking up where you left off A connection drops, a laptop sleeps, a bot restarts. Trade events are numbered so a client can come back and get the ones it missed instead of guessing. - Every `trade` event has `seq` (1, 2, 3, ... per account) and `id`, `":"`. `epoch` is when the server began this account's numbering (unix ms). The newest 1,024 events are kept in the server's database, so the numbering and the epoch carry on across a restart or an upgrade of the server, a changed password and turning the account off and on: an id you saw before any of those still resumes. A new numbering, with a new epoch, starts only when the account is added again or logs in to another broker account (another login or server). - A stream that follows `trades` or `orders` starts with a `status` that carries an `id` too: the newest id at that moment (`:0` before the first event), so you hold a cursor before any trade happens. Later `status` events carry none. - On SSE, the first `status` and every `trade` and `resync` event have an `id:` line. A browser's `EventSource` remembers the last one and sends it back as `Last-Event-ID` when it reconnects, so a page that uses `EventSource` resumes with no code at all. - Any client can resume by hand: open the stream with `?after=` (SSE and WebSocket). A malformed id is `400`. A resumed stream sends the first `status` (whose `id` is your cursor), then the events after your cursor, oldest first, without gaps, from the last 1,024 the server keeps for the account, then carries on live. On a WebSocket they come after `subscribed`. When the missed events cannot be replayed, you get one `resync` event instead (`type: "resync"` on a WebSocket), and the stream goes on live from the newest id: ```sse event: resync id: 1791012001502:3 data: {"seq":3,"id":"1791012001502:3","reason":"that id is from another numbering (the account now logs in to another broker account, or its kept events were lost)"} ``` A `resync` means one thing: read positions, orders and deals again (`GET /positions`, `GET /orders`, `GET /deals`), then trust the events that follow. It comes when your id is from another epoch, is newer than anything the account has sent, or is older than the 1,024 kept events, and when your own stream fell more than 1,024 events behind. Other resyncs are part of the numbering themselves and are replayed like trade events: after a gap (below) and when the server fell behind the broker's pushes (`"the server fell behind the broker's trade pushes"`). ### After a gap: the deals made meanwhile The broker never resends what it pushed while its link was down, and nothing reaches a server that is stopped. After such a gap the server reads the deals the broker made meanwhile from the account's history and sends each as a `trade` event with `caught_up: true`, oldest first, then a `resync` that says which gap it was: | Gap | `reason` | |---|---| | The broker link came back | `the broker link came back; its trade pushes sent while it was down are not replayed (the deals made meanwhile came first, marked caught_up)` | | The server restarted | `the server restarted; trade pushes sent while it was stopped are not replayed (the deals made meanwhile came first, marked caught_up)` | | The account's session started again (a changed password, turned off and on) | `the account's session started again; trade pushes sent in between are not replayed (the deals made meanwhile came first, marked caught_up)` | ```sse event: trade id: 1790968290117:48 data: {"seq":48,"id":"1790968290117:48","what":"closed","kind":"deal","deal":{"ticket":81200152,"order":51830050,"position_id":51830012,"symbol":"XAUUSD","type":"sell","entry":"out","volume":0.2,"price":2380.0,"profit":-100.0,"commission":-0.7,"swap":-1.12,"fee":0.0,"magic":0,"comment":"[sl 2380.00]","reason":"sl","time":1790990841,"time_msc":1790990841207},"caught_up":true} event: resync id: 1790968290117:49 data: {"seq":49,"id":"1790968290117:49","reason":"the server restarted; trade pushes sent while it was stopped are not replayed (the deals made meanwhile came first, marked caught_up)"} ``` A deal already sent is never sent again, and nothing older than the account's kept events is sent. A catch-up looks back at most 7 days and sends at most 500 deals (more than that: only the `resync`). Pending orders placed or removed and stops moved during the gap have no history, so the `resync` still follows: read positions and orders again. A client that only shows fills can show the caught-up deals as they come. ```python import json import os import time import requests url = os.environ["TERMLESS_URL"] + "/api/v1/accounts/pepperstone-12345678/stream" auth = {"Authorization": "Bearer " + os.environ["TERMLESS_KEY"]} cursor = None # keep it on disk to survive a restart of the bot def resync(): print("reading positions, orders and deals again") # your own reload here while True: params = {"events": "trades"} if cursor: params["after"] = cursor try: with requests.get(url, headers=auth, params=params, 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 == "resync": resync() elif event == "trade": print(data["seq"], data["what"], data["kind"]) if data.get("id"): # status, trade and resync carry one cursor = data["id"] except requests.RequestException as e: print("stream dropped:", e) time.sleep(2) ``` ```javascript // EventSource resumes by itself: it sends the last id back as Last-Event-ID. const url = new URL("/api/v1/accounts/pepperstone-12345678/stream", TERMLESS_URL); url.searchParams.set("events", "trades"); url.searchParams.set("key", TERMLESS_KEY); const es = new EventSource(url); es.addEventListener("trade", (e) => console.log(e.lastEventId, JSON.parse(e.data).what)); es.addEventListener("resync", () => reloadPositionsOrdersAndDeals()); ``` ### Polling instead of streaming A client that would rather ask now and then than hold a stream open reads the same numbering from `GET /api/v1/accounts/{id}/trades?after=`: ```json {"id": "1790968290117:44", "events": [{"event": "trade", "seq": 44, "id": "1790968290117:44", "what": "cancelled", "kind": "order", "pending": true, "order": {"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}, "state": "cancelled"}], "resync": null} ``` `id` is the newest event's id: send it as `after` next time. `events` are the events after `after`, oldest first, each with `event` (`trade` or `resync`) beside its own fields. `resync` is null, or a sentence saying why the events since `after` cannot be given; then read the account again and carry on from `id`. Without `after` you get every event the server keeps (up to 1,024). It needs a `read` key, and answers `503` while the account is turned off. ## WebSocket ```javascript const url = new URL("/api/v1/accounts/pepperstone-12345678/ws", TERMLESS_URL.replace(/^http/, "ws")); url.searchParams.set("symbols", "XAUUSD"); url.searchParams.set("key", TERMLESS_KEY); const ws = new WebSocket(url); ws.onopen = () => ws.send(JSON.stringify({ subscribe: ["EURUSD", "GBPUSD"] })); ws.onmessage = (e) => { const msg = JSON.parse(e.data); switch (msg.type) { case "status": console.log("broker link", msg.connected, msg.ping_ms); break; case "subscribed": console.log("now streaming", msg.symbols); break; case "tick": console.log(msg.symbol, msg.bid, msg.ask); break; case "error": console.warn(msg.message); break; } }; ``` Messages are JSON objects told apart by `type`: | `type` | Fields | When | |---|---|---| | `status` | `connected`, `ping_ms`, sometimes `reason`; on the first one `id` when the socket follows `trades` or `orders` | First message; again whenever `connected` changes; once more just before the socket closes. | | `subscribed` | `symbols` | After the open and after every `subscribe` or `unsubscribe`, with the whole current list. | | `tick` | `symbol`, `bid`, `ask`, `last`, `time_msc` | Every price change. | | `trade`, `account`, `positions`, `orders` | the same fields as the SSE events above | Only when asked for with `?events=`. Events replayed for `?after=` come right after `subscribed`, then an `orders` message. | | `resync` | `seq`, `id`, `reason` | When missed trade events cannot be replayed, or after a gap (the broker link came back, the server restarted, the account's session started again): read positions, orders and deals again. | | `error` | `message` | A command the server could not act on (an unknown symbol, more than 200 symbols). | You send `{"subscribe": ["GBPUSD"]}` or `{"unsubscribe": ["EURUSD"]}` (both in one message is fine; unsubscribe is applied first). The server pings every 15 seconds; most WebSocket libraries answer pongs for you. `?events=` works the same as on the SSE stream and cannot be changed after the open. A WebSocket has no `Last-Event-ID`: to resume, keep the last `id` you handled and reconnect with `?after=`. ## Bars Since 0.7.0 a stream can carry candles as they form, so a chart never polls `/candles`. Ask with `events=bars&bars=XAUUSD:M1,EURUSD:H1` (any official timeframe, at most 100 series a stream; add `ticks` to `events` for ticks too). On a WebSocket opened that way, `{"bars": ["GBPUSD:M5"]}` and `{"unbars": [...]}` add and remove series, answered by `{"type": "bars", "series": [...]}`. ```text event: bar data: {"symbol":"XAUUSD","timeframe":"M1","time":1790981160,"open":2391.2,"high":2391.9,"low":2391.1,"close":2391.42,"tick_volume":112,"real_volume":0,"state":"forming"} ``` - `state: "forming"`: the bar being built from the bids, as MetaTrader builds it, at most four a second per series (a slow stream keeps the newest). A series starts from the broker's own forming bar, so the first one is right. - `state: "closed"`: once the period ends by the server's clock (plus 2 s), the bar as the **broker** has it: one M1 read per symbol covers the closed minutes, every timeframe up to H12 is built from those, D1 and up are read directly. Use the closed bar, not your last forming one: they differ when ticks were missed. A period with no broker bar (no tick in it, a weekend) sends nothing. A trading symbol's minutes are read at their close even when none of their ticks reached the server, and a tick that turns up late for a closed period has it read again (0.7.1), so bars do not always arrive in time order: place each by its `time`. - `state: "corrected"`: a minute after a bar closed it is read again; if the broker changed it, it comes again. Replace the bar with the same `time`. After the autumn clock change on a New York + 7 server (Sunday 08:00 to 09:00 there happens twice), the repeated hour's bars that changed come again as corrected (0.7.1). - `event: bars_gap` with `{symbol, timeframe, from, to}`: bars this series cannot send (more than 500 missed while the link was down, a stream that fell far behind, a bar that could not be read again, or a minute of failed reads). Read that range with `GET /candles?from=&to=`. After a reconnect each series reads what it missed (up to 500 bars) and sends it in order before the forming bar. Series are shared: two streams asking for `XAUUSD:M1` cost one series on the account, which follows at most 200 symbols and 1,000 series across its streams (0.7.1). A symbol whose ticks the account cannot take still gets its closed bars, read from the broker each period. Names given while the account is down are checked when it comes up (see Names, in the API reference). ## When the stream ends A stream is tied to the account's current login. It ends, after one last `status` with `connected: false` and a `reason`, when: - the account is deleted, or logs in with new details (a changed password, server, host or port): `reason: "account changed"`; - the server is shutting down: `reason: "server stopping"`; - the key that opened it is deleted (`reason: "key revoked"`) or changed so it may no longer read this account (`reason: "key changed"`), or the dashboard session that opened it signs out (`reason: "signed out"`). Changes to other keys never end it. Reconnect to follow the account. `EventSource` does this on its own; a WebSocket client should reconnect with a short backoff (a second, doubling to about 30 s). Nothing is lost that matters: a new stream begins with the current status, a fresh `account`, `positions` and `orders` snapshot if you asked for them, and the next ticks. Trade events you missed come first when you reconnect with your last id ([above](#picking-up-where-you-left-off)), then the deals made while the account logged in again, marked `caught_up`, and a `resync`. Only when the account was deleted and added again, or now logs in to another broker account, does the numbering start again: then expect a `resync` for your old id and read the account again. ## Falling behind Streams carry every tick while you keep up. A client that reads slowly (a weak link, a background browser tab) gets the **latest tick per symbol** once it reads again: older ticks of that symbol are dropped, a tick is never delivered after a newer one of the same symbol, and the server never buffers more than 1,024 ticks for one stream. If you need every tick for a study, read quickly and write to disk; a stream is a price feed, not a recording. Trade events are never dropped that way. A stream that falls more than 1,024 trade events behind gets a `resync` event (`"this stream fell behind; read the account again"`) and, with `events=orders`, a fresh `orders` snapshot. Since 0.7.0 the stream says so: a `gap` event before what follows, `{reason, symbols, dropped, from_msc, to_msc}` on the ticks' own clock. `reason` is `behind` (you read too slowly: `symbols` lost `dropped` ticks between `from_msc` and `to_msc`), `reconnect` (the broker link was down) or `fanout` (the server's own fan-out fell behind); for the last two, every symbol of the stream may have missed ticks between your last tick (`from_msc`) and the next (`to_msc`, which follows the gap). Ticks are never replayed, the broker keeps no tick history; a chart can read the candles of that window instead. ```text event: gap data: {"reason":"reconnect","symbols":["XAUUSD"],"dropped":null,"from_msc":1790981170212,"to_msc":1790981191408} ``` `ticks_coalesced` in `GET /api/v1/diagnostics` counts how many ticks were dropped this way across all streams. ## Caps At most **1,024 streams** may be open on one server and **256 per key** (or per dashboard session), SSE and WebSocket together. Past that a new stream answers `429 too_many_requests` with `Retry-After` and a message saying which cap was hit. One stream can carry 200 symbols, 100 bar series and every event type, so this is rarely a constraint for one app; it is there so a reconnect loop gone wrong cannot take the server down. `streams` in `GET /api/v1/diagnostics` shows how many are open and the caps. ## What is not in a tick Ticks have no `time` in seconds (use `time_msc / 1000`), no volume and no flags. Candles carry `tick_volume`; `GET /quotes` carries both `time` and `time_msc`. `GET /ticks` returns the recent ticks the server kept for a symbol, with `time`, `volume` and `flags`: since 0.7.0 from the symbol's first `/ticks` read on (so the first answer is often empty), the newest 1,000 by default (a reconnect starts them again). It is a short look back, not a recording; to keep every tick, write them down from the stream.