#property copyright "Bugscoder Studio"
#property link      "https://www.bugscoder.com/"
#property version   "1.00"
#property strict
#property indicator_separate_window

#property indicator_buffers 4
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_width1  1
#property indicator_color1  clrLime
#property indicator_type2   DRAW_HISTOGRAM
#property indicator_width2  1
#property indicator_color2  clrTomato
#property indicator_type3   DRAW_NONE
#property indicator_type4   DRAW_NONE

input ENUM_TIMEFRAMES resLT = PERIOD_D1; //Res LT
input ENUM_TIMEFRAMES resMT = PERIOD_H4; //Res MT

double up[], dn[], MTc[], MTema20[];
string obj_prefix = "RSIMACDOBOS_";

int OnInit() {
   IndicatorDigits(Digits);
   IndicatorSetDouble(INDICATOR_MINIMUM, -1);
   IndicatorSetDouble(INDICATOR_MAXIMUM,  1);
   
   SetIndexLabel(0, "Long");
   SetIndexBuffer(0, up);
   SetIndexLabel(1, "Short");
   SetIndexBuffer(1, dn);
   
   SetIndexLabel(2, "");
   SetIndexBuffer(2, MTc);
   SetIndexLabel(3, "");
   SetIndexBuffer(3, MTema20);

   return(INIT_SUCCEEDED);
}

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[]) {

   int startPos = rates_total-prev_calculated-2;
   if (startPos <= 1) { startPos = 1; }
   
   //for(int pos=0; pos<=startPos; pos++) {
   for(int pos=startPos; pos>=0; pos--) {
      up[pos] = 0;
      dn[pos] = 0;
      
      int resLTShift = iBarShift(NULL, resLT, Time[pos]);
      int resMTShift = iBarShift(NULL, resMT, Time[pos]);
      
      double   LTo = iCustom(NULL, resLT, "Heiken Ashi", 2, resLTShift);
      double   LTc = iCustom(NULL, resLT, "Heiken Ashi", 3, resLTShift);
      double   MTo = iCustom(NULL, resMT, "Heiken Ashi", 2, resMTShift);
          MTc[pos] = iCustom(NULL, resMT, "Heiken Ashi", 3, resMTShift);
      
      bool LTlong  = LTc > LTo ? true : false;
      bool LTshort = LTc < LTo ? true : false;
      MTema20[pos] = iMAOnArray(MTc, 0, 20, 0, MODE_EMA, pos);
    
      double MTema20delta = change(MTema20, pos);
    
      bool MTlong  = MTc[pos] > MTo && MTc[pos] > MTema20[pos] && MTema20delta > 0 ? true : false;
      bool MTshort = MTc[pos] < MTo && MTc[pos] < MTema20[pos] && MTema20delta < 0 ? true : false;
      
      bool Long  = MTlong  == true && LTlong  == true ? true : false;
      bool Short = MTshort == true && LTshort == true ? true : false;
      
      if (Long  == true) { up[pos] =  1; }
      if (Short == true) { dn[pos] = -1; }
   }

   return(rates_total);
}

void OnDeinit(const int reason) {
   ObjectsDeleteAll(0, obj_prefix);
}

double change(double &_src[], int pos) {
   return _src[pos]-_src[pos+1];
}