//+------------------------------------------------------------------+
//| Função para determinar a tendência com base no gráfico H1 |
//+------------------------------------------------------------------+
int DetermineTrendOnH1() {
double fastSmaH1[2], slowSmaH1[2];
int fastSmaHandleH1 = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleH1 = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
code
if (CopyBuffer(fastSmaHandleH1, 0, 0, 2, fastSmaH1) <= 0 || CopyBuffer(slowSmaHandleH1, 0, 0, 2, slowSmaH1) <= 0) {
Print("Erro ao copiar buffers de SMA para H1: ", GetLastError());
return 0;
}
if (fastSmaH1[1] > slowSmaH1[1]) {
return 1; // Tendência de alta
} else if (fastSmaH1[1] < slowSmaH1[1]) {
return -1; // Tendência de baixa
}
return 0; // Sem tendência clara
}
//+------------------------------------------------------------------+
//| Execução de operações no gráfico M5 com base na tendência H1 |
//+------------------------------------------------------------------+
void ExecuteTradingOnM5(int trend) {
double ask, bid;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter preços Ask ou Bid: ", GetLastError());
return;
}
Assistant
User
Assistant
code
double spread = (ask - bid) / _Point;
if (spread < 0 || spread > 200) {
Print("Spread fora do intervalo aceitável: ", spread);
return;
}
double fastSmaM5[1], slowSmaM5[1];
int fastSmaHandleM5 = iMA(_Symbol, PERIOD_M5, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleM5 = iMA(_Symbol, PERIOD_M5, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandleM5, 0, 0, 1, fastSmaM5) <= 0 || CopyBuffer(slowSmaHandleM5, 0, 0, 1, slowSmaM5) <= 0) {
Print("Erro ao copiar buffers de SMA para M5: ", GetLastError());
return;
}
double priceCloseM5 = iClose(_Symbol, PERIOD_M5, 0);
if (orderOpened) {
if (PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
if ((positionType == POSITION_TYPE_BUY && trend == -1) || (positionType == POSITION_TYPE_SELL && trend == 1)) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
// Condições para abrir uma ordem alinhada à tendência de H1
if (!orderOpened && trend != 0) {
if (trend == 1 && fastSmaM5[0] > slowSmaM5[0] && priceCloseM5 > fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 - stopLossPoints * _Point;
if (trade.Buy(lotSize, _Symbol, ask, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
} else if (trend == -1 && fastSmaM5[0] < slowSmaM5[0] && priceCloseM5 < fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 + stopLossPoints * _Point;
if (trade.Sell(lotSize, _Symbol, bid, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick() {
double currentDailyProfit = GetDailyProfit();
if (currentDailyProfit >= dailyProfitTarget) {
Print("Meta de lucro diário alcançada: ", currentDailyProfit);
return;
}
code
int trend = DetermineTrendOnH1(); // Determina a tendência no H1
ExecuteTradingOnM5(trend); // Executa operações apenas em M5
}
O robo precisa fechar a ordem Caso em M5 a media de 20 rompa a media de 200 mesmo que em H1 esteja na mesa tendencia e somente volte a abrir a ordem novamente em M5 para o mesmo sentido que em H1
Para ajustar o robô para que ele feche a ordem se a média móvel de 20 períodos (fastSmaM5) romper a média móvel de 200 períodos (slowSmaM5) no gráfico M5, mesmo que a tendência em H1 permaneça no mesmo sentido, você pode modificar o código da função ExecuteTradingOnM5. Vou explicar o que precisa ser alterado:
Adicionar uma verificação adicional no trecho onde verificamos as médias móveis em M5: Precisaremos adicionar uma lógica que feche a posição caso a média rápida cruze a média lenta no gráfico M5, independentemente da tendência em H1.
Ajustar as condições de reabertura: Uma vez que a ordem é fechada em M5 devido a esse cruzamento contrário, a abertura de uma nova ordem deve esperar até que as condições sejam satisfeitas novamente em alinhamento com M1 e M5.
Aqui está uma versão ajustada do método ExecuteTradingOnM5:
cpp
void ExecuteTradingOnM5(int trend) {
double ask, bid;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter preços Ask ou Bid: ", GetLastError());
return;
}
double spread = (ask - bid) / _Point;
if (spread < 0 || spread > 200) {
Print("Spread fora do intervalo aceitável: ", spread);
return;
}
double fastSmaM5[2], slowSmaM5[2];
int fastSmaHandleM5 = iMA(_Symbol, PERIOD_M5, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleM5 = iMA(_Symbol, PERIOD_M5, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandleM5, 0, 0, 2, fastSmaM5) <= 0 || CopyBuffer(slowSmaHandleM5, 0, 0, 2, slowSmaM5) <= 0) {
Print("Erro ao copiar buffers de SMA para M5: ", GetLastError());
return;
}
double priceCloseM5 = iClose(_Symbol, PERIOD_M5, 0);
if (orderOpened) {
if (PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
// Fecha a ordem se as médias móveis de M5 cruzarem contrário
if ((positionType == POSITION_TYPE_BUY && fastSmaM5[0] < slowSmaM5[0]) ||
(positionType == POSITION_TYPE_SELL && fastSmaM5[0] > slowSmaM5[0])) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada devido ao cruzamento das SMAs em M5.");
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
// Condições para abrir uma ordem alinhada à tendência de H1
// O robô abrirá uma nova ordem apenas se não houver ordens abertas
if (!orderOpened && trend != 0) {
if (trend == 1 && fastSmaM5[0] > slowSmaM5[0] && priceCloseM5 > fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 - stopLossPoints * _Point;
if (trade.Buy(lotSize, _Symbol, ask, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
} else if (trend == -1 && fastSmaM5[0] < slowSmaM5[0] && priceCloseM5 < fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 + stopLossPoints * _Point;
if (trade.Sell(lotSize, _Symbol, bid, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
Considerações:
Cruzamentos em M5: A adição desta regra garante que as ordens abertas estejam sempre de acordo com a direção desejada do cruzamento em M5.
Relação H1 & M5: A estratégia continua a utilizar H1 para determinar o viés de longo prazo, garantindo que a direção do trade a ser aberto está sempre alinhada a esta análise superior.
Robustez e Testes: Este ajuste adiciona qualquer complexidade adicional que precise ser testada num ambiente de simulação antes de ir ao mercado real.
me entregue o codigo completo com as modificações:
//+------------------------------------------------------------------+
//| Função para determinar a tendência com base no gráfico H1 |
//+------------------------------------------------------------------+
int DetermineTrendOnH1() {
double fastSmaH1[2], slowSmaH1[2];
int fastSmaHandleH1 = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleH1 = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
code
if (CopyBuffer(fastSmaHandleH1, 0, 0, 2, fastSmaH1) <= 0 || CopyBuffer(slowSmaHandleH1, 0, 0, 2, slowSmaH1) <= 0) {
Print("Erro ao copiar buffers de SMA para H1: ", GetLastError());
return 0;
}
if (fastSmaH1[1] > slowSmaH1[1]) {
return 1; // Tendência de alta
} else if (fastSmaH1[1] < slowSmaH1[1]) {
return -1; // Tendência de baixa
}
return 0; // Sem tendência clara
}
//+------------------------------------------------------------------+
//| Execução de operações no gráfico M5 com base na tendência H1 |
//+------------------------------------------------------------------+
void ExecuteTradingOnM5(int trend) {
double ask, bid;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter preços Ask ou Bid: ", GetLastError());
return;
}
code
double spread = (ask - bid) / _Point;
if (spread < 0 || spread > 200) {
Print("Spread fora do intervalo aceitável: ", spread);
return;
}
double fastSmaM5[1], slowSmaM5[1];
int fastSmaHandleM5 = iMA(_Symbol, PERIOD_M5, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleM5 = iMA(_Symbol, PERIOD_M5, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandleM5, 0, 0, 1, fastSmaM5) <= 0 || CopyBuffer(slowSmaHandleM5, 0, 0, 1, slowSmaM5) <= 0) {
Print("Erro ao copiar buffers de SMA para M5: ", GetLastError());
return;
}
double priceCloseM5 = iClose(_Symbol, PERIOD_M5, 0);
if (orderOpened) {
if (PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
if ((positionType == POSITION_TYPE_BUY && trend == -1) || (positionType == POSITION_TYPE_SELL && trend == 1)) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem existente fechada.");
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
// Condições para abrir uma ordem alinhada à tendência de H1
if (!orderOpened && trend != 0) {
if (trend == 1 && fastSmaM5[0] > slowSmaM5[0] && priceCloseM5 > fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 - stopLossPoints * _Point;
if (trade.Buy(lotSize, _Symbol, ask, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
} else if (trend == -1 && fastSmaM5[0] < slowSmaM5[0] && priceCloseM5 < fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 + stopLossPoints * _Point;
if (trade.Sell(lotSize, _Symbol, bid, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick() {
double currentDailyProfit = GetDailyProfit();
if (currentDailyProfit >= dailyProfitTarget) {
Print("Meta de lucro diário alcançada: ", currentDailyProfit);
return;
}
code
int trend = DetermineTrendOnH1(); // Determina a tendência no H1
ExecuteTradingOnM5(trend); // Executa operações apenas em M5
}
Aqui está o código completo com as modificações para que o robô feche a ordem se a média móvel de 20 períodos (fastSmaM5) cruzar a média móvel de 200 períodos (slowSmaM5) no gráfico M5, mesmo que a tendência no gráfico H1 esteja no mesmo sentido. Assim, ele só abrirá uma nova ordem quando as condições estiverem novamente satisfeitas de acordo com a tendência de H1 e o cruzamento em M5.
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.01;
input int fastSmaPeriod = 20;
input int slowSmaPeriod = 200;
input double stopLossPoints = 65000.0;
input double dailyProfitTarget = 100.0;
bool orderOpened = false;
ulong orderTicket = 0;
CTrade trade;
//+------------------------------------------------------------------+
//| Função para obter o lucro diário atual |
//+------------------------------------------------------------------+
double GetDailyProfit() {
double profit = 0.0;
MqlDateTime today;
TimeToStruct(TimeCurrent(), today);
for (int i = 0; i < HistoryDealsTotal(); i++) {
ulong dealTicket = HistoryDealGetTicket(i);
datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
MqlDateTime closeTimeStruct;
TimeToStruct(closeTime, closeTimeStruct);
if (closeTimeStruct.day == today.day && closeTimeStruct.mon == today.mon && closeTimeStruct.year == today.year) {
profit += HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
}
}
return profit;
}
//+------------------------------------------------------------------+
//| Função para determinar a tendência com base no gráfico H1 |
//+------------------------------------------------------------------+
int DetermineTrendOnH1() {
double fastSmaH1[2], slowSmaH1[2];
int fastSmaHandleH1 = iMA(_Symbol, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleH1 = iMA(_Symbol, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandleH1, 0, 0, 2, fastSmaH1) <= 0 || CopyBuffer(slowSmaHandleH1, 0, 0, 2, slowSmaH1) <= 0) {
Print("Erro ao copiar buffers de SMA para H1: ", GetLastError());
return 0;
}
if (fastSmaH1[1] > slowSmaH1[1]) {
return 1; // Tendência de alta
} else if (fastSmaH1[1] < slowSmaH1[1]) {
return -1; // Tendência de baixa
}
return 0; // Sem tendência clara
}
//+------------------------------------------------------------------+
//| Execução de operações no gráfico M5 com base na tendência H1 |
//+------------------------------------------------------------------+
void ExecuteTradingOnM5(int trend) {
double ask, bid;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter preços Ask ou Bid: ", GetLastError());
return;
}
double spread = (ask - bid) / _Point;
if (spread < 0 || spread > 200) {
Print("Spread fora do intervalo aceitável: ", spread);
return;
}
double fastSmaM5[2], slowSmaM5[2];
int fastSmaHandleM5 = iMA(_Symbol, PERIOD_M5, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
int slowSmaHandleM5 = iMA(_Symbol, PERIOD_M5, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE);
if (CopyBuffer(fastSmaHandleM5, 0, 0, 2, fastSmaM5) <= 0 || CopyBuffer(slowSmaHandleM5, 0, 0, 2, slowSmaM5) <= 0) {
Print("Erro ao copiar buffers de SMA para M5: ", GetLastError());
return;
}
double priceCloseM5 = iClose(_Symbol, PERIOD_M5, 0);
if (orderOpened) {
if (PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
// Fecha a ordem se as médias móveis de M5 cruzarem contrário
if ((positionType == POSITION_TYPE_BUY && fastSmaM5[0] < slowSmaM5[0]) ||
(positionType == POSITION_TYPE_SELL && fastSmaM5[0] > slowSmaM5[0])) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada devido ao cruzamento das SMAs em M5.");
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
// Condições para abrir uma ordem alinhada à tendência de H1
if (!orderOpened && trend != 0) {
if (trend == 1 && fastSmaM5[0] > slowSmaM5[0] && priceCloseM5 > fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 - stopLossPoints * _Point;
if (trade.Buy(lotSize, _Symbol, ask, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de compra aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
} else if (trend == -1 && fastSmaM5[0] < slowSmaM5[0] && priceCloseM5 < fastSmaM5[0]) {
double stopLossPrice = priceCloseM5 + stopLossPoints * _Point;
if (trade.Sell(lotSize, _Symbol, bid, stopLossPrice)) {
orderTicket = trade.ResultOrder();
orderOpened = true;
Print("Ordem de venda aberta! Ticket: ", orderTicket);
} else {
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick() {
double currentDailyProfit = GetDailyProfit();
if (currentDailyProfit >= dailyProfitTarget) {
Print("Meta de lucro diário alcançada: ", currentDailyProfit);
return;
}
int trend = DetermineTrendOnH1(); // Determina a tendência no H1
ExecuteTradingOnM5(trend); // Executa operações apenas em M5
}
O que foi alterado:
Fechamento Forçado: O robô agora fecha a ordem se detectar um cruzamento adverso entre as médias móveis de 20 e 200 períodos no M5, mesmo que a tendência em H1 se mantenha.
Abertura Condicional: A abertura de novas ordens permanece dependente do alinhamento das condições estabelecidas tanto em H1 quanto em M5.
Estruturação do Código: As variáveis e chamadas de função são revisadas para garantir a execução correta dos trades baseados nas novas condições.
Certifique-se de testar o robô em um ambiente de simulação para garantir que ele se comporte conforme esperado antes de usá-lo em uma conta real.