Implementing Fibonacci and ATR into my EA - page 2

 

I think the code you want may look like this but will need adjustment for the broker you use.

//+------------------------------------------------------------------+
//|                                            PeepingTom Sample.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

extern double Lots = 0.1;
extern int MATrendPeriod = 50 ;
extern int Magic = 20110417 ;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double FibHigh = 0.618 ;
   double FibLow = 0.25 ;
   double myLength,EntryPoint,StopLvl ;
   double SignalPrevious, MaCurrent, MaPrevious ;
   double TakeProfit,StopLoss,TP1,TP2 ;
   int cnt, ticket, total;
   bool Skip ;
   

   myLength = High[1]-Low[1] ;      
   MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   StopLvl=MarketInfo(Symbol(),MODE_STOPLEVEL) ;
   if(StopLvl==0){StopLvl=Ask-Bid+Point ;}





   total=OrdersTotal();
   if(total<1) 
     {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // check for long position (BUY) possibility
      //   LONG- previous candle close > 50-SMA. 
      //   Entry point <=61.8% Fibonacci level of previous candle.
      //   Stop loss = 25.0% Fibonacci level of previous candle. 
      //   Take profit = lesser of SL x 2 or 5-period ATR.
      EntryPoint = Low[1]+myLength*FibHigh ;
      if( (Close[1]>MaPrevious) && (Ask<=EntryPoint) )
        {
         Skip=FALSE ; //Previous Bar length too small for trade
         StopLoss=Low[1]+NormalizeDouble(myLength*FibLow,Digits) ;
         TP1 = Ask+2*NormalizeDouble(myLength*FibLow,Digits) ;
         TP2 = Ask+iATR(Symbol(),0,5,0) ;
         if (TP1<TP2) {TakeProfit=TP1;} else {TakeProfit = TP2;}
         if ( (Bid-StopLoss) <= StopLvl ) {Skip=TRUE;}
         if ( (TakeProfit-Bid) <= StopLvl ) {Skip=TRUE;}
         if (!Skip)
         {
          Print(" StopLvl ",StopLvl," StopLoss ",StopLoss," TakeProfit ",TakeProfit," Length ",myLength," Bid ",Bid," Ask ",Ask) ;
          ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,StopLoss,TakeProfit,"PeepingTom",Magic,0,Green);         
          if(ticket>0)
            {
             if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
             PlaySound("Alert.wav");
            }
          else Print("Error opening BUY order : ",GetLastError()); 
         }//if Skip
         return(0); 
        }
        
      // check for short position (SELL) possibility
      //   SHORT- previous candle close < 50-SMA. 
      //   Entry point >=25.0% Fibonacci level of previous candle. 
      //   Stop loss = 61.8% Fibonacci level of previous candle. 
      //   Take profit = lesser of SL x 2 or 5-period ATR.

      EntryPoint = Low[1]+myLength*FibLow ;
      if( (Close[1] > MaPrevious) && (Bid <= EntryPoint) )
        {
         Skip=FALSE ; //Previous Bar length too small for trade
         StopLoss=Low[1]+NormalizeDouble(myLength*FibHigh,Digits) ;
         TP1 = Bid-2*NormalizeDouble(myLength*FibHigh,Digits) ;
         TP2 = Bid-iATR(Symbol(),0,5,0) ;
         if (TP1>TP2){TakeProfit=TP1;} else {TakeProfit = TP2;}
         if ( (StopLoss-Ask) <= StopLvl ) {Skip=TRUE;}
         if ( (Ask-TakeProfit) <= StopLvl ) {Skip=TRUE;}
         if (!Skip)
         {
          Print(" StopLvl ",StopLvl," StopLoss ",StopLoss," TakeProfit ",TakeProfit," Length ",myLength," Bid ",Bid," Ask ",Ask) ;
          ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,StopLoss,TakeProfit,"PeepingTom",Magic,0,Red);
          if(ticket>0)
            {
             if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
             PlaySound("Alert.wav");
            }
          else Print("Error opening SELL order : ",GetLastError()); 
         }//if Skip
         return(0); 
        }
      return(0);
     }
   return(0);
  }
// the end.
The results on EURUSD from January 1 11 to date are interesting
 
Not half as much loss as expected? :PP
 

Wow, you work fast. I was still working on the first part lol

Yes very interesting. This system is designed to be used on the Daily chart only, it performs terribly on anything less. I am also a little puzzled because in the testing, some of the stop losses are equal to the entry prices.

I also forgot to mention one small detail. On longs if all conditions are met but the previous candle is bearish, the trade does not happen that day (same goes for the next if today was bearish as well). Vice versa for shorts. Not sure how much that would affect the results.


I did some testing over various lengths of time with different lot sizes and unfortunately it looks like this system is a dud in EA form. I dunno. If tweaked it might work. Traded manually you can expect to win 50% of trades and make 10-20% per month. Chart time is about 10 minutes per day.


P.S. If any of you want to try a free Forex strategy builder look here: http://forexsb.com -- I find it very useful

 

I was tempted to add RSI - the question was why was it ok for the first part of this year and failed later - I did apply it to the daily chart and tried optimising for MA period and length to no avail

 

Is the previous candle without any wicks? wicks would explaing the "some of the stop losses are equal to the entry prices."

edit another things is that if the first trade is stopped out another trade can be entered on the same day - that also may not be part of the rules.

 

Ok - I'm not thebrightest tool in the box - but idea behind this system is to capture profit in the 50% reverse after a a fib move of 61.7% retrace and the stoploss is needed should the retrace continue in the same direction. So lets put the StopLoss for BUY below the entry point and for SELL above the entrypoint, and now apply the additional rule of previous candle must be LONG or SHORT and we only use the candle body absolute value of Open - Close. Leave in the more than one trade in a day.

Not tested but if I am correct about how the system is suppose to work then the code should be this

//+------------------------------------------------------------------+
//|                                            PeepingTom Sample.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

extern double Lots = 0.1;
extern int MATrendPeriod = 50 ;
extern int Magic = 20110417 ;
extern int MinLen = 0 ;


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double FibHigh = 0.618 ;
   double FibLow = 0.25 ;
   double myLength,EntryPoint,StopLvl,p2d ;
   double MaPrevious ;
   double TakeProfit,StopLoss,TP1,TP2 ;
   int cnt, ticket, total;
   bool Skip, IsUp, IsDown ;
   
   if (Point == 0.00001) p2d = 0.0001;
   else {
      if (Point == 0.001) p2d = 0.01;
      else p2d = Point;
   }


   myLength = MathAbs(Open[1]-Close[1]) ;      
   MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   StopLvl=MarketInfo(Symbol(),MODE_STOPLEVEL) ;
   if(StopLvl==0){StopLvl=Ask-Bid+Point ;}
   
   //is previous candle Bullish?
   if (Open[1]<Close[1] && (MathAbs(Open[1]-Close[1]) > MinLen*p2d) ) 
      {IsUp=true ;}
   else
      {IsUp=false;}

   if (Open[1]<Close[1] && (MathAbs(Open[1]-Close[1]) > MinLen*p2d) ) 
      {IsDown=true ;}
   else
      {IsDown=false;}

   total=OrdersTotal();
   if(total<1) 
     {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // Description of system as first presented see comments for interpretation  
      // check for long position (BUY) possibility
      //   LONG- previous candle close > 50-SMA. 
      //   previous candle is Bullish
      //   Entry point <=61.8% Fibonacci level of previous candle.
      //   Stop loss = 25.0% Fibonacci level of previous candle. 
      //   Take profit = lesser of SL x 2 or 5-period ATR.
      EntryPoint = NormalizeDouble( Close[1]-myLength*FibHigh,Digits ) ; //EP is a retrace 61% from up candle
      if( (Close[1]>MaPrevious) && (Ask<=EntryPoint) && IsUp ) //Price closed above MA price retraced below and last candle was up
        {
         Skip=FALSE ; //Previous Bar length too small for trade
         StopLoss=EntryPoint-NormalizeDouble(myLength*FibLow,Digits) ; //Stop loss if price continues down
         TP1 = Ask+2*NormalizeDouble(myLength*FibLow,Digits) ; //Add 50% op previous candle to entry Price for a take profit
         TP2 = Ask+iATR(Symbol(),0,5,0) ; //Add ATR(5) to entry price 
         if (TP1<TP2) {TakeProfit=TP1;} else {TakeProfit = TP2;} //use lower profit for close 
         if ( (Bid-StopLoss) <= StopLvl ) {Skip=TRUE;} //Check stoploss is valid
         if ( (TakeProfit-Bid) <= StopLvl ) {Skip=TRUE;} //check takeprofit is valid
         if (!Skip && myLength>=MinLen*p2d) //invalid takeprofit or stoploss no trade
         {
          Print(" StopLvl ",StopLvl," StopLoss ",StopLoss," TakeProfit ",TakeProfit," Length ",myLength," Bid ",Bid," Ask ",Ask) ;
          ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,StopLoss,TakeProfit,"PeepingTom",Magic,0,Green); //Broker may not like initial trade with S/L and T/P
          if(ticket>0)
            {
             if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
             PlaySound("Alert.wav");
            }
          else Print("Error opening BUY order : ",GetLastError()); 
         }//if Skip
         return(0); 
        }
        
      // check for short position (SELL) possibility
      //   SHORT- previous candle close < 50-SMA. 
      //   previous candle is Beareish
      //   Entry point >=25.0% Fibonacci level of previous candle. 
      //   Stop loss = 61.8% Fibonacci level of previous candle. 
      //   Take profit = lesser of SL x 2 or 5-period ATR.

      EntryPoint = NormalizeDouble(Close[1]+myLength*FibHigh,Digits) ; //Price retraced up 61.7% on Bull candle
      if( (Close[1] < MaPrevious) && (Bid >= EntryPoint) && IsDown ) //Price Closed below MA, price retraced above EntryPoint and last candle was down
        {
         Skip=FALSE ; //Previous Bar length too small for trade
         StopLoss=EntryPoint+NormalizeDouble(myLength*FibLow,Digits) ; //Stop loss price if price continues up from Entry Point
         TP1 = Bid-2*NormalizeDouble(myLength*FibLow,Digits) ; // Take Profit price 50% below Entry Price 
         TP2 = Bid-iATR(Symbol(),0,5,0) ; // Take Profit price Using ATR(5)
         if (TP1>TP2){TakeProfit=TP1;} else {TakeProfit = TP2;} //The higher price is the lesser profit in a SELL
         if ( (StopLoss-Ask) <= StopLvl ) {Skip=TRUE;} // Check values are valid
         if ( (Ask-TakeProfit) <= StopLvl ) {Skip=TRUE;}
         if (!Skip && myLength>=MinLen*p2d)
         {
          Print(" StopLvl ",StopLvl," StopLoss ",StopLoss," TakeProfit ",TakeProfit," Length ",myLength," Bid ",Bid," Ask ",Ask) ;
          ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,StopLoss,TakeProfit,"PeepingTom",Magic,0,Red);
          if(ticket>0)
            {
             if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
             PlaySound("Alert.wav");
            }
          else Print("Error opening SELL order : ",GetLastError()); 
         }//if Skip
         return(0); 
        }
      return(0);
     }
   return(0);
  }
// the end.

edit - tested - results even worse.

 

I feel like something isn't right here (edit: I see you used 50% fibo of previous for TP, which is incorrect)......I am new at this so it is probably best I describe how it works visually.....please excuse messy writing....I used my mouse :D

This is a hypothetical example I just pulled from the charts at random....yes I know today is not April 9 (:

Anyway, it's pretty self-explanatory but only <= one trade per day is allowed. You use a Fibonacci drawn on the previous candle to find entry and SL only, not TP. And we are going by wicks, not bodies.

Here, only longs are taken because the candles are above the 50 SMA. If the candles were below the SMA then only short trades would be taken.

The TP would ordinarily be 2x SL, which is 60 pips. But since the ATR is only 107, which is less than 120 (SL x 2), we use that as the TP instead.

As you can see, the price for "today" did not reach our BUY entry, so a trade would not have been taken. Zero trades today.

Had we hit our buy and entered the trade, we would've also hit our TP in the same day......107+ pips! The system is checked once per 24 hours; if we come back and in profit but not yet target we may go ahead and take profit or examine other indicators to decide to wait. Same goes if we are in negative but not yet stopped. Otherwise, we do not move any stops or targets whatsoever. For this example, in subsequent days the candles are bearish and since they are bearish in a "long zone" then we do not use them and do not trade those days.

 

SL is 25% of candle length Take profit is 2*SL or smaller if ATR is smaller therfore takeproft is max 50% of previous candle length! or am I missing something?

No problem to changing it to one trade per day.

I am sure I stated correctly the system works on putting in trades at the end of a retracement before continuing on in the same direction.

What I seem to be having a little dificulty with in working out is the Entrypoint, is it worked out from the top of the candle or the bottom?

However I can't see these changes making much difference to the results.

I did this because I had mapped out how to do it by editing the MACD sample and then thinking I understood the conditions edited the if statements

added a check for validity of order and then gave it a quick test to see how it went. The momentary blip of it working at the begining of 2011

held my interest in it but I think I have played around with it enough now to see the blip came from a dip and retrace were the cause of the momentary profitibility.

 

Sorry for the confusion. I am thinking in terms of pips....is it setting the TP at the 50% candle price (which won't work) or setting the TP at 50% number of pips in the entire candle?

Entry on long is technically the bottom of today; vice versa for shorts. In reality you can buy at even lower and keep the same SL, thus the <= statement earlier.

Anyway, I've come to the conclusion that it is best traded manually with trader discretion.

P.S. Your code says "MODE_EMA" on iMA. Again, I am new at MQL but this is a SMA...shouldn't it be "MODE_SMA"?

Edit : Hmmm....it seems like the many of losses can be attributed to placing new orders after getting stopped out. Because the winners are bigger than the losers but the losers are more frequent.

Edit 2: Wow, I made one trade a daily only--- results surprised me.

 

I can't get this forum to paste code correctly but try the attached EA. I revised MODE_EMA to MODE_SMA and updated the EA to include "One Trade Per Day" rule.

I tried it from 01-01-2009 to present day, lot setting 1.00

Results were MUCH BETTER than previously. Not the greatest but improved....

Start balance: $10,000

End balance was $12869.00

Worst loser: -$525.00

Best winner: $1020.00

Keep in mind this is using fixed position sizing. I wonder if ratio sizing would work better.

Also have only tried EUR/USD, so I wonder if other currencies are better.

Edit:

Tried it from 01-01-2010 to present day, same settings.

Less impressive results.

End balance was $9895.00

Worst loser: -$310.00

Best winner: $582.00

Similar result from 01-01-2011 to present day.

Seems to work best long term. Drawdown is surprisingly low-- less than 10%

Conclusion: Still doesn't generate enough profit to consider.

Files:
Reason: