About trailing stop

 

Can anybody please upload a code section on 

how to modify a position e.g. trailing stop.

I tried different variants and it does not work. 

Please help.

Thank You. 

 

Assuming you are using an Expert based off of Include/Expert/Expert.mqh you should have an object CExpertTrade named m_trade.  

If you then look at how the base expert class executes a trailing operation you will see how it is done. Pasted below from the Expert.mqh file for convenience:

//+------------------------------------------------------------------+
//| Trailing stop/profit long position                               |
//| INPUT:  sl - new stop loss,                                      |
//|         tp - new take profit.                                    |
//| OUTPUT: true-if trade operation successful, false otherwise.     |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
bool CExpert::TrailingStopLong(double sl,double tp)
  {
   return(m_trade.PositionModify(m_symbol.Name(),sl,tp));
  }
//+------------------------------------------------------------------+
//| Trailing stop/profit short position                              |
//| INPUT:  sl - new stop loss,                                      |
//|         tp - new take profit.                                    |
//| OUTPUT: true-if trade operation successful, false otherwise.     |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
bool CExpert::TrailingStopShort(double sl,double tp)
  {
   return(m_trade.PositionModify(m_symbol.Name(),sl,tp));
  }

 

 
firestrand:

Assuming you are using an Expert based off of Include/Expert/Expert.mqh you should have an object CExpertTrade named m_trade.  

If you then look at how the base expert class executes a trailing operation you will see how it is done. Pasted below from the Expert.mqh file for convenience:

 

firestrand, thank you for your help.

I am not familiar with classes and therefore it did not work for me.

Can anyone paste a simple function that modifies position stop loss

 
Learner21:

firestrand, thank you for your help.

I am not familiar with classes and therefore it did not work for me.

Can anyone paste a simple function that modifies position stop loss?


I dont have time to write an entire code because im working on an ATC 2011 hyper EA but ill just summarize and give you links that might help you

     MqlTradeRequest request;

double cprice,cprofit,oprice,new_sl,cbid,cask; 

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

// Assuming you gave your buy orders magic number 01 and sell orders 02

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

int Trailing=120;  // trailing stop

//------------------------------Get current bid or ask-----------------------------------------

   MqlTick last_tick;

   SymbolInfoTick(_Symbol,last_tick);

   cbid=last_tick.bid;         // automatically contains the value of our current bid

   cask=last_tick.Ask;     // ................................our current ask


//---------------------------------------Set parameters for structure of trade operations------------------------------------------

   MqlTradeRequest request;              // declaration

   MqlTradeResult result;           // declaration


   request.action=TRADE_ACTION_MODIFY;         // setting a modify order

   request.symbol=_Symbol;                      // symbol

   request.volume=1;                          // volume in lots

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

//----------------------------------Cycle and select orders--------------------------------------------------------------------------

for(int i=0; i<=PositionsTotal(); i++)          // Cycle searching in orders
     {
            

         if(PositionSelect(PositionGetSymbol(i))==true&&PositionGetInteger(POSITION_MAGIC)==01) // if position is selected and its the order magic number we want

          {

             oprice=PositionGetDouble(POSITION_PRICE_OPEN);                                               // open price of the order

             cprofit=NormalizeDouble(cbid-oprice*_Point,_Digits);                        // current profit

             if(cprofit>=Trailing)

                {

                   new_sl=NormalizeDouble(cbid-Trailing*_Point,_Digits);                   // this will be our new stop loss

                   request.sl=new_sl;                                                      // save it to the request structure

                   OrderSend(request,result);                                              // modify the order

                }

          
          }
      

     }

// lol thats just about the all code test it and see if it works

 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Data Structures / Trade Request Structure
  • www.mql5.com
Standard Constants, Enumerations and Structures / Data Structures / Trade Request Structure - Documentation on MQL5
 

It will greatly simplify your logic if you use the classes.


 
firestrand:

It will greatly simplify your logic if you use the classes.


He wants a code that doesn't use classes
 
Here's a function that i made to act as a trailing stop for my EAs. It works well, and it doesn't need a magic number from orders if you don't feel like putting one in (i sure didn't), so you can just take the code, paste it in at the bottom of the ea you're making, and then call the function with your trailing stop input variable as the parameter. You can use any code you want though, 'cause it's your choice after all.
void trailing(int trailstop)
 {
  double stop;
  double take;
  int trail = trailstop;
  if(Digits()==3||5)
   trail = trail*10;
  if(PositionSelect(Symbol())==true && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
   {
    stop = PositionGetDouble(POSITION_SL);
    take = PositionGetDouble(POSITION_TP);
    if(SymbolInfoDouble(Symbol(),SYMBOL_ASK)-trail*Point()>stop)
     {
      trade.sl = SymbolInfoDouble(Symbol(),SYMBOL_ASK)-trail*Point();
      trade.action = TRADE_ACTION_SLTP;
      trade.deviation = 0;
      trade.symbol = Symbol();
      if(OrderSend(trade,info)==false)
       Print("OrderSend failed with error #",GetLastError());
     }
   }
  if(PositionSelect(Symbol())==true && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
   {
    stop = PositionGetDouble(POSITION_SL);
    take = PositionGetDouble(POSITION_TP);
    if(SymbolInfoDouble(Symbol(),SYMBOL_BID)+trail*Point()<stop)
     {
      trade.sl = SymbolInfoDouble(Symbol(),SYMBOL_BID)+trail*Point();
      trade.action = TRADE_ACTION_SLTP;
      trade.deviation = 0;
      trade.symbol = Symbol();
      if(OrderSend(trade,info)==false)
       Print("OrderSend failed with error #",GetLastError());
     }
   }
 }
 
PipSlayer42:
Here's a function that i made to act as a trailing stop for my EAs. It works well, and it doesn't need a magic number from orders if you don't feel like putting one in (i sure didn't), so you can just take the code, paste it in at the bottom of the ea you're making, and then call the function with your trailing stop input variable as the parameter. You can use any code you want though, 'cause it's your choice after all.

which class does the variable "trade" come from?
 
PipSlayer42:
Here's a function that i made to act as a trailing stop for my EAs. It works well, and it doesn't need a magic number from orders if you don't feel like putting one in (i sure didn't), so you can just take the code, paste it in at the bottom of the ea you're making, and then call the function with your trailing stop input variable as the parameter. You can use any code you want though, 'cause it's your choice after all.

Also what if i dont want the trailing stop to operate on any order it finds open? See thats where magic number helps
 
tonny:
which class does the variable "trade" come from?
"trade" is what i call the MqlTradeRequest struct, and "info" is the MqlTradeResult struct. And for the second problem, i just dont really deal with it as much because i only have one open position at a time. I dont use pending orders, just market orders, so i only have one trade open at a time, which is why it works for me. And i was wondering about your code, is it for pending orders or for open positions? Because in the MQL5 reference in MetaEditor, "TRADE_ACTION_MODIFY" says it's for orders, which makes me think of pending orders (which i believe is the correct way to think about it) but sometimes the context that the words "order" and "position" are used in can make it a bit confusing. At least for me anyways. Other than all of that, my main point is that my code is really just for already opened positions, not really for the modification of pending orders.
Documentation on MQL5: Standard Constants, Enumerations and Structures / Data Structures / Trade Request Structure
  • www.mql5.com
Standard Constants, Enumerations and Structures / Data Structures / Trade Request Structure - Documentation on MQL5
 

Nice. Looks good to me everything but 

when I run this code

if(PositionSelect(Symbol())==true && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
   {
  Print(" Position select = ", GetLastError());
    stop = PositionGetDouble(POSITION_SL);
    take = PositionGetDouble(POSITION_TP);

 it says Error = 4753 which means position not found.

When I use

for(int b=0;b<=PositionsTotal();b++)
  if(PositionSelect(Symbol())==true && PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
   {
  Print(" Position select = ", GetLastError());

 it still gives the same error. 

Reason: