Download MetaTrader 5

Conversion from Indicator to EA not working

To add comments, please log in or register
Robin
27
Robin  

Hi,

I have taken an existing indicator and used it to make an EA. I use the indicator on the chart and load the EA separately. It compiles perfectly and loads fine, but it does not work. It is based on a turtle indicator.

Can someone show me where I have gone wrong please. Thanks in advance.

This is the indicator.

//+------------------------------------------------------------------+
//| TheTurtleTradingChannel.mq4
//| Copyright © Pointzero-indicator.com
//+------------------------------------------------------------------+
#property copyright "Copyright © Pointzero-indicator.com"
#property link      "http://www.pointzero-indicator.com"

//---- indicator settings
#property indicator_chart_window
#property indicator_buffers 6
#property indicator_color1 MediumSeaGreen
#property indicator_color2 OrangeRed
#property indicator_color3 clrNONE
#property indicator_color4 clrNONE
#property indicator_color5 MediumSeaGreen
#property indicator_color6 OrangeRed
#property indicator_width1 2
#property indicator_width2 2
#property indicator_width3 1
#property indicator_width4 1
#property indicator_width5 2
#property indicator_width6 2
#property indicator_style3 STYLE_DOT
#property indicator_style4 STYLE_DOT
#property indicator_style5 STYLE_DOT
#property indicator_style6 STYLE_DOT

//---- indicator parameters
extern int  TradePeriod         = 14;     // Donchian channel period for trading signals // updated from 18
extern int  StopPeriod          = 5;     // Donchian channel period for exit signals
extern bool Strict              = false;  // Apply strict entry parameters like the Turtles did
extern bool DisplayAlerts       = false;  // You know...

//---- indicator buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
double ExtMapBuffer5[];
double ExtMapBuffer6[];
double TrendDirection[];

//---- internal
static datetime TimeStamp;
static int AlertCount = 3;
datetime TIME;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
   // One more invisible buffer to store trend direction
   IndicatorBuffers(7);
   
   // Drawing settings
   SetIndexStyle(0,DRAW_LINE);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexStyle(2,DRAW_LINE);
   SetIndexStyle(3,DRAW_LINE);
   SetIndexStyle(4,DRAW_ARROW); SetIndexArrow(4,233);
   SetIndexStyle(5,DRAW_ARROW); SetIndexArrow(5,234);
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
   
   // Name and labels
   IndicatorShortName("Turtle Channel ("+ TradePeriod +"-"+ StopPeriod +")");
   SetIndexLabel(0,"Upper line");
   SetIndexLabel(1,"Lower line");
   SetIndexLabel(2,"Longs Stop line");
   SetIndexLabel(3,"Shorts Stop line");
   //SetIndexBuffer(4, "Bullish trend");
   //SetIndexBuffer(5, "Bearish trend");
   
   // Buffers
   SetIndexBuffer(0,ExtMapBuffer1);
   SetIndexBuffer(1,ExtMapBuffer2);
   SetIndexBuffer(2,ExtMapBuffer3);    // Stop level for longs
   SetIndexBuffer(3,ExtMapBuffer4);    // Stop level for shorts
   SetIndexBuffer(4,ExtMapBuffer5);
   SetIndexBuffer(5,ExtMapBuffer6);
   SetIndexBuffer(6,TrendDirection);
   
 
   return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
     // More vars here too...
     int start = 0;
     int limit;
     int counted_bars = IndicatorCounted();

     // check for possible errors
     if(counted_bars < 0) 
        return(-1);
        
     // Only check these
     limit = Bars - 1 - counted_bars;
     if(counted_bars==0) limit-=1+1;
     
     // Check the signal foreach bar
     for(int i = limit; i >= start; i--)
     {           
         // Highs and lows
         double rhigh = iHigh(Symbol(),Period(),iHighest(Symbol(), Period(), MODE_HIGH, TradePeriod,i+1));
         double rlow  = iLow(Symbol(),Period(),iLowest(Symbol(), Period(), MODE_LOW, TradePeriod, i+1));
         double shigh = iHigh(Symbol(),Period(),iHighest(Symbol(), Period(), MODE_HIGH, StopPeriod,i+1));
         double slow  = iLow(Symbol(),Period(),iLowest(Symbol(), Period(), MODE_LOW, StopPeriod, i+1));
         
         // Candle value
         double CLOSE = iClose(Symbol(),0, i);
         double HIGH = iHigh(Symbol(),0, i);
         double LOW = iLow(Symbol(),0, i);
         
         // Default behavior is to preserve the trend
         TrendDirection[i] = TrendDirection[i+1];
         
         // It might be recalculating bar zero
         ExtMapBuffer1[i] = EMPTY_VALUE;
         ExtMapBuffer2[i] = EMPTY_VALUE;
         ExtMapBuffer3[i] = EMPTY_VALUE;
         ExtMapBuffer4[i] = EMPTY_VALUE;
         ExtMapBuffer5[i] = EMPTY_VALUE;
         ExtMapBuffer6[i] = EMPTY_VALUE;
         
         // Change to uptrend
         if(((CLOSE > rhigh && i > 0) || (HIGH > rhigh && Strict == true)) && TrendDirection[i+1] != OP_BUY)
         {
            TrendDirection[i] = OP_BUY;
            ExtMapBuffer5[i] = rlow;
            ExtMapBuffer5[i] = iLow(Symbol(),0,i)-(5*Point); // Arrow to buy
            Alert("Turtle Trading "+ TradePeriod +" "+TIME+" "+ Symbol() +" BUY"); // Alert to buy
         
         // Change to downtrend
         } else if(((CLOSE < rlow && i > 0) || (LOW < rlow && Strict == true)) && TrendDirection[i+1] != OP_SELL) {
            
            TrendDirection[i] = OP_SELL;
            ExtMapBuffer6[i] = rhigh;
            ExtMapBuffer6[i] = iHigh(Symbol(),0,i)+(5*Point); // Arrow to sell
            Alert("Turtle Trading "+ TradePeriod +" "+TIME+" "+ Symbol() +" SELL"); // Alert to sell
         }
         
         
         // Draw lines
         if(TrendDirection[i] == OP_BUY)
         {
            ExtMapBuffer1[i] = rlow;
            ExtMapBuffer3[i] = slow;
            
         // Draw lines
         } else if(TrendDirection[i] == OP_SELL) {
         
            ExtMapBuffer2[i] = rhigh;
            ExtMapBuffer4[i] = shigh;
         }
     }
     /*
     // Alert
     if(TimeStamp != Time[0] && DisplayAlerts == true)
     {
         if(TrendDirection[1] == OP_SELL && TrendDirection[2] == OP_BUY && AlertCount == 0)
         {
            Alert("[Turtle Trading "+ TradePeriod +"-"+ StopPeriod +"]["+ Symbol() +"] SELL");
            
         } else if (TrendDirection[1] == OP_BUY && TrendDirection[2] == OP_SELL && AlertCount == 0)
         {
            Alert("[Turtle Trading "+ TradePeriod +"-"+ StopPeriod +"]["+ Symbol() +"] BUY");
         }
         
         
         TimeStamp = Time[0];
         AlertCount = 0;
     }
    */
    

   return(0);
}

This is the EA based on the indicator above. I have also added some other Buy / Sell instructions. My main problem is getting the EA to Open a trade when the arrow and Alert on the indicator appears. See comments

Robin
27
Robin  

No way to edit this post?

Here is the rest.

//+------------------------------------------------------------------+
//|                                            Expert     Turtle.mq4 |
//|                     Copyright © 2012, Marketcalls (Rajandran R). |
//|                                        http://www.marketcalls.in |
//+------------------------------------------------------------------+

//---- indicator settings
extern int  TradePeriod         = 14;     // Donchian channel period for trading signals
extern int  StopPeriod          = 5;     // Donchian channel period for exit signals
extern bool Strict              = false;  // Apply strict entry parameters like the Turtles did
extern bool DisplayAlerts       = false;  // You know...

//---- indicator buffers
double TrendDirection[];
double ExtMapBuffer5[];
double ExtMapBuffer6[];
double BUY,buy;
double SELL,sell;
double TrailingBuy,TBuy;
double TrailingSell,TSell;

//---- internal
static datetime TimeStamp;
static int AlertCount = 3;

//---- Expert input
extern int Slippage = 3;
extern double SL = 50; // StopLoss 50 pips | Used in calculation to set Lot amount traded - as  pips for spread
extern double TP = 300; // TakeProfit 300 pips
extern double TS = 70; // Trailing stop 70 pips
extern double Level = 2; // pips above Bid / Ask price to start Trailing stop
extern double MinLot = 0.01; // minimal lot for trading, if calculated lot is less than minimal (it depends on the equity)
extern int MagicNumber = 777; // This is magic number for the expert | Magic number must be Unique for each currency
extern int Digits2Round = 1;  // Floating point rounding
extern int PercentOfFreeDepo = 1; // Risk Percent of balance | Used in calculation to set Lot amount traded

   //===================Lets determine digits =======================================
   
int GetDigits()
{
   if(Digits == 5 || Digits == 3)
   {
     return(10);
   }
   else
   {
     return(1);
   }
}

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{


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

double L=iLow(NULL,NULL,1); 
double H=iHigh(NULL,NULL,1);
double C=iClose(NULL,NULL,0);
double O=iOpen(NULL,NULL,0);
double Spread=MarketInfo(Symbol(),MODE_SPREAD)*Point;
double FreeDepo=NormalizeDouble(AccountBalance()-AccountMargin(),Digits2Round);
double Risk=NormalizeDouble((FreeDepo*PercentOfFreeDepo/100),Digits2Round);
double Lot=NormalizeDouble(Risk/(SL/0.0001)*0.1,Digits2Round);
double Expire = iTime(Symbol(),PERIOD_H1,0)+900; //  15 min
double point = MarketInfo(Symbol(),MODE_POINT);
double digits = MarketInfo(Symbol(),MODE_DIGITS);
int  ask;
int bid;
datetime time;
double ticket;

int d = GetDigits();

   //===================== Lets determine lot size and risk ===================================
if ( Lot < MinLot )
    {
      Lot=MinLot;
    }
  
 //---- Comment
 Comment( "\n","Acceptable risk is ",PercentOfFreeDepo, "% = ",Risk," of the free money ",FreeDepo," in lots = ",Lot,
        "\n"," ", "SL ", SL,
        "\n"," ", "TP ", TP,
        "\n"," ", "TS ", TS);

 
   //======================= condition for ORDER BUY and SELL ===============================
    
 //---- Start Turtle    
for (int i = 0; i >= 0; i--)
     {           
         // Highs and lows
         double rhigh = iHigh(Symbol(),Period(),iHighest(Symbol(), Period(), MODE_HIGH, TradePeriod,i+1));
         double rlow  = iLow(Symbol(),Period(),iLowest(Symbol(), Period(), MODE_LOW, TradePeriod, i+1));
         double shigh = iHigh(Symbol(),Period(),iHighest(Symbol(), Period(), MODE_HIGH, StopPeriod,i+1));
         double slow  = iLow(Symbol(),Period(),iLowest(Symbol(), Period(), MODE_LOW, StopPeriod, i+1));
         
         // Candle value
         double CLOSE = iClose(Symbol(),0, i);
         double HIGH = iHigh(Symbol(),0, i);
         double LOW = iLow(Symbol(),0, i);
         
         // Default behavior is to preserve the trend
         TrendDirection[i] = TrendDirection[i+1];

         // Change to uptrend
         if(((CLOSE > rhigh && i > 0) || (HIGH > rhigh && Strict == true)) && TrendDirection[i+1] != OP_BUY)
         {           
            buy = BUY;          
         } 
            else Comment("\n","Buy Error ",GetLastError(),"  "); 
              
         
         // Change to downtrend
         if(((CLOSE < rlow && i > 0) || (LOW < rlow && Strict == true)) && TrendDirection[i+1] != OP_SELL)
         {            
            sell = SELL;                   
         }
            else Comment("\n","Sell Error ",GetLastError(),"  ");
         
     }   

   //====================== Close current order when I get a new signal ====================
   
//---- Check for open orders
 if (OrderSelect(1, SELECT_BY_POS) == true)
      if (MagicNumber == OrderMagicNumber() && Symbol() == OrderSymbol())
      {
                      if (OrderType() == OP_SELL){
                            if (BUY == true){
                            ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,clrNONE); // This should trigger a OP_SELL 
                            }                          
                            }
                            
      
                      if (OrderType() == OP_BUY){
                             if (SELL == true){
                             ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,clrNONE); // This should trigger a OP_BUY   
                              }
                              }                          
                           
      }
            else Comment("\n","Close Error ",GetLastError(),"  ");


   //======================= condition for ORDER BUY ===============================
 
if (OrdersTotal() < 2)
{
      if(BUY == true)     
        {
          ticket=OrderSend(Symbol(),OP_BUY,Lot,Ask,Slippage,(Point*SL)*10,(Point*TP*d),NULL,MagicNumber,0,Green);
        }  
     else Comment("\n","Buy Order Error ",GetLastError(),"  ");
   //========================= condition for ORDER SELL ==================== 
         
      if (SELL == true)
        {   
          ticket=OrderSend(Symbol(),OP_SELL,Lot,Bid,Slippage,(Point*SL)*10,(Point*TP*d),NULL,MagicNumber,0,Red);
        }           
        else Comment("\n","Sell Order Error ",GetLastError()," " ,(Point*SL*d) );
} 
     
 
     
   //============================== Start Trailing Stop =============================================

//---- Check for open orders

   if (OrderSelect(1, SELECT_BY_POS) == true)
      if (MagicNumber == OrderMagicNumber() && Symbol() == OrderSymbol())
      {
      // Trailing stop
            if (OrderType() == OP_BUY)
               if (Ask > OrderOpenPrice() + (Level*Point*d))
                 ticket=OrderModify(OrderTicket(),OrderOpenPrice(),(Point*TS*d),OrderTakeProfit(),0,clrNONE);
                 TrailingBuy = TBuy;
                 
            if (OrderType() == OP_SELL)
               if (Bid < OrderOpenPrice() - (Level*Point*d))
                 ticket=OrderModify(OrderTicket(),OrderOpenPrice(),(Point*TS*d),OrderTakeProfit(),0,clrNONE); 
                 TrailingSell = TSell;
                 
             // Trailing label
               while(true)
               {
                  RefreshRates();
                  time = iTime(Symbol(),0,0);
                  ask = MarketInfo(Symbol(),MODE_ASK);
                  bid = MarketInfo(Symbol(),MODE_BID);
                }
            
               if (TBuy == true)
               {
                  ObjectDelete("SL-");
                  ObjectCreate("SL-",OBJ_ARROW,0,time,ask-(Point*TS*d),0,0,0,0);              
                  ObjectSet   ("SL-",OBJPROP_ARROWCODE,4);
                  ObjectSet   ("SL-",OBJPROP_COLOR, Red);
               }
               if (TSell == true)
               {
                  ObjectDelete("SL+");
                  ObjectCreate("SL+",OBJ_ARROW,0,time,bid+(Point*TS*d),0,0,0,0);                     
                  ObjectSet   ("SL+",OBJPROP_ARROWCODE,4);
                  ObjectSet   ("SL+",OBJPROP_COLOR, Green);
               }         
                                                           
       }
      else Comment("\n","Trailing Error ",GetLastError(),"  ");

  
//---                         
   
    return(0);  
}
                   
//+------------------------------------------------------------------+

Any help will be appreciated, Thanks.

Robin
27
Robin  

Here are the files.

Robin
27
Robin  
and the indicator
qjol
3243
qjol  
why rewrite the indicator into the EA (it's not that simple copy paste) use iCustom
Robin
27
Robin  
qjol:
why rewrite the indicator into the EA (it's not that simple copy paste) use iCustom

Not much help, but thanks anyway.
SYED NAUFAL GADDAFI
1401
SYED NAUFAL GADDAFI  
61463:

Not much help, but thanks anyway.

qjol said is true and yet you say that he is giving you less than expected help?

What he said already covers the most important basic of knowledge.

Robin
27
Robin  
deysmacro:

qjol said is true and yet you say that he is giving you less than expected help?

What he said already covers the most important basic of knowledge.




I don't understand his comment. So it is not much help for me. Yours is less help. I am not a programmer. I am a trader. I have converted a few indicators into EA's, I just cant see where I am going wrong here. I can assure you that posting here is my last resort.
SYED NAUFAL GADDAFI
1401
SYED NAUFAL GADDAFI  

Then ask for professional job. Never ask here when you expect us to help you for free.

Go to >>> https://www.mql5.com/en/job

Robin
27
Robin  
deysmacro:

Then ask for professional job. Never ask here when you expect us to help you for free.

Go to >>> https://www.mql5.com/en/job


Are you looking for work?
Alain Verleyen
Moderator
31203
Alain Verleyen  
61463:

Are you looking for work?

It's simply misunderstanding.

We help for free on this forum, but in general people don't code for free at your place, however it can happen.

About your question, it's better to use the function iCustom() which is intended to call an indicator and return the value from its buffers, so you can use these values in your EA. See this topic : Detailed explanation of iCustom - MQL4 forum

12
To add comments, please log in or register