Get Free Consultation!
We are ready to answer right now! Sign up for a free consultation.
I consent to the processing of personal data and agree with the user agreement and privacy policy
Debugging Expert Advisors (EAs) can feel frustrating when trades don’t trigger, logic seems broken, or results don’t match your expectations. Knowing how to debug mql4 code in mt4 expert advisors turns that frustration into a clear, systematic process.
In this guide, you’ll learn practical, repeatable methods to find and fix bugs using MetaEditor, MT4 Strategy Tester, log files, and clean coding practices. Whether you’re just starting with MQL4 or you’ve already built several EAs, this walkthrough will help you debug faster and ship more stable trading robots.
An Expert Advisor is an automated trading program written in MQL4 that runs inside the MetaTrader 4 platform. It can:
Because an EA runs automatically, even a small bug can repeat many times and cause big losses. That’s why a solid debugging process is essential.
Most EAs are driven by special functions:
OnInit() – runs once when the EA is loaded.OnDeinit() – runs when the EA is removed or the terminal shuts down.OnTick() – runs every time a new tick (price update) arrives.Your trade logic, risk checks, and indicator calculations usually live inside OnTick(). If something goes wrong here, it may affect every tick, so debugging this flow is one of your main tasks.
Some of the most common issues include:
if or else, incorrect comparisons.OrderSend, wrong magic numbers, or ticket mix-ups.Knowing these categories helps you guess where to look when something misbehaves.
MetaEditor is the official editor for MQL4. To start:
F4).This integration is what lets you edit, compile, and test in a tight loop.
Before debugging logic, you must compile without syntax errors:
.mq4 file.Compilation checks:
A clean compile doesn’t mean there are no bugs, but it’s your first gate.
MT4 expects files in specific folders:
MQL4/Experts – for EAs.MQL4/Indicators – for custom indicators.MQL4/Include – for shared .mqh files.Keep your project tidy:
.mqh includes.EA_MeanReversion.mq4, RiskManagement.mqh.A clean structure makes debugging easier when your EA grows.
This is where you start actively investigating what your code is doing.
The simplest debugging tool is the Print() function. Example:
Print("Ask = ", Ask, " Bid = ", Bid);
Print("Current lot size: ", Lots, " StopLoss: ", sl, " TakeProfit: ", tp);
These messages appear in the Experts tab (and sometimes in the logs folder). You can:
Print("Step 1: Entry checks passed");.Use Print() generously during development, then remove or reduce them later.
MT4 logs help you reconstruct what happened:
logs folder in your MT4 data directory.A useful pattern is to tag logs:
Print("[CHECK_ENTRY] Condition met, trying to open BUY order");
Print("[ERROR_ORDER] OrderSend failed, error = ", GetLastError());
This way, you can filter quickly and follow the sequence of events.
Trade functions like OrderSend and OrderModify return values you must check:
int ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, sl, tp, "EA Test", Magic, 0, clrNONE);
if(ticket < 0)
{
int err = GetLastError();
Print("OrderSend failed with error #", err);
// Optional: handle or retry depending on error
}
By logging error codes, you can search what they mean in the MQL4 documentation (for reference, see the official docs on the MetaQuotes site). This is a crucial part of learning how to debug mql4 code in mt4 expert advisors responsibly and safely.
The Strategy Tester lets you run your EA on historical data:
Backtesting lets you:
In Visual Mode, you can:
This makes it easier to spot mismatches between expectation and reality.
After a test:
Look for:
MetaEditor has a built-in debugger that lets you:
Typical steps:
F5.The EA then starts under the debugger.
Breakpoints allow you to stop your EA when:
Once stopped, you can:
You can step through:
OnInit() to ensure parameters, indicators, and variables initialize correctly.OnTick() to verify entry conditions, trade placement, and risk calculations.OnDeinit() to ensure cleanup is done properly.Stepping line by line is slower than using Print(), but it gives you extremely precise control over the debugging process.
If the EA never opens trades:
true.OrderSend is actually called (log before and after the call).When trades are out of control:
if conditions for logical mistakes (e.g., using || instead of &&).Crashes can come from:
OnTick().Add checks like:
if(volume != 0)
ratio = price / volume;
else
Print("Warning: volume is zero, skipping ratio calculation");
And always confirm array indexes are within bounds.
Split your EA into small functions:
bool CheckEntryConditions();void OpenBuyOrder();void OpenSellOrder();void ManageOpenPositions();This makes your code:
Avoid “magic numbers” directly in code. Use:
#define MAGIC_EA_ID 123456
#define MAX_TRADES 5
Use descriptive variable names like maxRiskPerTrade instead of r or x. This reduces confusion when you come back to the code weeks or months later.
Add comments that explain why, not just what:
// Prevent multiple entries on the same bar
if(lastEntryTime == Time[0]) return;
Use version numbers in the file header and consider basic version control (e.g., Git or even renamed files with dates) to track changes.
For complex EAs, Print() might not be enough. You can write to files:
int handle = FileOpen("EA_Log.csv", FILE_CSV|FILE_WRITE|FILE_READ, ';');
if(handle != INVALID_HANDLE)
{
FileSeek(handle, 0, SEEK_END);
FileWrite(handle, TimeToStr(TimeCurrent(), TIME_DATE|TIME_SECONDS), Bid, Ask, Lots);
FileClose(handle);
}
This lets you:
MT4 has Global Variables of the Terminal, visible via Tools → Global Variables:
GlobalVariableSet("EA_LastTradeTime", TimeCurrent());
double value = GlobalVariableGet("EA_LastTradeTime");
These variables persist even if MT4 restarts, so they’re handy for:
If MT4 becomes slow:
OnTick().Optimization isn’t just about speed; a faster EA is easier to debug because it behaves more predictably under load.
On a demo account:
Make sure your EA:
While the EA runs:
Keep an eye on:
Different brokers have different:
So always:
MarketInfo(Symbol(), MODE_STOPLEVEL) and other broker settings.Don’t debug on a live account with big money. Instead:
Always validate inputs:
if(Lots < 0.01) Lots = 0.01;
if(Lots > 1.0) Lots = 1.0; // Safety cap
You can also implement:
When OrderSend fails with certain errors (like requotes or off quotes), you may retry or log and skip:
int err = GetLastError();
if(err == ERR_OFF_QUOTES || err == ERR_REQUOTE)
{
Print("Temporary error, will retry later. Error #", err);
// maybe implement a retry delay
}
This makes your EA more stable in real-world market conditions.
Common reasons:
OrderSend fails but you aren’t checking or logging the error.Add Print() statements around your entry logic and around OrderSend to see what’s actually happening.
Open the Terminal window (Ctrl+T) and go to the Experts tab. All Print() messages from your EA show up there with timestamps. You can also inspect log files in the terminal’s data folder under logs.
Yes. Use the MetaEditor debugger:
F5 to start debugging.This helps you inspect variables and follow the execution path precisely.
Always capture the return value:
int ticket = OrderSend(...);
if(ticket < 0)
{
int err = GetLastError();
Print("OrderSend failed, error #", err);
}
Then look up the error code in the official MQL4 documentation on MetaQuotes’ site for a detailed explanation and suggested fixes.
Always start with demo. Once your EA is stable and tested through backtests and forward tests, you can move to live accounts with small lot sizes. Debugging directly on live with large risk is dangerous and unnecessary.
Use a combination of:
Print() for quick checks.FileOpen, FileWrite) for long-term, structured data.You can export logs as CSV and open them in Excel or similar tools for deeper analysis.
Learning how to debug mql4 code in mt4 expert advisors is one of the most valuable skills you can develop as an EA developer. Instead of guessing why trades fail, you now have a toolkit:
Print() and logs for quick insights.By combining these methods and always testing on demo first, you can catch bugs early, protect your capital, and steadily improve the reliability and profitability of your trading robots.