MT4ClientApi文档说明-连接篇

所谓的连接是无需打开终端通过通信协议直接连接到其MT4服务器上,而其服务器信息在对应平台config目录下的srv里。
MT4在对应的*.srv文件中包含服务器详细信息(地址和端口)。对于简单的应用程序来说,连接主节点如下所示:

class Program
{
    static void Main(string[] args)
    {
        new Program().Run();
    }
    void Run()
    {
        try
        {
            MainServer srv = QuoteClient.LoadSrv(
            @"C:\srv\CreatForex-Demo.srv");
            QuoteClient qc = new QuoteClient(99999, "abcd123", srv.Host, srv.Port);
            Console.WriteLine("连接中...");
            qc.Connect();
            Console.WriteLine("已连接");
            Console.WriteLine("任意键退出");
            Console.ReadKey();
            qc.Disconnect();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

但在实际应用中,代理商可能有多个服务器地址,如果主服务器在不可用的情况下,通过子节点连接即可。

void Run()
{
	try
	{
    	//Server[] slaves;
    	MainServer primary = QuoteClient.LoadSrv( @"C:\srv\CreatForex-Demo.srv, out Server[] slaves);
    	QuoteClient qc = Connect(primary, slaves, 99999, "abcd123");
    	Console.WriteLine("已连接到服务器!!!");
    }
	catch (Exception ex)
	{
    	Console.WriteLine(ex.Message);
	}
	Console.WriteLine("任意键退出");
	Console.ReadKey();
}

QuoteClient Connect(MainServer primary, Server[] slaves, int user, string password)
{
	Console.WriteLine("正在连接...");
	QuoteClient qc = new QuoteClient(user, password, primary.Host, primary.Port);
	try
	{
    	qc.Connect();
    	return qc;
	}
	catch (Exception)
	{
    	Console.WriteLine("不能连接到主节点!!!");
    	return ConnectSlaves(slaves, user, password);
	}
}
QuoteClient ConnectSlaves(Server[] slaves, int user, string password)
{
	Console.WriteLine("正在连接子节点。。。");
	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("不能连接子节点!!!");
}

代理商可能定期更改.srv文件,如果要获取此类更新,请使用pathforsavingsrv。如果在connect()方法之前设置此字段,它将在连接期间自动更新。

MainServer srv = QuoteClient.LoadSrv( @"C:\srv\CreatForex-Demo.srv); 
QuoteClient qc = new QuoteClient(99999, "abcd123", srv.Host, srv.Port); 
qc.PathForSavingSrv = @"C:\Program Files\MetaTrader 4\config\"; 
qc.Connect(); 

ok,连接成功。

备注:做了一个社区,欢迎来玩。www.xmt4.com

你可能感兴趣的:(MT4,api,mt4server)