Criar um Expert Advisor (EA) em MQL5 com base em cruzamentos de médias móveis e preços é uma ótima ideia para automatizar estratégias de trading. Vamos implementar um EA baseado nas suas especificações.
Aqui está um exemplo básico do código MQL5 que segue suas regras:
//+------------------------------------------------------------------+
//| SimpleCrossEA.mq5 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property strict
// Input parameters
input double LotSize = 0.1;
input int TakeProfitPips = 20;
input int StopLossPips = 400;
input int TrailingStopPips = 10;
// Indicators handles
int EMA20Handle;
int SMA200Handle;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Create handles for moving averages
EMA20Handle = iMA(NULL, 0, 20, 0, MODE_EMA, PRICE_CLOSE);
SMA200Handle = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE);
if (EMA20Handle == INVALID_HANDLE || SMA200Handle == INVALID_HANDLE)
{
Print("Error creating indicator handles");
return INIT_FAILED;
}
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Release indicator handles
IndicatorRelease(EMA20Handle);
IndicatorRelease(SMA200Handle);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Get current and previous prices of moving averages
double EMA20Current = iMA(NULL, 0, 20, 0, MODE_EMA, PRICE_CLOSE, 0);
double EMA20Previous = iMA(NULL, 0, 20, 0, MODE_EMA, PRICE_CLOSE, 1);
double SMA200Current = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE, 0);
double SMA200Previous = iMA(NULL, 0, 200, 0, MODE_SMA, PRICE_CLOSE, 1);
// Current close price
double currentPrice = Close[0];
// Check for buy condition
if (EMA20Current > SMA200Current && currentPrice > SMA200Current)
{
bool crossedAboveFound = CheckCrossAbove(SMA200Current, 2);
if (crossedAboveFound)
{
CloseOrders(ORDER_TYPE_SELL);
OpenOrder(ORDER_TYPE_BUY);
}
}
// Check for sell condition
if (EMA20Current < SMA200Current && currentPrice < SMA200Current)
{
bool crossedBelowFound = CheckCrossBelow(SMA200Current, 2);
if (crossedBelowFound)
{
CloseOrders(ORDER_TYPE_BUY);
OpenOrder(ORDER_TYPE_SELL);
}
}
// Check for trailing stop
CheckTrailingStop();
}
//+------------------------------------------------------------------+
//| Close existing orders |
//+------------------------------------------------------------------+
void CloseOrders(int orderType)
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS) && OrderType() == orderType)
{
OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrRed);
}
}
}
//+------------------------------------------------------------------+
//| Open a new order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double sl = (orderType == ORDER_TYPE_BUY) ? currentPrice - StopLossPips * Point : currentPrice + StopLossPips * Point;
double tp = (orderType == ORDER_TYPE_BUY) ? currentPrice + TakeProfitPips * Point : currentPrice - TakeProfitPips * Point;
OrderSend(Symbol(), orderType, LotSize, currentPrice, 3, sl, tp, "My Expert Advisor", 0, 0, clrBlue);
}
//+------------------------------------------------------------------+
//| Check if the price has crossed above a given level for N bars |
//+------------------------------------------------------------------+
bool CheckCrossAbove(double level, int bars)
{
for (int i = 1; i <= bars; i++)
{
if (Close[i] < level)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check if the price has crossed below a given level for N bars |
//+------------------------------------------------------------------+
bool CheckCrossBelow(double level, int bars)
{
for (int i = 1; i <= bars; i++)
{
if (Close[i] > level)
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Check and apply trailing stop |
//+------------------------------------------------------------------+
void CheckTrailingStop()
{
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS))
{
double newSL;
if (OrderType() == ORDER_TYPE_BUY)
{
newSL = OrderOpenPrice() + TrailingStopPips * Point;
if (newSL > OrderStopLoss())
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrBlue);
}
else if (OrderType() == ORDER_TYPE_SELL)
{
newSL = OrderOpenPrice() - TrailingStopPips * Point;
if (newSL < OrderStopLoss())
OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrRed);
}
}
}
}
Explicação Rápida:
- Inicialização: As médias móveis são inicializadas com as configurações fornecidas.
- Abertura de Ordem: As regras são verificadas a cada tick para decidir se devem ser abertas posições de compra ou venda.
- Fechamento de Ordem: Antes de abrir uma nova posição, qualquer posição existente no sentido oposto é fechada.
- Trailing Stop: Ajusta o
stop loss à medida que o preço se move a favor da posição para proteger os ganhos.
- CheckCrossAbove/CrossBelow: Funções que verificam se o preço cruzou a média e fechou em determinado nível por um número específico de barras.
Atenção:
- Teste essa estratégia em uma conta demo antes de usá-la em uma conta real para entender completamente seu comportamento.
- Este é um modelo básico e deve ser modificado conforme suas necessidades específicas.
- Certifique-se de que o código está alinhado com as regulamentações de trading da sua corretora.