Coverage for src/PythonMetaTrader5/domain/market.py: 100%
64 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"""Read models returned by the terminal: quotes, positions, orders, receipts."""
3from __future__ import annotations
5from dataclasses import asdict, dataclass
6from enum import Enum
7from typing import Any
9from PythonMetaTrader5.domain.orders import Side
12@dataclass(frozen=True, slots=True)
13class Tick:
14 """The current quote of a symbol."""
16 bid: float
17 ask: float
19 def entry_price(self, side: Side) -> float:
20 """The price a market order on ``side`` fills at: ask to buy, bid to sell."""
21 return self.ask if side is Side.BUY else self.bid
23 def exit_price(self, side: Side) -> float:
24 """The price that closes a ``side`` position: bid for a long, ask for a short."""
25 # Closing a long sells at bid, closing a short buys at ask.
26 return self.entry_price(side.opposite)
29@dataclass(frozen=True, slots=True)
30class Position:
31 """An open position. ``sl`` and ``tp`` are ``None`` when not set."""
33 ticket: int
34 symbol: str
35 side: Side
36 volume: float
37 price_open: float
38 sl: float | None
39 tp: float | None
40 price_current: float
41 profit: float
42 time: int
43 magic: int
44 comment: str
45 # Kept although the 3.x API does not use them: 2.x returned the raw MT5
46 # object, so its users may read any of them (swap for P&L, identifier on
47 # netting accounts).
48 swap: float
49 identifier: int
50 reason: int
51 time_msc: int
52 time_update: int
53 time_update_msc: int
54 external_id: str
56 def to_dict(self) -> dict[str, Any]:
57 """The fields as a dict, with ``side`` as its string value."""
58 data = asdict(self)
59 data["side"] = self.side.value
60 return data
63class PendingKind(Enum):
64 """The type of a pending order."""
66 LIMIT = "limit"
67 STOP = "stop"
68 STOP_LIMIT = "stop_limit"
71@dataclass(frozen=True, slots=True)
72class PendingOrder:
73 """A pending order waiting on the server."""
75 ticket: int
76 symbol: str
77 side: Side
78 kind: PendingKind
79 volume: float
80 price: float
81 magic: int
82 comment: str
85@dataclass(frozen=True, slots=True)
86class TradeReceipt:
87 """Broker answer to a trade request.
89 Field names mirror MetaTrader5's ``OrderSendResult`` on purpose, so 2.x code
90 reading ``result.retcode`` / ``result.comment`` keeps working unchanged.
91 """
93 retcode: int
94 deal: int
95 order: int
96 volume: float
97 price: float
98 bid: float
99 ask: float
100 comment: str
101 request_id: int
102 retcode_external: int