Blog

From Idea to Execution: Building a Simple MT5 Algo for Forex and Crypto
Trading Strategy

From Idea to Execution: Building a Simple MT5 Algo for Forex and Crypto

Introduction

Algorithmic trading is no longer the exclusive domain of hedge funds. With MetaTrader 5 (MT5) you can code, test, and run a fully automated trading strategy from a personal laptop. This article walks you through every step – from defining the idea to deploying a live robot that works on both forex trading pairs like EUR/USD and GBP/USD and on crypto trading symbols such as BTC/USD. By the end you’ll have a reusable skeleton that you can adapt to any market, and a clear view of how it fits into a prop firm evaluation like the Global4EX Challenge.


1. Why Choose MT5 for Algorithmic Trading?

  • Multi‑asset support – MT5 handles forex, commodities (XAU/USD), indices, and crypto futures, letting you test a single script across diverse instruments.
  • Built‑in tester – The Strategy Tester offers visual, multi‑threaded backtesting, walk‑forward analysis, and detailed drawdown reports.
  • MQL5 language – A C‑style language that balances performance with readability, perfect for traders who know basic programming.
  • Community library – Thousands of open‑source indicators and Expert Advisors (EAs) you can study or extend.

These features make MT5 a natural platform for anyone aiming to meet the affordable prop firm evaluation standards of the best prop firm 2026.


2. Defining a Simple, Robust Idea

For a beginner‑friendly algorithm, a moving‑average crossover works well because:

  • It relies on clear technical analysis signals.
  • It can be applied to any time‑frame (e.g., 15‑minute for scalping or daily for swing).
  • It offers easy risk‑management parameters (stop‑loss, take‑profit, position sizing).

Strategy outline:

  1. Entry rule – Go long when the 9‑period Exponential Moving Average (EMA) crosses above the 21‑period EMA on the chosen chart. Go short on the opposite crossover.
  2. Exit rule – Close the position when the opposite crossover occurs or when a fixed risk‑reward target (e.g., 1:2) is hit.
  3. Risk management – Risk 1 % of account equity per trade, calculate lot size using the stop‑loss distance, and enforce a maximum drawdown of 5 % before halting the EA.

This logic is simple enough to avoid over‑fitting while still providing a trading strategy that can be scaled to a funded account.


3. Coding the EA in MQL5

Create a new Expert Advisor in MetaEditor and paste the skeleton below. Comments explain each block.

//+------------------------------------------------------------------+
//| Simple EMA Crossover EA                                          |
//+------------------------------------------------------------------+
#property copyright "Global4EX Educational"
#property version   "1.00"
#property strict

input int FastEMA = 9;          // Fast EMA period
input int SlowEMA = 21;         // Slow EMA period
input double RiskPercent = 1.0; // % of equity per trade
input double RR = 2.0;          // Reward‑to‑Risk ratio
input double MaxDrawdown = 5.0; // % equity drawdown limit

//--- Global variables
double Lots;
double StopLossPips;

int OnInit(){
   Print("Simple EMA Crossover EA initialized");
   return(INIT_SUCCEEDED);
}

void OnTick(){
   // Ensure we have only one open position per symbol
   if(PositionSelect(Symbol())) return;

   // Calculate EMAs
   double fast = iMA(Symbol(),0,FastEMA,0,MODE_EMA,PRICE_CLOSE,0);
   double slow = iMA(Symbol(),0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,0);
   double fastPrev = iMA(Symbol(),0,FastEMA,0,MODE_EMA,PRICE_CLOSE,1);
   double slowPrev = iMA(Symbol(),0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,1);

   // Determine crossover
   bool bullish  = (fastPrev < slowPrev) && (fast > slow);
   bool bearish  = (fastPrev > slowPrev) && (fast < slow);

   // Risk calculations
   double equity = AccountInfoDouble(ACCOUNT_EQUITY);
   double riskAmt = equity * RiskPercent / 100.0;
   double atr = iATR(Symbol(),0,14,0); // Use ATR for stop distance
   StopLossPips = atr * 10; // Rough conversion to pips
   Lots = NormalizeDouble(riskAmt / (StopLossPips * SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)),2);

   // Entry
   if(bullish)
      OrderSend(Symbol(),OP_BUY, Lots, Ask, 2, Ask-StopLossPips*_Point, Ask+RR*StopLossPips*_Point, "EMA Long", 0, 0, clrGreen);
   else if(bearish)
      OrderSend(Symbol(),OP_SELL, Lots, Bid, 2, Bid+StopLossPips*_Point, Bid-RR*StopLossPips*_Point, "EMA Short", 0, 0, clrRed);
}

void OnDeinit(const int reason){}

Key points:

  • Risk % is calculated on the fly, ensuring consistent position sizing regardless of account size.
  • ATR (Average True Range) provides a volatility‑adjusted stop‑loss, which is crucial for both forex and crypto where price swings differ.
  • The EA respects a drawdown limit – you can add a check at the start of OnTick() that disables trading if equity falls below the permitted threshold.

4. Backtesting & Optimization

  1. Select the instrument – Test on EUR/USD, GBP/USD, and BTC/USD to see how the same logic behaves across markets.
  2. Choose the timeframe – For a day‑trader, 15‑minute charts are common; for a swing‑trader, D1 works better.
  3. Set the period – Run a minimum of 2 years of data to capture different market regimes.
  4. Metrics to monitor:
    • Net profit and profit factor (aim > 1.5).
    • Maximum drawdown – keep it below the 5 % rule.
    • Win rate – not the primary focus; a 40‑45 % win rate can be acceptable if the RR ratio is strong.
  5. Avoid over‑fitting – Limit the number of input parameters. In the example above only the EMA periods, risk %, and RR are variable. Use walk‑forward testing to confirm stability.

When comparing the best prop firm 2026, a strategy that demonstrates low drawdown and consistent risk‑adjusted returns will stand out in the Global4EX Challenge or the 1‑Phase evaluation.


5. Deploying to a Live Account

After a successful backtest:

  1. Forward‑test on a demo account for at least 1 month. Monitor slippage and execution speed – MT5’s built‑in HFT (High‑Frequency Trading) mode can reduce latency, a feature that aligns with the best HFT prop firm offering.
  2. Adjust lot size based on live equity; the EA’s built‑in risk calculator will automatically adapt.
  3. Set alerts – enable email or push notifications for each trade to stay aware of activity, especially when trading volatile crypto pairs.
  4. Connect to a funded account – If you have passed the Global4EX Challenge, you can run the same EA on a MyFinancial Pro or MyFinancial Plus+ account. The prop‑firm’s low drawdown rules (often 5‑10 %) match the EA’s internal stop‑loss logic, simplifying compliance.

6. Common Pitfalls & How to Avoid Them

PitfallWhy it hurtsFix
Over‑optimizing on one pairResults may not translate to other symbols, leading to poor performance on BTC/USD or XAU/USD.Keep parameters generic; test on at least three unrelated assets.
Ignoring spread and commissionA strategy that looks good on paper can become unprofitable once real‑world costs are added.Use MT5’s Spread and Commission fields in the tester; factor them into the profit‑factor calculation.
Fixed stop‑loss in pipsDoes not adapt to volatility spikes, especially in crypto markets.Use ATR‑based stops as shown in the code.
Running multiple EAs on the same symbolCan cause conflicting orders and unexpected margin usage.Deploy only one EA per symbol or coordinate their logic.
Skipping risk‑management checksA single losing streak can breach the prop‑firm’s drawdown limit.Enforce the MaxDrawdown rule inside the EA and stop trading automatically when breached.

7. Scaling the Strategy

Once the basic crossover works, you can enhance it:

  • Add a filter – e.g., only trade when the 50‑EMA is trending upward for longs.
  • Multi‑timeframe confirmation – require the crossover on the 15‑minute chart and a confirming trend on the 1‑hour chart.
  • Dynamic position sizing – incorporate equity curve volatility (e.g., Kelly criterion) for more aggressive scaling.
  • Portfolio approach – run the same EA on several pairs simultaneously, keeping total risk at 1 % of equity across all trades.

These upgrades keep the core idea simple while providing the flexibility needed for larger funded accounts and for meeting the instant funding prop firm standards of the HFT Instant product.


8. Final Thoughts

Building a simple automated strategy on MT5 teaches you the full lifecycle of algorithmic trading: idea generation, coding, rigorous testing, and live deployment. By focusing on clear entry/exit rules, volatility‑adjusted risk management, and strict drawdown limits, you create a trading strategy that not only survives market noise but also aligns with the requirements of prop‑firm evaluations like the Global4EX Challenge.

Whether you are trading a personal account or a Global4EX funded account, the principles covered here—transparent risk, disciplined backtesting, and scalable automation—are the foundation of sustainable success in both forex trading and crypto trading. Happy coding, and may your EAs run profitably!


Published by the Global4EX Team. Learn more at global4ex.com

Your Talent Deserves Global4EX

Join Global4EX where traders unite, grow, and get rewards.

Join Community

Important information & disclaimer

Simulated trading environment

All accounts provided by Global4EX are demo accounts operating exclusively in a simulated trading environment. No actual trades are executed on live financial markets. The services we offer are designed for educational and evaluation purposes only.

No investment services

The simulated trading services are provided by Global4EX, operated by LOGIC GRATE SERVICES LTD. All content published and distributed by Global4EX and its related entities (collectively, the "Company") is for general informational purposes only.

The Company does not provide investment advice.

The Company does not solicit or recommend the purchase or sale of any financial instruments, securities, or funds.

The Company does not act as a broker, custodian, or financial intermediary.

Participation in any program is voluntary, and all fees paid to the Company are strictly service fees only.

Program fees:

are not deposits

do not represent client funds

are not investments

do not generate returns, interest, or profit

These fees are applied toward operational and administrative expenses, including platform infrastructure, technology, support services, and risk management systems. Payment of fees does not create any fiduciary, custodial, or investment relationship between participants and the Company. Participants should understand that such fees provide access only to simulated trading evaluations and related services in a demo environment. Nothing on this website or in our programs constitutes an offer to buy or sell futures, options, CFDs, forex, stocks, or any other financial instruments. All results displayed are based on simulated trading performance. Past simulated performance is not necessarily indicative of future results.

General risk warning

Trading financial markets involves a high level of risk. Even in a simulated environment, strategies and outcomes may not reflect real-world execution. Participants should carefully consider their experience, objectives, and risk tolerance before engaging in any trading-related activity.

Corporate & brand information

The website https://global4ex.com is owned and operated by LOGIC GRATE SERVICES LTD, registered in United Kingdom (Company No. 16914973), with registered office at 5 Brayford Square, London, England E1 0S.

Global4EX © 2026 is a brand name of LOGIC GRATE SERVICES LTD.