Make a forex EA, for mt4+5
- User
Make a forex EA, for mt4+5
- Assistant
Make a forex EA, for mt4+5
Creating a Forex Expert Advisor (EA) for MetaTrader 4 (MT4) and MetaTrader 5 (MT5) involves writing scripts in MQL4 and MQL5, respectively. Below, I'll provide a simple example of an EA based on a Moving Average Crossover strategy for both platforms. This strategy buys when a short-term moving average crosses above a long-term moving average and sells when the opposite occurs.
//+------------------------------------------------------------------+
//| SimpleMA_EA.mq4 |
//| Copyright 2023, YourName. |
//| https://www.yourwebsite.com |
//+------------------------------------------------------------------+
#property strict
//--- input parameters
input int FastMAPeriod = 10;
input int SlowMAPeriod = 30;
input double LotSize = 0.1;
input int Slippage = 3;
//--- global variables
double FastMA_Previous, FastMA_Current;
double SlowMA_Previous, SlowMA_Current;
//+------------------------------------------------------------------+
//| 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()
{
// Calculate Moving Averages
FastMA_Previous = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
FastMA_Current = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
SlowMA_Previous = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
SlowMA_Current = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
// Check for a Buy signal
if (FastMA_Previous < SlowMA_Previous && FastMA_Current > SlowMA_Current)
{
// Close any existing Sell orders
CloseOrders(OP_SELL);
// Open a Buy order
OrderSend(Symbol(), OP_BUY, LotSize, Ask, Slippage, 0, 0, "Buy Order", MAGIC_NUMBER, 0, clrGreen);
}
// Check for a Sell signal
if (FastMA_Previous > SlowMA_Previous && FastMA_Current < SlowMA_Current)
{
// Close any existing Buy orders
CloseOrders(OP_BUY);
// Open a Sell order
OrderSend(Symbol(), OP_SELL, LotSize, Bid, Slippage, 0, 0, "Sell Order", MAGIC_NUMBER, 0, clrRed);
}
}
//+------------------------------------------------------------------+
//| Function to close orders of a specific type |
//+------------------------------------------------------------------+
void CloseOrders(int type)
{
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(OrderSelect(i, SELECT_BY_POS) && OrderType() == type && OrderSymbol() == Symbol())
{
bool result;
if(type == OP_BUY)
result = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clrYellow);
else
result = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, clrYellow);
}
}
}
//+------------------------------------------------------------------+
Explanation:
Input Parameters:
FastMAPeriod: Period for the fast (short-term) moving average.SlowMAPeriod: Period for the slow (long-term) moving average.LotSize: Size of the trade.Slippage: Maximum allowed slippage.OnTick Function:
CloseOrders Function:
OP_BUY or OP_SELL).Magic Number:
MAGIC_NUMBER to identify orders opened by this EA, especially when running multiple EAs on the same account. Add input int MAGIC_NUMBER = 123456; at the beginning and replace MAGIC_NUMBER in OrderSend with the input variable.//+------------------------------------------------------------------+
//| SimpleMA_EA.mq5 |
//| Copyright 2023, YourName. |
//| https://www.yourwebsite.com |
//+------------------------------------------------------------------+
#property strict
//--- input parameters
input int FastMAPeriod = 10;
input int SlowMAPeriod = 30;
input double LotSize = 0.1;
input int Slippage = 3;
//--- global variables
double FastMA_Previous, FastMA_Current;
double SlowMA_Previous, SlowMA_Current;
//+------------------------------------------------------------------+
//| 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()
{
// Calculate Moving Averages
FastMA_Previous = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
FastMA_Current = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
SlowMA_Previous = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
SlowMA_Current = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
// Check for a Buy signal
if (FastMA_Previous < SlowMA_Previous && FastMA_Current > SlowMA_Current)
{
// Close any existing Sell positions
ClosePositions(ORDER_TYPE_SELL);
// Open a Buy position
OpenPosition(ORDER_TYPE_BUY);
}
// Check for a Sell signal
if (FastMA_Previous > SlowMA_Previous && FastMA_Current < SlowMA_Current)
{
// Close any existing Buy positions
ClosePositions(ORDER_TYPE_BUY);
// Open a Sell position
OpenPosition(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Function to close positions of a specific type |
//+------------------------------------------------------------------+
void ClosePositions(int type)
{
for(int i=PositionsTotal()-1;i>=0;i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_TYPE) == type && PositionGetString(POSITION_SYMBOL) == Symbol())
{
double price = (type == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double volume = PositionGetDouble(POSITION_VOLUME);
if(!PositionClose(ticket, volume, price, Slippage))
Print("Failed to close position: ", GetLastError());
}
}
}
}
//+------------------------------------------------------------------+
//| Function to open a position |
//+------------------------------------------------------------------+
void OpenPosition(int type)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = _Symbol;
request.volume = LotSize;
request.deviation= Slippage;
request.magic = 123456; // Define a unique magic number
request.type = type;
request.price = (type == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
request.sl = 0; // You can set Stop Loss
request.tp = 0; // You can set Take Profit
request.comment = "Simple MA Crossover EA";
if(!OrderSend(request, result))
{
Print("OrderSend failed: ", result.retcode);
}
else
{
Print("OrderSend succeeded: ", result.order);
}
}
//+------------------------------------------------------------------+
Explanation:
Input Parameters:
OnTick Function:
ClosePositions Function:
ORDER_TYPE_BUY or ORDER_TYPE_SELL).OpenPosition Function:
Magic Number:
magic number to identify positions opened by this EA.Backtesting:
Optimization:
Risk Management:
Error Handling:
Magic Number:
Broker Compatibility:
MetaTrader 4 (MT4):
.mq4 file (e.g., SimpleMA_EA.mq4) and paste the MT4 code above.MetaTrader 5 (MT5):
.mq5 file (e.g., SimpleMA_EA.mq5) and paste the MT5 code above.Advanced Strategies:
Money Management:
Logging and Notifications:
Trailing Stop:
The provided EA examples are for educational purposes only. Trading involves significant risk, and it's possible to lose more than your initial investment. Always test any EA extensively in a demo account before considering deployment on a live account. Consult with a financial advisor if you're unsure about trading strategies or their suitability for your financial situation.