Coverage for src/PythonMetaTrader5/adapters/mt5_mapping.py: 100%
20 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"""Translation between MetaTrader5's raw result objects and domain models.
3Split out of mt5_terminal.py (300-line limit). Pure functions: they read fields
4of MT5 objects but never call the terminal, so they need no session lock.
5"""
7from __future__ import annotations
9from typing import Any
11from PythonMetaTrader5.domain.market import PendingKind, PendingOrder, Position, TradeReceipt
12from PythonMetaTrader5.domain.orders import Side
14OrderTypes = dict[tuple[Side, PendingKind | None], int]
17def order_type_table(mt5: Any) -> OrderTypes:
18 return {
19 (Side.BUY, None): mt5.ORDER_TYPE_BUY,
20 (Side.SELL, None): mt5.ORDER_TYPE_SELL,
21 (Side.BUY, PendingKind.LIMIT): mt5.ORDER_TYPE_BUY_LIMIT,
22 (Side.SELL, PendingKind.LIMIT): mt5.ORDER_TYPE_SELL_LIMIT,
23 (Side.BUY, PendingKind.STOP): mt5.ORDER_TYPE_BUY_STOP,
24 (Side.SELL, PendingKind.STOP): mt5.ORDER_TYPE_SELL_STOP,
25 (Side.BUY, PendingKind.STOP_LIMIT): mt5.ORDER_TYPE_BUY_STOP_LIMIT,
26 (Side.SELL, PendingKind.STOP_LIMIT): mt5.ORDER_TYPE_SELL_STOP_LIMIT,
27 }
30def receipt(result: Any) -> TradeReceipt:
31 return TradeReceipt(
32 retcode=int(result.retcode),
33 deal=int(result.deal),
34 order=int(result.order),
35 volume=float(result.volume),
36 price=float(result.price),
37 bid=float(result.bid),
38 ask=float(result.ask),
39 comment=str(result.comment),
40 request_id=int(result.request_id),
41 retcode_external=int(result.retcode_external),
42 )
45def position(p: Any, position_buy: int) -> Position:
46 return Position(
47 ticket=int(p.ticket),
48 symbol=str(p.symbol),
49 side=Side.BUY if p.type == position_buy else Side.SELL,
50 volume=float(p.volume),
51 price_open=float(p.price_open),
52 # MT5 encodes "no stop" as 0.0, which is also a (useless) price.
53 sl=float(p.sl) or None,
54 tp=float(p.tp) or None,
55 price_current=float(p.price_current),
56 profit=float(p.profit),
57 time=int(p.time),
58 magic=int(p.magic),
59 comment=str(p.comment),
60 swap=float(p.swap),
61 identifier=int(p.identifier),
62 reason=int(p.reason),
63 time_msc=int(p.time_msc),
64 time_update=int(p.time_update),
65 time_update_msc=int(p.time_update_msc),
66 external_id=str(p.external_id),
67 )
70def pending_orders(
71 raw: tuple[Any, ...], by_type: dict[int, tuple[Side, PendingKind]]
72) -> list[PendingOrder]:
73 orders = []
74 for o in raw:
75 key = by_type.get(int(o.type))
76 # Market orders still being processed and close-by orders are not resting orders.
77 if key is None:
78 continue
79 side, kind = key
80 orders.append(
81 PendingOrder(
82 ticket=int(o.ticket),
83 symbol=str(o.symbol),
84 side=side,
85 kind=kind,
86 volume=float(o.volume_current),
87 price=float(o.price_open),
88 magic=int(o.magic),
89 comment=str(o.comment),
90 )
91 )
92 return orders