Why does my EA keeps giving negative profit when back testing? - page 3

 
deVries:

when you start your Metatrader the EA has to find out if there is a trade open 

I do only the loop counting down for checking trades if there's a trade

If I set it at the beginning on one and OrdersTotal() >0  then I make it checking trades if(.......>      || .......>     ){do the loop.... 

are you sure u gave me the code that gave u the results shown on above? i tested it on 1440 (1 DAY ) period and no trades were executed. however when i change it to 1M many trades were executed
 
cyxstudio:
are you sure u gave me the code that gave u the results shown on above? i tested it on 1440 (1 DAY ) period and no trades were executed. however when i change it to 1M many trades were executed
how many days back goes your data if you check my test again you will find the period of the test and the timeframe tested on
 

OK here goes.....I will attempt to help here if I can.

This Ma_Shift question is one that I had for sometime and was never able to get a clear answer on.

If you will notice in your code you are using a shift of 8 on your Moving averages.... what does this mean? 

MA200 = iMA(NULL, 0, 200, 8,MODE_SMA,PRICE_CLOSE, 0);
MA5 = iMA(NULL, 0, 5, 8,MODE_SMA,PRICE_CLOSE, 0);
CurrentRSI = iRSI (NULL, 0, VarPeriod,PRICE_CLOSE ,0);
As you can see this shift settting does not exist on the RSI ... it displays in it's own window.. that's a clue.
If you drop a moving average on your chart you will see what equates to the Ma_Shift as a setting in the Shift box.
Also notice the order of the parameters 200,8,sma,close. are the same when you call the indicator
as the order they are listed in the box...the NULL and timeframe are whatever you drop the Ma on
so they are not needed in here. nor is the last shift setting... as this ma will constantly be changing on the 
current candle....you will understand this in a moment.
if you go and look at the iAlligator indicator settings you will see settings for jaw shift, teeth shift, and lips shift... this is the MaShift of each of those Moving averages.
they can all be shifted on the chart to the left or right however many bars you want.

which displays like this............

This makes a 3 pip difference in the value on this 08:00 candle as shown here in the data window.
 

Which brings us to the question; What is the "Shift" setting at the end for?

Well as you mouse over your chart with the data window open and move from candle to candle

you will see the numbers change for the 5 SMA as you go from candle to candle... 

That is what that last SHIFT value is about... keeping in mind that the current candle that is being

drawn is candle zero... the last completed candle is candle 1 so if there are 1000 total candles on

your chart they are numbered backwards from 999 on the left edge of your chart to 0 where you

are currently.  So if you want to know what the value of the 5 SMA was 5 completed candles ago 

you put a 5 in that last spot... of course as time progresses... candle 5 will change to the next candle. 

Now as was mentioned .. if you are always geting the value of candle 0.. then that value is constanly

changing with price. So you may take a signal and then the indicator repaints on you .. but if you are

always asking for the info from candle 1 it is done and will not change....

I hope this helps... 

 
cyxstudio:

I've redone everything and fixed the loop,slippage, fixed the moving average and RSI values, made sure that every opened positions are closed before start new position. but when i backtest it, nothing happens, no buy/sell were executed... whats the problem with it again?

 



the init() function only runs at start up and not on every tick like the start() function.. you will need to put the moving averages back into the start function instead of in the init() only for it to work so that it keeps getting fresh numbers...
 

 Reworked

 Add in a feature where the EA will check if there are any pending orders before deciding to open a new position. If theres a pending or opened order then it wont attempt to open anymore.at

i see that everyone uses a loop to check if there is an open position before buying, i cant see the logic of that. as long as OrdersTotal is > 0 there are opened orders and my EA will not seek to open more positions.

 fixed the decreasing loop. 

This time it gives me OrderClose error 138 which cannot be solved by adding refreshrates() 

 and i still end up losing money which i shouldnt be.

 

i cant think of anything else to fix... 

 

//+------------------------------------------------------------------+
//|                                       RSI_strategy_cyxstudio.mq4 |
//|                                  Copyright 2013, Tjipke de Vries |
//|                                     https://forum.mql4.com/53695/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"


extern int RSIPeriod        =  3;      //number of periods for RSI
extern double UpperBound    =  90;     //set upper bound value for RSI
extern double LowerBound    =  5;      //set lower bound value for RSI
extern int MASlowPeriod     = 200;
extern int MAFastPeriod     = 5;
extern double Lots  = 0.1;
extern double StopLoss      = 60;       //Set the stop loss level
extern double TakeProfit    = 120;       //Set the take profit level
extern double TrailingStop = 40;
//extra settings for OrderSend
extern int        MagicNumber = 54333;
extern string     CommentEA = "RSI strategy";
extern int        Slippage.Pips    = 3;


int    BUYS=1,SELLS=1;
//++++ These are adjusted for 5 digit brokers.
int     pips2points;      // slippage  3 pips    3=points    30=points
double  pips2dbl;         // Stoploss 15 pips    0.015      0.0150
int     Digits.pips;      // DoubleToStr(dbl/pips2dbl, Digits.pips)
//---
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----   
   if(Digits % 2 == 1)  // DE30=1/JPY=3/EURUSD=5 forum.mql4.com/43064#515262
     {pips2dbl = Point*10; pips2points = 10;   Digits.pips = 1;}
     else {pips2dbl = Point;    pips2points =  1;   Digits.pips = 0;}
     // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl        
//----      

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   int Ticket;
   double SL,TP;
   int Total;
   double MagicNo;
   double Slippage;
   
   double pAsk = MarketInfo(Symbol(), MODE_ASK);
   double pBid = MarketInfo(Symbol(), MODE_BID);
   double MA200 = iMA(NULL, 0, MASlowPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);  //200 day Moving Average   
   double MA5 = iMA(NULL, 0, MAFastPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);      //  5 day Moving Average
   double CurrentRSI = iRSI (NULL, 1440, RSIPeriod,PRICE_CLOSE ,0);
  
   int Ticket2;
   int cnt;
   
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
   if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }


  
        
        
        if (OrdersTotal() == 0 ) {
        
        if (CurrentRSI < LowerBound && pAsk > MA200) {    //Condition to execute buy entry
  
        Ticket = OrderSend(Symbol(), OP_BUY, Lots, pAsk, 3, pBid - ( StopLoss * Point ), pAsk + ( TakeProfit * Point ), "Buy.", 111,0,Yellow)   ;       //execute buy order
   
    if(Ticket>0)
           {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("BUY order opened : ",OrderOpenPrice());
            
           }
         if (Ticket < 0) {
         Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
   }
  
  }
  
  
 
  if (CurrentRSI > UpperBound && pBid < MA200) {     //Condition to execute sell entry
  
       Ticket2 = OrderSend(Symbol(), OP_SELL, Lots, pBid, 3, pAsk + ( StopLoss * Point ), pBid - ( TakeProfit * Point ), "Sell.",000, 0, Yellow)  ;     //execute sell order
       if(Ticket2>0)
           {
            if(OrderSelect(Ticket2,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("SELL order opened : ",OrderOpenPrice());
           
           }
         if (Ticket2<0) {
          Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      
   
   } 
   }
   
   if (OrdersTotal() > 0 ) {
   
   int PositionIndex;    //  <-- this variable is the index used for the loop

int TotalNumberOfOrders;   //  <-- this variable will hold the number of orders currently in the Trade pool

TotalNumberOfOrders = OrdersTotal();    // <-- we store the number of Orders in the variable

for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)  //  <-- for loop to loop through all Orders . .   COUNT DOWN TO ZERO !
   {
   RefreshRates();
   if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) ) continue;   // <-- if the OrderSelect fails advance the loop to the next PositionIndex
   
   if( OrderMagicNumber() == MagicNo       // <-- does the Order's Magic Number match our EA's magic number ? 
      && OrderSymbol() == Symbol()         // <-- does the Order's Symbol match the Symbol our EA is working on ? 
      && ( OrderType() == OP_BUY           // <-- is the Order a Buy Order ? 
      ||   OrderType() == OP_SELL ) )      // <-- or is it a Sell Order ?
   
   if (pAsk > MA5){      //condition to close long position
   RefreshRates();
    OrderClose(OrderTicket(),OrderLots(),pBid,3,Violet); // close long position
 
   return(0); // exit
   
   if(TrailingStop>0)  
              {                 
               if(pBid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<pBid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),pBid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
   
  }
   
   if(pBid < MA5){       //condition to close short position
   RefreshRates();
   OrderClose(OrderTicket(),OrderLots(),pAsk,3,Violet); // close short position
  
   return(0); // exit
   
   
  if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-pAsk)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(pAsk+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),pAsk+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
   }
   
      if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) )               // <-- try to close the order
         Print("Order Close failed, order number: ", OrderTicket(), " Error: ", GetLastError() );  // <-- if the Order Close failed print some helpful information 
      
   } //  end of For loop
   
   
   }
  
   
   
   
   
   
        
        
           return(0);
}
 
cyxstudio:

 Reworked

 Add in a feature where the EA will check if there are any pending orders before deciding to open a new position. If theres a pending or opened order then it wont attempt to open anymore.at

i see that everyone uses a loop to check if there is an open position before buying, i cant see the logic of that. as long as OrdersTotal is > 0 there are opened orders and my EA will not seek to open more positions.

 fixed the decreasing loop. 

This time it gives me OrderClose error 138 which cannot be solved by adding refreshrates() 

 and i still end up losing money which i shouldnt be.

 

i cant think of anything else to fix... 

Why did you place the logic for opening a buy before you check the trades your EA have open on your account ???? 

 

What will happen now ????  with the programming you have so far ??? 

Assume you have an account running with your EA. You open manually a trade for GBPUSD.

 how many trades is OrdersTotal() with that trade ???

Your code....  for BUY

if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }


  
        
        
        if (OrdersTotal() == 0 ) {
        
        if (CurrentRSI < LowerBound && pAsk > MA200) {    //Condition to execute buy entry
  
        Ticket = OrderSend(Symbol(), OP_BUY, Lots, pAsk, 3, pBid - ( StopLoss * Point ), pAsk + ( TakeProfit * Point ), "Buy.", 111,0,Yellow)   ;       //execute buy order
   
    if(Ticket>0)
           {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("BUY order opened : ",OrderOpenPrice());
            
           }
         if (Ticket < 0) {
         Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
   }
  

 what is this doing   now ???   and for what reason is it doing so ???

 
deVries:

Why did you place the logic for opening a buy before you check the trades your EA have open on your account ???? 

 

What will happen now ????  with the programming you have so far ??? 

Assume you have an account running with your EA. You open manually a trade for GBPUSD.

 how many trades is OrdersTotal() with that trade ???

Your code....  for BUY

 what is this doing   now ???   and for what reason is it doing so ???


buy only if the conditions of buy has been met and if no positions has been opened
 
cyxstudio:

buy only if the conditions of buy has been met and if no positions has been opened

Assume you have an account running with your EA. You open manually a trade for GBPUSD.

will the condition be true  

 if (OrdersTotal() == 0 )
 
cyxstudio 2013.01.31 18:04

would you please let me have a look at your codes?

 i wnt to know why i failed and how to get it right. 

.

Your message to me I can give you the full code directly.....

That won't be for free.  For that you have to use  Jobs  section and pay to get it...

You will get it then there 

.

Another way is read your topics well 

We are helping you here to learn how to program it yourself.  That is free Help

We show you your errors and help you in the direction how to solve.

I show the code I have the moment you have learned a way to write it ....

 No need to pay then and you can that moment compare it with the code you made here with help of this forum

....

my last question here is still not answered 

Assume you have an account running with your EA. You open manually a trade for GBPUSD.

will the condition be true  

 if (OrdersTotal() == 0 )

.

. In other topic   OrderClose error 138 

you have been helped there very well   (RaptorUK and WHRoeder  thanks for explanation there I think very well done) 

.

Another question I have for you is

Why did you change the Timeframe in this calculating Moving Average

  

   double MA200 = iMA(NULL, 0, MASlowPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);  //200 day Moving Average   
   double MA5 = iMA(NULL, 0, MAFastPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);      //  5 day Moving Average

 This is not the same as I gave,

It is not calculating the right value on other chart Daily

.

So take time learning and practise and read carefully the help you get here on this forum

or you pay someone to program for you at a site like   Jobs 

 

 

 
deVries:
cyxstudio 2013.01.31 18:04

would you please let me have a look at your codes?

 i wnt to know why i failed and how to get it right. 

.

Your message to me I can give you the full code directly.....

That won't be for free.  For that you have to use  Jobs  section and pay to get it...

You will get it then there 

.

Another way is read your topics well 

We are helping you here to learn how to program it yourself.  That is free Help

We show you your errors and help you in the direction how to solve.

I show the code I have the moment you have learned a way to write it ....

 No need to pay then and you can that moment compare it with the code you made here with help of this forum

....

my last question here is still not answered 

Assume you have an account running with your EA. You open manually a trade for GBPUSD.

will the condition be true  

.

. In other topic   OrderClose error 138 

you have been helped there very well   (RaptorUK and WHRoeder  thanks for explanation there I think very well done) 

.

Another question I have for you is

Why did you change the Timeframe in this calculating Moving Average

  

 This is not the same as I gave,

It is not calculating the right value on other chart Daily

.

So take time learning and practise and read carefully the help you get here on this forum

or you pay someone to program for you at a site like   Jobs 

 

 

is OrdersTotal() suppose to reveal the total amount of pending orders and market orders regardless they were opened through EA or manual?

I was thinking in this way. My EA will always check if there are open orders and if there are, it wont open anymore orders and it will only open new orders when there are no open orders hence 

if (OrdersTotal() == 0 )

 I think its working fine because my results section shows me the order sequence 1,1,2,2,3,3,4,4 which means an order is closed before new order is opened.

 

the variables for moving average and RSI changed due to testing reasons. I was experimenting it on different time frame/period but didnt change it back when i post it here.

 

and the most bizarre of all , my code will ONLY execute buy order. it has never executed not even one...sell order. thats just weird,

 

in a nutshell, the problems i am still facing now.

1. it only executes buy but never execute sell despite the fact i have coded the sell 

2. still making negative profit which i am confidence this strategy isnt suppose to. 

Reason: