πŸ”₯Black Friday Sale: Get 25% OFF Premium with code BLACKFRIDAY β€” Sale ends December 1st!πŸŽ‰
How to Automate Your Trading Strategy on MetaTrader 5 β€” Complete MT5 Automation Guide

How to Automate Your Trading Strategy on MetaTrader 5 β€” Complete MT5 Automation Guide

By HorizonAI Team

Want to run your trading strategy 24/7 without manually placing orders? MetaTrader 5 (MT5) Expert Advisors (EAs) make it possible.

This complete guide walks you through automating your trading strategy from code to live execution, including:

  • Setting up your first Expert Advisor
  • Configuring MT5 for automated trading
  • Running EAs on a VPS for 24/7 operation
  • Risk management and monitoring
  • Common pitfalls and how to avoid them

By the end, you'll have a fully automated trading system running on MT5.

What is an Expert Advisor (EA)?

An Expert Advisor is an automated trading program written in MQL5 that:

  • Monitors market conditions continuously
  • Executes trades based on your strategy logic
  • Manages positions (stop loss, take profit, trailing stops)
  • Runs 24/7 without human intervention

Use cases:

  • Forex trading (works across all sessions: Asian, London, New York)
  • Scalping strategies (too fast for manual execution)
  • Systematic strategies (removes emotion from trading)
  • Testing strategies in live conditions (paper trading)

Step 1: Install MetaTrader 5

Download and Setup

  1. Visit your broker's website and download their MT5 installer
    • Or download from MetaQuotes: metaquotes.net/en/metatrader5
  2. Run the installer (Windows/Mac/Linux compatible)
  3. Launch MT5 and login with your broker credentials

Important: Use a demo account first. Never test new EAs on real money.

Enable Automated Trading

  1. In MT5, go to Tools β†’ Options
  2. Click the Expert Advisors tab
  3. Check these boxes:
    • βœ… Allow automated trading
    • βœ… Allow DLL imports (if your EA needs it)
    • βœ… Allow WebRequest for listed URL (for APIs)
  4. Click OK

You'll see an "AutoTrading" button in the toolbar. Make sure it's green (enabled).

Step 2: Create Your First Expert Advisor

Open MetaEditor

  1. In MT5, press F4 or go to Tools β†’ MetaQuotes Language Editor
  2. MetaEditor opens (this is where you write MQL5 code)

Create New EA

  1. In MetaEditor: File β†’ New
  2. Select Expert Advisor (template)
  3. Fill in details:
    • Name: MyFirstEA
    • Copyright: Your name
    • Parameters: Leave default for now
  4. Click Finish

You'll see template code with three main functions:

  • OnInit() - Runs once when EA starts
  • OnDeinit() - Runs once when EA stops
  • OnTick() - Runs on every price tick (this is where your logic goes)

Simple EA Example: EMA Crossover

Replace the template code with this working example:

//+------------------------------------------------------------------+
//| Expert Advisor: EMA Crossover                                     |
//+------------------------------------------------------------------+
#property copyright "HorizonAI"
#property version   "1.0"

// Input parameters (adjustable in EA settings)
input int      FastEMA = 9;      // Fast EMA period
input int      SlowEMA = 21;     // Slow EMA period
input double   LotSize = 0.1;    // Position size
input int      StopLoss = 50;    // Stop loss in points
input int      TakeProfit = 100; // Take profit in points

// Global variables for indicators
int fastHandle, slowHandle;
double fastEMA[], slowEMA[];

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Create EMA indicators
   fastHandle = iMA(_Symbol, PERIOD_CURRENT, FastEMA, 0, MODE_EMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, PERIOD_CURRENT, SlowEMA, 0, MODE_EMA, PRICE_CLOSE);
   
   if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
   {
      Print("Failed to create indicators");
      return INIT_FAILED;
   }
   
   Print("EA initialized successfully");
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Release indicator handles
   IndicatorRelease(fastHandle);
   IndicatorRelease(slowHandle);
   Print("EA removed");
}

//+------------------------------------------------------------------+
//| Expert tick function (runs on every price tick)                 |
//+------------------------------------------------------------------+
void OnTick()
{
   // Copy indicator values to arrays
   if(CopyBuffer(fastHandle, 0, 0, 3, fastEMA) < 3) return;
   if(CopyBuffer(slowHandle, 0, 0, 3, slowEMA) < 3) return;
   
   // Reverse arrays so [0] is current, [1] is previous
   ArraySetAsSeries(fastEMA, true);
   ArraySetAsSeries(slowEMA, true);
   
   // Check if we already have a position
   bool hasPosition = PositionSelect(_Symbol);
   
   // ENTRY LOGIC: Fast EMA crosses above Slow EMA
   if(fastEMA[1] <= slowEMA[1] && fastEMA[0] > slowEMA[0] && !hasPosition)
   {
      // Bullish crossover - open BUY position
      double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double sl = price - StopLoss * _Point;
      double tp = price + TakeProfit * _Point;
      
      if(OrderSend(_Symbol, ORDER_TYPE_BUY, LotSize, price, 10, sl, tp, "EMA Cross Buy") > 0)
         Print("BUY order opened at ", price);
      else
         Print("BUY order failed: ", GetLastError());
   }
   
   // EXIT LOGIC: Fast EMA crosses below Slow EMA
   if(fastEMA[1] >= slowEMA[1] && fastEMA[0] < slowEMA[0] && hasPosition)
   {
      // Bearish crossover - close position
      if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
      {
         double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         if(OrderSend(_Symbol, ORDER_TYPE_SELL, LotSize, price, 10, 0, 0, "EMA Cross Exit") > 0)
            Print("Position closed at ", price);
      }
   }
}
//+------------------------------------------------------------------+

Compile the EA

  1. Click Compile (F7) in MetaEditor
  2. Check the Errors tab at the bottom
  3. If "0 errors" - success! Your EA is ready

The compiled EA (.ex5 file) is saved in: MQL5/Experts/MyFirstEA.ex5

Step 3: Attach EA to Chart

Add EA to Chart

  1. In MT5, open a chart (e.g., EURUSD, 1-hour timeframe)
  2. In the Navigator panel (left side), expand Expert Advisors
  3. Drag MyFirstEA onto the chart
  4. A settings window appears:

Common Settings Tab:

  • βœ… Allow live trading (checked)
  • Set Maximum number of bars (default is fine)

Inputs Tab:

  • Adjust EA parameters (FastEMA, SlowEMA, LotSize, StopLoss, TakeProfit)
  1. Click OK

You'll see a smiley face icon in the top-right of the chart:

  • 😊 Green happy face = EA is running
  • 😐 Neutral face = EA loaded but AutoTrading is off (click toolbar button)
  • ❌ Red X = EA failed to load (check logs)

Step 4: Monitor Your EA

Where to Check EA Activity

1. Journal Tab (bottom panel)

  • Shows EA initialization messages
  • Prints from your code (e.g., "BUY order opened")
  • System messages

2. Toolbox β†’ Trade Tab

  • Shows open positions
  • Displays pending orders
  • Shows account balance and equity

3. Toolbox β†’ History Tab

  • Shows closed trades
  • View profit/loss per trade
  • Export trade history for analysis

Add Debug Prints

Good EAs include logging. Add prints to track what's happening:

void OnTick()
{
   // Print current EMA values every 100 ticks
   static int tickCount = 0;
   tickCount++;
   
   if(tickCount % 100 == 0)
   {
      Print("Fast EMA: ", fastEMA[0], " | Slow EMA: ", slowEMA[0]);
   }
   
   // Your trading logic here...
}

Step 5: Run EA on VPS for 24/7 Trading

Your PC needs to be on for EAs to run. For 24/7 operation, use a Virtual Private Server (VPS).

Why VPS?

  • βœ… Runs 24/7 (even when your PC is off)
  • βœ… Low latency (VPS near broker servers = faster execution)
  • βœ… No disconnections (stable internet)
  • βœ… Multiple EAs can run simultaneously

1. MetaQuotes VPS (Built into MT5)

  • Cost: $10-30/month
  • Pros: One-click setup, optimized for MT5
  • Cons: More expensive than alternatives

Setup:

  1. In MT5: Tools β†’ Options β†’ VPS
  2. Click Rent Virtual Server
  3. Choose plan and pay
  4. MT5 auto-migrates your EAs to VPS

2. Third-Party VPS (Cheaper)

  • Providers: Vultr, DigitalOcean, Amazon Lightsail, ForexVPS
  • Cost: $5-20/month
  • Pros: Cheaper, more control
  • Cons: Manual setup required

Setup (Third-Party VPS):

  1. Rent Windows VPS (2GB RAM minimum)
  2. Connect via Remote Desktop
  3. Install MT5 on VPS
  4. Login to your broker account
  5. Add your EA to charts
  6. Minimize (don't close) MT5 window

Pro tip: Use MetaQuotes VPS if you're not tech-savvy. Use third-party VPS if you want to save money and don't mind manual setup.

Step 6: Risk Management for Automated Trading

Automated trading can amplify losses if not managed properly. Follow these rules:

1. Start with Small Lot Sizes

input double BaseLotSize = 0.01;  // Start tiny!

Test with micro lots (0.01) for at least 1 week before increasing.

2. Set Maximum Daily Loss

Add a daily loss limit to your EA:

// Global variables
datetime lastResetDate = 0;
double dailyProfit = 0.0;
input double MaxDailyLoss = 100.0;  // In account currency

void OnTick()
{
   // Reset daily P&L at midnight
   if(TimeCurrent() >= lastResetDate + 86400)
   {
      dailyProfit = 0.0;
      lastResetDate = TimeCurrent();
   }
   
   // Calculate today's profit
   // (Add up profits from closed trades since midnight)
   
   // Stop trading if daily loss limit hit
   if(dailyProfit < -MaxDailyLoss)
   {
      Print("Daily loss limit reached. Stopping EA.");
      ExpertRemove();  // Turns off EA
      return;
   }
   
   // Your trading logic here...
}

3. Limit Maximum Open Positions

input int MaxPositions = 3;

void OnTick()
{
   // Count open positions
   int openCount = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(PositionGetSymbol(i) == _Symbol)
         openCount++;
   }
   
   if(openCount >= MaxPositions)
   {
      Print("Max positions reached. Waiting...");
      return;  // Don't open new trades
   }
   
   // Your entry logic here...
}

4. Always Use Stop Losses

Never rely on EA to "manage" positions without hard stops. Always set SL at order placement:

double sl = price - StopLoss * _Point;
double tp = price + TakeProfit * _Point;

// ALWAYS include SL and TP in order
OrderSend(_Symbol, ORDER_TYPE_BUY, LotSize, price, 10, sl, tp, "Comment");

Common EA Mistakes and Fixes

❌ Problem: EA isn't opening trades

Causes:

  • AutoTrading is disabled (click toolbar button to enable)
  • Insufficient margin (check account balance)
  • Broker doesn't allow trading (market closed, symbol unavailable)
  • Logic error in code

Debug:

void OnTick()
{
   Print("OnTick called");  // Should print every tick
   
   if(longCondition)
   {
      Print("Long condition TRUE");  // Is condition triggering?
      
      double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      Print("Price: ", price);  // Is price valid?
      
      long result = OrderSend(...);
      if(result < 0)
         Print("Order failed: Error ", GetLastError());  // Check error code
   }
}

❌ Problem: EA keeps repainting signals

Cause: Using [0] (current forming bar) instead of [1] (closed bar).

Fix: Only trade on confirmed bars:

// Check if new bar formed
static datetime lastBarTime = 0;
datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);

if(currentBarTime == lastBarTime)
   return;  // Wait for new bar

lastBarTime = currentBarTime;

// Now check conditions using [1] (previous closed bar)
if(fastEMA[1] < slowEMA[1] && fastEMA[0] > slowEMA[0])
{
   // Crossover confirmed on closed bar
}

❌ Problem: EA running too slow

Cause: Heavy calculations on every tick.

Fix: Optimize with IsNewBar() checks:

bool IsNewBar()
{
   static datetime lastBarTime = 0;
   datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
   
   if(currentBarTime != lastBarTime)
   {
      lastBarTime = currentBarTime;
      return true;
   }
   return false;
}

void OnTick()
{
   if(!IsNewBar())
      return;  // Only run logic on new bar formation
   
   // Heavy calculations here...
}

Testing Your EA Before Going Live

1. Strategy Tester (Backtesting)

  1. In MT5, press Ctrl+R to open Strategy Tester
  2. Select your EA from dropdown
  3. Choose symbol, timeframe, and date range
  4. Click Start
  5. Review Results, Graph, and Report tabs

Look for:

  • βœ… Net profit (positive after commissions)
  • βœ… Profit factor > 1.5
  • βœ… Max drawdown < 20%
  • βœ… Reasonable number of trades (not overfitting)

2. Forward Testing (Demo Account)

Never skip this step. Run EA on demo for at least 1 month before live trading.

What to monitor:

  • Does EA behave as expected?
  • Are slippage and commissions realistic?
  • Does performance match backtest?
  • Are there any unexpected errors?

3. Paper Trading with Real Prices

Some brokers offer "demo accounts with live prices." This is ideal for testing.

Generate MT5 Expert Advisors with AI

Writing MQL5 from scratch is time-consuming. Use HorizonAI to generate EAs instantly from plain English.

Example prompts:

"Create an MT5 Expert Advisor with 50/200 EMA crossover, ATR-based stops, and max 2% risk per trade"

"Build an MQL5 scalping EA using Bollinger Bands, 1:2 risk-reward, and maximum 3 open positions"

"Convert this Pine Script strategy to MT5: [paste code]"

HorizonAI generates:

  • βœ… Clean, optimized MQL5 code
  • βœ… Risk management built-in
  • βœ… Proper error handling
  • βœ… Ready to compile and run
Generate your EA now β†’

Checklist: Before Running EA Live

  • βœ… Backtested on 1+ years of data
  • βœ… Forward tested on demo for 1+ month
  • βœ… Risk management configured (max loss, position limits)
  • βœ… Stop losses set on all orders
  • βœ… Running on VPS (for 24/7 operation)
  • βœ… Starting with small lot size (0.01-0.1)
  • βœ… Monitoring EA daily (check journal, trades, P&L)
  • βœ… Written trading plan (when to stop EA, when to adjust settings)

Final Thoughts

Automated trading with MT5 EAs can free you from manual order placement and remove emotion from tradingβ€”but only if done correctly.

Follow these principles:

  1. Test extensively (backtest β†’ demo β†’ small live)
  2. Manage risk aggressively (stop losses, position limits, daily loss caps)
  3. Monitor regularly (don't set and forget)
  4. Start small (micro lots for first month)
  5. Use VPS (for reliability and 24/7 operation)

Done right, automated trading lets you run systematic strategies that would be impossible to execute manually.

Questions about MT5 Expert Advisors? Join our Discord community to discuss with other algo traders!