MT4 Java Connect to server

easy direct connection to any MT4 and MT5 server

MT4 Java Connect to server


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

1 QuoteClient qc = new QuoteClient(2090221607, "OJgYhOfEF8", "demo.mt4tickmill.com", 443);
2 qc.Connect();
3 System.out.println("Connected. Balance = " + qc.AccountBalance());

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

 1 void connectExtra() {
 2         try {
 3             Servers servers = QuoteClient.LoadSrv( "bin\\Debug\\GerchikCo-Demo.srv");
 4             QuoteClient qc = Connect(servers.PrimaryServer, servers.SecondaryServers, 67611, "wx1yhpn");
 5             System.out.println("Connected to server");
 6         } catch (Exception ex){
 7             System.out.println(ex.getMessage());
 8         }
 9     }
10 
11     QuoteClient Connect(PrimaryServer primary , SecondaryServer[] slaves, int user, String password) {
12         System.out.println("Connecting...");
13         QuoteClient qc = new QuoteClient(user, password, primary.getHost(), primary.getPort());
14         try {
15             qc.Connect();
16             return qc;
17         } catch (Exception ex){
18             System.out.println("Cannot connect to primary server: " + ex.getMessage());
19             return ConnectSlaves(slaves, user, password);
20         }
21     }
22 
23     QuoteClient ConnectSlaves(SecondaryServer[] servers, int user, String password) {
24         System.out.println("Connecting to slaves...");
25         for(SecondaryServer server: servers)
26         {
27             QuoteClient qc = new QuoteClient(user, password, server.getHost(), server.getPort());
28             try {
29                 qc.Connect();
30                 return qc;
31             } catch (Exception ex) {
32                 System.out.println(ex.getMessage());
33             }
34         }
35         throw new RuntimeException("Cannot connect to secondary servers");
36     }

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