FX NOOKAI CODE LAB
Loading

MT5 EA Builder: Turn a Strategy into a Tested EA

By FXNook Lab team

Notebook of trading-rule sketches beside a laptop at a quiet trading desk

An MT5 EA builder turns explicit trading rules into an MQL5 Expert Advisor, but the quality of the result depends on how clearly those rules are stated and how carefully you test the EA. Write down entries, exits, position sizing, and trade limits first; then review the generated specification and code before running the EA in MetaTrader’s Strategy Tester.

Some builders generate code from a plain-language strategy description and ask follow-up questions when details are missing. Others let you assemble conditions in a visual, rule-based interface. Either way, the builder needs precise instructions: “buy when the fast average crosses above the slow average” still leaves open which bars count, what happens to an existing position, and how the EA exits.

What an MT5 EA builder does

An Expert Advisor runs trading logic inside MetaTrader 5. It can read price data and indicator values, evaluate conditions on ticks or bars, and send or manage trade requests. An MT5 EA is written in MQL5 and uses MT5-specific trade and position functions; it is not simply an MT4 EA with a different file extension.

A code-generating builder translates a description or confirmed specification into an MQL5 program. A visual builder asks you to select conditions and actions from menus or blocks, then produces code or a runnable EA from those choices. The visual approach can make simple rule combinations easier to lay out, while a description-based builder can be more convenient for a strategy that needs custom behavior. Both need the same thing from you: rules that leave as little room for interpretation as possible.

For example, the instruction “enter on a moving-average cross” does not say whether the crossover must be confirmed at candle close, whether the EA can open more than one position, or whether it closes on an opposite cross. A builder cannot safely infer your intended behavior from those missing details. It should ask for clarification rather than silently choose a rule.

Write down the strategy rules before building

Prepare a short strategy brief before entering anything into a builder. Include the conditions that cause an order, the rules that manage an open position, and the limits on when the EA is allowed to trade. If a rule has a number, give the number and its unit; “small stop” is not a usable setting.

Ambiguous rules produce ambiguous EA behavior. For instance, “risk one percent” is incomplete if the brief does not state whether the calculation uses balance or equity, how the stop distance is measured, and what to do when the resulting volume is below the broker’s minimum lot size. Make the builder surface those choices before code is generated.

Worked example: make a moving-average brief exact

Start with this brief: “Buy when the fast moving average crosses above the slow one, sell when it crosses below, and use a stop and target.” It names a signal but leaves out nearly every setting needed to implement it. A clearer version might say:

On the chart symbol and timeframe, use a 10-period EMA and a 30-period EMA, both applied to closing prices. Evaluate signals once at the start of a new bar, using only completed bars. A buy signal occurs when the fast EMA was at or below the slow EMA two bars back and is above it on the most recently completed bar. A sell signal uses the inverse comparison. Use fixed lot size 0.10, a 500-point stop loss, and a 1,000-point take profit. Allow no more than one position on the symbol. If a position is open, close it on an opposite crossover and do not open a reverse position on that same bar. Do not add to an existing position.

These figures are example inputs, not a recommendation or a claim about performance. The useful part is the precision: “completed bars” rules out signals that appear and disappear while the current candle is forming, and the position rule defines what the EA does when a new signal arrives during an open trade.

Here is a compact MQL5 example of that crossover logic. It assumes a netting account and that this EA is the only program or trader managing the symbol. It uses fixed lots and point-based stops; a production EA should also validate volume and stop distances against the broker’s symbol settings.

#include <Trade/Trade.mqh>

input int FastPeriod = 10;
input int SlowPeriod = 30;
input double Lots = 0.10;
input int StopLossPoints = 500;
input int TakeProfitPoints = 1000;
input ulong MagicNumber = 26001;

CTrade trade;
int fastHandle = INVALID_HANDLE;
int slowHandle = INVALID_HANDLE;
datetime lastBar = 0;

int OnInit()
{
   if(FastPeriod <= 0 || SlowPeriod <= FastPeriod || Lots <= 0.0 ||
      StopLossPoints <= 0 || TakeProfitPoints <= 0)
      return INIT_PARAMETERS_INCORRECT;

   fastHandle = iMA(_Symbol, _Period, FastPeriod, 0, MODE_EMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, _Period, SlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
   if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
      return INIT_FAILED;

   trade.SetExpertMagicNumber(MagicNumber);
   trade.SetTypeFillingBySymbol(_Symbol);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   if(fastHandle != INVALID_HANDLE) IndicatorRelease(fastHandle);
   if(slowHandle != INVALID_HANDLE) IndicatorRelease(slowHandle);
}

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

   double fast1[1], fast2[1], slow1[1], slow2[1];
   if(CopyBuffer(fastHandle, 0, 1, 1, fast1) != 1 ||
      CopyBuffer(fastHandle, 0, 2, 1, fast2) != 1 ||
      CopyBuffer(slowHandle, 0, 1, 1, slow1) != 1 ||
      CopyBuffer(slowHandle, 0, 2, 1, slow2) != 1)
      return;

   lastBar = barTime;
   bool crossUp = fast2[0] <= slow2[0] && fast1[0] > slow1[0];
   bool crossDown = fast2[0] >= slow2[0] && fast1[0] < slow1[0];

   if(PositionSelect(_Symbol))
   {
      long type = PositionGetInteger(POSITION_TYPE);
      if((type == POSITION_TYPE_BUY && crossDown) ||
         (type == POSITION_TYPE_SELL && crossUp))
      {
         if(!trade.PositionClose(_Symbol))
            Print("Close failed: ", trade.ResultRetcode(), " ",
                  trade.ResultRetcodeDescription());
      }
      return;
   }

   double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(crossUp)
   {
      double sl = NormalizeDouble(ask - StopLossPoints * point, digits);
      double tp = NormalizeDouble(ask + TakeProfitPoints * point, digits);
      if(!trade.Buy(Lots, _Symbol, 0.0, sl, tp, "EMA cross buy"))
         Print("Buy failed: ", trade.ResultRetcode(), " ",
               trade.ResultRetcodeDescription());
   }
   else if(crossDown)
   {
      double sl = NormalizeDouble(bid + StopLossPoints * point, digits);
      double tp = NormalizeDouble(bid - TakeProfitPoints * point, digits);
      if(!trade.Sell(Lots, _Symbol, 0.0, sl, tp, "EMA cross sell"))
         Print("Sell failed: ", trade.ResultRetcode(), " ",
               trade.ResultRetcodeDescription());
   }
}

The two iMA calls create indicator handles; CopyBuffer reads the values for bars 1 and 2, which are completed bars. PositionSelect checks for a position on the current symbol, while CTrade sends and closes trades. In a hedging account, positions are separate tickets, so position selection and closing should be designed around the intended ticket and magic-number rules rather than assuming one position per symbol.

This example does not validate lot size against SYMBOL_VOLUME_MIN, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_STEP, nor does it check the broker’s minimum stop distance before sending an order. Those constraints can cause a request to be rejected. Also inspect ResultRetcode() after trade calls: a successful method call alone is not proof that the server accepted and executed the request.

Build the MT5 EA and clarify missing details

Once the brief is ready, use a builder that supports MT5 and specify that you want an MQL5 Expert Advisor, not an indicator or an MT4 program. Include the strategy rules, intended inputs, symbol and timeframe behavior, and account assumptions. If the builder asks follow-up questions, answer them as design decisions rather than relying on defaults you have not reviewed.

  1. Submit the strategy. Describe the rules in ordinary language or enter them through a step-by-step strategy interface. Include both the signal and the actions the EA should take.
  2. Resolve gaps. Answer questions about closed-bar signals, position limits, stop placement, lot sizing, trading hours, and other details that affect behavior.
  3. Review the specification. Read the proposed rules, inputs, and risk settings before building. Make sure they match the brief, especially when an opposite signal or an already-open position is involved.
  4. Build and inspect the output. Confirm that the result is an MT5 EA, then read the summary of its behavior and check the generated inputs before downloading or testing it.

The FXNook AI EA builder follows this describe, clarify, review, and build workflow for MT4 or MT5 programs. It asks for missing details and shows the strategy for review before building; the Lab also compiles and checks the generated program. You still need to test the EA against your stated rules in MetaTrader, because a builder’s checks are not a substitute for checking how it behaves in your account conditions.

A builder is often a better fit than adapting an existing EA when the new strategy has different entry and exit rules, or when the existing source is unavailable or difficult to understand. Adapting a known EA can be more direct when it already has the right trade-management structure and you need a limited change, such as a filter or an extra exit rule. For a port from MT4, remember that MT5 uses positions and indicator handles differently; a straight copy of MT4 order logic is not an MT5 conversion.

Check the MQL5 code and compile result

Open the source in MetaEditor and make sure it is an MQL5 Expert Advisor with the expected file type and event functions. Review the inputs in the header, the indicator setup, the entry and exit branches, position handling, and any stop or volume calculations. Confirm that there are no unrelated functions or settings that were not part of the approved specification.

Compile with MetaEditor’s Compile command and read the errors and warnings in the Toolbox. Resolve all compiler errors before testing; an error such as an unknown function or a type mismatch can mean that MT4 code or an incompatible call was used in an MT5 file. If an EA uses indicator handles, confirm that it creates them during initialization, reads values with CopyBuffer, and releases the handles when it is removed.

Compilation proves that MetaEditor can build the source. It does not prove that the EA follows the strategy, sends valid orders under your broker’s conditions, or manages every position correctly. For trade logic, inspect whether the code uses the intended symbol, timeframe, magic number, signal bar, and position model; then move to the Strategy Tester.

Test the EA in Strategy Tester

Use MT5 Strategy Tester to compare actual EA actions with the written rules. A run is most useful when its symbol, timeframe, dates, and modeling mode match the question you are trying to answer. Do not treat a single run or an attractive result as proof that the strategy will behave the same way in future market conditions; past or tested results do not guarantee future results.

  1. Select the EA and market. In Strategy Tester, choose the compiled Expert Advisor, the intended symbol, and the timeframe specified in the brief. Set the account and deposit assumptions you want the test to use.
  2. Set the test period and modeling options. Choose dates that cover relevant market conditions and select an available tick or price model appropriate to the EA’s logic. If the EA depends on intrabar movement, a model based only on bar openings may not answer the question you need to test.
  3. Set EA inputs. Enter the same periods, lot size, stop, target, and other inputs you reviewed in the specification. Make sure you are not testing a different setup by leaving stale values from another run.
  4. Run a visual pass. Watch several entries and exits on the chart. For a closed-bar crossover, verify that the EA acts on the completed-bar condition, not on a temporary crossing inside an unfinished candle.
  5. Compare actions with rules. Review each entry, stop, target, and close. Include cases where a position is already open, the opposite signal arrives, or the EA is outside its permitted trading hours.
  6. Read the Journal and results. Look for rejected requests and runtime messages. Errors such as TRADE_RETCODE_INVALID_VOLUME point to a volume that does not meet symbol rules; TRADE_RETCODE_INVALID_STOPS indicates stop prices that violate trading constraints. A permissions error can also occur if trading is not allowed for the program or account.
  7. Repeat under relevant conditions. Test other periods and any symbols or timeframes the EA is meant to support. If the rules are intended for more than one broker or account type, test the relevant constraints instead of assuming they are identical.

When a result differs from the brief, identify whether the cause is the specification, the implementation, or the test setup. For example, an EA that checks a signal on every tick can make a different entry decision from one that acts only once after a candle closes. Fix the rule or code at its source, compile again, and rerun the affected tests.

Common MT5 EA builder mistakes

ProblemWhy it causes troubleCorrection
Vague entry rule“Trade when momentum is strong” does not define an indicator, threshold, or evaluation bar.Name the signal, its settings, the comparison, and whether the signal uses a closed bar.
Missing exit behaviorThe EA may hold a position until a stop or target that was never defined, or handle an opposite signal unexpectedly.Specify every exit and say whether an opposite signal closes, reverses, or is ignored.
Unclear lot sizingA fixed lot, percentage risk, and balance-based calculation produce different order volumes.State the sizing method and rounding or minimum-volume behavior.
Duplicate entriesRepeated ticks can satisfy a condition multiple times, or the EA may not know whether another position is already open.Define signal frequency, one-position or multiple-position rules, and ownership by magic number where needed.
Broker constraints not testedVolume steps, minimum stop distances, filling rules, and permissions can prevent orders from being accepted.Use symbol settings and trade-result codes, then test on the intended broker conditions.

Before attaching the EA to a live chart

Move from compilation to live use in stages. First test the EA in Strategy Tester, then run it on a demo account using the intended symbol, timeframe, and inputs. A demo run can expose differences in order handling and permissions that a historical test does not show.

After the demo checks, the practical next step is to test the EA’s exact inputs and broker constraints in MetaTrader’s Strategy Tester, then continue monitoring it in the environment where you intend to use it. If you are starting from a strategy description, you can build an MT5 EA with the FXNook AI EA builder, review its confirmed rules, and download the compiled result for your own testing.

Questions

Can I build an MT5 EA without knowing MQL5?

Yes. An EA builder can turn a clear strategy description or a set of confirmed rules into an MQL5 program, so you do not need to write the code yourself. You should still review the EA’s stated behavior and test its entries, exits, and order handling before using it.

What details do I need to give an MT5 EA builder?

Provide exact entry and exit conditions, symbols and timeframes, position sizing, stop and target rules, and limits on open positions. Also specify whether signals use closed bars, trading hours, and what the EA should do when a signal occurs while a position is already open.

How do I test an EA built for MT5?

Compile the source in MetaEditor, then select the EA, symbol, timeframe, test period, and modeling options in MT5 Strategy Tester. Compare its trades with the written rules, inspect the Journal for rejected requests or runtime errors, and repeat tests for the conditions the EA is intended to handle.

Does compiling an MT5 EA mean it is ready to trade live?

No. A successful compile means MetaEditor accepted the code, not that the EA implements the intended rules or that a broker will accept its orders. Test it in Strategy Tester and on a demo account, and check its inputs, trade results, and broker constraints before considering live deployment.