Checking Metatrader connectivity

When running Metatrader locally, the first action the platform does when it starts up is connecting to the near by broker server. You may it clearly by looking at the lower right part of the platform and checking the connectivity status:

Server Connectivity

In this case, you may see it is green and traffic is floating successfully between the terminal to the server. If from some reason, there is no connectivity, this terminal section would look like:

No Connectivity

Manual solution


The manual solution is quite straightforward, mainly close and reopening the terminal. The challenge is knowing the connectivity got lost at the first place. When it happens, there is no way to tell unless you write the code which tells you the connectivity got lost. Once you know it happened, you need to restart the terminal and hope the problem got sorted out. If it continues, you can either scan the available serves or contact your broker.

Automated Connection monitoring


As noted above, it is challenging to know when the connectivity is lost if you're not sitting in front of your PC 24/5. For someone like who uses fully automated expert advisers, it is critical for me to know ASAP when the connectivity got lost. So, I will able to action on this issue and resolve it. The good news are that with 10-20 lines of code, you may create your own monitoring utility:
- first, we setup a timer. As we can't trust OnTick function to be called when there is a disconnection with the server, we must check it every X minutes, I personally use an hourly timer:
EventSetTimer(60*PERIOD_H1);
This will call OnTimer function every hour so we will be able to test for connectivity.
- In the function OnTimer, I will check for connectivity and set a certain flag to notify me if the connectivity got restored:
void OnTimer()
{
if(IsDisconnectedFlag==false && IsConnected()==false)
{
SendNotification("Broker connection lost...");
IsDisconnectedFlag=true;
}
else if(IsDisconnectedFlag==true && IsConnected()==true)
{
SendNotification("Broker connection retrieved...");
IsDisconnectedFlag=false;
}
}

This code simply notifies you if the connection got lost, or later on restored. Since the server connectivity is lost and not the internet connection, it is still possible to send notifications to your mobile device.

With this simple addition to your expert adviser, you will be able to get notified in real time that the terminal lost connection with the broker so you can safely act on it and try to fix it.

Don't forget to visit my downloads page for additional expert advisers, indicators and libraries.

Comments