In MT4, is there a simple way to get a UniqueID per *each* instance of an indicator? - page 3

 

Uses 1 temporary GV and bitwise operators.

#property strict
#property indicator_chart_window

string GVName   = "MyIndicator";
string tag      = "MyObject";
int instance    = -1;
int instances[] = {1,2,4,8,16,32,64,128,256,512};

int OnInit()
  {
   GVName+=(string)ChartID();
   if(!GlobalVariableCheck(GVName))
     {
      if(!GlobalVariableTemp(GVName)) return(INIT_FAILED);
      GlobalVariableSet(GVName,instances[0]);
      ObjectsDeleteAll(0,tag);
      instance = instances[0];
      tag+=(string)instance;
      Print("No GV found... Assigning 1, deleting ALL orphaned objects");
     }
   else
     {
      int val = (int)GlobalVariableGet(GVName),
          cnt = ArraySize(instances);
      for(int i=0; i<cnt; i++)
        {
         if((val&instances[i])==0)
           {
            instance=instances[i];
            GlobalVariableSet(GVName,val|instance);
            tag+=(string)instance;
            ObjectsDeleteAll(0,tag);
            printf("Assigning %i, deleting all orphaned '~%i' objects",instance,instance);
            break;
           }
        }
     }
   if(instance<0) return(INIT_FAILED);
   ObjectCreate(0,tag,OBJ_LABEL,0,0,0);
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0,tag);
   int val=(int)GlobalVariableGet(GVName);
   GlobalVariableSet(GVName,val&~instance);
   printf("Freeing up %i and deleting all '~%i' objects",instance,instance);
  }

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[])
  {
  
   return(rates_total);
  }
 
honest_knave:

Uses 1 temporary GV and bitwise operators.

//         if((val&instances[i])==0)
//           {
//            instance=instances[i];

         if((val&(1 << i))==0)
           {
            instance=(1 << i);
 
fxsaber:

Nice variation on the bitwise methodology. Slightly quicker too, I imagine
Reason: