MT4 Connecting

easy direct connection to any MT4 and MT5 server

MT4 Connecting

MT4 contains server details (address and port) in  *.srv files. For simple application is enough to get just primary server as shown below.    

using System;
using TradingAPI.MT4Server;
 
namespace Help
{
  class Program
  {
    static void Main(string[] args)
    {
      new Program().Run();
    }
 
    void Run()
    {
      try
      {
        MainServer srv = QuoteClient.LoadSrv(@"GerchikCo-Demo.srv");
        QuoteClient qc = new QuoteClient(67611, "wx1yhpn", srv.Host, srv.Port);
        Console.WriteLine("Connecting...");
        qc.Connect();
        Console.WriteLine("Connected to server");
        Console.WriteLine("Press any key...");
        Console.ReadKey();
        qc.Disconnect();
 
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        Console.WriteLine("Press any key...");
        Console.ReadKey();
      }
    }
  }
}

In real applications you need to get also slave servers and connect to them if primary server not available.

void Run()
{
   try
   {
      Server[] slaves;
      MainServer primary = QuoteClient.LoadSrv(@"GerchikCo-Demo.srv"out slaves);
      QuoteClient qc = Connect(primary, slaves, 67611, "wx1yhpn");
      Console.WriteLine("Connected to server");
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
   }
   Console.WriteLine("Press any key...");
   Console.ReadKey();
}
 
QuoteClient Connect(MainServer primary, Server[] slaves, uint user, string password)
{
   Console.WriteLine("Connecting...");
   QuoteClient qc = new QuoteClient(user, password, primary.Host, primary.Port);
   try
   {
      qc.Connect();
      return qc;
   }
   catch (Exception)
   {
      Console.WriteLine("Cannot connect to main server");
      return ConnectSlaves(slaves, user, password);
   }
}
 
QuoteClient ConnectSlaves(Server[] slaves, uint user, string password)
{
   Console.WriteLine("Connecting to slaves...");
   foreach (var server in slaves)
   {
      QuoteClient qc = new QuoteClient(user, password, server.Host, server.Port);
      try
      {
         qc.Connect();
         return qc;
      }
      catch (Exception)
      {
      }
   }
   throw new Exception("Cannot connect to slaves");
}

Broker could periodically change .srv file, if you want to get such updates use PathForSavingSrv field. If you set this field before Connect() method it would be updated during connection.

 

 

Leave a Reply