Coverage for src/PythonMetaTrader5/application/batch.py: 100%

31 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-12 12:29 +0000

1"""Applying one trade action to many positions/orders and reporting per item.""" 

2 

3from __future__ import annotations 

4 

5from collections.abc import Callable, Iterable 

6from dataclasses import dataclass, replace 

7from typing import Protocol, TypeVar 

8 

9from PythonMetaTrader5.domain.errors import TradeError 

10from PythonMetaTrader5.domain.inputs import ANY_MAGIC, AnyMagic 

11from PythonMetaTrader5.domain.market import TradeReceipt 

12from PythonMetaTrader5.result import Err, Ok, Result 

13 

14 

15class _Ticketed(Protocol): 

16 @property 

17 def ticket(self) -> int: ... 

18 

19 @property 

20 def magic(self) -> int: ... 

21 

22 

23_T = TypeVar("_T", bound=_Ticketed) 

24 

25 

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

27class BatchFailure: 

28 """Some items of a batch (close all / cancel all) failed; others may have succeeded.""" 

29 

30 succeeded: tuple[TradeReceipt, ...] 

31 errors: tuple[TradeError, ...] 

32 

33 def __str__(self) -> str: 

34 return f"{len(self.errors)} failed, {len(self.succeeded)} succeeded: " + "; ".join( 

35 str(e) for e in self.errors 

36 ) 

37 

38 

39def run_batch( 

40 items: Iterable[_T], action: Callable[[_T], Result[TradeReceipt, TradeError]] 

41) -> Result[list[TradeReceipt], BatchFailure]: 

42 # Every item is attempted even after a failure: stopping at the first error 

43 # would leave the remaining positions open while reporting only one problem. 

44 succeeded: list[TradeReceipt] = [] 

45 errors: list[TradeError] = [] 

46 for item in items: 

47 # isinstance, not a match without a fallback: an action that broke the 

48 # Result contract fails loudly on `.value` instead of being skipped, 

49 # which would end in Ok([]), read as "all closed". 

50 result = action(item) 

51 if isinstance(result, Err): 

52 errors.append(replace(result.error, ticket=item.ticket)) 

53 else: 

54 succeeded.append(result.value) 

55 if errors: 

56 return Err(BatchFailure(tuple(succeeded), tuple(errors))) 

57 return Ok(succeeded) 

58 

59 

60def with_magic(items: list[_T], magic: int | AnyMagic | None) -> list[_T]: 

61 if magic is None or magic is ANY_MAGIC: 

62 return items 

63 return [item for item in items if item.magic == magic]