Complete .mq5 source code

AI MQL5 Code Generator: Generate Expert Advisors with AI (2026)

This tutorial page explains how to use AI-powered tools to generate MQL5 Expert Advisor code for MetaTrader 5, dramatically reducing the time and expertise required to build automated trading systems. Readers learn how to prompt an AI code generator effectively, review and validate the output, and integrate it into the MetaEditor workflow to produce production-ready EAs.

Strategy logic

Entry conditions

N/A — this is a tutorial/indicator reference page. The embedded teaching example uses a dual moving-average crossover entry (fast MA crossing above slow MA for long, below for short) purely to demonstrate how AI-generated MQL5 boilerplate is structured and customised.

Exit conditions

N/A — this is a tutorial/indicator reference page. The teaching example closes positions when the opposite crossover signal fires, illustrating the symmetric exit pattern that AI generators typically produce as a starting scaffold.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//|  AI_MA_Crossover_Demo.mq5                                        |
//|  Teaching example — generated with Pineify AI MQL5 Code Generator|
//|  Demonstrates the boilerplate structure an AI tool produces.      |
//|  NOT a production strategy — review and test before live use.     |
//+------------------------------------------------------------------+
#property copyright "Pineify.app"
#property link      "https://pineify.app"
#property version   "1.00"
#property strict

//--- Input parameters (AI generator exposes these as user controls)
input int    FastMAPeriod   = 10;           // Fast MA period
input int    SlowMAPeriod   = 30;           // Slow MA period
input ENUM_MA_METHOD MAMethod = MODE_EMA;  // MA smoothing method
input double LotSize        = 0.1;          // Trade volume in lots
input int    MagicNumber    = 202600;       // Unique EA identifier
input int    Slippage       = 3;            // Max allowed slippage (points)
input double StopLossPips   = 50.0;         // Stop loss in pips
input double TakeProfitPips = 100.0;        // Take profit in pips

//--- Global handles and state
int    g_fastMAHandle = INVALID_HANDLE;
int    g_slowMAHandle = INVALID_HANDLE;
double g_point        = 0.0;

//+------------------------------------------------------------------+
//| Expert initialisation                                            |
//+------------------------------------------------------------------+
int OnInit()
  {
   //--- Validate period inputs
   if(FastMAPeriod >= SlowMAPeriod)
     {
      Print("ERROR: FastMAPeriod must be less than SlowMAPeriod.");
      return INIT_PARAMETERS_INCORRECT;
     }

   //--- Create indicator handles (MQL5 handle-based pattern)
   g_fastMAHandle = iMA(_Symbol, _Period, FastMAPeriod, 0, MAMethod, PRICE_CLOSE);
   g_slowMAHandle = iMA(_Symbol, _Period, SlowMAPeriod, 0, MAMethod, PRICE_CLOSE);

   if(g_fastMAHandle == INVALID_HANDLE || g_slowMAHandle == INVALID_HANDLE)
     {
      Print("ERROR: Failed to create MA indicator handles.");
      return INIT_FAILED;
     }

   //--- Cache point size for pip calculations
   g_point = _Point;
   if(_Digits == 3 || _Digits == 5)
      g_point *= 10; // Normalise to a full pip for 3/5-digit brokers

   Print("AI_MA_Crossover_Demo initialised on ", _Symbol,
         " | Fast MA: ", FastMAPeriod, " | Slow MA: ", SlowMAPeriod);
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
//| Expert deinitialization                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   //--- Release indicator handles to free terminal resources
   if(g_fastMAHandle != INVALID_HANDLE)
      IndicatorRelease(g_fastMAHandle);
   if(g_slowMAHandle != INVALID_HANDLE)
      IndicatorRelease(g_slowMAHandle);

   Print("AI_MA_Crossover_Demo removed. Reason code: ", reason);
  }

//+------------------------------------------------------------------+
//| Expert tick handler                                              |
//+------------------------------------------------------------------+
void OnTick()
  {
   //--- Only act on a new bar to avoid repeated signals on the same candle
   static datetime s_lastBarTime = 0;
   datetime currentBarTime = iTime(_Symbol, _Period, 0);
   if(currentBarTime == s_lastBarTime)
      return;
   s_lastBarTime = currentBarTime;

   //--- Copy two bars of MA data (current [0] and previous [1])
   double fastMA[2], slowMA[2];
   if(CopyBuffer(g_fastMAHandle, 0, 0, 2, fastMA) < 2 ||
      CopyBuffer(g_slowMAHandle, 0, 0, 2, slowMA) < 2)
     {
      Print("WARNING: Insufficient indicator data on ", _Symbol);
      return;
     }

   //--- Detect crossover direction
   bool bullishCross = (fastMA[1] < slowMA[1]) && (fastMA[0] > slowMA[0]);
   bool bearishCross = (fastMA[1] > slowMA[1]) && (fastMA[0] < slowMA[0]);

   //--- Close opposing position then open a new one on crossover
   if(bullishCross)
     {
      ClosePositions(ORDER_TYPE_SELL);
      OpenPosition(ORDER_TYPE_BUY);
     }
   else if(bearishCross)
     {
      ClosePositions(ORDER_TYPE_BUY);
      OpenPosition(ORDER_TYPE_SELL);
     }
  }

//+------------------------------------------------------------------+
//| Open a market position with SL and TP                           |
//+------------------------------------------------------------------+
void OpenPosition(ENUM_ORDER_TYPE orderType)
  {
   //--- Avoid duplicate positions managed by this EA
   if(CountPositions(orderType) > 0)
      return;

   MqlTradeRequest request = {};
   MqlTradeResult  result  = {};

   double price = (orderType == ORDER_TYPE_BUY)
                  ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
                  : SymbolInfoDouble(_Symbol, SYMBOL_BID);

   double sl = (orderType == ORDER_TYPE_BUY)
               ? price - StopLossPips   * g_point
               : price + StopLossPips   * g_point;

   double tp = (orderType == ORDER_TYPE_BUY)
               ? price + TakeProfitPips * g_point
               : price - TakeProfitPips * g_point;

   request.action    = TRADE_ACTION_DEAL;
   request.symbol    = _Symbol;
   request.volume    = LotSize;
   request.type      = orderType;
   request.price     = price;
   request.sl        = NormalizeDouble(sl, _Digits);
   request.tp        = NormalizeDouble(tp, _Digits);
   request.deviation = Slippage;
   request.magic     = MagicNumber;
   request.comment   = "AI_MA_Cross";
   request.type_filling = ORDER_FILLING_IOC;

   if(!OrderSend(request, result))
      Print("OrderSend failed: ", result.retcode, " — ", result.comment);
   else
      Print("Position opened: ", EnumToString(orderType),
            " @ ", price, " | Ticket: ", result.order);
  }

//+------------------------------------------------------------------+
//| Close all positions of a given type managed by this EA          |
//+------------------------------------------------------------------+
void ClosePositions(ENUM_ORDER_TYPE typeToClose)
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol)    continue;
      if(PositionGetInteger(POSITION_MAGIC)  != MagicNumber) continue;
      if((ENUM_ORDER_TYPE)PositionGetInteger(POSITION_TYPE) != typeToClose) continue;

      MqlTradeRequest req = {};
      MqlTradeResult  res = {};
      req.action   = TRADE_ACTION_DEAL;
      req.symbol   = _Symbol;
      req.volume   = PositionGetDouble(POSITION_VOLUME);
      req.position = ticket;
      req.type     = (typeToClose == ORDER_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
      req.price    = (req.type == ORDER_TYPE_SELL)
                     ? SymbolInfoDouble(_Symbol, SYMBOL_BID)
                     : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      req.deviation      = Slippage;
      req.magic          = MagicNumber;
      req.type_filling   = ORDER_FILLING_IOC;

      if(!OrderSend(req, res))
         Print("Close failed: ticket=", ticket, " retcode=", res.retcode);
     }
  }

//+------------------------------------------------------------------+
//| Count open positions of a given type for this EA                |
//+------------------------------------------------------------------+
int CountPositions(ENUM_ORDER_TYPE orderType)
  {
   int count = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL)  != _Symbol)     continue;
      if(PositionGetInteger(POSITION_MAGIC)  != MagicNumber) continue;
      if((ENUM_ORDER_TYPE)PositionGetInteger(POSITION_TYPE) == orderType) count++;
     }
   return count;
  }
//+------------------------------------------------------------------+

Copy this code into MetaEditor, save it in the MQL5/Experts folder, and compile with F7.

Generate a custom Multi-pair educational EA

Describe the ATR inputs, alert rules, visual style, or confirmation filter you want. Pineify generates editable MQL5 source code that you can inspect and compile in MetaEditor.

Pine Script vs MQL5: Same Strategy, Different Platforms

AspectPine Script (TradingView)MQL5 (MetaTrader 5)
ExecutionSeries evaluated on chart updatesEvent handlers with explicit buffers
DeploymentRuns in TradingView with alertsRuns in the MT5 terminal or on a VPS
Broker accessVia TradingView broker integrationDirect broker connectivity
BacktestingStrategy Tester for strategy scriptsStrategy Tester for Expert Advisors
Code complexitySimpler, functional syntaxC++-like, more powerful

The calculation can be implemented on either platform, but the runtime model and buffer APIs differ. Read the Pine Script Supertrend reference before porting logic between them.

Frequently Asked Questions

Related MQL5 pages

Risk and testing note

Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.