Coverage for src/copytrading_engine/execution/domain/positions.py: 97%

45 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Compare broker holdings with filled lots, allowing only known in-flight fills.""" 

2 

3from collections import defaultdict 

4from collections.abc import Iterable, Mapping 

5from dataclasses import dataclass 

6from decimal import Decimal 

7 

8from copytrading_engine.execution.domain.market import Position 

9from copytrading_engine.execution.domain.orders import OrderRecord, OwnedLot 

10from copytrading_engine.execution.domain.ownership import ExternalPosition 

11 

12# The most of a coin's buy CopyTrading takes as Alpaca's fee when it counts the fee from the 

13# holding: Alpaca's highest rate is 0.25% (crypto fee tier 1, taker), so 1% is room to spare. 

14CRYPTO_FEE_CEILING = Decimal("0.01") 

15 

16 

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

18class PositionComparison: 

19 symbol: str 

20 expected: Decimal 

21 actual: Decimal 

22 minimum: Decimal 

23 maximum: Decimal 

24 

25 @property 

26 def mismatched(self) -> bool: 

27 return not self.minimum <= self.actual <= self.maximum 

28 

29 

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

31class PositionAudit: 

32 positions: tuple[PositionComparison, ...] 

33 

34 @property 

35 def matched(self) -> bool: 

36 return all(p.actual == p.expected for p in self.positions) 

37 

38 def health(self) -> dict: 

39 return { 

40 "status": "matched" 

41 if self.matched 

42 else ("mismatch" if any(p.mismatched for p in self.positions) else "reconciling"), 

43 "differences": [ 

44 { 

45 "symbol": p.symbol, 

46 "expected_qty": str(p.expected), 

47 "broker_qty": str(p.actual), 

48 "pending_fill_possible": not p.mismatched, 

49 } 

50 for p in self.positions 

51 if p.actual != p.expected 

52 ], 

53 } 

54 

55 

56def expected_holdings( 

57 lots: Iterable[OwnedLot], external: Iterable[ExternalPosition] 

58) -> dict[str, Decimal]: 

59 """The shares the broker should hold of each stock: what the copied lots have left plus the 

60 owner's own. Stocks with none are left out. Every check of the broker's count uses this.""" 

61 expected: dict[str, Decimal] = defaultdict(Decimal) 

62 for lot in lots: 

63 expected[lot.symbol] += lot.remaining_qty 

64 for holding in external: 

65 expected[holding.symbol] += holding.qty 

66 return {symbol: qty for symbol, qty in expected.items() if qty} 

67 

68 

69def fee_allowance(orders: Iterable[OrderRecord]) -> dict[str, Decimal]: 

70 """How far under its lots a coin's holding may be while Alpaca's fee on its latest buys is 

71 still to be counted: the most that fee can be (ADR-0014).""" 

72 allowance: dict[str, Decimal] = defaultdict(Decimal) 

73 for order in orders: 

74 if order.unsettled_fee_qty: 

75 allowance[order.symbol] += order.unsettled_fee_qty * CRYPTO_FEE_CEILING 

76 return dict(allowance) 

77 

78 

79def compare_positions( 

80 lots: tuple[OwnedLot, ...], 

81 pending: tuple[OrderRecord, ...], 

82 positions: tuple[Position, ...], 

83 external: tuple[ExternalPosition, ...] = (), 

84 *, 

85 unsettled_fees: Mapping[str, Decimal] | None = None, 

86) -> PositionAudit: 

87 """The broker's holdings against the ledger's. A holding may differ by what open orders can 

88 still fill, and a coin's by the fee on its latest buys (`fee_allowance`), still to be 

89 counted.""" 

90 expected: dict[str, Decimal] = defaultdict(Decimal, expected_holdings(lots, external)) 

91 buys: dict[str, Decimal] = defaultdict(Decimal) 

92 sells: dict[str, Decimal] = defaultdict(Decimal, unsettled_fees or {}) 

93 for order in pending: 

94 # Prepared orders have not reached Alpaca and cannot explain a difference. 

95 if order.pending and order.submit_started_at is not None: 

96 remaining = order.qty - order.filled_qty 

97 (buys if order.side == "buy" else sells)[order.symbol] += remaining 

98 actual = {position.symbol: position.qty for position in positions} 

99 if len(actual) != len(positions): 99 ↛ 100line 99 didn't jump to line 100 because the condition on line 99 was never true

100 raise ValueError("Duplicate broker position symbols") 

101 return PositionAudit( 

102 tuple( 

103 PositionComparison( 

104 symbol, 

105 expected[symbol], 

106 actual.get(symbol, Decimal(0)), 

107 max(Decimal(0), expected[symbol] - sells[symbol]), 

108 expected[symbol] + buys[symbol], 

109 ) 

110 for symbol in sorted(expected.keys() | actual.keys() | buys.keys() | sells.keys()) 

111 ) 

112 )