Summary: Free MT4 EA source code implementing moving average crossover strategy. Includes full MQL4 code, parameter tuning guide, and compilation instructions for forex traders.




# Free MT4 EA Source Code: Moving Average Crossover Strategy

This article provides a complete, compilable MQL4 source code for a Moving Average Crossover Expert Advisor (EA). Perfect for beginners learning EA programming or traders wanting a customizable trend-following system.

Strategy Logic



The EA generates buy signals when a fast moving average (e.g., MA 5) crosses above a slow moving average (e.g., MA 20). Sell signals occur on the opposite cross. It includes fixed stop loss, take profit, and a simple money management option.

Complete MQL4 Source Code



```mql4
//+------------------------------------------------------------------+
//| MACrossoverEA.mq4 |
//| |
//| |
//+------------------------------------------------------------------+
#property copyright "自主编译"
#property link ""
#property version "1.00"
#property strict

//--- Input Parameters
input double LotSize = 0.1; // Lot size
input int FastMAPeriod = 5; // Fast MA period
input int SlowMAPeriod = 20; // Slow MA period
input int MAPrice = PRICE_CLOSE; // MA price: 0=CLOSE,1=OPEN,2=HIGH,3=LOW
input int MAMethod = MODE_SMA; // MA method: 0=SMA,1=EMA,2=LWMA
input int StopLoss = 50; // Stop loss in pips
input int TakeProfit = 100; // Take profit in pips
input int MagicNumber = 12345; // EA unique ID

//--- Global Variables
double fastMA, slowMA;
int ticket;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
if(StopLoss <= 0 || TakeProfit <= 0)
{
Print("Stop Loss and Take Profit must be positive values");
return(INIT_PARAMETERS_INCORRECT);
}
return(INIT_SUCCEEDED);
}

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

//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Calculate moving averages
fastMA = iMA(NULL, 0, FastMAPeriod, 0, MAMethod, MAPrice, 1);
slowMA = iMA(NULL, 0, SlowMAPeriod, 0, MAMethod, MAPrice, 1);
double fastMA_prev = iMA(NULL, 0, FastMAPeriod, 0, MAMethod, MAPrice, 2);
double slowMA_prev = iMA(NULL, 0, SlowMAPeriod, 0, MAMethod, MAPrice, 2);

// Check for open positions
if(CountOpenOrders() == 0)
{
// Buy signal: fast MA crosses above slow MA
if(fastMA_prev <= slowMA_prev && fastMA > slowMA)
{
OpenBuyOrder();
}
// Sell signal: fast MA crosses below slow MA
else if(fastMA_prev >= slowMA_prev && fastMA < slowMA)
{
OpenSellOrder();
}
}
}

//+------------------------------------------------------------------+
//| Open buy order function |
//+------------------------------------------------------------------+
void OpenBuyOrder()
{
double sl = 0, tp = 0;
if(StopLoss > 0)
sl = Ask - StopLoss * Point * 10;
if(TakeProfit > 0)
tp = Ask + TakeProfit * Point * 10;

ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "MA Crossover EA", MagicNumber, 0, clrGreen);
if(ticket < 0)
Print("Buy order failed: ", GetLastError());
}

//+------------------------------------------------------------------+
//| Open sell order function |
//+------------------------------------------------------------------+
void OpenSellOrder()
{
double sl = 0, tp = 0;
if(StopLoss > 0)
sl = Bid + StopLoss * Point * 10;
if(TakeProfit > 0)
tp = Bid - TakeProfit * Point * 10;

ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "MA Crossover EA", MagicNumber, 0, clrRed);
if(ticket < 0)
Print("Sell order failed: ", GetLastError());
}

//+------------------------------------------------------------------+
//| Count open orders by magic number |
//+------------------------------------------------------------------+
int CountOpenOrders()
{
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;
}
//+------------------------------------------------------------------+
```

Usage Instructions



1. Compile: Save the code as `MACrossoverEA.mq4` in `MQL4/Experts/` folder. Compile in MetaEditor (F7).
2. Attach to chart: Drag EA onto any MT4 chart (recommended: EURUSD, H1 timeframe).
3. Parameter tuning: Adjust FastMAPeriod, SlowMAPeriod, StopLoss, TakeProfit in Inputs tab.

Key Parameters Explained



| Parameter | Description | Recommended Range |
|-----------|-------------|-------------------|
| LotSize | Trade volume | 0.01 - 1.0 |
| FastMAPeriod | Fast moving average period | 3 - 10 |
| SlowMAPeriod | Slow moving average period | 14 - 50 |
| StopLoss | Stop loss distance in pips | 20 - 100 |
| TakeProfit | Take profit distance in pips | 50 - 200 |
| MagicNumber | Unique EA identifier | Any integer |

Compilation & Modification Tips



  • Compilation errors: Ensure `#property strict` is included. Check MT4 build compatibility.

  • Modify MA type: Change `MAMethod` to 1 (EMA) or 2 (LWMA).

  • Add trailing stop: Insert trailing stop logic in `OnTick()` after order selection.

  • Backtesting: Use MT4 Strategy Tester with 90% modeling quality.


  • Reference



  • 自主编译,基于MQL4官方文档标准语法

  • Moving Average concept from MetaQuotes Help: `iMA()` function reference


  • For advanced strategies and premium EA tools with full support, consider subscribing to our professional EA library.