Coverage for src/PythonMetaTrader5/adapters/mt5_session.py: 100%

23 statements  

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

1"""The one MetaTrader5 session of a process: how it is imported and locked. 

2 

3Shared by the adapter and the 2.x namespace re-export, so both import the 

4package the same way and every call through either holds the same lock. 

5""" 

6 

7from __future__ import annotations 

8 

9import functools 

10import importlib 

11import threading 

12from collections.abc import Callable 

13from types import ModuleType 

14from typing import ParamSpec, TypeVar 

15 

16# last_error() is process-global, so a call and the error read that explains it 

17# must not interleave with another thread's call. Module-level, not per adapter: 

18# connect() builds a new adapter each time, and every adapter and re-exported 

19# function in a process talks to the one MT5 session (ADR 0009). 

20SESSION = threading.RLock() 

21_P = ParamSpec("_P") 

22_R = TypeVar("_R") 

23 

24 

25def serialized(function: Callable[_P, _R]) -> Callable[_P, _R]: 

26 @functools.wraps(function) 

27 def locked(*args: _P.args, **kwargs: _P.kwargs) -> _R: 

28 with SESSION: 

29 return function(*args, **kwargs) 

30 

31 return locked 

32 

33 

34def import_metatrader5() -> ModuleType | None: 

35 """The MetaTrader5 module, or None when it is not installed. 

36 

37 Only "not installed" becomes None: it is the normal case outside Windows. A 

38 package that is installed but fails to import raises ImportError, whatever 

39 it raised itself: a numpy ABI mismatch can surface as ValueError or 

40 AttributeError, and an AttributeError leaking out of the package 

41 __getattr__ would read as "no such name" and silently empty the star import. 

42 """ 

43 try: 

44 return importlib.import_module("MetaTrader5") 

45 except Exception as error: 

46 if isinstance(error, ModuleNotFoundError) and error.name == "MetaTrader5": 

47 return None 

48 raise ImportError(f"MetaTrader5 is installed but cannot be imported: {error}") from error