How can i fix my while loop

 
//+------------------------------------------------------------------+
#property copyright "Copyright 2022"
#property link      "https://www.mql5.com/+"
#property version   "1.00"

string sym="";
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
//--- create timer
   EventSetTimer(1);
//---
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
//--- destroy timer
   EventKillTimer();

}

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer() {
//---

sym=_Symbol;
while(!IsStopped()) 
  { 
  Print("sleeping for 5 secoonds");
  Sleep(5000);
  if(sym==_Symbol)
  Print(_Symbol);
  else{
  Print("break");
  sym="";
  }
  }
}
//+------------------------------------------------------------------+

While loop not detecting when a chart symbol is changed, what mistake i am making here?

 
If I remember right, the EA gets reloaded on symbol change. This will reset your global variable _sym.

You will need to use global terminal variables for persistent storage across reloads.

 
  1. Arpit T: While loop not detecting when a chart symbol is changed, what mistake i am making here?

    Nothing is changing while your code is running. You will break out of the while because of IsStopped and go through a deinit/chart change/init cycle.

  2. Dominik Christian Egert #: If I remember right, the EA gets reloaded on symbol change.
    Indicators are reloaded, EAs are not.