Coverage for src/PythonMetaTrader5/application/execution.py: 100%
47 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"""Sending a request with a bounded, outcome-aware retry loop."""
3from __future__ import annotations
5import logging
6from collections.abc import Callable
7from dataclasses import dataclass, replace
9from PythonMetaTrader5.application.ports import Clock, Terminal
10from PythonMetaTrader5.domain.errors import ErrorKind, TradeError
11from PythonMetaTrader5.domain.market import TradeReceipt
12from PythonMetaTrader5.domain.requests import CancelRequest, OrderRequest
13from PythonMetaTrader5.domain.retcodes import DONE, DONE_PARTIAL, Outcome, classify, error_for
14from PythonMetaTrader5.result import Err, Ok, Result
16log = logging.getLogger("PythonMetaTrader5")
18RequestFactory = Callable[[], Result[OrderRequest | CancelRequest, TradeError]]
21@dataclass(frozen=True, slots=True)
22class RetryPolicy:
23 """How often a request the server provably did not execute is retried.
25 That is a requote, a price change, no quotes or too many requests, each
26 answered with a fresh quote, and a missing quote before sending.
28 Raises ``ValueError`` for fewer than one attempt or a negative delay.
29 Timeouts and lost connections are never retried, whatever the policy.
30 """
32 attempts: int = 3
33 delay_seconds: float = 0.5
35 def __post_init__(self) -> None:
36 # Misconfiguration is a programming error, not a market outcome, so it
37 # fails loudly at construction instead of travelling as a Result.
38 if self.attempts < 1 or self.delay_seconds < 0:
39 raise ValueError(f"invalid retry policy: {self}")
42def execute(
43 terminal: Terminal, clock: Clock, build: RequestFactory, policy: RetryPolicy
44) -> Result[TradeReceipt, TradeError]:
45 """Rebuild and send the request until it succeeds, fails, or attempts run out.
47 The request is rebuilt on every attempt so a requote is answered with the
48 current price instead of re-sending the stale one.
49 """
50 last: TradeReceipt | None = None
51 for attempt in range(1, policy.attempts + 1):
52 request = build()
53 if isinstance(request, Err):
54 # Nothing was sent, so waiting is safe; a symbol just added to Market
55 # Watch typically has no quote for the first few hundred milliseconds.
56 if request.error.kind is ErrorKind.NO_PRICE and attempt < policy.attempts:
57 clock.sleep(policy.delay_seconds)
58 continue
59 return request
60 sent = terminal.send(request.value)
61 if isinstance(sent, Err):
62 return sent
63 last = sent.value
64 outcome = classify(last.retcode)
65 if outcome is Outcome.SUCCESS:
66 return _confirm(request.value, last)
67 if outcome is Outcome.FAIL:
68 return Err(replace(error_for(last.retcode), receipt=last))
69 log.warning("retcode %s on attempt %s/%s", last.retcode, attempt, policy.attempts)
70 if attempt < policy.attempts:
71 clock.sleep(policy.delay_seconds)
72 if last is None: # pragma: no cover - range(1, attempts + 1) is never empty
73 raise AssertionError("retry loop ran zero times")
74 return Err(
75 TradeError(
76 ErrorKind.RETRIES_EXHAUSTED,
77 f"gave up after {policy.attempts} attempts: {error_for(last.retcode).message}",
78 retcode=last.retcode,
79 receipt=last,
80 )
81 )
84def _confirm(
85 request: OrderRequest | CancelRequest, receipt: TradeReceipt
86) -> Result[TradeReceipt, TradeError]:
87 """Only DONE proves a market deal (entry or close) executed in full.
89 PARTIAL leaves volume unfilled (an entry is smaller than asked, a close leaves
90 a remainder open) and PLACED means queued, not executed. Both come back as
91 errors carrying the receipt, and neither is retried: part of the deal may
92 already exist, so re-sending could double it.
93 """
94 if (
95 not isinstance(request, OrderRequest)
96 or request.pending is not None
97 or receipt.retcode == DONE
98 ):
99 return Ok(receipt)
100 if receipt.retcode == DONE_PARTIAL:
101 return Err(
102 TradeError(
103 ErrorKind.PARTIAL_FILL,
104 f"executed {receipt.volume} of {request.volume} lots; with RETURN "
105 "filling the rest may still be working as an order",
106 retcode=receipt.retcode,
107 receipt=receipt,
108 )
109 )
110 return Err(
111 TradeError(
112 ErrorKind.OUTCOME_UNKNOWN,
113 "accepted but not executed yet; check positions before re-sending",
114 retcode=receipt.retcode,
115 receipt=receipt,
116 )
117 )