Coverage for src/PythonMetaTrader5/legacy/broker.py: 100%

152 statements  

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

1"""2.x `Broker` facade over the 3.x Trader. 

2 

3Names, arguments and return shapes follow 2.x so old scripts keep running. The 

4behaviour that made 2.x dangerous is NOT preserved: no endless retry loops and 

5no Ctrl+E keystrokes into whichever window has focus. See MIGRATION.md. 

6""" 

7 

8from __future__ import annotations 

9 

10import logging 

11import warnings 

12from typing import Any, ClassVar 

13 

14from PythonMetaTrader5.adapters.mt5_terminal import MetaTrader5Terminal 

15from PythonMetaTrader5.adapters.system_clock import SystemClock 

16from PythonMetaTrader5.application.ports import Clock, Credentials, Terminal, parse_login 

17from PythonMetaTrader5.application.trader import Trader 

18from PythonMetaTrader5.domain.errors import ErrorKind, TradeError 

19from PythonMetaTrader5.domain.inputs import ANY_MAGIC, positive_number 

20from PythonMetaTrader5.domain.market import PendingKind, TradeReceipt 

21from PythonMetaTrader5.domain.orders import Side 

22from PythonMetaTrader5.legacy import views 

23from PythonMetaTrader5.legacy.arguments import legacy_stop, no_ticket, number 

24from PythonMetaTrader5.legacy.views import LegacyReceipt 

25from PythonMetaTrader5.result import Err, Ok, Result 

26 

27log = logging.getLogger("PythonMetaTrader5.legacy") 

28 

29_RELOGIN_DELAY_SECONDS = 1.0 

30 

31 

32class Broker: 

33 """Deprecated 2.x API, kept so existing bots run; use `connect` instead. 

34 

35 Read the migration guide before upgrading a bot that trades real money. 

36 """ 

37 

38 RetCodes: ClassVar[dict[int, str]] = { 

39 10027: "Enable Algo Trading in MetaTrader5 app", 

40 10018: "Market closed", 

41 10016: "Wrong SL", 

42 } 

43 

44 def __init__( 

45 self, 

46 log: int | str, 

47 password: Any, 

48 server: Any, 

49 *, 

50 terminal: Terminal | None = None, 

51 clock: Clock | None = None, 

52 ) -> None: 

53 warnings.warn( 

54 "Broker is deprecated; use PythonMetaTrader5.connect() (see MIGRATION.md)", 

55 DeprecationWarning, 

56 stacklevel=2, 

57 ) 

58 self.log = log 

59 self.server = str(server) 

60 account = parse_login(log) 

61 if account is None: 

62 # Programming error, raised as 2.x did for non-numeric logins; silently 

63 # coercing True or 12345678.9 would trade on another account. 

64 raise ValueError(f"login must be a positive integer, got {log!r}") 

65 self._credentials = Credentials(account, str(password), self.server) 

66 self._clock = clock or SystemClock() 

67 self._terminal = terminal or _load_terminal() 

68 self._trader = Trader(self._terminal, self._clock) if self._terminal else None 

69 self._connected = self.login() 

70 

71 def login(self, ToEffect: bool = False) -> bool: 

72 """Log in once, or keep trying every second until it works when ``ToEffect``.""" 

73 if self._terminal is None: 

74 return False 

75 while True: 

76 result = self._terminal.connect(self._credentials) 

77 if isinstance(result, Ok): 

78 log.info("%s: logged in to %s", self.log, self.server) 

79 self._connected = True 

80 return True 

81 # The adapter released the session, so nothing may trade until a login works. 

82 self._connected = False 

83 log.error("%s: %s", self.log, result.error) 

84 if not ToEffect: 

85 return False 

86 self._clock.sleep(_RELOGIN_DELAY_SECONDS) 

87 

88 # ---------------------------------------------------------------- queries 

89 

90 def GetPositionsBySymbol(self, symbol: str, as_dict: bool = False) -> list[Any]: 

91 return self.GetPositions(symbol, as_dict=as_dict) 

92 

93 def GetPositions( 

94 self, symbol: str | None = None, *, ticket: int | None = None, as_dict: bool = False 

95 ) -> list[Any]: 

96 trader = self._ready() 

97 if trader is None: 

98 return [] 

99 # 2.x: a ticket selects that position whatever symbol was passed. 

100 listed = trader.positions(None if ticket is not None else symbol, ticket=ticket) 

101 if isinstance(listed, Err): 

102 log.error("%s: %s", self.log, listed.error) 

103 return [] 

104 convert = views.as_dict if as_dict else views.as_object 

105 return [convert(p) for p in listed.value] 

106 

107 def GetPosition( 

108 self, symbol: str | None = None, *, ticket: int | None = None, as_dict: bool = False 

109 ) -> Any: 

110 found = self.GetPositions(symbol, ticket=ticket, as_dict=as_dict) 

111 return found[0] if found else None 

112 

113 # ---------------------------------------------------------------- entries 

114 

115 def OpenPosition( 

116 self, 

117 symbol: str, 

118 side: str, 

119 volume: float, 

120 *, 

121 sl: float | None = None, 

122 tp: float | None = None, 

123 price: float | None = None, 

124 comment: str | None = None, 

125 ticket: int | None = None, 

126 sl_type: str = "absolute", 

127 tp_type: str = "absolute", 

128 ) -> LegacyReceipt | None: 

129 trader = self._ready() 

130 if trader is None or not no_ticket(ticket): 

131 return None 

132 stops = legacy_stop(number(sl), sl_type), legacy_stop(number(tp), tp_type) 

133 if any(isinstance(stop, Err) for stop in stops): 

134 return None 

135 stop_loss, take_profit = (s.value for s in stops if isinstance(s, Ok)) 

136 result = trader.open_position( 

137 symbol, 

138 side, 

139 number(volume), 

140 sl=stop_loss, 

141 tp=take_profit, 

142 price=number(price), 

143 comment=comment, 

144 ) 

145 return self._receipt(result, f"{side} {symbol}") 

146 

147 def Buy(self, symbol: str, volume: float, price: float | None = None, **kw: Any) -> Any: 

148 return self.OpenPosition(symbol, "buy", volume, price=price, **kw) 

149 

150 def BuySL( 

151 self, symbol: str, volume: float, sl: float, price: float | None = None, **kw: Any 

152 ) -> Any: 

153 return self.OpenPosition(symbol, "buy", volume, sl=sl, price=price, **kw) 

154 

155 def Sell(self, symbol: str, volume: float, price: float | None = None, **kw: Any) -> Any: 

156 return self.OpenPosition(symbol, "sell", volume, price=price, **kw) 

157 

158 def SellSL( 

159 self, symbol: str, volume: float, sl: float, price: float | None = None, **kw: Any 

160 ) -> Any: 

161 return self.OpenPosition(symbol, "sell", volume, sl=sl, price=price, **kw) 

162 

163 def BuyLimit( 

164 self, 

165 symbol: str, 

166 volume: float, 

167 stoplimit: float, 

168 price: float | None = None, 

169 comment: str | None = None, 

170 ticket: int | None = None, 

171 ) -> LegacyReceipt | None: 

172 return self._limit( 

173 Side.BUY, symbol, volume, stoplimit, price=price, comment=comment, ticket=ticket 

174 ) 

175 

176 def SellLimit( 

177 self, 

178 symbol: str, 

179 volume: float, 

180 stoplimit: float, 

181 price: float | None = None, 

182 comment: str | None = None, 

183 ticket: int | None = None, 

184 ) -> LegacyReceipt | None: 

185 return self._limit( 

186 Side.SELL, symbol, volume, stoplimit, price=price, comment=comment, ticket=ticket 

187 ) 

188 

189 # ------------------------------------------------------------------ exits 

190 

191 def Close( 

192 self, symbol: str | None, *, comment: str | None = None, ticket: int | None = None 

193 ) -> bool: 

194 """True when at least one position closed and none failed.""" 

195 trader = self._ready() 

196 if trader is None: 

197 return False 

198 if symbol is None and ticket is None: 

199 # 2.x crashed here without closing anything; 3.x would close the account. 

200 log.error("%s: Close needs a symbol or ticket", self.log) 

201 return False 

202 # 2.x closed every magic; the 3.x own-magic default would skip them. 

203 result = trader.close_positions(symbol, ticket=ticket, magic=ANY_MAGIC, comment=comment) 

204 if isinstance(result, Err): 

205 log.error("%s: closing %s: %s", self.log, symbol, result.error) 

206 return False 

207 if not result.value: 

208 log.info("%s: there are no positions to close on %s", self.log, symbol) 

209 return bool(result.value) 

210 

211 def CancelOrders(self, symbol: str) -> None: 

212 trader = self._ready() 

213 if trader is None: 

214 return 

215 if not symbol: 

216 # 2.x matched orders against the symbol and so cancelled nothing here. 

217 log.error("%s: CancelOrders needs a symbol", self.log) 

218 return 

219 # 2.x only ever cancelled limit orders; stop orders stay untouched. 

220 result = trader.cancel_pending_orders(symbol, magic=ANY_MAGIC, kind=PendingKind.LIMIT) 

221 if isinstance(result, Err): 

222 log.error("%s: cancelling orders on %s: %s", self.log, symbol, result.error) 

223 

224 def Disconnect(self) -> None: 

225 if self._trader is not None: 

226 self._trader.shutdown() 

227 self._connected = False 

228 log.info("Disconnected from MT5") 

229 

230 # ---------------------------------------------------------------- helpers 

231 

232 def _limit( 

233 self, 

234 side: Side, 

235 symbol: str, 

236 volume: float, 

237 stoplimit: float, 

238 *, 

239 price: float | None, 

240 comment: str | None, 

241 ticket: int | None, 

242 ) -> LegacyReceipt | None: 

243 trader = self._ready() 

244 if trader is None or self._terminal is None or not no_ticket(ticket): 

245 return None 

246 volume = number(volume) 

247 if price is not None: 

248 log.error("%s: price has to be None for limit orders", self.log) 

249 return None 

250 # Checked before the crossing test below: a level of 0 always "crosses" 

251 # for a sell and would become a market order. 

252 level = positive_number(number(stoplimit), ErrorKind.INVALID_PRICE, "stoplimit") 

253 if isinstance(level, Err): 

254 log.error("%s: %s", self.log, level.error) 

255 return None 

256 stoplimit = level.value 

257 tick = self._terminal.tick(symbol) 

258 if isinstance(tick, Err): 

259 log.error("%s: %s", self.log, tick.error) 

260 return None 

261 quote = tick.value.entry_price(side) 

262 # 2.x semantics: a limit already reached by the market is filled at market. 

263 crossed = quote <= stoplimit if side is Side.BUY else quote >= stoplimit 

264 if crossed: 

265 result = trader.open_position(symbol, side, volume, comment=comment) 

266 else: 

267 result = trader.place_limit_order(symbol, side, volume, stoplimit, comment=comment) 

268 return self._receipt(result, f"{side.value} limit {symbol} @ {stoplimit}") 

269 

270 def _ready(self) -> Trader | None: 

271 if self._trader is None or not self._connected: 

272 log.error("%s: not connected to MetaTrader 5; call login()", self.log) 

273 return None 

274 return self._trader 

275 

276 def _receipt(self, result: Result[TradeReceipt, TradeError], what: str) -> LegacyReceipt | None: 

277 if isinstance(result, Ok): 

278 log.info("%s: %s done", self.log, what) 

279 return views.as_receipt(result.value) 

280 log.error("%s: %s failed: %s", self.log, what, result.error) 

281 return views.as_receipt(result.error.receipt) 

282 

283 

284def _load_terminal() -> Terminal | None: 

285 loaded = MetaTrader5Terminal.load() 

286 if isinstance(loaded, Err): 

287 log.error("%s", loaded.error) 

288 return None 

289 return loaded.value