To create an Expert Advisor (EA) in MQL5, you open MetaEditor from MetaTrader 5, create a new Expert Advisor, write the logic in the functions OnInit e OnTick, compiles and tests in the Strategy Tester. Below is a complete and functional crossover AE of means, with stop, target and control of one position at a time, explained line by line.
In short: An EA is a program that runs within MetaTrader 5 and reacts to each new quote by the function
OnTick. indicators are created once inOnInit(likeiMA) and read withCopyBuffer. orders are sent with the classCTrade. Before the real account, test with real ticks, costs and forward test, and then demo.
What is MQL5 and how does an Expert Advisor work?
MQL5 is the language of MetaQuotes for MetaTrader 5, a platform launched in 2010. It is not compatible with MetaTrader 4's MQL4, according to the MetaQuotes entry on Wikipedia. The syntax remembers C++.
An EA responds to events. The three main ones:
| Function | When it's called | Typical use |
|---|---|---|
OnInit() | When the EA is attached to the chart | Create indicator handles, validate parameters |
OnTick() | With each new quotation of the asset | Read indicators, decide, send orders |
OnDeinit() | When the EA is removed | Release indicators, clean objects |
A OnTick documentation Remember that the new tick event only exists for Expert Advisors; indicators and scripts do not receive it. If you still don't know the platform, check out the MetaTrader 5 Guide.
Want to buy bitcoin?Deposit in reais with PIX and buy BTC and other cryptos in a few minutes.Open accountHow to create the EA file in MetaEditor?
- Open MetaEditorIn MetaTrader 5, press F4 or click the editor icon.
- New fileChoose "Expert Advisor", give a name and proceed until you finish.
- Paste the codeReplace the model with the code for this article.
- CompilePress F7. The error tab should show 0 errors.
- Attach to the chartIn the terminal browser, drag the EA to the chart and enable Algotrading.
Those who don't want to program can use the MQL5 assistant, which generates an EA by combining signal modules, capital management and trailing stop. It is useful to learn the structure, but limits the logic.
The code: EA for crossing averages with CTrade
#include <Trade\Trade.mqh>
input int InpFastPeriod = 9; // Média rápida (EMA)
input int InpSlowPeriod = 21; // Média lenta (EMA)
input double InpLots = 0.10; // Lote
input int InpStopPoints = 300; // Stop loss em pontos
input int InpTakePoints = 600; // Take profit em pontos
input ulong InpMagic = 20261025; // Número mágico do EA
CTrade trade;
int hFast = INVALID_HANDLE;
int hSlow = INVALID_HANDLE;
datetime lastBar = 0;
int OnInit()
{
if(InpFastPeriod >= InpSlowPeriod)
return INIT_PARAMETERS_INCORRECT;
hFast = iMA(_Symbol, _Period, InpFastPeriod, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, InpSlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
trade.SetDeviationInPoints(20);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
IndicatorRelease(hFast);
IndicatorRelease(hSlow);
}
ulong MinhaPosicao()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket > 0 &&
PositionGetString(POSITION_SYMBOL) == _Symbol &&
PositionGetInteger(POSITION_MAGIC) == (long)InpMagic)
return ticket;
}
return 0;
}
void OnTick()
{
datetime barTime = iTime(_Symbol, _Period, 0);
if(barTime == lastBar)
return; // decide só uma vez por candle
lastBar = barTime;
double fast[], slow[];
ArraySetAsSeries(fast, true);
ArraySetAsSeries(slow, true);
if(CopyBuffer(hFast, 0, 1, 2, fast) < 2 || CopyBuffer(hSlow, 0, 1, 2, slow) < 2)
return;
// índice 0 = último candle fechado; índice 1 = o anterior
bool crossUp = fast[1] <= slow[1] && fast[0] > slow[0];
bool crossDown = fast[1] >= slow[1] && fast[0] < slow[0];
ulong ticket = MinhaPosicao();
if(ticket > 0 && crossDown)
trade.PositionClose(ticket);
if(ticket == 0 && crossUp)
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double sl = NormalizeDouble(ask - InpStopPoints * _Point, _Digits);
double tp = NormalizeDouble(ask + InpTakePoints * _Point, _Digits);
if(!trade.Buy(InpLots, _Symbol, ask, sl, tp, "Cruzamento EMA"))
Print("Falha na compra: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());
}
}
What each part does
#include <Trade\Trade.mqh>bring the class CTrade, which simplifies buying, selling and closing.inputCreates editable parameters in the EA window and the optimizer.iMAreturn one handle (identifier) of the indicator, not the value. In case of error, returnsINVALID_HANDLE, according to iMA reference.CopyBuffer(hFast, 0, 1, 2, fast)Copy two values from Candle 1 (the last closed). The CopyBuffer documentation explains that the count goes from the present to the past: position 0 is the current candlestick, still in formation. Reading from 1 avoids signs that appear and disappear.- Candle control: compare
iTimewithlastBarMakes EA decide once per candlestick, as in the closing backtest. - Magic number: Identifies the positions of this EA, so as not to mess with manual operations or other robots.
SetDeviationInPoints(20)Defines the maximum deviation accepted between request and executed price.
The EA uses two exponential averages: the shortest one reacts before the price, and the crossing between them generates the signal. Credit: Alex Kofman, Public Domain, via Wikimedia Commons.
The PIP and Lot accounts are in Pip, Lot and Spread; particularities of gold, in How to operate gold (XAUUSD).
How to test EA in Strategy Tester?
Open the tester (CTRL+R), choose the EA, the asset, the period and the modeling mode. MetaTrader 5 offers these modes, according to the official help:
| Mode | Precision | When to use |
|---|---|---|
| Every tick based on real ticks | Highest (real broker's real ticks) | FINAL VALIDATION |
| Every tick | High (simulated ticks) | When there are no real ticks |
| 1 minute OHLC | Average | Quick tests |
| Open prices only | Low | EA screening that decides only at the opening of the candlestick |
| Math calculations | No market data | Internal calculations and research |
Three adjustments make the test more honest:
- Execution Delay: The execution field allows you to simulate random or fixed delay, including based on the actual ping to the server.
- Forward: Reserve 1/2, 1/3 or 1/4 of the period for a test that does not participate in the optimization. The results appear in the “Forward” tab.
- Spread and Costs: Use the actual spread or a conservative amount and set up a commission if the account charges.
The optimizer offers complete search and fast genetic algorithm (Types of Optimization). Use sparingly: Too much optimizing leads to overfitting. The fundamentals of the test are in backtest.
To see an EA being written and executed from scratch in Portuguese, the video below covers the complete flow in MetaEditor.
Improvements for the next version
Risk
- Lot calculated by risk in % of the account
- Daily loss limit
- Maximum spread filter
Logic
- Stop by ATR instead of fixed points
- Operate sold at the crossing down
- Larger graphic time trend filter
Operation
- Time filter (avoid scrolling)
- Detailed logs in file
- Reconnection treatment
Risk batch calculation is the most important improvement. With $10,000 bill, 1% risk ($100) and 30 pips stop at EUR/USD, where 1 standard lot is worth about $10 per pip, the lot is 100 ÷ (30 × 10) = 0.33. The formula and care are in Risk Management in Trading.
Care before using real money
- Demo account first: Compare live operations with those of the tester.
- Regulated broker: The CVM informs that there is no authorized Forex and CFD offer in Brazil; Understand the scenario in Is forex cool in Brazil? e How to Choose Forex Broker.
- Moderate leverage: vide Leverage and margin.
- No Martingale: Doubling the lot after losses is the fastest way to reset an account with an EA.
- VPS: EA only operates with the terminal open and connected.
If you prefer to prototype before on the chart, the same crossing is in the Pine Script Tutorial.
Informational content, not investment advice.
Frequently asked questions
What is an Expert Advisor?
It is a program written in MQL5 (or MQL4, in MetaTrader 4) that runs inside the MetaTrader terminal, analyzes the quotes and can open, modify and close operations automatically.
Is MQL5 difficult?
It's harder than Pine Script, because the syntax is similar to C++ and you deal with indicator handles and sending orders. With the standard library's CTrade class, a basic robot fits in under 80 lines.
Does MQL4 robot work on MetaTrader 5?
Not directly. MetaTrader 5 is not compatible with MetaTrader 4, and the code in MQL4 needs to be rewritten or adapted to MQL5.
How to test an Expert Advisor?
In the MetaTrader 5's Strategy Tester, preferably in realistic tick mode, with realistic spread and delay, reserving part of the period for forward test. Then take into account demo.
Do I need to leave the computer on for the robot to operate?
Yes. Expert Advisor only runs while the terminal is open and connected. That's why many traders use a virtual server (VPS).
References
This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.