Help with inserting indicator into EA

 

Hello I have an indicator and am trying to get it to work in my Ea.

1st I tried to use I custom no buffer values then I inserted it into my Ea and nothing.

Need some help thanks. Here is part of my code.

//+------------------------------------------------------------------+
//|                                                 RAYS-Step_Ma.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
#include <stderror.mqh> 

#define  MagicNumber  155533

extern double Lots            = 0.1;
extern double MaximumRisk     = 0.1;
extern double DecreaseFactor  = 0.02;
extern    int ProfitTarget    = 100; 
extern    int     StopLoss    = 100; 
extern    int     Slippage    = 3;
//+------------------------------------------------------------------+ // here are the  step ma ind inputs and arrays
extern int EMAPeriod = 30;  
extern int ERangePeriod = 14;
extern int ERangeWindow = 8;            // Must be less then ERangePeriod, think of it as custom TF
extern string AppliedPriceText1 = "Close: 0, Open: 1, High: 2, Low: 3";
extern string AppliedPriceText2 = "Median: 4, Typical: 5, Weighted: 6";
extern int AppliedPrice = 4;
extern int PriceShift = 0;
extern int MaxBars = 4000;
//+------------------------------------------------------------------+
double UpBuffer[];
double DwBuffer[];
double Price[];
double ERange[];
double EmaAlpha = 0.0;
double ERangeAlpha = 0.0;
double indUp , indDw;
//+------------------------------------------------------------------+

 datetime CurrTime;
 datetime PrevTime;
 double   SymPoints,SymDigits;
 double   Profit, lot;
 string   Sym;
 int      TimeFrame;   
 bool     UseCompletedBars;  

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
 //----
         Sym = Symbol();
   TimeFrame = Period();   
   SymPoints = MarketInfo( Sym, MODE_POINT  );
   SymDigits = MarketInfo( Sym, MODE_DIGITS );

 //---
        if( SymPoints == 0.001   ) { SymPoints = 0.01;   SymDigits = 3; }
   else if( SymPoints == 0.00001 ) { SymPoints = 0.0001; SymDigits = 5; }

 //----         
        EmaAlpha = 2.0/(EMAPeriod + 1.0);
        ERangeAlpha = 2.0/(ERangePeriod + 1.0);
 //----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
  
  int deinit() {  return(0); }
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+

 int start()
  {
 //------

/*        int RealTime = 0;
     if( UseCompletedBars )
     {
         CurrTime = iTime(Sym, TimeFrame, 1 );
         if( CurrTime == PrevTime )  { return(0); }
         
 //------- Update Vars
         PrevTime = CurrTime;
         RealTime = 1;
*/
     indUp = 0.0 ; indDw = 0.0;
            Step_Ma();
        
     int f_New_Time,NewBar;
     bool f_New_Bar = false;
     static datetime New_Time;
     
    if (New_Time!=Time[0])
    {
      New_Time = Time[0]; 
      f_New_Bar=true;
    }        
   if (f_New_Bar==true){

      LotsOptimized();
                     
 //------- Need to check for a new Signal?
      if( CountAll( Sym, MagicNumber) == 0)
      {  
//   if ( UpBuffer[i]!= EMPTY_VALUE ) { ind1 = 2; }
//   if ( DwBuffer[i]!= EMPTY_VALUE ) { ind2 = 2; }

//         double ind1 = iCustom(NULL,0,"Step_EMA_LK",EMAPeriod ,ERangeWindow ,AppliedPrice,0,0+RealTime); // I tryed iCustom
//         double ind2 = iCustom(NULL,0,"Step_EMA_LK",EMAPeriod ,ERangeWindow ,AppliedPrice,1,0+RealTime);
 
    Print( "     Rays Step Ema      indUp = ",indUp,"     indDw = ",indDw );

              if( indUp > 0.0 ) { EnterLong(Sym, Lots, "");}
         else if( indDw > 0.0 ) { EnterShrt(Sym, Lots, "");}
      }
 //----
   
 //----
    }
  return(0); 
 }

//+------------------------------------------------------------------+
//| Expert Custom Functions                                          |
//+------------------------------------------------------------------+

  void Step_Ma() {
         
        int j = 0;
        int i = IndicatorCounted(); // I believe the problem is around here dont know how to fix
        if(i < 0) return(-1);
        i = Bars - i;

        if(i > MaxBars) {
                i = MaxBars;
                ArrayInitialize(UpBuffer, EMPTY_VALUE);
                ArrayInitialize(DwBuffer, EMPTY_VALUE);
                ArrayInitialize(ERange, High[i]-Low[i]);
        }
        j = i;
        while(j >= 0) {
        Price[j] = iMA(NULL, 0, 1, 0, 0, AppliedPrice, j+PriceShift);
                j--;
        }       
        while(i >= 0) {
  
   if ( UpBuffer[i]!= EMPTY_VALUE ) {  indUp = UpBuffer[i]; Print( "    WindowExpertName() ",WindowExpertName(),"     UpBuffer     = ",UpBuffer[i]); }
   if ( DwBuffer[i]!= EMPTY_VALUE ) {  indDw = DwBuffer[i]; Print( "    WindowExpertName() ",WindowExpertName(),"     DwBuffer     = ",DwBuffer[i]); }
  
//       Print( "       WindowExpertName() ",WindowExpertName(),"    UpBuffer    = ",UpBuffer[i],"  DwBuffer   = ",DwBuffer[i] );   
         
                double Range    = 0.0;
                double StepSize = 0.0;
                double SEma     = 0.0;
                double OldSEma  = 0.0;
                
                Range = High[ArrayMaximum(High, ERangeWindow, i+PriceShift+1)] - Low[ArrayMinimum(Low, ERangeWindow, i+PriceShift+1)];
                ERange[i] = (1.0-ERangeAlpha)*ERange[i+1] + ERangeAlpha*Range;
                StepSize  = ERange[i];
                
                if(UpBuffer[i+1] != EMPTY_VALUE) SEma = (1.0-EmaAlpha)*UpBuffer[i+1] + EmaAlpha*Price[i];
                if(DwBuffer[i+1] != EMPTY_VALUE) SEma = (1.0-EmaAlpha)*DwBuffer[i+1] + EmaAlpha*Price[i];
                if(SEma == 0.0) SEma = Price[i];
                
                if(SEma < Price[i]-StepSize) SEma = Price[i]-StepSize;
                if(SEma > Price[i]+StepSize) SEma = Price[i]+StepSize;
                
                if(UpBuffer[i+1] == EMPTY_VALUE) OldSEma = DwBuffer[i+1];
                else OldSEma = UpBuffer[i+1];
                
                if(SEma > OldSEma) {
                        UpBuffer[i] = SEma;
                        DwBuffer[i] = EMPTY_VALUE;
                        if(UpBuffer[i+1] == EMPTY_VALUE) UpBuffer[i+1] = OldSEma;
                }
                else {
                        DwBuffer[i] = SEma;
                        UpBuffer[i] = EMPTY_VALUE;
                        if(DwBuffer[i+1] == EMPTY_VALUE) DwBuffer[i+1] = OldSEma;
                }
                i--;
        }       
        return(0);
 }
 

Here is the other part of code.

//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
 
  double LotsOptimized()
   {
          lot    = Lots;
   int    orders = HistoryTotal();     // history orders total
   int    losses = 0;                  // number of losses orders without a break

//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break

   if(DecreaseFactor>0)
      {
      for(int i=orders-1;i>=0;i--)
        {
       if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
       if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;      
//---------------
       if(OrderProfit()>0) break;
       if(OrderProfit()<0) losses++;
        }      
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
      }
        
//------------------ return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
   }

//+------------------------------------------------------------------+
//       CountAll()      
//+------------------------------------------------------------------+
int CountAll( string Symbole, int Magic )
 {
    //---- 
    int count = 0;
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if ( OrderMagicNumber() != Magic   ) continue;
        if (      OrderSymbol() != Symbole ) continue;
        
             if ( OrderType() == OP_BUY  ) { count++; }
        else if ( OrderType() == OP_SELL ) { count++; }
    }
    //----
    return(count);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Calculate Stop Long                                              |
//+------------------------------------------------------------------+
double StopLong(double price,double stop,double point,double SymDgts )
{
 if(stop==0) { return(0); }
 else        { return(NormalizeDouble( price-(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Calculate Stop Short                                             |
//+------------------------------------------------------------------+
double StopShrt(double price,double stop,double point,double SymDgts )
{
 if(stop==0) { return(0); }
 else        { return(NormalizeDouble( price+(stop*point),SymDgts)); }
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeLong(double price,double take,double point,double SymDgts )
{
 if(take==0) {  return(0);}
 else        {  return(NormalizeDouble( price+(take*point),SymDgts));}
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Calculate Profit Target Long                                     |
//+------------------------------------------------------------------+
double TakeShrt(double price,double take,double point,double SymDgts )
{
 if(take==0) {  return(0);}
 else        {  return(NormalizeDouble( price-(take*point),SymDgts));}
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Place Long Order                                                 |
//+------------------------------------------------------------------+
int EnterLong( string FinalSymbol, double FinalLots, string EA_Comment )
 {
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
    {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
                               
      Ticket = OrderSend( FinalSymbol, OP_BUY, FinalLots, SymAsk, 0, 0.0, 0.0, EA_Comment, MagicNumber, 0, CLR_NONE ); 
                           
      int Err=GetLastError();
      
      switch (Err) 
       {
           //---- Success
           case               ERR_NO_ERROR: OrderLoop = true; 
                                            if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                            { OrderModify( Ticket, OrderOpenPrice(), StopLong(SymBid,StopLoss, SymPoints,SymDigits), TakeLong(SymAsk,ProfitTarget,SymPoints,SymDigits), 0, CLR_NONE ); }
                                            break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
    }
   //----               
   return(Ticket);
 }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Place Shrt Order                                                 |
//+------------------------------------------------------------------+
int EnterShrt( string FinalSymbol, double FinalLots, string EA_Comment )
 {
   int Ticket = -1; int err = 0; bool OrderLoop = False; int TryCount = 0;
                     
   while( !OrderLoop )
    {
      while( IsTradeContextBusy() ) { Sleep( 10 ); }
                           
      RefreshRates();
      double SymAsk = NormalizeDouble( MarketInfo( FinalSymbol, MODE_ASK ), SymDigits );    
      double SymBid = NormalizeDouble( MarketInfo( FinalSymbol, MODE_BID ), SymDigits );
                               
      Ticket = OrderSend( FinalSymbol, OP_SELL, FinalLots, SymBid, 0,  0.0, 0.0, EA_Comment, MagicNumber, 0, CLR_NONE ); 
                           
      int Err=GetLastError();
      
      switch (Err) 
       {
           //---- Success
                 case               ERR_NO_ERROR: OrderLoop = true;
                                                  if( OrderSelect( Ticket, SELECT_BY_TICKET ) )
                                                  { OrderModify( Ticket, OrderOpenPrice(), StopShrt(SymAsk,StopLoss, SymPoints,SymDigits), TakeShrt(SymBid,ProfitTarget, SymPoints,SymDigits), 0, CLR_NONE ); }
                                                  break;
     
           //---- Retry Error     
           case            ERR_SERVER_BUSY:
           case          ERR_NO_CONNECTION:
           case          ERR_INVALID_PRICE:
           case             ERR_OFF_QUOTES:
           case            ERR_BROKER_BUSY:
           case     ERR_TRADE_CONTEXT_BUSY: TryCount++; break;
           case          ERR_PRICE_CHANGED:
           case                ERR_REQUOTE: continue;
     
           //---- Fatal known Error 
           case          ERR_INVALID_STOPS: OrderLoop = true; Print( "Invalid Stops"    ); break; 
           case   ERR_INVALID_TRADE_VOLUME: OrderLoop = true; Print( "Invalid Lots"     ); break; 
           case          ERR_MARKET_CLOSED: OrderLoop = true; Print( "Market Close"     ); break; 
           case         ERR_TRADE_DISABLED: OrderLoop = true; Print( "Trades Disabled"  ); break; 
           case       ERR_NOT_ENOUGH_MONEY: OrderLoop = true; Print( "Not Enough Money" ); break; 
           case  ERR_TRADE_TOO_MANY_ORDERS: OrderLoop = true; Print( "Too Many Orders"  ); break; 
              
           //---- Fatal Unknown Error
           case              ERR_NO_RESULT:
                                   default: OrderLoop = true; Print( "Unknown Error - " + Err ); break; 
           //----                         
       }  
       // end switch 
       if( TryCount > 10) { OrderLoop = true; }
    }
   //----               
   return(Ticket);
 }



 
 
ray2955:

Hello I have an indicator and am trying to get it to work in my Ea.

1st I tried to use I custom no buffer values then I inserted it into my Ea and nothing.

  1. You don't provide the indicator so we can't even check your iCustom call
  2. You don't provide what the indicator values are vs what you get from the iCustom call
  3. "nothing" is meaning less. There are no mind readers here. iCustom returns something. If you mean it doesn't trade why haven't you placed your print statements dumping your variables so you find out why. If you mean iCustom isn't returning what you think you should have, did you print them out? Did you check GetLastError()?
  4. We're not going to debug your code for you. (Even IF you provided the indicator and all your code.)
  5. Detailed explanation of iCustom - MQL4 forum


 

Sorry I am a beginner and Yes you were correct so went through my code and corrected the bugs.

Thanks for the link I got iCustom to work. Here is the indicator to help others.

//+------------------------------------------------------------------+
//|                                                  Step_EMA_LK.mq4 |
//|                                 Copyright © 2009, Leif Karlsson. |
//|                                        Leffemannen1973@telia.com |
//+------------------------------------------------------------------+
//| Please feel free to copy, modify and / or redistribute this      |
//| software / source code in any way you see fit.                   |
//+------------------------------------------------------------------+
//+ ********************* Shameless Ad. **************************** +
//+ * I do custom programing jobs in Java, C, X86 Assembler & MQL4 * +
//+ ***** Pleace do not hesitate to get in contact if you nead ***** +
//+ ***** something special: EA, indicator or somthing else. ******* +
//+ ****************** Leffemannen1973@telia.com ******************* +
//+ **************************************************************** +
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Leif Kalrsson"
#property link      "mailto://Leffemannen1973@telia.com"
//+------------------------------------------------------------------+
#property  indicator_chart_window
#property  indicator_buffers 2
#property  indicator_color1  Yellow
#property  indicator_color2  Red
#property  indicator_width1  1
//+------------------------------------------------------------------+
extern int EMAPeriod = 15;
extern int ERangePeriod = 12;
extern int ERangeWindow = 5;            // Must be less then ERangePeriod, think of it as custom TF
extern string AppliedPriceText1 = "Close: 0, Open: 1, High: 2, Low: 3";
extern string AppliedPriceText2 = "Median: 4, Typical: 5, Weighted: 6";
extern int AppliedPrice = 4;
extern int PriceShift = 0;
extern int MaxBars = 4000;
//+------------------------------------------------------------------+
double UpBuffer[];
double DwBuffer[];
double Price[];
double ERange[];
double EmaAlpha = 0.0;
double ERangeAlpha = 0.0;
//+------------------------------------------------------------------+
int init() {

        IndicatorDigits(Digits+1);
        
        IndicatorBuffers(4);
        
        SetIndexStyle(0, DRAW_LINE);
        SetIndexStyle(1, DRAW_LINE);
        SetIndexBuffer(0, UpBuffer);
        SetIndexBuffer(1, DwBuffer);
        SetIndexBuffer(2, Price);
        SetIndexBuffer(3, ERange);
                        
        IndicatorShortName("Step_EMA, EMAPeriod: " + EMAPeriod + ", ERangePeriod: " + ERangePeriod + " ");
        
        EmaAlpha = 2.0/(EMAPeriod + 1.0);
        ERangeAlpha = 2.0/(ERangePeriod + 1.0);
        
     Print( "   WindowExpertName() ",   WindowExpertName()) ;
        
        return(0);
}
//+------------------------------------------------------------------+
int start() {
         
        int j = 0;
        int i = IndicatorCounted();
        if(i < 0) return(-1);
        i = Bars - i;
        if(i > MaxBars) {
                i = MaxBars;
                ArrayInitialize(UpBuffer, EMPTY_VALUE);
                ArrayInitialize(DwBuffer, EMPTY_VALUE);
                ArrayInitialize(ERange, High[i]-Low[i]);
        }
        
        j = i;
        while(j >= 0) {
                Price[j] = iMA(NULL, 0, 1, 0, 0, AppliedPrice, j+PriceShift);
                j--;
        }
                
        while(i >= 0) {
        
/*     int f_New_Time,NewBar;
     bool f_New_Bar = false;
     static datetime New_Time;
     
    if (New_Time!=Time[0])
    {
      New_Time = Time[0]; 
      f_New_Bar=true;
    }        
   if (f_New_Bar==true){
   if ( UpBuffer[i]!= EMPTY_VALUE ) { Print( "  WindowExpertName() ",WindowExpertName(),"     UpBuffer     = ",UpBuffer[i]); }
   if ( DwBuffer[i]!= EMPTY_VALUE ) { Print( "  WindowExpertName() ",WindowExpertName(),"     DwBuffer     = ",DwBuffer[i]); }
  }
*/
//       Print( "       WindowExpertName() ",WindowExpertName(),"    UpBuffer    = ",UpBuffer[i],"  DwBuffer   = ",DwBuffer[i] );   

   if ( UpBuffer[i]!= EMPTY_VALUE ) { Print( "        UpBuffer     = ",UpBuffer[i]); }
   if ( DwBuffer[i]!= EMPTY_VALUE ) { Print( "        DwBuffer     = ",DwBuffer[i]); }
         
                double Range    = 0.0;
                double StepSize = 0.0;
                double SEma     = 0.0;
                double OldSEma  = 0.0;
                
                Range = High[ArrayMaximum(High, ERangeWindow, i+PriceShift+1)] - Low[ArrayMinimum(Low, ERangeWindow, i+PriceShift+1)];
                ERange[i] = (1.0-ERangeAlpha)*ERange[i+1] + ERangeAlpha*Range;
                StepSize  = ERange[i];
                
                if(UpBuffer[i+1] != EMPTY_VALUE) SEma = (1.0-EmaAlpha)*UpBuffer[i+1] + EmaAlpha*Price[i];
                if(DwBuffer[i+1] != EMPTY_VALUE) SEma = (1.0-EmaAlpha)*DwBuffer[i+1] + EmaAlpha*Price[i];
                if(SEma == 0.0) SEma = Price[i];
                
                if(SEma < Price[i]-StepSize) SEma = Price[i]-StepSize;
                if(SEma > Price[i]+StepSize) SEma = Price[i]+StepSize;
                
                if(UpBuffer[i+1] == EMPTY_VALUE) OldSEma = DwBuffer[i+1];
                else OldSEma = UpBuffer[i+1];
                
                if(SEma > OldSEma) {
                        UpBuffer[i] = SEma;
                        DwBuffer[i] = EMPTY_VALUE;
                        if(UpBuffer[i+1] == EMPTY_VALUE) UpBuffer[i+1] = OldSEma;
                }
                else {
                        DwBuffer[i] = SEma;
                        UpBuffer[i] = EMPTY_VALUE;
                        if(DwBuffer[i+1] == EMPTY_VALUE) DwBuffer[i+1] = OldSEma;
                }
                i--;
        }       
        return(0);
 }