Problema com a quantidade total de pedidos em aberto

 

Olá a todos. Tentei todos os conselhos que posso encontrar neste fórum, mas nenhum parece funcionar. Alguém pode ajudar. Acredito que a questão está na minha função OrderTotal. Estou negociando 10 pares de moedas, ou seja, tenho a EA aberta em 10 gráficos. Esta é uma estratégia simples de hedging. Quero que a EA abra uma negociação (longa ou curta) dependendo dos sinais. Se a negociação seguir meu caminho, Trailingstop ou Take profit. Se, no entanto, a negociação for contra mim, quero que ela abra uma negociação na direção oposta. O código que estou usando parece funcionar, mas às vezes fica preso, ou seja, não abre mais nenhuma negociação. Além disso, quando há uma ou duas negociações abertas em um par, não parece querer abrir nenhuma negociação em nenhum outro par.

Aqui está meu código

int start()
{
     {
     if (OrdersTotal() == 0)
     if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*0.0001, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
         }

  for(int i=OrdersTotal()-1; i>=0; i--) 
  {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      if (OrderSymbol()==Symbol())
      //Calculate the point value in case there are extra digits in the quotes
      if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
      else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
      else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);

//calculate new lotsize of hedge based on lotsize of current open trade*Multiplier
      double lots = NormalizeDouble(OrderLots() * Multiplier, 2); 
      
     if (OrderType() == OP_BUY) 
      {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *PointValue,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *PointValue,Digits))
            {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *PointValue,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
              }
            }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*PointValue,Digits))
            if(OrdersTotal() == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*PointValue, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
          }
 
  1. Você precisa filtrar os ofícios.
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
          if (OrderSymbol()==Symbol())
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;  // These
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;// four
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01; // lines
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);                    // Execute only on Symbol orders.
    
          double lots = NormalizeDouble(OrderLots() * Multiplier, 2);  // This and below are always executed
          if (OrderType() == OP_BUY)                                   // Symbol is irrelevant.             
    
    Com aparelho.
          if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
          if (OrderSymbol()==Symbol())
    {                                                                   // Rest of code executes only on Symbol orders.
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    
          double lots = NormalizeDouble(OrderLots() * Multiplier, 2); 
          
          if (OrderType() == OP_BUY) 
             :
    }

  2. Em um corretor de 4 dígitos, ponto = 0,0001
          if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.00001) PointValue = 0.0001;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.0001) PointValue = 0.01;
          else if (MarketInfo(OrderSymbol(), MODE_POINT) == 0.001) PointValue = 0.01;
          else PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    
    Fixo e simplificado.
    PointValue = MarketInfo(OrderSymbol(), MODE_POINT);
    if(MarketInfo(OrderSymbol(), MODE_DIGITS) % 2 = 1) PointValue *= 10;

  3. Como tudo dentro do aparelho é Símbolo(), cada MarketInfo pode ser substituído por variáveis pré-definidas
  4. Não digite números de código rígido.
    Verifique seus códigos de retornoQuaissão os valores de retorno das funções ? Como posso utilizá-los ? -Fórum MQL4 e Erros Comuns nos Programas MQL4 e Como Evitá-los - Artigos MQL4
    result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*0.0001, 0, "Original", magicNumber, 0, Blue);
 

Muito obrigado por sua ajuda. Eu acrescentei um brace como sugerido, mas o EA ainda só abre uma negociação em um par de moedas. Ele não abrirá uma negociação em nenhum dos outros gráficos, mesmo que a condição de compra tenha sido cumprida. Eu estou preso a isto há semanas, por favor, dê outra olhada.

2. EDITAR: Não é mais necessário

3. meu código agora se parece com este

int start()
{
  {
    if (OrdersTotal() == 0)
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
  }       

  for(int i=OrdersTotal()-1; i>=0; i--) 
    {
      //calculate new lotsize of hedge based on lotsize of current open trade*Multiplier
      double lots = NormalizeDouble(OrderLots() * Multiplier, 2);
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true)
      if (OrderSymbol()==Symbol())
    { 
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(OrdersTotal() == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }
 
    if (OrdersTotal() == 0)
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*PointValue, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());
Se uma ordem estiver aberta em qualquer par, não abrirá outra ordem até que OrderTotal()==0 novamente
 
GumRai:
Se uma ordem estiver aberta em qualquer par, não abrirá outra ordem até que OrderTotal()==0 novamente

Obrigado por sua ajuda. Preciso limitar a primeira ordem original a apenas uma negociação. Não quero que a EA continue abrindo ordens quando a condição de compra for atendida. Por isso, acrescentei o Ordertotal para limitar isto. Este código, entretanto, parece interferir com o código aqui

else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(OrdersTotal() == 1) //<----------
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", 0, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());

Aqui eu só quero que a EA abra uma cobertura por comércio aberto, daí OrderTotal ==1

Então, qual é a melhor maneira de limitar o número de negócios, ou seja, um negócio original e um negócio de hedge? Obrigado.

 
Trader3000: Então, qual é a melhor maneira de limitar o número de operações, ou seja, uma operação original e uma operação de hedge?
  1. Portanto, conte o número de pedidos que estão abertos no gráfico atual. OrdensTotal retorna o número de ordens que estão abertas em todos os gráficos.
  2. A não filtragem por número mágico torna a EA incompatível com todas as outras (inclusive com outras TFs) e a negociação manual Símbolo Não é igual a Símbolo de Ordem quando outra moeda é adicionada a outro gráfico separado . - Fórum MQL4
 

Muito obrigado pela ajuda de todos. Resolvi o problema e agora a EA abrirá uma negociação em todos os gráficos quando a condição de compra for atendida, entretanto, nada abaixo disso está funcionando. A EA não está chamando as funções Trailingstop ou Hedge. Alguém pode, por favor, dar uma olhada e me dizer o que eu fiz de errado porque não consigo entender.

int start()
{ 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   double lots = NormalizeDouble(OrderLots() * Multiplier, 2);
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
    {
         result=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
    
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
 else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(total == 1)
            result=OrderSend(Symbol(), OP_SELL, lots, Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }
 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   double lots = NormalizeDouble(OrderLots() * Multiplier, 2);

Não sei exatamente o que você está fazendo, mas sugiro que você evite nomear 2 variáveis com a única diferença sendo uma letra maiúscula. É fácil confundir as 2, especialmente quando outros que estão lendo seu código podem muito bem ter adotado a convenção de que as variáveis que começam com uma letra maiúscula são Globalscope.

Nenhuma ordem foi selecionada, portanto, OrderLots() poderia ser qualquer coisa


    
     if (OrderType() == OP_BUY) 

Isto utilizaria os valores da última ordem selecionada no laço anterior, pode não ser o número mágico ou símbolo correto.

 

Obrigado por sua resposta. O que estou tentando fazer é que a EA abra o primeiro negócio original onde o lote é uma porcentagem do meu patrimônio. Se o negócio for contra

eu, a EA deve abrir uma sebe na direção oposta, mas aqui o tamanho do lote deve ser 3 vezes o tamanho do lote original (OrderLots).

A ordem foi selecionada, não pareceu afetar a operação. Agora coloquei os lotes diretamente na função OrderSend, mas nem o trailingstop nem

a sebe é acionada quando deveriam. Ambos funcionaram perfeitamente antes de eu acrescentar isto

total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }

int start()
{ 
   double Lots = NormalizeDouble(AccountEquity()*Percentage*Lotsize/100, 2);
   
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
         result=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
    {
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits))
            if(total == 1)
            result=OrderSend(Symbol(), OP_SELL, NormalizeDouble(OrderLots() * Multiplier, 2), Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
       }

Acredito que meus aparelhos {} não estão nos lugares certos

 
Já lhe disse na segunda parte do meu posto anterior
 

Muito obrigado por toda a ajuda até agora. Estou fazendo progressos. Agora tenho-a para que tudo pareça funcionar como deveria, exceto que a EA ignora a condição para abrir um comércio de sebes. Às vezes (mas nem sempre) abre um comércio de sebes mesmo quando as condições não foram cumpridas. Também o TrailingStop nem sempre entra em ação. Acho que ainda me faltam aparelhos {} em algum lugar. Meu código agora está assim. Alguém pode me dar uma olhada, por favor. Obrigado.

int start()
{ 
   total=0;
   for(i = OrdersTotal()-1; i >= 0 ; i--)
   if ( OrderSelect(i, SELECT_BY_POS)                
    &&  OrderMagicNumber()  == magicNumber            
    &&  OrderSymbol()       == Symbol())
    {             
      total++;
    }
    {
    if(total==0 )
    if(Close[1]>Close[2])
    {
         result=OrderSend(Symbol(), OP_BUY, 0.01, Ask, 3, Ask - StopLoss*Point*10, 0, "Original", magicNumber, 0, Blue);
         Print("Error setting Original order: ",GetLastError());     
    }
     if (OrderType() == OP_BUY) 
       {
        if (Bid - OrderOpenPrice() > NormalizeDouble(TrailingStart *Point*10,Digits))
         {
           if (OrderStopLoss() < Bid - NormalizeDouble(TrailingStop *Point*10,Digits))
           {
              if (OrderModify(OrderTicket(), OrderOpenPrice(), Bid - NormalizeDouble(TrailingStop *Point*10,Digits),
              OrderTakeProfit(), Blue)) 
              Print("Error setting Buy trailing stop: ",GetLastError()); 
           }
         }
            else if (OrderOpenPrice() > Bid + NormalizeDouble(Hedge*Point*10,Digits)) //<------- THIS IS BEING IGNORED SOMETIMES (I THINK)
            if(total == 1)
            {
            result=OrderSend(Symbol(), OP_SELL, NormalizeDouble(OrderLots() * Multiplier, 2), Bid, 3,  Bid + Stoploss*Point*10, 0, "Hedge", magicNumber, 0, Blue);
            Print("Error setting Sell Hedge: ", GetLastError());
            }
       }
      // else if (OrderType() == OP_SELL)
      // ... 

GumRai:

This would use the values from the last order selected in the previous loop, it may not be the correct magic number or symbol.


Eu tentei consertar isto trocando os aparelhos. É a melhor maneira, ou eu preciso duplicar e adicionar a função OrderSelect todas as vezes antes de OrderSend? Obrigado.
Razão: