Comparisons · 4 min read · 2026-06-11
MetaApi Python SDK Alternative: Connecting Python Apps to MT4/MT5
By MetaTrader API Editorial Team

Looking for a MetaApi Python alternative? Drop heavy proprietary SDKs and connect your Python app to MT4/MT5 with standard REST and WebSockets.
Python has become the undisputed language of algorithmic trading. Whether you are running complex Pandas data models, integrating TensorFlow for AI trading bots, or building a custom Django dashboard for a prop firm, you need a reliable way to pass your Python logic to MetaTrader.
For many developers, the MetaApi Python SDK is the first wrapper they encounter. As projects grow, some teams prefer to see and control every request themselves instead of working through an SDK's abstractions.
If you are looking for a lighter MetaApi Python alternative, you don't need an SDK at all.
With MetaTrader API you work with MT4 and MT5 through standard Python libraries (requests and websockets). There is nothing to install on your side, no EA for you to run and no MetaTrader window to keep open. An official Python SDK exists as well, but it is optional. In this guide we show how to execute trades and stream live data with plain HTTP and WebSocket calls.
1. Why Ditch the SDK?
Proprietary SDKs act as black boxes. They hide the raw API requests from you, which can be helpful for beginners but frustrating for advanced developers.
When you use a direct MT4 Python API or MT5 Python API alternative, you gain three immediate advantages:
- Minimal dependencies: You rely only on widely maintained libraries like
requests. The official SDK is optional, not required. - Plain requests: Every classic endpoint is a plain HTTP
GETwith query parameters, so you can reproduce any call with onecurlcommand. - Complete debugging control: When a request fails, you see the exact HTTP status code and JSON error body immediately, rather than digging through an SDK's error traceback.
2. Connecting and Authenticating in Python
With MetaTrader API, there are no "provisioning profiles" and no SDK to install. You connect the trading account once in the dashboard (app.metatraderapi.net): server name exactly as your MetaTrader login window shows it, login, main password. It is usually ACTIVE within 1–2 minutes, and you receive an account id (UUID) and an API key.
From then on every call is a plain GET with the key in the x-api-key header and the account id as ?id=, using nothing more than requests:
import requests
BASE = "https://api.metatraderapi.net"
HEADERS = {"x-api-key": "YOUR_API_KEY"}
ACCOUNT_ID = "YOUR_ACCOUNT_ID"
def api(path, **params):
# 75 s: the API waits up to 30 s for the account and retries a timed-out read once
r = requests.get(f"{BASE}{path}", headers=HEADERS, params={"id": ACCOUNT_ID, **params}, timeout=75)
r.raise_for_status()
return r.json()
summary = api("/AccountSummary")
print(f"Equity: {summary['equity']} {summary['currency']}")
Connecting accounts programmatically (for a SaaS onboarding flow) is POST https://api.metatraderapi.net/v1/seats with a management key; it returns the same account id the dashboard shows.
3. Executing a Trade (REST API)
Executing a trade is equally simple: no connection classes, you pass the order as query parameters. The same call works on an MT4 and an MT5 account. Send a unique clientOrderId with every order: a retry with the same id returns the original result instead of opening a second position.
import uuid
order = api(
"/OrderSend",
symbol="EURUSD",
operation="Buy", # or "Sell", "BuyLimit", "SellStop", ...
volume=0.5, # lots
stoploss=1.0850,
takeprofit=1.0950,
magic=1001,
comment="Python_REST_Trade",
clientOrderId=f"py-{uuid.uuid4().hex[:20]}", # safe to retry with the same id
)
# A broker refusal is not an HTTP error: it is HTTP 200, and only state 10009 means done.
if order["state"] != 10009:
raise SystemExit(f"refused: state {order['state']} ({order['comment']})")
print("Filled ticket", order["ticket"], "at", order["openPrice"])
# Close it again, and read /OpenedOrders for the authoritative position list.
closed = api("/OrderClose", ticket=order["ticket"])
print("closed" if closed["state"] == 10009 else f"close refused: state {closed['state']}")
4. Streaming Live Data (WebSockets)
For real-time trading, polling via REST is wasteful. MetaTrader API provides one standard WebSocket per account that you can use with the popular websockets library.
Here is an asynchronous script that subscribes to a symbol, prints live prices (at most one quote every 200 ms per symbol) and reconnects with backoff when the socket closes:
import asyncio
import json
import websockets # pip install "websockets>=14"
async def stream_live_quotes(api_key, account_id):
uri = f"wss://api.metatraderapi.net/v1/stream?id={account_id}"
delay = 1
while True:
try:
async with websockets.connect(uri, additional_headers={"x-api-key": api_key}) as ws:
delay = 1
# Quotes are sent only for subscribed symbols; positions and trades always.
await ws.send(json.dumps({"action": "subscribe", "symbol": "EURUSD"}))
print("Connected to the live stream...")
async for raw in ws:
frame = json.loads(raw) # {"type": "QUOTE"|"POSITIONS"|"TRADE"|..., "data": ...}
if frame["type"] == "QUOTE":
q = frame["data"]
print(f"Live price [{q['symbol']}]: bid {q['bid']} | ask {q['ask']}")
elif frame["type"] == "TRADE":
print("Deal executed:", frame["data"])
except websockets.ConnectionClosed as e:
print(f"stream closed ({e.rcvd.code if e.rcvd else '-'}), reconnecting in {delay}s")
await asyncio.sleep(delay)
delay = min(delay * 2, 30) # backoff 1, 2, 4 ... 30 s
# asyncio.run(stream_live_quotes("YOUR_API_KEY", "YOUR_ACCOUNT_ID"))
(Note: If you are building a system that tracks multiple accounts simultaneously, check out our guide on MetaApi CopyFactory Alternatives.)
Conclusion: Keep Your Python Stack Clean
When you build commercial software, fewer dependencies mean fewer things that can break.
With plain HTTP and WebSocket calls your codebase stays small, every request is easy to log and replay, and errors arrive as clear HTTP status codes with JSON bodies.
A seat costs $14 per month (graduated: $13 from the 5th seat, $12 from the 20th); there is no free trial, so test with a broker demo account.
👉 Read the MetaTrader API documentation
Ready to integrate the MetaTrader API?
REST, WebSocket and gRPC for MT4 and MT5. Pay per connected account.
Create account