How to Code an Expert Advisor (EA) in MQL5

How to Code an Expert Advisor (EA) in MQL5

Creating an Expert Advisor in MQL5 allows you to automate your trading strategies on the MetaTrader 5 platform. Here’s a step-by-step guide to get you started:

Basic Structure of an MQL5 EA

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Initialization code
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Cleanup code
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Main trading logic goes here
}

Step-by-Step Development Process

1. Set Up Your Development Environment

  • Open MetaEditor (press F4 in MT5 or go to Tools > MetaQuotes Language Editor)
  • Create new EA: File > New > Expert Advisor (template)

2. Define Input Parameters

input double   LotSize = 0.1;       // Lot size
input int      StopLoss = 50;       // Stop loss in points
input int      TakeProfit = 100;    // Take profit in points
input int      MovingAveragePeriod = 14; // MA period

3. Implement Trading Logic

Here’s a simple moving average crossover example:

void OnTick()
{
   // Check if we have enough bars
   if(Bars(_Symbol, _Period) < MovingAveragePeriod) return;
   
   // Get current moving average values
   double maCurrent = iMA(_Symbol, _Period, MovingAveragePeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
   double maPrevious = iMA(_Symbol, _Period, MovingAveragePeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
   
   // Check for open positions
   bool positionExists = PositionSelect(_Symbol);
   
   // Buy signal (MA crosses up)
   if(maCurrent > maPrevious && !positionExists)
   {
      MqlTradeRequest request = {0};
      MqlTradeResult  result = {0};
      
      request.action    = TRADE_ACTION_DEAL;
      request.symbol    = _Symbol;
      request.volume    = LotSize;
      request.type      = ORDER_TYPE_BUY;
      request.price     = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      request.sl        = request.price - StopLoss * _Point;
      request.tp        = request.price + TakeProfit * _Point;
      request.deviation = 10;
      
      OrderSend(request, result);
   }
   
   // Sell signal (MA crosses down)
   else if(maCurrent < maPrevious && positionExists)
   {
      // Close position code would go here
   }
}

4. Add Error Handling

if(!OrderSend(request, result))
{
   Print("OrderSend failed with error #", GetLastError());
   return;
}

5. Compile and Test

  • Click the “Compile” button or press F7
  • Load the EA on a chart in MT5 (drag from Navigator to chart)
  • Test in Strategy Tester (View > Strategy Tester or press Ctrl+R)

Key MQL5 Functions for EAs

  • OrderSend() – Main function to place trades
  • PositionSelect() – Check for existing positions
  • iMA()iRSI()iMACD() – Technical indicator functions
  • SymbolInfoDouble() – Get market data
  • AccountInfoDouble() – Get account information

Best Practices

  1. Always include proper error handling
  2. Use input parameters for customizable values
  3. Implement money management rules
  4. Test thoroughly in the Strategy Tester before live trading
  5. Consider adding logging functionality for debugging