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

1"""Read models returned by the terminal: quotes, positions, orders, receipts.""" 

2 

3from __future__ import annotations 

4 

5from dataclasses import asdict, dataclass 

6from enum import Enum 

7from typing import Any 

8 

9from PythonMetaTrader5.domain.orders import Side 

10 

11 

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

13class Tick: 

14 """The current quote of a symbol.""" 

15 

16 bid: float 

17 ask: float 

18 

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 

22 

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) 

27 

28 

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

30class Position: 

31 """An open position. ``sl`` and ``tp`` are ``None`` when not set.""" 

32 

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 

55 

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 

61 

62 

63class PendingKind(Enum): 

64 """The type of a pending order.""" 

65 

66 LIMIT = "limit" 

67 STOP = "stop" 

68 STOP_LIMIT = "stop_limit" 

69 

70 

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

72class PendingOrder: 

73 """A pending order waiting on the server.""" 

74 

75 ticket: int 

76 symbol: str 

77 side: Side 

78 kind: PendingKind 

79 volume: float 

80 price: float 

81 magic: int 

82 comment: str 

83 

84 

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

86class TradeReceipt: 

87 """Broker answer to a trade request. 

88 

89 Field names mirror MetaTrader5's ``OrderSendResult`` on purpose, so 2.x code 

90 reading ``result.retcode`` / ``result.comment`` keeps working unchanged. 

91 """ 

92 

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