-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathinit-test.py
More file actions
201 lines (173 loc) · 6.78 KB
/
init-test.py
File metadata and controls
201 lines (173 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import MetaTrader5 as mt5
import sys
from datetime import datetime
import time
def test_connection():
"""
Test MT5 connection and basic functionality
Returns:
bool: True if all tests pass, False otherwise
"""
tests_passed = 0
total_tests = 5
print("Running MT5 Connection Tests...")
print("=" * 40)
# Test 1: Initialize MT5
print("Test 1: MT5 Initialization... ", end="")
try:
if mt5.initialize():
print("✅ PASSED")
tests_passed += 1
else:
print("❌ FAILED")
print(f" Error: {mt5.last_error()}")
except Exception as e:
print("❌ FAILED")
print(f" Exception: {e}")
# Test 2: Get terminal info
print("Test 2: Terminal Information... ", end="")
try:
terminal_info = mt5.terminal_info()
if terminal_info:
print("✅ PASSED")
print(f" Build: {terminal_info.build}")
print(f" Path: {terminal_info.path}")
tests_passed += 1
else:
print("❌ FAILED")
except Exception as e:
print("❌ FAILED")
print(f" Exception: {e}")
# Test 3: Get account info
print("Test 3: Account Information... ", end="")
try:
account_info = mt5.account_info()
if account_info:
print("✅ PASSED")
print(f" Account: {account_info.login}")
print(f" Server: {account_info.server}")
print(f" Currency: {account_info.currency}")
tests_passed += 1
else:
print("❌ FAILED")
except Exception as e:
print("❌ FAILED")
print(f" Exception: {e}")
# Test 4: Symbol data retrieval
print("Test 4: Symbol Data Retrieval... ", end="")
try:
symbols_to_test = ["EURUSD", "GBPUSD", "USDJPY"]
successful_symbols = 0
for symbol in symbols_to_test:
tick = mt5.symbol_info_tick(symbol)
if tick:
successful_symbols += 1
if successful_symbols > 0:
print("✅ PASSED")
print(f" Successfully retrieved data for {successful_symbols}/{len(symbols_to_test)} symbols")
tests_passed += 1
else:
print("❌ FAILED")
print(" No symbol data available")
except Exception as e:
print("❌ FAILED")
print(f" Exception: {e}")
# Test 5: Trading permissions
print("Test 5: Trading Permissions... ", end="")
try:
account_info = mt5.account_info()
if account_info:
if account_info.trade_allowed and account_info.trade_expert:
print("✅ PASSED")
print(" Trading and Expert Advisors allowed")
tests_passed += 1
else:
print("⚠️ PARTIAL")
print(f" Trading allowed: {account_info.trade_allowed}")
print(f" EA allowed: {account_info.trade_expert}")
else:
print("❌ FAILED")
except Exception as e:
print("❌ FAILED")
print(f" Exception: {e}")
print("\n" + "=" * 40)
print(f"Tests completed: {tests_passed}/{total_tests} passed")
return tests_passed == total_tests
def get_market_data(symbols=["EURUSD", "GBPUSD", "USDJPY"]):
"""
Get current market data for specified symbols
Args:
symbols (list): List of symbols to get data for
"""
print("\nCurrent Market Data:")
print("=" * 60)
print(f"{'Symbol':<10} {'Bid':<10} {'Ask':<10} {'Spread':<10} {'Time':<20}")
print("-" * 60)
for symbol in symbols:
try:
# Add symbol to Market Watch if not visible
symbol_info = mt5.symbol_info(symbol)
if symbol_info and not symbol_info.visible:
mt5.symbol_select(symbol, True)
tick = mt5.symbol_info_tick(symbol)
if tick:
spread = (tick.ask - tick.bid) / mt5.symbol_info(symbol).point
timestamp = datetime.fromtimestamp(tick.time).strftime('%H:%M:%S')
print(f"{symbol:<10} {tick.bid:<10.5f} {tick.ask:<10.5f} {spread:<10.1f} {timestamp:<20}")
else:
print(f"{symbol:<10} {'N/A':<10} {'N/A':<10} {'N/A':<10} {'N/A':<20}")
except Exception as e:
print(f"{symbol:<10} Error: {str(e)[:40]:<40}")
def check_system_requirements():
"""
Check system requirements and settings
"""
print("\nSystem Requirements Check:")
print("=" * 40)
try:
terminal_info = mt5.terminal_info()
if terminal_info:
print(f"MT5 Build: {terminal_info.build}")
print(f"DLL Allowed: {terminal_info.dlls_allowed}")
print(f"Trade Allowed: {terminal_info.trade_allowed}")
print(f"Connected: {terminal_info.connected}")
if not terminal_info.dlls_allowed:
print("⚠️ Warning: DLL imports not allowed")
if not terminal_info.trade_allowed:
print("⚠️ Warning: Trading not allowed")
if not terminal_info.connected:
print("❌ Error: Not connected to trading server")
except Exception as e:
print(f"Error checking system: {e}")
def main():
"""
Main function to run all tests
"""
try:
print("MetaTrader 5 Connection Test Script")
print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 50)
# Run connection tests
if test_connection():
print("\n✅ All tests passed! MT5 is ready for trading.")
# Show market data
get_market_data()
# Check system requirements
check_system_requirements()
else:
print("\n❌ Some tests failed. Please check your MT5 setup.")
print("\nTroubleshooting tips:")
print("1. Ensure MT5 is running and logged in")
print("2. Check internet connection")
print("3. Verify trading account credentials")
print("4. Enable algorithmic trading in MT5 (Tools > Options > Expert Advisors)")
print("5. Allow DLL imports if using external libraries")
except KeyboardInterrupt:
print("\nTest cancelled by user")
except Exception as e:
print(f"\nUnexpected error: {e}")
finally:
print(f"\nCompleted at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
mt5.shutdown()
if __name__ == "__main__":
main()