mql5

Can we put void OnInit() and int OnCalculate() in one page?


When I write this code in MetaEditor:

#include <Trade\Trade.mqh>
CTrade md;
void OnInit()
{         
   md.BuyLimit(0.01, 3370, _Symbol, 0, 0,ORDER_TIME_DAY, 0, NULL);
}

It works. But when I add some codes to display "RSI", it doesn't work:

#include <Trade\Trade.mqh>
CTrade md;
void OnInit()
{         
   md.BuyLimit(0.01, 3370, _Symbol, 0, 0,ORDER_TIME_DAY, 0, NULL);
}

int i_COUNT, i_HANDLE, i_MA_PERIOD, i_START_POS;  
double db_ARRAY_RSI[];                            
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   i_MA_PERIOD = 14;                              
   i_HANDLE = iRSI(Symbol(), PERIOD_CURRENT, i_MA_PERIOD, PRICE_CLOSE); 
   i_START_POS = 0;                              
   i_COUNT = 1;                                 
   CopyBuffer(i_HANDLE, 0, i_START_POS, i_COUNT, db_ARRAY_RSI);      
   Comment("db_ARRAY_RSI[0]: ", NormalizeDouble(db_ARRAY_RSI[0], 2), "abc"); 
   return(rates_total); 
}

My question is this: Can't we put both "void OnInit()" and "int OnCalculate()" in one expert?

I want to display "RSI" on the chart. How can I do that?


Solution

  • So this is the solution :

    #include <Trade\Trade.mqh>
    CTrade trade;
    input int rsiPeriod=14;//period
    int rsiHandle=INVALID_HANDLE;
    int rsiWindow=-1;
    int OnInit()
      {
      Print(EnumToString((ENUM_SYMBOL_INFO_INTEGER)18));
      //start rsi indicator 
        rsiHandle=iRSI(_Symbol,_Period,rsiPeriod,PRICE_CLOSE);
        if(rsiHandle!=INVALID_HANDLE){
        //add the indicator 
          int windows=(int)ChartGetInteger(0,CHART_WINDOWS_TOTAL);
          if(ChartIndicatorAdd(0,windows,rsiHandle)){
            rsiWindow=windows;
            }else{Alert("Cannot add rsi");ExpertRemove();return(INIT_FAILED);}
        }else{Alert("Cannot start rsi");ExpertRemove();return(INIT_FAILED);
        }
      return(INIT_SUCCEEDED);
      }
    void OnTick()
      {
      //get rsi value 
        double value_return[];
        if(CopyBuffer(rsiHandle,0,0,1,value_return)==1){
          Comment("RSI "+DoubleToString(value_return[0],2));
          }
      }
    void OnDeinit(const int reason)
      {
      if(rsiWindow>=1&&rsiHandle!=INVALID_HANDLE){
        ChartIndicatorDelete(0,rsiWindow,"RSI("+IntegerToString(rsiPeriod)+")");
        IndicatorRelease(rsiHandle);
        }
      }