Start investing in Bitcoin with Pix, in a few minutesSponsoredOpen free account
MQL5: How to create an Expert Advisor in MetaTrader 5 walkthrough
Trading

MQL5: How to create an Expert Advisor in MetaTrader 5 walkthrough

Learn MQL5 by creating an Expert Advisor in MetaTrader 5: OnInit, OnTick, CTrade, moving averages, stop and target, more like testing in Strategy Tester.

Photo: Unsplash

By Boletim Bitcoin newsroom

. 6 min reading.

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 in OnInit (like iMA) and read with CopyBuffer. orders are sent with the class CTrade. 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:

FunctionWhen it's calledTypical use
OnInit()When the EA is attached to the chartCreate indicator handles, validate parameters
OnTick()With each new quotation of the assetRead indicators, decide, send orders
OnDeinit()When the EA is removedRelease 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 account

How to create the EA file in MetaEditor?

  1. Open MetaEditorIn MetaTrader 5, press F4 or click the editor icon.
  2. New fileChoose "Expert Advisor", give a name and proceed until you finish.
  3. Paste the codeReplace the model with the code for this article.
  4. CompilePress F7. The error tab should show 0 errors.
  5. 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.
  • input Creates editable parameters in the EA window and the optimizer.
  • iMA return one handle (identifier) of the indicator, not the value. In case of error, returns INVALID_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 iTime with lastBar Makes 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.

Price chart with a simple moving average and an overlapping exponential moving average 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.

Warning: Stop and target in points depend on the asset. 300 points in EUR/USD of 5 houses is 30 pips; In Gold (XAUUSD) can be only US$ 3. Adjust the instrument and check out the minimum batch, lot step and stop levels required by the broker.

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:

ModePrecisionWhen to use
Every tick based on real ticksHighest (real broker's real ticks)FINAL VALIDATION
Every tickHigh (simulated ticks)When there are no real ticks
1 minute OHLCAverageQuick tests
Open prices onlyLowEA screening that decides only at the opening of the candlestick
Math calculationsNo market dataInternal calculations and research

Three adjustments make the test more honest:

  1. Execution Delay: The execution field allows you to simulate random or fixed delay, including based on the actual ping to the server.
  2. 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.
  3. 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

  1. MQL5 Reference: OnTick
  2. MQL5 Reference: iMA
  3. MQL5 Reference: CopyBuffer
  4. MQL5 Reference: CTrade
  5. MetaTrader 5: Strategy Test
  6. MetaTrader 5: Types of Optimization
  7. MetaTrader 5: MQL5 Assistant
  8. Wikipedia: MetaQuotes Software
  • MQL5
  • Expert Advisor
  • MetaTrader 5
  • robot trader
  • CTrade
  • Strategy Tester
  • forex

This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.

Read also

Start in crypto today

Open your free account, deposit with PIX and access Spot, Futures, Copy Trading and Trading Robots in one app.

  • Easy deposits
  • Copy trading
  • Grid and DCA bots
  • All-in-one app
Advertising. Crypto involves risk, invest responsibly.
Create free account