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

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

  1. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

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

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

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

    //+------------------------------------------------------------------+ //| 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
    TrailStop();
    

    }

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

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

    }

    parece que esse robo acima esta fazendo estrategia de Grid como o codigo abaixo oque é impressao minha?

    #property copyright "Copyright 2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00"

    #include <Trade/Trade.mqh>

    CTrade trade; CPositionInfo pos; COrderInfo ord; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+

    input group "*** Trading Inputs ***"

         input double RiskPercent         = 3;   // Risk as % of Trading capital)
         input int    Tppoints            = 200; // Take Profit (10 points = 1 pip)
         input int    Slpoints            = 200; // Stoploss Points (10 points = 1 pip)
         input int    TslTriggerPoints    = 15;  // Points in profit before Trailing SL is activated (10 points = 1 pip)
         input int    TslPoints           = 10;  // Trailing Stoploss (10 points = 1 pip)
         input ENUM_TIMEFRAMES Timeframe  = PERIOD_CURRENT; //Time frame to run
         input int    InpMagic            = 298347; //EA indentification no
         input string TradeComment = "Scalpin Robot";
         
         
         enum StarHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
         input StarHour SHInput=0; // Star Hour
         
         enum EndHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
         input EndHour EHInput=0; // End Hour
         
         int SHChoice;
         int EHChoice;
         
         int BarsN            = 5;
         int ExpirationBars   = 100;
         int OrderDistPoints = 100;
         
         
    

    int OnInit() { //---

    //---

      trade.SetExpertMagicNumber(InpMagic);
      
         ChartSetInteger(0,CHART_SHOW_GRID,false);
    
      return(INIT_SUCCEEDED);
    

    } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //---

    } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //---

      TrailStop();
    
      if(!IsNewBar())return;
      
      MqlDateTime time;
      TimeToStruct(TimeCurrent(),time);
      
      int Hournow = time.hour;
      
      SHChoice = SHInput;
      EHChoice = EHInput;
      
      if(Hournow<SHChoice){CloseAllOrders(); return;}
      if(Hournow>=EHChoice && EHChoice!=0){CloseAllOrders(); return;}
      
      int BuyTotal=0;
      int SellTotal=0;
      
      
      for (int i=PositionsTotal()-1; i>=0; i--){
         pos.SelectByIndex(i);
         if(pos.PositionType()==POSITION_TYPE_BUY && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) BuyTotal++;
         if(pos.PositionType()==POSITION_TYPE_SELL && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) SellTotal++;
       }
       
       for (int i=PositionsTotal()-1; i>=0; i--){
         ord.SelectByIndex(i);
         if(ord.OrderType()==ORDER_TYPE_BUY_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) BuyTotal++;
         if(ord.OrderType()==ORDER_TYPE_SELL_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) SellTotal++;
       }
       
       if(BuyTotal <=0){
          double high = findHigh();
          if(high > 0){
             SendBuyOrder(high);
          }
        }
        
        
        if(SellTotal <=0){
          double low = findLow();
          if(low > 0){
             SendSellOrder(low);
          }
        }
      
    

    } //+------------------------------------------------------------------+

    double findHigh(){ double highestHigh = 0; for(int i = 0; i < 200; i++){ double high = iHigh(_Symbol,Timeframe,i); if(i > BarsN && iHighest(_Symbol,Timeframe,MODE_HIGH,BarsN*2+1,i-BarsN) == i){ if(high > highestHigh){ return high; }

       }
       highestHigh = MathMax(high, highestHigh);
      }
      return -1;
    

    }

    double findLow(){ double LowestLow = DBL_MAX; for(int i = 0; i <200; i++){ double Low = iLow(_Symbol,Timeframe,i); if(i > BarsN && iLowest(_Symbol,Timeframe,MODE_LOW,BarsN*2+1,i-BarsN) == i){ if(Low > LowestLow){ return Low; }

       }
       LowestLow = MathMin(Low, LowestLow);
      }
      return -1;
    

    }

    bool IsNewBar(){ static datetime previousTime = 0; datetime currentTime = iTime(_Symbol,Timeframe,0); if(previousTime!=currentTime){ previousTime=currentTime; return true;
    } return false; }

    void SendBuyOrder(double entry){

    double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);

       if(ask > entry - OrderDistPoints * _Point) return;
       
       double tp = entry + Tppoints * _Point;
       double sl = entry - Slpoints * _Point;
       
    double lots = 0.01;
    if(RiskPercent > 0) lots = calcLots(entry-sl);
    
    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
      
       trade.BuyStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
    

    }

    void SendSellOrder(double entry){

    double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);

       if(bid < entry + OrderDistPoints *_Point) return;
       
       double tp = entry - Tppoints*_Point;
       double sl = entry + Slpoints*_Point;
       
    double lots = 0.01;
    if(RiskPercent > 0) lots = calcLots(sl-entry);
    
    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
      
       trade.SellStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
    

    }

    double calcLots(double slPoints){ double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;

    double ticksize =SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble( _Symbol,SYMBOL_VOLUME_STEP); double minvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN); double maxvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX); double volumelimit = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_LIMIT);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep; double lots = MathFloor(risk / moneyPerLotstep) * lotstep;

    if(volumelimit!=0) lots = MathMin(lots,volumelimit); if(maxvolume!=0) lots = MathMin(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX)); if(minvolume!=0) lots = MathMax(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)); lots = NormalizeDouble(lots,2);

    return lots; }

    void CloseAllOrders(){

    for(int i=OrdersTotal()-1;i>=0;i--){ ord.SelectByIndex(i); ulong ticket = ord.Ticket(); if(ord.Symbol()==_Symbol && ord.Magic()==InpMagic){ trade.OrderDelete(ticket); } } }

    void TrailStop() {

    double sl = 0; double tp = 0;

    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--) { if (pos.SelectByIndex(i)) { ulong ticket = pos.Ticket();

         if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol) {
         
            if (pos.PositionType() == POSITION_TYPE_BUY) {
               if (bid - pos.PriceOpen() > TslTriggerPoints * _Point) {
                  tp = pos.TakeProfit();
                  sl = bid - (TslPoints * _Point);
                  
                  if (sl > pos.StopLoss() && sl != 0) {
                     trade.PositionModify(ticket, sl, tp);
                  }
               }
            }
             else if (pos.PositionType() == POSITION_TYPE_SELL) {
               if (ask +(TslTriggerPoints* _Point)<pos.PriceOpen()){
                  tp = pos.TakeProfit();
                  sl = ask + (TslPoints * _Point);
                  
                  if (sl > pos.StopLoss() && sl != 0) {
                     trade.PositionModify(ticket, sl, tp);
                  }
               }
            }
         }   
      }
    

    } }

  2. Assistant

    Based on the provided code snippets, your impression that the first code is using a grid strategy similar to the second one is not entirely accurate. The two snippets have different trading strategies, although they may share some similar trading concepts such as trailing stops.

    First Code Snippet (Bollinger Bands Breakout Strategy)

    • Objective: This script aims to open buy and sell orders based on a breakout strategy using Bollinger Bands. The code tries to detect when the price breaks above the upper Bollinger Band for a potential long entry or below the lower band for a potential short entry.
    • Order Management: It closes positions if they are profitable and the price reaches the middle Bollinger band. It uses a simple confirmation check for breakouts and a trailing stop system to try and secure profits once a certain point threshold is exceeded.
    • Breakout Logic: It checks for breakouts by comparing the price close to Bollinger Bands and uses some range conditions to confirm the breakout.

    Second Code Snippet (Grid Strategy)

    • Objective: The second code appears to follow a more structured grid trading approach. It calculates potential buy and sell levels based on high and low prices over a number of bars and sets pending buy and sell stop orders at calculated levels.
    • Order Management: It manages multiple orders and employs another form of trailing stop, aiming to gradually adjust the stop loss based on market movement.
    • Grid Logic: This strategy involves placing several pending orders above and below the current price level, which is a characteristic of grid trading. It does not focus on indicators like Bollinger Bands but rather on fixed pip distances and historical highs and lows.

    Key Differences:

    1. Indicator Use: The first EA relies on Bollinger Bands for breakout opportunities, while the second EA does not use any dynamic indicator structures but calculates entry levels based on past highs and lows and fixed distances.
    2. Strategy Type: The first code is primarily a breakout strategy, while the second uses a more grid-like approach due to its structured and repetitive pending order placements.
    3. Order Placement: The grid strategy places multiple pending orders systematically at predefined levels, while the first code waits for specific conditions (like breakouts) to place active orders.
    4. Code Complexity and Features: The second EA has more elements of position and order tracking across various grid levels or timeframes and includes features like start and end trading hours.

    These are different approaches to trading, and while certain elements like trailing stops and risk management are common, the core strategy logic significantly differs.

  3. User

    me responda e portugues

  4. Assistant

    Claro! Vamos lá:

    Primeiro Código (Estratégia de Rompimento com Bandas de Bollinger)

    • Objetivo: Este script se destina a abrir ordens de compra e venda com base em uma estratégia de rompimento usando Bandas de Bollinger. O código tenta detectar quando o preço ultrapassa a banda superior para uma possível entrada de compra ou abaixo da banda inferior para uma possível entrada de venda.
    • Gerenciamento de Ordens: Ele fecha posições se elas estiverem lucrativas e o preço atingir a linha do meio das Bandas de Bollinger. Utiliza uma verificação simples de confirmação de rompimentos e um sistema de trailing stop para tentar assegurar lucros uma vez que um certo limiar de pontos seja ultrapassado.
    • Lógica de Rompimento: Verifica rompimentos ao comparar o fechamento do preço com as bandas de Bollinger e utiliza algumas condições de alcance para confirmar o rompimento.

    Segundo Código (Estratégia de Grid)

    • Objetivo: O segundo código parece seguir uma abordagem de grid trading mais estruturada. Ele calcula potenciais níveis de compra e venda com base em preços altos e baixos ao longo de um número de barras e define ordens pendentes de compra e venda nos níveis calculados.
    • Gerenciamento de Ordens: Gerencia várias ordens e emprega outra forma de trailing stop, visando ajustar gradualmente o stop loss com base no movimento do mercado.
    • Lógica de Grid: Esta estratégia envolve colocar várias ordens pendentes acima e abaixo do nível de preço atual, característica do grid trading. Não se concentra em indicadores como Bandas de Bollinger, mas sim em distâncias fixas de pips e máximas e mínimas históricas.

    Principais Diferenças:

    1. Uso de Indicadores: O primeiro EA se apoia em Bandas de Bollinger para oportunidades de rompimento, enquanto o segundo EA não utiliza estruturas de indicadores dinâmicos, mas calcula níveis de entrada com base em máximas e mínimas passadas e distâncias fixas.
    2. Tipo de Estratégia: O primeiro código é principalmente uma estratégia de rompimento, enquanto o segundo usa uma abordagem mais de grid devido à sua colocação estruturada e repetitiva de ordens pendentes.
    3. Colocação de Ordens: A estratégia de grid coloca múltiplas ordens pendentes sistematicamente em níveis predefinidos, enquanto o primeiro código aguarda por condições específicas (como rompimentos) para colocar ordens ativas.
    4. Complexidade do Código e Recursos: O segundo EA possui mais elementos de rastreamento de posições e ordens através de vários níveis de grid ou períodos e inclui funcionalidades como horas de início e fim de negociação.

    Esses são diferentes enfoques de negociação, e enquanto certos elementos como trailing stops e gerenciamento de risco são comuns, a lógica central das estratégias é significativamente diferente.

  5. User

    é possivel colocar esse sistema de ordens pendentes que tem no segundo codigo no meu codigo afim de evitar grandes percas e prejuizo com orden em aberto ?

  6. Assistant

    Sim, é possível integrar o sistema de ordens pendentes do segundo código no seu código atual para melhorar a gestão de riscos e tentar evitar grandes perdas com ordens abertas. Integrar essa funcionalidade envolve modificar seu código para incluir lógica de colocação de ordens pendentes em vez de apenas ordens de mercado diretas, como está no momento. Aqui estão alguns passos gerais para te ajudar a integrar esse sistema:

    Passos para Integrar Ordens Pendentes

    1. Adicionar Condições de Entrada: Em vez de apenas abrir ordens de mercado quando certas condições são atendidas (como rompimentos das Bandas de Bollinger), você pode configurar ordens pendentes (buy stop ou sell stop) em níveis predefinidos. Isso pode incluir rompimentos confirmados ou níveis retestados.

    2. Modificar Lógica de Breakout: Quando detectar um possível rompimento usando as Bandas de Bollinger, ao invés de executar uma ordem imediatamente, você pode definir uma ordem pendente um pouco além do nível de rompimento para captura do movimento de preço.

    3. Configuração de Ordens Pendentes: Utilize funções de ordens pendentes como trade.BuyStop() ou trade.SellStop() no lugar das funções de execução direta de mercado como trade.Buy() e trade.Sell(). Ajuste a lógica para determinar o price de entrada, stop loss (SL), e take profit (TP) de acordo com sua estratégia.

    4. Cancelamento de Ordens Pendentes: Adicione lógica para cancelar ordens pendentes que não sejam ativadas dentro de um intervalo de tempo específico. Isso ajuda a manter o sistema limpo e focado nas oportunidades mais atuais.

    Exemplo de Implementação:

    Aqui está um pseudo-exemplo de como você poderia modificar o trecho de lógica de um rompimento para usar ordens pendentes:

    // Verificar rompimento de alta e definir ordem pendente de buy stop
    if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
        
        double buyStopPrice = priceHigh + 5 * _Point; // Ajuste conforme necessário
        double slBuy = buyStopPrice - 20 * _Point;    // Ajuste conforme necessário
        double tpBuy = buyStopPrice + 40 * _Point;    // Ajuste conforme necessário
    
        if (trade.BuyStop(lotSize, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        }
        else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Fazer similar para rompimentos de baixa com ordens sell stop
    

    Considerações Importantes

    • Teste Extensivo: Sempre teste seu robô em contas demo ou em backtests antes de aplicá-lo em uma conta real para verificar se ele funciona conforme o esperado.

    • Gerenciamento de Risco: Certifique-se de que a lógica de gestão de risco esteja bem configurada para proteger seu capital. Ordens pendentes devem ter stops (SL) e alvos (TP) bem definidos.

    • Validade Temporal: Considere adicionar validade temporal para ordens pendentes, para que sejam canceladas se não forem ativadas dentro de um período específico.

    Integrar o sistema de ordens pendentes pode ajudar a melhorar sua estratégia garantindo que suas entradas sejam mais precisas e responsáveis em termos de risco.

  7. User

    me entregue o codigo completo com a alteração:

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

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

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

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

    //+------------------------------------------------------------------+ //| 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
    TrailStop();
    

    }

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

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

    }

  8. Assistant

    Claro, vou ajustar o seu código para incluir a lógica para ordens pendentes baseada em rompimentos com as Bandas de Bollinger. Vou adicionar a criação de ordens pendentes em vez de ordens de mercado diretas em rompimentos detectados.

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    
    // Variáveis globais para controle de ordens
    bool orderOpened = false;
    ulong orderTicket = 0;
    
    // Variáveis para armazenar rompimento anterior
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    // Configurações de trailing stop
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    
    //+------------------------------------------------------------------+
    //| 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());
                    }
                }
            }
        }
    
        // Verificar rompimento de alta e configurar ordem pendente de buy stop
        if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
            
            double buyStopPrice = priceHigh + 5 * _Point; // Ajuste conforme necessário
            double slBuy = buyStopPrice - 20 * _Point;    // Ajuste conforme necessário
            double tpBuy = buyStopPrice + 40 * _Point;    // Ajuste conforme necessário
    
            if (trade.BuyStop(lotSize, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            }
            else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Verificar rompimento de baixa e configurar ordem pendente de sell stop
        if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
            
            double sellStopPrice = priceLow - 5 * _Point; // Ajuste conforme necessário
            double slSell = sellStopPrice + 20 * _Point;  // Ajuste conforme necessário
            double tpSell = sellStopPrice - 40 * _Point;  // Ajuste conforme necessário
    
            if (trade.SellStop(lotSize, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            }
            else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Gerenciamento de trailing stop
        TrailStop();
    }
    
    //+------------------------------------------------------------------+
    //| Gerenciamento de trailing stop                                   |
    //+------------------------------------------------------------------+
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
            {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
                    {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                }
                else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
                    {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0)
                        {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Considerações

    • Riscos e Benefícios: Certifique-se de ajustar os valores de SL e TP para refletir seu risco e estratégia de ganho desejados.
    • Testes: Teste o código em uma conta demo para garantir que ele funciona conforme esperado e analise os resultados antes de rodar em uma conta real.
    • Configuração de Distâncias: Os pontos para definir ordens pendentes são ilustrativos, ajuste-os conforme necessário baseado na volatilidade do ativo negociado.

    Essa integração busca combinar o uso de ordens pendentes para capturar rompimentos, potencialmente oferecendo um controle de risco melhorado ao não entrar imediatamente no mercado.

  9. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

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

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

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

    //+------------------------------------------------------------------+ //| 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());
                }
            }
        }
    }
    
    // Verificar rompimento de alta e configurar ordem pendente de buy stop
    if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
        
        double buyStopPrice = priceHigh + 5 * _Point; // Ajuste conforme necessário
        double slBuy = buyStopPrice - 20 * _Point;    // Ajuste conforme necessário
        double tpBuy = buyStopPrice + 40 * _Point;    // Ajuste conforme necessário
    
        if (trade.BuyStop(lotSize, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        }
        else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Verificar rompimento de baixa e configurar ordem pendente de sell stop
    if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
        
        double sellStopPrice = priceLow - 5 * _Point; // Ajuste conforme necessário
        double slSell = sellStopPrice + 20 * _Point;  // Ajuste conforme necessário
        double tpSell = sellStopPrice - 40 * _Point;  // Ajuste conforme necessário
    
        if (trade.SellStop(lotSize, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        }
        else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Gerenciamento de trailing stop
    TrailStop();
    

    }

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

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

    }

    com as ordens pendentes esta tendo somente prejuizos oque pode ser feito para melhorar o codigo e ter lucros?

  10. Assistant

    Para melhorar o desempenho do seu robô de trading e aumentar as chances de obter lucros, é essencial revisar e ajustar algumas partes da estratégia e do código. O fato de estar tendo prejuízos pode ser devido a diversos fatores, como:

    1. Condições de Mercado Inadequadas: A estratégia pode não estar adequada para o tipo de mercado atual. Certifique-se de que está implementando o EA em condições de mercado para as quais foi projetado (por exemplo, tendência vs. lateralidade).

    2. Parâmetros de Entrada Ajustados: Verifique se os parâmetros como lotes, distâncias de stop loss/take profit, e número de pontos para ativar o trailing stop são apropriados para o ativo que está negociando. Parâmetros mal ajustados podem facilmente levar a perdas.

    3. Filtragem de Sinais: Adicione mais filtros ou condições que possam melhorar a qualidade dos sinais. Indicadores adicionais ou confirmações podem ajudar a evitar sinais falsos.

    4. Gestão de Risco: Revise a gestão de risco para garantir que não está arriscando mais do que o aceitável. Use lotes adequados e definam limites de perda diários.

    5. Backtesting e Ajustes: Realize extensivos backtests para entender como a estratégia teria se comportado no passado e faça ajustes baseados nos resultados.

    6. Verificar Execuções e Erros: Certifique-se de que não há erros relacionados à execução no módulo de ordens pendentes que possam estar impactando negativamente os resultados.

    Aqui estão algumas sugestões específicas no código:

    Sugestões de Melhorias

    1. Mais Critérios de Entrada e Saída:

      • Considere utilizar outros indicadores em conjunto (como RSI, MACD) para confirmar rompimentos.
      • Estabeleça condições adicionais para entrada em ordens, tais como verificação de tendência em períodos maiores.
    2. Ajuste de Níveis de Stop Loss e Take Profit:

      • Revise as distâncias de SL e TP para garantir que são adequadas à volatilidade do ativo negociado.
      • Considere a volatilidade diária e ajuste os níveis de SL e TP para garantir que não são atingidos muito frequentemente em mercados voláteis.
    3. Avaliar a Hora de Negociar:

      • Evite negociar em horários de baixa liquidez, como durante as transições de sessão (por exemplo, entre o mercado asiático e europeu).
    4. Integrar Sistema de Proteção de Capital:

      • Implementar um corte de perdas diário ou semanal para proteger a conta em caso de várias operações perdidas consecutivas.

    Exemplo de Adição de Critérios de Entrada

    Você pode adicionar um filtro adicional como o RSI para garantir que só está negociando em condições de mercado favoráveis:

    double rsiValue = iRSI(_Symbol, PERIOD_M2, 14, PRICE_CLOSE, 0);
    // Exemplo de critério: só comprar se não estiver sobrecomprado
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && rsiValue < 70) {
        // Ordem pendente de buy stop
    }
    

    Lembre-se que a negociação no mercado financeiro envolve riscos, e um EA que funciona bem em um cenário pode não funcionar em outro. Ajustes contínuos e testes são necessários para adaptar-se às mudanças no mercado.

  11. User

    nao seria algo haver com distancia de trailinstop ou takeprofit ou spread ou algo assim?

  12. Assistant

    Certamente, a configuração inadequada de parâmetros como trailing stop, take profit, e o spread pode influenciar significativamente o desempenho do seu robô de trading. Vamos abordar cada um desses aspectos:

    1. Trailing Stop:

      • Distância: Se a distância do trailing stop for muito curta, pode resultar no encerramento precoce de posições, especialmente em mercados voláteis, onde pequenas flutuações de preço podem ativar o trailing stop. Ajuste a distância de acordo com a volatilidade do ativo.
      • Ativação: Certifique-se de que o ponto de ativação do trailing stop (TslTriggerPoints) seja sensato. Se for ativado cedo demais, pode não aproveitar movimentos mais amplos.
    2. Take Profit:

      • Definição: Examine se o valor do take profit está otimizado com base no movimento esperado do mercado. Um TP muito curto pode limitar os ganhos, enquanto um TP muito longo pode reduzir a taxa de acertos.
      • Volatilidade: Ajuste o TP em relação à volatilidade do ativo. Em mercados mais voláteis, um TP maior pode ser mais apropriado.
    3. Spread:

      • Consideração no Preço de Entrada: Certifique-se de considerar o spread na definição de ordens pendentes. Ordens podem ser executadas antes do esperado se o spread não for corretamente compensado em relação ao preço de entrada.
      • Alta Volatilidade: Durante períodos de alta volatilidade ou com ativos de spread naturalmente alto, suas ordens podem ser ativadas ou fechadas de maneira inesperada.

    Ajustes Práticos:

    Para otimizar esses parâmetros, você pode seguir algumas práticas:

    • Backtesting e Otimização: Executar backtests abrangentes com diferentes combinações de trailing stops, take profit, e considera o impacto do spread. Algumas plataformas permitem otimização automática para encontrar os melhores parâmetros dentro de um conjunto pré-estabelecido.

    • Observação do Spread: Antes de abrir ou configurar ordens, monitore o spread atual e ajuste seus cálculos de take profit e stop loss para assegurar que as ordens são colocadas a distâncias apropriadas considerando o spread.

    • Adaptação Dinâmica: Em mercados onde a volatilidade varia significativamente ao longo do dia, considere implementar um sistema que ajusta dinamicamente as configurações de TP, SL e trailing stop com base na volatilidade média ou no ATR (Average True Range).

    Aqui está um exemplo de como considerar o spread em suas ordens pendentes:

    double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point;
    double buyStopPrice = priceHigh + 5 * _Point + spread; // Inclui spread
    double slBuy = buyStopPrice - 20 * _Point;
    double tpBuy = buyStopPrice + 40 * _Point;
    

    Lembre-se, ajustar esses parâmetros requer teste e revisão cuidadosa para se adequar ao comportamento específico do seu mercado alvo e ativos negociados.

  13. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1;

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

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

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

    //+------------------------------------------------------------------+ //| 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());
                }
            }
        }
    }
    
    // Verificar rompimento de alta e configurar ordem pendente de buy stop
    if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
        
        double buyStopPrice = priceHigh + 5 * _Point; // Ajuste conforme necessário
        double slBuy = buyStopPrice - 20 * _Point;    // Ajuste conforme necessário
        double tpBuy = buyStopPrice + 40 * _Point;    // Ajuste conforme necessário
    
        if (trade.BuyStop(lotSize, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        }
        else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Verificar rompimento de baixa e configurar ordem pendente de sell stop
    if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
        
        double sellStopPrice = priceLow - 5 * _Point; // Ajuste conforme necessário
        double slSell = sellStopPrice + 20 * _Point;  // Ajuste conforme necessário
        double tpSell = sellStopPrice - 40 * _Point;  // Ajuste conforme necessário
    
        if (trade.SellStop(lotSize, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        }
        else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Gerenciamento de trailing stop
    TrailStop();
    

    }

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

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

    }

    oque é feito no codigo abaixo para compensar essas questoes pois no codigo abaixo as ordens pendentes dao lucro nao tem tantos prejuizos como no meu acima:

    #property copyright "Copyright 2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.00"

    #include <Trade/Trade.mqh>

    CTrade trade; CPositionInfo pos; COrderInfo ord; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+

    input group "*** Trading Inputs ***"

         input double RiskPercent         = 3;   // Risk as % of Trading capital)
         input int    Tppoints            = 200; // Take Profit (10 points = 1 pip)
         input int    Slpoints            = 200; // Stoploss Points (10 points = 1 pip)
         input int    TslTriggerPoints    = 15;  // Points in profit before Trailing SL is activated (10 points = 1 pip)
         input int    TslPoints           = 10;  // Trailing Stoploss (10 points = 1 pip)
         input ENUM_TIMEFRAMES Timeframe  = PERIOD_CURRENT; //Time frame to run
         input int    InpMagic            = 298347; //EA indentification no
         input string TradeComment = "Scalpin Robot";
         
         
         enum StarHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
         input StarHour SHInput=0; // Star Hour
         
         enum EndHour { Inactive=0, _0100=1, _0200=2, _0300=3, _0400=4, _0500=5, _0600=6, _0700=7, _0800=8, _0900=9, _1000=10, _1100=11, _1200=12, _1300=13, _1400=14, _1500=15, _1600=16, _1700=17, _1800=18, _1900=19, _2000=20, _2100=21, _2200=22, _2300=23};
         input EndHour EHInput=0; // End Hour
         
         int SHChoice;
         int EHChoice;
         
         int BarsN            = 5;
         int ExpirationBars   = 100;
         int OrderDistPoints = 100;
         
         
    

    int OnInit() { //---

    //---

      trade.SetExpertMagicNumber(InpMagic);
      
         ChartSetInteger(0,CHART_SHOW_GRID,false);
    
      return(INIT_SUCCEEDED);
    

    } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { //---

    } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { //---

      TrailStop();
    
      if(!IsNewBar())return;
      
      MqlDateTime time;
      TimeToStruct(TimeCurrent(),time);
      
      int Hournow = time.hour;
      
      SHChoice = SHInput;
      EHChoice = EHInput;
      
      if(Hournow<SHChoice){CloseAllOrders(); return;}
      if(Hournow>=EHChoice && EHChoice!=0){CloseAllOrders(); return;}
      
      int BuyTotal=0;
      int SellTotal=0;
      
      
      for (int i=PositionsTotal()-1; i>=0; i--){
         pos.SelectByIndex(i);
         if(pos.PositionType()==POSITION_TYPE_BUY && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) BuyTotal++;
         if(pos.PositionType()==POSITION_TYPE_SELL && pos.Symbol()==_Symbol && pos.Magic()==InpMagic) SellTotal++;
       }
       
       for (int i=PositionsTotal()-1; i>=0; i--){
         ord.SelectByIndex(i);
         if(ord.OrderType()==ORDER_TYPE_BUY_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) BuyTotal++;
         if(ord.OrderType()==ORDER_TYPE_SELL_STOP && ord.Symbol()==_Symbol && ord.Magic()==InpMagic) SellTotal++;
       }
       
       if(BuyTotal <=0){
          double high = findHigh();
          if(high > 0){
             SendBuyOrder(high);
          }
        }
        
        
        if(SellTotal <=0){
          double low = findLow();
          if(low > 0){
             SendSellOrder(low);
          }
        }
      
    

    } //+------------------------------------------------------------------+

    double findHigh(){ double highestHigh = 0; for(int i = 0; i < 200; i++){ double high = iHigh(_Symbol,Timeframe,i); if(i > BarsN && iHighest(_Symbol,Timeframe,MODE_HIGH,BarsN*2+1,i-BarsN) == i){ if(high > highestHigh){ return high; }

       }
       highestHigh = MathMax(high, highestHigh);
      }
      return -1;
    

    }

    double findLow(){ double LowestLow = DBL_MAX; for(int i = 0; i <200; i++){ double Low = iLow(_Symbol,Timeframe,i); if(i > BarsN && iLowest(_Symbol,Timeframe,MODE_LOW,BarsN*2+1,i-BarsN) == i){ if(Low > LowestLow){ return Low; }

       }
       LowestLow = MathMin(Low, LowestLow);
      }
      return -1;
    

    }

    bool IsNewBar(){ static datetime previousTime = 0; datetime currentTime = iTime(_Symbol,Timeframe,0); if(previousTime!=currentTime){ previousTime=currentTime; return true;
    } return false; }

    void SendBuyOrder(double entry){

    double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);

       if(ask > entry - OrderDistPoints * _Point) return;
       
       double tp = entry + Tppoints * _Point;
       double sl = entry - Slpoints * _Point;
       
    double lots = 0.01;
    if(RiskPercent > 0) lots = calcLots(entry-sl);
    
    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
      
       trade.BuyStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
    

    }

    void SendSellOrder(double entry){

    double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);

       if(bid < entry + OrderDistPoints *_Point) return;
       
       double tp = entry - Tppoints*_Point;
       double sl = entry + Slpoints*_Point;
       
    double lots = 0.01;
    if(RiskPercent > 0) lots = calcLots(sl-entry);
    
    datetime expiration = iTime(_Symbol,Timeframe,0) + ExpirationBars * PeriodSeconds(Timeframe);
      
       trade.SellStop(lots,entry,_Symbol,sl,tp,ORDER_TIME_SPECIFIED,expiration);
    

    }

    double calcLots(double slPoints){ double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;

    double ticksize =SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble( _Symbol,SYMBOL_VOLUME_STEP); double minvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN); double maxvolume=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX); double volumelimit = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_LIMIT);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep; double lots = MathFloor(risk / moneyPerLotstep) * lotstep;

    if(volumelimit!=0) lots = MathMin(lots,volumelimit); if(maxvolume!=0) lots = MathMin(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX)); if(minvolume!=0) lots = MathMax(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)); lots = NormalizeDouble(lots,2);

    return lots; }

    void CloseAllOrders(){

    for(int i=OrdersTotal()-1;i>=0;i--){ ord.SelectByIndex(i); ulong ticket = ord.Ticket(); if(ord.Symbol()==_Symbol && ord.Magic()==InpMagic){ trade.OrderDelete(ticket); } } }

    void TrailStop() {

    double sl = 0; double tp = 0;

    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

    for (int i = PositionsTotal() - 1; i >= 0; i--) { if (pos.SelectByIndex(i)) { ulong ticket = pos.Ticket();

         if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol) {
         
            if (pos.PositionType() == POSITION_TYPE_BUY) {
               if (bid - pos.PriceOpen() > TslTriggerPoints * _Point) {
                  tp = pos.TakeProfit();
                  sl = bid - (TslPoints * _Point);
                  
                  if (sl > pos.StopLoss() && sl != 0) {
                     trade.PositionModify(ticket, sl, tp);
                  }
               }
            }
             else if (pos.PositionType() == POSITION_TYPE_SELL) {
               if (ask +(TslTriggerPoints* _Point)<pos.PriceOpen()){
                  tp = pos.TakeProfit();
                  sl = ask + (TslPoints * _Point);
                  
                  if (sl > pos.StopLoss() && sl != 0) {
                     trade.PositionModify(ticket, sl, tp);
                  }
               }
            }
         }   
      }
    

    } }

  14. Assistant

    Os dois códigos que você forneceu utilizam abordagens diferentes para a execução de estratégias de trading, particularmente no contexto de ordens pendentes, manejo de risco e otimização de entradas/saídas.

    Aqui estão algumas diferenças e características do segundo código que podem estar ajudando a melhorar o desempenho em comparação com o primeiro:

    1. Gestão de Risco com Base Percentual:

      • O segundo código utiliza um gerenciamento de risco baseado em porcentagem do capital (RiskPercent). Isso ajusta dinamicamente o tamanho do lote para refletir o risco tolerado, ajudando a proteger a conta de riscos excessivos.
    2. Sistema de Horário de Operação:

      • Estabelecer horas específicas para operação pode ajudar a reduzir a exposição a mercados voláteis ou com pouca liquidez. Isso proporciona mais controle sobre quando o sistema negocia, evitando horários menos previsíveis.
    3. Estratégia de Entrada Refinada:

      • O segundo código parece utilizar uma lógica mais sofisticada para determinar o momento certo de colocação de ordens, usando high/lows alcançados ao longo de um conjunto de barras ao invés de apenas rompimentos baseados em um indicador como as Bandas de Bollinger.
    4. Condições de Cancelamento de Ordens:

      • Ordens pendentes são eliminadas se condições internas específicas forem atendidas (CloseAllOrders). Isso limpa o mercado, possivelmente evitando executar ordens que poderiam levar a perdas devido a condições de mercado alteradas.
    5. Cálculo Automático de Lotes:

      • Utiliza um cálculo detalhado para determinar tamanhos de lote (calcLots) em relação ao stop loss e valores de tick, assegurando que as posições abertas estejam alinhadas com o perfil de risco desejado.
    6. Otimização de Distâncias de SL/TP:

      • As distâncias para stop loss e take profit são ajustadas dinamicamente e com mais precisão em relação ao ponto de entrada, oferecendo maior margem para flutuações de mercado antes que os stops sejam executados.

    Sugestões de Ajuste no Primeiro Código:

    Para aproximar o seu primeiro código ao nível de otimização do segundo, considere:

    • Adicionar um Sistema de Gestão de Risco Dinâmico: Similar ao RiskPercent, ajuste o tamanho do lote automaticamente com base no risco desejado.
    • Incluir Janelas de Tempo para Operação: Restringir operações para períodos com maior previsibilidade ou liquidez.
    • Melhoria no Cálculo de Ordens: Refinar a lógica de entrada para incorporar mais variáveis de confimação. Isso pode reduzir execuções em condições desfavoráveis.
    • Revisar Parâmetros de SL/TP: Ajustar com base na volatilidade e dentro do contexto de retorno/risco aceitáveis.

    Essas sugestões são direções gerais que podem ser testadas e ajustadas em backtests para identificar quais proporcionam melhoria no desempenho.

  15. User

    adicione esse conceito de orden pendentes para melhorar os ganhos no meu codigo

  16. Assistant

    Para integrar o conceito de ordens pendentes e melhorar a gestão de riscos e aumento de ganhos no seu código inicial, podemos implementar um sistema que ajuste dinamicamente o tamanho do lote, implemente ordens pendentes com base nos níveis de preço calculados (como máximas e mínimas recentes), e que use regras de gerenciamento de risco mais robustas. Abaixo está uma adaptação do seu código com essas ideias:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3; // Percentual de risco baseado no capital total
    input int TslTriggerPoints = 15;  // Pontos de lucro antes do trailing stop ser ativado
    input int TslPoints = 10;         // Trailing stop em pips
    input int OrderDistPoints = 30;   // Distância mínima para ordem pendente
    input int Tppoints = 200;         // Distância do Take Profit em pontos
    input int Slpoints = 200;         // Distância do Stop Loss em pontos
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        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);
    
                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());
                    }
                }
            }
        }
    
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + SymbolInfoDouble(_Symbol, SYMBOL_SPREAD);
            if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - SymbolInfoDouble(_Symbol, SYMBOL_SPREAD);
            if (SymbolInfoDouble(_Symbol, SYMBOL_BID) < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(sellStopPrice - slSell);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
        double volumelimit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        if (volumelimit != 0) lots = MathMin(lots, volumelimit);
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Alterações e Melhorias Inclusas:

    1. Gerenciamento de Risco Dinâmico: Adicionada uma função calcLots que calcula automaticamente o tamanho do lote com base no risco percentual (RiskPercent) desejado.
    2. Ordens Pendentes com Calculo de Spread: Considera o spread na definição dos preços de entrada das ordens pendentes para evitar execuções prematuras ou fora do planejado.
    3. Restrições de Distância de Ordens: Implementei verificações para garantir que as ordens pendentes sejam colocadas apenas quando a distância mínima desejada (em OrderDistPoints) for atingida.
    4. Configuração de SL e TP Dinâmicos: As configurações de SL e TP agora são ajustadas dinamicamente de acordo com parâmetros de entrada e volatilidade esperada.

    Isso proporciona um controle mais robusto e adaptativo sobre o posicionamento de ordens, ajudando a proteger contra condições de mercado desfavoráveis e maximizando oportunidades de lucro. Certifique-se de testar amplamente essa estratégia em um ambiente de demonstração antes de aplicar ao trading real.

  17. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; // Percentual de risco baseado no capital total input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado input int TslPoints = 10; // Trailing stop em pips input int OrderDistPoints = 30; // Distância mínima para ordem pendente input int Tppoints = 200; // Distância do Take Profit em pontos input int Slpoints = 200; // Distância do Stop Loss em pontos

    bool orderOpened = false; ulong orderTicket = 0;

    bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    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);
    
            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());
                }
            }
        }
    }
    
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + SymbolInfoDouble(_Symbol, SYMBOL_SPREAD);
        if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - SymbolInfoDouble(_Symbol, SYMBOL_SPREAD);
        if (SymbolInfoDouble(_Symbol, SYMBOL_BID) < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(sellStopPrice - slSell);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); double volumelimit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    if (volumelimit != 0) lots = MathMin(lots, volumelimit);
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

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

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 35 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 81 56 could be one of 2 function(s) NASDAQ V2_003_.mq5 81 56 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 81 56 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 81 56 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 101 56 could be one of 2 function(s) NASDAQ V2_003_.mq5 101 56 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 101 56 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 101 56 2 errors, 1 warnings 3 2

  18. Assistant

    Os erros que você encontrou são comuns ao trabalhar com o MetaQuotes Language 5 (MQL5). Vamos resolver os problemas que você mencionou.

    Solução para os Erros:

    1. Erro de Conversão de Tipo: possible loss of data due to type conversion

      • Esse aviso sugere que você está tentando converter um tipo maior para um menor, possivelmente perdendo precisão. Vale a pena revisar sua lógica, especialmente em cálculos que envolvam tamanhos de lotes e verifique se eles estão sendo tratados corretamente. Certifique-se de que os cálculos aritméticos e parâmetros estão usando os tipos apropriados.
    2. Erro de Uso da Função SymbolInfoDouble:

      • Esse erro ocorre porque SymbolInfoDouble pode retornar um valor booleano (quando usado com uma referência) ou um double diretamente. O problema que ocorre no seu caso é provavelmente devido a chamada incorreta.

      Corrija o uso da função para verificar os valores de retorno. Vamos corrigir isso no trecho abaixo:

    // Ajustando as chamadas para SymbolInfoDouble
    double spread;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread))
    {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    // Use a variável spread depois de verificar o sucesso da chamada
    double buyStopPrice = priceHigh + 5 * _Point + spread;
    
    // Faça o mesmo para outras chamadas de SymbolInfoDouble
    

    Código Ajustado

    Após corrigir a chamada errada para SymbolInfoDouble, aqui está uma implementação ajustada:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        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);
    
                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());
                    }
                }
            }
        }
    
        double spread;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread))
        {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point; // Ajuste considerando que o spread vem em pontos
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
            if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
            if (SymbolInfoDouble(_Symbol, SYMBOL_BID) < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(sellStopPrice - slSell);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Explicações:

    • Ajustes do Spread: Verifique se o spread é obtido corretamente com SymbolInfoDouble e convertido em pontos com _Point.
    • Verificação de Erros: Toda chamada que obteve informações através de SymbolInfoDouble agora verifica o resultado para garantir a validade.
    • Cálculo de Lotes: Assegura que o cálculo de lotes leva em consideração o valor de risco configurado.

    Certifique-se de testar o código em um ambiente de demonstração para garantir que tudo está funcionando corretamente de acordo com suas expectativas de trading.

  19. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    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);
    
            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());
                }
            }
        }
    }
    
    double spread;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread))
    {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point; // Ajuste considerando que o spread vem em pontos
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
        if (SymbolInfoDouble(_Symbol, SYMBOL_ASK) > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
        if (SymbolInfoDouble(_Symbol, SYMBOL_BID) < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(sellStopPrice - slSell);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

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

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 76 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 76 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 76 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 76 10 possible use of uninitialized variable 'spread' NASDAQ V2_003_.mq5 81 5 1 errors, 2 warnings 2 3

  20. Assistant

    Vamos resolver os erros e avisos que você encontrou no seu código.

    1. Erro no Uso de SymbolInfoDouble:

    O erro ocorre porque a chamada para SymbolInfoDouble deve ser feita com os argumentos corretos. Ela pode retornar diretamente um valor double ou retornar um valor através de um argumento de referência.

    2. Aviso de Possível Uso de Variável Não Inicializada:

    Esse aviso ocorre porque a variável spread pode não ser inicializada corretamente se SymbolInfoDouble retornar false.

    Ajustes no Código:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        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);
    
                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());
                    }
                }
            }
        }
    
        double spread = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point; // Ajuste considerando que o spread está em pontos
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
            double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
            double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(sellStopPrice - slSell);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Alterações feitas:

    • Inicializei a variável spread com 0.0 para evitar o uso de valores não inicializados.
    • Corrigi a obtenção do preço de compra (ask) e venda (bid) diretamente para assegurar o uso correto de SymbolInfoDouble sem causar conflitos na verificação boolean vs. valor direto.

    Essas correções devem ajudar a solucionar os erros de compilação. Certifique-se de testar o código no ambiente de negociação desejado.

  21. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    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);
    
            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());
                }
            }
        }
    }
    
    double spread = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point; // Ajuste considerando que o spread está em pontos
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(sellStopPrice - slSell);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

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

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 76 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 76 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 76 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 76 10 1 errors, 1 warnings 2 2

  22. Assistant

    Parece que você está enfrentando alguns problemas relacionados à função SymbolInfoDouble e possíveis conversões de tipo no seu código. Vamos abordar esses problemas e fornecer um código ajustado.

    Problemas e Soluções

    1. Possível Perda de Dados na Conversão de Tipo:

      • Esse aviso geralmente ocorre quando se converte um tipo maior para um menor, onde há a chance de perder dados. Geralmente, é um aviso e não um erro crítico. Você deve revisar o seu código nesse ponto específico para garantir que o tipo dos dados é o esperado.
    2. Uso Incorreto de SymbolInfoDouble:

      • O erro de SymbolInfoDouble indica que a função foi chamada de forma incorreta. Deve ser chamada de forma que pode retornar um bool quando você quer que o valor seja passado por referência.

    Solução Proposta:

    Vamos ajustar o uso da função SymbolInfoDouble e também adicionar verificações de erro. Além disso, vamos assegurar que o tipo de todas as variáveis usadas em cálculos seja apropriado.

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        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);
    
                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());
                    }
                }
            }
        }
    
        double spread = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point; // Ajuste considerando que o spread está em pontos
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
            double ask = 0.0;
            if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
                Print("Erro ao obter preço de oferta: ", GetLastError());
                return;
            }
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(buyStopPrice - slBuy);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
            double bid = 0.0;
            if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
                Print("Erro ao obter preço de demanda: ", GetLastError());
                return;
            }
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = 0.0;
        double bid = 0.0;
    
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter preços de mercado: ", GetLastError());
            return;
        }
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Alterações e Explicações:

    • Correções na SymbolInfoDouble: Usando a referência para passar a variável na qual será armazenado o valor de retorno e tratando a resposta booleana para verificar se a chamada foi bem-sucedida.
    • Variáveis Inicializadas: As variáveis ask e bid foram inicializadas antes de serem usadas para evitar possíveis erros de uso de variáveis não inicializadas.
    • Verificações de Erro: Adicionei mais verificações de erro após cada chamada importante para capturar falhas na obtenção de dados importantes.

    Faça testes exaustivos em um ambiente de demonstração para verificar a funcionalidade do EA antes de usá-lo em uma conta de trading real.

  23. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    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);
    
            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());
                }
            }
        }
    }
    
    double spread = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point; // Ajuste considerando que o spread está em pontos
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
        double ask = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
            Print("Erro ao obter preço de oferta: ", GetLastError());
            return;
        }
    
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(buyStopPrice - slBuy);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
        double bid = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter preço de demanda: ", GetLastError());
            return;
        }
    
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(slSell - sellStopPrice);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

    double ask = 0.0;
    double bid = 0.0;
    
    if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
        Print("Erro ao obter preços de mercado: ", GetLastError());
        return;
    }
    
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i))) {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 76 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 76 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 76 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 76 10 1 errors, 1 warnings 2 2

  24. Assistant

    Parece que você tem alguns erros no uso das funções SymbolInfoDouble e possivelmente alguns avisos de conversão de tipo. Vamos corrigir seu código, focando nos problemas que você mencionou.

    Problemas e Soluções

    1. Erro no Uso de SymbolInfoDouble:

      • Esse erro acontece porque você não usou a função corretamente. SymbolInfoDouble pode ser usado para retornar diretamente um valor double ou, se filho uma variável de referência, para transmitir o valor obtido.
    2. Aviso de Possível Perda de Dados na Conversão de Tipo:

      • Este aviso geralmente surge ao converter um tipo maior para um menor, onde há risco de perda de precisão. Se o código não estiver afetando seu resultado esperado, pode ser uma conversão intencional e não há problema. Senão, revise o que está em torno da linha mencionada como problemático.

    Código Corrigido:

    Aqui está o código ajustado com correções para os problemas mencionados:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                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());
                    }
                }
            }
        }
    
        double spread = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point; 
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
            double ask = 0.0;
            if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
                Print("Erro ao obter preço de oferta: ", GetLastError());
                return;
            }
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
            double bid = 0.0;
            if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
                Print("Erro ao obter preço de demanda: ", GetLastError());
                return;
            }
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = 0.0;
        double bid = 0.0;
    
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter preços de mercado: ", GetLastError());
            return;
        }
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Notas:

    • Verificações de Erros: Certifique-se de verificar se as funções SymbolInfoDouble retornam com sucesso, especialmente ao buscar valores críticos como SYMBOL_SPREAD, SYMBOL_ASK, e SYMBOL_BID.
    • Tratamento de Conversões de Tipo: Avalie se há alguma operação onde a precisão de dados pode ser crucial e ajuste se necessário.

    Essas correções devem ajudar a eliminar os erros e avisos atuais. Teste sempre seu EA em um ambiente de simulação antes de usá-lo em negociação real.

  25. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            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());
                }
            }
        }
    }
    
    double spread = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point; 
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
        double ask = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
            Print("Erro ao obter preço de oferta: ", GetLastError());
            return;
        }
    
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
        double bid = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter preço de demanda: ", GetLastError());
            return;
        }
    
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(slSell - sellStopPrice);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

    double ask = 0.0;
    double bid = 0.0;
    
    if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
        Print("Erro ao obter preços de mercado: ", GetLastError());
        return;
    }
    
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de compra.");
                    }
                }
            } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                    double newSL = ask + TslPoints * _Point;
                    
                    if (newSL < currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop atualizado para posição de venda.");
                    }
                }
            }
        }
    }
    

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 76 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 76 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 76 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 76 10 1 errors, 1 warnings 2 2

  26. Assistant

    Vamos corrigir os erros no seu código:

    Problemas Identificados:

    1. Uso Incorreto do SymbolInfoDouble:

      • O erro indica que a função SymbolInfoDouble está sendo chamada de forma incorreta. Quando você espera obter um valor direto como SYMBOL_SPREAD, é necessário usar a sobrecarga que retorna um valor double. Quando você espera obter o valor por referência, você deve usar o outro formato que retorna um valor bool.
    2. Aviso de Possível Perda de Dados na Conversão de Tipo:

      • Isso ocorre por conversões de tipos que podem resultar em perda de precisão. Examine onde seu código pode estar convertendo entre tipos (por exemplo, de double para tipos inteiros como int) e ajuste conforme necessário.

    Código Corrigido:

    Vou ajustar o uso da função SymbolInfoDouble e abordar a conversão de tipo:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                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());
                    }
                }
            }
        }
    
        double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point;
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
            double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
            double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Explicações:

    • Uso Correto de SymbolInfoDouble: Usei SymbolInfoDouble para retornar valores de spread, ask e bid diretamente, removendo os erros relacionados a chamadas incorretas.
    • Verificações de Inicialização de Variáveis: Certifique-se de que todas as conversões de tipo e inicializações estão sendo feitas de forma a não perdê-las de vista durante a compilação ou execução, minimizando os riscos de perdas de dados ou imprecisões.

    Esse código não deve apresentar os erros mencionados anteriormente. Teste no ambiente desejado e ajuste conforme necessário.

  27. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            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());
                }
            }
        }
    }
    
    double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point;
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(slSell - sellStopPrice);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

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

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 76 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 76 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 76 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 76 10 1 errors, 1 warnings 2 2

  28. Assistant

    Vamos resolver os problemas que você encontrou no seu código:

    Problemas Identificados:

    1. Erro em SymbolInfoDouble:

      • O erro indica que a chamada para SymbolInfoDouble não está sendo feita corretamente. Existem duas formas de usar esta função, e é importante garantir que estamos usando a sobrecarga correta para o valor retornado esperado.
    2. Aviso de Possível Perda de Dados na Conversão de Tipo:

      • Este aviso surge ao fazer conversões explícitas ou implícitas de tipos que podem envolver perda de precisão, por exemplo, um double para um int.

    Solução e Ajustes no Código:

    Vou corrigir o uso de SymbolInfoDouble no código e abordar o aviso de conversão de dados.

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        // Checando as posições existentes
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                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());
                    }
                }
            }
        }
    
        // Obtendo os valores de spread, ask e bid
        double spread = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point;
    
        double ask = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
            Print("Erro ao obter o preço de oferta: ", GetLastError());
            return;
        }
    
        double bid = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter o preço de demanda: ", GetLastError());
            return;
        }
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(lots, maxvolume);
        lots = MathMax(lots, minvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Explicações e Ajustes:

    • Corrigi o uso de SymbolInfoDouble: Agora estamos obtendo o preço de spread, ask e bid por referência e verificando se foi bem-sucedido, o que é importante para evitar erros de chamada.
    • Assumindo Controle de Conversões: Verifique onde as operações podem gerar perda de precisão e assegure-se que estão corretas, especialmente quando lidando com cálculos de tamanho de lotes.
    • Verificação de Condições: Certifique-se de que todos os cálculos e a lógica respeitem o tipo de mercado para o qual o EA é desenhado.

    Essas correções devem eliminar os erros e avisos que você estava enfrentando. Sempre faça testes em um ambiente de simulação antes de utilizar um EA em uma conta real.

  29. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    // Checando as posições existentes
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            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());
                }
            }
        }
    }
    
    // Obtendo os valores de spread, ask e bid
    double spread = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point;
    
    double ask = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
        Print("Erro ao obter o preço de oferta: ", GetLastError());
        return;
    }
    
    double bid = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
        Print("Erro ao obter o preço de demanda: ", GetLastError());
        return;
    }
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
    
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
    
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(slSell - sellStopPrice);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

    double moneyPerLotstep = slPoints / ticksize * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(lots, maxvolume);
    lots = MathMax(lots, minvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

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

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 78 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 78 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 78 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 78 10 1 errors, 1 warnings 2 2

  30. Assistant

    Para resolver os erros no seu código, vamos focar nas questões de chamadas incorretas de SymbolInfoDouble e na possível perda de dados devido a conversões de tipo.

    Soluções para os Problemas:

    1. Erro de SymbolInfoDouble:

      • A função SymbolInfoDouble pode ser usada de duas maneiras: retornando um double diretamente ou utilizando uma variável de referência para armazenar o resultado. Verifique se a sobrecarga apropriada está sendo utilizada de acordo com o que você quer obter.
    2. Aviso de Conversão de Tipo:

      • Possível perda de dados ao converter entre tipos. Você deve garantir que todas as conversões são intencionais e não resultam em perda de precisão de dados críticos.

    Código Ajustado:

    Vamos corrigir o uso de SymbolInfoDouble e verificar os pontos críticos onde a conversão de dados possa ocorrer.

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        // Checando as posições existentes
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                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());
                    }
                }
            }
        }
    
        // Obtendo os valores de spread, ask e bid
        double spread = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
            Print("Erro ao obter informações sobre o spread: ", GetLastError());
            return;
        }
        spread *= _Point;
    
        double ask = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
            Print("Erro ao obter o preço de oferta: ", GetLastError());
            return;
        }
    
        double bid = 0.0;
        if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
            Print("Erro ao obter o preço de demanda: ", GetLastError());
            return;
        }
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = 0.0, tickvalue = 0.0, lotstep = 0.0, minvolume = 0.0, maxvolume = 0.0;
    
        // Asegure-se de obter todos os valores necessários para o cálculo de lotes
        if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, ticksize) ||
            !SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickvalue) ||
            !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotstep) ||
            !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minvolume) ||
            !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxvolume)) 
        {
            Print("Erro ao obter informações de símbolo para cálculo de lotes: ", GetLastError());
            return 0.0;  // Retorna zero se falhar no cálculo das informações
        }
    
        double moneyPerLotstep = (slPoints / ticksize) * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(MathMax(lots, minvolume), maxvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = 0.0;
        double bid = 0.0;
    
        if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || 
            !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) 
        {
            Print("Erro ao obter preços de mercado: ", GetLastError());
            return;
        }
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de compra.");
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
                        
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop atualizado para posição de venda.");
                        }
                    }
                }
            }
        }
    }
    

    Explicações e Ajustes:

    • Uso Correto de SymbolInfoDouble: Agora os valores são recuperados por referência corretamente, o que elimina os erros de aplicação anterior.
    • Validação de Acesso de Dados: Implementamos verificações para garantir que os dados cruciais são corretamente obtidos antes de prosseguir, protegendo contra possíveis falhas.
    • Tratamento de Conversões de Tipo: Assegure-se que todas as conversões sejam intencionais e mantenham a precisão necessária para seus cálculos.

    Essas mudanças devem resolver os erros que você estava enfrentando no código. Teste seu EA em um ambiente de simulação para verificar se está funcionando como esperado.

  31. User

    #include <Trade\Trade.mqh>

    input double lotSize = 0.1; input double RiskPercent = 3; input int TslTriggerPoints = 15; input int TslPoints = 10; input int OrderDistPoints = 30; input int Tppoints = 200; input int Slpoints = 200;

    bool orderOpened = false; ulong orderTicket = 0; bool lastBreakoutAlta = false; bool lastBreakoutBaixa = false; double breakoutHigh = 0.0; double breakoutLow = 0.0;

    int OnInit() { return(INIT_SUCCEEDED); }

    void OnDeinit(const int reason) { }

    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
    double priceLow = iLow(_Symbol, PERIOD_M2, 0);
    double priceClose = iClose(_Symbol, PERIOD_M2, 0);
    double range = priceHigh - priceLow;
    
    CTrade trade;
    
    // Checando as posições existentes
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong positionTicket = PositionGetTicket(i);
            double positionProfit = PositionGetDouble(POSITION_PROFIT);
            double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
            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());
                }
            }
        }
    }
    
    // Obtendo os valores de spread, ask e bid
    double spread = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
        Print("Erro ao obter informações sobre o spread: ", GetLastError());
        return;
    }
    spread *= _Point;
    
    double ask = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
        Print("Erro ao obter o preço de oferta: ", GetLastError());
        return;
    }
    
    double bid = 0.0;
    if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
        Print("Erro ao obter o preço de demanda: ", GetLastError());
        return;
    }
    
    // Rompimento de alta
    if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
        lastBreakoutAlta = true;
        breakoutHigh = priceHigh;
        Print("Possível rompimento de alta detectado.");
    
        double buyStopPrice = priceHigh + 5 * _Point + spread;
    
        if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
        double slBuy = buyStopPrice - Slpoints * _Point;
        double tpBuy = buyStopPrice + Tppoints * _Point;
    
        double lots = calcLots(slBuy - buyStopPrice);
    
        if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
            Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    // Rompimento de baixa
    if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
        lastBreakoutBaixa = true;
        breakoutLow = priceLow;
        Print("Possível rompimento de baixa detectado.");
    
        double sellStopPrice = priceLow - 5 * _Point - spread;
    
        if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
        double slSell = sellStopPrice + Slpoints * _Point;
        double tpSell = sellStopPrice - Tppoints * _Point;
    
        double lots = calcLots(slSell - sellStopPrice);
    
        if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
            Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
        } else {
            Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
        }
    }
    
    TrailStop();
    

    }

    double calcLots(double slPoints) { double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100; double ticksize = 0.0, tickvalue = 0.0, lotstep = 0.0, minvolume = 0.0, maxvolume = 0.0;

    // Corrigindo o uso de SymbolInfoDouble para armazenar o valor corretamente
    if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, ticksize) ||
        !SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickvalue) ||
        !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotstep) ||
        !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minvolume) ||
        !SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxvolume)) 
    {
        Print("Erro ao obter informações de símbolo para cálculo de lotes: ", GetLastError());
        return 0.0;  // Retorna zero se falhar no cálculo das informações
    }
    
    double moneyPerLotstep = (slPoints / ticksize) * tickvalue * lotstep;
    double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
    lots = MathMin(MathMax(lots, minvolume), maxvolume);
    return NormalizeDouble(lots, 2);
    

    }

    void TrailStop() { CTrade trade;

    double ask = 0.0;
    double bid = 0.0;
    
    if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) || 
        !SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) 
    {
        Print("Erro ao obter preços de mercado: ", GetLastError());
        return;
    }
    
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (PositionSelectByTicket(PositionGetTicket(i))) {
            ulong ticket = PositionGetTicket(i);
            double currentSL = PositionGetDouble(POSITION_SL);
            double tp = PositionGetDouble(POSITION_TP);
            
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                    double newSL = bid - TslPoints * _Point;
                    
                    if (newSL > currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop modificado para compra. Novo SL: ", newSL);
                    }
                }
            } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                    double newSL = ask + TslPoints * _Point;
    
                    if (newSL < currentSL || currentSL == 0) {
                        trade.PositionModify(ticket, newSL, tp);
                        Print("Trailing Stop modificado para venda. Novo SL: ", newSL);
                    }
                }
            }
        }
    }
    

    }

    erro:

    'NASDAQ V2_003_.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 V2_003_.mq5 34 57 'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 78 10 could be one of 2 function(s) NASDAQ V2_003_.mq5 78 10 built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 78 10 built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 78 10 1 errors, 1 warnings 2 2

  32. Assistant

    Vamos resolver os problemas de compilação que você está enfrentando, em particular o uso incorreto de SymbolInfoDouble e qualquer aviso de perda de dados devido a conversões de tipo.

    Problemas e Soluções:

    1. Erro de Uso de SymbolInfoDouble:

      • Quando você usa SymbolInfoDouble, certifique-se de que está usando a função corretamente. Utilize a versão que retorna um double quando não precisar verificar a validade e a versão que utiliza referência para verificar com bool se precisar garantir que a informação foi obtida corretamente.
    2. Aviso de Possível Perda de Dados:

      • Este aviso está geralmente relacionado a conversões implícitas, como de double para int, que podem causar perda de precisão. Aqui não parece crítico, mas é sempre bom revisar.

    Código Ajustado:

    Vamos aplicar correções ao método SymbolInfoDouble no código:

    #include <Trade\Trade.mqh>
    
    input double lotSize = 0.1;
    input double RiskPercent = 3;
    input int TslTriggerPoints = 15;
    input int TslPoints = 10;
    input int OrderDistPoints = 30;
    input int Tppoints = 200;
    input int Slpoints = 200;
    
    bool orderOpened = false;
    ulong orderTicket = 0;
    bool lastBreakoutAlta = false;
    bool lastBreakoutBaixa = false;
    double breakoutHigh = 0.0;
    double breakoutLow = 0.0;
    
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    void OnDeinit(const int reason)
    {
    }
    
    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 priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
        double priceLow = iLow(_Symbol, PERIOD_M2, 0);
        double priceClose = iClose(_Symbol, PERIOD_M2, 0);
        double range = priceHigh - priceLow;
    
        CTrade trade;
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong positionTicket = PositionGetTicket(i);
                double positionProfit = PositionGetDouble(POSITION_PROFIT);
                double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
    
                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());
                    }
                }
            }
        }
    
        double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point;
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        // Rompimento de alta
        if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
            lastBreakoutAlta = true;
            breakoutHigh = priceHigh;
            Print("Possível rompimento de alta detectado.");
    
            double buyStopPrice = priceHigh + 5 * _Point + spread;
    
            if (ask > buyStopPrice - OrderDistPoints * _Point) return;
    
            double slBuy = buyStopPrice - Slpoints * _Point;
            double tpBuy = buyStopPrice + Tppoints * _Point;
    
            double lots = calcLots(slBuy - buyStopPrice);
    
            if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
                Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        // Rompimento de baixa
        if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
            lastBreakoutBaixa = true;
            breakoutLow = priceLow;
            Print("Possível rompimento de baixa detectado.");
    
            double sellStopPrice = priceLow - 5 * _Point - spread;
    
            if (bid < sellStopPrice + OrderDistPoints * _Point) return;
    
            double slSell = sellStopPrice + Slpoints * _Point;
            double tpSell = sellStopPrice - Tppoints * _Point;
    
            double lots = calcLots(slSell - sellStopPrice);
    
            if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
                Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
            } else {
                Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
            }
        }
    
        TrailStop();
    }
    
    double calcLots(double slPoints)
    {
        double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
        double ticksize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
        double tickvalue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
        double lotstep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
        double minvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        double maxvolume = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
        double moneyPerLotstep = (slPoints / ticksize) * tickvalue * lotstep;
        double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
    
        lots = MathMin(MathMax(lots, minvolume), maxvolume);
        return NormalizeDouble(lots, 2);
    }
    
    void TrailStop()
    {
        CTrade trade;
    
        double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            if (PositionSelectByTicket(PositionGetTicket(i))) {
                ulong ticket = PositionGetTicket(i);
                double currentSL = PositionGetDouble(POSITION_SL);
                double tp = PositionGetDouble(POSITION_TP);
                
                if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point) {
                        double newSL = bid - TslPoints * _Point;
                        
                        if (newSL > currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop modificado para compra. Novo SL: ", newSL);
                        }
                    }
                } else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point) {
                        double newSL = ask + TslPoints * _Point;
    
                        if (newSL < currentSL || currentSL == 0) {
                            trade.PositionModify(ticket, newSL, tp);
                            Print("Trailing Stop modificado para venda. Novo SL: ", newSL);
                        }
                    }
                }
            }
        }
    }
    

    Explicações:

    • Uso Correto de SymbolInfoDouble: Agora utiliza-se a forma direta para spread, ask e bid sem a verificação booleana, uma vez que estamos assumindo um ambiente onde estas funções não falharão e fornecem um valor válido.
    • Limpeza de Avisos: Não houve conversões suspeitas identificáveis diretamente no código que forneceu. Certifique-se de que todas as variáveis envolvidas em cálculos críticos são do tipo correto.

    Por favor, teste estas mudanças e verifique se os erros e avisos foram resolvidos.