Skip to content

Commit 6718a21

Browse files
committed
test
1 parent c390090 commit 6718a21

File tree

4 files changed

+238
-119
lines changed

4 files changed

+238
-119
lines changed

mqpy/trade.py

Lines changed: 6 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -224,18 +224,6 @@ def open_buy_position(self, comment: str = "") -> None:
224224
Returns:
225225
None
226226
"""
227-
# Check trade mode to see if Buy operations are allowed
228-
symbol_info = Mt5.symbol_info(self.symbol)
229-
if symbol_info.trade_mode == 0:
230-
logger.warning(f"Cannot open Buy position for {self.symbol} - trading is disabled.")
231-
return
232-
if symbol_info.trade_mode == 2: # Short only
233-
logger.warning(f"Cannot open Buy position for {self.symbol} - only Sell positions are allowed.")
234-
return
235-
if symbol_info.trade_mode == 4 and len(Mt5.positions_get(symbol=self.symbol)) == 0:
236-
logger.warning(f"Cannot open Buy position for {self.symbol} - symbol is in 'Close only' mode.")
237-
return
238-
239227
point = Mt5.symbol_info(self.symbol).point
240228
price = Mt5.symbol_info_tick(self.symbol).ask
241229

@@ -268,18 +256,6 @@ def open_sell_position(self, comment: str = "") -> None:
268256
Returns:
269257
None
270258
"""
271-
# Check trade mode to see if Sell operations are allowed
272-
symbol_info = Mt5.symbol_info(self.symbol)
273-
if symbol_info.trade_mode == 0:
274-
logger.warning(f"Cannot open Sell position for {self.symbol} - trading is disabled.")
275-
return
276-
if symbol_info.trade_mode == 1: # Long only
277-
logger.warning(f"Cannot open Sell position for {self.symbol} - only Buy positions are allowed.")
278-
return
279-
if symbol_info.trade_mode == 4 and len(Mt5.positions_get(symbol=self.symbol)) == 0:
280-
logger.warning(f"Cannot open Sell position for {self.symbol} - symbol is in 'Close only' mode.")
281-
return
282-
283259
point = Mt5.symbol_info(self.symbol).point
284260
price = Mt5.symbol_info_tick(self.symbol).bid
285261

@@ -395,15 +371,14 @@ def open_position(self, *, should_buy: bool, should_sell: bool, comment: str = "
395371
"""
396372
symbol_info = Mt5.symbol_info(self.symbol)
397373

398-
# Check trade mode restrictions
399-
if self._handle_trade_mode_restrictions(symbol_info):
400-
return
401-
402374
# Open a position if no existing positions and within trading time
403375
if (len(Mt5.positions_get(symbol=self.symbol)) == 0) and self.trading_time():
404-
self._handle_position_by_trade_mode(
405-
symbol_info, should_buy=should_buy, should_sell=should_sell, comment=comment
406-
)
376+
if should_buy and not should_sell:
377+
self.open_buy_position(comment)
378+
self.total_deals += 1
379+
if should_sell and not should_buy:
380+
self.open_sell_position(comment)
381+
self.total_deals += 1
407382

408383
# Check for stop loss and take profit conditions
409384
self.stop_and_gain(comment)

scripts/setup_mt5.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#!/usr/bin/env python3
2+
"""Script to setup and configure MetaTrader 5 for automated trading."""
3+
4+
import os
5+
import sys
6+
import time
7+
from pathlib import Path
8+
import logging
9+
10+
try:
11+
import MetaTrader5 as Mt5
12+
except ImportError:
13+
print("MetaTrader5 package not installed. Install it with: pip install MetaTrader5")
14+
sys.exit(1)
15+
16+
logging.basicConfig(level=logging.INFO)
17+
logger = logging.getLogger(__name__)
18+
19+
def find_mt5_terminal():
20+
"""Find MetaTrader 5 terminal executable."""
21+
common_paths = [
22+
"C:\\Program Files\\MetaTrader 5\\terminal64.exe",
23+
"C:\\Program Files (x86)\\MetaTrader 5\\terminal.exe",
24+
os.path.expandvars("%APPDATA%\\MetaTrader 5\\terminal64.exe"),
25+
os.path.expandvars("%PROGRAMFILES%\\MetaTrader 5\\terminal64.exe"),
26+
]
27+
28+
for path in common_paths:
29+
if os.path.exists(path):
30+
return path
31+
return None
32+
33+
def check_trading_allowed():
34+
"""Check if trading is allowed and print current settings."""
35+
terminal_info = Mt5.terminal_info()
36+
logger.info("Current MetaTrader 5 settings:")
37+
logger.info(f"Connected: {terminal_info.connected}")
38+
logger.info(f"Trade allowed: {terminal_info.trade_allowed}")
39+
logger.info(f"DLLs allowed: {terminal_info.dlls_allowed}")
40+
41+
return terminal_info.trade_allowed and terminal_info.dlls_allowed
42+
43+
def main():
44+
"""Main function to setup MetaTrader 5."""
45+
logger.info("Looking for MetaTrader 5 terminal...")
46+
terminal_path = find_mt5_terminal()
47+
48+
if not terminal_path:
49+
logger.error("Could not find MetaTrader 5 terminal. Please install it first.")
50+
sys.exit(1)
51+
52+
logger.info(f"Found MetaTrader 5 terminal at: {terminal_path}")
53+
54+
# Try to initialize MT5
55+
if not Mt5.initialize(path=terminal_path):
56+
logger.error(f"MetaTrader 5 initialization failed. Error code: {Mt5.last_error()}")
57+
sys.exit(1)
58+
59+
try:
60+
if check_trading_allowed():
61+
logger.info("Trading is already enabled!")
62+
else:
63+
logger.warning("\nTrading is not fully enabled. For CI environments, you need to:")
64+
logger.warning("1. Create a pre-configured terminal with these settings:")
65+
logger.warning(" - Tools -> Options -> Expert Advisors:")
66+
logger.warning(" - Enable 'Allow automated trading'")
67+
logger.warning(" - Enable 'Allow DLL imports'")
68+
logger.warning(" - Enable 'Allow WebRequest for listed URL'")
69+
logger.warning("\n2. Package the pre-configured terminal with your CI pipeline")
70+
logger.warning("3. Use the pre-configured terminal path in your tests")
71+
logger.warning("\nNote: These settings cannot be enabled programmatically")
72+
sys.exit(1)
73+
74+
# Test symbol selection
75+
symbol = "EURUSD"
76+
logger.info(f"\nTesting symbol selection with {symbol}...")
77+
if not Mt5.symbol_select(symbol, True):
78+
logger.error(f"Failed to select symbol {symbol}")
79+
sys.exit(1)
80+
81+
symbol_info = Mt5.symbol_info(symbol)
82+
if symbol_info is None:
83+
logger.error(f"Failed to get symbol info for {symbol}")
84+
sys.exit(1)
85+
86+
logger.info(f"Symbol {symbol} info:")
87+
logger.info(f"Trade mode: {symbol_info.trade_mode}")
88+
logger.info(f"Visible: {symbol_info.visible}")
89+
logger.info(f"Bid: {symbol_info.bid}")
90+
logger.info(f"Ask: {symbol_info.ask}")
91+
92+
finally:
93+
Mt5.shutdown()
94+
95+
if __name__ == "__main__":
96+
main()

tests/test_book.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def test_book_get(symbol: str) -> None:
6464
assert market_data is not None
6565

6666
if market_data:
67-
assert isinstance(market_data, list)
67+
assert isinstance(market_data, (list, tuple))
6868

6969
# Loop separately to check for bids and asks
7070
has_bids = False

0 commit comments

Comments
 (0)