//+------------------------------------------------------------------+
//| 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
User
me entregue o codigo completo
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);
// Verifica se existe uma posição aberta
if (orderOpened && PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
// Fecha a ordem se o lucro atingir o threshold definido
if (positionProfit >= takeProfitThreshold) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada com lucro: ", positionProfit);
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Se a tendência mudar, fecha a ordem
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
}
coloque uma configuração que acada 1.00 de lucro seja encerrada a operação
Para implementar um ajuste no código que feche automaticamente as posições abertas sempre que o lucro atingir ou ultrapassar 1.00, você precisa fazer uma pequena modificação na lógica de fechamento de posições dentro da função ExecuteTradingOnM5. Atualmente, a função fecha a ordem quando o lucro alcança o valor definido em takeProfitThreshold, que está configurado como 0.50. Vamos mudar isso para 1.00 e garantir que a posição seja fechada quando o lucro atinge 1.00 ou mais.
Aqui está a modificação necessária:
cpp
//+------------------------------------------------------------------+
//| 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[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, slowSmaM5) <= 0) {
Print("Erro ao copiar buffers de SMA para M5: ", GetLastError());
return;
}
double priceCloseM5 = iClose(_Symbol, PERIOD_M5, 0);
// Verifica se existe uma posição aberta
if (orderOpened && PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
// Fecha a ordem se o lucro atingir 1.00
if (positionProfit >= 1.00) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada com lucro >= 1.00: ", positionProfit);
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Se a tendência mudar, fecha a ordem
if ((positionType == POSITION_TYPE_BUY && trend == -1) || (positionType == POSITION_TYPE_SELL && trend == 1)) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem existente fechada devido à mudança de tendência.");
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());
}
}
}
}
A alteração principal foi a linha condicionando o fechamento da ordem ao lucro exceder ou igualar a 1.00. Removemos o uso do parâmetro takeProfitThreshold nessa parte para simplificar o controle baseado diretamente no valor requisitado (1.00), mas você pode ajustar o valor diretamente ao seu critério.
me entregue ocodigo completo com a alteração:
#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;
input double takeProfitThreshold = 0.50; // Valor de lucro em R$ para fechar a ordem
//+------------------------------------------------------------------+
//| 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);
// Verifica se existe uma posição aberta
if (orderOpened && PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
// Fecha a ordem se o lucro atingir o threshold definido
if (positionProfit >= takeProfitThreshold) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada com lucro: ", positionProfit);
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Se a tendência mudar, fecha a ordem
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 a alteração solicitada para fechar a posição quando o lucro atinge ou excede 1.00:
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;
// input double takeProfitThreshold = 0.50; // Valor de lucro em R$ para fechar a ordem - não é mais necessário
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[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);
// Verifica se existe uma posição aberta
if (orderOpened && PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
// Fecha a ordem se o lucro atingir 1.00
if (positionProfit >= 1.00) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada com lucro >= 1.00: ", positionProfit);
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Se a tendência mudar, fecha a ordem
if ((positionType == POSITION_TYPE_BUY && trend == -1) || (positionType == POSITION_TYPE_SELL && trend == 1)) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem existente fechada devido à mudança de tendência.");
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
}
Alteração Principal: Removi a variável takeProfitThreshold que não é mais necessária, e na função ExecuteTradingOnM5, agora ela verifica diretamente se positionProfit >= 1.00 para fechar a posição.
Aqui está o código completo, incorporando a alteração para fechar a operação quando o lucro atinge ou ultrapassa 1.00:
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[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);
// Verifica se existe uma posição aberta
if (orderOpened && PositionSelect(_Symbol)) {
long positionType = PositionGetInteger(POSITION_TYPE);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
// Fecha a ordem se o lucro atingir ou ultrapassar 1.00
if (positionProfit >= 1.00) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem fechada com lucro >= 1.00: ", positionProfit);
orderOpened = false;
orderTicket = 0;
} else {
Print("Erro ao fechar ordem: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Se a tendência mudar, fecha a ordem
if ((positionType == POSITION_TYPE_BUY && trend == -1) || (positionType == POSITION_TYPE_SELL && trend == 1)) {
if (trade.PositionClose(_Symbol)) {
Print("Ordem existente fechada devido à mudança de tendência.");
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
}
Neste código, a operação será fechada quando o lucro da posição atingir ou ultrapassar 1.00, conforme especificado na função ExecuteTradingOnM5. Certifique-se de que o ambiente de execução do seu código suporte as funções e classes utilizadas, como CTrade.