Trailling Problem

 

I have a problem with my trailing stop.

Didn´t work!

I need to set it only with profit positions and for example I like to set it at 15 point and set Steps with 10 Points.

Anyone help Me?


I think this problem is :

  int digits_adjust=1;
            if(digits==3 || digits==5)
               digits_adjust=10;
            double m_adjusted_point=NormalizeDouble(point*digits_adjust,_Digits);


  //|TRAILING 2                                       |
//+------------------------------------------------------------------+
void Trailingg(double preco)
  {
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==Symbol())
           {
            if(m_position.Profit()>0.0)
               break;
            //---
            long digits=SymbolInfoInteger(m_position.Symbol(),SYMBOL_DIGITS);
            double point=SymbolInfoDouble(m_position.Symbol(),SYMBOL_POINT);
            //--- tuning for 3 or 5 digits
            int digits_adjust=1;
            if(digits==3 || digits==5)
               digits_adjust=10;
            double m_adjusted_point=NormalizeDouble(point*digits_adjust,_Digits);
            //---
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(m_position.PriceCurrent()+(TrailingStop-TrailingStep)*m_adjusted_point>m_position.StopLoss())
                 {
                  //--- save Magic Number for the position
                  m_trade.SetExpertMagicNumber(m_position.Magic());
                  m_trade.PositionModify(m_position.Ticket(),
                                         m_position.PriceCurrent()+TrailingStop*m_adjusted_point,
                                         m_position.TakeProfit());
                      Print("Trailing de posicao comprada: ");                   
                 }
              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)
              {
               double sl=0.0;
               if(m_position.StopLoss()>0)
                 {
                  if(m_position.PriceCurrent()-(TrailingStop+TrailingStep)*m_adjusted_point<m_position.StopLoss())
                    {
                     sl=m_position.PriceCurrent()-TrailingStop*m_adjusted_point;
                     //--- save Magic Number for the position
                     m_trade.SetExpertMagicNumber(m_position.Magic());
                     m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());
                     Print("Trailing de posicao vendida: ");  
                    }
                 }
               else
                 {
                  sl=m_position.PriceCurrent()+TrailingStop*m_adjusted_point;
                  //--- save Magic Number for the position
                  m_trade.SetExpertMagicNumber(m_position.Magic());
                  m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());
                 }
              }
           }
  }
 
jpg
 
Silverveins :
jpg

You messed something up with the pictures: in the code you are looking for POSITIONS, and in the picture there is an error for a POSTPONED ORDER.

It is not yet clear what exactly you need.

 

jpg


 
Silverveins:

I have a problem with my trailing stop.

Didn´t work!

I need to set it only with profit positions and for example I like to set it at 15 point and set Steps with 10 Points.

Anyone help Me?


I think this problem is :


Check STOP_LEVEL

 
Marco Montemari:

Check STOP_LEVEL

I changed the code, but I recived this error:

S 0 16:11:15.426 CUXeyFLY (WINV20,M1) 2020.09.01 09:13:03   CTrade::OrderSend: modify WINV20 (sl: 100785, tp: 0) [done]

KQ 0 16:11:15.426 CUXeyFLY (WINV20,M1) 2020.09.01 09:13:03   CTrade::OrderTypeCheck: Invalid order type

HD 0 16:11:15.426 CUXeyFLY (WINV20,M1) 2020.09.01 09:13:03   100735.0Ordem de TRAILING Venda - com falha. ResultRetcode: 10035, RetcodeDescription: invalid order


 need to set it only with profit positions and for example I like to set it at 15 point and set Steps with 10 Points, In this case Entry sell 100735 and I like the trailing stop below this value 100720


void OnTick()
  {           
   CopyRates(Symbol(),Period(),0,3,rates); 
    ulong PositionTicket = OrderGetTicket ( ORDER_MAGIC );
 //END POSITION --------------
   MqlDateTime dt;
TimeCurrent(dt);
if(dt.sec == 59){
endpos();
}  
//-----------------
      if(!SymbolInfoTick(Symbol(),ultimoTick))
         {
            Alert("Erro ao obter informações de Preços: ", GetLastError());
            return;
         }
         
      if(CopyRates(_Symbol, _Period, 0, 3, rates)<0)
         {
            Alert("Erro ao obter as informações de MqlRates: ", GetLastError());
            return;
         }
      
     /* if(CopyBuffer(smaHandle, 0, 0, 3, smaArray)<0)
         {
            Alert("Erro ao copiar dados da média móvel: ", GetLastError());
            return;
         }*/
         
      posAberta = false;
      for(int i = PositionsTotal()-1; i>=0; i--)
         {
            string symbol = PositionGetSymbol(i);
            ulong magic = PositionGetInteger(POSITION_MAGIC);
            if(symbol == _Symbol && magic == magicNum)
               {  
                  posAberta = true;
                  break;
               }
         }
         
      ordPendente = false;
      for(int i = OrdersTotal()-1; i>=0; i--)
         {
            ulong ticket = OrderGetTicket(i);
            string symbol = OrderGetString(ORDER_SYMBOL);
            ulong magic = OrderGetInteger(ORDER_MAGIC);
            if(symbol == _Symbol && magic == magicNum)
               {
                  ordPendente = true;
                  break;
               }
         }
      
      if(!posAberta)
         {
            beAtivo = false;
         }
         
     /* if(posAberta && !beAtivo)
         {
            BreakEven(ultimoTick.last);
         }*/
         
      if(posAberta) /*&& beAtivo)*/
         {
            Trailingg(ultimoTick.last);
         }
      
      //--- Getting data for calculations

   if(!GetIndValue())
      return;
   
 //COMPRA ----------------------------------------------------       
      if(corr[0]<-Inp_KeyLevel && !posAberta && !ordPendente)
         {
         PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.ask, _Digits);
            STL = NormalizeDouble(rates[1].low-5 /*PRC - stopLoss*/, _Digits);
            TKP = NormalizeDouble(PRC + takeProfit, _Digits);
            if(trade.BuyStop(lote, rates[1].high+5,_Symbol, /*PRC,*/ 0, 0/* ""*/))
               {
                  Print(PRC,"Ordem de Compra - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de Compra - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }
          // MODIFICANDO COMPRA   ---------------------------------------     
     else if(corr[0]<-Inp_KeyLevel && !posAberta && ordPendente)
         {
            PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.ask, _Digits);
            STL = NormalizeDouble(rates[1].high+5 /*PRC - stopLoss*/, _Digits);
            TKP = NormalizeDouble(PRC + takeProfit, _Digits);
           if(trade.BuyStop(lote, rates[1].high+5,_Symbol, /*PRC,*/ 0, 0/* ""*/)) 
             /*if(trade.OrderModify(PositionTicket, rates[1].high, /*PRC,*/ //STL, TKP,ENUM_ORDER_TYPE_TIME/* ""*/))
               {
                  Print(PRC,"Ordem de Compra - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de Compra - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }
             // TRAILING COMPRA   ---------------------------------------     
    /* else if(posAberta && ordPendente)
         {
            PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.ask, _Digits);
            STL = NormalizeDouble(rates[1].high+5 /*PRC - stopLoss*//*,/* _Digits);
         /*   TKP = NormalizeDouble(PRC + takeProfit, _Digits);
     /*      if(trade.Buy(lote, rates[1].high+5,_Symbol, /*PRC,*/ /*STL, TKP/* ""*//*)) 
             /*if(trade.OrderModify(PositionTicket, rates[1].high, /*PRC,*/ //STL, TKP,ENUM_ORDER_TYPE_TIME/* ""*/))
 /*              {
                  Print(PRC,"Ordem de Compra - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de Compra - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }*/
   //------------------VENDA----------------------------------------------------       
      if(corr[0]>Inp_KeyLevel && !posAberta && !ordPendente)
         {
         PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.bid, _Digits);
            STL = NormalizeDouble(rates[1].low-5 /*PRC - stopLoss*/, _Digits);
            TKP = NormalizeDouble(PRC + takeProfit, _Digits);
            if(trade.SellStop(lote, rates[1].low-5,_Symbol, /*PRC,*/ 0, 0/* ""*/))
               {
                  Print(PRC,"Ordem de Venda - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de Venda - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }
          //-------------- MODIFICANDO VENDA   ---------------------------------------     
     else if(corr[0]>Inp_KeyLevel && !posAberta && ordPendente)
         {
            PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.bid, _Digits);
            STL = NormalizeDouble(rates[1].low-5 /*PRC - stopLoss*/, _Digits);
            TKP = NormalizeDouble(PRC + takeProfit, _Digits);
           if(trade.SellStop(lote, rates[1].low-5,_Symbol, /*PRC,*/ 0, 0/* ""*/)) 
             /*if(trade.OrderModify(PositionTicket, rates[1].high, /*PRC,*/ //STL, TKP,ENUM_ORDER_TYPE_TIME/* ""*/))
               {
                  
                  Print(PRC,"Ordem de Venda - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de Venda - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }
//------------------TRALING VENDA----------------------------------------------------       
     else if( posAberta)
         {
         PendingOrderDelete();
            PRC = NormalizeDouble(ultimoTick.bid, _Digits);
            STL = NormalizeDouble(rates[1].low-5 /*PRC - stopLoss*/, _Digits);
            TKP = NormalizeDouble(PRC + takeProfit, _Digits);
            if(trade.Sell(lote, PRC,_Symbol, /*PRC,*/ 0, 0/* ""*/))
               {
                  Print(PRC,"Ordem de TRAILING Venda - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
            else
               {
                  Print(PRC,"Ordem de TRAILING Venda - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
               }
         }
          //--------------   ---------------------------------------     
 //------------------------------------------
  }
//---VOID AND BOOLS -------------------------------------------------------------------------------------------------------------------------------


//+------------------------------------------------------------------+
//| Buy conditions                                                   |
//+------------------------------------------------------------------+
bool BuySignal()
  {
   bool res=false;
   if(Inp_Strategy_type==1)
      res=(corr[0]<-Inp_KeyLevel)?true:false;
   else if(Inp_Strategy_type==2)
      res=(corr[0]<-Inp_KeyLevel)?true:false;
   return res;
  }
//+------------------------------------------------------------------+
//| Sell conditions                                                  |
//+------------------------------------------------------------------+
bool SellSignal()
  {
   bool res=false;
   if(Inp_Strategy_type==1)
      res=(corr[0]>Inp_KeyLevel)?true:false;
   else if(Inp_Strategy_type==2)
      res=(corr[0]>Inp_KeyLevel)?true:false;
   return res;
  }
  
 
  //+------------------------------------------------------------------+
  //+------------------------------------------------------------------+
//| Getting the current values of indicators                         |
//+------------------------------------------------------------------+
bool GetIndValue()
  {
   return(CopyBuffer(InpInd_Handle,0,0,2,corr)<=0)?false:true;
  }


//---TRAILING-------------------------------
/*void TrailingStop(double preco)
   {
      for(int i = PositionsTotal()-1; i>=0; i--)
         {
            string symbol = PositionGetSymbol(i);
            ulong magic = PositionGetInteger(POSITION_MAGIC);
            if(symbol == _Symbol && magic==magicNum)
               {
                  ulong PositionTicket = PositionGetInteger(POSITION_TICKET);
                  double StopLossCorrente = PositionGetDouble(POSITION_SL);
                  double PrecoEntrada = PositionGetDouble(POSITION_PRICE_OPEN);
                  double TakeProfitCorrente = PositionGetDouble(POSITION_TP);
                  if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                     {
                        if(preco >= (PrecoEntrada + gatilhoTS) )
                           {
                              double novoSL = NormalizeDouble(PositionTicket + stepTS, _Digits);
                              if(trade.PositionModify(PrecoEntrada, novoSL, TakeProfitCorrente))
                                 {
                                    Print("TrailingStop - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                              else
                                 {
                                    Print("TrailingStop - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                           }
                     }
                  else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                     {
                        if(preco <= (StopLossCorrente - gatilhoTS) )
                           {
                              double novoSL = NormalizeDouble(StopLossCorrente - stepTS, _Digits);
                              if(trade.PositionModify(PositionTicket, novoSL, TakeProfitCorrente))
                                 {
                                    Print("TrailingStop - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                              else
                                 {
                                    Print("TrailingStop - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                           }
                     }
               }
         }
   }
   */
   //|TRAILING 2                                       |
//+------------------------------------------------------------------+
void Trailingg(double preco)
  {
   for(int i=PositionsTotal()-1;i>=0;i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties
         if(m_position.Symbol()==Symbol())
           {
            if(m_position.Profit()>0.0)
               break;
            //---
            long digits=SymbolInfoInteger(m_position.Symbol(),SYMBOL_DIGITS);
            double point=SymbolInfoDouble(m_position.Symbol(),SYMBOL_POINT);
            //--- tuning for 3 or 5 digits
            int digits_adjust=1;
            if(digits==5 || digits==5)
               digits_adjust=10;
            double m_adjusted_point=NormalizeDouble(point*digits_adjust,_Digits);
            //---
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(m_position.PriceCurrent()-(TrailingStop-TrailingStep)*5/*m_adjusted_point*/>m_position.StopLoss())
                 {
                  //--- save Magic Number for the position
                  m_trade.SetExpertMagicNumber(m_position.Magic());
                  m_trade.PositionModify(m_position.Ticket(),
                                         m_position.PriceCurrent()+TrailingStop*5/*m_adjusted_point*/,
                                         m_position.TakeProfit());
                      Print("Trailing de posicao comprada: ");                   
                 }
              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)
              {
               double sl=0.0;
               if(m_position.StopLoss()>0)
                 {
                  if(m_position.PriceCurrent()+(TrailingStop+TrailingStep)*5/*m_adjusted_point*/<m_position.StopLoss())
                    {
                     sl=m_position.PriceCurrent()-TrailingStop*m_adjusted_point;
                     //--- save Magic Number for the position
                     m_trade.SetExpertMagicNumber(m_position.Magic());
                     m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());
                     Print("Trailing de posicao vendida: ");  
                    }
                 }
               else
                 {
                  sl=m_position.PriceCurrent()+TrailingStep*5/*m_adjusted_point*/;
                  //--- save Magic Number for the position
                  m_trade.SetExpertMagicNumber(m_position.Magic());
                  m_trade.PositionModify(m_position.Ticket(),sl,m_position.TakeProfit());
                 }
              }
           }
  }
//+------------------------------------------------------------------+
//---END POSITION------------------


void endpos()
{
for(int i=0; i< OrdersTotal();i++)
{
ulong orderTicket = OrderSelect(i); 
trade.OrderDelete(orderTicket);
}
}

//---CLOSE ALL POSITION


void PendingOrderDelete()
{
   int o_total=OrdersTotal();
   for(int j=o_total-1; j>=0; j--)
   {
      ulong o_ticket = OrderGetTicket(j);
      if(o_ticket != 0)
      {
         // delete the pending order
         trade.OrderDelete(o_ticket);
         Print("Ordens não realizadas foram excluídas.");
      }
   }
}

//-----------BREAKEVEN-----------------------------


void BreakEven(double preco)
   {
      for(int i = PositionsTotal()-1; i>=0; i--)
         {
            string symbol = PositionGetSymbol(i);
            ulong magic = PositionGetInteger(POSITION_MAGIC);
            if(symbol == _Symbol && magic == magicNum)
               {
                  ulong PositionTicket = PositionGetInteger(POSITION_TICKET);
                  double PrecoEntrada = PositionGetDouble(POSITION_PRICE_OPEN);
                  double TakeProfitCorrente = PositionGetDouble(POSITION_TP);
                  if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                     {
                        if( preco > (PrecoEntrada + gatilhoBE) )
                           {
                              if(trade.PositionModify(PositionTicket, PrecoEntrada, TakeProfitCorrente))
                                 {
                                    Print("BreakEven - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                    beAtivo = true;
                                 }
                              else
                                 {
                                    Print("BreakEven - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                           }                           
                     }
                  else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                     {
                        if( preco < (PrecoEntrada - gatilhoBE) )
                           {
                              if(trade.PositionModify(PositionTicket, PrecoEntrada, TakeProfitCorrente))
                                 {
                                    Print("BreakEven - sem falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                    beAtivo = true;
                                 }
                              else
                                 {
                                    Print("BreakEven - com falha. ResultRetcode: ", trade.ResultRetcode(), ", RetcodeDescription: ", trade.ResultRetcodeDescription());
                                 }
                           }
                     }
               }
         }
   }
Files:
20200913.log  11967 kb
 
Vladimir Karputov:

Você bagunçou alguma coisa com as imagens: no código você está procurando POSIÇÕES, e na imagem há um erro de PEDIDO ADIADO.

Ainda não está claro o que exatamente você precisa.

I need to set it only with profit positions and for example I like to set it at 15 point and set Steps with 10 Points, In this case Entry sell 100735 and I like the trailing stop below this value 100720 .

I changed the code (last message) but the trailling don´t work correctaly.

I´m very confused.

 
Silverveins :

I need to set it only with profit positions and for example I like to set it at 15 point and set Steps with 10 Points, In this case Entry sell 100735 and I like the trailing stop below this value 100720  .

I changed the code (last message) but the trailling don´t work correctaly.

I´m very confused.

Please decide: do you want to modify a POSITION or do you want to modify a PENDED ORDER? There is a lot of unnecessary garbage in your code. You need to decide (POSITION or POSTED ORDER) and start writing from scratch - gradually add the correct functions.

Reason: