66def test_mt5_initialization ():
77 """Test MetaTrader5 initialization in various ways until one succeeds."""
88 print (f'MT5 version: { mt5 .__version__ } ' )
9+
10+ # Start MetaTrader 5 process first before initialization
11+ import subprocess
12+ import time
13+
14+ # Set environment variables
15+ os .environ ['MT5_HEADLESS' ] = '1'
916 print ('MT5_HEADLESS:' , os .environ .get ('MT5_HEADLESS' ))
1017 print ('MT5_PORTABLE_PATH:' , os .environ .get ('MT5_PORTABLE_PATH' ))
1118 print ('Initializing...' )
12-
13- # Set environment variable directly in Python to ensure it's available
14- os .environ ['MT5_HEADLESS' ] = '1'
1519
1620 # Find MetaTrader 5 installation paths
1721 possible_paths = [
@@ -36,69 +40,91 @@ def test_mt5_initialization():
3640
3741 if not existing_paths :
3842 print ("WARNING: No MetaTrader 5 installation found in common locations!" )
43+ return False
44+
45+ # First start the MetaTrader terminal process with specific parameters
46+ mt5_path = existing_paths [0 ] # Use the first found path
47+ print (f"Starting MetaTrader 5 process from: { mt5_path } " )
48+
49+ try :
50+ # Kill any running MT5 processes first
51+ if sys .platform == 'win32' :
52+ subprocess .call ('taskkill /F /IM terminal64.exe' , shell = True , stderr = subprocess .DEVNULL )
53+ time .sleep (3 )
3954
40- # Attempt 1: Initialize with minimal parameters
41- result = mt5 .initialize ()
42- print (f'Initial result: { result } , Error code: { mt5 .last_error ()} ' )
43-
44- # Try each found path if initial attempt fails
45- if not result and existing_paths :
46- for idx , path in enumerate (existing_paths , 1 ):
47- print (f'Attempt { idx + 1 } : Trying with path: { path } ' )
55+ # Start MT5 with the /portable parameter which helps in CI environments
56+ mt5_process = subprocess .Popen ([mt5_path , '/portable' ],
57+ stdout = subprocess .PIPE ,
58+ stderr = subprocess .PIPE ,
59+ creationflags = subprocess .CREATE_NEW_PROCESS_GROUP if sys .platform == 'win32' else 0 )
60+
61+ print (f"Started MetaTrader 5 process with PID: { mt5_process .pid } " )
62+ # Wait for MT5 to start up
63+ time .sleep (15 )
64+
65+ # Now try connecting multiple times with different parameters
66+ max_attempts = 3
67+ for attempt in range (1 , max_attempts + 1 ):
68+ print (f"\n Attempt { attempt } /{ max_attempts } to initialize MT5..." )
4869
49- # Ensure previous attempt is cleaned up
50- if idx > 1 :
51- mt5 .shutdown ()
52- time .sleep (2 )
53-
54- # Try with this path
70+ # Cleanup any previous connection
71+ if attempt > 1 :
72+ try :
73+ mt5 .shutdown ()
74+ except :
75+ pass
76+ time .sleep (3 )
77+
78+ # Using longer timeouts and specifying path directly
5579 result = mt5 .initialize (
56- path = path ,
80+ path = mt5_path ,
5781 login = 0 ,
5882 password = "" ,
5983 server = "" ,
60- timeout = 60000
84+ timeout = 120000 # 2 minutes timeout
6185 )
6286
63- print (f'Result with path { path } : { result } , Error code: { mt5 .last_error ()} ' )
87+ error_code = mt5 .last_error ()
88+ print (f'Initialization result: { result } , Error: { error_code } ' )
6489
6590 if result :
66- print (f'Successfully initialized with path: { path } ' )
91+ print ('MT5 initialized successfully! ' )
6792 break
93+
94+ # If we're getting timeout errors, wait longer between attempts
95+ if error_code [0 ] == - 10005 : # IPC timeout
96+ print ("IPC timeout encountered, waiting longer before next attempt..." )
97+ time .sleep (10 )
6898
69- # If all path attempts fail, try with increased timeout
7099 if not result :
71- print ('All path attempts failed. Trying with increased timeout...' )
72- mt5 .shutdown ()
73- time .sleep (2 )
100+ print ("All initialization attempts failed" )
101+ return False
74102
75- # Final attempt: default init with longer timeout
76- result = mt5 .initialize (timeout = 120000 )
77- print (f'Result with increased timeout: { result } , Error code: { mt5 .last_error ()} ' )
78-
79- # Check if initialization was successful
80- if result :
103+ # Successfully connected, try accessing some basic data
81104 print ('MT5 initialized successfully' )
82105
83- # Try to get account info as test
84- account_info = mt5 .account_info ()
85- if account_info is not None :
86- print (f'Account info: { account_info } ' )
106+ # Try to get terminal information as test
107+ terminal_info = mt5 .terminal_info ()
108+ if terminal_info is not None :
109+ print (f'Terminal info: { terminal_info . _asdict () } ' )
87110 else :
88- print ('No account info available (demo mode)' )
89-
90- # Try to get symbol info as test
91- symbol_info = mt5 .symbol_info ('EURUSD' )
92- if symbol_info is not None :
93- print (f'Symbol info available: { symbol_info .name } ' )
94- else :
95- print ('Symbol info not available' )
111+ print ('Terminal info not available' )
96112
97113 # Clean shutdown
98114 mt5 .shutdown ()
99115 return True
100-
101- return False
116+
117+ except Exception as e :
118+ print (f"Error during MetaTrader 5 initialization: { e } " )
119+ return False
120+ finally :
121+ # Make sure to terminate the MT5 process when done
122+ try :
123+ if 'mt5_process' in locals () and mt5_process :
124+ mt5_process .terminate ()
125+ print ("Terminated MetaTrader 5 process" )
126+ except :
127+ pass
102128
103129if __name__ == "__main__" :
104130 success = test_mt5_initialization ()
0 commit comments