Coverage for src/PythonMetaTrader5/adapters/mt5_terminal.py: 100%
114 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"""Terminal port implemented with the official `MetaTrader5` package.
3This is the only module that knows MT5's request dictionaries, numeric order
4types and the shape of its result objects.
5"""
7from __future__ import annotations
9import math
10from typing import Any
12from PythonMetaTrader5.adapters import mt5_mapping
13from PythonMetaTrader5.adapters.mt5_session import import_metatrader5, serialized
14from PythonMetaTrader5.application.ports import Credentials
15from PythonMetaTrader5.domain.errors import ErrorKind, TradeError
16from PythonMetaTrader5.domain.market import PendingOrder, Position, Tick, TradeReceipt
17from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest
18from PythonMetaTrader5.domain.symbol import Filling, SymbolSpec
19from PythonMetaTrader5.result import Err, Ok, Result
21# last_error() codes for which order_send provably never left this process
22# (bad arguments, no IPC link, terminal refused). Any other failure (send,
23# receive, timeout) may have reached the server, so its outcome is unknown.
24_NOT_SENT_CODES = (
25 "RES_E_INVALID_PARAMS",
26 "RES_E_NO_MEMORY",
27 "RES_E_NOT_FOUND",
28 "RES_E_INVALID_VERSION",
29 "RES_E_AUTH_FAILED",
30 "RES_E_UNSUPPORTED",
31 "RES_E_INTERNAL_FAIL_INIT",
32 "RES_E_INTERNAL_FAIL_CONNECT",
33)
36class MetaTrader5Terminal:
37 def __init__(self, mt5: Any) -> None:
38 # `Any`: the MetaTrader5 package ships no type information.
39 self._mt5 = mt5
40 self._order_types = mt5_mapping.order_type_table(mt5)
41 self._pending_by_type = {
42 code: (side, kind)
43 for (side, kind), code in self._order_types.items()
44 if kind is not None
45 }
46 self._fillings = {
47 Filling.FOK: mt5.ORDER_FILLING_FOK,
48 Filling.IOC: mt5.ORDER_FILLING_IOC,
49 Filling.RETURN: mt5.ORDER_FILLING_RETURN,
50 }
51 # Every constant is read here, not at first use, so building the adapter
52 # against a new MetaTrader5 release fails at once if one was renamed.
53 self._deal = mt5.TRADE_ACTION_DEAL
54 self._pending = mt5.TRADE_ACTION_PENDING
55 self._remove = mt5.TRADE_ACTION_REMOVE
56 self._good_till_cancel = mt5.ORDER_TIME_GTC
57 self._position_buy = mt5.POSITION_TYPE_BUY
58 self._exchange_execution = mt5.SYMBOL_TRADE_EXECUTION_EXCHANGE
59 self._not_sent = frozenset(getattr(mt5, name) for name in _NOT_SENT_CODES)
60 self._auto_trading_disabled = mt5.RES_E_AUTO_TRADING_DISABLED
61 # MT5 reports "nothing found" and "call failed" both as None; only a
62 # last_error() of RES_S_OK tells "nothing found" apart.
63 self._ok = mt5.RES_S_OK
65 @classmethod
66 def load(cls) -> Result[MetaTrader5Terminal, TradeError]:
67 try:
68 module = import_metatrader5()
69 except ImportError as error:
70 # import_metatrader5 already says "installed but cannot be imported".
71 return Err(TradeError(ErrorKind.CONNECTION_FAILED, str(error)))
72 if module is None:
73 return Err(
74 TradeError(
75 ErrorKind.CONNECTION_FAILED,
76 "the MetaTrader5 package is not installed (it is available on Windows only)",
77 )
78 )
79 return Ok(cls(module))
81 @serialized
82 def connect(self, credentials: Credentials) -> Result[None, TradeError]:
83 args = (credentials.path,) if credentials.path else ()
84 if self._mt5.initialize(
85 *args,
86 login=credentials.login,
87 password=credentials.password,
88 server=credentials.server,
89 timeout=credentials.timeout_ms,
90 ):
91 return Ok(None)
92 error = self._last_error()
93 # Always released: MT5 has one session per process, so after a failed login
94 # it is unusable for everyone, and a half-open one makes every later
95 # initialize() fail (login(ToEffect=True) could never recover). A per-adapter
96 # "keep the live session" flag was tried and dropped: connect() builds a
97 # new adapter each time, so the flag protected nothing.
98 self._mt5.shutdown()
99 return Err(
100 TradeError(
101 ErrorKind.CONNECTION_FAILED,
102 f"login {credentials.login}@{credentials.server} failed: {error}",
103 )
104 )
106 @serialized
107 def shutdown(self) -> None:
108 self._mt5.shutdown()
110 @serialized
111 def symbol(self, name: str) -> Result[SymbolSpec, TradeError]:
112 info = self._mt5.symbol_info(name)
113 if info is None:
114 return Err(TradeError(ErrorKind.SYMBOL_NOT_FOUND, f"unknown symbol {name!r}"))
115 # Hidden symbols have no quotes; 2.x left users to fix Market Watch by hand.
116 if not info.visible and not self._mt5.symbol_select(name, True):
117 return Err(
118 TradeError(
119 ErrorKind.SYMBOL_NOT_FOUND,
120 f"{name!r} cannot be added to Market Watch: {self._last_error()}",
121 )
122 )
123 return Ok(
124 SymbolSpec(
125 name=info.name,
126 digits=int(info.digits),
127 point=float(info.point),
128 tick_size=float(info.trade_tick_size),
129 volume_min=float(info.volume_min),
130 volume_max=float(info.volume_max),
131 volume_step=float(info.volume_step),
132 filling_flags=int(info.filling_mode),
133 exchange_execution=int(info.trade_exemode) == self._exchange_execution,
134 )
135 )
137 @serialized
138 def tick(self, name: str) -> Result[Tick, TradeError]:
139 tick = self._mt5.symbol_info_tick(name)
140 # A zero side means no quote yet; trading at price 0 must never be attempted.
141 # NaN and inf are refused too: `nan <= 0` is False and would send price NaN.
142 if tick is None or not all(math.isfinite(p) and p > 0 for p in (tick.bid, tick.ask)):
143 return Err(TradeError(ErrorKind.NO_PRICE, f"no quote for {name!r}"))
144 return Ok(Tick(bid=float(tick.bid), ask=float(tick.ask)))
146 @serialized
147 def send(self, request: OrderRequest | CancelRequest) -> Result[TradeReceipt, TradeError]:
148 payload = self._payload(request)
149 result = self._mt5.order_send(payload)
150 if result is None:
151 return Err(self._send_failure())
152 return Ok(mt5_mapping.receipt(result))
154 @serialized
155 def positions(
156 self, *, symbol: str | None = None, ticket: int | None = None
157 ) -> Result[list[Position], TradeError]:
158 query: dict[str, object] = {}
159 if ticket is not None:
160 query["ticket"] = ticket
161 elif symbol is not None:
162 query["symbol"] = symbol
163 raw = self._listing(self._mt5.positions_get(**query), "positions_get")
164 if isinstance(raw, Err):
165 return raw
166 found = [mt5_mapping.position(p, self._position_buy) for p in raw.value]
167 # MT5 ignores `symbol` once `ticket` is given; the port promises both apply.
168 return Ok([p for p in found if symbol is None or p.symbol == symbol])
170 @serialized
171 def pending_orders(
172 self, *, symbol: str | None = None
173 ) -> Result[list[PendingOrder], TradeError]:
174 query = {"symbol": symbol} if symbol is not None else {}
175 raw = self._listing(self._mt5.orders_get(**query), "orders_get")
176 if isinstance(raw, Err):
177 return raw
178 return Ok(mt5_mapping.pending_orders(raw.value, self._pending_by_type))
180 # ------------------------------------------------------------------ helpers
182 def _payload(self, request: OrderRequest | CancelRequest) -> dict[str, Any]:
183 if isinstance(request, CancelRequest):
184 return {"action": self._remove, "order": request.order}
185 payload: dict[str, Any] = {
186 "action": self._deal if request.pending is None else self._pending,
187 "symbol": request.symbol,
188 "volume": request.volume,
189 "type": self._order_types[(request.side, request.pending)],
190 "price": request.price,
191 "deviation": request.deviation,
192 "magic": request.magic,
193 "comment": request.comment,
194 "type_filling": self._fillings[request.filling],
195 "type_time": self._good_till_cancel,
196 }
197 optional = {"sl": request.sl, "tp": request.tp, "position": request.position}
198 payload.update({key: value for key, value in optional.items() if value is not None})
199 return payload
201 def _listing(self, raw: Any, call: str) -> Result[tuple[Any, ...], TradeError]:
202 if raw is not None:
203 return Ok(tuple(raw))
204 code, _ = self._mt5.last_error()
205 if code == self._ok:
206 return Ok(())
207 return Err(TradeError(ErrorKind.TERMINAL_ERROR, f"{call} failed: {self._last_error()}"))
209 def _send_failure(self) -> TradeError:
210 code, text = self._error()
211 if code == self._auto_trading_disabled:
212 kind = ErrorKind.ALGO_TRADING_DISABLED
213 elif code in self._not_sent:
214 kind = ErrorKind.TERMINAL_ERROR
215 else:
216 kind = ErrorKind.OUTCOME_UNKNOWN
217 return TradeError(kind, f"order_send failed: {text}")
219 def _last_error(self) -> str:
220 return self._error()[1]
222 def _error(self) -> tuple[int, str]:
223 code, message = self._mt5.last_error()
224 return code, f"[{code}] {message}"