F

Forex Journal Team

June 13, 20262 min read

MT5 Automation: How to Build Your First Trading Bot in MQL5

strategymt5automationmql5trading-bottechnologystrategy

Building Your First MQL5 Expert Advisor

MetaTrader 5 (MT5) comes with a powerful built-in programming language called MQL5. With it, you can automate any strategy.

Prerequisites

  • MT5 installed (free from your broker)
  • Basic programming concepts (variables, loops, conditions)
  • A strategy you want to automate

Your First EA: A Simple Moving Average Crossover

//+------------------------------------------------------------------+
//| SimpleMAExpert.mq5                                              |
//+------------------------------------------------------------------+
input int FastMA = 10;      // Fast MA period
input int SlowMA = 30;      // Slow MA period
input double LotSize = 0.01; // Position size

int fastHandle, slowHandle;

int OnInit() {
   fastHandle = iMA(_Symbol, _Period, FastMA, 0, MODE_SMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, _Period, SlowMA, 0, MODE_SMA, PRICE_CLOSE);
   return INIT_SUCCEEDED;
}

void OnTick() {
   double fast[], slow[];
   CopyBuffer(fastHandle, 0, 0, 3, fast);
   CopyBuffer(slowHandle, 0, 0, 3, slow);
   
   if (fast[1] > slow[1] && fast[2] <= slow[2])
      Trade.Buy(LotSize);
   else if (fast[1] < slow[1] && fast[2] >= slow[2])
      Trade.Sell(LotSize);
}
//+------------------------------------------------------------------+

Testing Your EA

  1. Open MT5 Strategy Tester
  2. Select your EA, symbol, and date range
  3. Choose tick-by-tick simulation for accuracy
  4. Run the test and analyze the results (profit factor, drawdown, trades)

Deployment

Once tested:

  1. Add the EA to a chart (drag from Navigator)
  2. Enable algorithmic trading (Alt+T)
  3. Monitor it for the first few days

Pro Tips

  • Always use stop loss and take profit in your code
  • Start with a demo account
  • Don't automate more than 1% risk per trade
  • Keep a manual journal alongside to track EA performance
F

Written by Forex Journal Team

Track every trade. Master your edge.

Forex Journal helps you log, analyze, and improve your trading across forex, indices, crypto, and futures — all 100% free.

Start your free journal