Please Help needed : Trailing Stop Code

To add comments, please log in or register
Christoph Sackl
126
Christoph Sackl  
Hi,

I am new to the metaquote language and have problems with programing a trailing stop that works.

Can anybody help me with the code. Mine is changing the stop correctly when the market moves up but it also changes it when it moves down even if it shouldn't, this in the case of a Long position.

Here is the code I wrote. Hope there is just a mistake.

//---- if the MagicNumber is not equal to the Expert_ID, skip this position
    if ( OrderMagicNumber() != Expert_ID ) continue;
    else
   
    //Manage open orders
         //move TrailingStop if profit>TS
            if(OrderType()==OP_BUY)
            {
               if (Bid-OrderOpenPrice()>TrailingStop*Point && OrderStopLoss()<Bid-TrailingStop*Point)
               {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*Point,0,0,Green);
               }  
            }
           
            if(OrderType()==OP_SELL)
            {
               if(OrderOpenPrice()-Ask>TrailingStop*Point && OrderStopLoss()>Ask+TrailingStop*Point)
              {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TrailingStop*Point,0,0, Red);
              }           
           }
forexfordinner
62
forexfordinner  

Hi Chris, use this


int openedpositions;
double mySL, myResult;

openedpositions=OrdersTotal();
if ((openedpositions > 0))
{
int totalorders = OrdersTotal();
for(int i=0;i<totalorders;i++) // scan all orders and positions. ..
{
OrderSelect(i, SELECT_BY_POS);
if ( OrderSymbol()==Symbol() && OrderMagicNumber() == uniqueGridMagic) // only look if mygrid and symbol. ..
{
int type = OrderType();
if ( type == OP_BUY ) // its a long position
{
mySL = Ask-TrailingStop*Point; // new SL
if ( mySL > OrderStopLoss() )
{ // OK, we need to change the stoploss
myResult = OrderModify(OrderTicket(), OrderOpenPrice( ) ,mySL, OrderTakeProfit( ) ,0,CLR_NONE);
}
}
if ( type == OP_SELL )
{
mySL = Bid+TrailingStop*Point; // new SL
if (( mySL < OrderStopLoss()) || (OrderStopLoss() < Point) )
{ // OK, we need to change the stoploss
myResult = OrderModify(OrderTicket(), OrderOpenPrice( ) ,mySL, OrderTakeProfit( ) ,0,CLR_NONE);
}
}
}
}
}


just add it right before the end, good luck

Christoph Sackl
126
Christoph Sackl  

Thanks for your help. Unfortunately it seems it does exactly the same thing.
Meaning, while in a long position when the market moves up, the stop moves up and then rather surprisingly if the market starts to move down, the stop is decreased according to the trailing level (stop always XX pips from the market).

And my point is that I do not want the stop to move when market moves down. The opposite when short position of course.

My point is that there might be a bug in the OrderModify function.

Anybody has an idea?

afifio
10
afifio  
I suggest you chase it instead of trail. Chasing done by speficying "up" pip. The 5 point if there is a sudden jum and 2 point is for small increment.

for(OrderTicketNum=0;OrderTicketNum<total;OrderTicketNum++)
{
    OrderSelect(OrderTicketNum,SELECT_BY_POS,MODE_TRADES);
    
    if(OrderEqual(OP_BUY,Symbol(),0.0,0.0,0.0,0.0,"",0.0,""))
        {
 
    TradeOpen = OrderOpenPrice();
    StopLoss = OrderStopLoss();
        if(StopLoss != 0.0)
            {
            if(Bid - PriceBuffer > OrderStopLoss() + (Point*20) )
{
NewLongStopLoss = StopLoss+(5*Point); }
else
{
NewLongStopLoss = StopLoss+(2*Point); }
} LongBreakeven = OrderOpenPrice() + PriceBuffer; if(Bid-PriceBuffer > OrderStopLoss() && StopLoss != 0.0) { //Print("[Trail] "+OrderTicket()+" Pip:"+PriceToInt(NewLongStopLoss-TradeOpen)+" & Trade:"+OrderOpenPrice()+"-"+OrderComment()); tmp = OrderModify(OrderTicket(),TradeOpen,NewLongStopLoss,0.0,255,Green); } // snip snip
saha koko
154
saha koko  
Chris,

did you solve the problem? Unfortunately I have the same problem.
jess
117
jess  
if(OrderType()==OP_BUY && Bid-OrderOpenPrice() > Trailing_Stop*Point && OrderMagicNumber()==MAGICMA && OrderStopLoss()< Bid - Trailing_Stop*Point )
            {
                    OrderModify(OrderTicket(),OrderOpenPrice(),Bid - Trailing_Stop*Point,OrderTakeProfit(),0,Blue);
                    Sleep(10000);
            }
      if(OrderType()==OP_SELL && OrderOpenPrice()-Ask > Trailing_Stop*Point && OrderMagicNumber()==MAGICMA && OrderStopLoss()> Ask + Trailing_Stop*Point)
            {
                    OrderModify(OrderTicket(),OrderOpenPrice(),Bid + Trailing_Stop*Point,OrderTakeProfit(),0,Blue);
                    Sleep(10000);
            }

here this works, i'v been using it, it checks that the profit is greater than the open price so stop will be moved once in profit. then it checks that the stop loss is GREATER than your trailing amount.so will only move the stop price into profit, not backwards.

NabiKAZ
53
NabiKAZ  

@jess, Why use Sleep in here?

NabiKAZ
53
NabiKAZ  

@jess, And so I thinks in the second OrderModify function, must use Ask instead of Bid:

OrderModify(OrderTicket(),OrderOpenPrice(),Ask + Trailing_Stop*Point,OrderTakeProfit(),0,Blue);

Roman Starostin
4749
Roman Starostin  
You can use this base: https://www.mql5.com/en/code/9530
Quint Boney
902
Quint Boney  
jess:

here this works, i'v been using it, it checks that the profit is greater than the open price so stop will be moved once in profit. then it checks that the stop loss is GREATER than your trailing amount.so will only move the stop price into profit, not backwards.

This actually works perfect!

I modified very slightly. But still not sure if there is a way to get a ticket number from the modified order?


   double Trailing_Stop = 250;

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

     {

       if( OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderSymbol() == symbol)

         {

          if(OrderType()==OP_BUY && Bid-OrderOpenPrice() > Trailing_Stop*Point && OrderMagicNumber()==MagicNumber && OrderStopLoss()< Bid - Trailing_Stop*Point )

            {

                    ticket=OrderModify(OrderTicket(),OrderOpenPrice(),Bid - Trailing_Stop*Point,OrderTakeProfit(),0,Blue);

                    if (ticket > 0) 

                       {

                        Print("Trailing Stop for Buy Adjusted");

                       }

                        else

                       {

                         Print("Error opening Trailing Stop Buy order : ",GetLastError());

                       }

                    Sleep(10000);

            }

          if(OrderType()==OP_SELL && OrderOpenPrice()-Ask > Trailing_Stop*Point && OrderMagicNumber()==MagicNumber && OrderStopLoss()> Ask + Trailing_Stop*Point)

            {

                    ticket=OrderModify(OrderTicket(),OrderOpenPrice(),Bid + Trailing_Stop*Point,OrderTakeProfit(),0,Blue);

                    if (ticket > 0) 

                       {

                        Print("Trailing Stop for Sell Adjusted");

                       }

                        else

                       {

                         Print("Error opening Trailing Stop SELL order : ",GetLastError());

                       }  

                    Sleep(10000);                  

                    

            } 

         }

     }   

Marco vd Heijden
Moderator
12688
Marco vd Heijden  

It's the OrderTicket()


Print(OrderTicket(),"Trailing Stop for Buy Adjusted");
12
To add comments, please log in or register