MQL5 from Scratch: Build an Expert Advisor Step by Step

Technical revision: 1 October 2026 · Educational material

A first Expert Advisor should help you see what the terminal is doing. Start with an observable program, then add one responsibility at a time. This guide takes you from event handlers to a moving-average demonstration whose order submission is disabled by default.

Define the behavior before writing the entry

Our example reads two exponential moving averages on the chart symbol and timeframe. A signal is a crossing between the two most recent closed bars. It makes at most one entry attempt for each new bar and skips entries when any position or pending order already exists on that symbol. Exits use the initial stop and target; it does not close or reverse a position on an opposite signal.

Those are implementation choices for a learning example. They do not establish a profitable strategy. A separate validation process is needed to assess any trading hypothesis.

Create a small project in MetaEditor

  1. Open MT5, choose File → Open Data Folder and locate MQL5/Experts.
  2. Create an FTS-Learning folder. Put FtsLifecycleDemo.mq5, FtsClosedBarMAEA.mq5 and FtsRisk.mqh there.
  3. Open the logger in MetaEditor, press F7 and resolve every compiler error before attaching it to a demo chart.
  4. Inspect the Experts and Journal tabs. Wait for a new bar; the logger deliberately ignores a signal already present when attached.

Separate initialization, observation and execution

OnInit validates inputs and creates indicator handles. OnTick checks for a new bar, reads data and then evaluates the rule. OnDeinit releases the handles. A price close comes from a rates series such as CopyRates; there is no SYMBOL_CLOSE symbol property.

#property strict
#property version "1.00"
// Non-trading EA: logs a completed bar and its EMA.
input int InpPeriod=20;
int ma_handle=INVALID_HANDLE;
datetime last_bar=0;
int OnInit()
{
   if(InpPeriod<2) return INIT_PARAMETERS_INCORRECT;
   ma_handle=iMA(_Symbol,_Period,InpPeriod,0,MODE_EMA,PRICE_CLOSE);
   if(ma_handle==INVALID_HANDLE) return INIT_FAILED;
   last_bar=iTime(_Symbol,_Period,0);
   return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
   if(ma_handle!=INVALID_HANDLE) IndicatorRelease(ma_handle);
   Print("Lifecycle demo stopped. Reason=",reason);
}
void OnTick()
{
   datetime current=iTime(_Symbol,_Period,0);
   if(current<=0 || current==last_bar) return;
   if(BarsCalculated(ma_handle)<InpPeriod+2) return;
   double ma[1];
   MqlRates closed[1];
   if(CopyBuffer(ma_handle,0,1,1,ma)!=1 ||
      CopyRates(_Symbol,_Period,1,1,closed)!=1) return;
   if(!MathIsValidNumber(ma[0]) || ma[0]==EMPTY_VALUE) return;
   last_bar=current;
   Print("Closed bar ",TimeToString(closed[0].time),
         " close=",DoubleToString(closed[0].close,_Digits),
         " EMA=",DoubleToString(ma[0],_Digits));
}

Add execution only after the log makes sense

The second EA in the download adds two moving averages, symbol specification checks, estimated risk sizing and a synchronous CTrade request. Its InpEnableTrading input is false initially. Even when enabled, the example permits execution only in Strategy Tester or on a demo account.

All distance inputs use points, not pips. Check the broker’s symbol specification rather than assuming a particular decimal format. The example skips an invalid stop distance instead of silently changing the strategy.

Check observable behavior

  • Changing timeframe should release old handles and initialize new ones.
  • Unavailable indicator history must postpone processing instead of consuming the bar.
  • A manual position or pending order must block another entry on the same symbol.
  • A successful method return must be followed by a server return-code check.

Continue with CopyBuffer and closed-bar ordering, then the execution tutorial and the backtesting checklist. The Start Here route keeps the lessons in sequence.

Reference: MQL5 event handlers.

By Forex Real Trader

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like