Make a forex EA code, for mt4+5
- User
Make a forex EA code, for mt4+5
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Make a forex EA code, for mt4+5
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is an example of a simple Forex Expert Advisor (EA) for both MetaTrader 4 (MT4) and MetaTrader 5 (MT5). This EA implements a basic Moving Average Crossover strategy:
Please note that automated trading involves significant risk, and you should thoroughly test any EA in a demo account before using it on a live account.
//+------------------------------------------------------------------+
//| MovingAverageEA.mq4 |
//| Developed by OpenAI's ChatGPT Assistant |
//+------------------------------------------------------------------+
#property copyright ""
#property link ""
#property version "1.00"
#property strict
// Input parameters
extern int FastMAPeriod = 12;
extern int SlowMAPeriod = 26;
extern double Lots = 0.1;
extern int Slippage = 3;
// Global variables
int ticket;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert de-initialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Ensure we only check on a new bar
static datetime lastTime = 0;
datetime currentTime = Time[0];
if (currentTime == lastTime)
return;
lastTime = currentTime;
// Calculate the moving averages
double FastMA = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
double SlowMA = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
double FastMA_Prev = iMA(NULL, 0, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
double SlowMA_Prev = iMA(NULL, 0, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
// Check for a bullish crossover
if (FastMA_Prev < SlowMA_Prev && FastMA > SlowMA)
{
// Close any sell orders
CloseOrders(OP_SELL);
// Open a buy order if there are no open positions
if (OrdersTotal() == 0)
OpenOrder(OP_BUY);
}
// Check for a bearish crossover
else if (FastMA_Prev > SlowMA_Prev && FastMA < SlowMA)
{
// Close any buy orders
CloseOrders(OP_BUY);
// Open a sell order if there are no open positions
if (OrdersTotal() == 0)
OpenOrder(OP_SELL);
}
}
//+------------------------------------------------------------------+
//| Function to open orders |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double price = (orderType == OP_BUY) ? Ask : Bid;
int slippage = Slippage;
double lots = Lots;
string comment = "MovingAverageEA";
ticket = OrderSend(Symbol(), orderType, lots, price, slippage, 0, 0, comment, 0, 0, clrGreen);
if (ticket < 0)
Print("OrderSend failed with error #", GetLastError());
}
//+------------------------------------------------------------------+
//| Function to close orders |
//+------------------------------------------------------------------+
void CloseOrders(int orderType)
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderMagicNumber() == 0 && OrderSymbol() == Symbol() && OrderType() == orderType)
{
double price = (orderType == OP_BUY) ? Bid : Ask;
bool result = OrderClose(OrderTicket(), OrderLots(), price, Slippage, clrRed);
if (!result)
Print("OrderClose failed with error #", GetLastError());
}
}
}
}
Input Parameters:
FastMAPeriod: Period for the fast moving average.SlowMAPeriod: Period for the slow moving average.Lots: The trading volume for each order.Slippage: Maximum acceptable slippage in pips.OnInit(): Called when the EA is initialized. Currently, it does not perform any actions and returns INIT_SUCCEEDED.
OnTick(): This function is called on every tick (price change). However, we want our EA to act only when a new bar (candle) forms, so we check if the time has changed.
Calculating Moving Averages:
Signal Generation:
Order Management Functions:
For MT4 Users:
For MT5 Users:
Adjust Settings:
FastMAPeriod, SlowMAPeriod, Lots, Slippage) as needed.Testing:
Risk Management:
Broker Compatibility:
Market Conditions:
Further Enhancements:
The provided Expert Advisor is for educational purposes only. Trading foreign exchange on margin carries a high level of risk, and may not be suitable for all investors. Before deciding to trade foreign exchange, you should carefully consider your investment objectives, level of experience, and risk appetite. Any action you take upon the information provided is strictly at your own risk, and we will not be liable for any losses or damages in connection with the use of this EA.
Feel free to customize and enhance the EA according to your trading strategies and risk management preferences. If you have any questions or need further assistance, please let me know!
Not yet included in a published release.
//+------------------------------------------------------------------+
//| MovingAverageEA.mq5 |
//| Developed by OpenAI's ChatGPT Assistant |
//+------------------------------------------------------------------+
#property copyright ""
#property link ""
#property version "1.00"
#property strict
// Input parameters
input int FastMAPeriod = 12;
input int SlowMAPeriod = 26;
input double Lots = 0.1;
input int Slippage = 3;
// Global variables
ulong ticket;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert de-initialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Ensure we only check on a new bar
static datetime lastTime = 0;
MqlRates rates[];
ArraySetAsSeries(rates, true);
int copied = CopyRates(Symbol(), Period(), 0, 2, rates);
if (copied < 2)
return;
datetime currentTime = rates[0].time;
if (currentTime == lastTime)
return;
lastTime = currentTime;
// Calculate the moving averages
double FastMA[], SlowMA[];
CopyBuffer(iMA(Symbol(), Period(), FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE), 0, 0, 2, FastMA);
CopyBuffer(iMA(Symbol(), Period(), SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE), 0, 0, 2, SlowMA);
if (ArraySize(FastMA) < 2 || ArraySize(SlowMA) < 2)
return;
double FastMA_Current = FastMA[0];
double SlowMA_Current = SlowMA[0];
double FastMA_Previous = FastMA[1];
double SlowMA_Previous = SlowMA[1];
// Check for a bullish crossover
if (FastMA_Previous < SlowMA_Previous && FastMA_Current > SlowMA_Current)
{
// Close any sell positions
ClosePositions(POSITION_TYPE_SELL);
// Open a buy position if there are no open positions
if (PositionsTotal() == 0)
OpenPosition(ORDER_TYPE_BUY);
}
// Check for a bearish crossover
else if (FastMA_Previous > SlowMA_Previous && FastMA_Current < SlowMA_Current)
{
// Close any buy positions
ClosePositions(POSITION_TYPE_BUY);
// Open a sell position if there are no open positions
if (PositionsTotal() == 0)
OpenPosition(ORDER_TYPE_SELL);
}
}
//+------------------------------------------------------------------+
//| Function to open positions |
//+------------------------------------------------------------------+
void OpenPosition(EnumOrderType orderType)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.type = orderType;
request.volume = Lots;
request.price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
request.slippage = Slippage;
request.magic = 0;
request.deviation= Slippage;
request.type_filling = ORDER_FILLING_IOC;
request.type_time = ORDER_TIME_GTC;
if (!OrderSend(request, result))
Print("OrderSend failed with result: ", result.retcode);
else if (result.retcode != 10009) // 10009 - Request is completed
Print("OrderSend failed with retcode: ", result.retcode);
}
//+------------------------------------------------------------------+
//| Function to close positions |
//+------------------------------------------------------------------+
void ClosePositions(ENUM_POSITION_TYPE positionType)
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetSymbol(i) == Symbol() && PositionGetInteger(POSITION_TYPE) == positionType)
{
ulong ticket = PositionGetInteger(POSITION_TICKET);
double volume = PositionGetDouble(POSITION_VOLUME);
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_DEAL;
request.symbol = Symbol();
request.position = ticket;
request.volume = volume;
request.type = (positionType == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
request.price = (request.type == ORDER_TYPE_BUY) ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
request.slippage = Slippage;
request.magic = 0;
request.deviation= Slippage;
request.type_filling = ORDER_FILLING_IOC;
request.type_time = ORDER_TIME_GTC;
if (!OrderSend(request, result))
Print("OrderSend failed with result: ", result.retcode);
else if (result.retcode != 10009) // 10009 - Request is completed
Print("OrderSend failed with retcode: ", result.retcode);
}
}
}