Closing Duplicate Charts Problem

 

I have an expert running on a GBPAUD chart. Its job is to open other charts and apply a template if certain criteria is met for other pairs. Occasionally it will open a chart for the same pair more than once, and so I run a check when each chart is open to close duplicate charts. The problem is that it closes the GBPAUD chart, even if GBPAUD is not the pair running the duplicate check, and I can't figure out why.

This code should close the chart that ran it, if a chart for same pair is already open.

void CloseDuplicateCharts() {
   int numCharts = 0;
   long chartID=ChartFirst();
   
   while(chartID >= 0) {
      chartID = ChartNext(chartID);
      if (ChartSymbol(chartID) == Symbol()) {
         numCharts++;
      }
   }
   
   if (Symbol() == "GBPAUD") {
      if (numCharts > 2) {
         Print("Duplicate "+Symbol()+" Closed");
         ChartClose(0);
      }
   } else {
      if (numCharts > 1) {
         Print("Duplicate "+Symbol()+" Closed");
         ChartClose(0);
      }
   }
}

I have also tried to prevent duplicate charts from being opened, but the duplicates keep being occasionally opened. This code is intended to open a chart, if one is not already open.

bool OpenChart(string pair) {
   bool wasOpened = false;
   
   int numCharts = 0;
   long chartID=ChartFirst();
   
   while(chartID >= 0) {
      chartID = ChartNext(chartID);
      if (ChartSymbol(chartID) == pair) {
         numCharts++;
      }
   }
   
   if (pair == "GBPAUD") {
      if (numCharts == 1) {
         chartID = ChartOpen(pair, PERIOD_H1);
         ChartApplyTemplate(chartID, "Template");
         
         if (chartID > 0) {
            wasOpened = true;
            Print(pair+" Opened");
         }
      }
   } else {
      if (numCharts == 0) {
         chartID = ChartOpen(pair, PERIOD_H1);
         ChartApplyTemplate(chartID, "Template");
         
         if (chartID > 0) {
            wasOpened = true;
            Print(pair+" Opened");
         }
      }
   }
   
   return(wasOpened);
}

The reason GBPAUD has slightly different criteria is because it is running the Expert to open charts as needed, so 1 chart should always be open, the one with the Expert.

If anyone can help me fix either of these functions, it would be greatly appreciated.