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

#include <Trade\Trade.mqh> input double lotSize = 0.1; // Variáveis globais para…

  1. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

    // 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;

    // Configurações de trailing stop input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado input int TslPoints = 10; // Trailing stop em pips

    // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA

    CTrade trade;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }

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

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;

    // Cálculo das Bandas de Bollinger
    double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda superior
    double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda inferior
    
    // Atualizar informações de rompimento e confirmação
    UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
    // Fechar posições lucrativas
    CloseProfitablePositions();
    
    // Gerenciamento de trailing stop
    TrailStop();
    
    // Condições de abertura de ordens
    OpenOrders(priceClose);
    

    }

    //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }

    if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    }
    

    }

    //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            // Verifica se a posição está no lucro e se o preço está perto da linha do meio
            if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
            {
                if (trade.PositionClose(positionTicket))
                {
                    Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 1); // Banda média return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }

    //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { if (lastBreakoutAlta && priceClose > breakoutHigh) { double slBuy = priceClose - 10 * _Point; if (trade.Buy(lotSize, _Symbol, slBuy)) { 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 + 10 * _Point; 
        if (trade.Sell(lotSize, _Symbol, slSell))
        {
            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());
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void TrailStop() { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
        {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

    erro:

    'NASDAQ V2_007_Working.mq5' 1 Trade.mqh Object.mqh StdLibErr.mqh OrderInfo.mqh HistoryOrderInfo.mqh PositionInfo.mqh DealInfo.mqh 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 55 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 55 29 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 56 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 56 29 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 126 30 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 126 30 3 errors, 0 warnings 4 1

  2. Assistant

    The errors you're encountering in the MQL5 code relate to the incorrect usage of the iBands function. This function is used to calculate the Bollinger Bands in MetaTrader 5. It seems you've got issues with the parameters specified for this function.

    Here's the correct syntax for calling the iBands function:

    int iBands(
       const string         symbol,            // symbol name
       ENUM_TIMEFRAMES      timeframe,         // timeframe
       int                  period,            // averaging period
       int                  deviation,         // deviation
       double               bands_shift,       // bands shift
       ENUM_APPLIED_PRICE   applied_price      // applied price
    );
    

    Here are the mistakes in your code:

    1. Incorrect number of parameters passed to the iBands function.

    To fix these errors, you should update your calls to the iBands function to match its correct signature. Adjust them as follows:

    • For bollingerUpper:

      double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_UPPER);
      
    • For bollingerLower:

      double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_LOWER);
      
    • For bollingerMiddle:

      double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_MAIN);
      

    Notice that MODE_UPPER, MODE_LOWER, and MODE_MAIN are indices to access the upper, lower, and middle lines of the Bollinger Bands. They are required to correctly specify which line value you want from the iBands call.

    Make sure that these changes are made to the respective lines in your OnTick function and IsNearBollingerMiddle function as they relate to the Bollinger Bands. By adjusting the parameters and specifying the correct modes, your Bollinger Band calculations should work correctly.

  3. User

    me responda em portugues, e me entregue o codigo completo corrigido:

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

    // 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;

    // Configurações de trailing stop input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado input int TslPoints = 10; // Trailing stop em pips

    // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA

    CTrade trade;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }

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

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;

    // Cálculo das Bandas de Bollinger
    double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda superior
    double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda inferior
    
    // Atualizar informações de rompimento e confirmação
    UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
    // Fechar posições lucrativas
    CloseProfitablePositions();
    
    // Gerenciamento de trailing stop
    TrailStop();
    
    // Condições de abertura de ordens
    OpenOrders(priceClose);
    

    }

    //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }

    if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    }
    

    }

    //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            // Verifica se a posição está no lucro e se o preço está perto da linha do meio
            if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
            {
                if (trade.PositionClose(positionTicket))
                {
                    Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 1); // Banda média return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }

    //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { if (lastBreakoutAlta && priceClose > breakoutHigh) { double slBuy = priceClose - 10 * _Point; if (trade.Buy(lotSize, _Symbol, slBuy)) { 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 + 10 * _Point; 
        if (trade.Sell(lotSize, _Symbol, slSell))
        {
            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());
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void TrailStop() { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
        {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

  4. Assistant

    Claro! Vamos corrigir o uso das funções iBands para eliminar os erros referentes ao número incorreto de parâmetros. Aqui está o código corrigido:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    
    // 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;
    
    // Configurações de trailing stop
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    
    // Configurações de horário
    input int SHInput = 0; // Horário de início
    input int EHInput = 0; // Horário de fim
    input int InpMagic = 298347; // Identificação do EA
    
    CTrade trade;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
        // Função de finalização
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // 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;
    
        // Cálculo das Bandas de Bollinger
        double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_UPPER);
        double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_LOWER);
    
        // Atualizar informações de rompimento e confirmação
        UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
        // Fechar posições lucrativas
        CloseProfitablePositions();
    
        // Gerenciamento de trailing stop
        TrailStop();
    
        // Condições de abertura de ordens
        OpenOrders(priceClose);
    }
    
    //+------------------------------------------------------------------+
    //| Atualizar informações de rompimento                              |
    //+------------------------------------------------------------------+
    void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower)
    {
        if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Fechar posições lucrativas                                       |
    //+------------------------------------------------------------------+
    void CloseProfitablePositions()
    {
        double slippage = 3 * _Point;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                // Verifica se a posição está no lucro e se o preço está perto da linha do meio
                if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
                {
                    if (trade.PositionClose(positionTicket))
                    {
                        Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                    }
                    else
                    {
                        Print("Erro ao fechar a posição: ", GetLastError());
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Verifica se o preço está próximo da linha média da Banda de Bollinger |
    //+------------------------------------------------------------------+
    bool IsNearBollingerMiddle(double price, double slippage)
    {
        // Cálculo da linha média das Bandas de Bollinger
        double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_MAIN);
        return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage;
    }
    
    //+------------------------------------------------------------------+
    //| Função para abrir ordens                                         |
    //+------------------------------------------------------------------+
    void OpenOrders(double priceClose)
    {
        if (lastBreakoutAlta && priceClose > breakoutHigh)
        {
            double slBuy = priceClose - 10 * _Point; 
            if (trade.Buy(lotSize, _Symbol, slBuy))
            {
                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 + 10 * _Point; 
            if (trade.Sell(lotSize, _Symbol, slSell))
            {
                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());
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void TrailStop()
    {
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                    {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                    {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Corrigi as chamadas da função iBands para utilizar MODE_UPPER, MODE_LOWER e MODE_MAIN, que indicam as bandas superior, inferior e média, respectivamente. Agora o código deve compilar corretamente e as bandas de Bollinger serão calculadas conforme esperado.

  5. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

    // 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;

    // Configurações de trailing stop input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado input int TslPoints = 10; // Trailing stop em pips

    // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA

    CTrade trade;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }

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

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;

    // Cálculo das Bandas de Bollinger
    double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_UPPER);
    double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_LOWER);
    
    // Atualizar informações de rompimento e confirmação
    UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
    // Fechar posições lucrativas
    CloseProfitablePositions();
    
    // Gerenciamento de trailing stop
    TrailStop();
    
    // Condições de abertura de ordens
    OpenOrders(priceClose);
    

    }

    //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }

    if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    }
    

    }

    //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            // Verifica se a posição está no lucro e se o preço está perto da linha do meio
            if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
            {
                if (trade.PositionClose(positionTicket))
                {
                    Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_MAIN); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }

    //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { if (lastBreakoutAlta && priceClose > breakoutHigh) { double slBuy = priceClose - 10 * _Point; if (trade.Buy(lotSize, _Symbol, slBuy)) { 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 + 10 * _Point; 
        if (trade.Sell(lotSize, _Symbol, slSell))
        {
            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());
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void TrailStop() { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
        {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

    erro:

    'MODE_UPPER' - undeclared identifier NASDAQ V2_007_Working.mq5 55 79 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 55 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 55 29 'MODE_LOWER' - undeclared identifier NASDAQ V2_007_Working.mq5 56 79 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 56 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 56 29 'MODE_MAIN' - undeclared identifier NASDAQ V2_007_Working.mq5 126 80 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 126 30 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 126 30

  6. Assistant

    Os erros que você está encontrando estão relacionados ao uso incorreto da função iBands e dos identificadores MODE_UPPER, MODE_LOWER e MODE_MAIN, que na verdade se aplicam à função de manipulação de indicadores na biblioteca MQL4. Em MQL5, a função iBands retorna um handle, e você deve usar CopyBuffer para obter os valores das bandas.

    Vamos corrigir o código para usar a abordagem correta em MQL5. Aqui está o código atualizado:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    
    // 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;
    
    // Configurações de trailing stop
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    
    // Configurações de horário
    input int SHInput = 0; // Horário de início
    input int EHInput = 0; // Horário de fim
    input int InpMagic = 298347; // Identificação do EA
    
    CTrade trade;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
        // Função de finalização
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // 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;
    
        // Cálculo das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerUpper, bollingerLower, bollingerMiddle;
        CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper);
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerUpper);
        CopyBuffer(bollingerHandle, 2, 0, 1, bollingerUpper);
    
        // Atualizar informações de rompimento e confirmação
        UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
        // Fechar posições lucrativas
        CloseProfitablePositions();
    
        // Gerenciamento de trailing stop
        TrailStop();
    
        // Condições de abertura de ordens
        OpenOrders(priceClose);
    }
    
    //+------------------------------------------------------------------+
    //| Atualizar informações de rompimento                              |
    //+------------------------------------------------------------------+
    void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower)
    {
        if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Fechar posições lucrativas                                       |
    //+------------------------------------------------------------------+
    void CloseProfitablePositions()
    {
        double slippage = 3 * _Point;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                // Verifica se a posição está no lucro e se o preço está perto da linha do meio
                if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
                {
                    if (trade.PositionClose(positionTicket))
                    {
                        Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                    }
                    else
                    {
                        Print("Erro ao fechar a posição: ", GetLastError());
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Verifica se o preço está próximo da linha média da Banda de Bollinger |
    //+------------------------------------------------------------------+
    bool IsNearBollingerMiddle(double price, double slippage)
    {
        // Cálculo da linha média das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerMiddle;
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle);
        return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage;
    }
    
    //+------------------------------------------------------------------+
    //| Função para abrir ordens                                         |
    //+------------------------------------------------------------------+
    void OpenOrders(double priceClose)
    {
        if (lastBreakoutAlta && priceClose > breakoutHigh)
        {
            double slBuy = priceClose - 10 * _Point; 
            if (trade.Buy(lotSize, _Symbol, slBuy))
            {
                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 + 10 * _Point; 
            if (trade.Sell(lotSize, _Symbol, slSell))
            {
                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());
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void TrailStop()
    {
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                    {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                    {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    O código acima foi corrigido para que ele utilize a função CopyBuffer para obter os valores das bandas de Bollinger. Assim, você acessa corretamente as bandas superior, inferior e o meio em MQL5. As variáveis bollingerUpper, bollingerLower e bollingerMiddle são usadas para armazenar esses valores após a cópia feita da buffer do indicador.

  7. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

    // 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;

    // Configurações de trailing stop input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado input int TslPoints = 10; // Trailing stop em pips

    // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA

    CTrade trade;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }

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

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;

    // Cálculo das Bandas de Bollinger
    int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
    double bollingerUpper, bollingerLower, bollingerMiddle;
    CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper);
    CopyBuffer(bollingerHandle, 1, 0, 1, bollingerUpper);
    CopyBuffer(bollingerHandle, 2, 0, 1, bollingerUpper);
    
    // Atualizar informações de rompimento e confirmação
    UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower);
    
    // Fechar posições lucrativas
    CloseProfitablePositions();
    
    // Gerenciamento de trailing stop
    TrailStop();
    
    // Condições de abertura de ordens
    OpenOrders(priceClose);
    

    }

    //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }

    if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    }
    

    }

    //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            // Verifica se a posição está no lucro e se o preço está perto da linha do meio
            if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
            {
                if (trade.PositionClose(positionTicket))
                {
                    Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerMiddle; CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }

    //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { if (lastBreakoutAlta && priceClose > breakoutHigh) { double slBuy = priceClose - 10 * _Point; if (trade.Buy(lotSize, _Symbol, slBuy)) { 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 + 10 * _Point; 
        if (trade.Sell(lotSize, _Symbol, slSell))
        {
            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());
        }
    }
    

    }

    //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void TrailStop() { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
        {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0)
                    {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

    erro:

    'CopyBuffer' - no one of the overloads can be applied to the function call NASDAQ V2_007_Working.mq5 131 5

  8. Assistant

    Os erros que você está enfrentando ocorrem porque a função CopyBuffer requer uma matriz para armazenar os resultados, em vez de uma variável única. Precisamos alterar a maneira como estamos chamando CopyBuffer para corrigir isso.

    Vamos corrigir essas chamadas e garantir que a alocação e o armazenamento das informações das bandas de Bollinger sejam tratados corretamente em buffers do tipo array. Aqui está o código corrigido:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    
    // 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;
    
    // Configurações de trailing stop
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    
    // Configurações de horário
    input int SHInput = 0; // Horário de início
    input int EHInput = 0; // Horário de fim
    input int InpMagic = 298347; // Identificação do EA
    
    CTrade trade;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
        // Função de finalização
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // 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;
    
        // Cálculo das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerUpper[1], bollingerLower[1], bollingerMiddle[1];
        CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper);
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerLower);
        CopyBuffer(bollingerHandle, 2, 0, 1, bollingerMiddle);
    
        // Atualizar informações de rompimento e confirmação
        UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper[0], bollingerLower[0]);
    
        // Fechar posições lucrativas
        CloseProfitablePositions();
    
        // Gerenciamento de trailing stop
        TrailStop();
    
        // Condições de abertura de ordens
        OpenOrders(priceClose);
    }
    
    //+------------------------------------------------------------------+
    //| Atualizar informações de rompimento                              |
    //+------------------------------------------------------------------+
    void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower)
    {
        if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Fechar posições lucrativas                                       |
    //+------------------------------------------------------------------+
    void CloseProfitablePositions()
    {
        double slippage = 3 * _Point;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                // Verifica se a posição está no lucro e se o preço está perto da linha do meio
                if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
                {
                    if (trade.PositionClose(positionTicket))
                    {
                        Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                    }
                    else
                    {
                        Print("Erro ao fechar a posição: ", GetLastError());
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Verifica se o preço está próximo da linha média da Banda de Bollinger |
    //+------------------------------------------------------------------+
    bool IsNearBollingerMiddle(double price, double slippage)
    {
        // Cálculo da linha média das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerMiddle[1];
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle);
        return price >= bollingerMiddle[0] - slippage && price <= bollingerMiddle[0] + slippage;
    }
    
    //+------------------------------------------------------------------+
    //| Função para abrir ordens                                         |
    //+------------------------------------------------------------------+
    void OpenOrders(double priceClose)
    {
        if (lastBreakoutAlta && priceClose > breakoutHigh)
        {
            double slBuy = priceClose - 10 * _Point; 
            if (trade.Buy(lotSize, _Symbol, slBuy))
            {
                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 + 10 * _Point; 
            if (trade.Sell(lotSize, _Symbol, slSell))
            {
                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());
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void TrailStop()
    {
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                    {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                    {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Agora utilizamos arrays (bollingerUpper, bollingerLower, bollingerMiddle) para armazenar os valores da CopyBuffer, e acessamos os valores usando o índice [0]. Isso deve resolver os erros de compilação.

  9. User

    como aumentar a distancia de fechamento da orden?

  10. Assistant

    Para aumentar a distância de fechamento de uma ordem, você pode ajustar a lógica que decide quando fechar as ordens lucrativas. No código atual, a decisão é baseada se o preço da posição está próximo da linha média das Bandas de Bollinger. Se você quer aumentar a "distância de fechamento", pode alterar os fatores que determinam essa proximidade. Isso pode ser feito ajustando o parâmetro slippage na função CloseProfitablePositions.

    Atualmente, o código verifica se o lucro da posição é positivo e se o preço está perto da linha média das Bandas de Bollinger usando a função IsNearBollingerMiddle. Para aumentar a distância de fechamento, você pode alterar o valor do slippage ou criar um novo parâmetro de entrada que permita ajustar essa distância com base na sua estratégia.

    Aqui está uma versão modificada do seu código com um parâmetro de entrada adicionado para controlar a distância de fechamento:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double closeDistanceMultiplier = 2.0; // Multiplicador para a distância de fechamento
    
    // 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;
    
    // Configurações de trailing stop
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    
    // Configurações de horário
    input int SHInput = 0; // Horário de início
    input int EHInput = 0; // Horário de fim
    input int InpMagic = 298347; // Identificação do EA
    
    CTrade trade;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
        // Função de finalização
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // 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;
    
        // Cálculo das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerUpper[1], bollingerLower[1], bollingerMiddle[1];
        CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper);
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerLower);
        CopyBuffer(bollingerHandle, 2, 0, 1, bollingerMiddle);
    
        // Atualizar informações de rompimento e confirmação
        UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper[0], bollingerLower[0]);
    
        // Fechar posições lucrativas
        CloseProfitablePositions();
    
        // Gerenciamento de trailing stop
        TrailStop();
    
        // Condições de abertura de ordens
        OpenOrders(priceClose);
    }
    
    //+------------------------------------------------------------------+
    //| Atualizar informações de rompimento                              |
    //+------------------------------------------------------------------+
    void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower)
    {
        if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Fechar posições lucrativas                                       |
    //+------------------------------------------------------------------+
    void CloseProfitablePositions()
    {
        double slippage = 3 * _Point * closeDistanceMultiplier;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                // Verifica se a posição está no lucro e se o preço está perto da linha do meio
                if (positionProfit > 0 && IsNearBollingerMiddle(positionPrice, slippage))
                {
                    if (trade.PositionClose(positionTicket))
                    {
                        Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
                    }
                    else
                    {
                        Print("Erro ao fechar a posição: ", GetLastError());
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Verifica se o preço está próximo da linha média da Banda de Bollinger |
    //+------------------------------------------------------------------+
    bool IsNearBollingerMiddle(double price, double slippage)
    {
        // Cálculo da linha média das Bandas de Bollinger
        int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE);
        double bollingerMiddle[1];
        CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle);
        return price >= bollingerMiddle[0] - slippage && price <= bollingerMiddle[0] + slippage;
    }
    
    //+------------------------------------------------------------------+
    //| Função para abrir ordens                                         |
    //+------------------------------------------------------------------+
    void OpenOrders(double priceClose)
    {
        if (lastBreakoutAlta && priceClose > breakoutHigh)
        {
            double slBuy = priceClose - 10 * _Point; 
            if (trade.Buy(lotSize, _Symbol, slBuy))
            {
                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 + 10 * _Point; 
            if (trade.Sell(lotSize, _Symbol, slSell))
            {
                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());
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void TrailStop()
    {
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                    {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                    {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Com esse ajuste, você pode controlar a distância de fechamento alterando o valor do parâmetro closeDistanceMultiplier. Quanto maior for esse valor, maior será a distância antes de uma posição ser considerada próxima o suficiente para fechar.