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

83 statements  

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

1"""Validated entry parameters shared by market and pending entries. 

2 

3Split out of trader.py (300-line limit): this is the only place that turns raw 

4caller input into an entry request, so every check runs before any send. 

5""" 

6 

7from __future__ import annotations 

8 

9from dataclasses import dataclass 

10 

11from PythonMetaTrader5.application.ports import Terminal 

12from PythonMetaTrader5.domain.errors import ErrorKind, TradeError 

13from PythonMetaTrader5.domain.inputs import positive_number, stop_input 

14from PythonMetaTrader5.domain.market import PendingKind 

15from PythonMetaTrader5.domain.orders import Side, validate_comment 

16from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest 

17from PythonMetaTrader5.domain.stops import Stop, StopKind 

18from PythonMetaTrader5.domain.symbol import SymbolSpec 

19from PythonMetaTrader5.result import Err, Ok, Result 

20 

21StopInput = Stop | float | None 

22 

23 

24@dataclass(frozen=True, slots=True) 

25class Entry: 

26 spec: SymbolSpec 

27 side: Side 

28 volume: float 

29 comment: str 

30 stop_loss: Stop | None 

31 take_profit: Stop | None 

32 # The caller's price on the symbol's tick grid; None means "use the quote". 

33 price: float | None 

34 

35 def request( 

36 self, 

37 quote: float | None = None, 

38 *, 

39 pending: PendingKind | None, 

40 deviation: int, 

41 magic: int, 

42 ) -> Result[OrderRequest | CancelRequest, TradeError]: 

43 reference = self.price if self.price is not None else quote 

44 if reference is None: 

45 return Err(TradeError(ErrorKind.NO_PRICE, f"no price for {self.spec.name}")) 

46 spec, side = self.spec, self.side 

47 sl = self.stop_loss.stop_loss(side, reference, spec) if self.stop_loss else Ok(None) 

48 if isinstance(sl, Err): 

49 return sl 

50 tp = self.take_profit.take_profit(side, reference, spec) if self.take_profit else Ok(None) 

51 if isinstance(tp, Err): 

52 return tp 

53 return Ok( 

54 OrderRequest( 

55 symbol=spec.name, 

56 side=side, 

57 volume=self.volume, 

58 price=reference, 

59 filling=spec.market_filling() if pending is None else spec.pending_filling(), 

60 deviation=deviation, 

61 magic=magic, 

62 comment=self.comment, 

63 sl=sl.value, 

64 tp=tp.value, 

65 pending=pending, 

66 ) 

67 ) 

68 

69 

70def validate_entry( 

71 terminal: Terminal, 

72 symbol: str, 

73 side: Side | str, 

74 volume: float, 

75 *, 

76 comment: str | None, 

77 sl: StopInput, 

78 tp: StopInput, 

79 price: object = None, 

80 price_required: bool = False, 

81) -> Result[Entry, TradeError]: 

82 # Every check that needs no terminal, the price included, runs before the 

83 # symbol lookup, which costs a round trip and may add the symbol to Market 

84 # Watch. 

85 values = _caller_values(side, comment, sl, tp, price, price_required=price_required) 

86 if isinstance(values, Err): 

87 return values 

88 amount = positive_number(volume, ErrorKind.INVALID_VOLUME, "volume") 

89 if isinstance(amount, Err): 

90 return amount 

91 spec = _tradable_spec(terminal, symbol) 

92 if isinstance(spec, Err): 

93 return spec 

94 lots = spec.value.validate_volume(amount.value) 

95 if isinstance(lots, Err): 

96 return lots 

97 parsed_side, text, stop_loss, take_profit, level = values.value 

98 on_grid = _quote_free_levels(spec.value, level, stop_loss, take_profit) 

99 if isinstance(on_grid, Err): 

100 return on_grid 

101 return Ok( 

102 Entry(spec.value, parsed_side, lots.value, text, stop_loss, take_profit, on_grid.value) 

103 ) 

104 

105 

106def _tradable_spec(terminal: Terminal, symbol: str) -> Result[SymbolSpec, TradeError]: 

107 # Checked right after the lookup, before any caller value is judged against 

108 # the spec: broken broker data must not come back as the caller's 

109 # INVALID_VOLUME. It covers market orders without stops too, which never 

110 # reach price_on_grid. Closing never calls this. 

111 spec = terminal.symbol(symbol) 

112 if isinstance(spec, Err): 

113 return spec 

114 tradable = spec.value.check_tradable() 

115 return tradable if isinstance(tradable, Err) else spec 

116 

117 

118def _quote_free_levels( 

119 spec: SymbolSpec, price: float | None, sl: Stop | None, tp: Stop | None 

120) -> Result[float | None, TradeError]: 

121 # Absolute stops do not depend on the quote, so they are checked here, before 

122 # the first tick request: otherwise a stop that can never be valid would sit 

123 # through the NO_PRICE retries of a symbol without quotes first. 

124 # The price first, so a bad price is still reported before a bad stop. 

125 level = None if price is None else spec.price_on_grid(price, ErrorKind.INVALID_PRICE, "price") 

126 if isinstance(level, Err): 

127 return level 

128 for name, stop in (("sl", sl), ("tp", tp)): 

129 if stop is not None and stop.kind is StopKind.PRICE: 

130 checked = spec.price_on_grid(stop.value, ErrorKind.INVALID_STOPS, name) 

131 if isinstance(checked, Err): 

132 return checked 

133 return Ok(None if level is None else level.value) 

134 

135 

136def _caller_values( 

137 side: Side | str, 

138 comment: str | None, 

139 sl: StopInput, 

140 tp: StopInput, 

141 price: object, 

142 *, 

143 price_required: bool, 

144) -> Result[tuple[Side, str, Stop | None, Stop | None, float | None], TradeError]: 

145 parsed_side = Side.parse(side) 

146 if isinstance(parsed_side, Err): 

147 return parsed_side 

148 text = validate_comment(comment) 

149 if isinstance(text, Err): 

150 return text 

151 stop_loss, take_profit = stop_input(sl, "sl"), stop_input(tp, "tp") 

152 if isinstance(stop_loss, Err): 

153 return stop_loss 

154 if isinstance(take_profit, Err): 

155 return take_profit 

156 level = ( 

157 positive_number(price, ErrorKind.INVALID_PRICE, "price") 

158 if price is not None or price_required 

159 else Ok(None) 

160 ) 

161 if isinstance(level, Err): 

162 return level 

163 return Ok((parsed_side.value, text.value, stop_loss.value, take_profit.value, level.value))