me entregue o codigo completo com as novas implementações: #include <Trade\Trade.mqh>…
- User
me entregue o codigo completo com as novas implementações:
#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 = 1000.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);
if (orderOpened) { if (PositionSelect(_Symbol)) { long positionType = PositionGetInteger(POSITION_TYPE); if ((positionType == POSITION_TYPE_BUY && (trend == -1 || fastSmaM5[0] < slowSmaM5[0])) || (positionType == POSITION_TYPE_SELL && (trend == 1 || fastSmaM5[0] > slowSmaM5[0]))) { 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; }
int trend = DetermineTrendOnH1(); // Determina a tendência no H1 ExecuteTradingOnM5(trend); // Executa operações apenas em M5 }
preciso que o robo fecha a cada lucro obtido de 100 pontos mas continuar as operações logo em seguida!
- Assistant
Para implementar a funcionalidade de fechamento de uma operação a cada lucro de 100 pontos, mas continuar operando, precisamos adicionar uma verificação do lucro após cada operação. Vou incorporar essa funcionalidade em seu código:
#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 = 1000.0; input double profitPointsTarget = 100.0; // Novo input para determinar o lucro em pontos 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 obter lucro em pontos de uma posição aberta | //+------------------------------------------------------------------+ double GetPositionProfitPoints() { if (PositionSelect(_Symbol)) { double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK); return (currentPrice - openPrice) / _Point; } return 0.0; } //+------------------------------------------------------------------+ //| 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); if (orderOpened) { if (PositionSelect(_Symbol)) { // Adicionando verificação de lucro em pontos if (GetPositionProfitPoints() >= profitPointsTarget) { if (trade.PositionClose(_Symbol)) { Print("Ordem fechada após atingir lucro de 100 pontos."); orderOpened = false; orderTicket = 0; } else { Print("Erro ao fechar ordem após atingir lucro: ", trade.ResultRetcode(), " - ", GetLastError()); } } else { long positionType = PositionGetInteger(POSITION_TYPE); if ((positionType == POSITION_TYPE_BUY && (trend == -1 || fastSmaM5[0] < slowSmaM5[0])) || (positionType == POSITION_TYPE_SELL && (trend == 1 || fastSmaM5[0] > slowSmaM5[0]))) { if (trade.PositionClose(_Symbol)) { Print("Ordem existente fechada devido à mudança de tendência."); orderOpened = false; orderTicket = 0; } else { Print("Erro ao fechar ordem devido à mudança de tendência: ", trade.ResultRetcode(), " - ", GetLastError()); } } } } } // Condições para abrir uma nova 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ções feitas:
-
Lucro em Pontos: Adicionei um novo input
profitPointsTarget, que define quantos pontos de lucro você deseja obter antes de fechar a operação (100 pontos, conforme solicitado). -
Função
GetPositionProfitPoints(): Esta função calcula o lucro atual de uma posição aberta em termos de pontos. -
Verificação de Lucro: Antes de fechar a operação por mudança de tendência, o código agora verifica se a posição atingiu o lucro de 100 pontos e a fecha se for o caso, continuando assim as operações.
-