- Base URL
https://merlintrade.io/api/v1- Auth
- A bearer token the trader issues in Merlin (Settings → API tokens), with the scopes and accounts they choose and an optional expiry. Shown to them once; Merlin stores only its SHA-256.
- Writes
- Up to 500 trades per call. Every trade answers for itself; one bad record never sinks the batch.
- Idempotency
- Each trade is keyed by your own id, so a retry can never double-count. Send an Idempotency-Key header too and a retried call replays its first answer.
- Limits
- 600 calls a minute per token (120 of them writes), 600 per IP, 1 MB per request, insights 30 a minute
- Direction
- Merlin never places, changes or closes a trade. A token reaches one trader, and only the accounts they allow.
01Tokens and scopes
Access is the trader's to give. In Merlin they open Settings → API tokens, name the token after your platform, pick what it can do and which accounts it reaches, and copy it into your settings. They see when it was last used and can revoke it in one click; a revoked token is refused on its next call. Send it as Authorization: Bearer mtk_live_….
| Scope | Allows |
|---|---|
| trades:write | Write trades into the accounts the token reaches. |
| accounts:write | Link the trader's accounts to your ids, or create new ones (not for a token limited to chosen accounts). |
| accounts:read | List the accounts the token reaches. |
| trades:read | Read trades back, with Merlin's net-of-fee figure. |
| insights:read | Read the reading Merlin gives an account: the figures, the verdict, every behaviour check. |
02Endpoints
| Path | Scope | What it does | |
|---|---|---|---|
| GET | /me | any | The token in use: its scopes, accounts, expiry and limits. |
| GET | /accounts | accounts:read | Accounts the token reaches, with trade counts. |
| POST | /accounts | accounts:write | Link or create an account by your own id (externalRef). |
| POST | /trades | trades:write | Write up to 500 trades. Created, updated, unchanged or rejected, per trade. |
| GET | /trades | trades:read | Read trades, oldest first, by cursor. Filter by account or time. |
| GET | /accounts/{id}/insights | insights:read | The reading for one account over 7 to 365 days. |
03Writing trades
A trade is keyed by its account and your externalId. A new id is created; a known id is updated if anything moved (a partial close, a corrected fee) and left alone if nothing did; so a retry, or a full resync, can never double-count. A trade that matches one already imported from a statement with the same ticket updates it rather than adding a second. Every record answers for itself, in request order. New trades count against the trader's plan (the free plan holds 100); updates never do.
POST /api/v1/trades
Authorization: Bearer mtk_live_...
Idempotency-Key: stt-batch-20261124-000731
Content-Type: application/json
{
"trades": [
{
"externalId": "58211047",
"accountRef": "stt-follower-7731",
"symbol": "EURUSD",
"side": "buy",
"quantity": 0.5,
"openTime": "2026-11-24T08:02:11Z",
"closeTime": "2026-11-24T09:15:40Z",
"entryPrice": 1.0812,
"exitPrice": 1.0841,
"stopLoss": 1.079,
"pnl": 145.0,
"commission": -3.5,
"swap": 0,
"comment": "copied from master 7731"
}
]
}HTTP/1.1 200 OK
X-Request-Id: req_Hk3v9QmTq1pZ
{
"data": [
{ "index": 0, "externalId": "58211047", "accountId": 412, "status": "created" },
{ "index": 1, "externalId": "58211048", "status": "rejected",
"error": { "code": "invalid_field", "param": "trades[1].closeTime",
"message": "closeTime must be at or after openTime, and not in the future." } }
],
"summary": { "received": 2, "created": 1, "updated": 0, "unchanged": 0, "rejected": 1 },
"requestId": "req_Hk3v9QmTq1pZ"
}| Field | Type | Meaning |
|---|---|---|
| externalId | string, 1–64 | Your id for the position (a ticket). With the account, the key every write is idempotent on. |
| accountId | accountRef | integer | string | Merlin's account id, or your externalRef for it. Optional when the token reaches one account. |
| symbol | string | Broker suffixes such as XAUUSD+ or US30# are removed. |
| side | "buy" | "sell" | The side the position opened on. |
| quantity | number > 0 | Lots or contracts. |
| openTime | date-time | ISO 8601 with Z or an offset. |
| closeTime | date-time | null | null while open. Post the same externalId again when it closes. |
| entryPrice | number > 0 | Average entry. |
| exitPrice | number | null | Average exit. Required once closed. |
| stopLoss, takeProfit | number | null | At entry. Merlin measures risk in R from the stop. |
| pnl | number | In the account's currency, before commission and swap. |
| commission, swap | number | As the broker reports them: a cost is negative. Default 0. |
| comment | string, ≤ 500 | Free text, such as the master account it was copied from. |
04Accounts
Tell Merlin your id for each account once, and address trades by it from then on. If the trader already has an account of that name, it is linked rather than duplicated. A trader's first account is free; more need Pro or Premium, up to 25, exactly as in the app.
POST /api/v1/accounts
{ "externalRef": "stt-follower-7731", "name": "FTMO 100k (copy)", "currency": "USD", "broker": "mt5" }
→ 201 { "data": { "id": 412, "externalRef": "stt-follower-7731", ... }, "result": "created" }
→ 200 ... "result": "existing" (that externalRef is already linked)
→ 200 ... "result": "linked" (the trader had an account of that name; it now carries your ref)05Reading trades and insights
GET /trades pages through the trades the token reaches, oldest first: pass nextCursor back until it is null. Filter by accountId, accountRef or since. Each trade carries Merlin's netPnl, after commission and swap, the figure the trader sees.
GET /accounts/{id}/insights returns what Merlin reads in an account: its figures, the strength and the costliest pattern with its cost in R, the one change, every behaviour check, and results by session and market. It is built by the same engine as the trader's own screen, so your product and Merlin never disagree.
GET /api/v1/accounts/412/insights?days=90
{
"data": {
"accountId": 412, "currency": "USD", "trades": 324, "ready": true,
"summary": { "netPnl": 18836.41, "winRate": 59.88, "profitFactor": 2.29, "expectancy": 58.14,
"maxDrawdown": 1290.2, "averageHoldMinutes": 60, "fees": 1032.5, ... },
"verdict": {
"strength": { "title": "Your London edge is real", "detail": "..." },
"weakness": { "title": "Revenge trading", "detail": "...", "costR": -11.6 },
"action": "After any losing trade, your next entry waits. ..."
},
"patterns": [ { "type": "revenge_trading", "found": true, "occurrences": 78, "costR": -11.6, ... }, ... ],
"sessions": [ ... ], "markets": [ ... ]
}
}06Errors and retries
Every error has one shape: { error: { type, code, message, param?, requestId } }, and every reply carries an X-Request-Id. Writes are safe to retry. With an Idempotency-Key (8–255 characters, kept for a day per token) the same key and body replay the first reply, marked Idempotent-Replayed: true; the same key with a different body is refused.
| Status | Type | Codes |
|---|---|---|
| 400 | invalid_request | invalid_json, invalid_idempotency_key, invalid_cursor; 413 payload_too_large |
| 401 | authentication | missing_token, invalid_token (unknown, malformed or revoked), expired_token |
| 403 | permission | insufficient_scope, account_restricted, plan_required |
| 404 | not_found | account_not_found, not_found |
| 409 | conflict / idempotency | name_taken, account_limit, idempotency_key_reused, idempotency_in_flight |
| 422 | invalid_request | invalid_field, with param naming the field, e.g. trades[3].closeTime |
| 429 | rate_limited | Retry-After says when. Retrying a write is always safe. |
07Samples
curl https://merlintrade.io/api/v1/me \
-H "Authorization: Bearer $MERLIN_TOKEN"const MERLIN = "https://merlintrade.io/api/v1";
const TOKEN = process.env.MERLIN_TOKEN; // mtk_live_..., issued by the trader
// Send closed trades in batches of up to 500. A retry is always safe:
// trades are keyed by externalId, and the Idempotency-Key replays the reply.
export async function sendTrades(trades, batchId) {
const res = await fetch(`${MERLIN}/trades`, {
method: "POST",
headers: {
authorization: `Bearer ${TOKEN}`,
"content-type": "application/json",
"idempotency-key": batchId,
},
body: JSON.stringify({ trades }),
});
if (res.status === 429) throw new Error("rate limited: retry after " + res.headers.get("retry-after") + "s");
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message} (${body.error.requestId})`);
return body; // body.data[i].status: created | updated | unchanged | rejected
}import json, os, urllib.request
MERLIN = "https://merlintrade.io/api/v1"
TOKEN = os.environ["MERLIN_TOKEN"] # mtk_live_..., issued by the trader
def send_trades(trades: list, batch_id: str) -> dict:
req = urllib.request.Request(
f"{MERLIN}/trades",
data=json.dumps({"trades": trades}).encode(),
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json",
"Idempotency-Key": batch_id},
method="POST",
)
with urllib.request.urlopen(req) as res: # raises on 4xx/5xx
return json.loads(res.read()) # ["data"][i]["status"]08Security
- Read-only toward the broker, always: nothing in the API can place, change or close a trade.
- Tokens are 192-bit random values. Merlin stores only their SHA-256 and shows the trader a prefix; a database read yields no usable token.
- A token reaches one trader, only the scopes and accounts they chose, never their sample account, and nothing of anyone else's. Unknown and revoked tokens get the same answer.
- Every call is rate limited per address before any lookup, then per token. Bodies are capped while they are read.
- Cross-origin browser calls are not allowed: keep tokens on your servers.
- Merlin never sells trade data or shares it with advertisers. Traders can export or delete everything from Settings.
09The signed single-trade endpoint
For an expert advisor or a lightweight bridge there is also the endpoint the MerlinSync EA posts to: one trade per request, signed with a per-account key the trader creates on the Connect MetaTrader page. Nothing in it can read the journal.
- Endpoint
- POST https://merlintrade.io/api/ingest
- Auth
- A per-account key the trader creates in Merlin: a key ID (mk_live_…) and a secret, shown once
- Signature
- HMAC-SHA256 over key ID, timestamp, nonce and the payload's SHA-256
- Freshness
- Timestamps more than 5 minutes from our clock are refused
- Replay
- Each nonce is accepted once per key
- Idempotency
- One trade per ticket per account: resending a ticket updates it, never duplicates it
- Limits
- 1,000 posts a minute per key, 300 a minute per IP, 64 KB per request
- Direction
- Write-only into one account. Merlin never places, changes or closes a trade
{
"v": 1,
"keyId": "mk_live_3f9c2a71d04be58c6a1f0e92",
"ts": 1795510800,
"nonce": "9b2f6d1c4e8a4f0b",
"hmac": "<hex HMAC-SHA256, see below>",
"payload": {
"ticket": "STT-58211047",
"symbol": "EURUSD",
"direction": "buy",
"openTime": "2026-11-24T08:02:11Z",
"closeTime": "2026-11-24T09:15:40Z",
"openPrice": 1.0812,
"closePrice": 1.0841,
"sl": 1.0790,
"tp": 1.0860,
"lots": 0.5,
"pnl": 145.0,
"commission": -3.5,
"swap": 0,
"comment": "copied from master 7731"
}
}| Field | Type | Meaning |
|---|---|---|
| ticket | string, 1–64 | Your unique ID for the position. The idempotency key. |
| symbol | string | Letters, digits, dot, underscore or hyphen, up to 32. Broker suffixes such as XAUUSD+ or US30# are normalised. |
| direction | "buy" | "sell" | The side the position opened on. |
| openTime / closeTime | ISO 8601 | UTC. closeTime null while open; post the same ticket again when it closes. |
| openPrice / closePrice | number | Average entry and exit; closePrice null while open. |
| sl / tp | number | null | Stop loss and take profit at entry, if any. |
| lots | number > 0 | Position size in lots or contracts. |
| pnl | number | Profit or loss in the account's currency, before commission and swap. |
| commission / swap | number | As the broker reports them: a cost is negative. |
| comment | string, optional | Free text. Stored as-is. |
Hash the payload text with SHA-256 (hex), then sign <keyId>.<ts>.<nonce>.<sha256_hex(payload)> with the secret using HMAC-SHA256 (hex). The secret is used as text. Sign the payload exactly as you send it.
import { createHash, createHmac, randomUUID } from "node:crypto";
const KEY_ID = process.env.MERLIN_KEY_ID; // mk_live_...
const SECRET = process.env.MERLIN_SECRET; // shown once, when the trader creates the key
export async function sendTrade(trade) {
const payload = JSON.stringify(trade);
const ts = Math.floor(Date.now() / 1000);
const nonce = randomUUID();
const digest = createHash("sha256").update(payload).digest("hex");
const hmac = createHmac("sha256", SECRET)
.update(`${KEY_ID}.${ts}.${nonce}.${digest}`)
.digest("hex");
// The signature covers the payload text exactly as sent.
const body = `{"v":1,"keyId":"${KEY_ID}","ts":${ts},"nonce":"${nonce}","hmac":"${hmac}","payload":${payload}}`;
const res = await fetch("https://merlintrade.io/api/ingest", {
method: "POST",
headers: { "content-type": "application/json" },
body,
});
return { status: res.status, body: await res.json() };
}import hashlib, hmac, json, os, time, uuid, urllib.request
KEY_ID = os.environ["MERLIN_KEY_ID"] # mk_live_...
SECRET = os.environ["MERLIN_SECRET"]
def send_trade(trade: dict):
payload = json.dumps(trade, separators=(",", ":"))
ts = int(time.time())
nonce = uuid.uuid4().hex
digest = hashlib.sha256(payload.encode()).hexdigest()
sig = hmac.new(SECRET.encode(), f"{KEY_ID}.{ts}.{nonce}.{digest}".encode(), hashlib.sha256).hexdigest()
# The signature covers the payload text exactly as sent.
body = f'{{"v":1,"keyId":"{KEY_ID}","ts":{ts},"nonce":"{nonce}","hmac":"{sig}","payload":{payload}}}'
req = urllib.request.Request("https://merlintrade.io/api/ingest", data=body.encode(),
headers={"content-type": "application/json"}, method="POST")
with urllib.request.urlopen(req) as res: # raises on 4xx/5xx
return res.status, json.loads(res.read())| Status | Body | Meaning |
|---|---|---|
| 201 | { "ok": true, "duplicate": false } | A new trade was stored. |
| 200 | { "ok": true, "duplicate": true } | That ticket was already in the account; updated if any figure changed. |
| 401 / 408 | { "error": "rejected" } | Unknown or revoked key, bad signature, reused nonce or malformed envelope (401); a stale timestamp (408). |
| 413 / 422 / 429 | payload_too_large · bad_payload · rate_limited | Over 64 KB; a genuine envelope whose trade fails the schema; too many posts. |
10Talk to us
Building an integration? Write to us and we will set up a test trader for you. Webhooks and a sandbox environment are planned, not built; tell us what your platform needs and it shapes what comes first.
hello@merlintrade.io · OpenAPI 3.1 · Every integration · Partner programme