Episode 14 · AI Trading · Building a Complete Trading System

Reading an MT5 demo from Python without being able to send orders

Log in with the investor password, save 500 closed H1 candles to CSV, size the lot from the broker's own spec, and run order_check without sending anything.

How do you connect an agent to an MT5 demo so it can read data and size a lot, but cannot send an order? Stack three blocks: the investor password, MT5’s “no trading through the Python API” switch, and the algo-trading button off. Then a script that refuses to run if any of that is wrong.

If the script stops because the session can trade (you logged in with the master password), log in again with the investor password. Don’t delete the check.

Terms used below:

  • MT5 terminal: the MetaTrader 5 program where you log in. A Python script talks to the running terminal, not to the broker’s server. (Not to be confused with a PowerShell window.)
  • MetaTrader5 package: the official Python package. Version 5.0.6231 ships wheels only for 64-bit Windows on x64, Python 3.6 to 3.14.
  • Investor password: MT5’s view-only password. The master password (the Password field) is the one that trades.
  • symbol_info: the broker’s settings for a symbol: contract size, tick size, tick value, volume_min, volume_step, volume_max, digits, spread.
  • Tick size, tick value: the smallest price step, and the profit or loss of 1 lot when price moves one tick, in account currency; trade_tick_value_loss is the figure for a losing position.
  • Bar 0: the forming candle, still changing. The script starts at position 1 to use closed candles only.
  • order_check: checks a planned order (valid request? enough margin?) without sending it. Passing doesn’t guarantee a fill.
  • Magic number: an ID stamped on orders built by a program, so you can tell them apart from manual ones.

Requirements, a demo account and the investor password

The MetaTrader5 package has no source build, so you need 64-bit Windows with the project’s .venv on Python 3.14 and pytest installed. The MT5 terminal runs on macOS through Wine (macOS 10.15.7+, Apple M1 or newer), but there’s no Python package for it and community bridges aren’t official. On a Mac, use a Windows VM or VPS; the lot-function tests below run anywhere.

An MQL5 Expert Advisor (EA) runs inside the terminal. This is different: a Python script runs outside and attaches to the open terminal. It doesn’t log in. Called without a login, initialize() uses the last account; without a password, the one saved in the terminal. So the password is only ever typed into the terminal window: not in code, not in .env, not in a chat.

The Python API uses no API key; the password is what opens the account. The master password trades; the investor password lets you view the account and analyse prices, but not trade. Logged in with the investor password, the terminal’s Journal shows a line ending in trading has been disabled - investor mode. That’s the first block: whatever the script or agent gets wrong, this session can’t place an order. The master password and your broker’s client area login never go to any agent or script.

Open a demo account:

  1. Download MT5 from the official MetaTrader 5 site or your chosen broker, install and open it.
  2. File → Open an Account (or right-click in Navigator, Ctrl+N → Open an Account).
  3. Pick the broker; if it isn’t listed, type the company or server and click “Find your broker”. Next.
  4. Choose a demo account. Next.
  5. Fill in name, email, phone (international format). Choose hedging or netting. Pick an account type in USD (tick value is in account currency, and every example here is in USD). Choose a virtual deposit (1,000 USD matches this post) and leverage.
  6. Read the broker’s terms, agree, Next.
  7. The last screen shows Login, Password (master) and Investor. Store all three in a password manager, not in the project folder. Finish.
  8. Log in again, view-only: File → Login to Trade Account → Login; in Password enter the investor password; choose the server; tick Save password; OK. Save password lets the terminal reconnect on its own, so the script needs no password.
  9. Ctrl+T → Journal tab: look for the line ending in trading has been disabled - investor mode.

The sign-up page asks for name, email and phone, so read the broker’s terms first. Demo accounts use virtual money; their lifetime is up to the broker.

MT5’s safety switches: compare, lock down, screenshot

Tools → Options (Ctrl+O) → Expert Advisors. Compare each line with the table and change anything that differs, only in the stricter direction: tick blocking boxes, untick allowing ones. Click OK, reopen the tab to confirm, and screenshot it (Win+Shift+S, then Ctrl+S into reports\private, which .gitignore already excludes). Mask the account number before sharing.

Option on the Expert Advisors tab (newer builds may word it differently) What it does Here
Allow Auto Trading Allows or forbids EAs and scripts to trade across the platform; off, they still run but can’t trade Off
Disable automated trading when switching accounts Blocks EA and script trading on account switch, e.g. demo to live Ticked
Disable automatic trading through the external Python API Ticked by default for safety; Python scripts can trade only if you untick it Ticked
Allow DLL imports “Potentially dangerous, enable only for trusted applications” Off
Allow WebRequest for listed URL Off by default; only allows requests to addresses you list Off

The Python API line is the key one. Python scripts using the built-in module can trade, but that ability is off by default and you’d have to untick the box to enable it. Keep it ticked; unticking it, on a demo terminal only, comes much later, once a code check layer, a human approver and a kill switch exist.

The toolbar also has a platform-wide algo-trading button. “Algo Trading” (the button label), “AutoTrading” (its name in the help) and the “Allow Auto Trading” option all refer to the same switch; Ctrl+E toggles it. Keep it off.

From build 6060 (23 July 2026) MT5 also has an AI Assistant tab and an MCP tab in Options. On AI Assistant, Trading offers: the AI agent may trade, must ask for confirmation, or may not trade. Choose may not trade. The MCP tab’s “Enable internal server” turns on the terminal’s built-in MCP server, which isn’t used here; its API Key grants access to platform data and functions, so never paste it into a chat or give it to an agent.

MQL5 defines four layers of trading permission:

Layer What it is Blocked when
TERMINAL_TRADE_ALLOWED The terminal-wide automated trading switch on the toolbar The button is off
MQL_TRADE_ALLOWED The allow-trading box in an MQL5 program’s properties Not ticked when the program runs
ACCOUNT_TRADE_EXPERT Whether the server allows automated trading on this account The server disables it
ACCOUNT_TRADE_ALLOWED Whether the account may trade at all, manual or automated Disconnected; archived read-only account; server disabled trading; investor password login

The script below reads two of them: account_info().trade_allowed (False for an investor session) and terminal_info().trade_allowed. Two more notes: disabling EAs in settings forbids them to trade but doesn’t stop them (remove the EA, close the chart or close the platform for that); and indicators can’t trade at all, so if you only need to draw signals, use an indicator.

Install the package and run a read-only script

Open PowerShell (Win+X → Terminal, not the Admin entry). The MT5 terminal stays open, logged in with the investor password. Paste one line at a time:

cd C:\trading-agent-lab
.venv\Scripts\python -c "import sys, struct; print(sys.version); print(struct.calcsize('P') * 8, 'bit')"
.venv\Scripts\python -m pip install MetaTrader5 pandas
.venv\Scripts\python -c "import MetaTrader5 as m; print(m.__version__)"
notepad src\mt5_read.py

The first check must print a version starting 3.14 with AMD64 in brackets, then 64 bit. ARM64 means an ARM build of Python, for which the package has no wheel. pip ends with Successfully installed (or Requirement already satisfied); the next line must print 5.0.6231 or newer.

The script does five things: initialize() attaches to the terminal (starting it if needed; 60-second default timeout); it prints three safety lines and stops unless the account is demo and the session can’t trade; it reads the symbol’s spec with symbol_info; it fetches 500 H1 candles with copy_rates_from_pos starting at position 1, because position 0 is the forming candle; and it saves a CSV in data/. It always calls shutdown(), even when it stops early, and never prints the account number, name or balance.

src/mt5_read.py:

import os

import MetaTrader5 as mt5
import pandas as pd

SYMBOL = os.environ.get("TL_SYMBOL", "XAUUSD")   # symbol names differ between brokers
CANDLES = 500

path = os.environ.get("TL_MT5_PATH", "").strip('"')   # only needed with several terminals installed
ok = mt5.initialize(path) if path else mt5.initialize()
if not ok:
    print("initialize() error:", mt5.last_error())
    raise SystemExit(1)
try:
    acc = mt5.account_info()
    ter = mt5.terminal_info()
    if acc is None or ter is None:
        print("Could not read account or terminal:", mt5.last_error())
        raise SystemExit(1)
    # 3 safety lines: read these before any numbers
    print("Demo account:", acc.trade_mode == mt5.ACCOUNT_TRADE_MODE_DEMO)
    print("This session can trade (investor = False):", acc.trade_allowed)
    print("Algo trading button on:", ter.trade_allowed)
    if acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
        print("STOP: this is not a demo account.")
        raise SystemExit(1)
    if acc.trade_allowed:
        print("STOP: this session can trade. Log in again with the investor password.")
        raise SystemExit(1)

    mt5.symbol_select(SYMBOL, True)   # show the symbol in Market Watch if hidden
    info = mt5.symbol_info(SYMBOL)
    if info is None:
        print("Symbol not found:", SYMBOL, mt5.last_error())
        raise SystemExit(1)
    print("Symbol:", info.name, "| profit currency:", info.currency_profit, "| digits:", info.digits)
    print("contract_size:", info.trade_contract_size, "| tick_size:", info.trade_tick_size,
          "| tick_value_loss:", info.trade_tick_value_loss)
    print("volume_min:", info.volume_min, "| volume_step:", info.volume_step,
          "| volume_max:", info.volume_max)

    # position 0 is the forming candle -> start at 1 to get closed candles only
    rates = mt5.copy_rates_from_pos(SYMBOL, mt5.TIMEFRAME_H1, 1, CANDLES)
    if rates is None or len(rates) == 0:
        print("copy_rates_from_pos error:", mt5.last_error())
        raise SystemExit(1)
    df = pd.DataFrame(rates)
    df["time"] = pd.to_datetime(df["time"], unit="s")
    out = f"data/{SYMBOL.lower()}_h1_mt5.csv"
    df.to_csv(out, index=False)
    print(len(df), "closed candles ->", out, "| last candle opened:", df["time"].iloc[-1])
finally:
    mt5.shutdown()

Symbol names vary (GOLD, or XAUUSD with a suffix); check Market Watch (Ctrl+M) and set TL_SYMBOL for the current window. Only if you have several MT5 terminals installed, set TL_MT5_PATH to the demo terminal’s executable (right-click its desktop icon → Open file location → right-click the file → Copy as path; on Windows 10 hold Shift while right-clicking).

$env:TL_SYMBOL = "XAUUSD"
.venv\Scripts\python src\mt5_read.py
# only with several terminals:
$env:TL_MT5_PATH = "[PATH FROM COPY AS PATH]"
.venv\Scripts\python src\mt5_read.py

Example output (yours will differ by broker and time):

Demo account: True
This session can trade (investor = False): False
Algo trading button on: False
Symbol: XAUUSD | profit currency: USD | digits: 2
contract_size: 100.0 | tick_size: 0.01 | tick_value_loss: 1.0
volume_min: 0.01 | volume_step: 0.01 | volume_max: 100.0
500 closed candles -> data/xauusd_h1_mt5.csv | last candle opened: 2026-11-11 05:00:00

Read the three safety lines on every run before trusting any numbers.

You see Cause Fix
Version 3.15, 32 bit or ARM64; pip says No matching distribution found for MetaTrader5 Wheels exist only for Python 3.6–3.14 on 64-bit x64 Windows Recreate .venv with py -V:3.14 -m venv .venv, reinstall pandas, matplotlib, pytest, then MetaTrader5
ModuleNotFoundError: No module named 'MetaTrader5' A different Python, not .venv’s Always start with .venv\Scripts\python
initialize() error: (-6, …) Authorization failed: the terminal isn’t logged in Log in with the investor password, tick Save password, rerun
initialize() error with codes -10000 to -10005 Internal IPC error between Python and the terminal: not installed, not finished starting, or the wrong terminal Open the demo terminal first and wait for it to connect; with several installs set TL_MT5_PATH
STOP: this session can trade Logged in with the master password File → Login to Trade Account with the investor password; don’t edit out the check
Algo trading button on: True The toolbar button is on; the script continues because it only reads Turn it off (or untick Allow Auto Trading) and rerun
STOP: this is not a demo account A live or contest account is open Log into the demo; the script won’t run on anything else
Symbol not found: XAUUSD The broker uses another name Ctrl+M → right-click → Symbols, find it, set $env:TL_SYMBOL
copy_rates_from_pos error, or fewer than 500 candles The terminal only returns history it has loaded, capped by Max. bars in chart Open the H1 chart and scroll back so it loads more
OSError: Cannot save file into a non-existent directory: 'data' Wrong folder, or no data folder cd C:\trading-agent-lab; mkdir data

Size the lot from the broker’s spec, rounded down to volume_step

The lot function from earlier used fixed conventions (XAUUSD 1 lot = 100 oz, EURUSD 1 pip = 10 USD per lot, BTCUSD CFD 1 lot = 1 BTC). Brokers can differ, so the lot you actually use on MT5 must come from your demo broker’s symbol_info.

In words first: 1,000 USD demo, 1% risk is 10 USD. XAUUSD with the SL 5 USD away and tick size 0.01 is 5 ÷ 0.01 = 500 ticks. Each tick loses 1 USD per lot, so 1 lot loses 500 USD at the SL. You accept 10 USD, so the lot is 10 ÷ 500 = 0.02.

In general: loss per lot = (SL distance ÷ tick_size) × tick_value_loss; raw lot = risk ÷ loss per lot; lot = raw lot rounded down to volume_step. Below volume_min the function returns 0 (no trade with this SL); above volume_max it caps there. The SL distance is in price: XAUUSD 5 USD is 5, EURUSD 15 pips is 0.0015. It uses trade_tick_value_loss because this is a loss (trade_tick_value is the tick value for a profitable position); for USD-quoted symbols on a USD account they’re usually equal. The +1e-9 is floating-point tolerance, not rounding up.

Case (1,000 USD demo, 1% = 10 USD) Assumed spec Working Lot
XAUUSD, SL 5 USD away tick_size 0.01; tick value 1 USD (100 oz per lot) 5 ÷ 0.01 × 1 = 500 USD per lot; 10 ÷ 500 = 0.02 0.02
EURUSD, SL 15 pips (0.0015) tick_size 0.00001; tick value 1 USD (10 USD per pip per lot) 0.0015 ÷ 0.00001 × 1 = 150 USD per lot; 10 ÷ 150 = 0.066… 0.06
BTCUSD CFD, SL 1,500 USD away tick_size 0.01; tick value 0.01 USD (1 BTC per lot) 1,500 ÷ 0.01 × 0.01 = 1,500 USD per lot; 10 ÷ 1,500 = 0.0066… below 0.01: no trade

src/lot_mt5.py:

import math

def lot_by_broker(risk_usd, sl_distance_price, info):
    '''Lot from your broker's own specification, rounded DOWN to volume_step.

    info: the result of mt5.symbol_info(symbol), or any object with the same field names (for tests).
    sl_distance_price: distance from entry to SL in price
    (XAUUSD 5 USD is 5.0; EURUSD 15 pips is 0.0015). USD demo account.
    Returns 0.0 when the lot is below volume_min: no trade.
    '''
    if risk_usd <= 0 or sl_distance_price <= 0:
        raise ValueError('risk and SL distance must be positive')
    if info.trade_tick_size <= 0 or info.trade_tick_value_loss <= 0 or info.volume_step <= 0:
        raise ValueError('symbol specification missing: show the symbol in Market Watch and rerun')
    loss_per_lot = sl_distance_price / info.trade_tick_size * info.trade_tick_value_loss
    raw = risk_usd / loss_per_lot
    steps = math.floor(raw / info.volume_step + 1e-9)   # +1e-9: floating-point tolerance
    lot = round(steps * info.volume_step, 8)
    if lot < info.volume_min:
        return 0.0
    return min(lot, info.volume_max)

tests/test_lot_mt5.py uses simulated specs, so it runs without a terminal, even on a Mac. The fourth test is the fail-closed rule: missing information (a zero tick value) raises an error instead of guessing a lot.

from types import SimpleNamespace

import pytest

from src.lot_mt5 import lot_by_broker

def spec(tick_size, tick_value):
    '''Simulated values shaped like symbol_info; real ones come from your demo broker.'''
    return SimpleNamespace(trade_tick_size=tick_size, trade_tick_value_loss=tick_value,
                           volume_min=0.01, volume_step=0.01, volume_max=100.0)

def test_xauusd_sl_5_usd():
    assert lot_by_broker(10, 5.0, spec(0.01, 1.0)) == 0.02       # 10 / 500

def test_eurusd_sl_15_pips():
    assert lot_by_broker(10, 0.0015, spec(0.00001, 1.0)) == 0.06  # 10 / 150

def test_btcusd_below_volume_min_is_no_trade():
    assert lot_by_broker(10, 1500.0, spec(0.01, 0.01)) == 0.0     # 10 / 1,500

def test_missing_spec_raises():
    with pytest.raises(ValueError):
        lot_by_broker(10, 5.0, spec(0.01, 0.0))
.venv\Scripts\python -m pytest -q tests\test_lot_mt5.py

Expect 4 passed. Then compare against any position-size calculator for the same three cases. If they differ, open Market Watch → right-click the symbol → Specification, read Contract size, Tick size, Tick value, Minimal volume and Volume step, and explain the difference with those numbers. The broker’s lot is the usable lot; the fixed conventions are a reference. These are worked examples, not signals or advice.

Check an order without sending it

src/order_check_only.py builds a planned order from four inputs (symbol, BUY or SELL, SL distance in price, risk in USD), sizes the lot with the function above and checks three layers:

  1. Loss check. It puts its tick-based loss for 1 lot at the SL next to order_calc_profit (MT5’s estimate from the account and current market). That function returns a negative number for a loss; without the sign, the two should be close.
  2. Margin. order_calc_margin estimates margin (it ignores pending orders and open positions).
  3. order_check validates the request and returns a retcode plus margin and margin_free.

order_check sends nothing, and a successful check doesn’t mean a trade will succeed: by the time you send, the price may have moved and the broker may still reject it. The documented success example is retcode 0 with comment Done. In an investor session your result may differ, and the docs don’t say how order_check behaves when the account can’t trade, so record exactly the retcode and comment you get. 10017 (Trade is disabled) or 10027 (Autotrading disabled by client terminal) means a block is doing its job: the investor session, the terminal switch, or trading disabled on the symbol. Stop at the lot step; don’t unlock anything to test. If the call returns None, print last_error() (for example -8, auto-trading disabled).

The request carries magic number 26111101, so program-built orders can later be told apart from manual ones. The filling type (type_filling) is chosen from the symbol’s flags, i.e. what the broker allows: FOK fills the whole order or cancels; IOC fills what it can and cancels the rest; Return keeps the unfilled part working. Return isn’t allowed with Market execution, and a wrong choice can give 10030 (Invalid order filling type).

import os
import sys

import MetaTrader5 as mt5

from lot_mt5 import lot_by_broker

MAGIC_AI = 26111101   # ID for program-built orders

# Usage: .venv\Scripts\python src\order_check_only.py XAUUSD BUY 5 10
# (symbol, BUY or SELL, SL distance in price, risk in USD)
if len(sys.argv) != 5 or sys.argv[2] not in ("BUY", "SELL"):
    print("Usage: python src/order_check_only.py SYMBOL BUY|SELL SL_DISTANCE RISK_USD")
    raise SystemExit(1)
symbol, side = sys.argv[1], sys.argv[2]
sl_distance, risk = float(sys.argv[3]), float(sys.argv[4])

path = os.environ.get("TL_MT5_PATH", "").strip('"')
if not (mt5.initialize(path) if path else mt5.initialize()):
    print("initialize() error:", mt5.last_error())
    raise SystemExit(1)
try:
    acc = mt5.account_info()
    if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO or acc.trade_allowed:
        print("STOP: this runs only on a demo logged in with the investor password.")
        raise SystemExit(1)
    mt5.symbol_select(symbol, True)
    info = mt5.symbol_info(symbol)
    tick = mt5.symbol_info_tick(symbol)
    if info is None or tick is None:
        print("Could not read symbol or price:", mt5.last_error())
        raise SystemExit(1)
    try:
        lot = lot_by_broker(risk, sl_distance, info)
    except ValueError as err:
        print("STOP:", err)
        raise SystemExit(1)

    if side == "BUY":
        order_type, entry = mt5.ORDER_TYPE_BUY, tick.ask
        sl = round(entry - sl_distance, info.digits)
    else:
        order_type, entry = mt5.ORDER_TYPE_SELL, tick.bid
        sl = round(entry + sl_distance, info.digits)
    tick_loss = sl_distance / info.trade_tick_size * info.trade_tick_value_loss
    print("Loss of 1 lot at SL by ticks:", round(tick_loss, 2),
          "| by order_calc_profit:", mt5.order_calc_profit(order_type, symbol, 1.0, entry, sl))
    print("Lot rounded down:", lot, "| real risk:", round(lot * tick_loss, 2), "USD")
    if lot == 0:
        print("Below volume_min: NO TRADE. Stopping here.")
        raise SystemExit(0)
    print("Estimated margin:", mt5.order_calc_margin(order_type, symbol, lot, entry))

    # filling types the broker allows: flag 1 is FOK, flag 2 is IOC
    if info.filling_mode & 1:
        filling = mt5.ORDER_FILLING_FOK
    elif info.filling_mode & 2:
        filling = mt5.ORDER_FILLING_IOC
    else:
        filling = mt5.ORDER_FILLING_RETURN
    req = {"action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": order_type,
           "price": entry, "sl": sl, "deviation": 20, "magic": MAGIC_AI,
           "comment": "check only, not sent", "type_time": mt5.ORDER_TIME_GTC,
           "type_filling": filling}
    result = mt5.order_check(req)   # CHECK ONLY: this line sends no order
    if result is None:
        print("order_check returned None:", mt5.last_error())
    else:
        print("order_check retcode:", result.retcode, "| comment:", result.comment)
        print("margin:", result.margin, "| margin_free:", result.margin_free)
finally:
    mt5.shutdown()

Run the three cases, then confirm there’s no send call anywhere in src:

.venv\Scripts\python src\order_check_only.py XAUUSD BUY 5 10
.venv\Scripts\python src\order_check_only.py EURUSD BUY 0.0015 10
.venv\Scripts\python src\order_check_only.py BTCUSD BUY 1500 10
Select-String -Path src\*.py -Pattern "order_send"

Expect loss per lot of 500 and 150 USD (if the spec matches the table), lots 0.02 and 0.06 with an order_check result, NO TRADE for BTCUSD before order_check, and nothing printed by Select-String.

retcode MQL5 name Meaning What to do here
0 (documented example, comment Done) Check passed Record it; nothing has been sent
10014 TRADE_RETCODE_INVALID_VOLUME Invalid volume Check volume_min, volume_step; never round up
10016 TRADE_RETCODE_INVALID_STOPS Invalid SL or TP Compare the SL distance with Stops level in Specification
10017 TRADE_RETCODE_TRADE_DISABLED Trading disabled Expected with an investor session; stop at the lot step
10018 TRADE_RETCODE_MARKET_CLOSED Market closed Rerun during trading hours
10019 TRADE_RETCODE_NO_MONEY Not enough money Revisit lot and SL; never raise leverage to fit
10027 TRADE_RETCODE_CLIENT_DISABLES_AT Terminal has automated trading off The switch is working; don’t unlock it
10030 TRADE_RETCODE_INVALID_FILL Invalid filling type Note the symbol’s filling_mode for later
10031 TRADE_RETCODE_CONNECTION No connection to the trade server Check Journal, wait for reconnection, rerun

Hand the data to the agent

Here the agent doesn’t drive the terminal. It reads the CSV the script made, and runs the script only when you approve.

First establish which clock the time column uses. MT5 stores candle open times in UTC and returns UTC, but check it once by eye, because one hour off means the agent describes the wrong candle. While the market is open:

  1. On the symbol’s H1 chart open Data Window (Ctrl+D), hover the last closed candle, note its time and close.
  2. Compare with the CSV’s last row. Same time and price: same clock. Exactly N hours apart: write N down.
  3. Compare the open time of the forming H1 candle on the chart with the current UTC time. If it’s 08:20 UTC and the forming H1 candle opened at 10:00 on the chart, the chart runs UTC+2.
  4. Record the result and the date in AGENTS.md. Recheck monthly; broker server time may shift with the seasons.

Add this to the end of AGENTS.md yourself and commit it:

## MT5 demo data
- Source: MT5 terminal, DEMO account, investor password (view only).
- data/<symbol>_h1_mt5.csv is produced by src/mt5_read.py; closed candles only.
- The time column is the candle open time MT5 returns. Checked on [DATE]: [same as chart / N hours from
  chart]. UTC = chart time minus [N].
- Before the broker's seasonal time change (if any, give the date): UTC = chart time minus [N].
- Symbol specs come from symbol_info. Lots come from src/lot_mt5.py, rounded DOWN to volume_step; below
  volume_min, no trade.
- Every price level in an analysis must cite its CSV row (time value).
- Never ask for, read or write passwords, account numbers or .env.
- Never write or run order-sending code (order_send) at this stage.
cd C:\trading-agent-lab
notepad AGENTS.md
git add AGENTS.md
git commit -m "AGENTS.md: MT5 demo data conventions"
claude --permission-mode manual

The status bar must read ⏸ manual mode on (Shift+Tab until it does). With Codex, use codex --sandbox read-only --ask-for-approval on-request; there, commands within the read-only limits run without asking, so your prompt and your reading of each approval request matter more. Paste the prompt at the end. The only command to approve is .venv\Scripts\python src\mt5_read.py; anything else, especially installs or edits in src, gets No.

Grade the output:

Check Passes when
Row count, first and last time Match the file; the last candle is closed
Every price level Cites a time value and a column (open, high, low, close)
3 levels picked at random You find exactly that number on that row
Two scenarios Each has a condition checkable on a closed H1 candle; no “will rise”, no “buy”
Time gaps Named with the rows; not filled in

Strike out any level without a row behind it. Then compare three hours against a second source after converting the CSV time with your AGENTS.md rule. Small differences are normal; prices that match but are shifted by exactly one candle mean a time-conversion error. 500 H1 candles span 3–4 weeks; if the broker changed server time in that window, older candles are off by one more hour. If all three are shifted one hour the same way, record that period’s offset separately rather than changing today’s rule.

Optional: write a small read-only MCP server

With MCP, the agent can call “get 50 closed H1 candles” itself instead of reading a file you made. MT5’s own built-in MCP server (build 6060+) includes trading functions, and community servers run unvetted code on the machine with your terminal. So write a tiny server that wraps exactly three read functions, get_candles, symbol_spec and size_lot, with no order tool.

The official MCP Python SDK changed: mcp 2.3.0 uses the MCPServer class (the old FastMCP was renamed), and the old import path mcp.server.fastmcp is gone (ModuleNotFoundError). Guides still using FastMCP are outdated. mcp.run() with no arguments serves over stdio, and stdout is the transport, so never print; use logging.

Safety lives in the server’s code, not in instructions: only symbols in ALLOWED_SYMBOLS (edit to your broker’s names) and timeframes M15, H1, H4, D1; at most 1,000 candles per call; only on a demo session that can’t trade. Plain def tools may run on worker threads in parallel, so a lock makes sure only one tool opens and closes the terminal connection at a time. Keep the MT5 terminal open so initialize() doesn’t wait for it to start.

.venv\Scripts\python -m pip install mcp
.venv\Scripts\python -c "from mcp.server import MCPServer; print('ok')"
notepad src\mt5_read_server.py
'''Read-only MCP server for an MT5 demo: 3 read tools, no order tool.'''
import os
import threading
import time

import MetaTrader5 as mt5
from mcp.server import MCPServer

from lot_mt5 import lot_by_broker

mcp = MCPServer("mt5-read")
TIMEFRAMES = {"M15": mt5.TIMEFRAME_M15, "H1": mt5.TIMEFRAME_H1,
              "H4": mt5.TIMEFRAME_H4, "D1": mt5.TIMEFRAME_D1}
ALLOWED_SYMBOLS = {"XAUUSD", "EURUSD", "BTCUSD"}   # use your demo broker's exact names
SPEC_FIELDS = ("digits", "point", "spread", "trade_contract_size", "trade_tick_size",
               "trade_tick_value_loss", "volume_min", "volume_step", "volume_max",
               "trade_stops_level", "currency_profit")
_LOCK = threading.Lock()   # one tool at a time talks to the terminal

def _open(symbol):
    '''Attach to the terminal; accept only a demo logged in with the investor password.'''
    if symbol not in ALLOWED_SYMBOLS:
        raise ValueError("symbol not on the allowed list")
    path = os.environ.get("TL_MT5_PATH", "").strip('"')
    if not (mt5.initialize(path) if path else mt5.initialize()):
        raise RuntimeError("initialize() error: " + str(mt5.last_error()))
    acc = mt5.account_info()
    if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO or acc.trade_allowed:
        mt5.shutdown()
        raise RuntimeError("runs only on a demo logged in with the investor password")
    mt5.symbol_select(symbol, True)

@mcp.tool()
def get_candles(symbol: str, timeframe: str = "H1", count: int = 200) -> list[dict]:
    '''CLOSED candles (skips forming bar 0), newest last; time is the open time MT5 returns.'''
    if timeframe not in TIMEFRAMES:
        raise ValueError("timeframe must be M15, H1, H4 or D1")
    count = max(1, min(int(count), 1000))
    with _LOCK:
        _open(symbol)
        try:
            rates = mt5.copy_rates_from_pos(symbol, TIMEFRAMES[timeframe], 1, count)
            if rates is None:
                raise RuntimeError(str(mt5.last_error()))
            return [{"time": time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(r["time"]))),
                     "open": float(r["open"]), "high": float(r["high"]),
                     "low": float(r["low"]), "close": float(r["close"])} for r in rates]
        finally:
            mt5.shutdown()

@mcp.tool()
def symbol_spec(symbol: str) -> dict:
    '''Trading specification of a symbol, read from the demo broker's symbol_info.'''
    with _LOCK:
        _open(symbol)
        try:
            info = mt5.symbol_info(symbol)
            if info is None:
                raise RuntimeError(str(mt5.last_error()))
            return {k: getattr(info, k) for k in SPEC_FIELDS}
        finally:
            mt5.shutdown()

@mcp.tool()
def size_lot(symbol: str, risk_usd: float, sl_distance_price: float) -> dict:
    '''Lot rounded DOWN to the broker's volume_step; 0 means no trade. Places nothing.'''
    with _LOCK:
        _open(symbol)
        try:
            info = mt5.symbol_info(symbol)
            if info is None:
                raise RuntimeError(str(mt5.last_error()))
            return {"symbol": symbol, "lot": lot_by_broker(risk_usd, sl_distance_price, info)}
        finally:
            mt5.shutdown()

if __name__ == "__main__":
    mcp.run()   # no arguments: stdio

Run it by hand once to catch import errors: printing nothing and waiting is correct; Ctrl+C to quit. Then register it (local scope by default) and check:

.venv\Scripts\python src\mt5_read_server.py
claude mcp add --transport stdio mt5-read -- C:\trading-agent-lab\.venv\Scripts\python.exe C:\trading-agent-lab\src\mt5_read_server.py
claude mcp list
# with several terminals (remove first if already added); --env goes before the name,
# with at least one other option such as --transport between them:
claude mcp add --env TL_MT5_PATH="[PATH FROM COPY AS PATH]" --transport stdio mt5-read -- C:\trading-agent-lab\.venv\Scripts\python.exe C:\trading-agent-lab\src\mt5_read_server.py
# when you no longer need it:
claude mcp remove mt5-read

For Codex, in %USERPROFILE%\.codex\config.toml (uncomment env only with several terminals; no quotes around the path):

[mcp_servers.mt5-read]
command = 'C:\trading-agent-lab\.venv\Scripts\python.exe'
args = ['C:\trading-agent-lab\src\mt5_read_server.py']
cwd = 'C:\trading-agent-lab'
# env = { TL_MT5_PATH = '[PATH TO THE DEMO TERMINAL EXECUTABLE]' }
enabled_tools = ["get_candles", "symbol_spec", "size_lot"]
default_tools_approval_mode = "prompt"
tool_timeout_sec = 60

On the first call, confirm Codex actually asks you; if it doesn’t, stop and review the config. Then test: “Use server mt5-read: call symbol_spec for XAUUSD, then get_candles for XAUUSD, H1, count 5. Print the raw result as a table. Call nothing else, compute nothing.” Compare with the CSV, and try a symbol off the list: it must be refused. Read the parameters every time the agent asks to call a tool.

Try it: let the agent read the MT5 CSV

You are in [C:\trading-agent-lab]. Always ask me before every command and every file edit.
Context: I'm a trader who is learning. The data comes from an MT5 terminal, DEMO account, investor
password (view only). Never ask for, read or write passwords, account numbers or .env. Don't write or
suggest order-sending code.

1) Ask permission, then run exactly one command: .venv\Scripts\python src\mt5_read.py. Paste the output
   verbatim. If a line starts with STOP or reports an error, stop, explain what it means and what I
   need to do; don't edit the script or MT5 settings yourself.
2) Read [data/xauusd_h1_mt5.csv]: row count, time of the first and last rows, missing or duplicate
   hours, the row with the largest spread. The time column is the open time MT5 returns; apply the
   time-zone rule in AGENTS.md, don't guess.
3) Use only the last [48] rows. Describe the trend, recent highs and lows, and the most-traded price
   area. Present every price level as a table: level | CSV row time | column (open/high/low/close).
   Don't mention any level without a row behind it.
4) Give 2 scenarios, each with one condition checkable on a closed [H1] candle, e.g. "an H1 candle
   closes above …". Don't say which will happen.
5) List what this data can't tell us: upcoming news, higher timeframes, differences from other price
   sources.

The data cutoff is the last closed candle in the file. You don't know prices after it and you can be
wrong; say where you're unsure. No buy or sell recommendations.

Key takeaways

  • Keep three blocks: investor password login, the Python API trading box ticked, and the algo-trading button off.
  • Size from the broker’s spec: loss per lot = (SL distance ÷ tick_size) × tick_value_loss; lot = risk ÷ loss per lot, rounded down to volume_step. Missing spec means an error, not a guess.
  • Fetch candles from position 1, never 0, and verify the CSV’s clock against the chart before handing it to an agent.
  • order_check retcode 0 only means the request was valid at that moment. Nothing was sent, and a real send can still be rejected.

Comments