Download MetaTrader 5

Trailing Stop for my EA (MT4)

To add comments, please log in or register
Abhinand Bajikumar Sreekala
876
Abhinand Bajikumar Sreekala  

Hi, i need a help.... This is my first EA and i am a beginner...

can anyone help me to put Trailing stop for my EA ... i tried many ways but trailing stop is not activating when i am putting it on strategy tester... please help...

this is my full EA(based on CCI for H4 and Daily TF, preferably GBPJPY) , MT4 :

//+---------------------------+
//| Expert Custom2            |
//+---------------------------+
#property copyright "Abhinand BS"
#property link      "abhi1860@gmail.com"

// User Input
extern double Lots = 0.1;
extern int    TakeProfit=255;
extern int    StopLoss=0;
extern int    Interval=1;
extern int       myCCIs=30;   //  5 days
extern int       myCCIl=150;  // 25 days

// Global scope
double barmove0 = 0;
double barmove1 = 0;
int         itv = 0;

double Poin;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//|------------------------------------------------------------------|

int init()
  {
   //Checking for unconvetional Point digits number
   if (Point == 0.00001) Poin = 0.0001; //5 digits
   else if (Point == 0.001) Poin = 0.01; //3 digits
   else Poin = Point; //Normal
   itv=Interval;
   return(0);
  }


//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }


//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+

int start()

  {

   bool      found=false;
   bool     rising=false;
   bool    falling=false;
   bool      cross=false;

   double slA=0, slB=0, tpA=0, tpB=0;
   double p=Poin;
  
   double cCIs;
   double cCIm;
   double cCIf;
  
   int      cnt=0;

   // Error checking
   if(AccountFreeMargin()<(1000*Lots))        {Print("-----NO MONEY"); return(0);}
   if(Bars<100)                               {Print("-----NO BARS "); return(0);}
   if(barmove0==Open[0] && barmove1==Open[1]) {                        return(0);}

   // bars moved, update current position
   barmove0=Open[0];
   barmove1=Open[1];

   // interval (bar) counter
   // used to pyramid orders during trend
   itv++;
  
   // since the bar just moved
   // calculate TP and SL for (B)id and (A)sk
   tpA=Ask+(p*TakeProfit);
   slA=Ask-(p*StopLoss);
   tpB=Bid-(p*TakeProfit);
   slB=Bid+(p*StopLoss);
   if (TakeProfit==0) {tpA=0; tpB=0;}          
   if (StopLoss==0)   {slA=0; slB=0;}          
  
   // get CCI based on OPEN
   cCIs=iCCI(Symbol(),0,125,PRICE_OPEN,0);
   cCIm=iCCI(Symbol(),0, 25,PRICE_OPEN,0);
   cCIf=iCCI(Symbol(),0,  5,PRICE_OPEN,0);

   // is it crossing zero up or down
   if (cCIm<=0 && cCIs>=0 && cCIf>0) { rising=true; cross=true; Print("Rising  Cross");}
   if (cCIm>=0 && cCIs<=0 && cCIf<0) {falling=true; cross=true; Print("Falling Cross");}
  
   // close then open orders based on cross
   // pyramid below based on itv
   if (cross)
     {
      // Close ALL the open orders
      for(cnt=OrdersTotal();cnt>0;cnt--)
        {
         if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==true){
// some code for processing your order would go here.
         }
         int ticket = 0;
         if(OrderSymbol()==Symbol())
        
           {
            if (OrderType()==0)
            int ddd = OrderClose(OrderTicket(),Lots,Bid,3,White);
            if (OrderType()==1)
            int fff = OrderClose(OrderTicket(),Lots,Ask,3,Red);
            itv=0;
           }
        }
      // Open new order based on direction of cross
      ticket =  OrderSend(Symbol(),OP_BUY,Lots,Ask,3,slA,tpA,"ZZZ100",11123,0,White);
      ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,slB,tpB,"ZZZ100",11321,0,Red);
    
      // clear the interval counter
      itv=0;
     }
  
   // Only pyramid if order already open
   found=false;
   for(cnt=OrdersTotal();cnt>0;cnt--)
     {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==true)
      if(OrderSymbol()==Symbol())
        {
         if (OrderType()==0)  //BUY
           {
            if (itv >= Interval)
              {
               ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,slA,tpA,"ZZZ100",11123,0,White);
               itv=0;
              }
           }
         if (OrderType()==1)  //SELL
           {
            if (itv >= Interval)
              {
               ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,slB,tpB,"ZZZ100",11321,0,Red);
               itv=0;
              }
           }
         found=true;
         break;
        }
     }
       return(0);
}
Marco vd Heijden
Moderator
6056
Marco vd Heijden  

Are you writing a indicator of an expert?

For indicators can not order or modify and close orders.

I do not see any OrderModify () function in your code so i am not sure how you want it to work?

Osama Shaban
1585
Osama Shaban  

I don't know if this will work for you or not. I'm sure there is no errors in my code as I used it too many times ...

What I did ?

- Added 2 functions (trailing stop code for Buy orders, trailing stop code for Sell orders, Order modify function for SL). 

- As you use 2 different magic numbers, I put them in the external settings to get use the trailing stop function the right way.

- changed "extern" to "input" ... Will not effect the code, but only to make you get used to the new language commands. 

- Added EA_Name.

- Added SL value. 

If the EA will not work, sure you got something else you have to correct. I'm sorry, I can't trace your code as it is not

my coding style :( ....

 

My advice to you ... Always try to get used to divide your code to many parts (Functions) ... Each part serve a part of the problem.

This will make coding more clear, easy, less errors, easy to trace, any body can understand, you can modify easily, and the most

important is that these functions will serve you in other codes to make easier and faster EAs :)

 

Good luck ...

//+---------------------------+
//| Expert Custom2            |
//+---------------------------+
#property copyright "Abhinand BS"
#property link      "abhi1860@gmail.com"

// User Input
input double    Lots = 0.1;
input int TakeProfit = 255;
input int   StopLoss = 1000;
input int     TrStop = 100;   //0 to disable !!!
input int   Interval = 1;
input int     myCCIs = 30;   //  5 days
input int     myCCIl = 150;  // 25 days
input int   MagicBuy = 11123;
input int  MagicSell = 11321;
input string EA_Name = "ZZZ100";

// Global scope
double barmove0 = 0;
double barmove1 = 0;
int         itv = 0;

double Poin;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//|------------------------------------------------------------------|

int init()
  {
   //Checking for unconvetional Point digits number
   if (Point == 0.00001) Poin = 0.0001; //5 digits
   else if (Point == 0.001) Poin = 0.01; //3 digits
   else Poin = Point; //Normal
   itv=Interval;
   return(0);
  }


//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }


//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+

int start()

  {

   bool      found=false;
   bool     rising=false;
   bool    falling=false;
   bool      cross=false;

   double slA=0, slB=0, tpA=0, tpB=0;
   double p=Poin;
  
   double cCIs;
   double cCIm;
   double cCIf;
  
   int      cnt=0;

   // Error checking
   if(AccountFreeMargin()<(1000*Lots))        {Print("-----NO MONEY"); return(0);}
   if(Bars<100)                               {Print("-----NO BARS "); return(0);}
   if(barmove0==Open[0] && barmove1==Open[1]) {                        return(0);}

   // bars moved, update current position
   barmove0=Open[0];
   barmove1=Open[1];

   // interval (bar) counter
   // used to pyramid orders during trend
   itv++;
  
   // since the bar just moved
   // calculate TP and SL for (B)id and (A)sk
   tpA=Ask+(p*TakeProfit);
   slA=Ask-(p*StopLoss);
   tpB=Bid-(p*TakeProfit);
   slB=Bid+(p*StopLoss);
   if (TakeProfit==0) {tpA=0; tpB=0;}          
   if (StopLoss==0)   {slA=0; slB=0;}          
  
   // get CCI based on OPEN
   cCIs=iCCI(Symbol(),0,125,PRICE_OPEN,0);
   cCIm=iCCI(Symbol(),0, 25,PRICE_OPEN,0);
   cCIf=iCCI(Symbol(),0,  5,PRICE_OPEN,0);

   // is it crossing zero up or down
   if (cCIm<=0 && cCIs>=0 && cCIf>0) { rising=true; cross=true; Print("Rising  Cross");}
   if (cCIm>=0 && cCIs<=0 && cCIf<0) {falling=true; cross=true; Print("Falling Cross");}
  
   // close then open orders based on cross
   // pyramid below based on itv
   if (cross)
     {
      // Close ALL the open orders
      for(cnt=OrdersTotal();cnt>0;cnt--)
        {
         if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==true){
// some code for processing your order would go here.
         }
         int ticket = 0;
         if(OrderSymbol()==Symbol())
        
           {
            if (OrderType()==0)
            int ddd = OrderClose(OrderTicket(),Lots,Bid,3,White);
            if (OrderType()==1)
            int fff = OrderClose(OrderTicket(),Lots,Ask,3,Red);
            itv=0;
           }
        }
      // Open new order based on direction of cross
      ticket =  OrderSend(Symbol(),OP_BUY,Lots,Ask,3,slA,tpA,EA_Name,MagicBuy,0,White);
      ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,slB,tpB,EA_Name,MagicSell,0,Red);
    
      // clear the interval counter
      itv=0;
     }
  
   // Only pyramid if order already open
   found=false;
   for(cnt=OrdersTotal();cnt>0;cnt--)
     {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)==true)
      if(OrderSymbol()==Symbol())
        {
         if (OrderType()==0)  //BUY
           {
            if (itv >= Interval)
              {
               ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,slA,tpA,EA_Name,MagicBuy,0,White);
               itv=0;
              }
           }
         if (OrderType()==1)  //SELL
           {
            if (itv >= Interval)
              {
               ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,slB,tpB,EA_Name,MagicSell,0,Red);
               itv=0;
              }
           }
         found=true;
         break;
        }
     }
   if(TrStop != 0){
      TrailingPositionsBuy(TrStop);
      TrailingPositionsSell(TrStop);
   }    
       return(0);
}

void TrailingPositionsBuy(int trailingStop) {
   for (int i=0; i<OrdersTotal(); i++) {      
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicBuy) {
            if (OrderType()==OP_BUY) {
               if (Bid-OrderOpenPrice()>trailingStop*Poin) {
                  if (OrderStopLoss()<Bid-trailingStop*Poin)
                     ModifyStopLoss(Bid-trailingStop*Poin);
               }
            }
         }
      }
   }
}

void TrailingPositionsSell(int trailingStop) {
   for (int i=0; i<OrdersTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderSymbol()==Symbol() && OrderMagicNumber()==MagicSell) {
            if (OrderType()==OP_SELL) {
               if (OrderOpenPrice()-Ask>trailingStop*Poin) {
                  if (OrderStopLoss()>Ask+trailingStop*Poin)  
                     ModifyStopLoss(Ask+trailingStop*Poin);
               }
            }
         }
      }
   }
}

void ModifyStopLoss(double ldStopLoss) {
   bool fm;
   fm = OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);
}


 

Abhinand Bajikumar Sreekala
876
Abhinand Bajikumar Sreekala  
Marco vd Heijden:

Are you writing a indicator of an expert?

For indicators can not order or modify and close orders.

I do not see any OrderModify () function in your code so i am not sure how you want it to work?

Thank you....but still trailing stop is not working in strategy tester .
whroeder1
16764
whroeder1  
Roberto Jacobs
49014
Roberto Jacobs  
Abhinand Bajikumar Sreekala:

Hi, i need a help.... This is my first EA and i am a beginner...

can anyone help me to put Trailing stop for my EA ... i tried many ways but trailing stop is not activating when i am putting it on strategy tester... please help...

this is my full EA(based on CCI for H4 and Daily TF, preferably GBPJPY) , MT4 :


I know, this is the old code from 2009, I've learn this code, the fault is in Point on the init() function.


Bid-trailingStop*Poin // or
Ask+trailingStop*Poin // The conditions will never be fulfilled

Replace the init() function with



int OnInit()
  {
//----
   //-- Checking the Digits Point
   if(_Digits==3||_Digits==5) {Poin=_Point*10;}
   else if(_Digits==2||_Digits==4) {Poin=_Point;}
   //--
   itv=Interval;
//----
   return(INIT_SUCCEEDED);
  }
//---------//
To add comments, please log in or register