A moving average crossover EA is an Expert Advisor that opens and manages trades automatically when a fast moving average crosses a slower one. The idea is among the oldest in technical analysis, yet turning it into a dependable automated system takes more than two lines on a chart: settings, filters, risk controls and honest testing all shape the result.
This guide explains how these robots work, which settings traders commonly test, why crossovers misfire in sideways markets, and how the two MetaTrader versions differ. It then walks through a real USD/JPY build by Algo Trading Space mentor Sam Jackson, from generation through stress testing to demo incubation.
What Is a Moving Average Crossover EA?
It is a rule-based trading robot that runs in MetaTrader, watches two moving averages and acts when they cross. When the faster line moves above the slower one, the EA treats it as a buy signal; when it drops beneath, it treats it as a sell signal or an exit.
Traders search for the same tool under several names, including MA crossover EA and moving average crossover expert advisor, and the appeal is identical in each case: objectivity. Every signal is defined in advance, so the robot executes the same logic at 3 a.m. as it does mid-session, without hesitation or second-guessing. Fidelity describes the crossover method as buying or selling when a shorter average moves across a longer one, and notes that shorter averages are often called “fast” because they change direction more quickly (Fidelity Viewpoints, June 2026).

If Expert Advisors are new to you, our explainer on what an EA in forex can and cannot do is a useful primer before you automate anything.
How a Crossover Robot Makes Decisions
The robot recalculates both lines as new price data arrives, checks whether they have crossed, and then places, manages or closes orders according to its programmed rules.
| Component | What it does |
| Fast MA | Shorter period; reacts quickly to recent price changes |
| Slow MA | Longer period; smooths noise and tracks the broader trend |
| Long entry | Fast line climbs above the slow one |
| Short entry or exit | Fast line falls through the slow one |
| Strategy type | Trend following |
| Execution | Automated on every new tick or bar |
| Risk controls | Protective orders and position sizing |
| Platform | MT4 or MT5, depending on how it was compiled |
| Main weakness | Repeated false crosses in sideways conditions |
EAs that trade crossovers differ most in how they get out. Some stay in the market permanently, reversing direction at each cross. Others enter on a crossover but exit through a stop, target, trailing stop or separate indicator. That design choice changes the risk profile far more than the choice of averages.
How the Crossover Is Detected in Code
The classic simple moving average (MA) crossover is the easiest version to automate. Whether coded in MQL4 or MQL5, the core check compares the two averages on the last two completed bars. A bullish cross exists when the fast reading sat below the slow moving average two bars ago and above it on the most recent closed bar; a bearish cross is the mirror image.
Coding it this way, rather than comparing live values on the forming candle, stops the EA from firing repeatedly as price flickers back and forth across the line. It also makes backtests and real-time trading behave identically, because both evaluate the same finished data.
Should the EA Trade on the Current or Closed Candle?
Most well-built implementations confirm the crossover on a completed bar and enter at the open of the next one. A cross that appears while a candle is still forming can disappear before it closes, producing a signal that never really existed.
Confirming on closed bars costs a little entry speed but removes those phantom trades. MetaQuotes notes that its “Open prices only” testing mode uses only each bar’s opening price (MetaQuotes testing documentation), which suits EAs that act only at a new bar but will misrepresent one that trades intrabar.
Common Fast and Slow MA Settings
There is no universally best combination; the right pair depends on the market, timeframe and volatility you trade. The table below shows typical pairings traders test, from reactive to slow.
| Fast MA | Slow MA | Character |
| 9 EMA | 21 EMA | Very responsive, more signals and more noise |
| 10 | 20 | Short swings |
| 20 | 50 | Intermediate trend |
| 50 | 200 | Long-horizon trend |
The 50/200 pairing is the only one with a widely recognised name: Nasdaq’s glossary defines a golden cross as the 50-day average crossing above the 200-day (Nasdaq glossary). A 9/21 EMA crossover reacts within a few bars of a turn, whereas a 50/200 setup may lag by weeks on a daily chart. Shorter pairs trade more often, and every moving average cross pays the spread plus any commission, while longer pairs catch fewer, larger moves but give back more before exiting. Treat any combination as a hypothesis to test on your own data, not a setting to copy.
A customizable moving average EA exposes each period and the average type as an input, so you can test combinations without touching the code. Be wary of optimising periods too finely. If a 17/43 pair looks far better than 15/45 or 20/50 in a backtest, the difference is more likely noise than insight; a sound setting should perform reasonably across a neighbourhood of nearby values, not only at one precise combination.
SMA vs EMA: Which Average Should the EA Use?
An exponential moving average reacts faster than a simple one because it weights recent prices more heavily. MetaQuotes lists four types in MetaTrader, Simple, Exponential, Smoothed and Weighted, and explains that the first gives every price in the period equal weight while Exponential and Linear Weighted versions favour the latest data (MetaQuotes indicator reference).
In practice:
- SMA/SMA: signals later but whipsaws less often.
- EMA/EMA: an EMA cross turns sooner, capturing more of a new trend at the cost of extra false alarms.
- Mixed types: possible if the EA allows separate settings for each line.
Faster is not automatically better. An EMA pair may join a trend earlier and also jump into every fake-out sooner, so the only way to choose is to test both on the same data.
Why Crossover EAs Produce False Signals
Crossovers work best in sustained trends and struggle when price moves sideways. In a range, the two lines weave around each other, triggering a string of small losing trades known as whipsaws; this is the single biggest weakness of the approach.
Traders often test filters designed to skip low-quality crossover signals:
- Higher-timeframe trend filter: only take longs when a slower chart is also trending up.
- Trend strength: require an ADX reading above a chosen threshold.
- Momentum: use RSI or Stochastic to avoid entries at stretched levels.
- Volatility: use ATR to skip very quiet periods or size stops dynamically.
- Price position: require a close on the far side of the slow average, not merely past the quicker one.
- Session: trade only during the hours when the instrument usually trends.
Filters are not free. Each adds a parameter that can be fitted to history, so a filter should earn its place in the trading system by improving out-of-sample results, not just the backtest.
When do crossovers shine? During long directional phases, such as a central bank cycle pushing a currency steadily in one direction. The losses from whipsaws are the price paid for being positioned when those phases arrive, which is why a crossover system’s results tend to come in bursts rather than smoothly.
Risk Management Settings to Configure
Risk controls decide how much the robot can lose when its signals are wrong, which they frequently are in choppy markets. The settings worth defining before any real-money test are:
- Position sizing: fixed lots are simple; a set percentage of equity per trade scales risk with the account.
- Stop loss: a constant distance or one based on volatility, such as a multiple of ATR.
- Take profit: static, or omitted in favour of a moving exit that lets trends run.
- Trailing stop and break-even: lock in gains once a trade moves far enough in your favour.
- Maximum spread: skip entries when costs spike, for example around news or thin liquidity.
- Open-position cap and daily loss limit: contain exposure if the EA fires repeatedly.
Leverage limits also matter. Retail clients of EU-regulated brokers are capped at 30:1 on majors such as USD/JPY (CNMV summary of ESMA measures, June 2018), and higher gearing elsewhere magnifies a losing streak just as quickly as a winning one. Test these risk settings in the backtest itself rather than bolting them on later, because a stop or spread filter can change which trades exist and therefore the whole result.
MT4 vs MT5 Versions of the EA
An MT4 EA and an MT5 EA are separate programs. MT4 robots are written in MQL4 and run as .ex4 files; MT5 versions use MQL5 and, per MetaQuotes, compile to .ex5 files stored in the MQL5/Experts folder (MetaTrader 5 Help, Algorithmic Trading). You cannot copy an MT4 file into MT5 and expect it to run. To install either version, go to File > Open Data Folder, drop the EA into the Experts directory, then refresh the Navigator.
Beyond file formats, MT5 adds a multi-threaded tester and real-tick modelling, and its order handling differs, including support for netting as well as hedging accounts. Both terminals also ship with a simple sample MA-based EA you can study in the Navigator. Builders such as EA Studio can export identical logic to either platform, which avoids maintaining two hand-coded versions.
Building One in EA Studio: A Worked USD/JPY Example
In the video above, recorded in early 2024, Sam Jackson uses EA Studio to generate, filter and validate crossover strategies for USD/JPY. The process matters more than the specific robots, which were created on data that is now dated.
Why generate strategies rather than hand-code one? A generator tests thousands of rule and parameter combinations quickly, and the builder’s filters and validation tools then do the harder job of rejecting the ones that only look good by chance. The danger is the reverse of hand-coding: with so many candidates, some will pass on luck alone, which is why the checks below matter.
Generation Settings
| Setting | Value used in the video |
| Symbol and timeframe | USD/JPY, M15 |
| Data source | Darwinex |
| Generation period | 2 years, then 6 months out-of-sample and a further half-year for validation |
| Acceptance criteria | At least 150 trades, profit factor of 1.1 or higher |
| Protective orders | Fixed stop and target, each between 20 and 120 pips |
| Indicator limits | Up to 3 entry and 2 exit indicators |
| Generator run time | Close to 40 minutes |
Setting the date ranges manually keeps the last year of data unseen during generation, so later checks test the strategies on genuinely new price action.
Restricting the Rules to Crossover Logic
To steer the generator towards crossover systems, Jackson allowed only a handful of indicators: the Moving Average Crossover rule, a single Moving Average, RSI, Stochastic and Bollinger Bands. The extra indicators give the generator room to build filters, while the restriction keeps the output close to the intended strategy family.
Filtering the Collection
EA Studio’s performance filter then narrows the pool. Raising the minimum profit factor to 1.2 cut it to 103 strategies, and two further thresholds followed: balance stability of at least 60 and a return/drawdown figure of at least 1. These were choices for this example, not industry standards.
- Profit factor: the sum of winning trades divided by the sum of losing ones; above 1 means historical gains outweighed the losing trades.
- Balance stability: EA Studio’s measure of how steadily the balance line rises; higher values indicate a smoother curve.
- Return to drawdown: net gain relative to the deepest historical decline, a quick gauge of reward per unit of pain.
Monte Carlo Stress Testing
Next, the filtered strategies went through EA Studio’s Validator, where Monte Carlo testing randomised historical data and indicator parameters across 20 runs, requiring at least 80% of them to finish in profit. In the video, 63 strategies passed.

Passing this check shows a system is not wholly dependent on one exact price sequence or parameter set. It does not guarantee comparable live results. Our guide to Monte Carlo simulation for forex strategies explains what the method can and cannot prove.
Manual Review and a Second Data Source
A generator does not always produce what you asked for. Many of the 63 survivors relied mainly on Bollinger Bands, so Jackson reviewed each one and kept only genuine crossover systems, leaving 12. He also re-tested them on a different broker’s data, treating big differences between feeds as a warning that a system may not travel well. That quick comparison is cheap insurance: a system that only works on one data vendor’s prices is unlikely to work on yours.

Out-of-Sample and Validation Checks
Recalculating the 12 over the six-month out-of-sample window removed several that performed poorly on unseen data. The survivors were then run through the final validation window, which ended in February 2024. There, one strategy continued to perform well, another kept losing and was removed, and a third stayed roughly flat, leaving two to trade.
Those survivors had entered a stagnant spell, a normal feature of trend-following systems rather than an automatic reason to discard them. For a more systematic version of this step, see our explainer on walk-forward analysis. EA Studio’s Reactor tool can automate the whole sequence; the video breaks it into manual steps for clarity.

From Export to Demo Account
The final two strategies were exported as Expert Advisors and placed on a demo account for incubation. This stage confirms the EA executes as intended under current broker conditions; it does not prove future profitability, because live trading adds slippage, variable spreads, commissions and execution delays. Our guide to why backtest results differ from live trading covers those gaps in detail.

Ready-Made Alternatives
The two EAs from this video were offered as free downloads at the time, but Algo Trading Space retired all free EAs from its older videos in September 2025 because they needed re-optimisation. Any EA shared years ago was fitted to market conditions that have since changed, so treat old files as study material rather than ready-to-trade systems. Three monthly-refreshed EAs are now available in the Freebies tab of a free platform account. If you would rather study a finished expert advisor built around this logic, our moving average crossover robot for MetaTrader walks through one that combines the crossover with Stochastic confirmation.
FAQs
Can I build crossover logic outside MetaTrader?
Yes. The rule is simple enough to code on most platforms. TradingView’s Pine Script, TradeStation’s EasyLanguage and Python libraries can all compare two averages and trigger orders or alerts when they cross. What changes is execution: a MetaTrader EA trades directly through your broker’s terminal, while other platforms may need broker integration or an external bridge. Whichever route you take, test the code on past prices and on demo before trusting it with real money.
Does crossover logic work on gold?
It can, but gold’s sharp, news-driven swings make whipsaws and wide stops more common than on major currency pairs. Traders testing crossovers on XAUUSD often add volatility filters such as ATR, widen stop distances, and restrict activity to the London and New York sessions when gold tends to move most. Treat any XAUUSD version as a separate project with its own backtest, since settings tuned on a currency pair rarely transfer unchanged to such a different instrument.
What timeframe suits an MA crossover robot?
There is no single best timeframe; each involves trade-offs. Lower charts such as M5 or M15 sit closer to scalping and generate more crossovers, so trading costs and noise take a bigger share of every trade. Higher ones like H4 or D1 produce fewer, cleaner signals but need wider stops and more patience through flat periods. The example in this guide used M15 on USD/JPY. Test the timeframe you can realistically monitor, and always judge results after spread and commission are deducted.
Can this kind of EA be profitable?
Some crossover systems have made money over particular periods, but profitability is never guaranteed and simple two-line versions often struggle once trading costs are included. Results depend on market conditions, filters, risk settings and broker execution far more than on the crossover itself. The realistic aim is a setup with a small, durable edge that survives out-of-sample testing and demo incubation, run at a position size that keeps any losing streak survivable. Past performance does not predict future results.
Should the EA always be in the market?
Not necessarily. A stop-and-reverse design flips direction at every cross, so it never misses a trend but absorbs every whipsaw along the way. An entry-only design uses the cross to open trades and a stop loss, target or trailing exit to close them, which allows flat periods with no exposure. Many traders find the second approach easier to control, particularly on instruments that spend long stretches drifting sideways between trends, where constant reversals quickly add up in costs.
Can I run several crossover EAs on one account?
Yes, as long as each EA uses a unique magic number so MetaTrader can tell which positions belong to which robot. Running several uncorrelated crossover strategies, as in the portfolio from the video, can smooth the overall equity curve. However, crossover systems on related currency pairs often signal at similar times, which concentrates risk rather than spreading it. Check correlation and combined drawdown in a portfolio backtest before adding more EAs to one account.
Get Help Testing Your Crossover EA With Algo Trading Space
If you want a second pair of eyes on the settings, filters or validation tests of your moving average crossover EA, get in touch with the Algo Trading Space team. We can help you set up a fair testing process on your broker’s data before any capital is at risk.
Risk warning: Trading forex and CFDs carries a high risk of loss, and leverage can magnify losses beyond your initial deposit. This article is for educational purposes only and is not financial advice. Backtest results are hypothetical and do not guarantee future performance.




Comments
No comments yet. Be the first to comment!
Leave a Comment
Your email address will not be published. Required fields are marked with *