1
1
"""Integration tests for MetaTrader 5 connection functionality."""
2
2
3
3
import sys
4
-
4
+ import os
5
+ import time
5
6
import MetaTrader5 as mt5
6
7
7
8
@@ -13,22 +14,44 @@ def test_mt5_connection() -> bool:
13
14
"""
14
15
print (f"MetaTrader5 package version: { mt5 .__version__ } " )
15
16
16
- # Initialize MetaTrader 5
17
- if not mt5 .initialize ():
18
- print (f"initialize() failed, error code = { mt5 .last_error ()} " )
19
- sys .exit (1 )
20
-
21
- print (mt5 .terminal_info ())
22
- print (f"MetaTrader5 terminal copyright: { mt5 .terminal_info ().copyright } " )
23
- print (f"MetaTrader5 terminal name: { mt5 .terminal_info ().name } " )
24
- print (f"MetaTrader5 terminal path: { mt5 .terminal_info ().path } " )
25
-
26
- authorized = mt5 .login ()
27
- if authorized :
28
- print (f"Connected to account: { mt5 .account_info ().login } " )
29
- print (f"Balance: { mt5 .account_info ().balance } " )
30
-
17
+ # Define path to the MetaTrader terminal executable
18
+ path = "C:\\ Program Files\\ MetaTrader 5\\ terminal64.exe"
19
+ print (f"MetaTrader5 path: { path } " )
20
+
21
+ # Try to initialize with explicit path parameter
22
+ if not mt5 .initialize (path = path ):
23
+ error = mt5 .last_error ()
24
+ print (f"initialize() with path failed, error code = { error } " )
25
+
26
+ # Try the second method: initialize with just a delay
27
+ time .sleep (3 ) # Give some time before retry
28
+ print ("Retrying initialization..." )
29
+ if not mt5 .initialize ():
30
+ error = mt5 .last_error ()
31
+ print (f"initialize() without path failed, error code = { error } " )
32
+ sys .exit (1 )
33
+
34
+ # Connection successful
35
+ print ("MetaTrader5 initialized successfully" )
36
+
37
+ # Get account info
38
+ account_info = mt5 .account_info ()
39
+ if account_info is not None :
40
+ print (f"Account info: server={ account_info .server } , balance={ account_info .balance } " )
41
+ else :
42
+ print ("Failed to get account info - this is normal without login credentials" )
43
+
44
+ # Get terminal info
45
+ terminal_info = mt5 .terminal_info ()
46
+ if terminal_info is not None :
47
+ print (f"Terminal info: connected={ terminal_info .connected } , path={ terminal_info .path } " )
48
+ else :
49
+ print ("Failed to get terminal info" )
50
+
51
+ # Shutdown the connection
52
+ print ("Shutting down MetaTrader5 connection..." )
31
53
mt5 .shutdown ()
54
+ print ("Done" )
32
55
33
56
print ("Test completed successfully" )
34
57
return True
0 commit comments