AccountBalance() and change of the account

 

Hello,

I would be very grateful if someone could help me with my problem. I need the amount of the balance in one of my indicators. Which I get with the function AccountBalance(). The problem is: when I change the Account in the MT4 (Login with an another account and the indicator is already in the chart), the function AccountBalance() does not deliver the actual balance but the balance of the account with whom I was logged previously. Do somebody know what I can do, respectively what the reason is for this behaviour? The error does not occur every time, but very often.


Thank you very much for you help!

#property version   "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(){
   EventSetMillisecondTimer(500);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason){
   EventKillTimer();   
}
  int MyAccountNumber;
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[]){
   
   double MyBalance;
   if(MyAccountNumber!=AccountNumber()){

      MyAccountNumber = AccountNumber();
      Print("Change");
      Print("Balance: " + AccountBalance());
      MyBalance = AccountInfoDouble(ACCOUNT_BALANCE);
      Print("MyBalance: " + MyBalance);
  
   }
   return(rates_total);
  }
//+------------------------------------------------------------------+

void OnTimer(){
   double MyBalance;
   if(MyAccountNumber!=AccountNumber()){

      MyAccountNumber = AccountNumber();
      Print("Change");
      Print("Balance: " + AccountBalance());
      MyBalance = AccountInfoDouble(ACCOUNT_BALANCE);
      Print("MyBalance: " + MyBalance);
   }    
}



I have found that the new balance has not been loaded into the terminal at the moment when the balance is requested by the code.

The problem is I can not use Sleep() function in the indicator to wait for some time. I am very grateful for any suggestion how I can solve this problem.