Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI 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;

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    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;
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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
    if (orderOpened)
    {
        if (priceClose >= bollingerMiddle[0] - 3 * _Point && priceClose <= bollingerMiddle[0] + 3 * _Point)
        {
            if (trade.PositionClose(orderTicket))
            {
                Print("Posição fechada porque o preço chegou perto da linha central da Banda de Bollinger.");
                orderOpened = false;
            }
            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.");
                }
            }
        }
    }
    

    }

    em um cenario onde o preço estiver com varias ordens em aberto por exemplo de venda e muitos ou a grande maioria em positivo, quando o mercado chegar perto ou encostar na media do meio da banda de bolliger preciso que o robo feche imediatamente todas ordens que estao abertas e no lucro isso tambem vale para ordens de compra. esse exemplo deve ser para tanto no cenario de venda e compra , tendencia de alta ou tendencia de baixa.

  2. Assistant

    Para implementar a funcionalidade que você descreveu, precisamos modificar o código existente para que ele feche todas as ordens abertas que estão no lucro quando o preço se aproxima da linha do meio das Bandas de Bollinger. Vou mostrar como você pode modificar o seu código para adicionar essa lógica.

    A principal alteração é na função OnTick, onde vamos iterar por todas as posições abertas e fechar aquelas que estão no lucro e cujos preços estão próximos da linha do meio das Bandas de Bollinger.

    Aqui está uma forma de fazer isso:

    void OnTick()
    {
        double bollingerUpper[], bollingerLower[], bollingerMiddle[];
    
        int bbPeriod = 20;
        double bbDeviation = 2.0;
        double slippage = 3 * _Point;
        
        int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
        
        if (bbHandle == INVALID_HANDLE) {
            Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
            return;
        }
        
        ArraySetAsSeries(bollingerUpper, true);
        ArraySetAsSeries(bollingerMiddle, true);
        ArraySetAsSeries(bollingerLower, true);
        
        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;
        }
    
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    
        // Objeto para enviar ordens
        CTrade trade;
    
        // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionSelectByIndex(i))
            {
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                ulong positionTicket = PositionGetInteger(POSITION_TICKET);
    
                if (positionProfit > 0) // Verifica se a posição está no lucro
                {
                    if (positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                        }
                    }
                }
            }
        }
    
        // Restante da função OnTick mantida inalterada
        double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        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());
            }
        }
    
        if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
        }
    
        if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
        }
    
        ManageTrailingStop();
    }
    

    Explicações das alterações principais:

    1. Iteração nas Posições: No início da função OnTick, iteramos sobre todas as posições abertas com PositionSelectByIndex(i).

    2. Fechamento da Posição: Verificamos se a posição está no lucro (positionProfit > 0) e se o preço está dentro de uma faixa próxima da linha central das Bandas de Bollinger. Se ambas as condições forem verdadeiras, a posição é fechada usando trade.PositionClose(positionTicket).

    3. Slippage: slippage é usado para definir quão próximo o preço deve estar da linha do meio antes de fechar a posição. Você pode ajustar esse valor para controlar a sensibilidade.

    Essa implementação garante que todas as posições lucrativas sejam fechadas quando os preços se aproximarem da linha do meio, independentemente de estarem em posições de compra ou venda.

  3. User

    implemente no meu codigo e me entregue completo:

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

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    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;
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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
    if (orderOpened)
    {
        if (priceClose >= bollingerMiddle[0] - 3 * _Point && priceClose <= bollingerMiddle[0] + 3 * _Point)
        {
            if (trade.PositionClose(orderTicket))
            {
                Print("Posição fechada porque o preço chegou perto da linha central da Banda de Bollinger.");
                orderOpened = false;
            }
            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.");
                }
            }
        }
    }
    

    }

  4. Assistant

    Para implementar a funcionalidade que você pediu, adicionaremos uma parte no código que verifica se o preço está perto da linha do meio das Bandas de Bollinger e fecha todas as posições abertas que estão no lucro. Vou incorporar essa lógica no seu código original:

    #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;
    
    //+------------------------------------------------------------------+
    //| 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 (período 20, desvio 2)
        int bbPeriod = 20;
        double bbDeviation = 2.0;
        double slippage = 3 * _Point;
    
        // 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;
    
        // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionSelectByIndex(i))
            {
                ulong positionTicket = PositionGetInteger(POSITION_TICKET);
                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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                    }
                }
            }
        }
    
        // Atualizar informações de rompimento e confirmação
        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());
            }
        }
    
        // 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.");
        }
    
        // 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.");
                    }
                }
            }
        }
    }
    

    Explicações das alterações:

    • Fechamento de Posições Lucrativas: Adicionei um loop no início da função OnTick que verifica todas as posições abertas usando PositionSelectByIndex(i). Para cada posição, verifica-se se ela está no lucro (positionProfit > 0) e se o preço atual da posição está dentro do slippage em torno da linha do meio da Banda de Bollinger. Se ambas as condições forem verdadeiras, a posição é fechada.

    • slippage: Definido como 3 * _Point, o que indica a faixa de proximidade em torno da linha do meio em que as posições lucrativas serão fechadas.

    Essas alterações garantirão que todas as posições lucrativas sejam fechadas quando o preço atingir a linha do meio, conforme especificado na sua solicitação.

  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;

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    int bbPeriod = 20;
    double bbDeviation = 2.0;
    double slippage = 3 * _Point;
    
    // 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;
    
    // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionSelectByIndex(i))
        {
            ulong positionTicket = PositionGetInteger(POSITION_TICKET);
            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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                }
            }
        }
    }
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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.");
    }
    
    // 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.");
                }
            }
        }
    }
    

    }

    erro:

    'NASDAQ_005_Modificado.mq5' 1 Trade.mqh Object.mqh StdLibErr.mqh OrderInfo.mqh HistoryOrderInfo.mqh PositionInfo.mqh DealInfo.mqh possible loss of data due to type conversion NASDAQ_005_Modificado.mq5 46 57 'PositionSelectByIndex' - undeclared identifier NASDAQ_005_Modificado.mq5 79 13 'i' - some operator expected NASDAQ_005_Modificado.mq5 79 35 implicit conversion from 'number' to 'string' NASDAQ_005_Modificado.mq5 162 42 2 errors, 2 warnings 3 3

  6. Assistant

    Parece que você está tentando compilar um código MQL5, mas está enfrentando alguns problemas. Vamos corrigir esses erros:

    1. 'PositionSelectByIndex' - undeclared identifier: Em MQL5, não existe a função PositionSelectByIndex. Em vez disso, você deve usar PositionSelect e PositionGetTicket.

    2. 'i' - some operator expected: Esse erro sugere uma sintaxe incorreta.

    3. Warning sobre a perda de dados devido a conversão de tipo: Isso geralmente acontece quando você está convertendo tipos inteiros para long sem usar a função correta. Você pode ignorar esses avisos ou usar funções adequadas para evitar conversões implícitas.

    4. Implicit conversion warnings: Certifique-se de que suas concatenations de strings estejam corretas ao imprimir mensagens.

    Agora, aqui está o código ajustado:

    #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;
    
    //+------------------------------------------------------------------+
    //| 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 (período 20, desvio 2)
        int bbPeriod = 20;
        double bbDeviation = 2.0;
        double slippage = 3 * _Point;
    
        // 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;
    
        // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
        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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                    }
                }
            }
        }
    
        // Atualizar informações de rompimento e confirmação
        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());
            }
        }
    
        // 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.");
        }
    
        // 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--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong ticket = PositionGetTicket(i);
                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.");
                    }
                }
            }
        }
    }
    

    Principais correções feitas:

    • Ajuste do Loop de Posições: Alterei o uso de PositionSelectByIndex para garantir que você verifica corretamente todas as posições abertas usando PositionGetTicket(i).

    • Erros de Compilação e Avisos: Corrigi a sintaxe e adicionei verificações apropriadas para garantir que funções sejam usadas corretamente sem causar avisos de compilação.

    Certifique-se de importar corretamente as bibliotecas necessárias (como Trade\Trade.mqh) no ambiente MQL5 e de que você está compilando no ambiente certo (MetaEditor).

  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;

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    int bbPeriod = 20;
    double bbDeviation = 2.0;
    double slippage = 3 * _Point;
    
    // 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;
    
    // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
    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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                }
            }
        }
    }
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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.");
    }
    
    // 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--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong ticket = PositionGetTicket(i);
            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.");
                }
            }
        }
    }
    

    }

    é possivel aumentr esse stop que se move ? pois percebi que esta tendo muito stop e causando muito prejuizo poderia todos os stops que forem gerados indo seguindo o preço com uma distancia boa de pelo menos na minina de 2 candles anteriores

  8. Assistant

    Para aumentar o trailing stop e garantir que ele siga os preços com uma distância maior, baseada nos dois candles anteriores, você pode modificar a lógica na função ManageTrailingStop. A ideia é ajustar o Stop Loss para posições de compra com base no menor preço dos dois candles anteriores, e para posições de venda com base no maior preço dos dois candles anteriores. Isso cria um buffer maior, reduzindo a probabilidade de ser atingido rapidamente por flutuações de mercado.

    Aqui está como você pode modificar a função ManageTrailingStop para atingir isso:

    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void ManageTrailingStop()
    {
        CTrade trade;
    
        // Itera sobre todas as posições abertas
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0)
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double currentTP = PositionGetDouble(POSITION_TP);
    
                // Calcula os valores de preço baixo e alto nos dois candles anteriores
                double lastTwoLows = MathMin(iLow(_Symbol, PERIOD_M2, 1), iLow(_Symbol, PERIOD_M2, 2));
                double lastTwoHighs = MathMax(iHigh(_Symbol, PERIOD_M2, 1), iHigh(_Symbol, PERIOD_M2, 2));
    
                // Verificar se é uma posição de compra aberta e atualizar Stop Loss
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (lastTwoLows > currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, lastTwoLows, currentTP);
                        Print("Stop Loss atualizado para posição de compra. Novo SL: ", lastTwoLows);
                    }
                }
                // Verificar se é uma posição de venda aberta e atualizar Stop Loss
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (lastTwoHighs < currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, lastTwoHighs, currentTP);
                        Print("Stop Loss atualizado para posição de venda. Novo SL: ", lastTwoHighs);
                    }
                }
            }
        }
    }
    

    Explicações da Lógica:

    1. Cálculo das mínimas/máximas dos dois candles anteriores: Ao invés de pegar apenas um preço, o código considera os valores mínimos (para compras) e máximos (para vendas) dos dois candles anteriores. Isso configura um Stop Loss mais espaçado.

    2. Ajuste do Stop Loss: A modificação é aplicada apenas se o novo valor de Stop Loss é melhor (ou seja, oferece mais proteção) do que o atual ou se não há Stop Loss (currentSL == 0.0).

    3. Uso de MathMin e MathMax: Utilizamos as funções internas MathMin e MathMax para pegar os valores desejados dos últimos dois candles.

    Com essas mudanças, o Stop Loss será mais espaçado e, potencialmente, menos sensível a movimentos pequenos do mercado, reduzindo assim a probabilidade de paradas prematuras e ajudando a diminuir prejuízos em mercados voláteis. Ajuste essa configuração conforme necessário para se alinhar com sua estratégia de risco.

  9. User

    me entregue o codigo completo com as alterações:

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

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    int bbPeriod = 20;
    double bbDeviation = 2.0;
    double slippage = 3 * _Point;
    
    // 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;
    
    // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
    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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + 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());
                }
            }
        }
    }
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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.");
    }
    
    // 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--)
    {
        if (PositionGetTicket(i) > 0)
        {
            ulong ticket = PositionGetTicket(i);
            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.");
                }
            }
        }
    }
    

    }

  10. Assistant

    Para implementar um trailing stop que se move com base em valores de castiçais (candlesticks) anteriores, precisamos usar os preços mais baixos dos dois últimos candles para uma posição comprada e os preços mais altos para uma posição vendida. Aqui está o código completo com as alterações necessárias:

    #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;
    
    //+------------------------------------------------------------------+
    //| 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 (período 20, desvio 2)
        int bbPeriod = 20;
        double bbDeviation = 2.0;
        double slippage = 3 * _Point;
    
        // 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;
    
        // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            ulong ticket = PositionGetTicket(i);
            if (ticket > 0 && PositionSelect(ticket))
            {
                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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
                {
                    if (trade.PositionClose(ticket))
                    {
                        Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", ticket);
                    }
                    else
                    {
                        Print("Erro ao fechar a posição: ", GetLastError());
                    }
                }
            }
        }
    
        // Atualizar informações de rompimento e confirmação
        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());
            }
        }
    
        // 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.");
        }
    
        // 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);
    
                // Calcula os valores de preço baixo e alto nos dois candles anteriores
                double lastTwoLows = MathMin(iLow(_Symbol, PERIOD_M2, 1), iLow(_Symbol, PERIOD_M2, 2));
                double lastTwoHighs = MathMax(iHigh(_Symbol, PERIOD_M2, 1), iHigh(_Symbol, PERIOD_M2, 2));
    
                // Verificar se é uma posição de compra aberta e atualizar Stop Loss
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (lastTwoLows > currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, lastTwoLows, currentTP);
                        Print("Stop Loss atualizado para posição de compra. Novo SL: ", lastTwoLows);
                    }
                }
                // Verificar se é uma posição de venda aberta e atualizar Stop Loss
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (lastTwoHighs < currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, lastTwoHighs, currentTP);
                        Print("Stop Loss atualizado para posição de venda. Novo SL: ", lastTwoHighs);
                    }
                }
            }
        }
    }
    

    Explicações:

    • Stop Loss Dinâmico: O código ajusta o Stop Loss para as posições usando os valores de preço mínimo e máximo de dois candles anteriores, criando um buffer de proteção maior.

    • Funções MathMin e MathMax: São utilizadas para determinar os preços relevantes para ajustar o Stop Loss.

    • Gestão de Posições: As posições são fechadas automaticamente se estiverem no lucro e o preço atual for próximo do valor médio das Bandas de Bollinger.

    Essas alterações aumentam a distância do Stop Loss em relação ao preço atual, com base nos últimos dois candles, reduzindo assim a sensibilidade a flutuações pequenas de preço. Ajuste conforme necessário para adaptar à sua estratégia.

  11. 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;

    //+------------------------------------------------------------------+ //| 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 (período 20, desvio 2)
    int bbPeriod = 20;
    double bbDeviation = 2.0;
    double slippage = 3 * _Point;
    
    // 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;
    
    // Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        ulong ticket = PositionGetTicket(i);
        if (ticket > 0 && PositionSelect(ticket))
        {
            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 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
            {
                if (trade.PositionClose(ticket))
                {
                    Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", ticket);
                }
                else
                {
                    Print("Erro ao fechar a posição: ", GetLastError());
                }
            }
        }
    }
    
    // Atualizar informações de rompimento e confirmação
    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());
        }
    }
    
    // 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.");
    }
    
    // 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);
    
            // Calcula os valores de preço baixo e alto nos dois candles anteriores
            double lastTwoLows = MathMin(iLow(_Symbol, PERIOD_M2, 1), iLow(_Symbol, PERIOD_M2, 2));
            double lastTwoHighs = MathMax(iHigh(_Symbol, PERIOD_M2, 1), iHigh(_Symbol, PERIOD_M2, 2));
    
            // Verificar se é uma posição de compra aberta e atualizar Stop Loss
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                if (lastTwoLows > currentSL || currentSL == 0.0)
                {
                    trade.PositionModify(ticket, lastTwoLows, currentTP);
                    Print("Stop Loss atualizado para posição de compra. Novo SL: ", lastTwoLows);
                }
            }
            // Verificar se é uma posição de venda aberta e atualizar Stop Loss
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                if (lastTwoHighs < currentSL || currentSL == 0.0)
                {
                    trade.PositionModify(ticket, lastTwoHighs, currentTP);
                    Print("Stop Loss atualizado para posição de venda. Novo SL: ", lastTwoHighs);
                }
            }
        }
    }
    

    }

    onde altero a distancia do trailing top?

    no slippgae?

  12. Assistant

    Não, o parâmetro slippage que você mencionou não está relacionado diretamente à distância configurada para o trailing stop. O slippage é usado para definir uma margem de erro aceitável ao executar trades, relacionada à diferença entre o preço que você deseja e o preço que é efetivamente executado.

    Para ajustar a distância do trailing stop, você deve modificar como os valores de stop loss são calculados na função ManageTrailingStop. Atualmente, o código usa o preço mais baixo dos dois últimos candles para calcular um novo Stop Loss para posições compradas e o preço mais alto para posições vendidas.

    Se você deseja ajustar a distância do trailing stop, precisa alterar a lógica que determina o lastTwoLows e lastTwoHighs ou introduzir um novo parâmetro para definir essa distância adicional.

    Onde alterar a distância do Trailing Stop:

    Dentro da função ManageTrailingStop, as variáveis lastTwoLows e lastTwoHighs servem para determinar os novos valores de stop. Para tornar este ajuste mais flexível, podemos adicionar um novo input que define uma distância fixa adicional a ser considerada.

    // Adicionar um novo input para ajustar a distância do trailing stop
    input double trailingDistancePoints = 20;
    
    //+------------------------------------------------------------------+
    //| 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);
    
                // Calcula os valores de preço baixo e alto nos dois candles anteriores
                double lastTwoLows = MathMin(iLow(_Symbol, PERIOD_M2, 1), iLow(_Symbol, PERIOD_M2, 2));
                double lastTwoHighs = MathMax(iHigh(_Symbol, PERIOD_M2, 1), iHigh(_Symbol, PERIOD_M2, 2));
    
                // Verificar se é uma posição de compra aberta e atualizar Stop Loss
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    double newSLBuy = lastTwoLows - trailingDistancePoints * _Point;
                    if (newSLBuy > currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, newSLBuy, currentTP);
                        Print("Stop Loss atualizado para posição de compra. Novo SL: ", newSLBuy);
                    }
                }
                // Verificar se é uma posição de venda aberta e atualizar Stop Loss
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    double newSLSell = lastTwoHighs + trailingDistancePoints * _Point;
                    if (newSLSell < currentSL || currentSL == 0.0)
                    {
                        trade.PositionModify(ticket, newSLSell, currentTP);
                        Print("Stop Loss atualizado para posição de venda. Novo SL: ", newSLSell);
                    }
                }
            }
        }
    }
    

    Explicações:

    • trailingDistancePoints: Um input adicional que permite ao usuário definir quantos pontos além dos níveis calculados com base nos dois últimos candles o Stop Loss deve ser ajustado. Isso aumenta (ou diminui, se configurado negativamente) a distância do trailing stop em relação aos preços dos candles anteriores.

    • Ajustes de Stop Loss: O cálculo agora subtrai trailingDistancePoints para posições compradas e adiciona trailingDistancePoints para posições vendidas, aumentando a flexibilidade do trailing stop.

    Usando essa abordagem, você pode ajustar a distância do trailing stop dinamicamente ao alterar o valor de trailingDistancePoints no início do seu código. Defina esse número de acordo com sua estratégia e tolerância ao risco.