AlgoDeltaFXDocs

Trade MetaTrader 5 from Python

View .md Ask Claude Ask ChatGPT

The official MetaTrader5 Python package only runs on Windows, next to an MT5 terminal that stays open. The AlgoDeltaFX REST API removes that constraint: your Python code calls HTTPS endpoints from any OS, server, notebook or serverless function, and AlgoDeltaFX's cloud executes the orders on your broker's MT5 server.

Install#

The only dependency is requests:

bash
pip install requests

A small client#

Python
import os
import requests

BASE = "https://api.algodeltafx.com/api/v2/forexaccount"


class MT5Client:
    def __init__(self, token: str):
        self.s = requests.Session()
        self.s.headers["Authorization"] = f"Bearer {token}"

    def _call(self, method: str, path: str, body: dict | None = None):
        r = self.s.request(method, f"{BASE}/{path}", json=body, timeout=30)
        r.raise_for_status()
        res = r.json()
        if not res.get("status"):
            raise RuntimeError(res.get("msg", "Request failed"))
        return res.get("data")

    # Account data
    def profile(self):           return self._call("GET", "getprofile")
    def symbols(self):           return self._call("GET", "getsymbols")
    def positions(self):         return self._call("GET", "getopenpositions")
    def pending_orders(self):    return self._call("GET", "getpendingorders")

    # Trading
    def place(self, symbol, type, volume, price=None, sl=None, tp=None, stop_limit=None):
        body = {"symbol": symbol, "type": type, "volume": volume,
                "price": price, "sl": sl, "tp": tp, "stop_limit": stop_limit}
        return self._call("POST", "placeorder", {k: v for k, v in body.items() if v is not None})

    def modify(self, ticket, **fields):  return self._call("POST", "modifyorderorposition", {"ticket": ticket, **fields})
    def cancel(self, ticket):            return self._call("POST", "cancelorder", {"ticket": ticket})
    def close(self, ticket, volume=None):
        body = {"ticket": ticket} | ({"volume": volume} if volume else {})
        return self._call("POST", "squareoffposition", body)


mt5 = MT5Client(os.environ["ACCOUNT_TOKEN"])

Place a market order#

Python
BUY, SELL, BUY_LIMIT, SELL_LIMIT, BUY_STOP, SELL_STOP, BUY_STOP_LIMIT, SELL_STOP_LIMIT = range(8)

order = mt5.place("EURUSD", BUY, 0.10, sl=1.0750, tp=1.0950)
ticket = order["ticket"]

Place a pending order#

Python
mt5.place("XAUUSD", BUY_LIMIT, 0.05, price=2320.0, sl=2305.0, tp=2360.0)

Move the stop loss to break-even#

Python
mt5.modify(ticket, sl=1.0850)

Partially close, then close the rest#

Python
mt5.close(ticket, volume=0.05)  # close half
mt5.close(ticket)               # close the remainder

Pull closed trades for a report#

Python
def closed_positions(start, end):
    cursor = None
    while True:
        body = {"start_date": start, "end_date": end, "limit": 100}
        if cursor:
            body["cursor"] = cursor
        page = mt5._call("POST", "gethistorypositions", body)
        yield page
        cursor = page.get("cursor") if isinstance(page, dict) else None
        if not cursor:
            break

The field that carries the next cursor is described in Pagination.

Production tips#

  • Symbol names: read them from symbols() once and cache them. Broker suffixes like EURUSDm are the most common cause of rejected orders.
  • Timeouts and retries: retry GET calls on network errors. For placeorder, check positions() before you retry so a timeout does not open a duplicate trade.
  • Many accounts: create one MT5Client per account token, or use the Master API to copy one master to many accounts automatically.

FAQ#

Do I need the MetaTrader5 Python package?#

No. You only need requests. The MetaTrader5 package talks to a local terminal; this API talks to the AlgoDeltaFX cloud over HTTPS.

Can I run my Python MT5 bot on Linux or a Mac?#

Yes. Because the API is plain HTTPS, it works on Linux servers, macOS, Docker, AWS Lambda, Google Cloud Run and Jupyter notebooks.

Can I use pandas for history data?#

Yes. History endpoints return JSON lists that load directly with pandas.DataFrame(records).

Last updated 2026-11-04