Trading
Place, change and close trades on MT4 and MT5 accounts through the same API you read them with. Each call creates a trade request: the API waits up to about 10 seconds for the broker's answer, and you can read the request and its result for 30 days.
Before you trade
A trading call is refused, and nothing is stored, unless all four of these hold:
| Requirement | How to check | When it is missing |
|---|---|---|
| A Full Access API key | The key's access on the API keys page | A Read Only key gets 403 ForbiddenError. |
| The account is connected with its master password and the broker allows trading | tradeAllowed is true on the account | 403 with E_ACCOUNT_CANNOT_TRADE |
| The account is deployed and connected | state is deployed and connectionStatus is connected | 503 with E_ACCOUNT_NOT_CONNECTED |
| An MT4 account, or an MT5 account in hedging or netting mode | marginMode is hedging or netting on MT5 | 403 with E_TRADING_NOT_SUPPORTED |
- Any Full Access key can trade. A Read Only key cannot, and a key's access is fixed when it is created: to trade, create a Full Access key with Create API Key.
- Any key, Read Only included, can read trade requests.
- A key limited to chosen accounts trades only on those accounts. Any other account id returns
404. tradeAllowedandmarginModearenulluntil the account first reports them after connecting. WhiletradeAllowedisnull, ormarginModeisnullon an MT5 account, a trading call returns503withE_ACCOUNT_NOT_CONNECTED: send it again in a few seconds.
Switch an account to the master password
An account connected with its investor password reads data but cannot trade. Send its master password with Update Account (PATCH /v1/accounts/{id}):
- A deployed account reconnects with the new password: it is undeployed and deployed again, and the call returns it in
undeploying. It keeps its id, history, name, tags and metadata, and redeploying within the paid period costs nothing extra. - While the account is deploying, the call returns
409 ConflictErrorand changes nothing. Send it again once the deploy has finished. - In any other state the password is stored and used the next time the account deploys.
Once it is connected again, check that tradeAllowed is true. It is refreshed on every heartbeat while the account is connected, and it stays false when the password or the broker does not allow trading.
Code samples
The samples on this page share this setup. Replace the key and the account id with your own.
from fundedops import FundedOps
client = FundedOps(api_key="fo_live_...") # a Full Access key
ACCOUNT_ID = "3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10"FO_KEY="fo_live_..." # a Full Access key
ACCOUNT_ID="3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10"
BASE="https://api.fundedops.com/v1"const BASE = "https://api.fundedops.com/v1";
const API_KEY = "fo_live_..."; // a Full Access key
const ACCOUNT_ID = "3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10";
async function call(method, path, { body, idempotencyKey } = {}) {
const headers = { Authorization: `Bearer ${API_KEY}` };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const response = await fetch(`${BASE}${path}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
});
return { status: response.status, headers: response.headers, data: await response.json() };
}using System.Net.Http.Json;
using System.Text.Json;
var http = new HttpClient { BaseAddress = new Uri("https://api.fundedops.com/v1/") };
http.DefaultRequestHeaders.Add("Authorization", "Bearer fo_live_..."); // a Full Access key
var accountId = "3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10";
async Task<(int Status, JsonElement Body)> Call(
HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
{
var request = new HttpRequestMessage(method, path);
if (body is not null) request.Content = JsonContent.Create(body);
if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
var response = await http.SendAsync(request);
return ((int)response.StatusCode, await response.Content.ReadFromJsonAsync<JsonElement>());
}<?php
require 'vendor/autoload.php';
$client = new GuzzleHttp\Client([
'base_uri' => 'https://api.fundedops.com/v1/',
'headers' => ['Authorization' => 'Bearer fo_live_...'], // a Full Access key
'http_errors' => false,
]);
$accountId = '3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10';Switching to the master password, then waiting for the account to connect again:
client.accounts.update(ACCOUNT_ID, password="your-master-password")
account = client.wait_until_connected(ACCOUNT_ID, timeout=300)
print(account.trade_allowed) # Truecurl -X PATCH "$BASE/accounts/$ACCOUNT_ID" \
-H "Authorization: Bearer $FO_KEY" \
-H "Content-Type: application/json" \
-d '{"password": "your-master-password"}'
# Then poll until connectionStatus is "connected".
curl -s "$BASE/accounts/$ACCOUNT_ID" -H "Authorization: Bearer $FO_KEY"await call("PATCH", `/accounts/${ACCOUNT_ID}`, { body: { password: "your-master-password" } });
let account;
do {
await new Promise((resolve) => setTimeout(resolve, 2000));
({ data: account } = await call("GET", `/accounts/${ACCOUNT_ID}`));
} while (account.connectionStatus !== "connected");
console.log(account.tradeAllowed); // trueawait Call(HttpMethod.Patch, $"accounts/{accountId}", new { password = "your-master-password" });
JsonElement account;
do
{
await Task.Delay(TimeSpan.FromSeconds(2));
(_, account) = await Call(HttpMethod.Get, $"accounts/{accountId}");
} while (account.GetProperty("connectionStatus").ToString() != "connected");
Console.WriteLine(account.GetProperty("tradeAllowed").GetBoolean()); // True$client->patch("accounts/$accountId", ['json' => ['password' => 'your-master-password']]);
do {
sleep(2);
$account = json_decode((string) $client->get("accounts/$accountId")->getBody(), true);
} while ($account['connectionStatus'] !== 'connected');
echo var_export($account['tradeAllowed'], true), PHP_EOL; // truePlace an order
POST /v1/accounts/{id}/orders opens a position at the market price or places a pending order.
| Field | Required | Notes |
|---|---|---|
type | Yes | buy and sell fill at the market price. buy_limit, sell_limit, buy_stop and sell_stop wait at price. buy_stop_limit and sell_stop_limit (MT5 only) place a limit order at stopLimitPrice once the price reaches price. |
symbol | Yes | Exactly as the broker names it, for example EURUSD.r. List Symbols returns the names the account accepts. |
volume | Yes | Lots, from the symbol's volumeMin to its volumeMax and on its volumeStep. |
price | Pending orders | The order price. Not allowed on market orders. |
stopLimitPrice | Stop-limit orders | The price of the limit order. |
stopLoss, takeProfit | No | Prices. |
slippage | No | Market orders only. The largest accepted difference from the current price, in points, 0 to 10,000. Default 20. |
comment | No | Up to 31 characters: letters, digits, spaces and _ - . : # / +. |
magic | No | Your own number to tag the order with, 0 to 2,147,483,647. |
expirationType | No | Pending orders only. gtc (the default) until cancelled, day until the end of the trading day, specified until expirationTime. |
expirationTime | With specified | A time in the future. ISO 8601, read as UTC when it has no offset. |
fillingMode | No | MT5 only. fok fills the whole volume or nothing, ioc fills what is available at once, return keeps what is not filled as an order. Leave it out to use a mode the symbol allows. |
expiresInSeconds | No | 5 to 300, default 30. A request the account has not picked up by then expires, and nothing happens at the broker. |
The API checks the request before it reaches the broker and answers 400 ValidationError when:
- the body has a field the API does not know, so a misspelled
stoplossnever trades without its stop loss; - a market order has
price, or a pending order hasslippage; - the volume is outside the symbol's range or off its lot step. The volume is never rounded: the message names the allowed range and
metadatacarriescodeE_INVALID_VOLUME,volumeMin,volumeMaxandvolumeStep. Get Symbol (GET /) has the same three values;v1/ accounts/ {id}/ symbols/ {symbol} - the account does not list the symbol, or the broker does not allow the trade for it (
metadata.codeE_TRADE_DISABLED, orE_CLOSE_ONLYwhen the symbol only allows closing).
Prices and volumes take up to 10 decimal places.
trade = client.place_order(
ACCOUNT_ID, "buy", "EURUSD", 0.1,
stop_loss=1.079, take_profit=1.092,
)
print(trade.status, trade.idempotency_key)
if trade.status == "done":
print(trade.result.position_ticket, trade.result.price)curl -i -X POST "$BASE/accounts/$ACCOUNT_ID/orders" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: buy-eurusd-0001" \
-H "Content-Type: application/json" \
-d '{"type": "buy", "symbol": "EURUSD", "volume": 0.1, "stopLoss": 1.079, "takeProfit": 1.092}'const key = crypto.randomUUID(); // store it to retry this trade
const { status, data } = await call("POST", `/accounts/${ACCOUNT_ID}/orders`, {
body: { type: "buy", symbol: "EURUSD", volume: 0.1, stopLoss: 1.079, takeProfit: 1.092 },
idempotencyKey: key,
});
console.log(status, data.status ?? data.error);var key = Guid.NewGuid().ToString("N"); // store it to retry this trade
var (status, body) = await Call(HttpMethod.Post, $"accounts/{accountId}/orders",
new { type = "buy", symbol = "EURUSD", volume = 0.1m, stopLoss = 1.079m, takeProfit = 1.092m }, key);
Console.WriteLine($"{status} {body}");$key = bin2hex(random_bytes(16)); // store it to retry this trade
$response = $client->post("accounts/$accountId/orders", [
'headers' => ['Idempotency-Key' => $key],
'json' => ['type' => 'buy', 'symbol' => 'EURUSD', 'volume' => 0.1, 'stopLoss' => 1.079, 'takeProfit' => 1.092],
]);
echo $response->getStatusCode(), ' ', $response->getBody(), PHP_EOL;A 200 returns the trade request:
{
"id": "6a2f9c1e-4b7d-4e2a-9f0c-1d3e5b7a9c21",
"accountId": "3f6c1a2e-8b4d-4e0f-9a51-7c2d9e4b8a10",
"action": "place_order",
"status": "done",
"params": {"type": "buy", "symbol": "EURUSD", "volume": "0.1", "sl": "1.079", "tp": "1.092"},
"result": {
"orderTicket": "1834921107",
"positionTicket": "1834920571",
"dealTicket": "1612048873",
"price": 1.08412,
"volume": 0.1,
"brokerCode": 10009,
"message": "Request executed"
},
"error": null,
"createdAt": "2026-11-15T10:32:05.118223Z",
"expiresAt": "2026-11-15T10:32:35.118223Z",
"completedAt": "2026-11-15T10:32:05.684512Z"
}params is the request as the account received it, with every value as text. On the modify endpoints keep leaves a value unchanged and 0 removes a stop loss or take profit.
Idempotency keys
Every trading write needs an Idempotency-Key header: your own id for that trade, 1 to 64 characters of letters, digits and _ . : -. Without a valid key the call returns 400 with metadata.code E_IDEMPOTENCY_KEY_MISSING.
Create a new key for every new trade and store it before you send the request. When you do not know whether a call arrived (a timeout, a dropped connection, a restart, or a 502 or 504 from a proxy on the way), send the same request again with the same key. You get the first request's outcome instead of a second trade.
| You send the same key with | You get |
|---|---|
| The same request, already finished | The first answer again, with the same status code and body and the header Idempotent-Replayed: true. This applies to 200, 422 and 503 answers. |
The same request, still in progress or unknown | 202 with the request's current status, a Location header and Idempotent-Replayed: true. |
| A different request | 422 IdempotencyKeyReusedError with metadata.code E_IDEMPOTENCY_KEY_REUSED. Nothing is sent. |
- Keys are shared by all API keys of your developer account and remembered for 30 days.
- Requests are compared by their values, not their text: a volume of
0.1and0.10is the same request. The same key sent to another account or another endpoint returns422 IdempotencyKeyReusedError. expiresInSecondsis not compared: a retry with another value returns the first request.- A call refused before it is stored is not remembered. After a
400,401,403,404,429or a503withE_ACCOUNT_NOT_CONNECTED, fix the cause and send it again with the same key. - To send a trade again after it was rejected or expired, use a new key. The old key keeps returning the first answer.
The Python SDK sends a new key (uuid4().hex) with every call unless you pass idempotency_key=. It returns the key as trade.idempotency_key, and every error it raises carries it as err.idempotency_key, so you can retry with it. When the connection fails before any answer arrives (a timeout, a reset), the call raises TradeOutcomeUnknownError with the key: send the same call again with it.
Responses and statuses
A trading write waits up to about 10 seconds for the broker, then answers with the trade request:
| Status code | Trade request status | Meaning |
|---|---|---|
200 | done | The broker carried it out. result has the tickets and the fill. |
202 | queued, sent or unknown | Not finished within the wait. Location is the trade request's path. |
422 TradeRejectedError | rejected | Refused. metadata has code, brokerCode, retryable and tradeRequestId. |
503 ServiceUnavailableError, metadata.code E_REQUEST_EXPIRED | expired | Never sent, so nothing happened at the broker. metadata.tradeRequestId identifies it. Send it again with a new key. |
| Status | Final | Meaning |
|---|---|---|
queued | No | Stored, waiting for the account to pick it up. |
sent | No | The account has it and is waiting for the broker. |
done | Yes | The broker carried it out. |
rejected | Yes | Refused. error says why. |
expired | Yes | Not picked up within expiresInSeconds, or picked up too late and never sent. Nothing happened at the broker. |
unknown | Yes, until a late answer arrives | Sent to the broker, but the outcome was never confirmed. Check positions and orders before sending it again. |
Waiting for the outcome
After a 202, poll Get Trade Request at the Location path until the status is final, or wait for the trade_request.completed webhook described below. The Python SDK's wait_for_trade_request polls for you and returns the final trade request; it raises TimeoutError when timeout passes first.
trade = client.place_order(ACCOUNT_ID, "buy", "EURUSD", 0.1)
if trade.status in ("queued", "sent"):
trade = client.wait_for_trade_request(ACCOUNT_ID, trade.id, timeout=60)
print(trade.status)# Location from the 202: /v1/accounts/{id}/trade-requests/{tradeRequestId}
curl -s "$BASE/accounts/$ACCOUNT_ID/trade-requests/$TRADE_REQUEST_ID" \
-H "Authorization: Bearer $FO_KEY"async function waitForTradeRequest(id, timeoutMs = 60000) {
const deadline = Date.now() + timeoutMs;
while (true) {
const { data } = await call("GET", `/accounts/${ACCOUNT_ID}/trade-requests/${id}`);
if (["done", "rejected", "expired", "unknown"].includes(data.status)) return data;
if (Date.now() > deadline) throw new Error(`trade request ${id} is still ${data.status}`);
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}async Task<JsonElement> WaitForTradeRequest(string id, TimeSpan timeout)
{
var final = new[] { "done", "rejected", "expired", "unknown" };
var deadline = DateTime.UtcNow + timeout;
while (true)
{
var (_, trade) = await Call(HttpMethod.Get, $"accounts/{accountId}/trade-requests/{id}");
var status = trade.GetProperty("status").GetString();
if (final.Contains(status)) return trade;
if (DateTime.UtcNow > deadline) throw new TimeoutException($"trade request {id} is still {status}");
await Task.Delay(TimeSpan.FromSeconds(1));
}
}function waitForTradeRequest($client, string $accountId, string $id, int $timeout = 60): array
{
$deadline = time() + $timeout;
while (true) {
$trade = json_decode((string) $client->get("accounts/$accountId/trade-requests/$id")->getBody(), true);
if (in_array($trade['status'], ['done', 'rejected', 'expired', 'unknown'], true)) {
return $trade;
}
if (time() > $deadline) {
throw new RuntimeException("trade request $id is still {$trade['status']}");
}
sleep(1);
}
}When the status is unknown
The request reached the broker, but no outcome came back: the broker did not answer, the account sent no answer within a minute after expiresAt, or the account lost its connection to the broker while it sent an open or a close (result.brokerCode is 10031 on MT5 or 6 on MT4), so the request may have reached the broker's server. The trade may or may not have happened.
- Do not send the trade again yet. The same key only returns
unknownagain, and a new key could trade twice. - Look for the trade in List Positions, List Pending Orders and List History Deals, for example by its
commentormagic. - If you find it, treat the request as done. Send the trade again with a new key only when you are sure it did not happen.
A late answer still counts: the trade request changes to done or rejected, or to expired when the account received it too late and never sent it, and a second trade_request.completed webhook is sent with the real outcome.
When a request expires
A 503 with metadata.code E_REQUEST_EXPIRED means the account did not pick the request up within expiresInSeconds, for example because its connection was briefly down. Nothing was sent to the broker. Check that the trade still makes sense at the current price, then send it again with a new key.
The answer is the same when the account received the request after its time had run out: it does not send it, and the trade request ends expired with error.retryable true.
Modify a pending order
PATCH / changes a pending order's price, stopLimitPrice (MT5 stop-limit orders), stopLoss, takeProfit, expirationType and expirationTime.
- A field you leave out keeps its current value.
nullremoves a stop loss or take profit. price,stopLimitPriceandexpirationTypecannot benull. SendexpirationTypegtcto remove an expiration, on MT4 too.- Send at least one of
price,stopLimitPrice,stopLoss,takeProfitorexpirationType.
# The stop loss is left at KEEP (the default), so it does not change.
# None removes the take profit.
trade = client.modify_order(ACCOUNT_ID, "1834921107", price=1.0795, take_profit=None)curl -X PATCH "$BASE/accounts/$ACCOUNT_ID/orders/1834921107" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: modify-1834921107-0001" \
-H "Content-Type: application/json" \
-d '{"price": 1.0795, "takeProfit": null}'const { status, data } = await call("PATCH", `/accounts/${ACCOUNT_ID}/orders/1834921107`, {
body: { price: 1.0795, takeProfit: null },
idempotencyKey: crypto.randomUUID(),
});var (status, body) = await Call(HttpMethod.Patch, $"accounts/{accountId}/orders/1834921107",
new { price = 1.0795m, takeProfit = (decimal?)null }, Guid.NewGuid().ToString("N"));$response = $client->patch("accounts/$accountId/orders/1834921107", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
'json' => ['price' => 1.0795, 'takeProfit' => null],
]);Cancel a pending order
DELETE / cancels a pending order. It has no body.
trade = client.cancel_order(ACCOUNT_ID, "1834921107")curl -X DELETE "$BASE/accounts/$ACCOUNT_ID/orders/1834921107" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: cancel-1834921107-0001"const { status, data } = await call("DELETE", `/accounts/${ACCOUNT_ID}/orders/1834921107`, {
idempotencyKey: crypto.randomUUID(),
});var (status, body) = await Call(HttpMethod.Delete, $"accounts/{accountId}/orders/1834921107",
idempotencyKey: Guid.NewGuid().ToString("N"));$response = $client->delete("accounts/$accountId/orders/1834921107", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
]);Modify a position
PATCH / changes an open position's stopLoss and takeProfit. A field you leave out keeps its value, null removes it, and at least one of the two must be sent.
# The take profit is left at KEEP, so only the stop loss changes.
trade = client.modify_position(ACCOUNT_ID, "1834920571", stop_loss=1.0815)curl -X PATCH "$BASE/accounts/$ACCOUNT_ID/positions/1834920571" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: sl-1834920571-0001" \
-H "Content-Type: application/json" \
-d '{"stopLoss": 1.0815}'const { status, data } = await call("PATCH", `/accounts/${ACCOUNT_ID}/positions/1834920571`, {
body: { stopLoss: 1.0815 },
idempotencyKey: crypto.randomUUID(),
});var (status, body) = await Call(HttpMethod.Patch, $"accounts/{accountId}/positions/1834920571",
new { stopLoss = 1.0815m }, Guid.NewGuid().ToString("N"));$response = $client->patch("accounts/$accountId/positions/1834920571", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
'json' => ['stopLoss' => 1.0815],
]);Close a position
POST / closes an open position. The body is optional:
volumecloses part of the position, in lots on the symbol'svolumeStep. Leave it out to close the whole position. A volume above the position's volume is rejected withE_INVALID_CLOSE_VOLUMEbefore anything is sent, so a close never opens a position the other way.slippagein points, 0 to 10,000. Default 20.
trade = client.close_position(ACCOUNT_ID, "1834920571", volume=0.05)curl -X POST "$BASE/accounts/$ACCOUNT_ID/positions/1834920571/close" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: close-1834920571-0001" \
-H "Content-Type: application/json" \
-d '{"volume": 0.05}'const { status, data } = await call("POST", `/accounts/${ACCOUNT_ID}/positions/1834920571/close`, {
body: { volume: 0.05 },
idempotencyKey: crypto.randomUUID(),
});var (status, body) = await Call(HttpMethod.Post, $"accounts/{accountId}/positions/1834920571/close",
new { volume = 0.05m }, Guid.NewGuid().ToString("N"));$response = $client->post("accounts/$accountId/positions/1834920571/close", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
'json' => ['volume' => 0.05],
]);Close all positions
POST / closes every open position in one trade request. The body is optional: symbol closes only the positions on that symbol, and slippage works as above.
result.positionslists each position with itsticket, itsstatus(done,rejectedorunknown) and, when it was not closed, itsbrokerCode.- When every position closed, the request is
done. With no open positions it isdonewith an empty list. - When any position was not closed, the request is
rejectedwith422andcodeE_SOME_POSITIONS_NOT_CLOSED. Read the trade request (metadata.tradeRequestId) forresult.positions. - When the outcome of any position is not known, the request is
unknown, also when other positions were not closed. A close sent while the account lost its connection to the broker (brokerCode10031on MT5 or6on MT4) counts as not known: its entry'sstatusisunknown, as that position may be closed. - A position that closed by itself in the meantime (stop loss, take profit, by hand) is left out, and one the broker reports as already closed counts as
done.
from fundedops import TradeRejectedError
try:
trade = client.close_positions(ACCOUNT_ID, symbol="EURUSD")
except TradeRejectedError as err:
trade = client.get_trade_request(ACCOUNT_ID, err.trade_request_id)
if trade.result:
for position in trade.result.positions:
print(position["ticket"], position["status"], position.get("brokerCode"))curl -X POST "$BASE/accounts/$ACCOUNT_ID/positions/close" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: close-all-eurusd-0001" \
-H "Content-Type: application/json" \
-d '{"symbol": "EURUSD"}'const { status, data } = await call("POST", `/accounts/${ACCOUNT_ID}/positions/close`, {
body: { symbol: "EURUSD" },
idempotencyKey: crypto.randomUUID(),
});var (status, body) = await Call(HttpMethod.Post, $"accounts/{accountId}/positions/close",
new { symbol = "EURUSD" }, Guid.NewGuid().ToString("N"));$response = $client->post("accounts/$accountId/positions/close", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
'json' => ['symbol' => 'EURUSD'],
]);Close by an opposite position
POST / closes the position ticket against an opposite position on the same symbol. The body takes oppositeTicket (required) and expiresInSeconds.
- Both positions must be open, on the same symbol and in opposite directions. Otherwise the call returns
400withmetadata.codeE_INVALID_CLOSE_BYbefore anything is stored. When the API does not know a position yet, the account refuses instead and the trade request isrejectedwith the same code. - It works on MT4 and on MT5 hedging accounts. An MT5 netting account returns
403withE_TRADING_NOT_SUPPORTED. - The volumes can differ. The smaller position closes and the larger one stays open with the rest.
result.volumeis the volume closed on each side, andresult.remainingTicketis the ticket of the position left open, ornullwhen both closed in full. - On MT4 the rest stays open under a new ticket, and
remainingTicketis that ticket. When the new ticket cannot be identified,remainingTicketis left out andmessagesays so: list the positions to find it. - It needs a Full Access key and an
Idempotency-Key, and it waits for the broker like Place Order.
trade = client.close_position_by(ACCOUNT_ID, "1834920571", "1834920572")
if trade.result:
print(trade.result.volume, trade.result.remaining_ticket)curl -X POST "$BASE/accounts/$ACCOUNT_ID/positions/1834920571/close-by" \
-H "Authorization: Bearer $FO_KEY" \
-H "Idempotency-Key: close-by-1834920571-0001" \
-H "Content-Type: application/json" \
-d '{"oppositeTicket": "1834920572"}'const { status, data } = await call("POST", `/accounts/${ACCOUNT_ID}/positions/1834920571/close-by`, {
body: { oppositeTicket: "1834920572" },
idempotencyKey: crypto.randomUUID(),
});
console.log(status, data.result?.volume, data.result?.remainingTicket);var (status, body) = await Call(HttpMethod.Post, $"accounts/{accountId}/positions/1834920571/close-by",
new { oppositeTicket = "1834920572" }, Guid.NewGuid().ToString("N"));
Console.WriteLine($"{status} {body}");$response = $client->post("accounts/$accountId/positions/1834920571/close-by", [
'headers' => ['Idempotency-Key' => bin2hex(random_bytes(16))],
'json' => ['oppositeTicket' => '1834920572'],
]);
echo $response->getStatusCode(), ' ', $response->getBody(), PHP_EOL;Check an order before sending it
Three read-only calls ask the account's broker what a trade would cost, and nothing is placed. Any API key can call them, Read Only included, because they are GET requests. The numbers come from the account's broker, in the account currency, and each call waits up to about 10 seconds for the account.
Calculate margin
GET / takes symbol, type and volume, and optionally price. Without price the current price is used, and the answer's price is the one the margin was worked out at. Any positive volume is calculated, on the lot step or not.
margin = client.accounts.calculate_margin(ACCOUNT_ID, "EURUSD", "buy", 0.1)
print(margin.margin, margin.currency)curl -s "$BASE/accounts/$ACCOUNT_ID/calculate-margin?symbol=EURUSD&type=buy&volume=0.1" \
-H "Authorization: Bearer $FO_KEY"const { data } = await call(
"GET",
`/accounts/${ACCOUNT_ID}/calculate-margin?symbol=EURUSD&type=buy&volume=0.1`,
);
console.log(data.margin, data.currency);var (_, margin) = await Call(HttpMethod.Get,
$"accounts/{accountId}/calculate-margin?symbol=EURUSD&type=buy&volume=0.1");
Console.WriteLine($"{margin.GetProperty("margin")} {margin.GetProperty("currency")}");$margin = json_decode((string) $client->get("accounts/$accountId/calculate-margin", [
'query' => ['symbol' => 'EURUSD', 'type' => 'buy', 'volume' => 0.1],
])->getBody(), true);
echo $margin['margin'], ' ', $margin['currency'], PHP_EOL;{"symbol": "EURUSD", "type": "buy", "volume": 0.1, "price": 1.0842, "margin": 108.42, "currency": "USD"}Calculate profit
GET / takes symbol, type (buy or sell, the direction of the trade), volume, openPrice and closePrice. A loss is negative. Any positive volume is calculated.
{"symbol": "EURUSD", "type": "buy", "volume": 1.0, "openPrice": 1.08, "closePrice": 1.0855, "profit": 550.0, "currency": "USD"}Check order
GET / takes Place Order's fields as query parameters: type, symbol, volume, and price, stopLimitPrice, stopLoss and takeProfit where the order type uses them. It validates them exactly like Place Order, so a malformed request is a 400 here too.
- A valid order that the account would refuse is still a
200withcanPlacefalse.codeandmessagehold what Place Order would answer, for exampleE_INVALID_VOLUME,E_TRADE_DISABLED,E_NO_MONEY,E_ACCOUNT_CANNOT_TRADEorE_TRADING_NOT_SUPPORTED. An investor-password account getsE_ACCOUNT_CANNOT_TRADEthis way, not a403. - When
canPlaceistrue,codeandmessagearenull.marginis the margin the order adds to the account's margin in use.freeMargin,marginLevel,balanceandequitydescribe the account after the order. All five arenullwhen the order cannot be placed for a reason other than free margin. volumemust be on the symbol's lot step, as in Place Order. Calculate Margin and Calculate Profit do not check it.- An account that is not connected is a
503, as for every call that needs the account.
check = client.accounts.check_order(ACCOUNT_ID, "buy", "EURUSD", 0.1, stop_loss=1.079)
if check.can_place:
print(check.margin, check.free_margin, check.margin_level)
else:
print(check.code, check.message)curl -s "$BASE/accounts/$ACCOUNT_ID/check-order?type=buy&symbol=EURUSD&volume=0.1&stopLoss=1.079" \
-H "Authorization: Bearer $FO_KEY"const { data } = await call(
"GET",
`/accounts/${ACCOUNT_ID}/check-order?type=buy&symbol=EURUSD&volume=0.1&stopLoss=1.079`,
);
console.log(data.canPlace ? data.freeMargin : `${data.code}: ${data.message}`);var (_, check) = await Call(HttpMethod.Get,
$"accounts/{accountId}/check-order?type=buy&symbol=EURUSD&volume=0.1&stopLoss=1.079");
Console.WriteLine(check.GetProperty("canPlace").GetBoolean()
? check.GetProperty("freeMargin").ToString()
: $"{check.GetProperty("code")}: {check.GetProperty("message")}");$check = json_decode((string) $client->get("accounts/$accountId/check-order", [
'query' => ['type' => 'buy', 'symbol' => 'EURUSD', 'volume' => 0.1, 'stopLoss' => 1.079],
])->getBody(), true);
echo $check['canPlace'] ? $check['freeMargin'] : "{$check['code']}: {$check['message']}", PHP_EOL;An order that can be placed:
{
"canPlace": true,
"code": null,
"message": null,
"margin": 108.42,
"freeMargin": 9891.58,
"marginLevel": 9223.39,
"balance": 10000.0,
"equity": 10000.0
}An order the account would refuse:
{
"canPlace": false,
"code": "E_NO_MONEY",
"message": "There is not enough free margin for this request.",
"margin": 108420.0,
"freeMargin": -98420.0,
"marginLevel": 9.2,
"balance": 10000.0,
"equity": 10000.0
}Read trade requests
List Trade Requests (GET /) returns the account's trade requests newest first, with offset and limit like the other lists (100 by default, up to 1,000). Get Trade Request (GET /) returns one. Any API key can read them, and they are kept for 30 days.
for trade in client.list_trade_requests(ACCOUNT_ID, limit=20):
print(trade.created_at, trade.action, trade.status)curl -s "$BASE/accounts/$ACCOUNT_ID/trade-requests?limit=20" \
-H "Authorization: Bearer $FO_KEY"const { data } = await call("GET", `/accounts/${ACCOUNT_ID}/trade-requests?limit=20`);
for (const trade of data.tradeRequests) console.log(trade.createdAt, trade.action, trade.status);var (_, list) = await Call(HttpMethod.Get, $"accounts/{accountId}/trade-requests?limit=20");
foreach (var trade in list.GetProperty("tradeRequests").EnumerateArray())
Console.WriteLine($"{trade.GetProperty("createdAt")} {trade.GetProperty("action")} {trade.GetProperty("status")}");$list = json_decode((string) $client->get("accounts/$accountId/trade-requests?limit=20")->getBody(), true);
foreach ($list['tradeRequests'] as $trade) {
echo $trade['createdAt'], ' ', $trade['action'], ' ', $trade['status'], PHP_EOL;
}Results
Which keys a done trade request's result holds depends on the action. Tickets are strings.
| Action | Result keys |
|---|---|
| Place Order, market | orderTicket, positionTicket, dealTicket (MT5), price (the fill), volume |
| Place Order, pending | orderTicket, price, volume |
| Modify Order | orderTicket, price |
| Cancel Order | orderTicket |
| Modify Position | positionTicket |
| Close Position | positionTicket, orderTicket, dealTicket (MT5), price (the close price), volume (the closed volume) |
| Close Position By | volume (closed on each side), remainingTicket (the position left open, or null), orderTicket and dealTicket (MT5) |
| Close Positions | positions |
brokerCode and message are added when the broker sent them. A rejected request has error (code, message, brokerCode, retryable) and can also have a result.
Platform differences
MT4
- No stop-limit orders:
buy_stop_limit,sell_stop_limitandstopLimitPricereturn400. - No
fillingMode: sending it returns400. - A pending order can expire only at a set time: on Place Order send
expirationTypespecifiedwithexpirationTime, or leave both out.gtcanddayreturn400. Modify Order also takesgtc, which removes the expiration;dayreturns400. - A set expiration can only be placed while the forex market is open. At other times, or when the broker does not allow expirations, the request is rejected with
E_INVALID_EXPIRATION. - One ticket per order: a market order's
orderTicketandpositionTicketare the same, and there are no deal tickets. - A partial close leaves the rest of the position open under a new ticket. The result's
positionTicketis that new ticket andorderTicketis the closed one. When the broker's records do not name the new ticket,positionTicketis left out andmessagesays so: list the positions to find it. - Close Position By leaves the larger position's rest open under a new ticket, and
remainingTicketis that ticket. When the new ticket cannot be identified,remainingTicketis left out andmessagesays so. - Calculate Margin is MT4's margin per lot times the volume, at the current price. With a
price, CFD and index symbols scale with that price, and forex and futures symbols do not. Calculate Profit uses the symbol's tick value at the current exchange rate. - MT4 has no order check function, so Check Order runs these checks in order and stops at the first that fails: trading allowed (account, symbol and AutoTrading), volume limits and step, stop distance, free margin. Free margin is checked for market orders only, because a pending order needs no margin until it triggers.
MT5
- Calculate Margin, Calculate Profit and Check Order use the platform's own margin, profit and order check functions.
MT5 netting
- An account holds one position per symbol. A buy on an open sell reduces, closes or reverses it, and a buy on an open buy adds to it.
- Modify Position and Close Position take the position's ticket, as in List Positions.
- The
positionTicketin a result is the position's identifier, and it keeps working for that position. - Close Position By returns
403withE_TRADING_NOT_SUPPORTED: it works on hedging accounts only.
Expiration times
expirationTime is UTC. The account converts it to the broker's server time with the server's current UTC offset, so an expiration that falls after a daylight saving change on the server can be one hour off.
Webhook
The trade_request.completed event is sent when a trade request finishes as done, rejected, expired or unknown. data.tradeRequest is the trade request as Get Trade Request returns it, and data.account is the account. When a late answer turns an unknown request into done, rejected or expired, a second event is sent for the same trade request with the real status. Choose the event for an endpoint on the Webhooks page; see the Webhooks guide for signatures and retries.
Positions and orders also change in reads, in the stream and in the position.opened, position.closed and deal.added events shortly after a trade.
Errors
Every trading error uses the standard error body. metadata.code is a stable code to branch on.
Refused before anything is stored
Nothing is stored or sent. Fix the cause, then send the request again: with the same key, except after E_IDEMPOTENCY_KEY_REUSED, which needs a new key.
| Status | Code | Meaning |
|---|---|---|
400 | E_IDEMPOTENCY_KEY_MISSING | The Idempotency-Key header is missing or invalid. |
400 | E_INVALID_VOLUME | The volume is outside the symbol's range or off its lot step. metadata has volumeMin, volumeMax and volumeStep. |
400 | E_TRADE_DISABLED | The broker does not allow this trade on the symbol: trading is disabled, or only buys or only sells are allowed. |
400 | E_CLOSE_ONLY | The symbol only allows closing positions. |
400 | E_INVALID_CLOSE_BY | Close Position By: the two tickets are the same, are on different symbols or are in the same direction. details names oppositeTicket. |
400 | none | Any other invalid field. details names it. |
403 | none | The API key is Read Only. |
403 | E_ACCOUNT_CANNOT_TRADE | The account is connected with its investor password, or the broker has disabled trading. |
403 | E_TRADING_NOT_SUPPORTED | Trading is not available for the account's platform and margin mode. |
404 | none | The account or trade request does not exist, or the API key is limited to other accounts. |
422 | E_IDEMPOTENCY_KEY_REUSED | IdempotencyKeyReusedError: the key was used for a different request. Use a new key. |
429 | none | The request rate limit. metadata and Retry-After are sent. |
429 | E_QUEUE_FULL | 50 trade requests are already waiting for the account. No Retry-After: send it again once some have finished. |
503 | E_ACCOUNT_NOT_CONNECTED | The account is not deployed and connected, or its connection has not reported yet whether it can trade (tradeAllowed is null, or marginMode is null on MT5). |
Outcomes of a trade request
422 TradeRejectedError and 503 with E_REQUEST_EXPIRED are outcomes of a stored trade request: its error.code holds the same code. retryable says whether the same trade can succeed when you send it again with a new key, after a short wait. When it is false, change the request first.
brokerCode is the broker's own code: an MT5 return code or an MT4 error number. Negative numbers are FundedOps codes for requests the account refused before they reached the broker.
| Code | Meaning | Retryable |
|---|---|---|
E_REQUOTE | The price changed before the broker could fill the request. | Yes |
E_REJECTED | The broker rejected the request. | No |
E_BROKER_TIMEOUT | The broker did not answer in time. Check the order state before retrying. | Yes |
E_INVALID_REQUEST | The broker did not accept the request parameters. | No |
E_INVALID_VOLUME | The volume is not valid for this symbol. | No |
E_INVALID_PRICE | The price is not valid. | No |
E_INVALID_STOPS | The stop loss or take profit is too close to the market price, or invalid. | No |
E_INVALID_EXPIRATION | The expiration could not be used. | No |
E_INVALID_FILL | The broker does not support this filling mode for the symbol. | No |
E_INVALID_CLOSE_VOLUME | The close volume is larger than the position volume. Nothing was sent. | No |
E_INVALID_CLOSE_BY | Close Position By: the two positions are not open on the same symbol in opposite directions. | No |
E_TRADE_DISABLED | Trading is disabled for this symbol or account, also when the broker's server disables automated trading. | No |
E_CLOSE_ONLY | The broker only allows closing positions for this symbol. | No |
E_MARKET_CLOSED | The market is closed. | No |
E_NO_MONEY | There is not enough free margin for this request. | No |
E_NO_QUOTES | The broker has no prices for this symbol right now. | Yes |
E_ORDER_LOCKED | The order or position is being processed. | Yes |
E_FROZEN | The order or position is frozen because it is too close to the market price. | Yes |
E_TOO_MANY_REQUESTS | Too many requests were sent to the broker. | Yes |
E_TOO_MANY_ORDERS | The account reached the broker's limit for orders or positions. | No |
E_AUTOTRADING_DISABLED | Automated trading is disabled for this account. | Yes |
E_NO_CONNECTION | The account has no connection to the broker. Returned for changes and cancels only: an open or a close ends unknown instead. | Yes |
E_BUSY | The trade context is busy. | Yes |
E_FIFO | The broker requires positions to be closed in FIFO order. | No |
E_POSITION_NOT_FOUND | The position does not exist. It may already be closed. | No |
E_ORDER_NOT_FOUND | The order does not exist. It may already be filled or cancelled. | No |
E_SOME_POSITIONS_NOT_CLOSED | Close Positions: some positions were not closed. result.positions has the details. | No |
E_NOT_SENT | The request was not sent and nothing changed on the account. | Yes |
E_REQUEST_EXPIRED | The request expired before it was sent to the broker. Nothing happened: send it again with a new key. Always a 503. | Yes |
E_ACCOUNT_CANNOT_TRADE | Trading is not allowed on this account. | No |
E_TRADING_NOT_SUPPORTED | This connection does not support trading. | No |
E_BROKER_ERROR | Any other broker code. brokerCode has it. | No |
Broker codes map to these codes by meaning. For example, MT4 errors 4051 and 4106 (unknown symbol) are E_INVALID_REQUEST, 4107 is E_INVALID_PRICE, and 4110 and 4111 (buys or sells not allowed) are E_TRADE_DISABLED. MT5 code 10026 and MT4 error 4112 (the broker's server disabled automated trading) are also E_TRADE_DISABLED and not retryable, while MT5 code 10027 is E_AUTOTRADING_DISABLED.
With the Python SDK a 422 raises TradeRejectedError (code, broker_code, retryable, trade_request_id), a 503 with E_REQUEST_EXPIRED raises TradeExpiredError, a reused key raises IdempotencyKeyReusedError, and a connection that fails before any answer raises TradeOutcomeUnknownError:
from fundedops import (
IdempotencyKeyReusedError,
TradeExpiredError,
TradeOutcomeUnknownError,
TradeRejectedError,
)
try:
trade = client.place_order(ACCOUNT_ID, "buy", "EURUSD", 0.1)
except TradeRejectedError as err:
print(err.code, err.broker_code, err.retryable, err.trade_request_id)
except TradeExpiredError as err:
print("not sent, nothing happened:", err.trade_request_id)
except TradeOutcomeUnknownError as err:
print("no answer, send it again with the same key:", err.idempotency_key)
except IdempotencyKeyReusedError as err:
print("key already used for another request:", err.idempotency_key)Limits
| Limit | Value |
|---|---|
| Wait for the broker's answer | About 10 seconds, then 202 |
expiresInSeconds | 5 to 300, default 30 |
Trade requests waiting per account (queued or sent) | 50. More returns 429 with E_QUEUE_FULL. |
| Trade requests and idempotency keys kept | 30 days |
| Requests per second, per developer account | 25, with bursts up to 100, shared with every other endpoint |