MT5 guide

Expert Advisor Coding: A Beginner’s Path in MQL5

Expert advisor coding means writing an MQL5 program that runs inside MetaTrader 5, reads market data and, if you add the code for it, sends orders. The practical path is: set up MetaEditor, learn the three event handlers, compile, test in the Strategy Tester, then forward test on a demo account. The first program here only reads prices.

Trading forex and CFDs involves substantial risk of loss. Automation applies rules; it does not remove trading risk. Read our risk disclosure.

Key takeaways

What expert advisor coding involves

An expert advisor (EA) is an MQL5 program that MetaTrader 5 runs against one chart and symbol. Coding one means writing source code in the MQL5 language, whose syntax the MQL5 documentation describes as similar to C++. The source is compiled into an .ex5 file, and the terminal runs that file when you attach it to a chart.

Coding is not the same as having a working strategy. The program does exactly what you specify, and the market does not have to behave the way your rules assume. Much of the real work is in the rules, the testing and the record keeping. The language is the smallest part of it.

You do not need a programming degree to start. You do need patience with compiler messages and the habit of changing one thing at a time.

The learning path, in order

  1. Install and open MetaEditor. It is the MQL5 development environment that comes with MetaTrader 5, and you open it from the terminal.
  2. Learn the event handlers. Expert advisors are built around OnInit, OnTick and OnDeinit; indicators use OnInit, OnCalculate and OnDeinit instead.
  3. Write a small program that reads data and does not trade. Check that it behaves as you expect on a chart.
  4. Compile with the Compile command (F7 in the default layout) and fix each error before you continue.
  5. Test the program in the Strategy Tester, then run it on a demo account.
  6. Only then add order logic, one feature at a time.

Your first program: reading a moving average

The example below does not place trades. It creates a moving average handle when the program starts, reads the latest value on each tick, and writes the current Bid and the average into the chart comment. Create a new Expert Advisor in MetaEditor, replace the template’s contents with this code, compile it, and attach it to a demo chart to see what it does.

input int InpMAPeriod = 20;   // moving-average period
int maHandle = INVALID_HANDLE;

int OnInit()
  {
   maHandle = iMA(_Symbol, _Period, InpMAPeriod, 0, MODE_SMA, PRICE_CLOSE);
   if(maHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   IndicatorRelease(maHandle);
   Comment("");
  }

void OnTick()
  {
   double ma[];
   if(CopyBuffer(maHandle, 0, 0, 1, ma) != 1)
      return;
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   Comment(StringFormat("Bid %.5f   MA(%d) %.5f", bid, InpMAPeriod, ma[0]));
  }

The code uses iMA, CopyBuffer, SymbolInfoDouble, Comment, StringFormat and IndicatorRelease. Each is documented in the MQL5 Reference, linked under Sources.

The three event handlers

MetaTrader calls these functions for you. Your job is to write what each one does.

OnInit
Runs once when the program is attached or reinitialised. Create indicator handles here, and return INIT_FAILED if something required is missing.
OnTick
Runs on each new price tick for the chart symbol. Keep it light, because it runs often and heavy calculations slow everything down.
OnDeinit
Runs when the program is removed or reinitialised. Release handles here, as the example does with IndicatorRelease.
Four steps in order: write the code in MetaEditor, compile it with F7, test it in the Strategy Tester, then forward test on a demo account. A separate panel gives the role of OnInit, OnTick and OnDeinit.
Concept diagram, not an app screenshot.

Compile, read the errors and test

Compiling turns your source into an .ex5 file. Errors stop the build, and warnings deserve the same attention. Fix the first error listed, because later messages are often caused by it.

Choose the modelling mode before you read any result. The modes and their limits are in the expert advisor tester guide.

In the Strategy Tester, set the expert, symbol, timeframe, date range and deposit, and leave optimisation off for a first run. Then read the report and the graph, and compare the trades with what your code should do on a chart you can see. The help page on strategy testing lists every option. The step-by-step walkthrough is on the expert advisor tester page.

The next step: sending orders safely

Once the readout works, you can add orders. MQL5 includes a standard trade class, CTrade, in the Trade\Trade.mqh include file. Include it at the top of the file and call its methods, such as Buy and Sell, rather than building raw order requests in a first project. The exact method signatures are in the CTrade reference.

Keep order code out of the first version. A program that reads, logs and draws is much easier to debug.

Limits, licensing and what coding cannot do

Code does not make a strategy work. It gives you control over what the program does, not over what the market does next. An EA can lose money exactly as its rules say it should.

Testing is evidence about the past. A strategy test uses historical data, your chosen settings and the modelling assumptions of the tester, so it cannot show how the same rules will behave on a live account. Read how to verify a trading bot to see what the evidence can and cannot show, and keep a trading journal of your demo results.

Only use code you wrote, bought or licensed. Do not use copied or “free” versions of paid products. Check your broker’s terms before running any EA, because some accounts restrict automated trading.

For context on YO4X: it is a Windows desktop workspace for supported MetaTrader 5 strategies, bot configuration and trading journals, and it runs on 64-bit Windows 10 and Windows 11. It does not execute EX5 files or arbitrary uploaded code, and its current desktop workflow is gated to supported MT5 demo accounts. Live-money trading is not released. See YO4X for Windows.

Frequently asked questions

Do I need to know C++ before I start expert advisor coding?

MQL5 syntax is similar to C++, so C++ experience helps with braces, types and functions. It is not required. Start with the event handlers and the MQL5 Reference, and write small programs you can check on a chart.

Why does my EA compile but do nothing on the chart?

Compiling only checks the code; it does not make the program trade. Check that the program is attached, that the Algo Trading button on the toolbar is on (AutoTrading in some versions), and that your conditions ever become true. The Experts tab shows messages your code prints.

Is MetaEditor a separate program from MetaTrader 5?

MetaEditor opens from the MT5 terminal and is installed with it, but it is a separate editor window. Use it to write, compile and debug MQL5. Menu names and shortcuts can differ slightly between builds, so check your own installation.

Does a successful backtest mean my EA will be profitable?

No. A backtest shows how the rules behaved on historical data with the settings you chose. It does not predict live results, and it can be flattered by narrow date ranges and optimisation. Forward test on a demo account before drawing any conclusion.

Can I use code I found online in my EA?

Only if its licence allows your use and you know who owns it. Do not copy code from paid products or present someone else’s work as your own. Read the licence terms first. This is general information, not legal advice.

Keep reading

Sources: MQL5 Reference – How to use algorithmic/automated trading language for MetaTrader 5 · Event Handling Functions - Functions - Language Basics - MQL5 Reference · CTrade - Trade Classes - Standard Library - MQL5 Reference · Strategy Testing - Algorithmic Trading, Trading Robots - MetaTrader 5 Help

Trading forex and CFDs involves substantial risk of loss. Past performance and backtests do not guarantee future results. Read our risk disclosure before you trade.