# API2Trade — API v2 documentation
Everything about API v2 in one file: guides, then the Account API and Trading API reference.
Index of all pages: https://docs.api2trade.com/llms.txt — API v1 (Legacy, switched off on 31 December 2026) is listed there and left out here.
---
# Introduction
Source: https://docs.api2trade.com/docs
> Api2Trade API Documentation
**Api2Trade** is a next-generation API provider for traders, developers, and projects working with MT4 or MT5.
With our API, you don’t need to keep MetaTrader open or running.
API2Trade is a technical SaaS API infrastructure provider for MetaTrader 4 and MetaTrader 5 connectivity. We provide REST API and WebSocket access that allows developers, SaaS platforms, AI trading bot builders, signal providers, and automation tools to connect to users’ own MT4/MT5 trading accounts.
We are not a broker, investment platform, financial adviser, or asset manager. We do not hold client funds, provide trading recommendations, manage user accounts, or execute trades on behalf of customers. API2Trade only provides the technical API layer that enables users and businesses to integrate their existing MetaTrader accounts with their own software systems.
## Two APIs
**API v2** is current. Each connected account gets its own dedicated
connection, its own endpoint, and a WebSocket for live prices, positions and trade
events. Start here.
**API v1** is the Legacy API. **It will be switched off on 31 December 2026**;
until then it keeps working unchanged.
[Migrating to API v2](/docs/migrate-to-v2) shows how to move your accounts.
## Get started
---
# Quickstart
Source: https://docs.api2trade.com/docs/quickstart
> From an API key to live quotes in four steps.
Everything below uses one credential: your team's API key, which you can copy
from **Settings** in the [dashboard](https://app.api2trade.com/dashboard/general).
```bash
export API2TRADE_API_KEY="your-key"
```
## 1. Connect a trading account
Give the API your MetaTrader credentials and the server name exactly as your
broker writes it in the account details email.
```bash
curl -X POST \
-H "X-API-Key: $API2TRADE_API_KEY" \
-H 'content-type: application/json' \
-d '{
"accountNumber": "1082118",
"name": "Demo one",
"type": "Metatrader 5",
"accountPassword": "your-mt-password",
"accountServerHost": "ICMarketsEU-Demo"
}' \
'https://api.api2trade.com/v2/accounts'
```
The response comes back immediately with `"terminalStatus": "provisioning"` and
the account's `id` — a UUID. Every call from here on uses it.
The dashboard does the same thing: **Accounts → Add Account → API v2**. The
[API Playground](https://app.api2trade.com/dashboard/playground) then lets you
try every endpoint on this page without writing any code, and shows the
matching `curl` for each one.
## 2. Wait for it to come up
A dedicated connection is set up for your account and logs in to your broker.
That takes a few minutes. Poll until it settles:
```bash
curl -s -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/accounts/YOUR_ACCOUNT_ID' \
| grep -o '"terminalStatus":"[^"]*"'
```
`ready` means it is logged in and serving. `error` means it will not come up on
its own, and `terminalLastError` says why — usually a wrong account number,
password or server name. See [Errors](/docs/api-v2/errors).
## 3. Call the account's own API
Each connected account gets its own base URL:
```
https://api.api2trade.com/v2/{account_id}/
```
```bash title="Is it actually trading-ready?"
curl -s -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/YOUR_ACCOUNT_ID/status'
```
Check `broker.connected` and `account.loggedIn` before trusting any numbers —
a connection that never logged in still answers `200`, with zeros.
```bash title="A quote"
curl -s -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/YOUR_ACCOUNT_ID/getQuote?symbol=EURUSD'
```
```bash title="Balance and equity"
curl -s -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/YOUR_ACCOUNT_ID/AccountSummary'
```
The full list is under [Trading API](/docs/api-v2/trading-api/system).
## 4. Stream instead of polling
Quotes, positions and trade events are all available on one socket, which is
cheaper and faster than polling `getQuote` in a loop:
```
wss://api.api2trade.com/v2/{account_id}/ws?api_key=YOUR_API_KEY
```
```json
{ "action": "subscribe", "topic": "prices", "symbol": "EURUSD" }
```
See [WebSocket](/docs/api-v2/websocket) for every topic and the frame shapes.
## What next
---
# Authentication
Source: https://docs.api2trade.com/docs/authentication
> One API key for everything, and where each API expects it.
Every API2Trade API authenticates with your team's **API key**, which you copy
from **Settings** in the [dashboard](https://app.api2trade.com/dashboard/general).
One key covers the Account API, every connected account's Trading API, and the
WebSocket stream.
```http
X-API-Key: YOUR_API_KEY
```
Generating a new key in Settings invalidates the old one immediately, and
every v2 account reconnects with the new one — unreachable for about a minute
while its connection restarts. Positions at your broker are untouched. Update
your own code before you rotate.
## API v2
The key goes in the `X-API-Key` **header**, and the account is part of the
**path**.
```bash title="Account API — your team's accounts"
curl -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/accounts'
```
```bash title="Trading API — one account"
curl -H "X-API-Key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/v2/{account_id}/AccountSummary'
```
The `account_id` in the path is **routing, not authentication**: the key still
has to have access to that account, or the answer is `401`.
### The WebSocket is the one exception
A browser cannot set a header on a WebSocket, so the socket reads the key from
the query string:
```
wss://api.api2trade.com/v2/{account_id}/ws?api_key=YOUR_API_KEY
```
Treat a URL containing your key as the key itself — it lands in shell histories
and server logs the way a header does not.
## API v1 (Legacy)
The Legacy API will be switched off on 31 December 2026 — see
[Migrating to API v2](/docs/migrate-to-v2).
The legacy API takes the same key in the same header, but identifies the account
with an `id` **query parameter** rather than a path segment:
```bash
curl -H "x-api-key: $API2TRADE_API_KEY" \
'https://api.api2trade.com/AccountSummary?id=YOUR_ACCOUNT_UUID'
```
Accounts are connected either in the dashboard or through `/RegisterAccount`,
described in the [MetaTrader 5](/docs/api-v1/metatrader-5-api/connection) and
[MetaTrader 4](/docs/api-v1/metatrader-4-api/connection) sections.
## At a glance
| | Credential | Where | Account identified by |
| ---------------- | ---------- | ------------------ | --------------------------- |
| **v2 REST** | API key | `X-API-Key` header | path: `/v2/{account_id}/…` |
| **v2 WebSocket** | API key | `?api_key=` query | path: `/v2/{account_id}/ws` |
| **v1 REST** | API key | `x-api-key` header | query: `?id={uuid}` |
---
# AI coding agents
Source: https://docs.api2trade.com/docs/ai-agents
> Give Claude Code, Cursor, Copilot and other coding agents the docs in a form they read well.
Coding agents write better integrations when they read the real documentation
instead of guessing from what they saw in training. These docs are published in
formats made for them.
## Docs for agents
| URL | What it is |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| [`/llms.txt`](/llms.txt) | An index of every page with a link to its Markdown version, in the [llms.txt](https://llmstxt.org) format |
| [`/llms-full.txt`](/llms-full.txt) | All of API v2 in one Markdown file — guides plus the full Account API and Trading API reference |
| `/docs/.mdx` | Any page as Markdown: append `.mdx` to its address, e.g. [`/docs/quickstart.mdx`](/docs/quickstart.mdx) |
| [`api.api2trade.com/v2/openapi.json`](https://api.api2trade.com/v2/openapi.json) | OpenAPI spec of the Account API |
| [`/openapi/trading-api-mt5.json`](/openapi/trading-api-mt5.json) | OpenAPI spec of the Trading API — the same endpoints for [MT4](/openapi/trading-api-mt4.json) |
Every page also has a **Copy Markdown** button below its title, and an
**Open in** menu that hands the page to ChatGPT or Claude.
## Point your agent at them
Most agents can read a URL. Give yours this one and ask it to read it before
writing any code against the API:
```
https://docs.api2trade.com/llms-full.txt
```
For agents that take standing instructions from a file in your repository —
`AGENTS.md` (Codex, Copilot, Cursor and others), `CLAUDE.md` (Claude Code) or
your editor's rules file — add the brief below.
## A brief for your repository
The things agents most often get wrong with this API, in a form you can paste
as it is:
```md title="AGENTS.md"
## API2Trade (MetaTrader 4/5 API)
Docs: https://docs.api2trade.com/llms-full.txt — read them before writing API code.
- Use API v2 only. API v1 (Legacy: /RegisterAccount, the ?id= query parameter)
is switched off on 31 December 2026.
- Every REST request sends the header `X-API-Key`. Read the key from the
environment variable API2TRADE_API_KEY; never hard-code or log it.
- Connecting an account: POST https://api.api2trade.com/v2/accounts with
accountNumber, name, type ("Metatrader 4" | "Metatrader 5"), accountPassword
and accountServerHost (the server name exactly as the broker writes it).
It returns at once with terminalStatus "provisioning". Poll
GET /v2/accounts/{id} until terminalStatus is "ready" — or "error", where
terminalLastError says why; do not retry the same credentials.
- Each account has its own base URL: https://api.api2trade.com/v2/{account_id}/
(e.g. GET AccountSummary, GET getQuote?symbol=EURUSD, POST OrderSend with a
JSON body). MT4 and MT5 accounts have the same endpoints.
- Before trusting balances or quotes, check GET /status: broker.connected and
account.loggedIn must both be true. An account that has not logged in still
answers 200 — with zeros.
- Live data: one WebSocket per account,
wss://api.api2trade.com/v2/{account_id}/ws?api_key= — the only place the
key goes in a URL. Send {"action":"subscribe","topic":"prices","symbol":"EURUSD"};
topics: prices, bars (with timeframe M1…MN1), account, positions, trades,
orders, terminal. Frames are typed tick, bar, account, positions, trade,
modify, order, terminal; ignore unknown types. Add up `dropped` from "warning"
frames; reconnect with backoff, resubscribing to trades with
"since": to replay what you missed.
- Errors are JSON {"error": CODE, "message": text}. Branch on `error`, never on
`message`. 401 is a wrong key, 403 means your plan's account limit is
reached, 404 means no such account or no access, 429 means too many different
accounts connected recently. Retry reads on 503 and 504 with backoff.
- Orders: send every POST OrderSend with a unique clientOrderId and reuse it on
retries — a repeat never places a second order (needs bridge.version 0.17.0+
on MT5 / 0.15.0+ on MT4 in GET /status; older versions ignore the id). Never
resend an order after a 504 MRPC_TRADE_OUTCOME_UNKNOWN without that id. A 200
only means the broker answered; check `success` and `retcode`.
```
Agents follow a short brief more reliably than a long one. For everything
else, let them read the docs — that is what the Markdown versions are for.
---
# Migrating to API v2
Source: https://docs.api2trade.com/docs/migrate-to-v2
> The Legacy API is switched off on 31 December 2026. What changes, and how to move an account.
API v2 replaces the Legacy API, documented here as API v1.
**The Legacy API will be switched off on 31 December 2026.** Until then, accounts
on it keep running unchanged, but each one has to be on API v2 by that date.
An account you add on the Legacy API today has to be moved again before
31 December. Choose **API v2** when you add it.
## What changes
| | Legacy API (v1) | API v2 |
| ---------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------ |
| Base URL | `https://api.api2trade.com/`, the same for every account | `https://api.api2trade.com/v2/{account_id}/`, one per account |
| Account identified by | `?id=` query parameter | the path |
| API key | `x-api-key` header | `X-API-Key` header — the same key |
| Placing, modifying, closing orders | `GET` with query parameters | `POST` with a JSON body |
| Live data | polling | [WebSocket](/docs/api-v2/websocket) |
| Connecting accounts | `RegisterAccount`, `GetAccounts`, `DeleteAccount` | [Account API](/docs/api-v2/account-api/accounts) at `/v2/accounts` |
| Time to connect | seconds | a few minutes |
| MT4 and MT5 | different endpoints | [the same endpoints](/docs/api-v2/platforms) |
## Moving an account
1. **Check the calls you use** against the [table below](#endpoint-by-endpoint).
A few Legacy calls have no v2 equivalent.
2. **Remove the account** from the Legacy API — in the dashboard under
**Accounts**, or with `DeleteAccount`. Its slot is free again immediately.
3. **Add it on API v2** — in the dashboard with **Add Account → API v2**, or with
`POST /v2/accounts` as in the [Quickstart](/docs/quickstart). It takes the
same slot.
4. **Wait for `ready`.** The account shows as `provisioning` for a few minutes
while it logs in to your broker. If the broker rejects the login,
`terminalLastError` says why.
5. **Point your code at the new base URL.** The account has a new ID, so its URL
is new as well.
Between removing the account and v2 reporting `ready`, the account answers on
neither API. Move it at a time when your software can pause for a few minutes.
## Endpoint by endpoint
API v2's Trading API has the same endpoints on MT4 and MT5, so one table covers both; some
of the Legacy names existed on only one platform. Order calls move from `GET`
with query parameters to `POST` with a JSON body, and their fields are
camelCase — `stopLoss`, `takeProfit`, `volume`.
| Legacy API (v1) | API v2 | Notes |
| ------------------------------------------------------------------------------ | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AccountSummary` | `AccountSummary` | |
| `AccountDetails`, `Account` | `AccountInfo` | |
| `CheckConnect`, `Ping` | `status` | Always `200` — read `broker.connected` and `account.loggedIn` |
| `GetQuote`, `Quote` | `getQuote` | |
| `GetQuoteMany`, `MarketWatchMany` | WebSocket topic `prices` | Or one `getQuote` per symbol |
| `Symbols`, `SymbolList` | `symbols` | Names only |
| `SymbolParams`, `SymbolParamsMany` | `SymbolInfo` | `symbols=EURUSD,GBPUSD` for up to 100 in one call |
| `SymbolSessions` | `SymbolInfo` | In `sessions` |
| `TickValueWithSize`, `GetTickValueMany` | `SymbolInfo`, `OrderCalcProfit` | `tickValue` is in `SymbolInfo` |
| `RequiredMargin` | `OrderCalcMargin` | |
| `OpenedOrders`, `OpenedOrder`, `OpenedOrdersTickets` | `OpenedOrders` | One list of positions and pending orders |
| — | `PendingOrders` | New: the pending orders alone, with expiry and initial volume |
| `OrderSend` | `OrderSend` | A `200` only means MetaTrader answered — check `success` and `retcode` |
| `OrderModify` | `OrderModify` | |
| `OrderClose` | `OrderClose` | `volume` instead of `lots`; also deletes pending orders |
| `OrderDelete` | `OrderClose` | With the pending order's ticket |
| — | `CloseAll` | New: closes every position in one call |
| — | `SymbolSelect` | New: prepares up to 100 symbols for trading in one call |
| `OrderHistory`, `ClosedOrders`, `OrderHistoryPagination` | `OrderHistory` | Deals in a `from`–`to` range, not paged; `stopLoss`/`takeProfit` are `sl`/`tp` — see [stop-loss in the history](/docs/api-v2/platforms#stop-loss-and-take-profit-in-the-history) |
| `HistoryPositions`, `HistoryPositionsByCloseTime` | `PositionHistory` | Closed round trips in a `from`–`to` range, `sl`/`tp` as at close |
| `HistoryDealsByPositionId` | `OrderHistory` | Filter on `position` |
| `PriceHistory` and its `…Ex`, `…Today`, `…Month`, `…HighLow`, `…Many` variants | `PriceHistory` | One symbol per call, `from`–`to` range, `timeframe` |
| `QuoteHistory`, `QuoteHistoryMany`, `RequestQuoteHistory` | `PriceHistory` | `from`–`to` instead of `from` + `count` |
| `ServerTimezone` | `ServerTimezone` | |
| `RegisterAccount`, `GetAccounts`, `DeleteAccount` | [Account API](/docs/api-v2/account-api/accounts) | `POST`, `GET` and `DELETE` on `/v2/accounts` |
### Not available on API v2
* **Trade statistics:** `TradeStats`, `TradeStatsEquityHistory`, `EquityHistory`
* **Broker mail:** `Mails`
* **Session checks:** `IsTradeSession`, `IsQuoteSession` and their `…Many`
variants — the session windows themselves are in `SymbolInfo`
* **Pending order history:** `PendingOrderHistory` — `OrderHistory` only lists
orders that were filled. Active pending orders are in `PendingOrders`, and the
WebSocket topic `orders` reports each one being placed, changed, deleted,
expired or filled
* **MT4 extras:** `OrderCloseBy`, `Groups`, `IsInvestor`, `TradeRightsMany`
* **Broker server lookup:** `Search`, `LoadServersDat`, `LoadServersIni`,
`LoadSrv`, `PingHost`, `PingHostMany` — v2 takes the server name exactly as
your broker writes it
If your integration depends on one of these, [contact us](https://t.me/noblemindsmedia)
before you move it.
---
# Accounts
Source: https://docs.api2trade.com/docs/api-v2/account-api/accounts
Connect, inspect and disconnect MetaTrader accounts. Each connected account then gets its own trading API, documented separately.
Base URL: `https://api.api2trade.com`
### GET /v2/accounts
**List trading accounts**
Every trading account on the team, newest first — on API v2 and on the Legacy API. Accounts on API v2 also carry the links to their own API, Swagger page and WebSocket tester.
Responses:
- `200` — array of V2AccountOut
Response fields (200):
- `id` (string, required)
- `accountNumber` (string, required)
- `accountServerHost` (string, required)
- `name` (string, required)
- `status` (string, required)
- `type` (string, required)
- `statusMessage` (string, required)
- `createdAt` (string, required)
- `updatedAt` (string, required)
- `provisioner` (string, required)
- `terminalStatus` (string, required)
- `terminalLastError` (string, required)
- `suspended` (boolean, required)
- `suspendedAt` (string, required)
- `apiBaseUrl` (string)
- `swaggerUrl` (string)
- `wsTesterUrl` (string)
### POST /v2/accounts
**Connect a new trading account**
Sets up a dedicated connection for the credentials given. Returns straight away with `terminalStatus: provisioning` — logging in to the broker takes a few minutes. Poll the account until `terminalStatus` is `ready`, or `error` with the reason in `terminalLastError`.
The server name must match your broker's exactly, as written in the account details email.
Request body (JSON, V2AccountInRequest):
- `accountNumber` (string, required)
- `name` (string, required)
- `type` ("Metatrader 4" | "Metatrader 5", required): * `Metatrader 4` - Metatrader 4 * `Metatrader 5` - Metatrader 5
- `accountPassword` (string, required)
- `accountServerHost` (string, required)
Responses:
- `201` — V2AccountOut
- `400`: Invalid request body — V2Error
- `403`: No account slot free — V2Error
- `429`: Too many different accounts connected on these slots recently. Reconnecting an account you already used does not count. — V2Error
- `503`: API v2 unavailable — V2Error
Response fields (201):
- `id` (string, required)
- `accountNumber` (string, required)
- `accountServerHost` (string, required)
- `name` (string, required)
- `status` (string, required)
- `type` (string, required)
- `statusMessage` (string, required)
- `createdAt` (string, required)
- `updatedAt` (string, required)
- `provisioner` (string, required)
- `terminalStatus` (string, required)
- `terminalLastError` (string, required)
- `suspended` (boolean, required)
- `suspendedAt` (string, required)
- `apiBaseUrl` (string)
- `swaggerUrl` (string)
- `wsTesterUrl` (string)
### GET /v2/accounts/{account_id}
**Fetch one trading account**
Parameters:
- `account_id` (path, string (uuid), required)
Responses:
- `200` — V2AccountOut
- `404`: No such account, or no access to it — V2Error
Response fields (200):
- `id` (string, required)
- `accountNumber` (string, required)
- `accountServerHost` (string, required)
- `name` (string, required)
- `status` (string, required)
- `type` (string, required)
- `statusMessage` (string, required)
- `createdAt` (string, required)
- `updatedAt` (string, required)
- `provisioner` (string, required)
- `terminalStatus` (string, required)
- `terminalLastError` (string, required)
- `suspended` (boolean, required)
- `suspendedAt` (string, required)
- `apiBaseUrl` (string)
- `swaggerUrl` (string)
- `wsTesterUrl` (string)
### DELETE /v2/accounts/{account_id}
**Disconnect and remove a trading account**
Disconnects the account and deletes it. This frees the slot immediately. It cannot be undone — reconnecting means providing the credentials again.
Parameters:
- `account_id` (path, string (uuid), required)
Responses:
- `204`: Removed
- `404`: No such account, or no access to it — V2Error
---
# System
Source: https://docs.api2trade.com/docs/api-v2/trading-api/system
Is the connection alive, connected to the broker, and logged in?
Base URL: `https://api.api2trade.com/v2/{account_id}`
### GET /status
**Health of this account's connection.**
Is the connection alive, connected to the broker, and is the trading
account logged in? **Always returns HTTP 200** (even when the
connection is down) — the failure detail is in the body. Read the
top-level `status` field: `ready`, `starting` (logged in, still
syncing), `degraded` (connection up but broker/login down), or `down`
(connection not answering). Uptime monitors that need an HTTP status
code instead can use the open `/healthz` (fully ready) and `/livez`
(answering at all) endpoints.
Responses:
- `200`: Health snapshot — inspect the `status` field. — StatusResponse
Response fields (200):
- `account` (AccountHealth, required)
- `bridge` (BridgeHealth, required)
- `broker` (BrokerHealth, required)
- `serverTime` (string, required): Broker server time (ISO-8601). Empty when the connection is down.
- `status` (string, required)
- `terminal` (TerminalHealth, required)
---
# Account
Source: https://docs.api2trade.com/docs/api-v2/trading-api/account
Account state, open trades, deal history.
Base URL: `https://api.api2trade.com/v2/{account_id}`
### GET /AccountInfo
**Static identity and configuration of the connected account.**
The account's *who and how* — name, login, broker company/server,
currency, leverage, account type, **margin mode** (netting/hedging/
exchange), stop-out configuration, and trade permissions. These rarely
change. For the live balance/equity/margin figures use
`/AccountSummary` instead; for whether the account is logged in at all,
use `/status`.
Responses:
- `200`: Account identity + configuration. — AccountInfoData
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `company` (string, required): Broker company name.
- `currency` (string, required)
- `currencyDigits` (integer (int64), required): Decimal places for money values in this account's currency.
- `fifoClose` (boolean, required): Positions must be closed FIFO (US-style).
- `leverage` (integer (int64), required): Account leverage, e.g. `200` for 1:200.
- `limitOrders` (integer (int64), required): Max simultaneously-active pending orders (`0` = unlimited).
- `login` (integer (int64), required): MT5 account number.
- `marginCallLevel` (number (double), required): Margin-call level (in `marginSoMode` units).
- `marginMode` (string, required): Position accounting: `Netting`, `Hedging`, or `Exchange`. Decides whether an opposite order nets an existing position or opens a new one — clients running trade logic need this.
- `marginSoMode` (string, required): Stop-out trigger basis: `Percent` (of margin level) or `Money`.
- `name` (string, required): Account holder name.
- `server` (string, required): Broker server, e.g. `TegasFX-Main-UK`.
- `stopOutLevel` (number (double), required): Stop-out level (in `marginSoMode` units).
- `tradeAllowed` (boolean, required): Trading permitted for this account (broker-side flag).
- `tradeExpert` (boolean, required): Automated trading (Expert Advisors) permitted for this account.
- `type` (string, required): `Demo`, `Real`, or `Contest`.
### GET /AccountSummary
**Snapshot of the connected trading account.**
Returns the current balance, equity, margin, free margin, floating
profit, leverage, account currency, broker name, server name, and
trade-allowed flags. Reflects broker-side state at call time — no
caching.
Responses:
- `200`: Live account snapshot. — AccountSummaryData
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `balance` (number (double), required)
- `credit` (number (double), required)
- `currency` (string, required)
- `equity` (number (double), required)
- `freeMargin` (number (double), required)
- `leverage` (integer (int64), required)
- `margin` (number (double), required)
- `marginLevel` (number (double), required)
- `profit` (number (double), required)
- `type` (string, required)
### GET /OpenedOrders
**All open positions and active pending orders.**
Returns one row per position (already-filled trade) and one row per
pending order (limit / stop / stop-limit). Each row carries `ticket`,
`symbol`, `type` (`Buy`/`Sell`/`BuyLimit`/…), `volume` (lots), open
price, current price, SL/TP, swap, floating profit, comment, and
magic number. Pending orders show their trigger price in the open-
price field.
Responses:
- `200`: Open positions plus active pending orders. — array of OpenedOrder
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `comment` (string, required)
- `currentPrice` (number (double), required)
- `kind` (string, required)
- `lots` (number (double), required)
- `magic` (integer (int64), required)
- `openPrice` (number (double), required)
- `openTime` (string, required)
- `profit` (number (double), required)
- `stopLoss` (number (double), required)
- `swap` (number (double), required)
- `symbol` (string, required)
- `takeProfit` (number (double), required)
- `ticket` (integer (int64), required)
- `type` (string, required)
### GET /OrderHistory
**Closed deals in a time range.**
Returns DEAL entries (executions), not ORDER entries — pending
orders that never filled don't appear here. Each row has `ticket`,
`position` (the id shared by a round-trip's `In`/`Out` rows — the
join key to the WS `trade` events and `/PositionHistory`), `symbol`,
`type` (`Buy`/`Sell`), `volume`, `price`, `sl`/`tp`, `profit`,
`commission`, `swap`, `magic`, `comment`, and the deal `time`. Omit
both bounds to fetch all-time history.
Parameters:
- `from` (query, string): Inclusive lower bound (broker server time). Accepts ISO-8601 (`2026-01-01T00:00:00Z`) or `YYYY-MM-DD`. Empty/absent → epoch.
- `to` (query, string): Inclusive upper bound (broker server time). Same formats as `from`. Empty/absent → now.
Responses:
- `200`: Closed deals executed in the requested window. — array of HistoryTrade
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `comment` (string, required)
- `commission` (number (double), required)
- `entry` (string, required)
- `magic` (integer (int64), required)
- `order` (integer (int64), required)
- `position` (integer (int64), required): `DEAL_POSITION_ID` — the join key linking this deal to its position (`In` and `Out` rows of one round-trip share it, and it matches the WS `trade` event's `position` and `/PositionHistory.positionId`). Exit deals carry no magic/comment (MT5 semantics), so this is the only REST-side correlation carrier on closes.
- `price` (number (double), required)
- `profit` (number (double), required)
- `sl` (number (double), required): Stop Loss (`0` = none). Entry deals carry the opening order's level, exit deals the position's level when it closed (`DEAL_SL`).
- `swap` (number (double), required)
- `symbol` (string, required)
- `ticket` (integer (int64), required)
- `time` (string, required)
- `tp` (number (double), required): Take Profit on this row (`0` = none).
- `type` (string, required)
- `volume` (number (double), required)
### GET /PendingOrders
**Active pending orders, with their expiry.**
The pending rows of `/OpenedOrders` plus what copying an order needs:
the stop-limit price, initial and remaining volume, and the expiry —
its kind, server time and real UTC. The `orders` WebSocket topic
opens with the same rows, then reports every change as an `order`
event.
Responses:
- `200`: Active pending orders. — array of PendingOrder
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `comment` (string, required)
- `expiration` (string, required): When it expires, broker server time like every other time here; empty when it does not.
- `expirationMode` (string, required): `gtc`, `day`, `specified` or `specifiedDay` (see `/SymbolInfo` `expirationModes`).
- `expirationUtc` (string, required): The same moment in real UTC — comparable across brokers.
- `magic` (integer (int64), required)
- `price` (number (double), required): The price it triggers at.
- `sl` (number (double), required)
- `stopLimitPrice` (number (double), required): The limit price a stop-limit order turns into; 0 otherwise.
- `symbol` (string, required)
- `ticket` (integer (int64), required)
- `time` (string, required): When it was placed, broker server time.
- `timeUtc` (string): `time` in real UTC, converted with the server's current offset; absent until that offset is known (the connection's first second) and when `time` is empty.
- `tp` (number (double), required)
- `type` (string, required): `BuyLimit`, `SellLimit`, `BuyStop`, `SellStop`, `BuyStopLimit` or `SellStopLimit`.
- `volume` (number (double), required): Lots still to fill.
- `volumeInitial` (number (double), required): Lots when placed.
### GET /PositionHistory
**Closed trades (round-trip positions) in a time window.**
Unlike `/OrderHistory` — which is the raw *deal* log (one row per
execution, two per round-trip) — this returns **one row per closed
position**, the view a trading-history screen wants: `positionId`,
`symbol`, `type` (`Buy`/`Sell`), `volume`, open/close price + time,
`sl`/`tp` (the levels the position carried when it closed), and
P/L split into `profit` (gross), `swap`, `commission`, and `netProfit`
(the sum — what hit the balance). Reconstructed by grouping deals on
the MT5 position id, so a position opened before `from` but closed
inside the window is still returned complete. Deposits/withdrawals are
excluded. The window filters on the *close* time; omit both bounds for
all-time.
Parameters:
- `from` (query, string): Inclusive lower bound (broker server time). Accepts ISO-8601 (`2026-01-01T00:00:00Z`) or `YYYY-MM-DD`. Empty/absent → epoch.
- `to` (query, string): Inclusive upper bound (broker server time). Same formats as `from`. Empty/absent → now.
Responses:
- `200`: Closed round-trip positions in the window. — array of PositionTrade
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `closePrice` (number (double), required)
- `closeTime` (string, required)
- `comment` (string, required)
- `commission` (number (double), required)
- `magic` (integer (int64), required)
- `netProfit` (number (double), required): `profit + swap + commission` — the net effect on the balance.
- `openPrice` (number (double), required)
- `openTime` (string, required)
- `positionId` (integer (int64), required)
- `profit` (number (double), required): Gross price profit (sum of the position's deal profits).
- `sl` (number (double), required): Stop Loss the position carried when it closed (`0` = none).
- `swap` (number (double), required)
- `symbol` (string, required)
- `tp` (number (double), required): Take Profit the position carried when it closed (`0` = none).
- `type` (string, required)
- `volume` (number (double), required): Volume opened (lots).
### GET /ServerTimezone
**Broker server time and its offset from UTC.**
Returns `serverTime` (ISO-8601 in broker server time — the trailing
`Z` is stylistic, matching the rest of the API) and
`utcOffsetSeconds`, computed as `TimeTradeServer() - TimeGMT()`. Use
the offset to translate any of the other endpoints' `Z`-labelled
timestamps to real UTC: `utc = serverTime - utcOffsetSeconds`.
Common values: `0` for a UTC broker, `7200` for a UTC+2 broker,
`10800` during summer (UTC+3). Most MetaTrader brokers run on EET
(UTC+2 / UTC+3 with DST).
Responses:
- `200`: Broker server clock and UTC offset. — ServerTimezoneData
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `serverTime` (string, required)
- `utcOffsetSeconds` (integer (int64), required)
---
# Market
Source: https://docs.api2trade.com/docs/api-v2/trading-api/market
Quotes, OHLC bars, symbol contract specs.
Base URL: `https://api.api2trade.com/v2/{account_id}`
### GET /PriceHistory
**OHLC bars for a symbol and timeframe.**
Returns one candle per bar in the requested window. Fields:
`time` (bar open, server time), `open`, `high`, `low`, `close`,
`tickVolume`, `realVolume`, `spread`.
MT5 fetches missing history from the broker on demand, so wide
ranges on small timeframes can take several seconds. An empty
response is normal when the requested window predates the broker's
retained history or covers a closed market.
Parameters:
- `symbol` (query, string, required): Symbol name as listed by `/symbols` (e.g. `EURUSD`).
- `timeframe` (query, string, required): Bar timeframe. MT5 labels (`M1`, `M5`, `M15`, `M30`, `H1`, `H4`, `D1`, `W1`, `MN1`) or human forms (`5min`, `1h`, `1d`).
- `from` (query, string): Inclusive lower bound (broker server time). ISO-8601 or `YYYY-MM-DD`. Empty/absent → epoch.
- `to` (query, string): Inclusive upper bound (broker server time). Same formats as `from`. Empty/absent → now.
Responses:
- `200`: OHLC bars covering the requested window. — array of Candle
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `close` (number (double), required)
- `high` (number (double), required)
- `low` (number (double), required)
- `open` (number (double), required)
- `realVolume` (integer (int64), required)
- `spread` (integer (int64), required)
- `tickVolume` (integer (int64), required)
- `time` (string, required)
### GET /SymbolInfo
**Contract specification for a symbol.**
Returns broker-side contract specs: `digits`, `point`, `spread`,
`contractSize`, `tickSize`, `tickValue`, swap rates,
`volumeMin` / `volumeMax` / `volumeStep`, `tradeMode`, base/quote/
profit currencies. Call this before `/OrderSend` to validate
volumes and round prices to the right precision.
With `symbols=A,B,C` instead of `symbol` it answers for all of them
in one call — `{symbols: [...], errors: [{symbol, error, message}]}`
— and puts them all into Market Watch first, like `/SymbolSelect`.
Parameters:
- `symbol` (query, string): Symbol name as listed by `/symbols` (e.g. `EURUSD`).
- `symbols` (query, string): Several symbols, comma-separated (`EURUSD,GBPUSD`), instead of `symbol` — at most 100. The reply is then a `SymbolInfoBulk`.
Responses:
- `200`: Contract specification for the symbol (with `symbols`: a `SymbolInfoBulk`). — SymbolInfoData
- `400`: Neither or both of `symbol` and `symbols`, or too many symbols. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `ask` (number (double), required)
- `bid` (number (double), required)
- `commissions` (array of CommissionRule, required): The broker's commission rules for this symbol, straight from the server's symbol specification (MetaTrader build 6060+; empty when the broker publishes none or the build is older).
- `contractSize` (number (double), required)
- `currencyBase` (string, required)
- `currencyMargin` (string, required)
- `currencyProfit` (string, required)
- `description` (string, required)
- `digits` (integer (int64), required)
- `expirationModes` (array of string, required): Pending-order expiry kinds: `gtc` (until cancelled), `day` (end of the trading day), `specified` (date and time), `specifiedDay` (end of a given day).
- `fillingModes` (array of string, required): Fill policies: `fok`, `ioc`, `boc`. Empty on MT4, which has none.
- `freezeLevel` (integer (int64), required)
- `orderModes` (array of string, required): Order kinds the broker takes on this symbol: `market`, `limit`, `stop`, `stopLimit`, `sl`, `tp`, `closeBy`.
- `point` (number (double), required)
- `sessions` (array of TradingSession, required): Trading-session windows per weekday, in the broker's server time.
- `spread` (integer (int64), required)
- `stopsLevel` (integer (int64), required)
- `swapLong` (number (double), required)
- `swapShort` (number (double), required)
- `symbol` (string, required)
- `tickSize` (number (double), required)
- `tickValue` (number (double), required)
- `tradeMode` (string, required)
- `volumeMax` (number (double), required)
- `volumeMin` (number (double), required)
- `volumeStep` (number (double), required)
### POST /SymbolSelect
**Put symbols into Market Watch, ready to trade.**
A symbol outside Market Watch gets no quotes, so the first order or
`/SymbolInfo` on it waits for its first tick. Selecting the symbols a
client will trade ahead of time (a copier: its masters' symbols on
every follower, at start) moves that wait out of the first trade. All
symbols are selected in one pass, which then waits up to 1 s,
once, for the fresh ones to quote. They stay selected.
A bulk `/SymbolInfo` warms symbols up the same way.
Request body (JSON, SymbolSelectBody):
- `symbols` (array of string, required): Symbol names as listed by `/symbols` — at most 100.
Responses:
- `200`: One row per symbol, in request order. — array of SymbolSelectResult
- `400`: No symbols, too many, or a name with a comma. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `quoting` (boolean, required): It had a live bid/ask by the time the reply was sent. A freshly selected symbol may need a moment longer — or never quote, for a name the broker lists but does not feed.
- `selected` (boolean, required): The symbol is in Market Watch (false: unknown to this broker).
- `symbol` (string, required)
### GET /getQuote
**Latest tick for a symbol.**
Returns the most recent `bid`, `ask`, `last`, `volume`, and broker
server `time` for `symbol`. If the symbol isn't yet in Market Watch
it is enabled on demand, which may add a small delay on the
first call.
For continuous tick streaming use the WebSocket `prices` topic.
Parameters:
- `symbol` (query, string, required): Symbol name as listed by `/symbols` (e.g. `EURUSD`, `XAUUSD`).
Responses:
- `200`: Most recent tick for the symbol. — QuoteData
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `ask` (number (double), required)
- `bid` (number (double), required)
- `last` (number (double), required)
- `symbol` (string, required)
- `time` (string, required)
- `volume` (integer (int64), required)
### GET /symbols
**Every symbol the broker offers — the whole catalog, not just Market Watch**
Symbols with trading disabled are left out.
Use the returned names verbatim with `/getQuote`, `/SymbolInfo`,
`/PriceHistory`, and `/OrderSend`. A symbol outside Market Watch has
no quotes until it is added — `/SymbolSelect` adds several at once
and waits until they quote.
Responses:
- `200`: Every symbol the broker offers (not only Market Watch). — array of string
- `504`: The connection did not answer in time. — ErrorBody
---
# Trading
Source: https://docs.api2trade.com/docs/api-v2/trading-api/trading
Margin/profit calculation and placing, modifying and closing orders.
Base URL: `https://api.api2trade.com/v2/{account_id}`
### POST /CloseAll
**Close every open position — the panic button.**
Optionally filtered by `symbol` and/or `magic`, and optionally also
deleting pending orders. Runs as ONE pass; the reply carries
a per-ticket result for every attempted close/delete, plus counts.
Positions opened while the pass is running are not covered — check
`/OpenedOrders` afterwards if that matters.
Request body (JSON, CloseAllBody):
- `deletePending` (boolean): Also delete pending orders matching the filters (default false).
- `magic` (integer (int64)): Only act on orders with this exact magic number — 0 matches manually-opened orders. Omit the field entirely for no filter.
- `symbol` (string): Only act on this symbol (omit = all symbols).
Responses:
- `200`: Per-ticket outcomes — inspect each `retcode`. — CloseAllSummary
- `503`: The trading engine is not ready yet. — ErrorBody
- `504`: No reply in time — but closing CONTINUES to completion on the account. Check `/OpenedOrders` to see what remains open before acting again. — ErrorBody
Response fields (200):
- `closed` (integer (int64), required): Attempts the broker accepted.
- `failed` (integer (int64), required): Attempts the broker rejected — inspect `results`.
- `requested` (integer (int64), required): Orders matched by the filters and attempted.
- `results` (array of CloseAllResult, required)
### GET /OrderCalcMargin
**Required margin for a hypothetical order.**
Asks MT5 to compute the broker-side margin needed to open `volume`
lots of `symbol` at `price` in the given `operation` direction.
Returns the margin in the account currency. **Does not place an
order** — purely a sizing/risk query.
Parameters:
- `symbol` (query, string, required): Symbol name as listed by `/symbols` (e.g. `EURUSD`).
- `operation` (query, string, required): Order direction: `Buy`, `Sell`, `BuyLimit`, `SellLimit`, `BuyStop`, `SellStop`, `BuyStopLimit`, `SellStopLimit` (case- and separator-insensitive).
- `volume` (query, number (double), required): Volume in lots.
- `price` (query, number (double), required): Hypothetical entry price (account-quote currency).
Responses:
- `200`: Required margin in account currency. — MarginResult
- `400`: Unknown `operation` value. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `currency` (string, required)
- `margin` (number (double), required)
- `operation` (string, required)
- `price` (number (double), required)
- `symbol` (string, required)
- `volume` (number (double), required)
### GET /OrderCalcProfit
**Projected P&L for a hypothetical open→close move.**
Asks MT5 to compute the profit/loss if `volume` lots of `symbol`
were opened at `priceOpen` and closed at `priceClose` in the given
direction. Returns profit in account currency. **Does not place an
order** — useful for sizing and UI.
Parameters:
- `symbol` (query, string, required): Symbol name as listed by `/symbols` (e.g. `EURUSD`).
- `operation` (query, string, required): Order direction: `Buy` or `Sell` (case-insensitive). Pending variants are accepted but only the direction is used.
- `volume` (query, number (double), required): Volume in lots.
- `priceOpen` (query, number (double), required): Hypothetical open price.
- `priceClose` (query, number (double), required): Hypothetical close price.
Responses:
- `200`: Projected profit in account currency. — ProfitResult
- `400`: Unknown `operation` value. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `currency` (string, required)
- `operation` (string, required)
- `priceClose` (number (double), required)
- `priceOpen` (number (double), required)
- `profit` (number (double), required)
- `symbol` (string, required)
- `volume` (number (double), required)
### POST /OrderClose
**Close a position or delete a pending order.**
One endpoint covers both — the action is inferred from the ticket
type:
- **Position ticket** → closes the position. Supply `volume` for a
partial close (must respect the symbol's `volumeStep`); omit or
pass `0` for a full close.
- **Pending-order ticket** → deletes the order. `volume` is ignored.
With `pendingOnly: true` only the second applies, also to a partly
filled order (the filled part stays open). A ticket that is only a
position (its order filled a moment ago) is refused with **409
`MRPC_NOT_PENDING`** and stays open.
Inspect `success`/`retcode` on the response.
Request body (JSON, OrderCloseBody):
- `pendingOnly` (boolean): Only delete a pending order. A ticket whose order has filled into a position by now is left open and refused with `409 MRPC_NOT_PENDING`, so a cancel that crosses a fill keeps the fill.
- `slippage` (integer (int64))
- `ticket` (integer (int64), required): Position ticket (closes it) or pending-order ticket (deletes it).
- `volume` (number (double)): Partial close volume; omit / 0 = full close. Ignored for pendings.
Responses:
- `200`: MT5 trade result — inspect `success` and `retcode`. — OrderSendResult
- `400`: Validation failed (e.g. missing `ticket`). — ErrorBody
- `409`: `pendingOnly` and the ticket is a position, not a pending order (`MRPC_NOT_PENDING`). — ErrorBody
- `503`: The trading engine is not ready yet. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `ask` (number (double), required)
- `bid` (number (double), required)
- `clientOrderId` (string): The request's `clientOrderId`, when it carried one.
- `comment` (string, required)
- `deal` (integer (int64), required)
- `order` (integer (int64), required)
- `outcome` (string, required): `"applied"` | `"no_change"` | `"partial"` | `"rejected"` — see `trade_outcome`.
- `position` (integer (int64), required): Position the trade opened, changed or closed (`DEAL_POSITION_ID`); 0 for a pending order, or when the deal record was not in history yet and the position could not be told from the order.
- `price` (number (double), required)
- `remainderTicket` (integer (int64), required): MT4 only (a partial close moves the rest to a new ticket); 0 here.
- `retcode` (integer (int64), required)
- `retcodeDescription` (string, required)
- `success` (boolean, required)
- `time` (string, required): When the order filled, ms precision, broker server time like every other time here; empty when nothing filled (modify, pending order, rejection) or the deal record was not in history yet.
- `timeUtc` (string): `time` in real UTC, converted with the server's current offset; absent until that offset is known (the connection's first second) and when `time` is empty.
- `volume` (number (double), required)
### POST /OrderModify
**Modify an existing position or pending order.**
The ticket type decides what's modifiable:
- **Position ticket** → only `stopLoss` and `takeProfit`.
- **Pending-order ticket** → `price`, `stopLimitPrice`, `expiration`,
`stopLoss`, `takeProfit`.
Omit a field to keep its current value. Inspect `success`/`retcode`
on the response — a `200` only proves a reply arrived, not that the
broker accepted the change.
Request body (JSON, OrderModifyBody):
- `expiration` (string): New expiration (date string, broker server time) — pending orders only.
- `expirationUtc` (string): New expiration in real UTC instead (ISO-8601, e.g. `2026-11-03T17:00:00Z`). Not together with `expiration`.
- `price` (number (double)): New price — pending orders only.
- `stopLimitPrice` (number (double)): New StopLimit price — *StopLimit pending orders only.
- `stopLoss` (number (double)): New SL/TP (omit to keep current). For positions only SL/TP apply.
- `takeProfit` (number (double))
- `ticket` (integer (int64), required): Position or pending-order ticket.
Responses:
- `200`: MT5 trade result — inspect `success` and `retcode`. — OrderSendResult
- `400`: Validation failed (e.g. missing `ticket`). — ErrorBody
- `503`: The trading engine is not ready yet. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `ask` (number (double), required)
- `bid` (number (double), required)
- `clientOrderId` (string): The request's `clientOrderId`, when it carried one.
- `comment` (string, required)
- `deal` (integer (int64), required)
- `order` (integer (int64), required)
- `outcome` (string, required): `"applied"` | `"no_change"` | `"partial"` | `"rejected"` — see `trade_outcome`.
- `position` (integer (int64), required): Position the trade opened, changed or closed (`DEAL_POSITION_ID`); 0 for a pending order, or when the deal record was not in history yet and the position could not be told from the order.
- `price` (number (double), required)
- `remainderTicket` (integer (int64), required): MT4 only (a partial close moves the rest to a new ticket); 0 here.
- `retcode` (integer (int64), required)
- `retcodeDescription` (string, required)
- `success` (boolean, required)
- `time` (string, required): When the order filled, ms precision, broker server time like every other time here; empty when nothing filled (modify, pending order, rejection) or the deal record was not in history yet.
- `timeUtc` (string): `time` in real UTC, converted with the server's current offset; absent until that offset is known (the connection's first second) and when `time` is empty.
- `volume` (number (double), required)
### POST /OrderSend
**Submit a market or pending order.**
A `200` response only means MT5 answered — **always inspect `success`
and `retcode`** to confirm the broker accepted it.
**Required fields by operation**
- Market (`Buy`/`Sell`): `symbol`, `volume`. `price` is ignored.
- Pending (`*Limit`/`*Stop`): `symbol`, `volume`, `price`.
- StopLimit (`BuyStopLimit`/`SellStopLimit`): additionally
`stopLimitPrice`.
**Optional fields**
- `slippage` (default 10 points), `stopLoss`, `takeProfit`,
`expiration` (date string — absent ⇒ good-till-cancelled),
`comment`, `expertId` (a.k.a. `magic`, also accepts `magicNumber`).
- `clientOrderId`: makes the request safe to repeat after a timeout —
see the field.
- `execution`: `EA` (default) or `Manual` — see below.
**`execution: "Manual"`** — for brokers that block expert trading.
The order is entered in MetaTrader's own New Order dialog and Buy/Sell
pressed there, so the broker records a manual order (`ORDER_REASON_CLIENT`).
Market orders only (`Buy`/`Sell`, with optional `stopLoss`,
`takeProfit`, `comment`); magic is always 0, so `expertId` is
refused. Before the click every value is read back from the dialog;
if one does not match, nothing is sent and the reply is
`500 MRPC_MANUAL_NOT_SENT`. The reply otherwise has the usual shape:
`comment` is the dialog's own result line, a rejection carries the
matching retcode where the text names one (else 10006). Takes about
1–3 s, during which other trade commands wait.
Returns `503` while the trading engine is not ready yet.
Request body (JSON, OrderSendBody):
- `clientOrderId` (string): Your id for this order (1–64 characters). Repeating a request with the same id within 10 minutes places nothing new: it is answered with the first request's outcome (header `Idempotent-Replayed: true`), waiting for it if it is still being executed. Reusing an id for a different order is a `409`.
- `comment` (string)
- `execution` (string): How the order is placed: `EA` (default) sends it as an expert order, the normal way; `Manual` places it through MetaTrader's own New Order dialog, for brokers that block expert trading (`tradeExpert: false` on `/AccountInfo`, expert orders fail with retcode 10026). A Manual order is a market order (`Buy`/`Sell`) and always has magic 0; `slippage` does not apply.
- `expertId` (integer (int64)): Magic number. Accepts `expertId`, `magic`, `expertID`.
- `expiration` (string): Date string in broker server time; absent → good-till-cancelled.
- `expirationUtc` (string): The expiry in real UTC instead (ISO-8601, e.g. `2026-11-03T17:00:00Z`), converted with the server's current offset. Not together with `expiration`.
- `operation` (string, required): Buy, Sell, BuyLimit, SellLimit, BuyStop, SellStop, BuyStopLimit, SellStopLimit (case/separator-insensitive).
- `price` (number (double)): Required for pending orders; ignored for market orders.
- `slippage` (integer (int64))
- `stopLimitPrice` (number (double)): Required for *StopLimit operations.
- `stopLoss` (number (double))
- `symbol` (string, required): Symbol to trade, e.g. `EURUSD`.
- `takeProfit` (number (double))
- `volume` (number (double), required)
Responses:
- `200`: MT5 trade result — inspect `success` and `retcode`. — OrderSendResult
- `400`: Validation failed (unknown operation, missing price for pending, non-positive volume, …). — ErrorBody
- `409`: `clientOrderId` already used for a different order. — ErrorBody
- `503`: The trading engine is not ready yet. — ErrorBody
- `504`: The connection did not answer in time. — ErrorBody
Response fields (200):
- `ask` (number (double), required)
- `bid` (number (double), required)
- `clientOrderId` (string): The request's `clientOrderId`, when it carried one.
- `comment` (string, required)
- `deal` (integer (int64), required)
- `order` (integer (int64), required)
- `outcome` (string, required): `"applied"` | `"no_change"` | `"partial"` | `"rejected"` — see `trade_outcome`.
- `position` (integer (int64), required): Position the trade opened, changed or closed (`DEAL_POSITION_ID`); 0 for a pending order, or when the deal record was not in history yet and the position could not be told from the order.
- `price` (number (double), required)
- `remainderTicket` (integer (int64), required): MT4 only (a partial close moves the rest to a new ticket); 0 here.
- `retcode` (integer (int64), required)
- `retcodeDescription` (string, required)
- `success` (boolean, required)
- `time` (string, required): When the order filled, ms precision, broker server time like every other time here; empty when nothing filled (modify, pending order, rejection) or the deal record was not in history yet.
- `timeUtc` (string): `time` in real UTC, converted with the server's current offset; absent until that offset is known (the connection's first second) and when `time` is empty.
- `volume` (number (double), required)
---
# MT4 vs MT5
Source: https://docs.api2trade.com/docs/api-v2/platforms
> The trading API is the same on both platforms, with a few differences worth knowing.
The Trading API has **the same endpoints on MetaTrader 4 and MetaTrader 5** — the
same 19 endpoints, the same paths, the same parameters. You do not need to write
against one or the other: an MT4 account and an MT5 account answer the same
calls. Where the platforms themselves differ, the answers differ too; this page
lists where.
## Commissions
`GET /SymbolInfo` reports commission differently, because the two platforms expose
different information.
### MetaTrader 5 — the broker's actual rules
MT5 exposes commission configuration server-side, so the response carries it
structured, under `commissions`:
```json title="MT5 — GET /SymbolInfo?symbol=EURUSD (abridged)"
{
"symbol": "EURUSD",
"commissions": [
{
"chargeMode": "instant",
"entryMode": "both",
"directionMode": "both",
"profitMode": "all",
"rangeMode": "lots",
"currency": "USD",
"tiers": [
{
"mode": "money",
"volumeType": "by_volume",
"value": 3.5,
"rangeFrom": 0,
"rangeTo": 0,
"minValue": 0,
"maxValue": 0,
"currency": "USD"
}
]
}
]
}
```
Each rule says when it is charged (`chargeMode`), whether it applies on entry,
exit or both (`entryMode`), to buys, sells or both (`directionMode`), and to all
deals or only profitable or losing ones (`profitMode`). The `tiers` hold the
amounts and the volume or turnover ranges they apply to.
These are the broker's configured rules, so they are authoritative.
### MetaTrader 4 — an estimate from your own history
MT4 has no equivalent API. API v2 therefore **derives** a figure from the
account's most recent closed orders:
```json title="MT4 — GET /SymbolInfo?symbol=EURUSD (abridged)"
{
"symbol": "EURUSD",
"commissionPerLot": 7.0,
"commissionSamples": 12
}
```
| Field | Meaning |
| ------------------- | -------------------------------------------------------------------------------------- |
| `commissionPerLot` | Estimated commission for 1.0 lot |
| `commissionSamples` | How many closed orders the estimate came from — **`0` means no estimate was possible** |
It is calculated from what your account was actually charged, not from the
broker's configuration. With `commissionSamples: 0` there is no history to
derive it from and `commissionPerLot` carries no information. A new account
reports `0` until it has closed trades, and a broker that changes its
commission is not reflected until new trades land.
### Writing for both
If your code supports both platforms, read whichever field is present:
```javascript
function commissionPerLot(symbolInfo) {
// MT5: the broker's rules. Take the first money-per-volume tier.
if (Array.isArray(symbolInfo.commissions)) {
for (const rule of symbolInfo.commissions) {
for (const tier of rule.tiers ?? []) {
if (tier.mode === 'money' && tier.volumeType === 'by_volume') {
return { value: tier.value, source: 'broker' }
}
}
}
return { value: null, source: 'broker' }
}
// MT4: an estimate, and only if there was history to estimate from.
if (symbolInfo.commissionSamples > 0) {
return { value: symbolInfo.commissionPerLot, source: 'estimate' }
}
return { value: null, source: 'none' }
}
```
## Partial closes on MT4
On MT5 a position keeps its ticket when you close part of it. On MT4, closing
part of an order **moves the rest to a new ticket**, and the API tells you which:
* the `/OrderClose` reply carries the new ticket in `remainderTicket`;
* on the [`trades` topic](/docs/api-v2/websocket#trade-events), the `Out` frame
carries `remainderTicket` and the remainder's `In` frame carries `remainderOf`,
the ticket it came from.
`positionVolume` follows the chain, so it still says how much of the original
position is open. On MT5 both fields are always `0`.
## Stop-loss and take-profit in the history
`/OrderHistory` and `/PositionHistory` rows carry `sl` and `tp`; `0` means none
was set.
* **MT5** records them per deal: an `In` row has the levels sent with the
opening order, an `Out` row the position's levels when it closed.
`/PositionHistory` shows the levels at close.
* **MT4** keeps one pair per order: its levels when it closed, in both
endpoints.
For the risk a trade started with — R multiples, for example — take `sl` from
the `In` row on MT5, matched to the position by `position`. A stop moved later,
trailed or set to break-even, shows only its last level. A stop added after the
order was placed is `0` on the `In` row, and MT4 never keeps the original stop.
To have it in every case, record it while the position is open: the `trade` and
`modify` frames on the [`trades` topic](/docs/api-v2/websocket#trade-events)
carry the stops at every change.
`sl` and `tp` on history rows come with version `0.18.3` on MT5 and `0.16.2`
on MT4 — `GET /status` reports it as `bridge.version`. Older versions leave
both fields out. Connections move to the new version when they restart.
## Everything else that differs
| | MT5 | MT4 |
| ------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Stop-limit orders (`BuyStopLimit`, `SellStopLimit`) | Yes | No — `400 MRPC_UNSUPPORTED` |
| `/OrderHistory` | One row per deal | One row per closed order |
| `trade` frames | `deal` is the deal ticket | `deal` is `0`; `order` and `position` are the order ticket — deduplicate on `order` plus `entry` |
| `/SymbolInfo` `orderModes`, `expirationModes`, `fillingModes` | The broker's settings for the symbol | A fixed set: no stop-limit, expiry `gtc` or `specified`, no filling modes |
| `/PendingOrders` | Partly filled orders show `volume` below `volumeInitial` | No partial fills and no stop-limit: `volume` = `volumeInitial`, `stopLimitPrice` is `0` |
Brokers also set a minimum distance for a pending order's expiry — often a few
minutes on MT5, and more on MT4, where ten minutes or longer is common. An expiry
closer than that is rejected by the broker.
Everything else — quotes, bars, symbols, positions, placing, modifying and
closing orders, and the rest of the [WebSocket](/docs/api-v2/websocket) —
behaves the same on both.
---
# WebSocket
Source: https://docs.api2trade.com/docs/api-v2/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_KEY
```
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](/docs/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 |
```json title="Subscribe to EURUSD ticks"
{ "action": "subscribe", "topic": "prices", "symbol": "EURUSD" }
```
```json title="Subscribe to 5-minute candles"
{ "action": "subscribe", "topic": "bars", "symbol": "EURUSD", "timeframe": "M5" }
```
```json title="Subscribe to account changes"
{ "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`](/docs/api-v2/trading-api/market) 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.
```json title="A tick"
{
"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"
}
}
```
```json title="Subscription confirmed"
{ "type": "subscribed", "topic": "prices", "message": "" }
```
| `type` | Meaning |
| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `tick`, `bar`, `account`, `positions`, `trade`, `modify`, `order`, `terminal` | Data — see [Topics](#topics) |
| `orders` | The snapshot an `orders` subscription opens with — see [Pending orders](#pending-orders) |
| `subscribed` / `unsubscribed` | Your request was accepted |
| `subscriptions` | The reply to `list` |
| `replayed` | A `since` replay is complete — see [Catching up](#catching-up-after-a-reconnect) |
| `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
* **`seq`** numbers the live frames of each topic, +1 per frame. A gap means
frames were dropped for you.
* **`ts`** is 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`, `prices` or
`orders`, you get the current state once, marked `"snapshot": true` and
without `seq`, 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`](/docs/api-v2/trading-api/account) 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:
```json
{ "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:
```json title="A trade frame"
{
"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](/docs/api-v2/platforms#partial-closes-on-mt4) |
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:
```json
{ "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:
```json
{ "type": "replayed", "topic": "trades", "count": 3, "truncated": false }
```
* `since` reaches back at most **24 hours**, and the replay holds the newest
**1000** deals; `truncated: true` means 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: `order` plus
`entry`).
* `since` only applies to `trades`; on any other topic it is an `error`.
## Pending orders
The `orders` topic opens with an `orders` snapshot — the same rows as
[`GET /PendingOrders`](/docs/api-v2/trading-api/account) — then sends an `order`
frame for every step of a pending order's life:
```json title="An order frame"
{
"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
```javascript title="Node.js"
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))
```
```python title="Python"
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`.
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`.
---
# Errors
Source: https://docs.api2trade.com/docs/api-v2/errors
> What the API returns when something is wrong, and which failures are worth retrying.
Both halves of v2 — the Account API and each account's Trading API — answer
errors in the same shape, so one handler covers both:
```json
{
"error": "NO_SLOT_AVAILABLE",
"message": "Account limit reached — 5 of 5 in use. Upgrade your plan or contact support."
}
```
`error` is a stable code worth branching on. `message` is written for a human and
may change; do not match on it. Trading API errors also carry a `command_id` —
quote it when you report a problem.
## Status codes
| Status | When | Retry? |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `400` | The request was malformed — a missing field, an unknown platform, a symbol the broker does not offer, a ticket that does not exist | No, fix the request |
| `401` | No API key, or one that is not valid | No, check the key |
| `403` | Authenticated, but not allowed — no free account slot | No, free a slot or upgrade |
| `404` | No such account, or no access to it | No |
| `409` | The `clientOrderId` was already used for a different order | No, use a new id |
| `429` | Too many **different** accounts connected on your slots recently | Yes, once the window frees up |
| `500` | The account could not answer this one — see the [Trading API codes](#trading-api) | Depends on the code |
| `503` | The connection is not answering or is still starting, or v2 is not available for your account yet | Yes, with backoff |
| `504` | The connection did not answer in time | **On orders, depends on the code** — see [Timeouts on orders](#timeouts-on-orders) |
An account you have no access to answers `404`, the same as one that does not
exist.
## Codes
### Account API
| Code | Meaning |
| ----------------------- | ----------------------------------------------------- |
| `UNAUTHORIZED` | Missing or invalid API key |
| `INVALID_REQUEST` | The body failed validation; `message` names the field |
| `NO_SLOT_AVAILABLE` | Your plan's account slots are all in use |
| `NOT_FOUND` | No such account, or no access to it |
| `TOO_MANY_NEW_ACCOUNTS` | Connection limit reached — see below |
| `UNAVAILABLE` | v2 cannot serve this request right now |
| `TIMEOUT` | The connection did not answer in time |
### Trading API
| Code | Status | Meaning | Retry? |
| -------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------- | ---------------------------------- |
| `UNAUTHORIZED` | `401` | Missing or invalid API key | No |
| `MRPC_VALIDATION` | `400` | A parameter is missing or invalid; `message` names it | No |
| `MRPC_UNKNOWN_SYMBOL` | `400` | The broker has no such symbol | No |
| `MRPC_UNKNOWN_TICKET` | `400` | No such order or position | No |
| `MRPC_BAD_TIMEFRAME` | `400` | The timeframe is not recognised | No |
| `MRPC_UNSUPPORTED` | `400` | The platform cannot do this — stop-limit orders on MT4 | No |
| `MRPC_CLIENT_ORDER_ID_REUSED` | `409` | The `clientOrderId` was already used for a different order | No |
| `MRPC_SYMBOL_NOT_QUOTING` | `500` | The symbol has no price yet — prepare it with `POST /SymbolSelect` | Yes |
| `MRPC_TICKET_BUSY` | `500` | Another request for this ticket is still running; nothing was sent | Yes |
| `MRPC_TRADE_EA_STOPPED` | `500` | Trading stopped on the connection before the order was sent; nothing was executed | Yes, with backoff |
| `MRPC_HISTORY_UNAVAILABLE`, `MRPC_PRICE_HISTORY_UNAVAILABLE`, `MRPC_CALC_FAILED` | `500` | The broker did not deliver the data | Yes, with backoff |
| `MRPC_INTERNAL`, `MRPC_UNKNOWN_COMMAND` | `500` | An internal fault — report it with the `command_id` | No |
| `MRPC_TRADE_EA_NOT_READY` | `503` | The connection is still starting up and does not take orders yet | Yes, with backoff |
| `MRPC_ABANDONED` | `504` | The order never reached the broker — **not executed** | Yes |
| `MRPC_TIMEOUT` | `504` | No answer in time; the request was **not executed** | Yes |
| `MRPC_TRADE_OUTCOME_UNKNOWN` | `504` | The order reached the broker and no verdict came back — **it may have executed** | Only with the same `clientOrderId` |
## Timeouts on orders
Order calls (`/OrderSend`, `/OrderModify`, `/OrderClose`) wait up to 60 seconds
for the broker. When that runs out, three `504`s mean different things, so
branch on the code, never on the status alone:
* `MRPC_ABANDONED` and `MRPC_TIMEOUT` — nothing was executed. Sending the order
again is safe.
* `MRPC_TRADE_OUTCOME_UNKNOWN` — the order was handed to the broker, so it may be
live. **Do not simply send it again.** Either repeat it with the same
`clientOrderId` (below) — that answers with the order's real result once it
is known, and never places it twice — or check `GET /OpenedOrders` and
`GET /OrderHistory` first, matching on your own `expertId` (`magic` in the
rows) and `comment`.
### Retrying an order safely
Give every `POST /OrderSend` a `clientOrderId` of your own, 1–64 characters.
Within 10 minutes, a request with the same id places nothing new: it is answered
with the first request's result — waiting for it if it is still running — and
carries the header `Idempotent-Replayed: true`. The same id with a different
order is refused with `409 MRPC_CLIENT_ORDER_ID_REUSED`. After `MRPC_ABANDONED`
the id is free again.
```javascript title="Node.js — one order, retried safely"
import { randomUUID } from 'node:crypto'
const ACCOUNT = 'your-account-uuid'
const BASE = `https://api.api2trade.com/v2/${ACCOUNT}`
async function placeOrder(order) {
// The body — and with it the id — stays the same on every attempt.
const body = JSON.stringify({ ...order, clientOrderId: randomUUID() })
for (let attempt = 0; attempt < 4; attempt++) {
const res = await fetch(`${BASE}/OrderSend`, {
method: 'POST',
headers: { 'X-API-Key': process.env.API2TRADE_API_KEY, 'Content-Type': 'application/json' },
body,
})
if (res.status !== 503 && res.status !== 504) return res.json()
await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt))
}
throw new Error('no answer — check /OpenedOrders before sending this order again')
}
```
A retry later than that — or after the connection itself restarted — is
treated as a new order. If you cannot retry within a few minutes, check
`/OpenedOrders` and `/OrderHistory` instead.
`clientOrderId` works from version `0.17.0` on MT5 and `0.15.0` on MT4 —
`GET /status` reports it as `bridge.version`. An older version ignores the
field, so a retry there places a second order. Connections move to the new
version when they restart; until then, reconcile before you resend.
## The connection limit
Your slots cap how many accounts run **at once**. Separately, there is a limit
on how many **different** accounts you may connect within a window — ten per
slot per hour — so a single slot cannot be used to serve an endless series of
accounts.
```json
{
"error": "TOO_MANY_NEW_ACCOUNTS",
"message": "You have connected 10 different accounts in the last 1 hours, which is the limit for your plan. …"
}
```
The limit counts *distinct* account numbers, not attempts. If you disconnect
and reconnect the same account — after fixing a password, say — it does not
count against the limit, however many times you do it.
## Failures that are not HTTP errors
A connected account can be unhealthy while every request still returns `200`.
This is the one thing worth building for deliberately.
A connection that has not logged in to the broker answers `GET /AccountSummary`
with **`200` and all zeros** — a balance of `0` is indistinguishable from a real
empty account unless you look at the session:
```json title="GET /status on an account that never logged in"
{
"status": "degraded",
"broker": { "connected": false, "server": "VTMarkets-Demo" },
"account": { "loggedIn": false, "login": 1082118 }
}
```
So before trusting any figure, check that `broker.connected` and
`account.loggedIn` are both `true`. `GET /status` always returns `200`; the
state is in the body.
An order the broker rejects is a `200` too: the call worked, the broker said no.
Check `success` and `retcode` in the body of every order call.
### While an account is still starting
Connecting an account returns straight away, but the connection needs a few
minutes to start and log in. Poll the account on the Account API until
`terminalStatus` settles:
| `terminalStatus` | Meaning |
| ---------------- | ------------------------------------------------------------- |
| `provisioning` | Starting up or logging in. Wait. |
| `ready` | Logged in and serving |
| `error` | It will not come up on its own — `terminalLastError` says why |
A rejected login is reported as soon as the broker rejects it, with the broker's
own wording:
```json
{
"terminalStatus": "error",
"terminalLastError": "VTMarkets-Demo rejected this login: Invalid account. Check account number, password and server."
}
```
That is not worth retrying — the account number, password or server name is
wrong. Fix it and connect again.