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

que estrategia usando retração de fibonacci é mais acertiva?

  1. User

    que estrategia usando retração de fibonacci é mais acertiva?

  2. Assistant

    A estratégia de retração de Fibonacci é uma ferramenta popular na análise técnica usada para identificar potenciais níveis de suporte e resistência. No entanto, não há uma "estratégia única" que funcione de forma garantida, pois o mercado é imprevisível e as condições variam. No entanto, alguns princípios gerais podem ajudar a aumentar a eficácia ao usar retrações de Fibonacci:

    1. Combinar com Outras Ferramentas: A retração de Fibonacci tende a ser mais eficaz quando usada em conjunto com outras ferramentas de análise técnica, como padrões de velas, médias móveis, ou indicadores como o RSI e MACD. Isso ajuda a confirmar os níveis de suporte e resistência.

    2. Identificação Correta dos Pontos: Certifique-se de identificar corretamente o ponto alto e o ponto baixo relevantes para traçar as linhas de Fibonacci. Essas linhas devem ser desenhadas sobre uma perna de movimento significativa no gráfico, seja de alta ou de baixa.

    3. Níveis Relevantes: Preste atenção especial aos níveis de 38,2%, 50% e 61,8%, pois são considerados os níveis mais confiáveis onde ocorrem reversões de preço.

    4. Verificação de Confluência: Procure por confluência entre os níveis de Fibonacci e outros níveis de suporte ou resistência que possam ser identificados através de linhas de tendência ou outros métodos. Áreas de confluência tendem a ser mais poderosas.

    5. Consideração do Prazo: Aplique a ferramenta em múltiplos prazos para identificar níveis chave que podem coincidir em mais de uma escala temporal, o que pode reforçar a validade dos níveis de Fibonacci identificados.

    6. Monitoramento de Volume: Use o volume para confirmar cenários onde o preço pode realmente inverter ou continuar. Aumento de volume em torno dos níveis de Fibonacci pode indicar uma reversão iminente ou a continuação do movimento.

    7. Gestão de Riscos: Como com qualquer estratégia de trading, é essencial ter um plano de gestão de riscos sólido. Use ordens de stop-loss para proteger seu capital contra movimentos desfavoráveis inesperados.

    Lembre-se de que nenhuma estratégia é infalível e é importante testar suas abordagens e ajustar conforme necessário ao seu estilo de negociação e às condições do mercado.

  3. User

    como seria um HFT com uma estrategia usando retração de fibonacci onde cada vez que o preço for nadireçao a favor da ordem da retração tenha umtrailing stop acompanhando o preço a medida que for avançando trailing de 20 pontos caso o preçoretorne e lucro seja protegido, crie um codigo robo em MQL5 precisa abrir até 4 ordens por vez nomaximo, apenas abra mais orden quando as 4 forem encerradas e abrir novamente novas apenas quando tiver novas oportunidades boa de lucro

  4. Assistant

    Criar um robô de alta frequência (HFT) completo para MetaTrader 5 usando retração de Fibonacci e um trailing stop requer bastante código. Eu posso fornecer um exemplo básico em MQL5 que inclui a lógica essencial para abrir ordens com base em retrações de Fibonacci e usar um trailing stop. Este exemplo não cobre todos os aspectos que um robô HFT completo deveria ter, como análise de mercado abrangente, otimização de parâmetros, etc.

    Por favor, entenda que o uso de robôs de trading de alta frequência tem riscos significativos e requer um ambiente robusto de execução, baixa latência e uma gestão rigorosa dos riscos.

    Aqui está um exemplo simplificado:

    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    input int MaxOrders = 4;
    
    double highPrice, lowPrice;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        int openOrders = OrdersTotal();
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Verifica condições para abrir ordens
        if (openOrders < MaxOrders) {
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
                // Abrir uma ordem de Compra
                OpenOrder(ORDER_TYPE_BUY);
            }
            // Repita para outros níveis de Fibonacci
        }
    
        // Gerenciar trailing stop
        ManageTrailingStops();
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));    
    }
    
    void OpenOrder(int orderType)
    {
        double lotSize = 0.1; // Lote fixo, ajustar conforme sua estratégia de gestão de risco
        double price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double sl = orderType == ORDER_TYPE_BUY ? price - TrailingStopPoints * _Point : price + TrailingStopPoints * _Point;
        double tp = 0; // Sem Take Profit fixo
    
        MqlTradeRequest request;
        MqlTradeResult result;
        ZeroMemory(request);
        ZeroMemory(result);
    
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = lotSize;
        request.type = orderType;
        request.price = price;
        request.sl = sl;
        request.tp = tp;
        request.deviation = 10;
    
        if (!OrderSend(request, result) || result.retcode != TRADE_RETCODE_DONE) {
            Print("Falha ao abrir ordem: ", result.comment);
        }
    }
    
    void ManageTrailingStops()
    {
        for (int i = 0; i < OrdersTotal(); i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                double newSl;
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > OrderGetDouble(ORDER_SL)) {
                        OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC);
                    }
                }
                else if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < OrderGetDouble(ORDER_SL)) {
                        OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC);
                    }
                }
            }
        }
    }
    

    Notas Importantes:

    1. Gestão de Risco: Modifique o lotSize e o TrailingStopPoints de acordo com seu gerenciamento de risco e a escala do seu capital.

    2. Condições de Mercado: Certifique-se de testar o robô em diferentes condições de mercado, principalmente em modo de teste histórico antes de usar em contas reais.

    3. Ajustes e Otimização: Este exemplo pode necessitar de ajustes e otimizações adicionais para assegurar que funciona corretamente em seu ambiente e de acordo com suas metas de negociação.

    4. Compliance: Certifique-se de que o uso deste robô está em conformidade com as políticas da corretora e as regulamentações locais.

    Sempre que implementar um robô de negociação, é essencial proceder com cautela, especialmente no espaço HFT, onde pequenos erros podem resultar em perdas significativas.

  5. User

    lembrando que o robo nao pode fazer Hedge

  6. Assistant

    Para garantir que o robô não faça hedge em MetaTrader 5 (onde você não pode ter posições longas e curtas abertas simultaneamente no mesmo símbolo), precisamos modificar a lógica para manter apenas uma direção de negociação por vez. Isso pode ser alcançado administrando cada posição adequadamente e garantindo que ordens opostas sejam evitadas até que sejam completamente fechadas.

    Aqui estão as modificações necessárias para garantir que o robô não faça hedge:

    1. Controlar a Direção das Posições: Manter uma variável para armazenar a direção atual da posição e só permitir novas ordens na mesma direção até que a posição esteja completamente fechada.

    2. Verificar Ordens Abertas: Antes de abrir uma nova ordem, verifique a direção das ordens abertas e evite abrir ordens na direção oposta.

    Aqui está como você pode modificar o exemplo de código para incluir essa lógica:

    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    input int MaxOrders = 4;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        int openOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
    
        // Contar as ordens abertas por direção
        for (int i = 0; i < openOrders; i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    buyOrders++;
                }
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    sellOrders++;
                }
            }
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Verifica condições para abrir ordens sem hedge
        if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
            // Pode abrir nova direção
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
                // Abrir uma ordem de Compra
                OpenOrder(ORDER_TYPE_BUY);
                currentDirection = 1;
            }
            else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
                // Abrir uma ordem de Venda
                OpenOrder(ORDER_TYPE_SELL);
                currentDirection = -1;
            }
        }
    
        // Gerenciar trailing stop
        ManageTrailingStops();
    
        // Verifica se todas as ordens na direção atual foram fechadas
        if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
            currentDirection = 0;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));    
    }
    
    void OpenOrder(int orderType)
    {
        double lotSize = 0.1; // Lote fixo, ajustar conforme sua estratégia de gestão de risco
        double price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double sl = orderType == ORDER_TYPE_BUY ? price - TrailingStopPoints * _Point : price + TrailingStopPoints * _Point;
        double tp = 0; // Sem Take Profit fixo
    
        MqlTradeRequest request;
        MqlTradeResult result;
        ZeroMemory(request);
        ZeroMemory(result);
    
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = lotSize;
        request.type = orderType;
        request.price = price;
        request.sl = sl;
        request.tp = tp;
        request.deviation = 10;
    
        if (!OrderSend(request, result) || result.retcode != TRADE_RETCODE_DONE) {
            Print("Falha ao abrir ordem: ", result.comment);
        }
    }
    
    void ManageTrailingStops()
    {
        for (int i = 0; i < OrdersTotal(); i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                double newSl;
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > OrderGetDouble(ORDER_SL)) {
                        OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC);
                    }
                }
                else if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < OrderGetDouble(ORDER_SL)) {
                        OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC);
                    }
                }
            }
        }
    }
    

    Explicações:

    • Controle de Direção: Usamos currentDirection para garantir que não fazemos hedge. 1 indica posições de compra, -1 para posições de venda, e 0 para nenhum.
    • Condicional de Abertura de Ordens: Verificamos se currentDirection é 0 antes de abrir novas posições, evitando hedge.
    • Verificação de Fechamento: Após o fechamento de todas as ordens na direção atual (buyOrders ou sellOrders são 0), o currentDirection é redefinido para permitir novas aberturas.

    Teste o robô em ambiente de demonstração e ajuste os parâmetros de acordo com suas necessidades específicas antes de usar em uma conta real.

  7. User

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20; input int MaxOrders = 4;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); int openOrders = OrdersTotal(); int buyOrders = 0; int sellOrders = 0;

    // Contar as ordens abertas por direção
    for (int i = 0; i < openOrders; i++) {
        ulong ticket = OrderGetTicket(i);
        if (OrderSelect(ticket)) {
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                buyOrders++;
            }
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                sellOrders++;
            }
        }
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Verifica condições para abrir ordens sem hedge
    if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
            // Abrir uma ordem de Compra
            OpenOrder(ORDER_TYPE_BUY);
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
            // Abrir uma ordem de Venda
            OpenOrder(ORDER_TYPE_SELL);
            currentDirection = -1;
        }
    }
    
    // Gerenciar trailing stop
    ManageTrailingStops();
    
    // Verifica se todas as ordens na direção atual foram fechadas
    if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
        currentDirection = 0;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }

    void OpenOrder(int orderType) { double lotSize = 0.1; // Lote fixo, ajustar conforme sua estratégia de gestão de risco double price = (orderType == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double sl = orderType == ORDER_TYPE_BUY ? price - TrailingStopPoints * _Point : price + TrailingStopPoints * _Point; double tp = 0; // Sem Take Profit fixo

    MqlTradeRequest request;
    MqlTradeResult result;
    ZeroMemory(request);
    ZeroMemory(result);
    
    request.action = TRADE_ACTION_DEAL;
    request.symbol = _Symbol;
    request.volume = lotSize;
    request.type = orderType;
    request.price = price;
    request.sl = sl;
    request.tp = tp;
    request.deviation = 10;
    
    if (!OrderSend(request, result) || result.retcode != TRADE_RETCODE_DONE) {
        Print("Falha ao abrir ordem: ", result.comment);
    }
    

    }

    void ManageTrailingStops() { for (int i = 0; i < OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if (OrderSelect(ticket)) { double newSl; if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > OrderGetDouble(ORDER_SL)) { OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC); } } else if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < OrderGetDouble(ORDER_SL)) { OrderModify(ticket, OrderGetDouble(ORDER_PRICE_OPEN), newSl, OrderGetDouble(ORDER_TP), ORDER_TIME_GTC); } } } } }

    erros:

    implicit enum conversion HFT_01.mq5 78 20 'OrderModify' - undeclared identifier HFT_01.mq5 98 21 ',' - unexpected token HFT_01.mq5 98 39 'ticket' - some operator expected HFT_01.mq5 98 33 ',' - unexpected token HFT_01.mq5 98 73 expression has no effect HFT_01.mq5 98 56 ',' - unexpected token HFT_01.mq5 98 80 expression has no effect HFT_01.mq5 98 75 ',' - unexpected token HFT_01.mq5 98 106 ')' - unexpected token HFT_01.mq5 98 122 expression has no effect HFT_01.mq5 98 108 'OrderModify' - undeclared identifier HFT_01.mq5 104 21 ',' - unexpected token HFT_01.mq5 104 39 'ticket' - some operator expected HFT_01.mq5 104 33 ',' - unexpected token HFT_01.mq5 104 73 expression has no effect HFT_01.mq5 104 56 ',' - unexpected token HFT_01.mq5 104 80 expression has no effect HFT_01.mq5 104 75 ',' - unexpected token HFT_01.mq5 104 106 ')' - unexpected token HFT_01.mq5 104 122 expression has no effect HFT_01.mq5 104 108

  8. Assistant

    Os erros que você está encontrando no seu código MQL5 estão relacionados a algumas funções e operadores incorretamente utilizados, além de problemas de sintaxe. Vamos corrigi-los:

    1. Conversões implícitas de enumeração: Certifique-se de que você está utilizando os valores e métodos corretos associados aos tipos enumerados.

    2. Substituir OrderModify: Em MQL5, as operações de modificação de ordens são realizadas com a função OrderSend() com os tipos de modificação corretos em vez da função OrderModify() que existia no MQL4.

    3. Sintaxe em OrderSend: Corrigir a sintaxe do envio e modificação das ordens.

    4. Verificar Funções de Ordem: Podemos revisar e garantir que todas as operações e funções de ordens estejam utilizando os sintaxes adequados do MQL5.

    Vamos resolver essas questões no código:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    input int MaxOrders = 4;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    
    CTrade trade; // Utilizar a classe CTrade para operações comerciais
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        int openOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
    
        // Contar as ordens abertas por direção
        for (int i = 0; i < openOrders; i++) {
            if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    buyOrders++;
                }
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    sellOrders++;
                }
            }
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Verifica condições para abrir ordens sem hedge
        if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
            // Pode abrir nova direção
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
                // Abrir uma ordem de Compra
                OpenOrder(ORDER_BUY);
                currentDirection = 1;
            }
            else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
                // Abrir uma ordem de Venda
                OpenOrder(ORDER_SELL);
                currentDirection = -1;
            }
        }
    
        // Gerenciar trailing stop
        ManageTrailingStops();
    
        // Verifica se todas as ordens na direção atual foram fechadas
        if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
            currentDirection = 0;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));    
    }
    
    void OpenOrder(int orderType)
    {
        double lotSize = 0.1; // Lote fixo, ajustar conforme sua estratégia de gestão de risco
        double price = (orderType == ORDER_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
        double sl = (orderType == ORDER_BUY) ? price - TrailingStopPoints * _Point : price + TrailingStopPoints * _Point;
        trade.SetStopLossInPoints(TrailingStopPoints);
    
        if (orderType == ORDER_BUY) {
            if (!trade.Buy(lotSize, NULL, price, sl, 0)) {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        } else if (orderType == ORDER_SELL) {
            if (!trade.Sell(lotSize, NULL, price, sl, 0)) {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        for (int i = 0; i < OrdersTotal(); i++) {
            if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
                double newSl;
                ulong ticket = OrderGetTicket(i);
                if (OrderGetInteger(ORDER_TYPE) == ORDER_BUY) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
                else if (OrderGetInteger(ORDER_TYPE) == ORDER_SELL) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
            }
        }
    }
    

    Principais Alterações:

    • Uso da Biblioteca Trade.mqh: Utiliza a classe CTrade para gerenciar operações comerciais, que corrige a sintaxe de envio e modificação de ordens no MQL5.
    • Remoção do OrderModify: Substituído por trade.PositionModify() que é o método correto para modificar Stop Loss e Take Profit.
    • Iteração das Ordens: Garantia de que OrderSelect é corretamente utilizado para navegar através das posições.

    Teste o código com cuidado em um ambiente de demonstração antes de qualquer implementação em contas reais. Assegure-se também de ajustar os parâmetros e conceitos de gestão de risco de acordo com suas próprias necessidades e estratégias.

  9. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20; input int MaxOrders = 4;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum

    CTrade trade; // Utilizar a classe CTrade para operações comerciais

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); int openOrders = OrdersTotal(); int buyOrders = 0; int sellOrders = 0;

    // Contar as ordens abertas por direção
    for (int i = 0; i < openOrders; i++) {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                buyOrders++;
            }
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                sellOrders++;
            }
        }
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Verifica condições para abrir ordens sem hedge
    if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
            // Abrir uma ordem de Compra
            OpenOrder(ORDER_BUY);
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
            // Abrir uma ordem de Venda
            OpenOrder(ORDER_SELL);
            currentDirection = -1;
        }
    }
    
    // Gerenciar trailing stop
    ManageTrailingStops();
    
    // Verifica se todas as ordens na direção atual foram fechadas
    if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
        currentDirection = 0;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }

    void OpenOrder(int orderType) { double lotSize = 0.1; // Lote fixo, ajustar conforme sua estratégia de gestão de risco double price = (orderType == ORDER_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double sl = (orderType == ORDER_BUY) ? price - TrailingStopPoints * _Point : price + TrailingStopPoints * _Point; trade.SetStopLossInPoints(TrailingStopPoints);

    if (orderType == ORDER_BUY) {
        if (!trade.Buy(lotSize, NULL, price, sl, 0)) {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    } else if (orderType == ORDER_SELL) {
        if (!trade.Sell(lotSize, NULL, price, sl, 0)) {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStops() { for (int i = 0; i < OrdersTotal(); i++) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { double newSl; ulong ticket = OrderGetTicket(i); if (OrderGetInteger(ORDER_TYPE) == ORDER_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } else if (OrderGetInteger(ORDER_TYPE) == ORDER_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } } } }

    erros abaixo:

    'SELECT_BY_POS' - undeclared identifier HFT_01.mq5 23 28 'MODE_TRADES' - undeclared identifier HFT_01.mq5 23 43 'OrderSelect' - wrong parameters count HFT_01.mq5 23 13 built-in: bool OrderSelect(ulong) HFT_01.mq5 23 13 'ORDER_BUY' - undeclared identifier HFT_01.mq5 41 23 'ORDER_SELL' - undeclared identifier HFT_01.mq5 46 23 'ORDER_BUY' - undeclared identifier HFT_01.mq5 69 34 'ORDER_BUY' - undeclared identifier HFT_01.mq5 70 31 'SetStopLossInPoints' - undeclared identifier HFT_01.mq5 71 11 'TrailingStopPoints' - some operator expected HFT_01.mq5 71 31 'ORDER_BUY' - undeclared identifier HFT_01.mq5 73 22 'ORDER_SELL' - undeclared identifier HFT_01.mq5 77 29 'SELECT_BY_POS' - undeclared identifier HFT_01.mq5 87 28 'MODE_TRADES' - undeclared identifier HFT_01.mq5 87 43 'OrderSelect' - wrong parameters count HFT_01.mq5 87 13 built-in: bool OrderSelect(ulong) HFT_01.mq5 87 13 'ORDER_BUY' - undeclared identifier HFT_01.mq5 90 48 'ORDER_SELL' - undeclared identifier HFT_01.mq5 96 53

  10. Assistant

    Para corrigir os erros mencionados no seu código MQL5, vamos revisar e ajudar com as correções necessárias. Os erros estão relacionados à importação e uso incorretos de enums e funções do MQL5. Vamos corrigir isso:

    Ajustes Necessários:

    1. Importar Enums e Constantes: Certifique-se de incluir os cabeçalhos corretos para enums, como os tipos de ordem (ORDER_BUY, ORDER_SELL) e constantes (SELECT_BY_POS, MODE_TRADES).

    2. Funções de Seleção de Ordem: Em MQL5, OrderSelect aceita um ticket de ordem como argumento e não usa SELECT_BY_POS ou MODE_TRADES como no MQL4.

    3. Funções de Trailing Stop e Modificação de Ordem: A classe CTrade possui métodos para gerenciar ordens sem a necessidade de definir trailing stops manualmente. Vamos revisar o código de trailing stop.

    4. Erros de Sintaxe: Vamos corrigir os erros de sintaxe e remover as chamadas a métodos não reconhecidos.

    Código Corrigido:

    #include <Trade\Trade.mqh>
    #include <Trade\SymbolInfo.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    input int MaxOrders = 4;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        int openOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
    
        // Contar as ordens abertas por direção
        for (int i = 0; i < openOrders; i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    buyOrders++;
                }
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    sellOrders++;
                }
            }
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Verifica condições para abrir ordens sem hedge
        if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
            // Pode abrir nova direção
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
                OpenOrder(ORDER_BUY); // Abrir uma ordem de Compra
                currentDirection = 1;
            }
            else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
                OpenOrder(ORDER_SELL); // Abrir uma ordem de Venda
                currentDirection = -1;
            }
        }
    
        // Gerenciar trailing stop
        ManageTrailingStops();
    
        // Verifica se todas as ordens na direção atual foram fechadas
        if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
            currentDirection = 0;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));    
    }
    
    void OpenOrder(int orderType)
    {
        double lotSize = 0.1; // Lote fixo
        trade.SetStopLossInPoints(TrailingStopPoints);
        if (orderType == ORDER_BUY) {
            if (!trade.Buy(lotSize)) {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        } else if (orderType == ORDER_SELL) {
            if (!trade.Sell(lotSize)) {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        for (int i = 0; i < OrdersTotal(); i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                double newSl;
                if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
                else if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
            }
        }
    }
    

    Ajustes Importantes:

    • Inclusão Correta de Enums: Certifique-se de que os headers adequados são inclusos. A biblioteca Trade.mqh e outras essenciais devem fornecer os enums necessários, como ORDER_BUY e ORDER_SELL.
    • Verificação com OrderSelect: Agora usa apenas o ticket de ordem para localizar ordens abertas.
    • Chamadas de Função da CTrade: Modificação das ordens agora usa trade.PositionModify() conforme apropriado para MQL5.

    Teste o código em ambiente de demonstração antes de qualquer uso em conta real para garantir que ele se comporte conforme esperado e faça qualquer ajuste adicional que possa ser necessário.

  11. User

    #include <Trade\Trade.mqh> #include <Trade\SymbolInfo.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20; input int MaxOrders = 4;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); int openOrders = OrdersTotal(); int buyOrders = 0; int sellOrders = 0;

    // Contar as ordens abertas por direção
    for (int i = 0; i < openOrders; i++) {
        ulong ticket = OrderGetTicket(i);
        if (OrderSelect(ticket)) {
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) {
                buyOrders++;
            }
            if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) {
                sellOrders++;
            }
        }
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Verifica condições para abrir ordens sem hedge
    if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
            OpenOrder(ORDER_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
            OpenOrder(ORDER_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    // Gerenciar trailing stop
    ManageTrailingStops();
    
    // Verifica se todas as ordens na direção atual foram fechadas
    if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
        currentDirection = 0;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }

    void OpenOrder(int orderType) { double lotSize = 0.1; // Lote fixo trade.SetStopLossInPoints(TrailingStopPoints); if (orderType == ORDER_BUY) { if (!trade.Buy(lotSize)) { Print("Falha ao abrir ordem de compra: ", GetLastError()); } } else if (orderType == ORDER_SELL) { if (!trade.Sell(lotSize)) { Print("Falha ao abrir ordem de venda: ", GetLastError()); } } }

    void ManageTrailingStops() { for (int i = 0; i < OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if (OrderSelect(ticket)) { double newSl; if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } else if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } } } }

    erros abaixo:

    'ORDER_BUY' - undeclared identifier HFT_01.mq5 41 23 'ORDER_SELL' - undeclared identifier HFT_01.mq5 45 23 'SetStopLossInPoints' - undeclared identifier HFT_01.mq5 68 11 'TrailingStopPoints' - some operator expected HFT_01.mq5 68 31 'ORDER_BUY' - undeclared identifier HFT_01.mq5 69 22 'ORDER_SELL' - undeclared identifier HFT_01.mq5 73 29

  12. Assistant

    Os erros que você está enfrentando estão relacionados principalmente à falta de definição de identificadores específicos no MQL5, como ORDER_BUY e ORDER_SELL, e ao uso incorreto de métodos para gerenciar stop loss. Para resolver isso, vamos fazer as seguintes correções:

    Correções Necessárias:

    1. Definição de ORDER_BUY e ORDER_SELL: No MQL5, você deve usar POSITION_TYPE_BUY e POSITION_TYPE_SELL para identificar o tipo de operação de compra e venda quando estiver trabalhando com posições.

    2. Método SetStopLossInPoints: Esse método não existe na classe CTrade. Em vez disso, você pode definir o stop loss diretamente ao enviar a ordem com as funções Buy ou Sell do objeto CTrade.

    3. Bibliotecas e Funções: Certifique-se de que todas as bibliotecas e suas funções são utilizadas corretamente.

    Veja como o código revisado deve ficar:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    input int MaxOrders = 4;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        int openOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
    
        // Contar as ordens abertas por direção
        for (int i = 0; i < openOrders; i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_BUY) {
                    buyOrders++;
                }
                if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_SELL) {
                    sellOrders++;
                }
            }
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Verifica condições para abrir ordens sem hedge
        if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
            // Pode abrir nova direção
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
                OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
                currentDirection = 1;
            }
            else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
                OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
                currentDirection = -1;
            }
        }
    
        // Gerenciar trailing stop
        ManageTrailingStops();
    
        // Verifica se todas as ordens na direção atual foram fechadas
        if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
            currentDirection = 0;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));    
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = TrailingStopPoints * _Point;
        if (positionType == POSITION_TYPE_BUY) {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0)) {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        } else if (positionType == POSITION_TYPE_SELL) {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0)) {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        for (int i = 0; i < OrdersTotal(); i++) {
            ulong ticket = OrderGetTicket(i);
            if (OrderSelect(ticket)) {
                double newSl;
                if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_BUY) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
                else if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_SELL) {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < OrderGetDouble(ORDER_SL)) {
                        trade.PositionModify(ticket, newSl, 0);
                    }
                }
            }
        }
    }
    

    Notas Adicionais:

    • Ajustes de Parâmetros: Você pode querer ajustar o tamanho do lote e o valor de trailing stop conforme seu gerenciamento de risco e estratégia específica.
    • Testes Extensivos: Como sempre, teste o robô em um ambiente de demonstração antes de implementá-lo em operações reais para garantir que ele funcione conforme o esperado.
  13. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20; input int MaxOrders = 4;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID); int openOrders = OrdersTotal(); int buyOrders = 0; int sellOrders = 0;

    // Contar as ordens abertas por direção
    for (int i = 0; i < openOrders; i++) {
        ulong ticket = OrderGetTicket(i);
        if (OrderSelect(ticket)) {
            if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_BUY) {
                buyOrders++;
            }
            if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_SELL) {
                sellOrders++;
            }
        }
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Verifica condições para abrir ordens sem hedge
    if (currentDirection == 0 && buyOrders == 0 && sellOrders == 0) {
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1) {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1) {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    // Gerenciar trailing stop
    ManageTrailingStops();
    
    // Verifica se todas as ordens na direção atual foram fechadas
    if ((currentDirection == 1 && buyOrders == 0) || (currentDirection == -1 && sellOrders == 0)) {
        currentDirection = 0;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = TrailingStopPoints * _Point; if (positionType == POSITION_TYPE_BUY) { if (!trade.Buy(lotSize, NULL, 0, sl, 0)) { Print("Falha ao abrir ordem de compra: ", GetLastError()); } } else if (positionType == POSITION_TYPE_SELL) { if (!trade.Sell(lotSize, NULL, 0, sl, 0)) { Print("Falha ao abrir ordem de venda: ", GetLastError()); } } }

    void ManageTrailingStops() { for (int i = 0; i < OrdersTotal(); i++) { ulong ticket = OrderGetTicket(i); if (OrderSelect(ticket)) { double newSl; if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } else if (OrderGetInteger(ORDER_TYPE) == POSITION_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < OrderGetDouble(ORDER_SL)) { trade.PositionModify(ticket, newSl, 0); } } } } }

    esta abrindo muitas ordens ao mesmo tempo preciso que abra apenas uma ordem por vez

  14. Assistant

    Para garantir que o sistema abra apenas uma ordem por vez, é essencial verificar se não há ordens abertas antes de tentar abrir uma nova. Como o código atual tenta contar as ordens de compra e venda existentes, nós simplesmente precisamos modificar a lógica para garantir que não abra uma nova ordem se já houver uma aberta. Além disso, vamos simplificar verificando apenas se já existe uma posição aberta em vez de contar, usando a função PositionSelect(), que verifica se já existe uma posição aberta no símbolo.

    Vamos corrigir o código para garantir que ele abra apenas uma ordem por vez:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Verifique se já existe uma posição aberta
        if (PositionSelect(_Symbol))
        {
            // Não abre novas ordens se já houver uma posição aberta
            ManageTrailingStops(); // Ajusta apenas o trailing stop, se necessário
            return;
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = TrailingStopPoints * _Point;
    
        if (positionType == POSITION_TYPE_BUY)
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL)
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        if (PositionSelect(_Symbol))
        {
            ulong ticket = PositionGetTicket();
            double newSl;
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                if (newSl > PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(ticket, newSl, 0);
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                if (newSl < PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(ticket, newSl, 0);
                }
            }
        }
    }
    

    Explicação das Alterações:

    • PositionSelect(_Symbol): Isso verifica se já há uma posição aberta no símbolo atual, evitando a abertura de novas ordens se uma posição já existir.

    • Remoção da contagem de ordens: A contagem de ordens foi reduzida, usando diretamente a função PositionSelect() para determinar se uma nova posição pode ser aberta.

    • Lógica de Trailing Stop: A lógica foi mantida para ajustar o trailing stop para qualquer posição existente.

    Certifique-se de testar o código em um ambiente de demonstração para garantir que ele atue conforme esperado antes de implementar em uma conta real.

  15. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Verifique se já existe uma posição aberta
    if (PositionSelect(_Symbol))
    {
        // Não abre novas ordens se já houver uma posição aberta
        ManageTrailingStops(); // Ajusta apenas o trailing stop, se necessário
        return;
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Pode abrir nova direção
    if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
        currentDirection = 1;
    }
    else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
        currentDirection = -1;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0)); }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = TrailingStopPoints * _Point;

    if (positionType == POSITION_TYPE_BUY)
    {
        if (!trade.Buy(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    }
    else if (positionType == POSITION_TYPE_SELL)
    {
        if (!trade.Sell(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStops() { if (PositionSelect(_Symbol)) { ulong ticket = PositionGetTicket(); double newSl; if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > PositionGetDouble(POSITION_SL)) { trade.PositionModify(ticket, newSl, 0); } } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < PositionGetDouble(POSITION_SL)) { trade.PositionModify(ticket, newSl, 0); } } } }

    erro abaixo:

    'PositionGetTicket' - wrong parameters count HFT_01.mq5 71 24 built-in: ulong PositionGetTicket(uint) HFT_01.mq5 71 24

  16. Assistant

    Peço desculpas pelo erro. O MQL5 requer que o PositionGetTicket() não aceite argumentos, pois ele retorna o ticket da posição previamente selecionada usando PositionSelect().

    Aqui está um código corrigido:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 20;
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Verifique se já existe uma posição aberta
        if (PositionSelect(_Symbol))
        {
            // Não abre novas ordens se já houver uma posição aberta
            ManageTrailingStops(); // Ajusta apenas o trailing stop, se necessário
            return;
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = TrailingStopPoints * _Point;
    
        if (positionType == POSITION_TYPE_BUY)
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL)
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        if (PositionSelect(_Symbol))
        {
            double newSl;
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                if (newSl > PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                if (newSl < PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                }
            }
        }
    }
    

    Explicação:

    • Correção do Método PositionGetTicket: Utilizamos PositionGetInteger(POSITION_TICKET) para obter o ticket da posição atual. Esta chamada não requer parâmetros e é a maneira correta de recuperar o ticket de uma posição.

    Certifique-se de testar este código em um ambiente de demonstração antes de qualquer implementação em contas reais para garantir que as modificações funcionem conforme esperado.

  17. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Verifique se já existe uma posição aberta
    if (PositionSelect(_Symbol))
    {
        // Não abre novas ordens se já houver uma posição aberta
        ManageTrailingStops(); // Ajusta apenas o trailing stop, se necessário
        return;
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Pode abrir nova direção
    if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
        currentDirection = 1;
    }
    else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
        currentDirection = -1;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0)); }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = TrailingStopPoints * _Point;

    if (positionType == POSITION_TYPE_BUY)
    {
        if (!trade.Buy(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    }
    else if (positionType == POSITION_TYPE_SELL)
    {
        if (!trade.Sell(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStops() { if (PositionSelect(_Symbol)) { double newSl; if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > PositionGetDouble(POSITION_SL)) { trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0); } } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < PositionGetDouble(POSITION_SL)) { trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0); } } } }

    percebi que com esse codigo estou sendo stopado e tendo prejuizo o tempo todo analise e diga oque podemelhorar em questao de trailing stops etc

  18. Assistant

    Para melhorar o desempenho do robô e reduzir o risco de ser estopado frequentemente, podemos considerar ajustamentos em várias áreas, incluindo a lógica de trailing stop, o ponto de entrada e talvez implementar outro mecanismo de gerenciamento de risco. Aqui estão algumas sugestões:

    1. Ajustar o Trailing Stop:

    • Tamanho do Trailing Stop: Se o trailing stop está muito apertado, você pode ser estopado por oscilações pequenas do mercado. Considere aumentar o número de pontos para oferecer mais "margem de manobra".

    • Iniciar o Trailing Stop Após Alcançar Lucro: Configure o trailing stop para começar a se mover somente depois que a posição tenha alcançado um determinado nível de lucro. Isso evita que o trailing stop se mova antes que haja um colchão de lucro.

    2. Review de Pontos de Entrada:

    • Confirmar Entrada com Outro Indicador: Utilize outro indicador, como o RSI ou MACD, para confirmar que a entrada está alinhada com a tendência geral ou correção esperada.

    3. Estratégia de Saída:

    • Definir Níveis Fixos de Stop Loss e Take Profit: Além do trailing stop, considere definir um stop loss fixo que esteja mais alinhado com seu ponto de entrada e volatilidade do mercado.

    4. Gerenciamento de Risco:

    • Redução do Tamanho do Lote: Use um tamanho de lote menor se estiver percebendo perdas excessivas, ajustando assim sua exposição ao risco até que a estratégia se prove eficaz.

    Código Aperfeiçoado:

    Abaixo está uma modificação que inclui um trailing stop mais estratégico:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input int TrailingStopPoints = 50; // Ajuste este valor conforme a volatilidade
    input int InitialProfitPoints = 100; // Apenas exemplo, mudar conforme sua análise
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Verifique se já existe uma posição aberta
        if (PositionSelect(_Symbol))
        {
            // Ajuste o trailing stop, se necessário
            ManageTrailingStops();
            return;
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = TrailingStopPoints * _Point;
        double tp = InitialProfitPoints * _Point;
    
        if (positionType == POSITION_TYPE_BUY)
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, tp)) // Ajustando para incluir um TP inicial
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL)
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, tp)) // Ajustando para incluir um TP inicial
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStops()
    {
        if (PositionSelect(_Symbol))
        {
            double newSl;
            double posOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            double currentProfit = PositionGetDouble(POSITION_PROFIT);
    
            // Só começar a trailing stop após alcançar o lucro inicial
            if (currentProfit > InitialProfitPoints * _Point)
            {
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point;
                    if (newSl > PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point;
                    if (newSl < PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                    }
                }
            }
        }
    }
    

    Sugestões de Teste:

    • Backtest Extensivo: Execute testes de backtest em dados históricos para compreender o comportamento e efetividade dessas alterações.

    • Ajuste Dinâmico: Considerar adaptar parâmetros conforme seu entendimento dos mercados e condições de volatilidade.

    • Monitorar Efetividade: Observe quaisquer padrões emergentes de ineficiência e ajuste os níveis de stop e targets conforme necessário, sem ultrapassar limites razoáveis de avaliação e mudança.

    O objetivo principal é encontrar um equilíbrio entre proteger lucros e não ser estopado muito cedo devido a pequenas flutuações de preços.

  19. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input int TrailingStopPoints = 20;

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Verifique se já existe uma posição aberta
    if (PositionSelect(_Symbol))
    {
        // Não abre novas ordens se já houver uma posição aberta
        ManageTrailingStops(); // Ajusta apenas o trailing stop, se necessário
        return;
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Pode abrir nova direção
    if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
        currentDirection = 1;
    }
    else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
        currentDirection = -1;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0)); }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = TrailingStopPoints * _Point;

    if (positionType == POSITION_TYPE_BUY)
    {
        if (!trade.Buy(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    }
    else if (positionType == POSITION_TYPE_SELL)
    {
        if (!trade.Sell(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStops() { if (PositionSelect(_Symbol)) { double newSl; if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_BID) - TrailingStopPoints * _Point; if (newSl > PositionGetDouble(POSITION_SL)) { trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0); } } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) { newSl = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TrailingStopPoints * _Point; if (newSl < PositionGetDouble(POSITION_SL)) { trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0); } } } }

    aumente o stop loss para ficar no nivel de 100% da fibo e um trailing stops ajustado para scalping e a cada vela de 1 minuto que tiver um lucro de 10 a 20 pontos fechar a order para garantir o lucro

  20. Assistant

    Para ajustar o código para que o stop loss inicial seja colocado no nível de 100% de Fibonacci e implementar um trailing stop mais adaptado para scalping, além de fechar ordens a cada vela de 1 minuto que atinja um lucro de 10 a 20 pontos, você pode seguir o código abaixo. Esta abordagem envolve atualização do método de gerenciamento de posições para incluir essa nova lógica de fechamento e ajuste de trailing stop.

    Código Ajustado:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input double ScalpingProfit = 10; // Lucro alvo por ponto
    input int TrailingStopPoints = 5; // Ajustado para scalping
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Verifique se já existe uma posição aberta
        if (PositionSelect(_Symbol))
        {
            // Não abre novas ordens se já houver uma posição aberta
            ManageTrailingStopsAndProfit();
            return;
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice; // Stop loss em nível de 100% da Fibo
    
        if (positionType == POSITION_TYPE_BUY)
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL)
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStopsAndProfit()
    {
        if (PositionSelect(_Symbol))
        {
            double newSl;
            double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            double profitPoints = (currentPrice - openPrice) / _Point;
    
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                // Ajuste o trailing stop
                newSl = currentPrice - TrailingStopPoints * _Point;
                if (newSl > PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                }
                // Fecha a posição se o lucro for suficiente
                if (profitPoints >= ScalpingProfit)
                {
                    trade.PositionClose(PositionGetInteger(POSITION_TICKET));
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                // Ajuste o trailing stop
                newSl = currentPrice + TrailingStopPoints * _Point;
                if (newSl < PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                }
                // Fecha a posição se o lucro for suficiente
                if (profitPoints <= -ScalpingProfit)
                {
                    trade.PositionClose(PositionGetInteger(POSITION_TICKET));
                }
            }
        }
    }
    

    Ajustes e Conceitos Chave:

    1. Stop Loss Baseado em Fibonacci: O stop loss é posicionado no nível de 100% Fibonacci (high ou low do movimento).

    2. Trailing Stop para Scalping: Um trailing stop mais apertado para permitir que você proteja pequenos lucros rapidamente.

    3. Fechamento de Ordem com Base em Lucro: Introduz lógica que fecha a posição toda vez que um lucro predeterminado é atingido em pontos, adequando-se ao estilo de scalping.

    4. Verificação Subsidiária: Há inclusão da lógica para que a ordem seja fechada quando atinge um determinado alvo de lucro ou perda em termos de pontos.

    Importante:

    • Volatilidade: Teste e ajuste o TrailingStopPoints e o ScalpingProfit conforme necessário para se adaptar às condições de volatilidade do mercado.

    • Backtesting: Realize testes extensivos com dados históricos antes de usar em contas reais para garantir que a estratégia funcione conforme esperado e faça ajustes baseados nos resultados.

    Seguir essas estratégias ajudará a evitar ser estopado em movimentos contra pequenos e a garantir lucros menores mais frequentemente em um estilo semelhante ao scalping.

  21. User

    preciso que seja fechado ordem assim que a ordem estiver positiva entre 10, 20 a 30 pontos nao deixar o trailing stop fechar a ordem caso esteja saldo negativo ainda

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input double ScalpingProfit = 10; // Lucro alvo por ponto input int TrailingStopPoints = 5; // Ajustado para scalping

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Verifique se já existe uma posição aberta
    if (PositionSelect(_Symbol))
    {
        // Não abre novas ordens se já houver uma posição aberta
        ManageTrailingStopsAndProfit();
        return;
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Pode abrir nova direção
    if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
        currentDirection = 1;
    }
    else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
        currentDirection = -1;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0)); }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice; // Stop loss em nível de 100% da Fibo

    if (positionType == POSITION_TYPE_BUY)
    {
        if (!trade.Buy(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    }
    else if (positionType == POSITION_TYPE_SELL)
    {
        if (!trade.Sell(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStopsAndProfit() { if (PositionSelect(_Symbol)) { double newSl; double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID); double openPrice = PositionGetDouble(POSITION_PRICE_OPEN); double profitPoints = (currentPrice - openPrice) / _Point;

        if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
        {
            // Ajuste o trailing stop
            newSl = currentPrice - TrailingStopPoints * _Point;
            if (newSl > PositionGetDouble(POSITION_SL))
            {
                trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
            }
            // Fecha a posição se o lucro for suficiente
            if (profitPoints >= ScalpingProfit)
            {
                trade.PositionClose(PositionGetInteger(POSITION_TICKET));
            }
        }
        else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
        {
            // Ajuste o trailing stop
            newSl = currentPrice + TrailingStopPoints * _Point;
            if (newSl < PositionGetDouble(POSITION_SL))
            {
                trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
            }
            // Fecha a posição se o lucro for suficiente
            if (profitPoints <= -ScalpingProfit)
            {
                trade.PositionClose(PositionGetInteger(POSITION_TICKET));
            }
        }
    }
    

    }

  22. Assistant

    Para implementar a lógica onde uma ordem será fechada apenas quando estiver com lucro entre 10 a 30 pontos, e ajustar o trailing stop para não encerrar a posição negativamente, podemos modificar a função ManageTrailingStopsAndProfit para calcular os pontos de ganho e fechar apenas se estiver dentro do intervalo desejado. O trailing stop só será aplicado se a posição estiver lucrativa dentro desse intervalo.

    Vamos ajustar o código:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input double MinScalpingProfit = 10; // Lucro mínimo para fechamento
    input double MaxScalpingProfit = 30; // Lucro máximo para fechamento
    input int TrailingStopPoints = 5; // Ajustado para scalping
    
    double highPrice, lowPrice;
    int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Verifique se já existe uma posição aberta
        if (PositionSelect(_Symbol))
        {
            // Não abre novas ordens se já houver uma posição aberta
            ManageTrailingStopsAndProfit();
            return;
        }
    
        // Calcular Níveis de Fibonacci
        CalculateFibonacciLevels();
    
        // Pode abrir nova direção
        if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
            currentDirection = 1;
        }
        else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
        {
            OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
            currentDirection = -1;
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1; // Lote fixo
        double sl = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice; // Stop loss em nível de 100% da Fibo
    
        if (positionType == POSITION_TYPE_BUY)
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL)
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManageTrailingStopsAndProfit()
    {
        if (PositionSelect(_Symbol))
        {
            double newSl, openPrice, currentPrice, profitPoints;
            ulong positionTicket = PositionGetInteger(POSITION_TICKET);
            openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) 
                           ? SymbolInfoDouble(_Symbol, SYMBOL_BID) 
                           : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            
            profitPoints = (currentPrice - openPrice) / _Point * ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? 1 : -1);
            
            if (profitPoints >= MinScalpingProfit)
            {
                // Ajuste o trailing stop apenas para posições atualmente lucrativas
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    newSl = currentPrice - TrailingStopPoints * _Point;
                    if (newSl > PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(positionTicket, newSl, 0);
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    newSl = currentPrice + TrailingStopPoints * _Point;
                    if (newSl < PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(positionTicket, newSl, 0);
                    }
                }
    
                // Fecha a posição se o lucro estiver dentro do intervalo desejado
                if (profitPoints >= MinScalpingProfit && profitPoints <= MaxScalpingProfit)
                {
                    trade.PositionClose(positionTicket);
                }
            }
        }
    }
    

    Mudanças Feitas:

    1. Intervalo de Lucro para Fechamento de Posição: Agora a posição é fechada somente se o lucro estiver entre 10 e 30 pontos.

    2. Trailing Stop Aplicado Somente a Lucros: O trailing stop agora só modifica o stop loss quando a posição é lucrativa e dentro do intervalo permitido.

    3. Lógica de Lucro Ajustada: Para calcular corretamente o lucro em pontos considerando a direção da posição (compra ou venda).

    Testes:

    Execute backtests amplos e talvez um período de teste em uma conta demo para garantir que a estratégia funcione conforme desejado. Ajuste os parâmetros de profit points e trailing stop conforme necessário, de acordo com a volatilidade e estilo de trading de scalping desejado.

  23. User

    #include <Trade\Trade.mqh>

    input double FibLevel1 = 0.382; input double FibLevel2 = 0.500; input double FibLevel3 = 0.618; input double MinScalpingProfit = 10; // Lucro mínimo para fechamento input double MaxScalpingProfit = 30; // Lucro máximo para fechamento input int TrailingStopPoints = 5; // Ajustado para scalping

    double highPrice, lowPrice; int currentDirection = 0; // 1 para Buy, -1 para Sell, 0 para nenhum CTrade trade;

    void OnTick() { double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    // Verifique se já existe uma posição aberta
    if (PositionSelect(_Symbol))
    {
        // Não abre novas ordens se já houver uma posição aberta
        ManageTrailingStopsAndProfit();
        return;
    }
    
    // Calcular Níveis de Fibonacci
    CalculateFibonacciLevels();
    
    // Pode abrir nova direção
    if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_BUY); // Abrir uma ordem de Compra
        currentDirection = 1;
    }
    else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
    {
        OpenOrder(POSITION_TYPE_SELL); // Abrir uma ordem de Venda
        currentDirection = -1;
    }
    

    }

    void CalculateFibonacciLevels() { highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0)); lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0)); }

    void OpenOrder(int positionType) { double lotSize = 0.1; // Lote fixo double sl = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice; // Stop loss em nível de 100% da Fibo

    if (positionType == POSITION_TYPE_BUY)
    {
        if (!trade.Buy(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de compra: ", GetLastError());
        }
    }
    else if (positionType == POSITION_TYPE_SELL)
    {
        if (!trade.Sell(lotSize, NULL, 0, sl, 0))
        {
            Print("Falha ao abrir ordem de venda: ", GetLastError());
        }
    }
    

    }

    void ManageTrailingStopsAndProfit() { if (PositionSelect(_Symbol)) { double newSl, openPrice, currentPrice, profitPoints; ulong positionTicket = PositionGetInteger(POSITION_TICKET); openPrice = PositionGetDouble(POSITION_PRICE_OPEN); currentPrice = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);

        profitPoints = (currentPrice - openPrice) / _Point * ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? 1 : -1);
        
        if (profitPoints >= MinScalpingProfit)
        {
            // Ajuste o trailing stop apenas para posições atualmente lucrativas
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                newSl = currentPrice - TrailingStopPoints * _Point;
                if (newSl > PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(positionTicket, newSl, 0);
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                newSl = currentPrice + TrailingStopPoints * _Point;
                if (newSl < PositionGetDouble(POSITION_SL))
                {
                    trade.PositionModify(positionTicket, newSl, 0);
                }
            }
    
            // Fecha a posição se o lucro estiver dentro do intervalo desejado
            if (profitPoints >= MinScalpingProfit && profitPoints <= MaxScalpingProfit)
            {
                trade.PositionClose(positionTicket);
            }
        }
    }
    

    }

    com este codigo en caso da ordem esta abert em compra e derrepente o preço muda de direção mudando a tendencia oque acontece? pois percebi que o stoploss fica muito longe teria como robo detectar essa mudança de tendencia usando penas a fibo e cancelar a orden anterio em caso desse risco e abrir para lado oposto para ter lucro?

  24. Assistant

    Para abordar a questão de mudança repentina de tendência e ajustar a estratégia para reagir adequadamente, é necessário implementar uma detecção de reversão potencial baseada em Fibonacci e talvez em outros sinais, como cruzamento de médias móveis ou até análise de preço em múltiplos prazos. Aqui, vamos implementar uma estratégia básica que tenta reagir a mudanças de tendência ao ajustar o stop loss mais perto ou inverter a posição.

    Estratégia:

    1. Utilizar Níveis de Fibonacci para Detectar Reversão: Ao romper um nível crítico de Fibonacci (como 100%, próximo da atual operação), pode-se interpretar como um sinal de que a tendência pode estar mudando.

    2. Inverter Posições: Seguindo um rompimento claro de Fibonacci e potencial confirmação de mudança de tendência, encerre a posição atual e abra uma nova no sentido oposto.

    3. Ajustar o Stop Loss: Ao percorrer sempre que houver sinais de fraqueza na direção.

    Código Ajustado:

    Este exemplo é uma representação básica e deverá ser ajustado e extensivamente testado:

    #include <Trade\Trade.mqh>
    
    input double FibLevel1 = 0.382;
    input double FibLevel2 = 0.500;
    input double FibLevel3 = 0.618;
    input double MinScalpingProfit = 10;
    input double MaxScalpingProfit = 30;
    input int TrailingStopPoints = 5;
    
    double highPrice, lowPrice;
    CTrade trade;
    
    void OnTick()
    {
        double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        if (PositionSelect(_Symbol))
        {
            // Se há uma posição aberta, verifica e gerencia a posição
            ManagePositions();
        }
        else
        {
            // Calcular Níveis de Fibonacci
            CalculateFibonacciLevels();
    
            // Abrir uma nova ordem com base em Fibonacci
            if (price <= lowPrice + (highPrice - lowPrice) * FibLevel1)
            {
                OpenOrder(POSITION_TYPE_BUY);
            }
            else if (price >= highPrice - (highPrice - lowPrice) * FibLevel1)
            {
                OpenOrder(POSITION_TYPE_SELL);
            }
        }
    }
    
    void CalculateFibonacciLevels()
    {
        highPrice = iHigh(_Symbol, PERIOD_H1, iHighest(_Symbol, PERIOD_H1, MODE_HIGH, 24, 0));
        lowPrice = iLow(_Symbol, PERIOD_H1, iLowest(_Symbol, PERIOD_H1, MODE_LOW, 24, 0));
    }
    
    void OpenOrder(int positionType)
    {
        double lotSize = 0.1;
        double sl = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice; // Ajuste conforme necessário
    
        if (positionType == POSITION_TYPE_BUY && (SymbolInfoDouble(_Symbol, SYMBOL_BID) > sl))
        {
            if (!trade.Buy(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de compra: ", GetLastError());
            }
        }
        else if (positionType == POSITION_TYPE_SELL && (SymbolInfoDouble(_Symbol, SYMBOL_ASK) < sl))
        {
            if (!trade.Sell(lotSize, NULL, 0, sl, 0))
            {
                Print("Falha ao abrir ordem de venda: ", GetLastError());
            }
        }
    }
    
    void ManagePositions()
    {
        if (PositionSelect(_Symbol))
        {
            double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            double profitPoints = (currentPrice - openPrice) / _Point * ((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? 1 : -1);
            double positionType = PositionGetInteger(POSITION_TYPE);
            double slLevel = (positionType == POSITION_TYPE_BUY) ? lowPrice : highPrice;
    
            // Detecta a mudança de tendência usando o rompimento da Fibo de 100%
            if ((positionType == POSITION_TYPE_BUY && currentPrice < slLevel) ||
                (positionType == POSITION_TYPE_SELL && currentPrice > slLevel))
            {
                trade.PositionClose(PositionGetInteger(POSITION_TICKET)); // Fechar posição atual
                int newPositionType = (positionType == POSITION_TYPE_BUY) ? POSITION_TYPE_SELL : POSITION_TYPE_BUY;
                OpenOrder(newPositionType); // Abre posição no sentido oposto
                return;
            }
    
            // Ajuste de trailing stop e lucro
            double newSl;
            if (profitPoints >= MinScalpingProfit)
            {
                if (positionType == POSITION_TYPE_BUY)
                {
                    newSl = currentPrice - TrailingStopPoints * _Point;
                    if (newSl > PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                    }
                }
                else if (positionType == POSITION_TYPE_SELL)
                {
                    newSl = currentPrice + TrailingStopPoints * _Point;
                    if (newSl < PositionGetDouble(POSITION_SL))
                    {
                        trade.PositionModify(PositionGetInteger(POSITION_TICKET), newSl, 0);
                    }
                }
    
                if (profitPoints >= MinScalpingProfit && profitPoints <= MaxScalpingProfit)
                {
                    trade.PositionClose(PositionGetInteger(POSITION_TICKET));
                }
            }
        }
    }
    

    Comentários:

    • Detecção de Mudança de Tendência: A lógica básica foi implementada para fechar a posição atual e abrir outra posição na direção oposta caso o nível de 100% de Fibonacci seja violado.

    • Trailing Stop Ajustado: O trailing stop move o nível de stop loss para proteger ganhos quando a posição se torna definitivamente lucrativa.

    Importante:

    Essas modificações representam uma estratégia base que pode precisar de testes exaustivos para verificar a eficácia em diferentes condições de mercado. Inclua outras análises técnicas ou sinais para reforçar ainda mais os sinais de reversão e mitigar falsos positivos. Ajuste os parâmetros baseados em backtests e revisões iterativas para encontrar o ajuste certo para seu perfil de trading e condição de mercado esperada.