Coverage for src/PythonMetaTrader5/domain/inputs.py: 100%

47 statements  

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

1"""Checks on raw caller input that MT5 would otherwise misread without an error. 

2 

3Webhook payloads arrive as loosely typed JSON. Each value below has a reading 

4in MT5 that is valid but almost never meant: ``sl=0`` is "no stop", 

5``ticket=0`` may be "no filter", ``volume=True`` is one lot. They are refused 

6here instead of being passed on. 

7""" 

8 

9from __future__ import annotations 

10 

11from dataclasses import replace 

12from enum import Enum 

13from numbers import Integral 

14from typing import Final 

15 

16from PythonMetaTrader5.domain.amounts import positive_float 

17from PythonMetaTrader5.domain.errors import ErrorKind, TradeError 

18from PythonMetaTrader5.domain.stops import Stop, StopKind 

19from PythonMetaTrader5.result import Err, Ok, Result 

20 

21 

22def positive_number(value: object, kind: ErrorKind, what: str) -> Result[float, TradeError]: 

23 number = positive_float(value) 

24 if number is None: 

25 return Err(TradeError(kind, f"{what} must be a positive finite number, got {value!r}")) 

26 return Ok(number) 

27 

28 

29def stop_input(value: object, what: str) -> Result[Stop | None, TradeError]: 

30 """``None`` means no stop; a float is a price; zero is refused, never "no stop".""" 

31 if value is None or isinstance(value, Stop): 

32 return Ok(value) # a Stop validated itself when it was built 

33 parsed = Stop.parse(value, StopKind.PRICE) 

34 if isinstance(parsed, Err): 

35 return Err(replace(parsed.error, message=f"{what}: {parsed.error.message}")) 

36 return Ok(parsed.value) 

37 

38 

39def ticket_filter(ticket: object) -> Result[int | None, TradeError]: 

40 if ticket is None: 

41 return Ok(None) 

42 if isinstance(ticket, bool) or not isinstance(ticket, Integral) or ticket <= 0: 

43 return Err( 

44 TradeError( 

45 ErrorKind.INVALID_ARGUMENT, f"ticket must be a positive integer, got {ticket!r}" 

46 ) 

47 ) 

48 return Ok(int(ticket)) 

49 

50 

51def symbol_filter(symbol: str | None) -> Result[str | None, TradeError]: 

52 # "" is rejected rather than passed on: a missing webhook field arrives as "" 

53 # and is easily mistaken for "no filter" (2.x and the first 3.0 draft both 

54 # dropped falsy filters), which would act on the whole account. 

55 if symbol == "": 

56 return Err(TradeError(ErrorKind.INVALID_ARGUMENT, "symbol must not be empty")) 

57 return Ok(symbol) 

58 

59 

60class AnyMagic(Enum): 

61 """The type of ``ANY_MAGIC``.""" 

62 

63 ANY = "any" 

64 

65 

66# A named value, not None: close-all and cancel-all default to the trader's own 

67# magic, and a None read from a missing config key must not widen them to the 

68# whole account (ADR 0011). 

69ANY_MAGIC: Final = AnyMagic.ANY 

70"""Pass as ``magic=`` to act on every magic number, manual trades included.""" 

71# MT5 stores magic as a ulong; a larger value would overflow in order_send. 

72_MAX_MAGIC: Final = 2**64 - 1 

73 

74 

75def magic_filter(magic: object) -> Result[int | AnyMagic | None, TradeError]: 

76 # "42" or True would match no position and report an empty success with 

77 # everything still open. 0 is valid: it is what manual trades carry. 

78 if magic is None or magic is ANY_MAGIC: 

79 return Ok(magic) 

80 if ( 

81 isinstance(magic, bool) 

82 or not isinstance(magic, Integral) 

83 or not 0 <= int(magic) <= _MAX_MAGIC 

84 ): 

85 return Err( 

86 TradeError( 

87 ErrorKind.INVALID_ARGUMENT, 

88 f"magic must be an integer from 0 to 2**64-1 or ANY_MAGIC, got {magic!r}", 

89 ) 

90 ) 

91 return Ok(int(magic)) 

92 

93 

94def own_magic(magic: object) -> Result[int, TradeError]: 

95 """The magic a trader stamps on its orders and closes by default.""" 

96 checked = magic_filter(magic) 

97 # None or ANY_MAGIC here would make the own-magic default mean "every magic", 

98 # and a missing config key would close the whole account (ADR 0011). One 

99 # message for every refusal: magic_filter's would suggest ANY_MAGIC. 

100 if isinstance(checked, Err) or not isinstance(checked.value, int): 

101 return Err( 

102 TradeError( 

103 ErrorKind.INVALID_ARGUMENT, 

104 f"the trader's own magic must be an integer from 0 to 2**64-1, got {magic!r}", 

105 ) 

106 ) 

107 return Ok(checked.value)