Trailing profit Problems

 
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?

Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Order Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Requests to execute trade operations are formalized as orders. Each order has a variety of properties for reading. Information on them can be obtained using functions Position identifier that is set to an order as soon as it is executed. Each executed order results in a deal that opens or modifies an already existing position. The identifier of...
 

Forum on trading, automated trading systems and testing trading strategies

When you post code please use the CODE button (Alt-S)!

Use the CODE button



 
Sergey Golubev:
// VOID ON TICK --------------------------------------------- -------------------------------------------------- ----------------------------------



  

void OnTick ()

  {           

   CopyRates (Symbol (), Period (), 0,3, taxas); 

    ulong PositionTicket = OrderGetTicket (ORDER_MAGIC);

 // END POSITION --------------

   MqlDateTime dt;

TimeCurrent (dt);

if (dt.sec == 60) {

endpos ();

}  

// -----------------

      if (! SymbolInfoTick (Symbol (), ultimoTick))

         {

            Alert ("Erro ao obter informações de preços:", GetLastError ());

            Retorna;

         }

         

      if (CopyRates (_Symbol, _Period, 0, 3, rates) <0)

         {

            Alert ("Erro ao obter as informações de MqlRates:", GetLastError ());

            Retorna;

         }

      

     / * if (CopyBuffer (smaHandle, 0, 0, 3, smaArray) <0)

         {

            Alert ("Erro ao copiar dados da média móvel:", GetLastError ());

            Retorna;

         } * /

         

      posAberta = falso;

      para (int i = PositionsTotal () - 1; i> = 0; i--)

         {

            símbolo de string = PositionGetSymbol (i);

            ulong magic = PositionGetInteger (POSITION_MAGIC);

            if (símbolo == _Symbol && magic == magicNum)

               {  

                  posAberta = true;

                  pausa;

               }

         }

         

      ordPendente = false;

      for (int i = OrdersTotal () - 1; i> = 0; i--)

         {

            ulong ticket = OrderGetTicket (i);

            símbolo de string = OrderGetString (ORDER_SYMBOL);

            ulong magic = OrderGetInteger (ORDER_MAGIC);

            if (símbolo == _Symbol && magic == magicNum)

               {

                  ordPendente = verdadeiro;

                  pausa;

               }

         }

      

      if (! posAberta)

         {

            beAtivo = falso;

         }

         

      if (posAberta &&! beAtivo)

         {

            BreakEven (ultimoTick.last);

         }

         

      if (posAberta && beAtivo)

         {

            TrailingStop (ultimoTick.last);

         }

      

      // --- Obtendo dados para cálculos



   if (! GetIndValue ())

      Retorna;

   

 // COMPRA ----------------------------------------------- -----       

      if (corr [0] <- Inp_KeyLevel &&! posAberta &&! ordPendente)

         {

         

            PRC = NormalizeDouble (ultimoTick.ask, _Digits);

            STL = NormalizeDouble (taxas [1] .low-5 / * PRC - stopLoss * /, _Digits);

            TKP = NormalizeDouble (PRC + takeProfit, _Digits);

            if (trade.BuyStop (lote, rates [1] .high + 5, _Symbol, / * PRC, * / STL, TKP / * "" * /))

               {

                  Print ("Ordem de Compra - sem falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

            outro

               {

                  Print ("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 (taxas [1] .high + 5 / * PRC - stopLoss * /, _Digits);

            TKP = NormalizeDouble (PRC + takeProfit, _Digits);

           if (trade.BuyStop (lote, rates [1] .high + 5, _Symbol, / * PRC, * / STL, TKP / * "" * /)) 

             /*if(trade.OrderModify(PositionTicket, rates [1] .high, / * PRC, * / // STL, TKP, ENUM_ORDER_TYPE_TIME / * "" * /))

               {

                  Print ("Ordem de Compra - sem falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

            outro

               {

                  Print ("Ordem de Compra - com falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

         }

    

      // VENDA --------------------------

      else if (corr [0]> Inp_KeyLevel &&! posAberta &&! ordPendente)

         {

            PRC = NormalizeDouble (ultimoTick.bid, _Digits);

            STL = NormalizeDouble (taxas [1] .high + 5, _Digits);

            TKP = NormalizeDouble (PRC - takeProfit, _Digits);

            if (trade.SellStop (lote, rates [1] .low-5, _Symbol, / * PRC, * / STL, TKP / * "" * /))

               {

                  Print ("Ordem de Venda - sem falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

            outro

               {

                  Print ("Ordem de Venda - com falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

         }  

         // MODIFICANDO VENDA ---------------------------

      else if (corr [0]> Inp_KeyLevel &&! posAberta && ordPendente)

         {

            PRC = NormalizeDouble (ultimoTick.bid, _Digits);

            STL = NormalizeDouble (taxas [1] .high + 5, _Digits);

            TKP = NormalizeDouble (PRC - takeProfit, _Digits);

            if (trade.SellStop (lote, rates [1] .low-5, _Symbol, / * PRC, * / STL, TKP / * "" * /))

               {

                  Print ("Ordem de Venda - sem falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

            outro

               {

                  Print ("Ordem de Venda - com falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

               }

         }    

  }

// --- VOID AND BOOLS ------------------------------------------ -------------------------------------------------- -----------------------------------





// + ----------------------------------------------- ------------------- +

// | Condições de compra |

// + ----------------------------------------------- ------------------- +

bool BuySignal ()

  {

   bool res = falso;

   if (Inp_Strategy_type == 1)

      res = (corr [0] <- Inp_KeyLevel)? verdadeiro: falso;

   else if (Inp_Strategy_type == 2)

      res = (corr [0] <- Inp_KeyLevel)? verdadeiro: falso;

   return res;

  }

// + ----------------------------------------------- ------------------- +

// | Condições de venda |

// + ----------------------------------------------- ------------------- +

bool SellSignal ()

  {

   bool res = falso;

   if (Inp_Strategy_type == 1)

      res = (corr [0]> Inp_KeyLevel)? verdadeiro: falso;

   else if (Inp_Strategy_type == 2)

      res = (corr [0]> Inp_KeyLevel)? verdadeiro: falso;

   return res;

  }

  

 

  // + ----------------------------------------------- ------------------- +

  // + ----------------------------------------------- ------------------- +

// | Obtendo os valores atuais dos indicadores |

// + ----------------------------------------------- ------------------- +

bool GetIndValue ()

  {

   return (CopyBuffer (InpInd_Handle, 0,0,2, corr) <= 0)? false: true;

  }





//---SEGUINDO-------------------------------



void TrailingStop (double preco)

   {

      para (int i = PositionsTotal () - 1; i> = 0; i--)

         {

            símbolo de string = PositionGetSymbol (i);

            ulong magic = PositionGetInteger (POSITION_MAGIC);

            if (símbolo == _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 ());

                                 }

                              outro

                                 {

                                    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 ());

                                 }

                              outro

                                 {

                                    Print ("TrailingStop - com falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

                                 }

                           }

                     }

               }

         }

   }

   

// --- POSIÇÃO FINAL ------------------





void endpos ()

{

para (int i = 0; i <OrdersTotal (); i ++)

{

ulong orderTicket = OrderSelect (i); 

trade.OrderDelete (orderTicket);

}

}



// --- FECHAR TODAS AS POSIÇÕES





void PendingOrderDelete ()

{

   int o_total = OrdersTotal ();

   para (int j = o_total-1; j> = 0; j--)

   {

      ulong o_ticket = OrderGetTicket (j);

      if (o_ticket! = 0)

      {

         // exclua o pedido pendente

         trade.OrderDelete (o_ticket);

         Impressão ("Ordens não realizadas foram excluídas.");

      }

   }

}



// -----------





void BreakEven (double preco)

   {

      para (int i = PositionsTotal () - 1; i> = 0; i--)

         {

            símbolo de string = PositionGetSymbol (i);

            ulong magic = PositionGetInteger (POSITION_MAGIC);

            if (símbolo == _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 = verdadeiro;

                                 }

                              outro

                                 {

                                    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 = verdadeiro;

                                 }

                              outro

                                 {

                                    Print ("BreakEven - com falha. ResultRetcode:", trade.ResultRetcode (), ", RetcodeDescription:", trade.ResultRetcodeDescription ());

                                 }

                           }

                     }

               }

         }

   }
Reason: