Help me debug ... cannot load indicator 'Relative Strength Index' [4002]

 

Hello Members

I have created Custom Indicator for %b (BB,MFI &RSI) values which is working perfectly fine. Attached jpeg for the indicator chart.

PercentB custom indicator working fine

I have also create a CLASS to access this custom indicator values and when try to run it in Test EA, get "cannot load indicator 'Relative Strength Index' [4002]"

Tried to go through threads on the same issue on forum and checked values (non zero inputs) and parameter types. However I have failed to locate the issue.

Seeking Expert's help to debug what is causing this error. Relevant codes sections are attached below.

Indicator Code Sections

//+----------------------------------------------------------------------------------------------------------+
//| Define Input Parameters
//+----------------------------------------------------------------------------------------------------------+
  input group "Parameters for %BB Indicator"
  input int       BB_Period       = 21;       // Bollinger Middle Averaging Period
  input double    BB_Deviation    = 2.0;      // BB Standard Deviation
  input group "Parameters for %MFI Indicator"
  input int       MFI_Period      = 9;        // MFI Averaging Period
  input int       MFI_BBPeriod    = 40;       // MFI Bollinger Middle Averaging Period
  input double    MFI_BBDeviation = 2.0;      // MFI BB Standard Deviation
  input group "Parameters for %RSI Indicator"
  input int       RSI_Period      = 14;       // RSI Averaging Period
  input int       RSI_BBPeriod    = 50;       // RSI Bollinger Middle Averaging Period
  input double    RSI_BBDeviation = 2.1;      // MFI BB Standard Deviation
  input group "Common Parameters"
  input int                 MA_Shift      = 0;            // Horizontal Shift for BB, MFI & RSI
  input ENUM_APPLIED_PRICE  AppliedPrice  = PRICE_CLOSE;
  input ENUM_APPLIED_VOLUME AppliedVolume = VOLUME_TICK;
.....
  //+--------------------------------------------------------------------------------------------------------+
  //| Indicator Handles ...
  //+--------------------------------------------------------------------------------------------------------+
    //+------------------------------------------------------------------------------------------------------+
    //| %b BB Handles ...
    //+------------------------------------------------------------------------------------------------------+
      handle_BB = iBands(_Symbol,PERIOD_CURRENT,BB_Period,MA_Shift,BB_Deviation,AppliedPrice);
      if(handle_BB < 0)
        {
          Print(__FUNCTION__," Error create handle_BB, code ",GetLastError()); return(INIT_FAILED);
        }
    //+------------------------------------------------------------------------------------------------------+
    //| %b MFI Handles ...
    //+------------------------------------------------------------------------------------------------------+
      handle_MFI = iMFI(_Symbol,PERIOD_CURRENT,MFI_Period,AppliedVolume);
      if(handle_MFI < 0)
        {
          Print(__FUNCTION__," Error create handle_MFI, code ",GetLastError()); return(INIT_FAILED);
        }
      handle_MFI_BB = iBands(_Symbol,PERIOD_CURRENT,MFI_BBPeriod,MA_Shift,MFI_BBDeviation,handle_MFI);
      if(handle_MFI_BB < 0)
        {
          Print(__FUNCTION__," Error create handle_MFI_BB, code ",GetLastError()); return(INIT_FAILED);
        }
    //+------------------------------------------------------------------------------------------------------+
    //| %b RSI Handles ...
    //+------------------------------------------------------------------------------------------------------+
      handle_RSI = iRSI(_Symbol,PERIOD_CURRENT,RSI_Period,AppliedPrice);
      if(handle_RSI < 0)
        {
          Print(__FUNCTION__," Error create handle_RSI, code ",GetLastError()); return(INIT_FAILED);
        }
      handle_RSI_BB = iBands(_Symbol,PERIOD_CURRENT,RSI_BBPeriod,MA_Shift,RSI_BBDeviation,handle_RSI);
      if(handle_RSI_BB < 0)
        {
          Print(__FUNCTION__," Error create handle_RSI_BB, code ",GetLastError()); return(INIT_FAILED);
        }

CLASS CiPercentB Code sections

complete code added later in thread ... 

Test EA Code 

complete code added later in thread ... 

EA run time error ...

2021.05.22 16:06:56.490 Core 1 2021.05.20 23:55:00   cannot load indicator 'Relative Strength Index' [4002]

2021.05.22 16:06:56.490 Core 1 2021.05.20 23:55:00   OnInit Error create handle_RSI, code 4002

2021.05.22 16:06:56.490 Core 1 2021.05.20 23:55:00   %b BB [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b MFI [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b RSI [1] 0.00000 [2] 0.00000 [3] 0.00000

 
Anil Varma:
// why it does not allow me to declare without default value ?

Because the previous parameter has a default value.

 
William Roeder:

Because the previous parameter has a default value.

Thanks William.

any clue for cannot load indicator error 4002 !!!

 
Anil Varma:

Thanks William.

any clue for cannot load indicator error 4002 !!!

Because you can't just omit the "group" parameter in your iCustom call. They need a value.
 
Alain Verleyen:
Because you can't just omit the "group" parameter in your iCustom call. They need a value.

:) :) :) Learners keep on making silly mistakes

I have commented out the input group and this solution worked well for error 4002. THANKS A LOT FOR YOUR SHARP EYES TO NOTICE THE MISTAKES.

However still not calculating the values except first 2/3 calls.

and first time loading indicator is taking 19190 ms !!! which seems too much.

please suggest any alternate way of achieving this goal. 

2021.05.23 08:38:06.360 Core 1  Intel Xeon  E3-1245 v3 @ 3.40GHz, 32520 MB
2021.05.23 08:38:06.360 Core 1  US30: symbol to be synchronized
2021.05.23 08:38:06.360 Core 1  US30: symbol synchronized, 3720 bytes of symbol info received
2021.05.23 08:38:06.360 Core 1  US30: load 23 bytes of history data to synchronize in 0:00:00.001
2021.05.23 08:38:06.360 Core 1  US30: history synchronized from 2017.08.28 to 2021.05.21
2021.05.23 08:38:06.360 Core 1  US30,M5: history cache allocated for 101418 bars and contains 97303 bars from 2020.01.02 01:00 to 2021.04.30 23:50
2021.05.23 08:38:06.360 Core 1  US30,M5: history begins from 2020.01.02 01:00
2021.05.23 08:38:06.360 Core 1  US30,M5 (Pepperstone-Demo): every tick generating
2021.05.23 08:38:06.360 Core 1  US30,M5: testing of Experts\AKTAdvisor\Testing EAs\EATest iPercentB.ex5 from 2021.05.01 00:00 to 2021.05.21 00:00 started
2021.05.23 08:38:06.360 Core 1  program file added: \Indicators\Final Version\iFx PercentB.ex5. 20512 bytes loaded
2021.05.23 08:38:19.806 Core 1  2021.05.01 00:00:00   Function OnCalculate in iFx PercentB.mq5 took 19190.0 ms // THE FIRST LOAD IS TAKING TOO MUCH TIME !!!
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:00:00   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:00:00   %b BB [1] 0.69189 [2] 0.71057 [3] 0.81005 || %b MFI [1] 0.62898 [2] 0.80118 [3] 0.91075 || %b RSI [1] 0.64439 [2] 0.64990 [3] 0.78215
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:05:00   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:05:00   %b BB [1] 0.00000 [2] 0.69189 [3] 0.71057 || %b MFI [1] 0.00000 [2] 0.62898 [3] 0.80118 || %b RSI [1] 0.00000 [2] 0.64439 [3] 0.64990
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:10:00   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:10:00   %b BB [1] 0.00000 [2] 0.00000 [3] 0.69189 || %b MFI [1] 0.00000 [2] 0.00000 [3] 0.62898 || %b RSI [1] 0.00000 [2] 0.00000 [3] 0.64439
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:15:00   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:15:00   %b BB [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b MFI [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b RSI [1] 0.00000 [2] 0.00000 [3] 0.00000
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:20:00   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:20:00   %b BB [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b MFI [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b RSI [1] 0.00000 [2] 0.00000 [3] 0.00000
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:25:30   Function OnCalculate in iFx PercentB.mq5 took 0.0 ms
2021.05.23 08:38:19.806 Core 1  2021.05.03 01:25:30   %b BB [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b MFI [1] 0.00000 [2] 0.00000 [3] 0.00000 || %b RSI [1] 0.00000 [2] 0.00000 [3] 0.00000

all remaining calss returned as ZERO ... until 21 May 2021
 

 
Anil Varma:

:) :) :) Learners keep on making silly mistakes

I have commented out the input group and this solution worked well for error 4002. THANKS A LOT FOR YOUR SHARP EYES TO NOTICE THE MISTAKES.

However still not calculating the values except first 2/3 calls.

and first time loading indicator is taking 19190 ms !!! which seems too much.

please suggest any alternate way of achieving this goal. 

all remaining calss returned as ZERO ... until 21 May 2021
 

You will have to fix your code, which we can't see.
 
Alain Verleyen:
You will have to fix your code, which we can't see.

Thanks Alain

attached are code and Cutom indicator file. Hope this could be good enough for you to debug ...

Else I am trying to create another Indicator without using iBand, iMFI, iRSI standard indicators from MQL. Will that help ?

Complete Class Code

//+----------------------------------------------------------------------------------------------------------+
//| CLASS:        CiPercentB
//| APPLICATION:  to get values from custom indicator iFx NormBB_MFI_RSI
//+----------------------------------------------------------------------------------------------------------+
class CiPercentB
  {
private:
  //--- class variable for parameters
    string              m_Symbol;
    ENUM_TIMEFRAMES     m_TimeFrame;
    int                 m_Handle;             // Indicator handle
    string              m_IndicatorName;      // iCustom needs Custom Indicator name located in Indicator folder
  //--- "Parameters for %BB Indicator"
    int                 m_BB_Period;          // Bollinger Middle Averaging Period
    double              m_BB_Deviation;       // BB Standard Deviation
  //--- "Parameters for %MFI Indicator"
    int                 m_MFI_Period;         // MFI Averaging Period
    int                 m_MFI_BBPeriod;       // MFI Bollinger Middle Averaging Period
    double              m_MFI_BBDeviation;    // MFI BB Standard Deviation
  //---"Parameters for %RSI Indicator"
    int                 m_RSI_Period;         // RSI Averaging Period
    int                 m_RSI_BBPeriod;       // RSI Bollinger Middle Averaging Period
    double              m_RSI_BBDeviation;    // MFI BB Standard Deviation
  //---"Common Parameters"
    int                 m_MA_Shift;             // Horizontal Shift for BB, MFI & RSI
    ENUM_APPLIED_PRICE  m_AppliedPrice;
    ENUM_APPLIED_VOLUME m_AppliedVolume;

  //--- Instance of other Class(s)
    //CLog*             m_log;                // Logging

public:
  //--- Parametric Contstructor and default Destructor methods
          CiPercentB(string pSymbol,ENUM_TIMEFRAMES pTimeFrame,
                     int pBBPeriod,double pBBDeviation,
                     int pMFIPeriod,int pMFIBBPeriod,double pMFIBBDeviation,
                     int pRSIPeriod,int pRSIBBPeriod,double pRSIBBDeviation,
                     int pMAShift = 0,ENUM_APPLIED_PRICE pAppliedPrice = PRICE_CLOSE);
         ~CiPercentB(void);
    void  Init_Handle(void);
  //--- Specific methods to get values from Custome Indicator 'iFx PercentB'
    bool  Get_iPercentB(int barStart,int barCount,double &PercentB_BB[],double &PercentB_MFI[],double &PercentB_RSI[]);
    //bool  Get_iPercentB(int barStart,int barCount,double &PercentB_BB[]);
    //bool  Get_iPercentB(int barStart,int barCount,double &PercentB_MFI[]);
    //bool  Get_iPercentB(int barStart,int barCount,double &PercentB_RSI[]);
  };
//+----------------------------------------------------------------------------------------------------------+
//| METHOD:       CiPercentB()
//| APPLICATION:  'parametric constructor' method with parameters passed into the Class
//+----------------------------------------------------------------------------------------------------------+
CiPercentB::          CiPercentB(string pSymbol,ENUM_TIMEFRAMES pTimeFrame,
                                 int pBBPeriod,double pBBDeviation,
                                 int pMFIPeriod,int pMFIBBPeriod,double pMFIBBDeviation,
                                 int pRSIPeriod,int pRSIBBPeriod,double pRSIBBDeviation,
                                 int pMAShift,ENUM_APPLIED_PRICE pAppliedPrice = PRICE_CLOSE)
  {
    m_Symbol             = pSymbol;
    m_TimeFrame          = pTimeFrame;
    m_IndicatorName      = "Final Version\\iFx PercentB";
    m_BB_Period          = pBBPeriod;
    m_BB_Deviation       = pBBDeviation;
    m_MFI_Period         = pMFIPeriod;
    m_MFI_BBPeriod       = pMFIBBPeriod;
    m_MFI_BBDeviation    = pMFIBBDeviation;
    m_RSI_Period         = pRSIPeriod;
    m_RSI_BBPeriod       = pRSIBBPeriod;
    m_RSI_BBDeviation    = pRSIBBDeviation;
    m_MA_Shift           = pMAShift;
    m_AppliedPrice       = PRICE_CLOSE;
    m_AppliedVolume      = VOLUME_TICK;         // default volume type is set as VOLUME_TICK
    //m_log = CLog::GetLog();
  } // END Of CiPercentB()
//+----------------------------------------------------------------------------------------------------------+
//| METHOD:       CiPercentB()
//| APPLICATION:  default destructor method
//+----------------------------------------------------------------------------------------------------------+
CiPercentB::~CiPercentB(void)
  {
    if(m_Handle != INVALID_HANDLE)
      IndicatorRelease(m_Handle);
//---
  } // END Of ~CiPercentB()
//+----------------------------------------------------------------------------------------------------------+
//| METHOD:       Init_Handle()
//| APPLICATION:  Indicator Initialization method || to be placed in EA Method ... OnInit()
//+----------------------------------------------------------------------------------------------------------+
void CiPercentB::Init_Handle(void)
  {
  //--- Check indicator handle and recreate if INVALID_HANDLE
    if(m_Handle != INVALID_HANDLE)
      IndicatorRelease(m_Handle);
  //--- Create / ReCreate the indicator handle
    m_Handle = iCustom(m_Symbol,m_TimeFrame,m_IndicatorName,
                       m_BB_Period,m_BB_Deviation,
                       m_MFI_Period,m_MFI_BBPeriod,m_MFI_BBDeviation,
                       m_RSI_Period,m_RSI_BBPeriod,m_RSI_BBDeviation,
                       m_MA_Shift,m_AppliedPrice,m_AppliedVolume,
                       PRICE_CLOSE            // for iCustom() Handle or Applied Price Paramenter as last value
                       );
    if(m_Handle == INVALID_HANDLE)
      Print("FAILED Creating iFx PercentB indicator. Error Code ",GetLastError());
  } // END Of Init_Handle()
//+----------------------------------------------------------------------------------------------------------+
//| METHOD:       Get_iPercentB()
//| APPLICATION:  Copy Custom iNormBB_MFI_RSI indicator values to the target array
//| BUFFER:       %b BB = 0 || %b MFI = 1 || %b RSI = 2
//+----------------------------------------------------------------------------------------------------------+
bool CiPercentB::Get_iPercentB(int barStart,int barCount,double &PercentB_BB[],double &PercentB_MFI[],
                               double &PercentB_RSI[])
  {
    if(m_Handle == INVALID_HANDLE)
      Init_Handle();
  //--- Array to be filled and returned with Volume Weighted MACD values
    ArrayResize(PercentB_BB,barCount+1);
    ArrayResize(PercentB_MFI,barCount+1);
    ArrayResize(PercentB_RSI,barCount+1);
    ArraySetAsSeries(PercentB_BB,true);
    ArraySetAsSeries(PercentB_MFI,true);
    ArraySetAsSeries(PercentB_RSI,true);
  //--- Copy Buffer values from Custom Indicator "iFx VWMACD"
    ResetLastError();
    if(!CopyBuffer(m_Handle,0,barStart,barCount,PercentB_BB))       // Buffer 0 for PercentB BB
      {
        Print(__FUNCTION__,": FAILED CopyBuffer iPercentB BB Error Code ",GetLastError());
        return(false);
      }
    if(!CopyBuffer(m_Handle,1,barStart,barCount,PercentB_MFI))      // Buffer 2 for PercentB MFI
      {
        Print(__FUNCTION__,": FAILED CopyBuffer iPercentB MFI Error Code ",GetLastError());
        return(false);
      }
    if(!CopyBuffer(m_Handle,2,barStart,barCount,PercentB_RSI))      // Buffer 3 for PercentB RSI
      {
        Print(__FUNCTION__,": FAILED CopyBuffer iPercentB RSI Error Code ",GetLastError());
        return(false);
      }
  //---
    return(true);
  } // END Of Get_iPercentB() method
//+----------------------------------------------------------------------------------------------------------+

Complete EA Code

  #include "\..\Indicator\CiPercentB.mqh"
//+----------------------------------------------------------------------------------------------------------+
//| Define 'global variables' used in EA
//+----------------------------------------------------------------------------------------------------------+
  string              ea_Symbol       = _Symbol;
  ENUM_TIMEFRAMES     ea_TFM05        = PERIOD_M5;
  //--- "Parameters for %BB Indicator"
  int                 BB_Period       = 21;       // Bollinger Middle Averaging Period
  double              BB_Deviation    = 2.0;      // BB Standard Deviation
  //--- "Parameters for %MFI Indicator"
  int                 MFI_Period      = 9;       // MFI Averaging Period
  int                 MFI_BBPeriod    = 40;       // MFI Bollinger Middle Averaging Period
  double              MFI_BBDeviation = 2.0;      // MFI BB Standard Deviation
  //--- "Parameters for %RSI Indicator"
  int                 RSI_Period      = 14;       // RSI Averaging Period
  int                 RSI_BBPeriod    = 50;       // RSI Bollinger Middle Averaging Period
  double              RSI_BBDeviation = 2.1;      // MFI BB Standard Deviation
  //--- "Common Parameters for Indicator"
  int                 MA_Shift        = 0;              // Horizontal Shift for BB, MFI & RSI
  ENUM_APPLIED_PRICE  AppliedPrice    = PRICE_CLOSE;
  //ENUM_APPLIED_VOLUME AppliedVolume   = VOLUME_TICK;  // defaulted within CiPercentB Class as tick Volume
  
//+----------------------------------------------------------------------------------------------------------+
//| INCLUDE MQL5 or Custom 'CLASS' files and create instances of them
//+----------------------------------------------------------------------------------------------------------+
  CiPercentB          PercentB_M05(ea_Symbol,ea_TFM05,
                                   BB_Period,BB_Deviation,
                                   MFI_Period,MFI_BBPeriod,MFI_BBDeviation,
                                   RSI_Period,RSI_BBPeriod,RSI_BBDeviation,
                                   MA_Shift,AppliedPrice);
//+----------------------------------------------------------------------------------------------------------+
//| Expert initialization function
//+----------------------------------------------------------------------------------------------------------+
int OnInit()
  {
//---
    PercentB_M05.Init_Handle();
//---
    return(INIT_SUCCEEDED);
  }
//+----------------------------------------------------------------------------------------------------------+
//| Expert de initialization function
//+----------------------------------------------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+----------------------------------------------------------------------------------------------------------+
//| Expert tick function
//+----------------------------------------------------------------------------------------------------------+
void OnTick()
  {
    int barStart = 0, barCount = 5, index = 1;

  //---
    if(IsNewBar())    // Check every 5 minute ...
      {
        double  M05_PercentB_BB[], M05_PercentB_MFI[], M05_PercentB_RSI[];
        PercentB_M05.Get_iPercentB(barStart,barCount,M05_PercentB_BB,M05_PercentB_MFI,M05_PercentB_RSI);
        Print("%b BB [1] ",DoubleToString(M05_PercentB_BB[1],5)," [2] ",DoubleToString(M05_PercentB_BB[2],5)," [3] ",DoubleToString(M05_PercentB_BB[3],5)," || ",
              "%b MFI [1] ",DoubleToString(M05_PercentB_MFI[1],5)," [2] ",DoubleToString(M05_PercentB_MFI[2],5)," [3] ",DoubleToString(M05_PercentB_MFI[3],5)," || ",
              "%b RSI [1] ",DoubleToString(M05_PercentB_RSI[1],5)," [2] ",DoubleToString(M05_PercentB_RSI[2],5)," [3] ",DoubleToString(M05_PercentB_RSI[3],5));
      }
  } // END Of expert advisor
//+----------------------------------------------------------------------------------------------------------+
//| METHOD:       IsNewBar()
//| APPLICATION:  Check if it is a New Candle on specified instrument & Time Frame
//+----------------------------------------------------------------------------------------------------------+
bool IsNewBar(void)
{
  bool   newBar;
  static datetime dtBarCurrent  = WRONG_VALUE;
         datetime dtBarPrevious = dtBarCurrent;
  // "SERIES_LASTBAR_DATE" Open time of the last bar of the symbol - period
  dtBarCurrent = (datetime)SeriesInfoInteger(ea_Symbol,ea_TFM05,SERIES_LASTBAR_DATE);  
  if(dtBarCurrent != dtBarPrevious)  newBar = true;
  else                               newBar = false;
  //---
  return(newBar);
} // END Of IsNewBar()
//+----------------------------------------------------------------------------------------------------------+

Indicator .exe file 

Files:
 
Code Sultan #:

I'm always getting an error "cannot load indicator 'Relative Strength Index' [4302]"

Someone please help! Here is the code



You are off-topic, this thread is about error 4002. Don't do that please.
 

hi, can you help me with error 4002 please?? 

none of my indicators (MA & RSI) can be loaded and i keep getting 4002 in strategy tester. 

and here is my code:

#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
enum EXPERT_IN_STRATEGY
   {
      MA_ONLY,
      RSI_ONLY,
      MA_AND_RSI
   };
//+------------------------------------------------------------------+
//|      Input Parameters                                                            |
//+------------------------------------------------------------------+
input group "Moving Averages inputs"
sinput string sp; //--- fast MA inputs---
input int ma_fast_p = 12;
input ENUM_MA_METHOD ma_fast_method = MODE_SMA;
input ENUM_APPLIED_PRICE ma_fast_app = PRICE_CLOSE;
input ENUM_TIMEFRAMES ma_fast_tm = PERIOD_H1;
sinput string sp1; //--- slow MA inputs---
input int ma_slow_p = 32;
input ENUM_MA_METHOD ma_slow_method = MODE_SMA;
input ENUM_APPLIED_PRICE ma_slow_app = PRICE_CLOSE;
input ENUM_TIMEFRAMES ma_slow_tm = PERIOD_H1;
input group "RSI Inputs"
input ENUM_APPLIED_PRICE rsi_app = PRICE_CLOSE;
input ENUM_TIMEFRAMES rsi_tm = PERIOD_H1;
input int rsi_p;
input int overBought_rsi_level = 70;
input int overSold_rsi_level = 30;
input group "Automatic Trading Inputs"
input int TK = 100; //pip
input int SL = 30; //pip
input double lots_vol = 0.01;
sinput string sp2; //--- Select Expert In Strategy
input EXPERT_IN_STRATEGY expertInStrategy = MA_ONLY;
//+------------------------------------------------------------------+
//|        Indicators Variables                                                          |
//+------------------------------------------------------------------+
int ma_fast_handle;
double ma_fast_buffer[];
int ma_slow_handle;
double ma_slow_buffer[];
int rsi_handle;
double rsi_buffer[];
//+------------------------------------------------------------------+
//|         Global Variables                                                         |
//+------------------------------------------------------------------+
MqlRates candle[];
MqlTick tick;
CTrade trade;
CPositionInfo positionInfo;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   ma_fast_handle = iMA(_Symbol, ma_fast_tm, ma_fast_p, 0, ma_fast_method, ma_fast_app);
   ma_slow_handle = iMA(_Symbol, ma_slow_tm, ma_slow_p, 0, ma_slow_method, ma_slow_app);
   rsi_handle = iRSI(_Symbol, rsi_tm, rsi_p, rsi_app);
   if(ma_fast_handle<0 || ma_slow_handle<0 || rsi_handle<0)
     {
      Alert("init failed");
      return (INIT_FAILED);
     }
   CopyRates(_Symbol, _Period, 0, 5, candle);
   ArraySetAsSeries(candle, true);
   ChartIndicatorAdd(0, 0, ma_fast_handle);
   ChartIndicatorAdd(0, 0, ma_slow_handle);
   ChartIndicatorAdd(0, 1, rsi_handle);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   IndicatorRelease(ma_fast_handle);
   IndicatorRelease(ma_slow_handle);
   IndicatorRelease(rsi_handle);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   bool buy_in_signal = false;
   bool sell_in_signal = false;
   bool buy_out_signal = false;
   bool sell_out_signal = false;
   
   SymbolInfoTick(_Symbol,tick);
   CopyRates(_Symbol, _Period, 0, 5, candle);
   ArraySetAsSeries(candle, true);
   
   CopyBuffer(ma_fast_handle, 0, 0, 5, ma_fast_buffer);
   CopyBuffer(ma_slow_handle, 0, 0, 5, ma_slow_buffer);
   CopyBuffer(rsi_handle, 0, 0, 5, rsi_buffer);
   ArraySetAsSeries(ma_fast_buffer, true);
   ArraySetAsSeries(ma_slow_buffer, true);
   ArraySetAsSeries(rsi_buffer,true);
   
   bool ma_buy_signal = ma_fast_buffer[0]>ma_slow_buffer[0] && ma_fast_buffer[2]<ma_slow_buffer[2];
   bool ma_sell_signal = ma_fast_buffer[0]<ma_slow_buffer[0] && ma_fast_buffer[2]>ma_slow_buffer[2];
   bool rsi_buy_signal = rsi_buffer[0]<overSold_rsi_level;
   bool rsi_sell_signal = rsi_buffer[0]>overBought_rsi_level;
   
   //buy_in_signal = ma_buy_signal && rsi_buy_signal;
   //sell_in_signal = ma_sell_signal && rsi_sell_signal;
   
   if (expertInStrategy == MA_ONLY)
      {
         buy_in_signal = ma_buy_signal;
         sell_in_signal = ma_sell_signal;
      }
   else if (expertInStrategy == RSI_ONLY)
      {
         buy_in_signal = rsi_buy_signal;
         sell_in_signal = rsi_sell_signal;
      }
      else if (expertInStrategy == MA_AND_RSI)
      {
         buy_in_signal = ma_buy_signal && rsi_buy_signal;
         sell_in_signal = ma_sell_signal && rsi_sell_signal;
   
      }
   
   buy_out_signal = ma_sell_signal;
   sell_out_signal = ma_buy_signal;
   
   bool isNewCandleFormed = isNewBar();
   
   if (isNewCandleFormed)
   {
      if (PositionSelect(_Symbol) == true)
      {
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && buy_out_signal)
         {
            exitFromBuyPositions();
            drawExitSignal("Buy Exit Signal"+candle[0].time, candle[0].time, (candle[0].high+candle[0].low)/2, clrYellow);
         }
         else
          if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && sell_out_signal)
         {
            exitFromSellPositions();
            drawExitSignal("Sell Exit Signal"+candle[0].time, candle[0].time, (candle[0].high+candle[0].low)/2, clrYellow);
         }
      }
   }
   
   if (isNewCandleFormed)
   {
      if (buy_in_signal)
      {
         if (PositionSelect(_Symbol) == false)
         {
            openBuyPosition();
         }
         drawBuySignal("BuySignal"+candle[0].time, candle[0].time, candle[0].low, clrBlue);
      }
      else
      if (sell_in_signal)
      {
         if (PositionSelect(_Symbol) == false)
         {
            openSellPosition();
         }
         drawSellSignal("SellSignal"+candle[0].time, candle[0].time, candle[0].high, clrRed);
      }
   }
   
   
   
   }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|  Funtions for automatic trading                                                                |
//+------------------------------------------------------------------+
void openBuyPosition(){
    double price = NormalizeDouble(tick.ask, _Digits);
    double slPrice = price - NormalizeDouble(SL * _Point, _Digits);
    double tkPrice = price + NormalizeDouble(TK * _Point, _Digits);
    int retCode = trade.ResultRetcode();
    
    trade.Buy(lots_vol, _Symbol, price, slPrice, tkPrice);
    
    if (retCode == TRADE_RETCODE_DONE || retCode == TRADE_RETCODE_PLACED){
      Print("openBuyPosition function, buy position placed or done successfully");
    }
    //else if (retCode == TRADE_RETCODE_CANCEL){
    //  // try again
    //}
    else{
      Print("openBuyPosition function, buy position failed" + GetLastError());
      ResetLastError();
    }
}
void openSellPosition(){
    double price = NormalizeDouble(tick.bid, _Digits);
    double slPrice = price + NormalizeDouble(SL * _Point, _Digits);
    double tkPrice = price - NormalizeDouble(TK * _Point, _Digits);
    int retCode = trade.ResultRetcode();
    
    trade.Sell(lots_vol, _Symbol, price, slPrice, tkPrice);
    
    if (retCode == TRADE_RETCODE_DONE || retCode == TRADE_RETCODE_PLACED){
      Print("openSellPosition function, sell position placed or done successfully");
    }
    else{
      Print("openSellPosition function, sell position failed" + GetLastError());
      ResetLastError();
    }
}
void exitFromBuyPositions(){
   if (PositionSelect(_Symbol) == true)
      {
         for (int i=PositionsTotal()-1;i>=0;i--)
            {
               positionInfo.SelectByIndex(i);
               if (positionInfo.Symbol() == Symbol() && positionInfo.PositionType() == POSITION_TYPE_BUY)
                {
                 trade.PositionClose(positionInfo.Ticket());
                }
            }
      }
}
void exitFromSellPositions(){
   if (PositionSelect(_Symbol) == true)
      {
         for (int i=PositionsTotal()-1;i>=0;i--)
            {
               positionInfo.SelectByIndex(i);
               if (positionInfo.Symbol() == Symbol() && positionInfo.PositionType() == POSITION_TYPE_SELL)
                {
                 trade.PositionClose(positionInfo.Ticket());
                }
            }
      }
}
//+------------------------------------------------------------------+
//|  Functions for signaling and strategy visualization                                                               |
//+------------------------------------------------------------------+
void drawBuySignal(string name, datetime dt, double price, color clr=clrBlue){
   ObjectDelete(0, name);
   ObjectCreate(0, name, OBJ_ARROW_UP, 0, dt, price);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 6);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_TOP);
}
void drawSellSignal(string name, datetime dt, double price, color clr=clrRed){
   ObjectDelete(0, name);
   ObjectCreate(0, name, OBJ_ARROW_DOWN, 0, dt, price);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 6);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_BOTTOM);
}
void drawExitSignal(string name, datetime dt, double price, color clr=clrPurple){
   ObjectDelete(0, name);
   ObjectCreate(0, name, OBJ_ARROW_STOP, 0, dt, price);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_WIDTH, 6);
   ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_CENTER);
}
//+------------------------------------------------------------------+
//|  Utility functions                                                                |
//+------------------------------------------------------------------+
bool isNewBar(){
   bool newBar = false;
   static datetime last_time = 0;
   
   datetime lastBar_time= (datetime)SeriesInfoInteger(Symbol(), Period(), SERIES_LASTBAR_DATE);
   if (last_time == 0)
      {
         last_time = lastBar_time;
         newBar = false;
      }
   else if (last_time != lastBar_time)
      {
         last_time = lastBar_time;
         newBar = true;
      }
   return(newBar);
}
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • 2023.12.09
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
Files:
 
maryam mehraban #:

hi, can you help me with error 4002 please?? 

none of my indicators (MA & RSI) can be loaded and i keep getting 4002 in strategy tester. 

and here is my code:

You don't deserve help as you didn't bother to read and understand the issue. The solution has already been given.
 
Alain Verleyen #:
You don't deserve help as you didn't bother to read and understand the issue. The solution has already been given.

first, mind your language sir, second, it is not easy for a "beginner" to find solution between all this mess above!