Coverage for src/PythonMetaTrader5/domain/stops.py: 100%
52 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"""Stop-loss / take-profit given either as a price or as a distance in points."""
3from __future__ import annotations
5from dataclasses import dataclass
6from enum import Enum
8from PythonMetaTrader5.domain.amounts import positive_float
9from PythonMetaTrader5.domain.errors import ErrorKind, TradeError
10from PythonMetaTrader5.domain.orders import Side
11from PythonMetaTrader5.domain.symbol import SymbolSpec
12from PythonMetaTrader5.result import Err, Ok, Result
15class StopKind(Enum):
16 """How a `Stop` value is read: an absolute price or a distance in points."""
18 PRICE = "price"
19 POINTS = "points"
22@dataclass(frozen=True, slots=True)
23class Stop:
24 """A stop-loss or take-profit level, as a price or as a distance in points.
26 Build one with `Stop.at_price`, `Stop.points` or, for a value that may be
27 bad at runtime, `Stop.parse`. A stop of zero, a negative price or a value
28 that is not finite cannot exist: MT5 would read 0 as "no stop".
29 """
31 value: float
32 kind: StopKind
34 def __post_init__(self) -> None:
35 # The invariant lives here, so every Stop is valid wherever it is built.
36 # Raised, not returned: a Stop of 0 cannot exist (MT5 would read it as "no
37 # stop"). Code holding a value that may be bad (an ATR that is NaN during
38 # warm-up) uses Stop.parse, which returns a Result instead.
39 parsed = _checked(self.value, self.kind)
40 if isinstance(parsed, Err):
41 raise ValueError(parsed.error.message)
42 object.__setattr__(self, "value", parsed.value)
44 @classmethod
45 def parse(cls, value: object, kind: StopKind) -> Result[Stop, TradeError]:
46 """Build a stop, or return ``Err(INVALID_STOPS)`` for a bad value instead of raising.
48 A ``kind`` that is not a `StopKind` is a programming error and still
49 raises ``TypeError``.
50 """
51 checked = _checked(value, kind)
52 if isinstance(checked, Err):
53 return checked
54 return Ok(cls(checked.value, kind))
56 @classmethod
57 def at_price(cls, price: float) -> Stop:
58 """A stop at an absolute ``price``; raises ``ValueError`` unless positive and finite."""
59 return cls(price, StopKind.PRICE)
61 @classmethod
62 def points(cls, distance: float) -> Stop:
63 """A stop ``distance`` points from the entry price; the sign is ignored.
65 Raises ``ValueError`` for zero or a value that is not finite; use
66 `Stop.parse` for a value that may be bad at runtime.
67 """
68 return cls(distance, StopKind.POINTS)
70 def stop_loss(
71 self, side: Side, reference: float, spec: SymbolSpec
72 ) -> Result[float, TradeError]:
73 """The stop-loss price for a ``side`` trade entered at ``reference``, on the tick grid."""
74 return self._resolve(-side.sign, reference, spec, "sl")
76 def take_profit(
77 self, side: Side, reference: float, spec: SymbolSpec
78 ) -> Result[float, TradeError]:
79 """The take-profit price for a ``side`` trade entered at ``reference``, on the tick grid."""
80 return self._resolve(side.sign, reference, spec, "tp")
82 def _resolve(
83 self, direction: int, reference: float, spec: SymbolSpec, what: str
84 ) -> Result[float, TradeError]:
85 # Resolved without a sign check here: price_on_grid is the single place a
86 # level below zero (a long points distance) or off the grid is refused.
87 level = self.value
88 if self.kind is StopKind.POINTS:
89 distance = spec.points_to_price(self.value)
90 if isinstance(distance, Err):
91 return distance
92 level = reference + direction * distance.value
93 return spec.price_on_grid(level, ErrorKind.INVALID_STOPS, what)
96def _checked(value: object, kind: StopKind) -> Result[float, TradeError]:
97 # A wrong kind is a programming error, raised for every value alike (also by
98 # Stop.parse), rather than read as a price.
99 if not isinstance(kind, StopKind):
100 raise TypeError(f"kind must be a StopKind, got {kind!r}")
101 # A points distance drops its sign: direction comes from the trade side, so
102 # `-1000` and `1000` both mean "1000 points on the losing side".
103 number = positive_float(value, unsigned=kind is StopKind.POINTS)
104 if number is None:
105 message = f"{kind.value} stop must be a positive finite number, got {value!r}"
106 return Err(TradeError(ErrorKind.INVALID_STOPS, message))
107 return Ok(number)