Coverage for src/PythonMetaTrader5/domain/symbol.py: 100%
87 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"""Instrument specification and the rules that depend only on it."""
3from __future__ import annotations
5import math
6from dataclasses import dataclass
7from enum import Enum
9from PythonMetaTrader5.domain.errors import ErrorKind, TradeError
10from PythonMetaTrader5.result import Err, Ok, Result
12# Bit flags of SYMBOL_FILLING_MODE as documented in MQL5. The Python package does
13# not export them, so they are defined here rather than guessed at call sites.
14_FILLING_FOK_FLAG = 1
15_FILLING_IOC_FLAG = 2
17# Tolerances for float checks: volumes are entered as decimal literals (0.07)
18# that are not exactly representable in binary floating point, so an exact
19# comparison would reject valid lots.
20_EPSILON = 1e-9
21_STEP_TOLERANCE = 1e-6
22# Volume precision sent to the server; well below any broker's volume_step.
23_VOLUME_DECIMALS = 8
26class Filling(Enum):
27 FOK = "fok"
28 IOC = "ioc"
29 RETURN = "return"
32@dataclass(frozen=True, slots=True)
33class SymbolSpec:
34 name: str
35 digits: int
36 point: float
37 tick_size: float
38 volume_min: float
39 volume_max: float
40 volume_step: float
41 filling_flags: int
42 # Required on purpose: a default would quietly treat an exchange symbol as
43 # market execution and send limits that cancel instead of resting.
44 exchange_execution: bool
46 # Broken terminal data (a point of 0 or inf, a NaN tick size, a volume step
47 # of 0) is reported as BROKEN_SYMBOL_DATA: it is the broker's fault, so a bot
48 # must not file it as a bad signal, nor resend as after a TERMINAL_ERROR.
49 # It is checked on use rather than refused for the whole spec, because
50 # closing a position needs only filling_flags and must keep working on such
51 # a symbol (a constructor invariant was tried and dropped for exactly that).
52 # Entries call check_tradable() first.
54 def check_tradable(self) -> Result[None, TradeError]:
55 problem = self._pricing_problem() or self._volume_problem()
56 return Ok(None) if problem is None else Err(self._data_error(problem))
58 def price_on_grid(self, price: float, kind: ErrorKind, what: str) -> Result[float, TradeError]:
59 """``price`` on the tick grid, refused if it is not a usable positive level.
61 Every caller-supplied level (an explicit entry price, sl, tp) goes through
62 here; quote prices come from the terminal already on the grid. The two
63 ways a positive finite input still goes wrong are checked once: 1e305 /
64 1e-5 overflows to inf (round(inf) raises), and 1e-6 snaps to 0.0, which
65 MT5 reads as "no stop" or "fill at the market".
66 """
67 problem = self._pricing_problem()
68 if problem is not None:
69 return Err(self._data_error(problem))
70 # A price must sit on the tick grid, not merely have `digits` decimals:
71 # index CFDs often have tick 0.25 with 2 digits and reject 5780.13.
72 step = self._step
73 if not math.isfinite(price / step):
74 return Err(TradeError(kind, f"{what} {price} is out of range for {self.name}"))
75 level = round(round(price / step) * step, self.digits)
76 if level <= 0:
77 return Err(TradeError(kind, f"{what} {price} snaps to {level} on {self.name}"))
78 return Ok(level)
80 def points_to_price(self, points: float) -> Result[float, TradeError]:
81 # Only points stops need `point`: a symbol with a valid tick size and a
82 # point of 0 still trades absolute prices.
83 if not _usable(self.point):
84 return Err(self._data_error(f"point {self.point!r} cannot measure a points stop"))
85 return Ok(points * self.point)
87 def validate_volume(self, volume: float) -> Result[float, TradeError]:
88 problem = self._volume_problem()
89 if problem is not None:
90 return Err(self._data_error(problem))
91 if volume < self.volume_min - _EPSILON or volume > self.volume_max + _EPSILON:
92 return Err(self._volume_error(volume, "outside"))
93 steps = (volume - self.volume_min) / self.volume_step
94 if abs(steps - round(steps)) > _STEP_TOLERANCE:
95 return Err(self._volume_error(volume, "not a multiple of the step within"))
96 snapped = self.volume_min + round(steps) * self.volume_step
97 return Ok(round(snapped, _VOLUME_DECIMALS))
99 @property
100 def _step(self) -> float:
101 # A tick size of 0 means the terminal did not report one; point is used.
102 return self.tick_size if self.tick_size > 0 else self.point
104 def _pricing_problem(self) -> str | None:
105 # Checked before _step is used: a NaN or negative tick size would
106 # otherwise fall back to point without anyone noticing.
107 if not (self.tick_size == 0 or _usable(self.tick_size)):
108 return f"tick size {self.tick_size!r} is neither 0 nor positive and finite"
109 if not _usable(self._step):
110 return f"no usable tick size or point (point {self.point!r})"
111 if self.digits < 0:
112 return f"digits {self.digits} is negative"
113 return None
115 def _volume_problem(self) -> str | None:
116 limits = (self.volume_min, self.volume_max, self.volume_step)
117 if not all(_usable(x) for x in limits):
118 return f"volume min/max/step {limits} are not all positive and finite"
119 if self.volume_max < self.volume_min:
120 return f"volume_max {self.volume_max} is below volume_min {self.volume_min}"
121 return None
123 def _data_error(self, problem: str) -> TradeError:
124 return TradeError(ErrorKind.BROKEN_SYMBOL_DATA, f"{self.name}: {problem}")
126 def market_filling(self) -> Filling:
127 # FOK first: a webhook bot asking for 1 lot must get 1 lot or nothing.
128 # IOC could silently leave it with a partial fill it never asked for.
129 if self.filling_flags & _FILLING_FOK_FLAG:
130 return Filling.FOK
131 if self.filling_flags & _FILLING_IOC_FLAG:
132 return Filling.IOC
133 return Filling.RETURN
135 def pending_filling(self) -> Filling:
136 # Exchange-execution symbols (stocks, futures) only let a limit rest in the
137 # book with RETURN; FOK/IOC there would cancel it unless instantly fillable.
138 # Elsewhere the market rule applies: RETURN is refused by many
139 # market-execution brokers (10030) that accepted the IOC sent by 2.x.
140 return Filling.RETURN if self.exchange_execution else self.market_filling()
142 def _volume_error(self, volume: float, reason: str) -> TradeError:
143 return TradeError(
144 ErrorKind.INVALID_VOLUME,
145 f"{self.name}: volume {volume} is {reason} "
146 f"[{self.volume_min}, {self.volume_max}] step {self.volume_step}",
147 )
150def _usable(value: float) -> bool:
151 # The type check keeps a hand-built spec (point=None, point=True) on the
152 # Result path instead of raising TypeError from math.isfinite.
153 return (
154 isinstance(value, (int, float))
155 and not isinstance(value, bool)
156 and math.isfinite(value)
157 and value > 0
158 )