WebSocket
Live prices, bars, account changes, pending orders and trade events over one socket.
Every connected account serves a WebSocket alongside its REST endpoints. One socket carries every topic you subscribe to, so a strategy that needs ticks for three symbols plus position updates opens one connection, not four.
wss://api.api2trade.com/v2/{account_id}/ws?api_key=YOUR_API_KEYThe key goes in the query string here
A browser cannot set an X-API-Key header on a WebSocket, so the socket reads
?api_key=. Everything else in this API takes the header — see
Authentication. Treat a URL containing your key like
the key itself.
Subscribing
Send JSON. Every message has an action:
| Action | Fields | Does |
|---|---|---|
subscribe | topic, plus symbol / timeframe where the topic needs them; since on trades | Starts a stream |
unsubscribe | the same fields you subscribed with | Stops it |
list | — | Replies with a subscriptions frame listing what this socket holds |
{ "action": "subscribe", "topic": "prices", "symbol": "EURUSD" }{ "action": "subscribe", "topic": "bars", "symbol": "EURUSD", "timeframe": "M5" }{ "action": "subscribe", "topic": "account" }One socket holds up to 32 subscriptions; past that, subscribe answers with an
error frame until you unsubscribe something.
Topics
| Topic | Needs | Frame type | Sends |
|---|---|---|---|
prices | symbol | tick | Every tick: bid, ask, last, volume and the broker's server time |
bars | symbol, timeframe | bar | Each candle once it has closed |
account | — | account | Balance, equity, margin and free margin |
positions | — | positions | All open positions with live profit |
trades | — | trade, modify | Every executed deal, and every stop-loss / take-profit change on an open position |
orders | — | order | Every step of a pending order: placed, modified, deleted, expired, triggered |
terminal | — | terminal | Health of the connection itself: broker link, trading allowed, server time |
account and positions go out within about 50 ms of a change and at least
once a second. Subscribing to prices or bars for a symbol that is not yet in
Market Watch enables it on demand, so the first few ticks can take a moment to
arrive — POST /SymbolSelect prepares
several symbols at once.
Timeframes
M1, M5, M15, M30, H1, H4, D1, W1, MN1.
Frames you receive
Every frame has a type. The topic frames put the payload in data, and
tick and bar frames repeat the symbol (and timeframe) they belong to, so
one handler can route several subscriptions.
{
"type": "tick",
"symbol": "EURUSD",
"seq": 1042,
"ts": 1762183884120,
"data": {
"symbol": "EURUSD",
"bid": 1.15121,
"ask": 1.15136,
"last": 0,
"volume": 0,
"time": "2026-11-03T17:31:24.118Z"
}
}{ "type": "subscribed", "topic": "prices", "message": "" }type | Meaning |
|---|---|
tick, bar, account, positions, trade, modify, order, terminal | Data — see Topics |
orders | The snapshot an orders subscription opens with — see Pending orders |
subscribed / unsubscribed | Your request was accepted |
subscriptions | The reply to list |
replayed | A since replay is complete — see Catching up |
warning | Frames were dropped for you — see below |
error | The request was rejected; message says why |
Ignore types you do not know. New ones are added from time to time.
seq, ts and snapshots
seqnumbers the live frames of each topic, +1 per frame. A gap means frames were dropped for you.tsis when the frame was sent, in Unix milliseconds UTC. Compare it with your own clock to see how much of a delay is the network.- Snapshots. Right after you subscribe to
account,positions,pricesororders, you get the current state once, marked"snapshot": trueand withoutseq, so you are not blank until the next change. It can arrive after the first live frame.
Times
Times are the broker's server time, written with a Z the way MetaTrader
writes them — not UTC. Fields named …Utc are real UTC: trade, modify and
order frames carry timeUtc next to time, and pending orders carry
expirationUtc. timeUtc is left out until the server's offset is known —
normally from the first second after the connection starts.
GET /ServerTimezone gives the offset.
Dropped frames
If your client reads slower than the market moves, the stream drops frames
rather than queueing without limit, and tells you how many in a warning frame
that names the topic:
{ "type": "warning", "topic": "prices", "symbol": "EURUSD", "dropped": 42, "ts": 1762183884120 }Add dropped up as you go. A non-zero total means your handler is the
bottleneck — the gap is on your side, not a market gap, and a strategy that
assumes it saw every tick would be wrong. trade and order frames are sent
ahead of queued ticks, so a burst of prices does not delay a fill.
Heartbeat
The server sends a WebSocket ping every 5 seconds and closes a socket that has sent nothing back for 30 seconds. Every WebSocket library answers pings on its own, so you only notice this if your client stops reading its socket.
Trade events
The trades topic sends a trade frame for every executed deal — your own
orders, orders placed in MetaTrader or by another tool, stop-loss and
take-profit hits:
{
"type": "trade",
"seq": 18,
"ts": 1762183205131,
"data": {
"deal": 52211873,
"order": 61523348,
"position": 61523348,
"symbol": "EURUSD",
"type": "Buy",
"entry": "In",
"volume": 0.1,
"price": 1.15172,
"sl": 1.149,
"tp": 1.156,
"positionVolume": 0.1,
"profit": 0,
"commission": -0.35,
"swap": 0,
"magic": 12345,
"comment": "copy-7f3a",
"time": "2026-11-03T17:20:05.118Z",
"timeUtc": "2026-11-03T15:20:05.118Z",
"degraded": false,
"remainderTicket": 0,
"remainderOf": 0
}
}| Field | Meaning |
|---|---|
entry | In opens or adds, Out closes, InOut reverses, OutBy closes by an opposite position |
position | The position the deal belongs to — the same id in /OrderHistory and /PositionHistory |
positionVolume | Lots still open in the position after this deal; -1 when unknown |
sl, tp | The position's stops after this deal |
degraded | true when the deal was reported before its full record was available — check it against /OrderHistory |
remainderTicket, remainderOf | MT4 only — see MT4 vs MT5 |
A modify frame on the same topic (sharing its seq) reports a new stop-loss or
take-profit on an open position: position, symbol, type, volume,
price, the new sl and tp, magic, comment, time and timeUtc.
Catching up after a reconnect
Add since to the trades subscription — a server time as the frames print it,
usually the last time you saw:
{ "action": "subscribe", "topic": "trades", "since": "2026-11-03T17:20:05.118Z" }You first get the deals at or after that moment as trade frames marked
"replay": true (no seq, oldest first), then a replayed frame, then the live
frames:
{ "type": "replayed", "topic": "trades", "count": 3, "truncated": false }sincereaches back at most 24 hours, and the replay holds the newest 1000 deals;truncated: truemeans there were more — fetch the rest from/OrderHistory.- Nothing falls between the replay and the live frames, but a deal right at the
switch-over can arrive twice. Deduplicate on
deal(on MT4:orderplusentry). sinceonly applies totrades; on any other topic it is anerror.
Pending orders
The orders topic opens with an orders snapshot — the same rows as
GET /PendingOrders — then sends an order
frame for every step of a pending order's life:
{
"type": "order",
"seq": 4,
"ts": 1762183300412,
"data": {
"event": "placed",
"ticket": 61523390,
"symbol": "EURUSD",
"type": "BuyLimit",
"volumeInitial": 0.1,
"volume": 0.1,
"price": 1.148,
"stopLimitPrice": 0,
"sl": 1.145,
"tp": 1.155,
"expirationMode": "specified",
"expiration": "2026-11-03T20:00:00.000Z",
"expirationUtc": "2026-11-03T18:00:00.000Z",
"magic": 12345,
"comment": "",
"time": "2026-11-03T17:21:40.002Z",
"timeUtc": "2026-11-03T15:21:40.002Z",
"position": 0
}
}event | Meaning |
|---|---|
placed | A new pending order |
modified | Price, stops or expiry changed |
deleted | Cancelled |
expired | Its expiry passed |
triggered | It filled; position is the position the fill opened or added to (MT4: the order's ticket) |
The fill itself also arrives as a trade frame on the trades topic.
A minimal client
import WebSocket from 'ws'
const ACCOUNT = 'your-account-uuid'
const KEY = process.env.API2TRADE_API_KEY
const ws = new WebSocket(
`wss://api.api2trade.com/v2/${ACCOUNT}/ws?api_key=${KEY}`
)
ws.on('open', () => {
ws.send(JSON.stringify({ action: 'subscribe', topic: 'prices', symbol: 'EURUSD' }))
})
let dropped = 0
ws.on('message', (raw) => {
const msg = JSON.parse(raw)
if (msg.type === 'warning' && msg.dropped) dropped += msg.dropped
if (msg.type === 'tick') {
console.log(msg.symbol, msg.data.bid, msg.data.ask)
}
})
// 1006 with no close frame is usually a rejected key or a connection that
// went away; reconnect with backoff rather than in a tight loop.
ws.on('close', (code) => console.log('closed', code, 'dropped so far:', dropped))import json, os
from websockets.sync.client import connect
ACCOUNT = "your-account-uuid"
KEY = os.environ["API2TRADE_API_KEY"]
with connect(f"wss://api.api2trade.com/v2/{ACCOUNT}/ws?api_key={KEY}") as ws:
ws.send(json.dumps({"action": "subscribe", "topic": "prices", "symbol": "EURUSD"}))
for raw in ws:
msg = json.loads(raw)
if msg.get("type") == "tick":
print(msg["symbol"], msg["data"]["bid"], msg["data"]["ask"])Trying it without writing code
Every connected account has a tester built into the dashboard — pick the account
on the API Playground page and the socket panel subscribes, unsubscribes and
shows the frames as they arrive. Each account also has its own tester at
/v2/{account_id}/ws-tester.
The stream only speaks once the connection is logged in
A connection that has not logged in to your broker answers HTTP and accepts
socket subscriptions, but has nothing to publish. If a stream stays silent,
check GET /status first: broker.connected and account.loggedIn both have
to be true.