Coverage for src/PythonMetaTrader5/domain/orders.py: 100%
32 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-12 12:29 +0000
1"""Trade direction and the order requests sent through the terminal port."""
3from __future__ import annotations
5from enum import Enum
7from PythonMetaTrader5.domain.errors import ErrorKind, TradeError
8from PythonMetaTrader5.result import Err, Ok, Result
10_SIDE_ALIASES = {"buy": "BUY", "long": "BUY", "sell": "SELL", "short": "SELL"}
13class Side(Enum):
14 """Trade direction. Calls also accept ``"buy"``, ``"sell"``, ``"long"``, ``"short"``."""
16 BUY = "buy"
17 SELL = "sell"
19 @property
20 def opposite(self) -> Side:
21 """The side that closes a position of this side."""
22 return Side.SELL if self is Side.BUY else Side.BUY
24 @property
25 def sign(self) -> int:
26 """``1`` for BUY, ``-1`` for SELL: the direction in which profit grows."""
27 return 1 if self is Side.BUY else -1
29 @classmethod
30 def parse(cls, value: Side | str) -> Result[Side, TradeError]:
31 """A `Side`, or ``Err(INVALID_ARGUMENT)`` for an unknown name."""
32 if isinstance(value, Side):
33 return Ok(value)
34 name = _SIDE_ALIASES.get(str(value).strip().lower())
35 if name is None:
36 return Err(
37 TradeError(ErrorKind.INVALID_ARGUMENT, f"unknown side {value!r}; use buy/sell")
38 )
39 return Ok(cls[name])
42# Measured with order_check, not taken from the docs: MetaTrader5 5.0.6231
43# accepts 29 UTF-16 code units and refuses 30 with [-2] Invalid "comment"
44# argument before sending. The documented 31 would let 30-31 through to a
45# TERMINAL_ERROR that hides the cause, and trimming would change what the user
46# asked to store. tests/integration re-measures it when the package changes.
47MAX_COMMENT_LENGTH = 29
50def validate_comment(comment: object) -> Result[str, TradeError]:
51 if comment is None:
52 return Ok("")
53 # `comment or ""` would store 0 or False as an empty comment without a word.
54 if not isinstance(comment, str):
55 return Err(TradeError(ErrorKind.INVALID_ARGUMENT, f"comment must be text, not {comment!r}"))
56 # The package counts UTF-16 units, not len(): "\U0001f680" * 15 is refused.
57 # surrogatepass: the package accepts a lone surrogate (measured), so it is
58 # one unit here, not a UnicodeEncodeError.
59 units = len(comment.encode("utf-16-le", "surrogatepass")) // 2
60 if units > MAX_COMMENT_LENGTH:
61 return Err(
62 TradeError(
63 ErrorKind.INVALID_ARGUMENT,
64 f"comment is {units} UTF-16 units (characters outside the BMP, such as "
65 f"most emoji, count as 2; combined emoji more); "
66 f"the MetaTrader5 package accepts at most {MAX_COMMENT_LENGTH}",
67 )
68 )
69 return Ok(comment)