Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

#include <Trade\Trade.mqh> input double lotSize = 0.01; input int fastSmaPeriod = 20;…

  1. User

    #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);
    
    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; }

    int trend = DetermineTrendOnH1();  // Determina a tendência no H1
    ExecuteTradingOnM5(trend);         // Executa operações apenas em M5
    

    }

    implemente no meu codigo acima o mesmo sistema de trailing stop para captura de lucros a cada movimento afacor do fluxo para obter mais lucros possiveis e nao modifique nada alem disso no meu codigo mantenha todas outras funcionalidades. use como exemplo o trailing stop do codigo abaixo para implementar no meu codigo acima e me entregue o codigo completo:

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double stopLossPips = 10; // Stop Loss in pips input double takeProfitPips = 20; // Take Profit in pips

    // Variáveis globais para controle de ordens bool orderOpened = false; ulong orderTicket = 0;

    // Variáveis para armazenar rompimento anterior bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { // Configurações do EA return(INIT_SUCCEEDED); }

    //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização }

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Variáveis para bandas de Bollinger double bollingerUpper[], bollingerLower[], bollingerMiddle[];

    // Configurações das Bandas de Bollinger
    int bbPeriod = 20;
    double bbDeviation = 2.0;
    
    // Obtenção das Bandas de Bollinger
    int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
    
    // Verifique se o handle é válido
    if (bbHandle == INVALID_HANDLE) {
        Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
        return;
    }
    
    // Inicializar os buffers das bandas de Bollinger
    ArraySetAsSeries(bollingerUpper, true);
    ArraySetAsSeries(bollingerMiddle, true);
    ArraySetAsSeries(bollingerLower, true);
    
    // Preencher os buffers
    if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
        CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
        CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
        Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
        return;
    }
    
    // Preço atual e range da vela
    double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    // Objeto para enviar ordens
    CTrade trade;
    
    // Verificar se há uma ordem aberta
    if (!orderOpened) {
        // Atualizar informações de rompimento e confirmação
        if (lastBreakoutAlta && priceClose > breakoutHigh)
        {
            double slBuy = priceClose - stopLossPips * _Point;
            double tpBuy = priceClose + takeProfitPips * _Point;
            if (trade.Buy(lotSize, _Symbol, priceClose, slBuy, tpBuy))
            {
                orderOpened = true;
                orderTicket = trade.ResultOrder();
                Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
                lastBreakoutAlta = false;
            }
            else
            {
                Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        if (lastBreakoutBaixa && priceClose < breakoutLow)
        {
            double slSell = priceClose + stopLossPips * _Point;
            double tpSell = priceClose - takeProfitPips * _Point;
            if (trade.Sell(lotSize, _Symbol, priceClose, slSell, tpSell))
            {
                orderOpened = true;
                orderTicket = trade.ResultOrder();
                Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
                lastBreakoutBaixa = false;
            }
            else
            {
                Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Verificar rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        // Verificar rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    }
    
    // Fechar ordem se o preço estiver perto da linha do meio da Banda de Bollinger
    // e se a posição estiver em lucro
    if (orderOpened)
    {
        double profit = PositionGetDouble(POSITION_PROFIT);
    
        if (profit > 0)
        {
            if (MathAbs(priceClose - bollingerMiddle[0]) <= 20 * _Point)
            {
                if (trade.PositionClose(orderTicket))
                {
                    Print("Posição lucrativa fechada porque o preço chegou perto da linha do meio da Banda de Bollinger.");
                    orderOpened = false;
                    orderTicket = 0;
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    
    // Gerenciamento de trailing stop
    ManageTrailingStop();
    

    }

    //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void ManageTrailingStop() { CTrade trade;

    // Itera sobre todas as posições abertas
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if (ticket > 0 && PositionSelect(ticket))
        {
            double currentSL = PositionGetDouble(POSITION_SL);
            double currentTP = PositionGetDouble(POSITION_TP);
            double lastLow = iLow(_Symbol, PERIOD_M2, 1);
            double lastHigh = iHigh(_Symbol, PERIOD_M2, 1);
    
            // Verificar se é uma posição de compra aberta e atualizar Stop Loss
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (lastLow > currentSL || currentSL == 0.0)
                {
                    trade.PositionModify(ticket, lastLow, currentTP);
                    Print("Stop Loss atualizado para posição de compra.");
                }
            }
            // Verificar se é uma posição de venda aberta e atualizar Stop Loss
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (lastHigh < currentSL || currentSL == 0.0)
                {
                    trade.PositionModify(ticket, lastHigh, currentTP);
                    Print("Stop Loss atualizado para posição de venda.");
                }
            }
        }
    }
    

    }

  2. Assistant

    Para implementar um sistema de trailing stop no seu código, precisamos adicionar a função ManageTrailingStop() no seu código original e chamá-la dentro da função OnTick(). O trailing stop ajusta o stop loss de uma posição em direção ao preço atual à medida que a posição se move a favor da tendência, permitindo capturar mais lucro.

    Vou integrar a funcionalidade de trailing stop ao seu código original, preservando toda a lógica e estrutura existentes.

    Aqui está o código completo com o trailing stop adicionado:

    #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);
    
        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());
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop |
    //+------------------------------------------------------------------+
    void ManageTrailingStop() {
        if (orderOpened) {
            double currentSL = PositionGetDouble(POSITION_SL);
            double lastLow = iLow(_Symbol, PERIOD_M5, 1);
            double lastHigh = iHigh(_Symbol, PERIOD_M5, 1);
    
            if (PositionSelect(_Symbol)) {
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (lastLow > currentSL || currentSL == 0.0) {
                        if (trade.PositionModify(orderTicket, lastLow, 0.0)) {
                            Print("Stop Loss atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (lastHigh < currentSL || currentSL == 0.0) {
                        if (trade.PositionModify(orderTicket, lastHigh, 0.0)) {
                            Print("Stop Loss atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| 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
        ManageTrailingStop();              // Gerenciar trailing stop
    }
    

    Neste código, o método ManageTrailingStop() foi adicionado para ajustar o stop loss conforme a posição se move em favor do mercado. Esta função é chamada dentro da função OnTick(), logo após a execução de negociações com base na tendência identificada. O stop loss é ajustado para a mínima de uma vela anterior em compras e a máxima em vendas se essas condições se moverem a favor da posição aberta.