Make your
first connection.
Everything you need to bring MetaTrader accounts, market data, and trading into your application.
This guide follows the MT4/MT5 Client API contract, with mt2api implementation differences checked against the project reference on September 9, 2026. The endpoint catalog covers core integration workflows, not every declared compatibility endpoint. Broker and parameter support vary; consult your deployment’s /capabilities before relying on an operation.
Your first request.
Open the mt2api app for account access. Send MT4 requests to https://mt4.mt2api.com and MT5 requests to https://mt5.mt2api.com. The app host is separate from the API.
- Prepare your environment. Install Python and
requests. SetMTAPI_API_KEYon your backend. The example uses the MT5 API host. - Create a session. Use ConnectEx with a demo account and the broker’s exact server name.
- Read your account. Store the returned token as
MTAPI_SESSION_TOKENand make the read-only request below.
import os
import requests
# Public MT5 API. Use mt4.mt2api.com for MT4.
# Keep credentials on your backend, not in browser code.
gateway = "https://mt5.mt2api.com"
headers = {"X-Api-Key": os.environ["MTAPI_API_KEY"]}
token = os.environ["MTAPI_SESSION_TOKEN"]
response = requests.get(
f"{gateway}/AccountSummary",
headers=headers,
params={"id": token},
timeout=30,
allow_redirects=False,
)
if response.status_code != 200 or response.headers.get("X-MtApi-Error-Code"):
raise RuntimeError("Account request failed; verify session and API status.")
account = response.json()
if not isinstance(account, dict) or not {"equity", "currency"} <= account.keys():
raise RuntimeError("Unexpected account response.")
print(account["equity"], account["currency"])For MT4, use https://mt4.mt2api.com/AccountSummary. Amounts use the returned currency; do not assume USD.
Two credentials. Different jobs.
| Credential | Where it goes | Purpose |
|---|---|---|
X-Api-Key | HTTP header, including WebSocket handshake | Authenticates access to the gateway. |
id | Query parameter | Identifies a connected MT4 or MT5 session. |
The public API selects the platform by hostname: https://mt4.mt2api.com/AccountSummary or https://mt5.mt2api.com/AccountSummary. For a self-hosted gateway serving both platforms, use explicit /mt4 and /mt5 prefixes unless your deployment routes them by hostname.
- Keep API keys, passwords, and tokens on your backend. Use HTTPS or a controlled local connection.
- Compatibility login parameters contain the password in the query. Disable query logging, automatic redirects, and URL echoes in errors.
- Encode parameters with your HTTP client. Arrays use repeated keys, not comma-separated strings.
- Parameter names are case-sensitive. For example,
expertIDandstoplossmust be spelled exactly. - MT5 identifiers are int64. Use a lossless JSON parser when handling IDs outside JavaScript’s safe integer range.
Connect once. Keep the token.
ConnectEx accepts a trading account login, password, and server name. Success returns a plain-text token, not a JSON object. Reuse it as id for account, quote, and trading calls.
# Requires: pip install requests
import os
import requests
gateway = "https://mt5.mt2api.com"
response = requests.get(
f"{gateway}/ConnectEx",
headers={"X-Api-Key": os.environ["MTAPI_API_KEY"]},
params={
"user": os.environ["MTAPI_LOGIN"],
"password": os.environ["MTAPI_PASSWORD"],
"server": os.environ["MTAPI_SERVER"],
"connectTimeoutSeconds": 60,
},
timeout=75,
allow_redirects=False,
)
if response.status_code != 200 or response.headers.get("X-MtApi-Error-Code"):
raise RuntimeError("Connection failed; inspect a redacted server error.")
token = response.text.strip() # Keep private; do not log.
if not token or "text/plain" not in response.headers.get("Content-Type", ""):
raise RuntimeError("Unexpected connection response.")Repeated ordinary connections can create multiple terminal sessions. Manage concurrency in your application and call Disconnect when finished.
ConnectByToken needs saved encrypted credentials and persistent storage. Disconnect ends the active session but does not invalidate saved recovery credentials. The current client API has no separate token-revocation endpoint.
Find your next request.
Core endpoints for connections, accounts, quotes, orders, history, and streaming. Select a platform or search by endpoint, parameter, or topic. All ordinary operations listed below use GET; WebSocket endpoints upgrade an authenticated GET request.
GET/ConnectExConnect using the exact broker server name.MT4MT5
GET https://mt4.mt2api.com/ConnectExGET https://mt5.mt2api.com/ConnectExConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
user | integer · required | MT4 int32 / MT5 int64 account login. |
password | string · required | Trading account password. |
server | string · required | Trading server name, not a broker website URL. |
connectTimeoutSeconds | integer | 1–300 seconds. Defaults: MT4 30, MT5 60. |
Success response
text/plain session token.
GET/ConnectConnect using a broker trading-server address.MT4MT5
GET https://mt4.mt2api.com/ConnectGET https://mt5.mt2api.com/ConnectConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
user | integer · required | MT4 int32 / MT5 int64 account login. |
password | string · required | Account password. |
host | string · required | Trading-server host, without scheme or path. |
port | integer · required | Submit explicitly, even for port 443. |
Success response
text/plain session token.
GET/ConnectByTokenRestore a session from saved connection information.MT4MT5
GET https://mt4.mt2api.com/ConnectByTokenGET https://mt5.mt2api.com/ConnectByTokenConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
connectTimeoutSeconds | integer | Connection timeout, 1–300 seconds. |
Success response
Session token.
GET/DisconnectClose the active account session and its subscriptions.MT4MT5
GET https://mt4.mt2api.com/DisconnectGET https://mt5.mt2api.com/DisconnectConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
JSON string "OK".
GET/ConnectionStatusRead connection state by probing the terminal worker.MT4MT5
GET https://mt4.mt2api.com/ConnectionStatusGET https://mt5.mt2api.com/ConnectionStatusConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
Connection status object.
GET/SearchFind broker trading servers in the public directory.MT4MT5
GET https://mt4.mt2api.com/SearchGET https://mt5.mt2api.com/SearchConnections · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
company | string · required | Company search term; supported ASCII characters, 1–128 characters. |
Success response
Array of { companyName, results: [{ name, access }] }.
GET/AccountSummaryRead account balance, equity, margin, and currency.MT4MT5
GET https://mt4.mt2api.com/AccountSummaryGET https://mt5.mt2api.com/AccountSummaryAccounts · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
{ balance, credit, equity, margin, freeMargin, profit, marginLevel, leverage, currency, type }. MT5 also includes method and synced.
GET/AccountDetailsRead account identity, broker information, and available trading permissions.MT4MT5
GET https://mt4.mt2api.com/AccountDetailsGET https://mt5.mt2api.com/AccountDetailsAccounts · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
Account details including user, accountName, serverName, company, currency, and accountLeverage.
GET/SymbolListList symbol names available on the connected account.MT4MT5
GET https://mt4.mt2api.com/SymbolListGET https://mt5.mt2api.com/SymbolListMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
string[] of broker-specific symbol names.
GET/SymbolParamsRead symbol details such as price increments and lot limits.MT4MT5
GET https://mt4.mt2api.com/SymbolParamsGET https://mt5.mt2api.com/SymbolParamsMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact broker symbol. |
Success response
Platform-specific symbol metadata.
GET/QuoteRead one MT4 quote.MT4
GET https://mt4.mt2api.com/QuoteMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact symbol name. |
msNotOlder | integer | Freshness requirement in milliseconds. Default 0 allows an older synchronized tick. |
Success response
{ symbol, bid, ask, time }.
GET/GetQuoteRead one MT5 quote.MT5
GET https://mt5.mt2api.com/GetQuoteMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact symbol name. |
msNotOlder | integer | Freshness requirement in milliseconds; default 0. |
Success response
{ symbol, bid, ask, time, last, volume }.
GET/GetQuoteManyRead quotes for several symbols in request order.MT4MT5
GET https://mt4.mt2api.com/GetQuoteManyGET https://mt5.mt2api.com/GetQuoteManyMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbols | string[] · required | Repeat symbols in the query: symbols=EURUSD&symbols=GBPUSD. |
msNotOlder | integer | Freshness requirement; default 0. |
Success response
Quote[] in request order.
GET/QuoteHistoryRead historical MT4 bars backwards from a starting time.MT4
GET https://mt4.mt2api.com/QuoteHistoryMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact symbol name. |
timeframe | enum · required | M1, M5, M15, M30, H1, H4, D1, W1, MN1. |
from | string · required | Broker-calendar start time. |
count | integer · required | Number of bars. |
Success response
Bar[] with open, high, low, close, time, volume, tickVolume, spread.
GET/PriceHistoryRead MT5 bars in an explicit time range.MT5
GET https://mt5.mt2api.com/PriceHistoryMarket data · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact symbol name. |
from / to | string · required | Explicit broker-calendar range. |
timeFrame | integer · required | Timeframe in minutes; note capital F. |
timeoutSeconds | integer | Default 30; 1–300. |
Success response
Bar[] with openPrice, highPrice, lowPrice, closePrice, time, volume, tickVolume, spread.
GET/OpenedOrdersRead current positions and pending orders together.MT4MT5
GET https://mt4.mt2api.com/OpenedOrdersGET https://mt5.mt2api.com/OpenedOrdersOrders · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
sort | MT5 integer | MT5 only: 0 opening time (default), 1 closing time. |
ascending | MT5 boolean | MT5 only: default true. |
Success response
Order[].
GET/OpenedOrderRead one current position or pending order.MT4MT5
GET https://mt4.mt2api.com/OpenedOrderGET https://mt5.mt2api.com/OpenedOrderOrders · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | integer · required | Current order/position ticket: int32 for MT4, int64 for MT5. |
Success response
Order object.
GET/OrderSendSubmit an MT4 market or pending order.MT4
GET https://mt4.mt2api.com/OrderSendTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact broker symbol. |
operation | enum · required | Buy, Sell, BuyLimit, SellLimit, BuyStop, SellStop. |
volume | number · required | Opening size in lots. |
placedType | enum · explicit | Use Expert. The contract default Client is unsupported. |
price / slippage | number / int32 | Default 0. Pending orders need an actual price. Slippage is in points. |
stoploss / takeprofit | number | Default 0 means no stop or target. |
magic / comment | int32 / string | Optional strategy tags; magic defaults to 0. |
Success response
Order object.
GET/OrderSendTaskSubmit an MT5 market or pending order.MT5
GET https://mt5.mt2api.com/OrderSendTaskTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact broker symbol. |
operation | integer · required | 0 Buy, 1 Sell, 2 BuyLimit, 3 SellLimit, 4 BuyStop, 5 SellStop, 6 BuyStopLimit, 7 SellStopLimit. |
volume | number · required | Opening size in lots. |
price / slippage | number / int64 | Default 0. Pending price must be positive; slippage in points. |
stoploss / takeprofit | number | Default 0 means no stop or target. |
expertID | int64 | Strategy identifier, default 0. Exact spelling matters. |
stopLimitPrice | number | Required positive value for stop-limit orders. |
expirationType / expiration | integer / string | 0 GTC, 1 Day, 2 Specified, 3 SpecifiedDay. Default 2 without expiration uses GTC for new pending orders. |
placedType | integer | Only 0 is supported. |
Success response
Order object; inspect fills and reconcile against positions/deals.
GET/OrderModifyModify an MT4 order.MT4
GET https://mt4.mt2api.com/OrderModifyTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int32 · required | Current order ticket. |
stoploss / takeprofit | number · required | Pass current values to preserve them; zero removes them. |
price | number | Explicitly use the desired pending price or current openPrice. |
expiration | string | Optional expiration. |
Success response
Order object.
GET/OrderModifyTaskModify an MT5 position or pending order.MT5
GET https://mt5.mt2api.com/OrderModifyTaskTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int64 · required | Current position/pending-order ticket. |
stoploss / takeprofit | number · required | Pass current values to preserve them. |
price / stoplimit | number | Default 0. Explicitly preserve the stop-limit price when needed. |
expirationType / expiration | integer / string | Choose the broker-supported expiry policy. |
Success response
Order object.
GET/OrderCloseClose an MT4 market position.MT4
GET https://mt4.mt2api.com/OrderCloseTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int32 · required | Current market-order ticket. |
lots | number | Default 0 closes the full position. |
price / slippage | number / int32 | Default 0; slippage is in points. |
Success response
Order object.
GET/OrderCloseTaskClose an MT5 position.MT5
GET https://mt5.mt2api.com/OrderCloseTaskTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int64 · required | Current position ticket, not the position identifier. |
lots | number | Default 0 closes the full position. |
price / slippage | number / int64 | Default 0; slippage in points. |
comment | string | Optional comment. |
Success response
Order object.
GET/OrderDeleteCancel an MT4 pending order.MT4
GET https://mt4.mt2api.com/OrderDeleteTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int32 · required | Pending-order ticket. |
Success response
JSON string "OK".
GET/OrderCancelTaskCancel an MT5 pending order.MT5
GET https://mt5.mt2api.com/OrderCancelTaskTrading · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int64 · required | Pending-order ticket. |
lots | number | Use 0 for full cancellation; partial cancellation is unsupported. |
comment | string | Optional comment. |
Success response
Historical pending Order object, not "OK".
GET/ClosedOrdersRead recently closed orders associated with the session.MT4MT5
GET https://mt4.mt2api.com/ClosedOrdersGET https://mt5.mt2api.com/ClosedOrdersHistory · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
Order[], up to 100 recent records.
GET/OrderHistoryRead order history for an explicit broker-calendar range.MT4MT5
GET https://mt4.mt2api.com/OrderHistoryGET https://mt5.mt2api.com/OrderHistoryHistory · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
from | string · required | Range start. |
to | string · explicit | Required for MT5. Always submit it on MT4 as well. |
sort / ascending | MT5 integer / boolean | MT5 defaults: 0 / true. |
filter | MT5 string[] | Optional MT5 field filter using repeated keys. |
Success response
MT4: Order[]. MT5: { orders, internalDeals, internalOrders, action, partialResponse }.
GET/OrderHistoryPaginationRead a numbered page of history.MT4MT5
GET https://mt4.mt2api.com/OrderHistoryPaginationGET https://mt5.mt2api.com/OrderHistoryPaginationHistory · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
from / to | string · explicit | Broker-calendar range; always provide both. |
ordersPerPage | integer · required | Positive page size. |
pageNumber | integer · required | Zero-based page number. |
requestAgain | boolean | Default false; true refreshes the MT5 range cache. |
Success response
MT4: Order[]. MT5: { pagesCount, pageNumber, orders }.
GET/HistoryDealsByPositionIdRead deals associated with a position identifier.MT5
GET https://mt5.mt2api.com/HistoryDealsByPositionIdHistory · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
ticket | int64 · required | The position identifier, not necessarily the current position ticket. |
Success response
DealInternal[].
GET/SubscribeSubscribe a session to a symbol before opening OnQuote.MT4MT5
GET https://mt4.mt2api.com/SubscribeGET https://mt5.mt2api.com/SubscribeStreaming · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Exact broker symbol. |
interval | integer | Milliseconds; default 0 adds no explicit throttle. |
Success response
Subscription acknowledgement.
GET/SubscribeManySubscribe to several broker symbols.MT4MT5
GET https://mt4.mt2api.com/SubscribeManyGET https://mt5.mt2api.com/SubscribeManyStreaming · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbols | string[] · explicit | Repeat symbols keys. Required on MT5; omitting on MT4 means all symbols. |
interval | integer | Milliseconds; default 0. |
replace / force | platform-specific boolean | MT4 replace=false. MT5 force=false currently has no worker behavior difference. |
Success response
Subscription acknowledgement.
GET/SubscribedSymbolsRead the session’s explicitly subscribed symbols.MT4MT5
GET https://mt4.mt2api.com/SubscribedSymbolsGET https://mt5.mt2api.com/SubscribedSymbolsStreaming · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
string[].
GET/UnSubscribeRemove one explicit symbol subscription.MT4MT5
GET https://mt4.mt2api.com/UnSubscribeGET https://mt5.mt2api.com/UnSubscribeStreaming · requires X-Api-Key
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
symbol | string · required | Symbol to remove. |
Success response
Unsubscribe acknowledgement.
WS/OnQuoteReceive quote events over an authenticated WebSocket.MT4MT5
WS wss://mt4.mt2api.com/OnQuoteWS wss://mt5.mt2api.com/OnQuoteStreaming · requires X-Api-Key on the WebSocket handshake
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
{ type: "Quote", id, timestampUTC, data: Quote }.
WS/OnOrderUpdateReceive sampled account and order snapshots.MT4MT5
WS wss://mt4.mt2api.com/OnOrderUpdateWS wss://mt5.mt2api.com/OnOrderUpdateStreaming · requires X-Api-Key on the WebSocket handshake
| Parameter | Type / requirement | Description |
|---|---|---|
id | string · required | Session token returned by ConnectEx or Connect. |
Success response
type="OrderUpdate". MT4 data includes orders; MT5 includes openedOrders and user.
No matching endpoints.
Try a different name, parameter, or platform.
Parameters shown cover the common integration surface. Optional aliases and advanced compatibility methods are not exhaustively listed. Platform-specific behavior in this guide takes precedence over assumptions based on a similar method name.
Subscribe. Then stream.
Call Subscribe or SubscribeMany over HTTP, then connect to wss://mt5.mt2api.com/OnQuote?id=… using WebSocket. Use wss: for a gateway served over HTTPS.
The handshake requires X-Api-Key. Native browser WebSocket cannot set that header; connect from your backend with a client such as Node.js ws. Do not place the API key in the URL to work around this.
// Node.js; install the ws package. Do not run in a browser.
import WebSocket from 'ws';
const { MTAPI_API_KEY, MTAPI_SESSION_TOKEN } = process.env;
const gateway = 'https://mt5.mt2api.com';
const subscribe = new URL('/Subscribe', gateway);
subscribe.searchParams.set('id', MTAPI_SESSION_TOKEN);
subscribe.searchParams.set('symbol', 'EURUSD'); // Use your broker's symbol.
const response = await fetch(subscribe, {
headers: { 'X-Api-Key': MTAPI_API_KEY },
redirect: 'error',
signal: AbortSignal.timeout(30_000),
});
if (response.status !== 200 || response.headers.has('X-MtApi-Error-Code')) {
throw new Error('Subscription failed.');
}
const url = new URL('/OnQuote', gateway);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.searchParams.set('id', MTAPI_SESSION_TOKEN);
const socket = new WebSocket(url, {
headers: { 'X-Api-Key': MTAPI_API_KEY },
});
socket.on('message', (raw) => {
try {
const event = JSON.parse(raw.toString());
if (event.type === 'Quote' && event.data) {
console.log(event.data.symbol, event.data.bid, event.data.ask);
} else {
console.warn('Non-quote event; inspect and resynchronize as needed.');
}
} catch {
console.warn('Invalid event; resynchronize before continuing.');
}
});
socket.on('error', () => console.error('Stream error; check session.'));
socket.on('close', () => console.warn('Stream closed; resynchronize before reconnecting.'));
// On shutdown, close the socket AND call UnSubscribe or Disconnect.{
"type": "Quote",
"id": "<SESSION_TOKEN>",
"timestampUTC": 0,
"data": {
"symbol": "<BROKER_SYMBOL>",
"bid": 0,
"ask": 0,
"time": "<BROKER_TIME>"
}
}Zeros above illustrate field types, not actual quotes. timestampUTC is the gateway’s frame-send time in Unix milliseconds. data.time is the broker quote time and may have different timezone semantics.
- Each socket has a bounded 512-event queue; a slow consumer can be disconnected.
- Order events are sampled snapshots. Intermediate states can be missed; there is no replay or sequence-offset guarantee.
- After a disconnect, refresh accounts, positions, pending orders, and relevant history before resuming.
- Closing the socket does not remove explicit symbol subscriptions. Call
UnSubscribeorDisconnectwhen finished.
Respect the platform differences.
Disable automatic retries for order submission, modification, cancellation, and closing in HTTP clients, proxies, and job queues. A timeout may occur after the broker accepts a request. Reconcile before deciding what to do next.
| Operation | MT4 | MT5 |
|---|---|---|
| Place | OrderSend | OrderSendTask |
| Modify | OrderModify | OrderModifyTask |
| Close | OrderClose | OrderCloseTask |
| Cancel pending | OrderDelete | OrderCancelTask |
| Buy / Sell | Buy / Sell strings | 0 / 1 integers |
| Order source | Explicit placedType=Expert | Only placedType=0 |
- Opening size uses
volume; closing size useslots.lots=0closes all current volume. - Slippage is in points, not pips. Validate lot size and increments against the actual broker symbol.
- For modifications, submit existing stop-loss and take-profit values if preserving them. Zero clears them.
- MT5
TaskandSafemethods do not provide durable idempotency.OrderSendSafedoes not acceptexpertID. - MT5 current position tickets, position identifiers, pending-order tickets, and deal tickets are different concepts. Use the current ticket for closing and the position identifier for deal lookup.
- A successful response may reflect a partial fill. Reconcile requested volume, current positions, and deals.
Check more than the status code.
Ordinary API errors default to HTTP 201 and carry X-MtApi-Error-Code. A successful-looking HTTP status or MT5 code: 0 does not establish success. Inspect the error header, HTTP status, error-shaped body, and expected success structure.
HTTP/1.1 201 Created
Content-Type: text/json
X-MtApi-Error-Code: TRADE_RESULT_UNKNOWN
{
"message": "<REDACTED_ERROR_MESSAGE>",
"stackTrace": null,
"nodeName": "<NODE>",
"user": 0,
"code": 0
}| Error / condition | How to handle it |
|---|---|
INVALID_PARAM, INVALID_PARAMETER | Correct the request before sending again. |
INVALID_TOKEN, NO_CONNECTION, CONNECT_ERROR | Verify the session and account identity; stop sending new trades. |
UNSUPPORTED_OPERATION, UNSUPPORTED_PARAMETER | Check deployment capabilities. Do not silently substitute a different operation. |
TIMEOUT, STALE_QUOTE, NO_QUOTES | For reads, apply your retry policy; never present an old quote as fresh. |
TRADE_RESULT_UNKNOWN, TRADE_TIMEOUT, lost response | The broker may have acted. Reconcile orders and deals before any new trade attempt. |
| HTTP 401 / 501 | Usually gateway authentication failure / unsupported operation. Read the error response. |
MT4 ordinary error bodies contain message, stackTrace, code. MT5 additionally includes nodeName, user. Log only redacted context. An empty history result after a connection failure does not prove a trade was never executed.
Build against verified behavior.
Core demo workflows have been exercised on IC Markets MT4 and MT5. IG MT4 has read-only connection evidence, while trading was rejected in documented tests. That does not establish support for every broker, instrument, account mode, or parameter combination.
/healthzchecks gateway liveness./readyzchecks terminal configuration; it does not prove a broker login or trading permission./capabilitiesdescribes deployment limits. Declared routes and static implementation coverage are not acceptance evidence.- MT5 timestamps may carry
Zwithout full broker-time normalization. Use explicit, verified broker-calendar ranges for history. - MT4 history is limited to loaded terminal history. MT5 history depends on broker and SDK availability.
ClosedOrdersis not a full reconciliation source. - OTP/certificate login, general proxy support, broker account creation, and several statistics and timezone functions remain incomplete.
- The self-hosted implementation requires MetaTrader terminal templates inside Docker. Connection capacity depends on infrastructure and workload.