How to keep MT4/5 API connected

easy direct connection to any MT4 and MT5 server

How to keep MT4/5 API connected

To keep connection with mt4 server always alive just need to use OnDisconnect event in MT4 .NET API and reconnect inside if required:

QuoteClient qc = new QuoteClient(500476959, "ehj4bod", "mt4-demo.roboforex.com", 443);
qc.OnDisconnect += delegate (object sender, DisconnectEventArgs args)
{
    var qc = (QuoteClient)sender;
    Console.WriteLine(qc.User + " reconnecting...");
    for (int i = 0; i < 1000; i++)
        try
        {
            qc.Connect();
            Console.WriteLine(qc.User + " reconnected");
            break;
        }
        catch (Exception ex)
        {
            Console.WriteLine(qc.User + " " + ex.Message);
            Thread.Sleep(3000);
        }
        if(!qc.Connected)
            Console.WriteLine(qc.User + " cannot reconnect after 1000 attempts");
};
qc.Connect();
Console.WriteLine(qc.User + " connected to server");

For MT5 need to use event OnConnectProgress event:

var api = new MT5API(62333850, "tecimil4", "78.140.180.198", 443);
api.OnConnectProgress += delegate (MT5API sender, ConnectEventArgs args)
{
    if (args.Progress == ConnectProgress.Disconnect)
    {
        Console.WriteLine(api.User + " reconnecting...");
        for (int i = 0; i < 1000; i++)
            try
            {
                sender.Connect();
                Console.WriteLine(api.User + " reconnected");
                break;
            }
            catch (Exception ex)
            {
                Console.WriteLine(api.User + " " + ex.Message);
                Thread.Sleep(3000);
            }
    }
    if (!api.Connected)
        Console.WriteLine(api.User + " cannot reconnect after 1000 attempts");  
};
api.Connect();
Console.WriteLine(api.User + " connected to server");

Leave a Reply