FX NOOKAI CODE LAB
Loading

MQL5 Algo Trading: Build, Test, and Run an EA

By FXNook Lab team

MQL5 algo trading in MetaTrader 5 means using an Expert Advisor (EA) to evaluate programmed rules and, when trading is permitted, send trade requests. To run one, create and compile the EA in MetaEditor, test it in Strategy Tester, then attach it to a chart with the required permissions enabled. Turning on algorithmic trading only allows EAs to operate; it does not create a strategy or make an EA place trades.

What MQL5 algo trading means in MT5

An EA is a program attached to a chart that can respond to platform events, inspect market data, evaluate its rules and submit trade requests. Those rules might use indicator values, price levels, time filters or other conditions. Whether the EA sends an order depends on its code, the current market data and the trading permissions available to it.

A custom indicator has a different job. It calculates values and displays information on a chart, often using lines, arrows or a separate indicator window. An indicator does not normally manage trades by itself. An EA can use indicator data, but it must include its own decision and order-handling logic if it is meant to trade.

In MQL5, many built-in indicators such as iMA return a handle. The EA then reads calculated values with CopyBuffer. This differs from the simpler value-returning indicator calls commonly found in MQL4, and it matters when adapting older code. For more background, see MQL5: How to Use It to Build and Run MetaTrader Code.

The basic EA cycle: OnInit, OnTick and trade requests

MetaTrader calls an EA's event functions as the program runs. OnInit runs when the EA starts, so it is where code commonly prepares indicator handles and validates inputs. OnTick runs when a new price tick arrives for the chart symbol. An EA can also use other event handlers, but these two explain the basic lifecycle.

  1. Initialize: MetaTrader loads the EA and calls OnInit. The EA prepares the resources it needs and reports whether initialization succeeded.
  2. Read updates: On each relevant tick, OnTick reads current data. The EA may wait for a new bar or use tick-by-tick conditions.
  3. Evaluate rules: The EA checks whether its entry, exit and risk rules are satisfied. If not, it waits; doing nothing is normal when conditions are not met.
  4. Handle a request: If a rule calls for a trade, the EA submits a request, then inspects the result and handles any error or rejection.

For trade operations in MQL5, developers often use the standard CTrade class from Trade/Trade.mqh. A successful call to a method such as Buy does not, by itself, prove that a trade was executed. Inspect ResultRetcode() and ResultRetcodeDescription(), and use the Experts or Journal log to understand the server response.

The example below is a compilable EA that shows initialization and tick handling. It prints once when a new chart bar appears, but it deliberately sends no orders. That makes it suitable for learning the event flow without placing trades; add a defined, tested entry rule and order handling before expecting it to trade.

Create and compile a minimal MQL5 Expert Advisor

  1. In MT5, open MetaEditor from the toolbar or press F4.
  2. Choose File > New, select Expert Advisor (template), and follow the wizard. Give the EA a clear name.
  3. Locate the generated event functions. Replace the template content with the example, or adapt the functions while keeping their signatures unchanged.
  4. Compile with F7. Read the Errors and Toolbox panels. Correct compiler errors, then compile again and confirm that MetaEditor reports no errors.

MQL5 example: a new-bar event EA with no trading logic

#property version   "1.00"
#property description "Prints once when a new chart bar begins; sends no orders."

datetime last_bar_time = 0;

int OnInit()
  {
   Print("EA initialized on ", _Symbol, " ", EnumToString(_Period));
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {
   datetime bar_time = iTime(_Symbol, _Period, 0);
   if(bar_time == 0 || bar_time == last_bar_time)
      return;

   last_bar_time = bar_time;
   Print("New bar: ", TimeToString(bar_time));
  }

void OnDeinit(const int reason)
  {
   Print("EA removed. Reason: ", reason);
  }

This example uses iTime to read the opening time of the current chart bar. It prints once when that time changes, rather than on every tick. The initial tick after attachment also counts as the first observed bar, which is useful to know when reading the log.

A clean compile means MetaEditor accepted the code's syntax and types. It does not prove that a trading rule is reachable, that an order will meet broker requirements, or that the EA behaves as intended under live prices. When an EA includes indicators, verify handle creation and data copying too; an invalid handle or unavailable buffer values can prevent a signal from being evaluated.

Test the EA in Strategy Tester before using a live account

Strategy Tester runs an EA against historical or generated price data under selected test settings. It is the place to check whether the program initializes, whether its rules are reached and what orders or log messages appear. A test can help expose coding and configuration problems, but it cannot guarantee future behavior or results.

  1. Open Strategy Tester in MT5 with Ctrl+R. Select the EA in the Expert list.
  2. Choose the symbol and timeframe that match the EA's intended use. Set a date range for which the terminal has sufficient history.
  3. Select a modeling mode appropriate to the logic. Tick-sensitive rules need a tick-based test; a simpler mode may be enough for rules that only evaluate completed bars.
  4. Set the EA's inputs and review the deposit and account settings available in the tester. For an EA that sends trades, use a test configuration that does not put real funds at risk.
  5. Start the test, then inspect its Journal and trade results. Look for initialization messages, order requests, rejections, and whether the expected conditions were reached.

Test assumptions affect what the results mean. Spread, available history, price modeling and the timing of signal evaluation can all change what the EA sees. If a rule reads the current unfinished candle, its value can change before the bar closes; if the intended rule is based on a completed candle, the code and test should use that bar consistently.

For the example above, the useful result is a new-bar message in the tester log, not a trade list. If it does not appear, investigate whether the EA initialized and whether the test is producing price updates for the selected symbol and period. For a complete setup walkthrough, see How to Use an EA in MT5: Setup, Test, and Run.

Attach the EA and enable algorithmic trading

Once the EA is compiled and tested, the chart setup has several separate permission points. An EA can be visible on a chart while trading remains disabled. The platform, the EA's own properties and the trading account or broker can each affect whether an order is allowed.

  1. Return to MT5 and open the intended symbol and timeframe chart.
  2. Find the EA in the Navigator. Drag it onto the chart or open its properties from the Navigator.
  3. Review the Inputs tab. Confirm values such as timeframe, volume and filters match the intended test setup.
  4. In the EA properties' Common tab, allow algorithmic trading for that EA.
  5. Enable the platform's Algo Trading control. Also review Tools > Options > Expert Advisors and ensure algorithmic trading is allowed there.
  6. Look at the chart's EA status indicator and the Experts log. Read the initialization message or error before assuming the EA is ready.

These settings do not override an account restriction. A broker can restrict automated trading, a symbol can be unavailable for trading, and the account may not permit the requested operation. MQL5 code can inspect permissions such as TERMINAL_TRADE_ALLOWED, MQL_TRADE_ALLOWED and ACCOUNT_TRADE_ALLOWED, but a permitted request can still be rejected for other reasons.

If the EA is attached but sends no trades

Start with the Experts and Journal tabs, then match the message to the EA's logic. A lack of trades may be expected if a signal has not occurred; an order rejection usually points to a request or account constraint. Common causes and practical checks are shown below.

Possible causeWhat to inspectUseful next step
Entry conditions are not metInputs, indicator values, timeframe, bar index and any spread or session filters.Trace each condition and log its value. Check whether the signal is evaluated on the current bar or a completed bar.
Trading permission is disabledThe MT5 Algo Trading control, Tools > Options > Expert Advisors, the EA's Common tab and account permission.Enable the relevant setting and review the log for a trading-disabled message. A platform setting cannot override broker restrictions.
Volume or stops are invalidSymbol volume minimum, maximum and step, plus stop distance and price precision.Read symbol properties and normalize the request to the broker's allowed limits. Do not assume every symbol uses the same lot step or stop rules.
Symbol or session is restrictedWhether the symbol is selected and tradeable, the market session and any EA time filter using server time.Compare the EA's time basis with the broker's server time, and inspect symbol trading properties and account conditions.
The broker rejects the requestThe request result and its retcode, along with the Experts and Journal messages.For CTrade, log ResultRetcode() and ResultRetcodeDescription(). Fix the specific request issue rather than treating a method call as proof of execution.

For example, an EA may reject every signal because its spread limit is expressed in points but was chosen for a different quote format. Another EA may calculate a lot size below the symbol's minimum or use a stop closer than the broker permits. On MT5, an unsupported filling mode can also cause rejection; the accepted mode depends on the symbol and broker.

Logs help distinguish these cases. The Experts tab records EA messages, while the Journal tab records broader platform and trading activity. When the program gives no useful detail, add focused logging around the entry decision and order result, or inspect the full decision path. See MT5 EA Not Taking Trades: Checks, Causes, and Fixes for a longer troubleshooting sequence.

Live-running checklist and monitoring

Monitor a new EA before relying on it to handle orders. A running EA can still miss its conditions, encounter a rejected request or behave differently when live spreads and account settings differ from the test. Past or tested results do not guarantee future results.

If you want help checking the code itself, the FXNook Lab's EA debugger describes why an EA may not trade and can make a fix as a new version. For a new EA, the AI EA builder turns a confirmed specification into an MT4 or MT5 program that is compiled and checked. The practical next step is to run the EA in Strategy Tester, read the logs, and only then attach it with the correct permissions on the intended chart.

Questions

How do I enable algo trading in MT5?

Turn on the Algo Trading control in MT5, allow algorithmic trading under Tools > Options > Expert Advisors, and enable it in the EA's Common properties. The account and broker must also permit automated trading, so check the Experts and Journal tabs if the EA still cannot send requests.

What is the difference between an MQL5 Expert Advisor and an indicator?

An Expert Advisor evaluates rules in response to platform events and can send trade requests when its code and permissions allow. An indicator calculates or displays information, such as lines or arrows, but does not normally manage trades by itself.

Why is my MT5 EA not opening trades?

The EA may be waiting because its entry conditions are false, or a permission, symbol session, volume, stop-distance or broker request constraint may be blocking an order. Read the Experts and Journal messages, and log the values of each entry condition and the order retcode to identify which case applies.