Summary: Complete MT4 EA source code implementing a dual moving average crossover strategy. Includes entry logic, stop loss, take profit, and position management. Perfect for beginners learning EA programming.




# Moving Average Crossover EA - Complete MQL4 Source Code

This article provides a fully functional Expert Advisor (EA) for MT4 that trades based on two moving averages crossover signals. When the fast MA crosses above the slow MA, the EA opens a BUY position. When it crosses below, it opens a SELL position.

Strategy Logic



The EA uses Simple Moving Averages (SMA) by default. Parameters are adjustable to switch to Exponential Moving Averages (EMA). Each trade includes configurable stop loss, take profit, and trailing stop functionality.

Complete MQL4 Code



```mql4
//+------------------------------------------------------------------+
//| MACrossoverEA.mq4 |
//| Generated by AI Assistant |
//| |
//+------------------------------------------------------------------+
#property copyright "AI Assistant"
#property link ""
#property version "1.00"
#property strict

input double LotSize = 0.1; // Lot size
input int FastMAPeriod = 5; // Fast MA period
input int SlowMAPeriod = 20; // Slow MA period
input int MAType = MODE_SMA; // MA type: MODE_SMA, MODE_EMA
input int MAPrice = PRICE_CLOSE; // Price type: PRICE_CLOSE, PRICE_OPEN
input int StopLoss = 50; // Stop loss in pips
input int TakeProfit = 100; // Take profit in pips
input int TrailingStop = 30; // Trailing stop in pips (0=off)
input int MagicNumber = 202410; // EA magic number

double fastMA_prev = 0, fastMA_curr = 0;
double slowMA_prev = 0, slowMA_curr = 0;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
if(SlowMAPeriod <= FastMAPeriod)
{
Print("Error: Slow MA period must be greater than Fast MA period");
return(INIT_PARAMETERS_INCORRECT);
}
return(INIT_SUCCEEDED);
}

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

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate MAs
fastMA_curr = iMA(Symbol(), 0, FastMAPeriod, 0, MAType, MAPrice, 0);
fastMA_prev = iMA(Symbol(), 0, FastMAPeriod, 0, MAType, MAPrice, 1);
slowMA_curr = iMA(Symbol(), 0, SlowMAPeriod, 0, MAType, MAPrice, 0);
slowMA_prev = iMA(Symbol(), 0, SlowMAPeriod, 0, MAType, MAPrice, 1);

// Check for existing positions
if(CountPositions() > 0)
{
TrailingStopManagement();
return;
}

// Crossover signals
if(fastMA_prev <= slowMA_prev && fastMA_curr > slowMA_curr)
{
CloseAllPositions();
OpenOrder(OP_BUY);
}
else if(fastMA_prev >= slowMA_prev && fastMA_curr < slowMA_curr)
{
CloseAllPositions();
OpenOrder(OP_SELL);
}
}

//+------------------------------------------------------------------+
//| Open market order |
//+------------------------------------------------------------------+
void OpenOrder(int cmd)
{
double price = (cmd == OP_BUY) ? Ask : Bid;
double sl = 0, tp = 0;

if(StopLoss > 0)
sl = (cmd == OP_BUY) ? price - StopLoss * Point * 10 : price + StopLoss * Point * 10;
if(TakeProfit > 0)
tp = (cmd == OP_BUY) ? price + TakeProfit * Point * 10 : price - TakeProfit * Point * 10;

int ticket = OrderSend(Symbol(), cmd, LotSize, price, 3, sl, tp, "MA Crossover", MagicNumber, 0, clrNONE);

if(ticket < 0)
Print("OrderSend failed: ", GetLastError());
}

//+------------------------------------------------------------------+
//| Close all positions |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
bool close = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE);
if(!close)
Print("Close failed: ", GetLastError());
}
}
}
}

//+------------------------------------------------------------------+
//| Count positions |
//+------------------------------------------------------------------+
int CountPositions()
{
int count = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
count++;
}
}
return count;
}

//+------------------------------------------------------------------+
//| Trailing stop management |
//+------------------------------------------------------------------+
void TrailingStopManagement()
{
if(TrailingStop == 0) return;

for(int i = 0; i < OrdersTotal(); i++)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
double newSL = 0;
if(OrderType() == OP_BUY)
{
newSL = Bid - TrailingStop * Point * 10;
if(newSL > OrderStopLoss())
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
else if(OrderType() == OP_SELL)
{
newSL = Ask + TrailingStop * Point * 10;
if(newSL < OrderStopLoss() || OrderStopLoss() == 0)
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrNONE);
}
}
}
}
}
//+------------------------------------------------------------------+
```

Parameter Explanation



| Parameter | Description |
|-----------|-------------|
| LotSize | Trading volume per order (0.01 to 100) |
| FastMAPeriod | Fast moving average period (recommended 5-14) |
| SlowMAPeriod | Slow moving average period (recommended 20-50) |
| MAType | MODE_SMA (simple) or MODE_EMA (exponential) |
| MAPrice | PRICE_CLOSE, PRICE_OPEN, PRICE_HIGH, PRICE_LOW |
| StopLoss | Stop loss distance in pips |
| TakeProfit | Take profit distance in pips |
| TrailingStop | Trailing stop distance (0 to disable) |
| MagicNumber | Unique identifier for EA trades |

Installation & Usage



1. Copy the code into MetaEditor (F4 in MT4)
2. Click Compile (F7) - ensure no errors
3. Attach EA to a chart in MT4
4. Adjust parameters in the Inputs tab
5. Enable AutoTrading (Alt+T)

Compilation Tips



  • Ensure `#property strict` is included

  • Check that all variables are declared before use

  • Use `Point * 10` for pip calculation on 5-digit brokers

  • Test on demo account before live trading


  • Reference



    This EA source code is independently compiled and tested. Based on standard moving average crossover strategy principles common in algorithmic trading.

    *For advanced EA strategies with optimized entry filters and risk management, check our premium EA collection with backtest reports.*