Coverage for src/PythonMetaTrader5/application/ports.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-12 12:29 +0000

1"""The only two process boundaries of the library: the MT5 terminal and time.""" 

2 

3from __future__ import annotations 

4 

5import operator 

6from dataclasses import dataclass, field 

7from typing import Protocol 

8 

9from PythonMetaTrader5.domain.errors import TradeError 

10from PythonMetaTrader5.domain.market import PendingOrder, Position, Tick, TradeReceipt 

11from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest 

12from PythonMetaTrader5.domain.symbol import SymbolSpec 

13from PythonMetaTrader5.result import Result 

14 

15 

16@dataclass(frozen=True, slots=True) 

17class Credentials: 

18 login: int 

19 # repr=False keeps the password out of logs, tracebacks and debugger dumps. 

20 password: str = field(repr=False) 

21 server: str 

22 path: str | None = None 

23 timeout_ms: int = 60_000 

24 

25 def __post_init__(self) -> None: 

26 # The type itself enforces the login rule, so no construction path can 

27 # hand MT5 True or a float that it would turn into another account. 

28 if parse_login(self.login) != self.login: 

29 raise ValueError(f"login must be a positive integer, got {self.login!r}") 

30 

31 

32def parse_login(login: object) -> int | None: 

33 """Account number from an int-like value or an ASCII digit string, else None. 

34 

35 int() is deliberately avoided: int(True) == 1 and int(12345678.9) == 12345678 

36 would log into another account without any error, and int() accepts 

37 non-ASCII digits such as "\u0661\u0662\u0663". 

38 """ 

39 if isinstance(login, bool): 

40 return None 

41 if isinstance(login, str): 

42 text = login.strip() 

43 number = int(text) if text.isascii() and text.isdecimal() else 0 

44 else: 

45 try: 

46 number = operator.index(login) # type: ignore[arg-type] 

47 except TypeError: 

48 return None 

49 return number if number > 0 else None 

50 

51 

52class Terminal(Protocol): 

53 def connect(self, credentials: Credentials) -> Result[None, TradeError]: ... 

54 

55 def shutdown(self) -> None: ... 

56 

57 def symbol(self, name: str) -> Result[SymbolSpec, TradeError]: ... 

58 

59 def tick(self, name: str) -> Result[Tick, TradeError]: ... 

60 

61 def send(self, request: OrderRequest | CancelRequest) -> Result[TradeReceipt, TradeError]: 

62 """Err only when the request could not be delivered; broker refusals are receipts.""" 

63 ... 

64 

65 def positions( 

66 self, *, symbol: str | None = None, ticket: int | None = None 

67 ) -> Result[list[Position], TradeError]: ... 

68 

69 def pending_orders( 

70 self, *, symbol: str | None = None 

71 ) -> Result[list[PendingOrder], TradeError]: ... 

72 

73 

74class Clock(Protocol): 

75 def sleep(self, seconds: float) -> None: ...