1+ """Test MetaTrader5 initialization in headless environments like GitHub CI."""
2+
3+ import os
4+ import sys
5+ import time
6+ import subprocess
7+ import MetaTrader5 as mt5
8+
9+ def setup_headless_environment ():
10+ """Prepare the environment for headless MT5 operation."""
11+ # Create required directories that might be expected by MT5
12+ base_path = os .path .expanduser ("~" )
13+ mt5_data_path = os .path .join (base_path , "AppData" , "Roaming" , "MetaQuotes" , "Terminal" )
14+
15+ os .makedirs (mt5_data_path , exist_ok = True )
16+ print (f"Created MT5 data directory: { mt5_data_path } " )
17+
18+ # Set environment variables that might help with headless operation
19+ os .environ ["MT5_HEADLESS" ] = "1"
20+ return True
21+
22+ def test_headless_initialize ():
23+ """Test MT5 initialization in a headless environment."""
24+ print (f"MetaTrader5 package version: { mt5 .__version__ } " )
25+
26+ # Setup headless environment
27+ setup_headless_environment ()
28+
29+ # Start MT5 terminal process with headless-friendly options
30+ mt_path = "C:\\ Program Files\\ MetaTrader 5\\ terminal64.exe"
31+ if not os .path .exists (mt_path ):
32+ print (f"ERROR: MetaTrader5 executable not found at { mt_path } " )
33+ return False
34+
35+ print (f"Found MetaTrader5 at: { mt_path } " )
36+
37+ # Kill any existing MT5 processes
38+ try :
39+ subprocess .run (["taskkill" , "/F" , "/IM" , "terminal64.exe" ],
40+ stdout = subprocess .PIPE , stderr = subprocess .PIPE )
41+ print ("Killed any existing MetaTrader 5 processes" )
42+ time .sleep (2 )
43+ except Exception as e :
44+ print (f"Note: No existing processes to kill: { e } " )
45+
46+ # Launch with multiple flags for headless operation
47+ try :
48+ print ("Starting MetaTrader 5 terminal with headless-friendly options..." )
49+ process = subprocess .Popen ([
50+ mt_path ,
51+ "/portable" , # Use portable mode to avoid requiring login
52+ "/skipupdate" , # Skip checking for updates
53+ "/config:headless" , # Use a specific config name
54+ "/nogui" # No GUI needed (might not be supported but worth trying)
55+ ], stdout = subprocess .PIPE , stderr = subprocess .PIPE )
56+
57+ print (f"Started MetaTrader 5 with PID: { process .pid } " )
58+ time .sleep (15 ) # Give it time to initialize backend services
59+ except Exception as e :
60+ print (f"Error starting MetaTrader 5: { e } " )
61+ return False
62+
63+ # Try initialization methods in sequence
64+ print ("\n Attempting MT5 initialization..." )
65+
66+ # Method 1: With path parameter and longer timeout
67+ print ("Method 1: With explicit path and timeout" )
68+ try :
69+ result = mt5 .initialize (path = mt_path , timeout = 60000 ) # 60-second timeout
70+ error = mt5 .last_error ()
71+ print (f"Result: { result } , Error: { error } " )
72+ if result :
73+ print ("Method 1 SUCCESS!" )
74+ terminal_info = mt5 .terminal_info ()
75+ if terminal_info :
76+ print (f"Terminal info - Path: { terminal_info .path } , Connected: { getattr (terminal_info , 'connected' , 'N/A' )} " )
77+ mt5 .shutdown ()
78+ return True
79+ except Exception as e :
80+ print (f"Exception in method 1: { e } " )
81+
82+ # Method 2: With server parameter (try to avoid login)
83+ print ("\n Method 2: With server parameter" )
84+ try :
85+ result = mt5 .initialize (
86+ path = mt_path ,
87+ server = "Demo" , # Use demo server
88+ login = 0 , # No login
89+ timeout = 60000 # 60-second timeout
90+ )
91+ error = mt5 .last_error ()
92+ print (f"Result: { result } , Error: { error } " )
93+ if result :
94+ print ("Method 2 SUCCESS!" )
95+ mt5 .shutdown ()
96+ return True
97+ except Exception as e :
98+ print (f"Exception in method 2: { e } " )
99+
100+ # Method 3: Basic initialization with longer wait after process start
101+ print ("\n Method 3: After additional delay" )
102+ try :
103+ print ("Waiting 30 more seconds for MT5 to fully initialize..." )
104+ time .sleep (30 )
105+ result = mt5 .initialize ()
106+ error = mt5 .last_error ()
107+ print (f"Result: { result } , Error: { error } " )
108+ if result :
109+ print ("Method 3 SUCCESS!" )
110+ mt5 .shutdown ()
111+ return True
112+ except Exception as e :
113+ print (f"Exception in method 3: { e } " )
114+
115+ # If we got here, all methods failed
116+ print ("\n All initialization attempts failed in headless mode" )
117+ return False
118+
119+ if __name__ == "__main__" :
120+ success = test_headless_initialize ()
121+ if success :
122+ print ("\n HEADLESS TEST PASSED: Successfully initialized MT5" )
123+ sys .exit (0 )
124+ else :
125+ print ("\n HEADLESS TEST FAILED: Could not initialize MT5" )
126+ sys .exit (1 )
0 commit comments