MetaTrader 5 + Python: socket & MetaTrader5

MetaTrader 5 + Python: socket & MetaTrader5

MetaTrader 5 can be connected to Python in two common ways:

  1. Use a socket bridge between an Expert Advisor or script in MQL5 and a Python process.
  2. Use the official MetaTrader5 Python package to communicate with a running MetaTrader 5 terminal.

Both methods are useful, but they solve slightly different problems. A socket bridge is flexible and works well when the trading logic must stay inside MetaTrader while Python handles calculation, data processing, or machine learning. The MetaTrader5 package is simpler when Python should directly request market data, inspect account state, or send orders through the terminal.

Option 1: Socket bridge

A socket bridge usually has two parts:

  • an MQL5 Expert Advisor that sends requests and receives responses;
  • a Python server that listens on a local port and processes those requests.

The safest layout is to run the socket server on 127.0.0.1 so it is reachable only from the same machine.

A minimal Python TCP server looks like this:

import socket

HOST = "127.0.0.1"
PORT = 9090

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    server.listen(1)
    print(f"Listening on {HOST}:{PORT}")

    while True:
        conn, addr = server.accept()
        with conn:
            data = conn.recv(4096)
            if not data:
                continue

            message = data.decode("utf-8").strip()
            print("received:", message)

            response = "ok\n"
            conn.sendall(response.encode("utf-8"))

On the MQL5 side, use the platform’s socket functions to connect to the local server, send a message, and read the reply. Keep the protocol simple at first: one line of UTF-8 text per request, terminated with \n. After the connection works, move to JSON so the message fields are explicit.

Example request payload:

{"symbol":"EURUSD","timeframe":"M1","action":"signal","bid":1.1284,"ask":1.1286}

When using sockets for trading decisions, handle the failure cases carefully:

  • Python process not running;
  • port already in use;
  • timeout while waiting for a response;
  • malformed response;
  • duplicated requests after reconnecting;
  • trading disabled in the terminal or account.

Do not let the Expert Advisor block indefinitely while waiting for Python. Use timeouts and fall back to a safe no-trade decision when communication fails.

Option 2: The MetaTrader5 Python package

The official Python package is often the fastest way to start. Install it with pip:

python -m pip install MetaTrader5

MetaTrader 5 must be installed and logged in on the same machine. The Python package talks to the terminal, so the terminal should be running before the script starts.

A minimal connection check:

import MetaTrader5 as mt5

if not mt5.initialize():
    print("initialize() failed:", mt5.last_error())
    raise SystemExit(1)

print(mt5.version())
print(mt5.account_info())

mt5.shutdown()

To request recent bars:

from datetime import datetime, timezone

import MetaTrader5 as mt5

symbol = "EURUSD"
timeframe = mt5.TIMEFRAME_M1
count = 100

if not mt5.initialize():
    print("initialize() failed:", mt5.last_error())
    raise SystemExit(1)

rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count)
if rates is None:
    print("copy_rates_from_pos() failed:", mt5.last_error())
else:
    for row in rates[:5]:
        ts = datetime.fromtimestamp(row["time"], tz=timezone.utc)
        print(ts, row["open"], row["high"], row["low"], row["close"])

mt5.shutdown()

Before sending orders from Python, verify the terminal, broker, symbol, and account permissions locally. The exact fields and allowed order parameters can vary by broker and account type, so inspect mt5.symbol_info(symbol), mt5.account_info(), and the return value of mt5.order_send() instead of assuming one fixed configuration.

Choosing between them

Use a socket bridge when:

  • an Expert Advisor already owns the trading loop;
  • Python is only a calculation or signal service;
  • you need a custom protocol between MQL5 and Python;
  • you want the EA to control order submission inside MetaTrader.

Use the MetaTrader5 package when:

  • Python should be the main program;
  • you need quick access to account information, symbols, ticks, bars, or orders;
  • you want less MQL5 code;
  • all work runs on the same machine as the MetaTrader 5 terminal.

For research and automation, start with MetaTrader5 because it is simpler to validate. For a production Expert Advisor that calls external analytics, a local socket bridge gives more control, but it also requires more defensive engineering around timeouts, retries, and message validation.

Leave a Reply