Step By Step Guide On Creating MQL5 And MQL4 EA(Expert Adviser) Trading Bot
FOREX BOT AUTOMATION 11 June 2026

Step By Step Guide On Creating MQL5 And MQL4 EA(Expert Adviser) Trading Bot

A
angiterver2244
Author
0 comments    122 views

Part 1

What is an EA (Expert Advisor)Bot?
An Expert Advisor (EA) is a piece of software written specifically for the MetaTrader platform. Its job is to monitor financial markets and execute trades automatically based on a pre-defined set of rules (your strategy).
The “Expert” part: It follows your logic perfectly without getting tired, greedy, or scared.
The “Advisor” part: It can either alert you to a trade or execute it for you instantly.

Creating an Expert Advisor (EA) for MetaTrader 4 (MQL4) and MetaTrader 5 (MQL5) is a rewarding way to automate your trading strategy. While the languages are similar (both based on C++), MQL5 is more modern and powerful, whereas MQL4 is simpler for legacy systems.

Here is a step by step guide to building your first basic EA.

Phase 1: The Setup
Before writing code, you need the right environment.
1. Install MetaTrader: Download MT4 or MT5 from your broker.
2. Open MetaEditor: Inside MetaTrader, press F4 or click the “IDE” icon (a small book with a gear) on the toolbar. This is where you will write your code.
3. Create a New File:
In MetaEditor, click New.
Select Expert Advisor (template) and click Next.
Give it a name (e.g EABot).
Click Next through the event handler options (the defaults are fine for now) and click Finish.

Phase 2: Understanding the Structure
Your template will contain three “Event Handlers.” Think of these as the bot’s brain functions:

 

OnInit(): Runs once when you attach the bot to a chart. Use this for setup.
OnDeinit(): Runs once when you remove the bot. Use this for cleanup.
OnTick(): This is the heart of the bot. It runs every single time the price moves (a “tick”). Your logic goes here.

Phase 3: Writing the Code (Moving Average Cross)
We will build a simple “Moving Average Cross” strategy: Buy when a fast moving average crosses above a slow one; Sell when it crosses below.
1. Define Inputs
At the very top of your code, define variables that you can change without rewriting the code.

 

CPP
input int FastMA = 10; // Period for the Fast Moving Average
input int SlowMA = 20; // Period for the Slow Moving Average
input double Lots = 0.1; // Trading volume

2. The Logic (Inside OnTick)
We need to calculate the current price and the MA values.

For MQL4:

 

CPP
void OnTick() {
// Calculate MA values
double fastPrev = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 1);
double fastCurr = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 0);
double slowPrev = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 1);
double slowCurr = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 0);

// Check for Buy Signal (Fast crosses above Slow)
if(fastPrev < slowPrev && fastCurr > slowCurr) {
OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, 0, 0, “My Buy”, 0, 0, clrGreen);
}

// Check for Sell Signal (Fast crosses below Slow)
if(fastPrev > slowPrev && fastCurr < slowCurr) {
OrderSend(Symbol(), OP_SELL, Lots, Bid, 3, 0, 0, “My Sell”, 0, 0, clrRed);
}
}

For MQL5:
MQL5 requires a bit more setup for trading using the CTrade class.

 

CPP
#include
CTrade trade;

void OnTick() {
// Get MA Handles and Copy Buffer (Brief version for beginners)
double fastArray[], slowArray[];
ArraySetAsSeries(fastArray, true);
ArraySetAsSeries(slowArray, true);

// Logic is similar, but uses trade.Buy() and trade.Sell()
if(fastArray[0] > slowArray[0] && fastArray[1] < slowArray[1]) {
trade.Buy(Lots, _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_ASK), 0, 0);
}
}

Phase 4: Compiling and Testing
1. Compile: Press F7 in MetaEditor. Check the “Errors” tab at the bottom. If it says “0 errors,” you are successful.
2. Attach to Chart: Go back to MetaTrader. Find your bot in the Navigator window (Ctrl+N) under “Expert Advisors.” Drag it onto a chart.
3. Enable Trading: Ensure the Algo Trading button at the top of MetaTrader is green.

4. Strategy Tester: Press Ctrl+R to open the Strategy Tester. Select your bot and a date range to see how it would have performed in the past.

Critical Tips for Beginners
Start on Demo: Never run a new bot on a live account first. Bugs in code can empty an account in seconds.
The “Magic Number”: In professional EAs, you use a “Magic Number” to identify orders so the bot doesn’t accidentally close trades you opened manually.
Check for Open Orders: Add a line of code to check if a trade is already open before opening a new one, otherwise, the bot might open 100 trades on a single signal.

Remember me for faster sign in

to take the bot from a basic “crossing lines” EA bot to a professional grade Expert Advisor, you need to add layers of protection. Adding Stop Loss (SL), Take Profit (TP), Slippage Control, section Filters and news filter makes the bot much more safer.
Here is the logic for both MQL4 and MQL5.

 

Defining the Advanced Inputs
Add this variables to the code. This allows you to control the risk and timing from the MetaTrader inputs settings window.
Note: (10 points = 1 pip)
CPP
input int StopLoss = 200; // Stop Loss in Points (10 points = 1 pip)
input int TakeProfit = 400; // Take Profit in Points
input int MaxSlippage = 3; // Max allowed price deviation (Pips)
input int StartHour = 9; // Trading Start Hour (Broker Time)
input int EndHour = 18; // Trading End Hour (Broker Time)
input bool UseNewsFilter = true; // Enable/Disable News Filter (Manual toggle)

This is just an example for advanced inputs parameters you can make changes as you want.

Trading Session & Slippage Control
Before the bot looks for a “Buy” or “Sell” signal, it must pass a “Permission Check.” You put this inside the OnTick() function.
The Time Filter
This ensures the bot only trades during high liquidity sessions (like London or New York) and stays flat during volatile market opens/closes.

 

CPP
bool IsTradingTime() {
datetime currentTime = TimeCurrent();
int currentHour = TimeHour(currentTime);

if(currentHour >= StartHour && currentHour < EndHour) {
return true;
}
return false;
}

Slippage Logic
In MQL4, slippage is a parameter inside the OrderSend() function. In MQL5, you set it using trade.SetDeviationInPoints(). This prevents the bot from entering a trade if the price jumps too far during the execution.

Adding SL, TP, and News Management
Here is how the refined execution looks. Note how you calculate the price levels and check if a trade is already open to avoid “cluttering” the chart.

Optimized MQL4 Code Snippet

 

CPP
void OnTick() {
// 1. Check Trading Session
if(!IsTradingTime()) return;

// 2. Check if we already have an open position
if(OrdersTotal() > 0) return;

double ask = MarketInfo(Symbol(), MODE_ASK);
double bid = MarketInfo(Symbol(), MODE_BID);

// 3. Buy Logic with SL/TP and Slippage
if(fastCurr > slowCurr && fastPrev <= slowPrev) {
double sl = ask — (StopLoss * Point);
double tp = ask + (TakeProfit * Point);

int ticket = OrderSend(Symbol(), OP_BUY, Lots, ask, MaxSlippage, sl, tp, “MyBot”, 12345, 0, clrGreen);
}
}

Optimized MQL5 Code Snippet
CPP
#include
CTrade trade;

void OnTick() {
if(!IsTradingTime()) return;
if(PositionsTotal() > 0) return; // Basic check for MQL5

trade.SetDeviationInPoints(MaxSlippage); // Slippage control

if(fastCurr > slowCurr && fastPrev <= slowPrev) {
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double sl = ask — (StopLoss * _Point);
double tp = ask + (TakeProfit * _Point);

trade.Buy(Lots, _Symbol, ask, sl, tp, “MQL5 Bot”);
}
}

The News Filter Challenge
A Perfect News Filter is the most complex part of bot programming because MQL4/5 does not have a built in Economic Calendar feed. You have two options:
1. The Manual Way (Recommended for Beginners): Use an input bool AvoidNews = true;. You manually turn the bot off during NFP or CPI announcements.
2. The Automatic Way (Advanced): You must use WebRequest() to pull data from an external URL (like ForexFactory or Investing.com) and parse the HTML/JSON.
NOTE: This requires high-level coding knowledge.
Beginner Tip: Start by coding a Pause timer. For example, tell the bot not to trade on Fridays after 16:00, which avoids most weekend gap risks and late week news spikes.

Checklist for Perfect Accuracy
NormalizeDouble: Always wrap your Price, SL, and TP calculations in NormalizeDouble(value, Digits) to ensure the broker’s server accepts the decimal places.
Check Return Values: Always check if OrderSend or trade.Buy returned a “true” or “ticket number.” If it returns -1, print the error code using GetLastError() to see why (e.g., “Invalid Stops” or “No Money”).
Magic Numbers: Use a unique ID (e.g 12345) in your trade functions so your bot doesn’t try to manage trades you opened manually on your phone.

Happy coding and trading, always remember to apply proper risk management.

Comments 0

No approved comments yet — be the first!

Leave a Comment

Comments are reviewed before appearing publicly. Thank you for keeping it constructive.