# Quickstart

> MetaTrader API docs for developers and coding agents. Last updated: 2026-10-15. Index: https://www.metatraderapi.net/llms.txt
>
> © 2026 Apex Vanguard Dynamics LLC. You, and the software tools and AI agents working for you, may read and use this documentation to build, run and support integrations with MetaTrader API; its code examples may be copied into your own software. Republishing or redistributing the documentation, in whole or in substantial part, is not permitted. Terms: https://www.metatraderapi.net/en/terms/

From nothing to a live quote and a first order in about ten minutes. Every request below is real and runs against the production API at `https://api.metatraderapi.net`.

## 1. Get an account id and an API key

1. Create an account at https://app.metatraderapi.net/sign-up and start the subscription. There is no free trial and no sandbox: every connected account (a "seat") is a paid seat. Use a broker **demo** account while you build (see https://www.metatraderapi.net/docs/testing.md).
2. In the dashboard, connect your MT4 or MT5 account: broker server name, account number (login) and the account's **main** (trading) password.
3. When the connection is `ACTIVE`, you need two values from the account's card:
   - the **account id**, a UUID, sent as `?id=` on every request;
   - the **API key**, starting with `mt5api_`, sent as the `x-api-key` header. Click "Generate key" if none is shown. It is shown once; store it as a secret. This key works for every trading account in your dashboard login (choose with `?id=`), so keep it on your server; see https://www.metatraderapi.net/docs/authentication.md for keys limited to one account.

Doing this from your own backend instead of the dashboard: see https://www.metatraderapi.net/docs/provisioning.md.

```bash
export MTAPI_KEY="mt5api_..."            # your API key
export MTAPI_ID="7f123497-63b2-496d-864d-cf3657f73b1f"   # your account id
```

## 2. First call: account summary

```bash
curl -s -H "x-api-key: $MTAPI_KEY" "https://api.metatraderapi.net/AccountSummary?id=$MTAPI_ID"
```

Response (values are your account's):

```json
{"balance": 10000.0, "credit": 0.0, "profit": 0.0, "equity": 10000.0, "margin": 0.0, "freeMargin": 10000.0, "marginLevel": 0.0, "leverage": 100, "currency": "USD", "method": 0, "type": "demo", "isInvestor": false, "synced": true, "currencyDigits": 2}
```

`synced: true` means the connection to the broker is live. `false` means these are the last known values while the connection is restored.

## 3. A quote

Symbol names are the broker's own, including any suffix (`EURUSD`, `EURUSD.m`, `XAUUSDm`, ...). List them first; never guess.

```bash
curl -s -H "x-api-key: $MTAPI_KEY" "https://api.metatraderapi.net/SymbolList?id=$MTAPI_ID"
curl -s -H "x-api-key: $MTAPI_KEY" "https://api.metatraderapi.net/GetQuote?id=$MTAPI_ID&symbol=EURUSD"
```

## 4. A market order, safely

```bash
curl -s -H "x-api-key: $MTAPI_KEY" \
  "https://api.metatraderapi.net/OrderSend?id=$MTAPI_ID&symbol=EURUSD&operation=Buy&volume=0.01&clientOrderId=my-order-0001"
```

- `volume` is in lots. `stoploss` / `takeprofit` are absolute prices. `slippage` is in points (default 10).
- `clientOrderId` makes the call safe to retry: the same id never opens a second order (see https://www.metatraderapi.net/docs/orders.md).
- **HTTP 200 does not mean the order was filled.** Check `state` in the response: `10009` = done. Any other value is the broker's reason for refusing it (invalid stops, market closed, not enough money, ...).

Close it with the `ticket` from the response:

```bash
curl -s -H "x-api-key: $MTAPI_KEY" "https://api.metatraderapi.net/OrderClose?id=$MTAPI_ID&ticket=123456789"
```

## 5. The same in Python

```python
import os, time, uuid, requests

API = "https://api.metatraderapi.net"
KEY, ACCOUNT = os.environ["MTAPI_KEY"], os.environ["MTAPI_ID"]
TRADES = {"OrderSend", "OrderClose", "OrderModify", "OrderDelete", "OrderCloseBy"}
NOT_SENT = {"RATE_LIMITED", "TERMINAL_UNREACHABLE", "ACCOUNT_RESUMING",
            "this account's API connection isn't connected yet"}
s = requests.Session()
s.headers["x-api-key"] = KEY

def call(path, **params):
    """GET a classic endpoint. Retries only what is safe to retry."""
    for attempt in range(4):
        r = s.get(f"{API}/{path}", params={"id": ACCOUNT, **params}, timeout=75)
        if r.status_code in (429, 500, 503) or 520 <= r.status_code <= 524:
            body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
            if path not in TRADES or body.get("error") in NOT_SENT:
                time.sleep(int(r.headers.get("retry-after", "2")))
                continue
        r.raise_for_status()
        return r.json()
    r.raise_for_status()

print(call("AccountSummary"))

order = call("OrderSend", symbol="EURUSD", operation="Buy", volume=0.01,
             clientOrderId=f"demo-{uuid.uuid4().hex[:20]}")
if order.get("state") != 10009:
    raise RuntimeError(f"broker refused the order, retcode {order.get('state')}")
print("filled", order["ticket"], order["openPrice"])
```

Why trades are not retried on every 503: a `TIMEOUT` may mean the order reached the broker. Trades are retried only on errors that prove the request was never sent. After a `TIMEOUT`, look at `/OpenedOrders` before doing anything else. The `clientOrderId` guarantees a resend with the same id never creates a second order.

## 6. Live data over WebSocket

```python
import asyncio, json, os, websockets   # pip install "websockets>=14"

async def main():
    url = f"wss://api.metatraderapi.net/v1/stream?id={os.environ['MTAPI_ID']}"
    async with websockets.connect(url, additional_headers={"x-api-key": os.environ["MTAPI_KEY"]}) as ws:
        await ws.send(json.dumps({"action": "subscribe", "symbol": "EURUSD"}))
        async for raw in ws:
            msg = json.loads(raw)
            if msg["type"] == "QUOTE":
                print(msg["data"]["symbol"], msg["data"]["bid"], msg["data"]["ask"])

asyncio.run(main())
```

Positions, pending orders, trades, candles and heartbeats come over the same socket: https://www.metatraderapi.net/docs/streaming.md.

## Next

- Before writing more code, read https://www.metatraderapi.net/docs/errors.md and https://www.metatraderapi.net/docs/limits.md.
- All endpoints and parameters: https://www.metatraderapi.net/openapi.json and https://app.metatraderapi.net/docs.
