How do you build an EA (a program that runs by itself inside MT5), and why doesn’t renaming the file give you an MT4 version?
This post compiles a first EA that only writes a log line for each closed bar, then checks 20 bars of that log: no duplicates, no gaps. The easy mistake: 0 compile errors only means the syntax is right. Lot size, risk and fill prices still need their own checks.
Terms used below:
- Expert Advisor (EA): an automated program driven by terminal events. It needs checks on permissions, account mode and order state.
- MetaEditor: MT5’s code editor and compiler (F4 from the terminal).
- OnTick: the EA function MT5 calls on every new price, many times within one bar.
- Bar 1, bar 0: bar 1 is the last closed bar; bar 0 is still forming.
- Dry run: printing the order request the EA would send, without sending it.
Compile, then log one line per closed bar
Open MetaEditor from the terminal, create a new EA, save it in the right folder of the terminal you’re using, compile, and read Errors and Warnings. The first version only writes one log line per closed bar: symbol, time, OHLC. Only after comparing that log with the chart do you add an entry rule. The Strategy Tester needs the right symbol, timeframe, dates, tick model and costs; don’t just drag the EA onto a live chart.
| The compiler checks | The compiler doesn’t check | How to check more |
|---|---|---|
| Syntax | That risk and fills are right | Compare the per-bar log with the chart |
| Data types | That the signal logic means what you intended | Strategy Tester with Visualization |
| That the strategy has been validated |
Stop the same bar being processed many times
OnTick runs on every new price, so it fires many times within one bar. Store the timestamp of the bar you’ve processed, compute signals only from closed bars, and run once per new bar. Then check 20 bars of the log: no duplicates, and no gaps when the data is complete. Say “MQL5” explicitly; a port to MQL4 needs its own design and tests for orders and positions.
| Gate | Question | If not |
|---|---|---|
| 1 | Has a new bar just closed? | Ignore this tick |
| 2 | Is this bar’s timestamp not processed yet? | Already done: don’t run again |
| Passed | Compute from the closed bar, write the log, store the timestamp |
The EA, BarLogger.mq5:
//+------------------------------------------------------------------+
//| BarLogger.mq5: logs ONE line per CLOSED bar to the Experts tab |
//| and to MQL5\Files\bar_log.csv. Sends no orders. Demo/Tester only. |
//+------------------------------------------------------------------+
#property version "1.00"
input string RuleVersion = "log-only-v1"; // written on every line
input int EmaPeriod = 20; // an indicator value to compare with the chart
datetime g_last_logged = 0; // open time of the last bar already logged
int g_ema = INVALID_HANDLE;
int OnInit()
{
g_ema = iMA(_Symbol, _Period, EmaPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(g_ema == INVALID_HANDLE)
{
Print("iMA failed, error ", GetLastError());
return(INIT_FAILED);
}
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
if(g_ema != INVALID_HANDLE)
IndicatorRelease(g_ema);
}
void OnTick()
{
// OnTick runs on every new price, many times per bar: act only once per newly CLOSED bar
datetime opened = iTime(_Symbol, _Period, 1); // bar 1 = the last closed bar; bar 0 is still forming
if(opened == 0 || opened == g_last_logged)
return; // no history yet, or this bar is already logged
MqlRates r[];
double ema[];
if(CopyRates(_Symbol, _Period, 1, 1, r) != 1)
return;
if(CopyBuffer(g_ema, 0, 1, 1, ema) != 1)
return; // indicator not ready: try again on the next tick
g_last_logged = opened;
string line = StringFormat("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s",
RuleVersion, _Symbol, EnumToString(_Period),
TimeToString(opened, TIME_DATE | TIME_MINUTES),
TimeToString(opened + PeriodSeconds(_Period), TIME_DATE | TIME_MINUTES),
DoubleToString(r[0].open, _Digits), DoubleToString(r[0].high, _Digits),
DoubleToString(r[0].low, _Digits), DoubleToString(r[0].close, _Digits),
DoubleToString(ema[0], _Digits));
Print(line);
int h = FileOpen("bar_log.csv", FILE_READ | FILE_WRITE | FILE_TXT | FILE_ANSI | FILE_SHARE_READ);
if(h == INVALID_HANDLE)
{
Print("FileOpen failed, error ", GetLastError());
return;
}
if(FileSize(h) == 0)
FileWriteString(h, "rule_version,symbol,timeframe,bar_open_server,bar_close_server,open,high,low,close,ema\r\n");
FileSeek(h, 0, SEEK_END);
FileWriteString(h, line + "\r\n");
FileClose(h);
}To install it: MetaEditor (F4) → File → New → Expert Advisor (template); the
file belongs in MQL5\Experts (File → Open Data Folder shows where). Paste the
code over the template, compile with F7, and fix every error first. Attach it
to a demo chart, or run it in View → Strategy Tester with Visualization ticked.
The CSV lands in MQL5\Files\bar_log.csv of the terminal’s data folder; in the
Strategy Tester it lands in the tester agent’s own MQL5\Files folder
instead.
Compare a few lines with the chart’s Data Window (open, high, low, close and
the EMA on the same bar), then check the latest 20 bars with a small script,
src/check_bar_log.py:
# src/check_bar_log.py: check an EA's bar log: one line per closed bar, no duplicates, no unexplained gaps.
# Reads the CSV only. Run: .venv\Scripts\python src\check_bar_log.py data\bar_log.csv --last 20
import argparse
import csv
from collections import Counter
from datetime import datetime, timedelta
TF = "%Y.%m.%d %H:%M" # MQL5 TimeToString(..., TIME_DATE | TIME_MINUTES)
STEP = {"PERIOD_M15": 15, "PERIOD_H1": 60, "PERIOD_H4": 240}
ap = argparse.ArgumentParser()
ap.add_argument("file")
ap.add_argument("--last", type=int, default=20, help="how many of the latest bars to check")
a = ap.parse_args()
with open(a.file, encoding="utf-8-sig") as f:
rows = list(csv.DictReader(f))[-a.last:]
dups = [t for t, n in Counter(r["bar_open_server"] for r in rows).items() if n > 1]
step = timedelta(minutes=STEP[rows[0]["timeframe"]])
gaps = []
for p, x in zip(rows, rows[1:]):
t0, t1 = datetime.strptime(p["bar_open_server"], TF), datetime.strptime(x["bar_open_server"], TF)
if t1 != t0 and t1 - t0 != step: # equal times are duplicates, counted above
gaps.append(f"{p['bar_open_server']} -> {x['bar_open_server']}")
bad = [r["bar_open_server"] for r in rows
if not float(r["low"]) <= min(float(r["open"]), float(r["close"])) <= max(float(r["open"]), float(r["close"])) <= float(r["high"])]
print(f"{len(rows)} bars | versions {sorted({r['rule_version'] for r in rows})} | duplicates {len(dups)} | gaps {len(gaps)} | bad OHLC {len(bad)}")
for g in gaps:
print(" gap:", g, "(market break or weekend? if not, the EA missed a bar)")
for d in dups:
print(" duplicate:", d, "(the once-per-bar check isn't working)")
for b in bad:
print(" bad OHLC:", b)The log’s last lines look like this (made-up values):
rule_version,symbol,timeframe,bar_open_server,bar_close_server,open,high,low,close,ema
log-only-v1,XAUUSD,PERIOD_M15,2026.11.17 15:00,2026.11.17 15:15,4063.100,4064.300,4062.800,4063.900,4062.600
log-only-v1,XAUUSD,PERIOD_M15,2026.11.17 15:15,2026.11.17 15:30,4063.900,4065.100,4063.600,4064.700,4063.400
log-only-v1,XAUUSD,PERIOD_M15,2026.11.17 15:30,2026.11.17 15:45,4064.700,4065.100,4063.300,4063.600,4064.200On a made-up log with one planted duplicate and one missing bar:
20 bars | versions ['log-only-v1'] | duplicates 1 | gaps 1 | bad OHLC 0
gap: 2026.11.17 13:45 -> 2026.11.17 14:15 (market break or weekend? if not, the EA missed a bar)
duplicate: 2026.11.17 12:15 (the once-per-bar check isn't working)A gap can be the market’s daily break or the weekend; if it isn’t, the EA missed a bar. A duplicate means the once-per-bar check isn’t working.
MT5, MT4, cTrader: code doesn’t carry over
| MT5 | MT4 | cTrader |
|---|---|---|
| MQL5 | Needs its own MQL4 code | Robots are called cBots |
Files in MQL5\Experts |
Indicator and order/position APIs differ | Written in C# or Python in cTrader Algo |
| Compile in MetaEditor (F7) | Renaming to .mq4 isn’t a port |
An MQL5 EA doesn’t carry over |
If your demo account is on cTrader rather than MT5, the robot there is a cBot, written in C# or Python in cTrader Algo. Changing platforms means rewriting, recompiling and retesting from the log-each-bar step.
Worked example: an EA that reports signals before an EA that places orders
Build a demo EA in four rungs; finish each before the next:
| Rung | What | Check |
|---|---|---|
| 1. Log only | Closed bars: symbol, timeframe, bar close, rule version, indicator values | The values match the indicator on the chart |
| 2. Specification check | Contract, tick, volume min and step, stops level | Read from the symbol, not typed in |
| 3. Dry run | Print the intended request and the budget | A size below the minimum is refused |
| 4. Demo order adapter | Handle retcodes | Demo account only |
On a copy of the project for the demo, ask the AI for an EA that only reads closed bars and logs symbol, timeframe, bar close, rule version and indicator values. Compile it in MetaEditor, read each error, run it on a demo chart and compare the values with the indicator on screen; leave order sending off.
Once the data is right, add a function that checks the specification: contract, tick, volume minimum and step, stops level. Then a dry run that prints the intended request with the budget; test that a size below the minimum is refused. Only after that write the demo order adapter and handle retcodes.
MQL4 and MQL5 differ in their indicator, order and position APIs and in how data is fetched. Changing the file extension isn’t moving the system. When you ask an AI to port code, ask for the list of differences, a separate build, and tests comparing signals and quantities; don’t treat a successful compile as validating the strategy.
Try it: an MQL5 skeleton with orders off by default
From this spec, propose a skeleton MQL5 EA for MetaTrader 5. Before writing, check the official MQL5 documentation and ask if any rule is unclear. Create the files in a separate project folder; don't read credentials, don't log in to an account, don't send trade requests. The EA may only run its logic in the Strategy Tester, with an input that keeps orders off by default. Say exactly how it handles symbol, point and tick size, lot min/max/step, stops level, spread and retcodes. Then walk me through compiling in MetaEditor and setting up Strategy Tester with Visualization, step by step. Don't claim the code is safe or ready for live trading. Spec: [PASTE THE TABLE].Fill the [brackets] with your own details. Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- MetaEditor (F4) → File → New → Expert Advisor; the file goes in
MQL5\Experts; paste the MQL5 code, compile (F7), fix errors first. - MT5 → View → Strategy Tester: pick the EA, symbol, timeframe, dates, deposit and tick model; tick Visualization to watch the trades.
- MT4 needs its own MQL4 code; only try it on a demo account after checking the EA and the symbol’s specification.
Key takeaways
- OnTick runs on every new price, many times per bar; store the time of the bar you processed so each bar is computed once.
- Before any demo order: check the lot step and the minimum SL distance, print the intended order without sending it, and refuse a lot below the minimum.
- To run on MT4, write a separate MQL4 version, because orders and positions work differently; test it and compare its signals with the MT5 version.
Comments