What you need
- Python 3 with the requests package. httpx works the same way if you prefer it. The optional DataFrame step also needs pandas.
- A FiveSocket API key from the control panel. It is shown once, so keep it in an environment variable such as FIVESOCKET_KEY.
- An MT5 account linked to FiveSocket. Link it with POST /v1/accounts and the accounts:write scope, or in the control panel. Use the investor password if the program should only read.
FiveSocket has no official Python package. The examples below use requests over the public REST API, so you copy a few lines instead of adding a dependency. The OpenAPI document at https://api.fivesocket.com/v1/openapi.json describes every request if you would rather generate a client.
Each key carries scopes. Listing accounts needs accounts:read, balance, positions and candles need data:read, and orders need trading:execute. Give each program its own key with only the scopes it uses. Read about the MT5 REST API
Why not the MetaTrader5 package
MetaQuotes ships the MetaTrader5 package as Windows wheels, and it talks to a terminal on the same machine. That is why it will not install on a Mac or in a Linux container, and why scripts built on it need a Windows machine or VPS running all day. A REST call has none of those limits.
On a Mac the package does not install, so the options are Wine or a hosted API. MetaTrader5 for Python on Mac
The same applies on a Linux server, in Docker and in CI. MetaTrader5 for Python on Linux
To reach MT5 from code on any machine, read the wider background. Use MT5 from code without Windows
A small Python helper
Start with one helper that sends the Bearer key, raises a typed error when a call fails, and waits and retries when the API says to. Save it as fivesocket.py and import it from the other examples.
import os
import time
import requests
BASE = "https://api.fivesocket.com/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['FIVESOCKET_KEY']}"
class FiveSocketError(Exception):
def __init__(self, status, code, request_id, message):
super().__init__(f"{status} {code}: {message}")
self.status = status
self.code = code
self.request_id = request_id
def api(path, method="GET", params=None, body=None, idempotency_key=None):
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
for attempt in range(6):
response = session.request(
method, f"{BASE}{path}", params=params, json=body, headers=headers, timeout=60
)
retryable = response.status_code in (429, 503) or (
response.status_code == 202 and method == "GET"
)
if retryable and attempt < 5:
wait = response.headers.get("Retry-After", "")
time.sleep(int(wait) if wait.isdigit() and int(wait) > 0 else 2**attempt)
continue
if not response.ok:
error = response.json()["error"]
raise FiveSocketError(
response.status_code, error["code"], error["requestId"], error["message"]
)
return response.json()Errors from the API are JSON with an error object holding a stable code, a message and a requestId. Quote the requestId if you contact support.
List accounts, read the balance and open positions
GET /v1/accounts lists your linked accounts and their status. Use an account's id in the path of every other call. Balance and positions come from the live MT5 session when you ask. Money, prices and volumes are decimal strings, so keep them as strings or parse them with decimal.Decimal rather than doing float maths on them.
from fivesocket import api
accounts = api("/accounts")["data"]
account_id = accounts[0]["id"]
balance = api(f"/accounts/{account_id}/balance")
print(balance["balance"], balance["equity"], balance["currency"])
for position in api(f"/accounts/{account_id}/positions")["positions"]:
print(position["symbol"], position["side"], position["volume"], position["openPrice"])The first read after a session has gone idle logs in to your broker and can take several seconds. If it runs long, the API answers 202 with the code account_warming and a Retry-After header, and the helper repeats the request for you.
Read candles into a DataFrame
The candles endpoint takes a symbol spelled exactly as your broker spells it, a timeframe of M1, M5, M15, H1, H4 or D1, and either a count of recent completed bars from 1 to 1,000, or an ordered from and to range with an optional limit. Count cannot be combined with from, to or limit, and a range needs both from and to with from earlier than to. Range pages run backward: keep everything else the same, replace to with nextTo, and stop when it is null.
import os
from fivesocket import api
account_id = os.environ["FIVESOCKET_ACCOUNT_ID"]
path = f"/accounts/{account_id}/candles"
recent = api(path, params={"symbol": "EURUSD", "timeframe": "H1", "count": 200})
bars = []
params = {
"symbol": "EURUSD",
"timeframe": "H1",
"from": "2026-10-01T00:00:00Z",
"to": "2026-11-01T00:00:00Z",
"limit": 1000,
}
while True:
page = api(path, params=params)
bars = page["data"] + bars
if page["nextTo"] is None:
break
params["to"] = page["nextTo"]
print(len(recent["data"]), len(bars), bars[-1]["close"])A symbol the account does not have returns 404 with the code symbol_not_found and up to five suggested names. A 503 with candle_history_unavailable and Retry-After means the terminal is still loading history, and the helper waits and retries.
If you use pandas, turn the bars into a DataFrame. This step is optional, and the prices arrive as strings, so convert the columns you need.
import pandas as pd
frame = pd.DataFrame(bars)
frame["openTime"] = pd.to_datetime(frame["openTime"])
for column in ["open", "high", "low", "close", "tickVolume"]:
frame[column] = pd.to_numeric(frame[column])
frame = frame.set_index("openTime")
print(frame["close"].resample("D").last().tail())Deals and orders export the same way as candles. Read the historical data guide
Place an order
Trading is off until you turn it on for an account with a policy of exact symbols and the largest order size for each. The key needs the trading:execute scope. Every write needs an Idempotency-Key header, and an order also carries a clientOrderId that is unique for the account. Repeating the same key with the same order never sends it to the broker twice.
import os
from fivesocket import FiveSocketError, api
account_id = os.environ["FIVESOCKET_ACCOUNT_ID"]
execution = f"/accounts/{account_id}/execution"
api(execution, method="PUT", idempotency_key="enable-1", body={"symbols":[{"symbol":"EURUSD","maxVolume":"0.10"}]})
try:
command = api(
f"{execution}/orders",
method="POST",
idempotency_key="order-1",
body={"clientOrderId":"order-1","symbol":"EURUSD","side":"buy","type":"market","volume":"0.10"},
)
print(command["outcome"], command["commandId"])
except FiveSocketError as error:
print(error.status, error.code, error.request_id)
raise- The response is a command with a commandId and an outcome. A rejection by the gateway or the broker comes back as a 200 with the outcome rejected, so check the outcome and not only the status.
- If the broker's reply is lost, the outcome can be commit_unknown. Do not send a new order. Poll the original command at /v1/accounts/{accountId}/execution/commands/{commandId}.
Test against a demo account first, and keep the policy's symbols and sizes narrow. Code that places real orders can lose real money when it misbehaves.
Handle errors and rate limits
- 400 invalid_request: the request is wrong, such as mixing count with from and to. Fix it and do not retry.
- 401 invalid_api_key, 402 subscription_required and 403 insufficient_scope: the key, the subscription or the key's scopes need attention.
- 429 rate_limit_exceeded: you passed the per-key, per-workspace or per-account limit for the minute. The response carries Retry-After and RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. Wait the number of seconds given.
- 503 with Retry-After, such as capacity_exhausted or candle_history_unavailable: a transient condition. Wait and send the same request again.
- 504 request_timeout: the read ran past its deadline. Retry reads after a pause. For a trade, look up its command before trying again.
The helper above retries 429 and 503 up to five times, using Retry-After and falling back to exponential backoff, and repeats a GET after a 202. It does not retry anything else. Requests per minute depend on your plan, and headers on each successful response show how many you have left.
There is no streaming feed and no webhooks, so your code polls. Poll at a pace that stays under your limit.
Frequently asked questions
- Is there a FiveSocket Python package?
- No. There is no official FiveSocket Python package. The API is plain HTTPS with an OpenAPI document, so you can use requests or httpx directly, or generate a client from the document.
- Can I use the MetaTrader5 Python package instead?
- Only on Windows with a MetaTrader 5 terminal running on the same machine. It does not install on macOS or Linux. FiveSocket is an HTTPS API, so the same Python code runs on any of them.
- Do I need Windows or a VPS?
- No. FiveSocket hosts the MT5 terminal session for you, so your code runs on macOS, Linux, Windows or a serverless function, and you run no MT5 terminal.
- Can I get MT5 candles into pandas?
- Yes. Read candles with count or with a from and to range, then pass the data list to pandas.DataFrame. Prices arrive as strings, so convert the columns you need with pandas.to_numeric.
- How do I handle a 429 rate limit?
- Wait the number of seconds in the Retry-After header, then send the same request again. Cap the number of retries and back off if the header is missing. Requests per minute depend on your plan.
- Can I stream prices over a WebSocket?
- No. FiveSocket has no streaming feed and no webhooks. Your code polls the REST endpoints for balances, positions and candles.
- Can I place trades from Python?
- Yes, after you turn trading on for the account with a policy of exact symbols and maximum order sizes, using a key with the trading:execute scope. Send an Idempotency-Key with every write, and test on a demo account first.
- How much does it cost?
- Plans start at $9.99 a month for one MT5 account. Link your MT5 account and try it free, no card: 24 hours or 100 calls, whichever comes first. Then a 7-day free trial, card required. Cancel anytime. The trial includes one connected MT5 account.