Based on the provided code, I will recreate it in MQL4 (MetaQuotes Language 4) which is a programming language used for developing trading strategies and technical indicators for the MetaTrader 4 platform.
Here is the corrected code:
```mql4
//+------------------------------------------------------------------+
//| Script program starts function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Gold EA Initialized");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Script deinit function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print("Gold EA Deinitialized");
}
//+------------------------------------------------------------------+
//| OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
double ClosePrice = iClose(Symbol(), PERIOD_M5, 0);
double MACD = iMACD(Symbol(), PERIOD_M5, 12, 26, 9, PRICE_CLOSE, 0, 0, 0, 0, MODE_ALLGATOR, 0);
double MA20 = iMA(Symbol(), PERIOD_M5, 20, 0, MODE_SMA, PRICE_CLOSE, 0);
double MA50 = iMA(Symbol(), PERIOD_M5, 50, 0, MODE_SMA, PRICE_CLOSE, 0);
int signal = trading_strategy(ClosePrice, MACD, MA20, MA50);
static int position = 0;
static double StopLoss = 0;
static double TakeProfit = 0;
if (signal == 1 && position == 0)
{
position = 1;
StopLoss = ClosePrice - 20 * _Point;
TakeProfit = ClosePrice + 20 * _Point;
int ticket = OrderSend(Symbol(), OP_BUY, 0.1, ClosePrice, 3, StopLoss, TakeProfit, "Buy Order", 0, 0, Green);
if (ticket >= 0)
{
Print("Buy Order Placed Successfully, Ticket: ", ticket);
}
else
{
Print("Buy Order failed: Error Code = ", GetLastError());
position = 0;
}
}
else if (signal == -1 && position == 0)
{
position = -1;
StopLoss = ClosePrice + 20 * _Point;
TakeProfit = ClosePrice - 20 * _Point;
int ticket = OrderSend(Symbol(), OP_SELL, 0.1, ClosePrice, 3, StopLoss, TakeProfit, "Sell Order", 0, 0, Red);
if (ticket >= 0)
{
Print("Sell Order Placed Successfully, Ticket: ", ticket);
}
else
{
Print("Sell Order failed: Error Code = ", GetLastError());
position = 0;
}
}
update_position(position, StopLoss, TakeProfit);
}
//+------------------------------------------------------------------+
//| Trading strategy function |
//+------------------------------------------------------------------+
int trading_strategy(double ClosePrice, double MACD, double MA20, double MA50)
{
if (MACD > 0 && ClosePrice > MA20 && ClosePrice > MA50) return 1;
else if (MACD < 0 && ClosePrice < MA20 && ClosePrice < MA50) return -1;
else return 0;
}
//+------------------------------------------------------------------+
//| Update position function |
//+------------------------------------------------------------------+
void update_position(int pos, double StopLoss, double TakeProfit)
{
double currentPrice = iClose(Symbol(), PERIOD_H1, 0);
if (pos == 1)
{
if (currentPrice < StopLoss || currentPrice > TakeProfit)
{
ClosePosition(OP_BUY, StopLoss, TakeProfit);
}
}
else if (pos == -1)
{
if (currentPrice > StopLoss || currentPrice < TakeProfit)
{
ClosePosition(OP_SELL, StopLoss, TakeProfit);
}
}
}
//+------------------------------------------------------------------+
//| Close position function |
//+------------------------------------------------------------------+
void ClosePosition(int type, double StopLoss, double TakeProfit)
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS))
{
if (OrderType() == type)
{
bool closed = OrderClose(OrderTicket(), OrderLots(), MarketInfo(Symbol(), MODE_BID), 3, Violet);
if (!closed)
{
Print("Failed to close order: Error Code = ", GetLastError());
}
else
{
position = 0;
Print("Position Closed Successfully, Ticket: ", OrderTicket());
}
}
}
}
}
```
Resumen del código:
* La función `OnInit` se utiliza para inicializar la EA y se devuelve `INIT_SUCCEEDED` para indicar que la inicialización fue exitosa.
* La función `OnDeinit` se utiliza para desinicializar la EA y se imprime un mensaje para indicar que la desinicialización fue exitosa.
* La función `OnTick` se utiliza para evaluar la estrategia de trading en cada tick. Se calculan los precios de cierre, MACD, MA20 y MA50. Luego, se evalúa la señal de trading y se toma una decisión según la señal. Si la señal es de compra o venta, se envía una orden correspondiente y se actualiza la posición.
* La función `trading_strategy` se utiliza para evaluar la estrategia de trading y devuelve una señal de compra o venta según las condiciones de MACD y las medias móviles.
* La función `update_position` se utiliza para actualizar la posición y verificar si se debe cerrar la posición según los niveles de StopLoss y TakeProfit.
* La función `ClosePosition` se utiliza para cerrar una posición según el tipo de orden y los niveles de StopLoss y TakeProfit.
Justificación del lenguaje de programación:
Se utilizó MQL4 porque es el lenguaje de programación propio del MetaTrader 4, que es una plataforma de trading popular. MQL4 es específicamente diseñado para desarrollar estrategias de trading y indicadores técnicos para el mercado de divisas y otros mercados financieros.