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

29 statements  

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

1"""Which magic a close-all / cancel-all acts on when the caller gives none (ADR 0011). 

2 

3Kept apart from Trader: the rule and the warnings it owes are one decision, 

4and they would otherwise push trader.py past the file-length limit. 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10from collections.abc import Callable 

11from typing import TypeVar 

12 

13from PythonMetaTrader5.domain.errors import TradeError 

14from PythonMetaTrader5.domain.inputs import ANY_MAGIC, AnyMagic, magic_filter 

15from PythonMetaTrader5.result import Ok, Result 

16 

17log = logging.getLogger("PythonMetaTrader5") 

18_T = TypeVar("_T") 

19 

20 

21def resolve( 

22 own: int, magic: int | AnyMagic | None, ticket: int | None 

23) -> Result[int | AnyMagic, TradeError]: 

24 """The magic to filter by: the caller's, else the trader's own.""" 

25 checked = magic_filter(magic) 

26 if not isinstance(checked, Ok): 

27 return checked 

28 if checked.value is not None: 

29 return Ok(checked.value) 

30 # A named ticket is explicit intent: filtering it out by magic would 

31 # report Ok([]) for a position the caller asked to close. 

32 return Ok(ANY_MAGIC if ticket is not None else own) 

33 

34 

35def warn_about_default( 

36 own: int, 

37 magic: object, 

38 ticket: int | None, 

39 matched: list[_T], 

40 everything: Callable[[], Result[list[_T], TradeError]], 

41) -> None: 

42 """Say what the own-magic default cannot know; quiet once a magic is given.""" 

43 if magic is not None or ticket is not None: 

44 return 

45 if matched: 

46 if own == 0: 

47 # magic 0 stays allowed (it is the connect() default), but then 

48 # "own" includes every manual trade. 

49 log.warning( 

50 "trader magic is 0, which manual trades share: this close/cancel " 

51 "includes them; set magic at connect(), or pass magic=0 to confirm" 

52 ) 

53 return 

54 # Matched nothing: on netting the bot's deal may have merged into a position 

55 # that kept another magic, and Ok([]) alone would read as "flat". The extra 

56 # listing runs only on this path. 

57 others = everything() 

58 if not isinstance(others, Ok): 

59 # Not turned into an Err: the close/cancel itself did what was asked, 

60 # and failing it would make a bot retry an action that already ran. 

61 log.warning( 

62 "nothing with magic %s to close/cancel, and could not check for items " 

63 "with other magics left open: %s", 

64 own, 

65 others.error, 

66 ) 

67 return 

68 if others.value: 

69 log.warning( 

70 "nothing with magic %s to close/cancel; %d item(s) with other magics " 

71 "left open (on netting a deal merges into a position that keeps its " 

72 "first magic); pass magic=ANY_MAGIC to include them", 

73 own, 

74 len(others.value), 

75 )