Guide · 10 min read

Algorithmic Trading in Python with MetaTrader 5

A practical walkthrough for building your first algorithmic trading bot in Python using the open-source open-api-mt5 library from Scenixa. You'll set up the environment, connect to MetaTrader 5, pull market data, and run a moving average crossover strategy end-to-end.

Why Python for algorithmic trading?

Python has become the default language for algorithmic trading because of its data ecosystem — pandas, NumPy, scikit-learn — and its first-class bindings for broker platforms like MetaTrader 5. open-api-mt5 wraps the official MT5 terminal with a clean, typed API so you can focus on the strategy rather than the plumbing.

1. Set up the environment

Install Python 3.10+, the MetaTrader 5 terminal, and the Scenixa client:

pip install open-api-mt5 pandas

Log into your broker account inside the MT5 terminal at least once so the Python client can attach to the running session.

2. Connect to MetaTrader 5

from open_api_mt5 import MT5Client

client = MT5Client()
client.initialize()

account = client.account_info()
print(f"Connected as {account.login} · balance {account.balance}")

initialize() attaches to the local MT5 terminal. If the call fails, confirm MT5 is running and that the account allows algorithmic trading.

3. Fetch market data

import pandas as pd
from datetime import datetime, timedelta

symbol = "EURUSD"
end = datetime.now()
start = end - timedelta(days=30)

rates = client.copy_rates_range(symbol, timeframe="H1", start=start, end=end)
df = pd.DataFrame(rates)
df["time"] = pd.to_datetime(df["time"], unit="s")
df = df.set_index("time")

You now have a clean OHLC DataFrame — the foundation of every strategy.

4. Build a moving average crossover

df["fast"] = df["close"].rolling(20).mean()
df["slow"] = df["close"].rolling(50).mean()
df["signal"] = 0
df.loc[df["fast"] > df["slow"], "signal"] = 1   # long
df.loc[df["fast"] < df["slow"], "signal"] = -1  # short

latest = df.iloc[-1]
print(f"Latest signal for {symbol}: {latest['signal']}")

When the fast moving average crosses above the slow one, the strategy goes long. When it crosses below, it goes short. Simple — and a solid baseline to benchmark more advanced ideas against.

5. Send the order

if latest["signal"] == 1:
    client.order_send(
        symbol=symbol,
        action="BUY",
        volume=0.1,
        type="MARKET",
    )
elif latest["signal"] == -1:
    client.order_send(
        symbol=symbol,
        action="SELL",
        volume=0.1,
        type="MARKET",
    )

Always paper-trade first on a demo account. Real accounts should include stop losses, position sizing based on account equity, and slippage handling.

Next steps

  • Backtest the strategy on 12+ months of data before going live.
  • Schedule the script — cron on Linux, Task Scheduler on Windows, or the upcoming Scenixa scenario scheduler.
  • Layer risk controls: max drawdown, per-trade risk %, correlation limits.
  • Instrument the bot with structured logs so you can debug live behavior.

Scenixa's enterprise tier adds observability, alerting, and pluggable Python scenarios on top of open-api-mt5 get in touch if you're running MT5 in production.