Coverage for src/copytrading_engine/execution/presentation/account_feed.py: 81%
68 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""One account's feed: what happened to its money, a row per outcome, newest first."""
3from decimal import Decimal
4from typing import Literal
6from pydantic import AwareDatetime
8from copytrading_engine.execution.domain.events import (
9 AccountControlChanged,
10 JournalEvent,
11 LimitChange,
12 LimitsChanged,
13 ManualSaleRecorded,
14 OrderUpdate,
15 OwnershipResolved,
16)
17from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot
18from copytrading_engine.execution.domain.orders import OrderRecord
19from copytrading_engine.execution.domain.values import Value
21FeedKind = Literal[
22 "bought",
23 "sold",
24 "cancelled",
25 "expired",
26 "rejected",
27 "paused",
28 "resumed",
29 "settled",
30 "limits_changed",
31]
32# Who made it happen: a guru's post, or the owner (a sale in the app or at the broker, a reviewed
33# post, a pause, a settled holdings review).
34FeedSource = Literal["guru", "you"]
35_ENDED: dict[str, FeedKind] = {"canceled": "cancelled", "expired": "expired"}
37_OWNER_ORDERS = ("lotsale-", "manual-")
40class AccountFeedItem(Value):
41 sequence: int
42 at: AwareDatetime
43 kind: FeedKind
44 source: FeedSource
45 # Which way an order went; a cancelled, expired, or rejected row needs it to say what ended.
46 side: Literal["buy", "sell"] | None = None
47 symbol: str | None = None
48 shares: Decimal | None = None
49 price: Decimal | None = None
50 amount: Decimal | None = None
51 guru_id: str | None = None
52 message_id: str | None = None
53 order_id: str | None = None
54 # The holding a trade belongs to (ADR-0010): the lot a buy opened or joined, or the lot a sell
55 # sold from, so every buy and sale of one position reads as one story.
56 lot_id: str | None = None
57 # The limits the owner changed, for a limits_changed row.
58 changes: tuple[LimitChange, ...] = ()
59 # Why a holdings count was settled, for a settled row: the owner answered, or the broker's
60 # filled count showed shares bought or sold outside the app (ADR-0011).
61 reason: str | None = None
64class AccountFeedPage(Value):
65 account_id: str
66 items: tuple[AccountFeedItem, ...]
67 next_before_seq: int | None = None
70def account_feed(
71 account_id: str,
72 snapshot: LedgerSnapshot,
73 rows: tuple[tuple[int, JournalEvent], ...],
74 limit: int,
75) -> AccountFeedPage:
76 items = tuple(item for seq, event in rows if (item := _item(seq, event, snapshot)) is not None)
77 return AccountFeedPage(
78 account_id=account_id,
79 items=items,
80 next_before_seq=rows[-1][0] if len(rows) == limit else None,
81 )
84def _item(seq: int, event: JournalEvent, snapshot: LedgerSnapshot) -> AccountFeedItem | None:
85 payload = event.payload
86 match payload:
87 case OrderUpdate():
88 return _order_item(seq, event, payload, snapshot)
89 case ManualSaleRecorded(sale=sale): 89 ↛ 90line 89 didn't jump to line 90 because the pattern on line 89 never matched
90 order = sale.order
91 price = order.filled_avg_price
92 return AccountFeedItem(
93 sequence=seq,
94 at=sale.filled_at,
95 kind="sold",
96 source="you",
97 side="sell",
98 symbol=order.symbol,
99 shares=order.filled_qty,
100 price=price,
101 amount=None if price is None else order.filled_qty * price,
102 order_id=order.client_order_id,
103 lot_id=sale.lot_id,
104 )
105 case OwnershipResolved(resolution=resolution): 105 ↛ 106line 105 didn't jump to line 106 because the pattern on line 105 never matched
106 request = resolution.request
107 incident = snapshot.ownership_incidents.get(request.incident_id)
108 # How far the broker's count moved from the app's, which is what the owner did.
109 moved = (
110 abs(request.broker_qty - incident.expected_qty)
111 if incident is not None
112 else request.external_qty
113 )
114 return AccountFeedItem(
115 sequence=seq,
116 at=event.at,
117 kind="settled",
118 source="you",
119 symbol=request.symbol,
120 shares=moved,
121 reason=request.reason,
122 )
123 case LimitsChanged(changes=changes):
124 return AccountFeedItem(
125 sequence=seq, at=event.at, kind="limits_changed", source="you", changes=changes
126 )
127 case AccountControlChanged(result=result) if result.command.action in ("pause", "resume"):
128 return AccountFeedItem(
129 sequence=seq,
130 at=event.at,
131 kind="paused" if result.command.action == "pause" else "resumed",
132 source="you",
133 )
134 return None
137def _order_item(
138 seq: int, event: JournalEvent, update: OrderUpdate, snapshot: LedgerSnapshot
139) -> AccountFeedItem | None:
140 order = snapshot.orders.get(update.client_id)
141 if order is None: 141 ↛ 142line 141 didn't jump to line 142 because the condition on line 141 was never true
142 return None
143 message = snapshot.messages.get(order.message_id)
144 owner = update.client_id.startswith(_OWNER_ORDERS)
145 filled = update.filled_qty
146 # A partly filled order that then ended reads as what it bought or sold.
147 if filled > 0 and update.filled_avg_price is not None: 147 ↛ 152line 147 didn't jump to line 152 because the condition on line 147 was always true
148 kind: FeedKind = "bought" if order.side == "buy" else "sold"
149 shares, price = filled, update.filled_avg_price
150 amount: Decimal | None = filled * price
151 else:
152 kind = _ENDED.get(update.status, "rejected")
153 shares, price, amount = order.qty, order.limit_price or order.stop_price, None
154 return AccountFeedItem(
155 sequence=seq,
156 at=event.at,
157 kind=kind,
158 source="you" if owner else "guru",
159 side=order.side,
160 symbol=order.symbol,
161 shares=shares,
162 price=price,
163 amount=amount,
164 guru_id=None if owner or message is None else message.guru,
165 message_id=order.message_id,
166 order_id=update.client_id,
167 lot_id=_lot_of(order, snapshot),
168 )
171def _lot_of(order: OrderRecord, snapshot: LedgerSnapshot) -> str | None:
172 """The lot a sell sold from, or the lot a buy's fills went into; none for a buy that never
173 filled."""
174 if order.lot_id is not None:
175 return order.lot_id
176 for key, lot in snapshot.lots.items(): 176 ↛ 179line 176 didn't jump to line 179 because the loop on line 176 didn't complete
177 if order.client_id in lot.entries(key): 177 ↛ 176line 177 didn't jump to line 176 because the condition on line 177 was always true
178 return key
179 return None