MT4 EA Builder: Turn Your Strategy into a Working EA
By FXNook Lab team
An MT4 EA builder turns explicit trading rules into an Expert Advisor, but it cannot fill in missing decisions or show that a strategy will be profitable. To get a usable EA, define the entry, exit, position-size and operating rules first, then compile the generated MQL4 and test its behavior in MetaTrader 4's Strategy Tester.
This guide follows a simple moving-average crossover from written rules to an illustrative MQL4 program and a tester checklist. The same process applies whether you use a visual builder, write MQL4 yourself or use an AI-assisted workflow.
What an MT4 EA builder does—and what it cannot decide
An Expert Advisor is a program that runs on a chart and can evaluate conditions, send or manage orders, and respond to market events. An EA builder converts a strategy description or a visual rule setup into MQL4 source code, usually an .mq4 file. MetaEditor compiles that source into an .ex4 file that MT4 can run.
A builder can implement rules such as “buy when the fast moving average crosses above the slow moving average.” It cannot know what you intended by “when the trend is strong,” “use a sensible stop” or “avoid bad hours” unless you define those terms in measurable conditions. Different interpretations produce different trading logic.
Nor does a successful compile establish that the EA behaves as you expect. An EA can compile but never reach its order code, send repeated entries, use an unintended lot size or have orders rejected by the broker. Compiling, testing and reading the logs are separate steps.
Choose a visual builder, MQL4 code or an AI-assisted workflow
The right option depends on how precise your rules are and how much control you want over the source. Before choosing a builder, find out whether it lets you inspect and download the MQL4, and how you will diagnose a problem after the EA is generated.
| Approach | Coding skill | Flexibility and debugging | Practical fit |
|---|---|---|---|
| Visual builder | Usually little or none for basic rules | Quick to configure common indicators and conditions; unusual logic can be difficult to express. Debugging depends on whether the tool exposes generated code and useful logs. | Useful for a strategy made from standard signals, filters and order rules. |
| Custom MQL4 | Requires MQL4 knowledge | Full control over order handling, state and special conditions; you are responsible for testing and maintaining the code. | A good fit when you need a specific behavior, or want to understand every implementation detail. |
| AI-assisted builder | Can reduce the amount of coding needed, but rules still need to be clear | Can turn a confirmed specification into code and help explain or repair it; generated code still needs review and testing. | Useful when you can describe the strategy precisely but do not want to write every MQL4 function by hand. |
For example, a visual builder may handle a moving-average cross and a fixed stop without trouble, but struggle when the rule is “close after three failed attempts to make a new high.” Custom MQL4 gives you room to define that state precisely. An AI-assisted workflow can also help translate the rule, but you should review the specification it proposes before code is produced.
FXNook AI Code Lab supports MT4 and MT5 EAs and indicators. Its AI EA builder takes a description or confirmed specification, asks for missing details, and builds, compiles and checks the program. You can also download the result and test it in MetaTrader's Strategy Tester.
Write a complete strategy specification before building
Decide what the EA should do before choosing how to make it. Record the rules in a checklist that another developer could implement without having to guess at the meaning of a phrase.
- Symbol and timeframe: Which instrument and chart period should the EA use? Should it trade only the chart symbol or a separate symbol?
- Signal conditions: Which indicator values, prices or other conditions create an entry? Specify whether a signal uses the current, still-forming bar or a closed bar.
- Trade direction: Can the EA buy, sell or both? State whether an opposite signal closes an existing trade, opens an opposite trade, or is ignored.
- Position limits: How many open trades are allowed, and do pending orders count? Say whether the limit applies per symbol, per EA or across the account.
- Lot sizing: Use a fixed lot size or define the calculation. If sizing by risk, specify how risk is calculated and what happens when the stop distance changes.
- Stop loss and take profit: Give the units and exact placement rule, such as points from the entry price or a recent swing. Define whether either value can be absent.
- Exit rules: State what closes a trade besides its stop or target, including any time-based or opposite-signal exit.
- Trading hours: Specify the hours, the time zone and what happens to open trades when the permitted session ends.
Example: a closed-bar moving-average crossover
Here is a deliberately simple specification that can be implemented without interpreting subjective terms:
- Run on the chart symbol and chart timeframe.
- Calculate a 10-period and a 30-period exponential moving average using closing prices.
- Buy when the fast average was at or below the slow average on the previous closed bar and is above it on the most recently closed bar.
- Sell when the fast average was at or above the slow average on the previous closed bar and is below it on the most recently closed bar.
- Allow at most one open market order for this symbol and this EA's magic number. Ignore a new signal while that order is open.
- Use a fixed lot size, a stop loss of 300 points and a take profit of 600 points.
- Do not close or reverse a trade just because an opposite crossover appears. The stop loss or take profit closes it.
- Evaluate once when a new chart bar begins, using closed bars for the crossover.
Those choices are examples, not recommended trading settings. In particular, “points” are not the same as pips on every quote format, and a stop or target may be too close for a broker's minimum distance. The builder needs the actual rules you intend to test.
Build the example EA and understand its MQL4 parts
The program needs inputs for its settings, signal checks for the crossover, and order handling for a qualifying signal. In MQL4, iMA returns a moving-average value for the requested shift; shifts 1 and 2 below refer to closed bars. OrderSend submits the market order, while OrdersTotal and OrderSelect let the EA look for an existing trade.
This compact example is an MT4 Expert Advisor that follows the rules above. It uses the chart's symbol and timeframe, fixed lots, and a single open market order for its symbol and magic number.
// MQL4, for MetaTrader 4
#property strict
input int FastPeriod = 10;
input int SlowPeriod = 30;
input double Lots = 0.10;
input int StopLossPoints = 300;
input int TakeProfitPoints = 600;
input int Slippage = 3;
input int MagicNumber = 24001;
datetime lastBarTime = 0;
int OnInit()
{
if(FastPeriod < 1 || SlowPeriod < 2 || FastPeriod >= SlowPeriod ||
Lots <= 0 || StopLossPoints < 0 || TakeProfitPoints < 0)
{
Print("Invalid EA input values.");
return(INIT_PARAMETERS_INCORRECT);
}
return(INIT_SUCCEEDED);
}
bool HasOpenTrade()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
continue;
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber &&
(OrderType() == OP_BUY || OrderType() == OP_SELL))
return(true);
}
return(false);
}
void OnTick()
{
if(Bars < SlowPeriod + 3 || Time[0] == lastBarTime)
return;
lastBarTime = Time[0];
double fastPrevious = iMA(NULL, 0, FastPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
double fastRecent = iMA(NULL, 0, FastPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
double slowPrevious = iMA(NULL, 0, SlowPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
double slowRecent = iMA(NULL, 0, SlowPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
bool buySignal = fastPrevious <= slowPrevious && fastRecent > slowRecent;
bool sellSignal = fastPrevious >= slowPrevious && fastRecent < slowRecent;
if(!buySignal && !sellSignal)
return;
if(HasOpenTrade())
return;
if(!IsTradeAllowed())
{
Print("Trading is not allowed for this EA at this time.");
return;
}
RefreshRates();
int type = buySignal ? OP_BUY : OP_SELL;
double price = buySignal ? Ask : Bid;
double stopLoss = 0;
double takeProfit = 0;
if(StopLossPoints > 0)
stopLoss = buySignal ? price - StopLossPoints * Point : price + StopLossPoints * Point;
if(TakeProfitPoints > 0)
takeProfit = buySignal ? price + TakeProfitPoints * Point : price - TakeProfitPoints * Point;
price = NormalizeDouble(price, Digits);
if(stopLoss > 0) stopLoss = NormalizeDouble(stopLoss, Digits);
if(takeProfit > 0) takeProfit = NormalizeDouble(takeProfit, Digits);
ResetLastError();
int ticket = OrderSend(Symbol(), type, Lots, price, Slippage, stopLoss,
takeProfit, "MA crossover", MagicNumber, 0, clrNONE);
if(ticket < 0)
Print("OrderSend failed. Error: ", GetLastError());
else
Print("Order opened. Ticket: ", ticket);
}The new-bar check prevents the same closed-bar signal from being processed repeatedly on every tick. The open-order check prevents a second trade from being added while the first is still open. This example does not normalize the lot size to broker limits or adjust stops to the broker's minimum stop distance; those checks are needed before using it on a broker account.
Also note what the program does not do: it does not close a position on an opposite crossover, apply a trading-hours filter, calculate lots from account risk or trade multiple symbols. If your specification requires any of those behaviors, they need to be implemented and tested rather than assumed.
Compile the EA in MetaEditor
- Open MetaEditor from MT4, or press
F4in the terminal. - Create an Expert Advisor source file or open the generated
.mq4file. Save it under a clear name in theMQL4/Expertsfolder. - Compile the file with the MetaEditor Compile command or
F7. Read the Errors tab at the bottom and note the file and line number for each message. - Fix the source and compile again until there are no errors. Return to MT4 and refresh the Expert Advisors list in the Navigator if the EA does not appear.
A compile error means MetaEditor cannot build the program. Examples include an undeclared identifier, a wrong parameter count or an unexpected end of program caused by a missing brace. A warning is different: compilation may succeed, but the warning can point to a conversion or other code issue worth understanding.
Runtime trade problems happen after compilation. For example, OrderSend can fail because the lot size is invalid, trading is not permitted, or the stop is too close to market price. The EA should log the returned error with GetLastError(); a compiled file alone cannot tell you whether the broker will accept its orders.
If MetaEditor reports errors in existing code, the FXNook Lab's MQL4/MQL5 error-fixing workflow can compile the uploaded code, identify causes, repair it and compile it again. Keep the original file and compare the changed version so you understand what was altered.
Backtest the EA in MT4 before attaching it to a chart
Use the MT4 Strategy Tester to inspect how the EA responds to historical price data and to catch implementation problems. Backtesting is not proof of future behavior: past or tested results do not guarantee future results.
- Open Strategy Tester from the View menu or press
Ctrl+R. Select the EA by its name. - Choose the same symbol and timeframe that your specification calls for. Confirm that the history available for the selected period is suitable for the test.
- Set a date range that includes enough data to exercise entries and exits. Start with optimization off so you are testing one set of inputs.
- Select a modeling method appropriate to the question. MT4 offers methods such as Every tick, Control points and Open prices only; they do not all represent price movement at the same level of detail. Do not treat a test based on coarse modeling as a precise check of intrabar behavior.
- Set the spread and EA inputs deliberately. Review the lot size, stop and target units, moving-average periods, slippage and magic number before starting.
- Run the test. Use Visual mode when you need to see entries and exits on the chart, then inspect the Results, Graph, Report and Journal tabs.
- Read the Experts and Journal messages for order errors or skipped signals. Compare the trades against the written rules, including whether entries use closed bars and whether the EA respects its one-position limit.
Modeling quality and the available price history affect what the tester can show. A test that opens no trades may indicate a rare signal, insufficient history, an incorrect symbol or timeframe, a rule that is never reached, or an order rejection. The Journal and Experts messages help distinguish these cases.
After the logic behaves as specified in a test, try a demo account to observe the EA in the terminal and check broker-specific behavior. A backtest or demo run cannot establish that a strategy will make money or behave the same way in future market conditions.
Common MT4 EA builder mistakes and how to check the result
| Problem | Common cause | What to do |
|---|---|---|
| Rules are incomplete | Phrases such as “strong trend” or “close at the right time” have no exact condition. | Write measurable conditions, define which bar is used, and decide what happens when entry and exit rules overlap. |
| Lot or stop values are wrong | Points are mistaken for pips, or the requested lot and stop distance do not match broker limits. | Confirm the symbol's digits and point size. Compare the lot size with the broker's minimum, maximum and lot step, and check the minimum stop distance. |
| Repeated entries appear | The signal remains true across ticks or the code does not track existing orders. | Use a new-bar or signal-state check where appropriate, and filter open orders by symbol and the EA's magic number. |
| Broker refuses an order | Trading permission is off, the volume is invalid, or a stop is too close or otherwise rejected. | Read the Experts or Journal log and the error code. Check terminal and EA trading permissions, lot constraints and stop-distance requirements. |
| The EA compiles but does not trade | The signal never occurs, the EA is not allowed to trade, the wrong chart or inputs are selected, or order handling fails. | Verify the signal with the same symbol and timeframe, inspect terminal settings and logs, then use the Strategy Tester to isolate the condition. |
Before a demo run
- The entry, exit, direction and position-limit rules are explicit.
- The EA is saved in the MT4
MQL4/Expertsfolder and compiles without errors. - The selected chart or tester symbol and timeframe match the intended rules.
- Lot size, point-based stops, targets and trading hours are understood.
- The EA's magic number is distinct from other EAs that may trade the same symbol.
- The Strategy Tester logs have been reviewed, including any failed order messages.
- Any generated code has been inspected for duplicate entries and the intended order parameters.
The practical next step is to write your rules in the checklist above, then build and test against that specification rather than relying on a short strategy description. If you want help turning the rules into an MT4 program, see the FXNook AI EA builder; if you already have MQL4 that will not compile, use the MQL error-fixing page.
Questions
Can I build an MT4 EA without knowing MQL4?
Yes. A visual builder or AI-assisted builder can create an EA from rules you provide, so you do not need to write all the MQL4 yourself. You still need to specify the strategy clearly and test the generated EA in MetaTrader 4.
What information should I give an EA builder?
Give it the symbol and timeframe, exact entry and exit conditions, allowed trade directions, position limits, lot-sizing method, stop and target rules, and any trading-hour restrictions. Also state whether signals use a forming bar or a closed bar, and what the EA should do when an opposite signal appears.
How do I test an EA made with an MT4 EA builder?
Compile the EA in MetaEditor, then select it in MT4's Strategy Tester and set the intended symbol, timeframe, date range, model and inputs. Review the trades and the Experts or Journal logs for behavior that differs from your rules or orders rejected by the broker. A historical test does not guarantee future results.
Can an MT4 EA builder create an EA from an indicator?
It can if the indicator's signal is available in a form the EA can read, such as indicator buffers or clearly defined conditions. You need to specify how the EA should interpret each signal and manage orders after it appears; an indicator signal alone does not define position sizing or exits.