converta em MQL4 e implemente para que quando o robo bater a meta estipulada pelo…
- User
converta em MQL4 e implemente para que quando o robo bater a meta estipulada pelo usuario por exemplo $1 dolar o robo encerre a operação em aberto:
#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 targetPartialProfit = 2.00; // Alvo de lucro para realizar parcial
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}
//+------------------------------------------------------------------+ //| Função para verificar se é necessário fazer parcial | //+------------------------------------------------------------------+ void CheckPartialProfit() { if (orderOpened && PositionSelect(_Symbol)) { double currentProfit = PositionGetDouble(POSITION_PROFIT); double lotSizeCurrent = PositionGetDouble(POSITION_VOLUME);
if (currentProfit >= targetPartialProfit) { double partialLotSize = lotSizeCurrent * 0.7; // Realiza 70% da posição if (trade.PositionClose(_Symbol, partialLotSize)) { Print("Parcial realizada. Lote: ", partialLotSize); orderOpened = true; // Mantém a ordem aberta } else { Print("Erro ao realizar parcial: ", trade.ResultRetcode(), " - ", GetLastError()); } } }}
//+------------------------------------------------------------------+ //| 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) { CheckPartialProfit(); // Verifica se é necessário fazer parcial 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; }
int trend = DetermineTrendOnH1(); // Determina a tendência no H1 ExecuteTradingOnM5(trend); // Executa operações apenas em M5}
- Assistant
Para converter o código MQL5 para MQL4 e implementar o fechamento das operações quando a meta de lucro diário é alcançada, você precisa ajustar algumas funcionalidades, pois algumas funções e métodos usados no MQL5 não estão disponíveis no MQL4. Vamos fazer as alterações necessárias:
-
Trocar as funções exclusivas do MQL5 por equivalentes do MQL4: Como
CTrade,PositionSelect,PositionGetDouble,PositionClose,PositionGetInteger, etc. -
Usar variáveis globais para gerenciar as operações: Em MQL4, você precisa lidar com dados de ordem através das funções de ordens embutidas.
Aqui está a implementação possível em MQL4:
//+------------------------------------------------------------------+ //| Inputs | //+------------------------------------------------------------------+ input double lotSize = 0.01; input int fastSmaPeriod = 20; input int slowSmaPeriod = 200; input double stopLossPoints = 65000.0; input double dailyProfitTarget = 1.00; // Meta de lucro em dólares input double targetPartialProfit = 2.00; //+------------------------------------------------------------------+ //| Variáveis Globais | //+------------------------------------------------------------------+ bool orderOpened = false; int orderTicket = 0; //+------------------------------------------------------------------+ //| Função para obter o lucro diário atual | //+------------------------------------------------------------------+ double GetDailyProfit() { double profit = 0.0; datetime today = iTime(NULL, PERIOD_D1, 0); for (int i = OrdersHistoryTotal() - 1; i >= 0; i--) { if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) { if (OrderCloseTime() >= today && OrderSymbol() == Symbol()) { profit += OrderProfit(); } } } return profit; } //+------------------------------------------------------------------+ //| Função para determinar a tendência com base no gráfico H1 | //+------------------------------------------------------------------+ int DetermineTrendOnH1() { double fastSmaH1Current = iMA(NULL, PERIOD_H1, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); double slowSmaH1Current = iMA(NULL, PERIOD_H1, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); if (fastSmaH1Current > slowSmaH1Current) { return 1; // Tendência de alta } else if (fastSmaH1Current < slowSmaH1Current) { return -1; // Tendência de baixa } return 0; // Sem tendência clara } //+------------------------------------------------------------------+ //| Verificar necessidade de realização de lucro parcial | //+------------------------------------------------------------------+ void CheckPartialProfit() { if (orderOpened) { if (OrderSelect(orderTicket, SELECT_BY_TICKET)) { double currentProfit = OrderProfit(); if (currentProfit >= targetPartialProfit) { double partialLotSize = OrderLots() * 0.7; // Realiza 70% da posição if (OrderClose(orderTicket, partialLotSize, OrderClosePrice(), 3, clrViolet)) { Print("Parcial realizada. Lote: ", partialLotSize); orderOpened = true; // Mantém a ordem aberta } else { Print("Erro ao realizar parcial: ", GetLastError()); } } } } } //+------------------------------------------------------------------+ //| Execução de operações no gráfico M5 com base na tendência H1 | //+------------------------------------------------------------------+ void ExecuteTradingOnM5(int trend) { double ask = MarketInfo(Symbol(), MODE_ASK); double bid = MarketInfo(Symbol(), MODE_BID); double priceCloseM5 = iClose(NULL, PERIOD_M5, 0); double fastSmaM5Current = iMA(NULL, PERIOD_M5, fastSmaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); double slowSmaM5Current = iMA(NULL, PERIOD_M5, slowSmaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0); if (orderOpened && OrderSelect(orderTicket, SELECT_BY_TICKET)) { CheckPartialProfit(); if ((OrderType() == OP_BUY && trend == -1) || (OrderType() == OP_SELL && trend == 1)) { if (OrderClose(orderTicket, OrderLots(), OrderClosePrice(), 3, clrRed)) { Print("Ordem existente fechada."); orderOpened = false; orderTicket = 0; } else { Print("Erro ao fechar ordem: ", GetLastError()); } } } // Condições para abrir uma ordem alinhada à tendência de H1 if (!orderOpened && trend != 0) { if (trend == 1 && fastSmaM5Current > slowSmaM5Current && priceCloseM5 > fastSmaM5Current) { double stopLossPrice = NormalizeDouble(priceCloseM5 - stopLossPoints * Point, Digits); orderTicket = OrderSend(Symbol(), OP_BUY, lotSize, ask, 3, stopLossPrice, 0, "Buy Order", 0, 0, clrGreen); if (orderTicket > 0) { orderOpened = true; Print("Ordem de compra aberta! Ticket: ", orderTicket); } else { Print("Erro ao abrir ordem de compra: ", GetLastError()); } } else if (trend == -1 && fastSmaM5Current < slowSmaM5Current && priceCloseM5 < fastSmaM5Current) { double stopLossPrice = NormalizeDouble(priceCloseM5 + stopLossPoints * Point, Digits); orderTicket = OrderSend(Symbol(), OP_SELL, lotSize, bid, 3, stopLossPrice, 0, "Sell Order", 0, 0, clrRed); if (orderTicket > 0) { orderOpened = true; Print("Ordem de venda aberta! Ticket: ", orderTicket); } else { Print("Erro ao abrir ordem de venda: ", GetLastError()); } } } } //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { double currentDailyProfit = GetDailyProfit(); if (currentDailyProfit >= dailyProfitTarget) { Print("Meta de lucro diário alcançada: ", currentDailyProfit); if (orderOpened) { if (OrderSelect(orderTicket, SELECT_BY_TICKET)) { OrderClose(orderTicket, OrderLots(), OrderClosePrice(), 3, clrRed); orderOpened = false; } } return; } int trend = DetermineTrendOnH1(); // Determina a tendência no H1 ExecuteTradingOnM5(trend); // Executa operações apenas em M5 }Notas importantes ao migrar para MQL4:
- No MQL4, usa-se
OrderSend,OrderClose,OrderSelect,OrdersTotal()e outras funções de pedidos diretamente em vez de classes de gerenciamento de ordens. - As funções de obtenção de preços, médias móveis e outras são semelhantes, mas devem ser chamadas diretamente sem objetos de negociação complexa.
- Faça sempre um teste em conta demo antes de implementar este código em ambiente de produção, para verificar se todas as lógicas e condições estão funcionando conforme o esperado.
-