Time Trader EA - Trailing Stop problem

Back to topics list To post a new topic, please log in or register
avatar
15
Chris1303 2015.12.18 22:22
 

Hi All,

 I wanted to create an EA that would open a trade at specific date and time. I also wanted to add Trailing Stop to it. I made a research on this forum and did not find ready solution. So I tried to mix some EAs. Som efeuterues added correctly. However I have a problem with Trailing Stop that activates after take profit is reached.

 

EAs that I used:

1. Time Trader - https://www.mql5.com/en/code/10822

2. eTrailing - https://www.mql5.com/ru/code/7778 

 

My changed code:

 

//---- input parameters



extern double   Lots=100;

extern int      TakeProfit=0;

extern int      StopLoss=0;

extern int      Slip=5;

extern bool     AllPositions  =false;         

extern bool     ProfitTrailing=true;          

extern int      TrailingStop  =5;           

extern int      TrailingStep  =5;

extern string   TradeSettings="Mt4 time(min-max): hours 0-23, minutes 0-59";

extern bool     AllowBuy=true;

extern bool     AllowSell=true;

extern int      TradeYear=2015;

extern int      TradeMonth=12;

extern int      TradeDay=0;

extern int      TradeHour=0;

extern int      TradeMinutes=0;

extern int      TradeSeconds=0;

extern string   MagicNumbers="To be changed in case of conflict with other EAs";

extern int      BuyMagicNumber =10001;

extern int      SellMagicNumber =10002;



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

//| expert initialization function                                   |

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

int init()

  {

//----

   

//----

   return(0);

  }

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

//| expert starts                                  |

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



int start()

  {

  

  

//----

int StopMultd,Sleeper=1;







int digits=MarketInfo("EURUSD",MODE_DIGITS);

StopMultd=1;

double TP=NormalizeDouble(TakeProfit*StopMultd,Digits);

double SL=NormalizeDouble(StopLoss*StopMultd,Digits);

int Slippage=Slip*StopMultd;



// Calculate stop loss

double slb=NormalizeDouble(Ask-SL*Point,Digits);

double sls=NormalizeDouble(Bid+SL*Point,Digits);



// Calculate take profit

double tpb=NormalizeDouble(Ask+TP*Point,Digits);

double tps=NormalizeDouble(Bid-TP*Point,Digits);



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

//Check open orders

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

if(OrdersTotal()>0){

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

     {

      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) // If the next is available

        break;

        {

          if(OrderSymbol()==Symbol() && OrderMagicNumber()==BuyMagicNumber) {int halt1=1;}

          if(OrderSymbol()==Symbol() && OrderMagicNumber()==SellMagicNumber) {int halt2=1;}

          if (AllPositions || OrderSymbol()==Symbol()) {int TrailingPositions=1;}

          if (AllPositions || OrderSymbol()==Symbol()) {int ModifyStopLoss=1;} 

             {

              bool fm;

              fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);

             }

        }

     }

}

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





if((halt1!=1)&&(AllowBuy==true)){// halt1



// Buy criteria

if ((TradeHour==Hour())&&(TradeMinutes==Minute())&&(TradeSeconds==Seconds())&&(TradeYear==Year())&&(TradeMonth==Month())&&(TradeDay==Day())) //Signal Buy

 {

   int openbuy=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"time trader buy order ",BuyMagicNumber,0,Blue);

   if(openbuy<1){int buyfail=1;}

 }

 

}// halt1

 

if((halt2!=1)&&(AllowSell==true)){// halt2

RefreshRates();

 // Sell criteria

 if ((TradeHour==Hour())&&(TradeMinutes==Minute())&&(TradeSeconds==Seconds())&&(TradeYear==Year())&&(TradeMonth==Month())&&(TradeDay==Day())) //Signal Sell

 {

   int opensell=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"time trader sell order ",SellMagicNumber,0,Green);

   if(opensell<1){int sellfail=1;}

 }

 

}// halt2



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

if(OrdersTotal()>0){

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

  

      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false){ // If the next is available

        

          if((OrderSymbol()==Symbol() && OrderMagicNumber()==BuyMagicNumber)&&(OrderTakeProfit()==0||OrderStopLoss()==0)) { OrderModify(OrderTicket(),0,slb,tpb,0,CLR_NONE); }

          if((OrderSymbol()==Symbol() && OrderMagicNumber()==SellMagicNumber)&&(OrderTakeProfit()==0||OrderStopLoss()==0)) { OrderModify(OrderTicket(),0,sls,tps,0,CLR_NONE); }



        }

     }

}

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

// Trailing Stop

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



if((TrailingPositions!=1)&&(AllPositions=true))

  {

   double pBid, pAsk, pp;

//----

   pp=MarketInfo(OrderSymbol(), MODE_POINT);

     if (OrderType()==OP_BUY) 

     {

      pBid=MarketInfo(OrderSymbol(), MODE_BID);

        if (!ProfitTrailing || (pBid-OrderOpenPrice())>TrailingStop*pp) 

        {

           if (OrderStopLoss()<pBid-(TrailingStop+TrailingStep-1)*pp) 

           {

            ModifyStopLoss(pBid-TrailingStop*pp);

            return;

           }

        }

     }

     if (OrderType()==OP_SELL) 

     {

      pAsk=MarketInfo(OrderSymbol(), MODE_ASK);

        if (!ProfitTrailing || OrderOpenPrice()-pAsk>TrailingStop*pp) 

        {

           if (OrderStopLoss()>pAsk+(TrailingStop+TrailingStep-1)*pp || OrderStopLoss()==0) 

           {

            ModifyStopLoss(pAsk+TrailingStop*pp);

            return;

           }

        }

     }

  }



// Modify Order



  





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

// Error processing

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

if(buyfail==1||sellfail==1){

int Error=GetLastError();

  if(Error==130){Alert("Wrong stops. Retrying."); RefreshRates();}

  if(Error==133){Alert("Trading prohibited.");}

  if(Error==2){Alert("Common error.");}

  if(Error==146){Alert("Trading subsystem is busy. Retrying."); Sleep(500); RefreshRates();}



}





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

   return(0);

  }

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

 

Could you please point me in the right direction how to fix it and enable Trailing Stop?

 

Kind regards,

Chris 

avatar
13006
WHRoeder 2015.12.19 02:35 #
 
  1. Don't paste code
    Play video
    Please edit your post.
    For large amounts of code, attach it.

  2.   pBid=MarketInfo(OrderSymbol(), MODE_BID);
    Why use a function call when you can just use the predefined Bid?
  3. Check your return codes and find out why. What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
  4. Do NOT use NormalizeDouble, EVER. For ANY Reason. It's a kludge, don't use it. It's use is always wrong
avatar
15
Chris1303 2015.12.19 10:11 #
 

Hi WHRoeder,

Thank you for your quick reply. I have edited my above post as you requested and used SRC.

I`m  starting to study in order to implement your hints.

I will make an update soon. 

Kind regards,

Chris 

avatar
15
Chris1303 2015.12.19 14:06 #
 

Spent hours to solve the case, tried hunders of combinations, however with no result.

My knowledge seems insufficient in regards to mql4 coding.

I thought I could figure it out like I do it for excel macros, but it is more difficult.  

I will post this on mql4 job site.

Thank once again.

I consider this trad closed.

Kind regards,

Chris 

avatar
2017
gooly 2015.12.19 14:23 #
 

1) make it a habit to count down open orders!

// failes if you close orders: for(i=0; i<OrdersTotal(); i++){          // Cycle searching in orders
for(i=OrdersTotal()-1; i>=0; i--){          // Cycle searching in orders

2) Your code is - for me - quite confusing. Keep OrderSelect() in the same loop you cont down the OrdersTotal-loop.


avatar
15
Chris1303 2015.12.20 11:17 #
 

Hi gooly,

Yes, that code can be confusing, with no doubt :)

I`m not a developer, just mixed two EAs and adjusted some part of code found on the net in most logical way for the guy with no mql4 knowledge. 

Just posted above on mql5 job site. Raul agreed to work on it with me.

Thanks for your help. 

 

Back to topics list  

To add comments, please log in or register