Coverage for src/copytrading_engine/execution/presentation/operator_views.py: 95%

284 statements  

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

1"""Operator read views of one execution account: exposure, destinations, and journal events.""" 

2 

3import datetime as dt 

4from decimal import Decimal 

5from typing import Literal 

6 

7from pydantic import AwareDatetime 

8 

9from copytrading_engine.execution.domain.events import ( 

10 AccountControlChanged, 

11 BrokerAcknowledged, 

12 CancelRequested, 

13 JournalEvent, 

14 LimitChange, 

15 LimitsChanged, 

16 Message, 

17 OrderPrepared, 

18 OrderUpdate, 

19 SubmissionAborted, 

20 SubmissionQuote, 

21 SubmitError, 

22 SubmitStarted, 

23) 

24from copytrading_engine.execution.domain.events import Skipped as SkippedEvent 

25from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot, MessageRecord 

26from copytrading_engine.execution.domain.market import Account, Position 

27from copytrading_engine.execution.domain.order_lifecycle import OrderStatus 

28from copytrading_engine.execution.domain.orders import ( 

29 BuyLimit, 

30 OrderRecord, 

31 OwnedLot, 

32 copy_client_id, 

33) 

34from copytrading_engine.execution.domain.ownership import OwnershipInspection 

35from copytrading_engine.execution.domain.progress import ( 

36 InstructionProgress, 

37 OrderLinked, 

38 Pending, 

39 Skipped, 

40) 

41from copytrading_engine.execution.domain.values import Money, Positive, Quantity, Value 

42 

43EXCERPT_LENGTH = 140 

44 

45 

46class LotBuyView(Value): 

47 """One buy in a lot that still holds shares: the post that made it, how many shares it bought 

48 and has left, and the price they filled at.""" 

49 

50 order_id: str 

51 source_id: str | None 

52 posted_at: AwareDatetime | None 

53 excerpt: str | None 

54 bought_at: AwareDatetime | None 

55 bought_qty: Quantity 

56 remaining_qty: Quantity 

57 #: The guru's price for the buy, which a sell naming a buy price is matched against. 

58 guru_price: Positive 

59 price: Positive | None 

60 #: This buy's remaining shares at the broker's current price, against what they cost. 

61 unrealized_pl: Money | None = None 

62 

63 

64class LotView(Value): 

65 """One block of shares the copier bought: every buy of one stock from one guru (ADR-0010), 

66 keyed by the post that opened it.""" 

67 

68 lot_id: str 

69 source_id: str | None 

70 guru_id: str | None 

71 posted_at: AwareDatetime | None 

72 excerpt: str | None 

73 bought_at: AwareDatetime | None 

74 original_qty: Quantity 

75 remaining_qty: Quantity 

76 average_price: Positive 

77 #: The lot's remaining shares at the broker's current price, against what they cost. 

78 unrealized_pl: Money | None = None 

79 #: The buys that still hold shares, oldest first. 

80 buys: tuple[LotBuyView, ...] = () 

81 

82 

83class StopView(Value): 

84 """A stop guarding some of a stock's shares: the price the guru posted, how many shares it 

85 covers, whether its order is open at Alpaca now, and the post that set it.""" 

86 

87 stop_price: Positive 

88 quantity: Quantity 

89 working: bool 

90 source_id: str 

91 

92 

93class PositionView(Value): 

94 """One symbol: the shares CopyTrading bought, the owner's own, and the broker's valuation of 

95 the whole position. Prices are the broker's; missing when the broker was not read.""" 

96 

97 symbol: str 

98 owned_qty: Quantity 

99 external_qty: Quantity 

100 broker_qty: str | None = None 

101 lots: tuple[LotView, ...] = () 

102 stops: tuple[StopView, ...] = () 

103 avg_entry_price: Money | None = None 

104 current_price: Money | None = None 

105 market_value: Money | None = None 

106 unrealized_pl: Money | None = None 

107 unrealized_plpc: Money | None = None 

108 

109 

110class OwnershipIncidentView(Value): 

111 incident_id: str 

112 symbol: str 

113 expected_qty: Quantity 

114 actual_qty: str 

115 observed_at: AwareDatetime 

116 cause: str 

117 

118 

119class AccountBalanceView(Value): 

120 """The broker's own valuation of the account at `observed_at`; the app never computes it.""" 

121 

122 equity: Money 

123 previous_close_equity: Money 

124 day_change_usd: Money 

125 cash: Money 

126 buying_power: Money 

127 observed_at: AwareDatetime 

128 

129 

130def account_balance(account: Account, observed_at: dt.datetime) -> AccountBalanceView: 

131 return AccountBalanceView( 

132 equity=account.equity, 

133 previous_close_equity=account.last_equity, 

134 day_change_usd=account.equity - account.last_equity, 

135 cash=account.cash, 

136 buying_power=account.buying_power, 

137 observed_at=observed_at, 

138 ) 

139 

140 

141class AccountOverview(Value): 

142 account_id: str 

143 environment: Literal["paper", "live"] 

144 active_configuration: bool 

145 broker_identity: str 

146 entry_permission: str 

147 recovery_preference: str 

148 readiness: str 

149 account_risk_status: str 

150 account_risk_reason: str | None 

151 account_activity_status: str 

152 account_activity_reason: str | None 

153 total_exposure_usd: Quantity | None 

154 app_cost_basis_usd: Quantity | None 

155 positions: tuple[PositionView, ...] 

156 unresolved_incidents: tuple[str, ...] 

157 ownership_incidents: tuple[OwnershipIncidentView, ...] 

158 pending_orders: int | None 

159 balance: AccountBalanceView | None 

160 # When its record last changed; read for a record of an account no longer in the setup. 

161 last_activity_at: dt.datetime | None = None 

162 

163 

164type UnavailableReason = Literal["timeout", "read_failed", "earlier_version"] 

165 

166 

167class AccountUnavailable(Value): 

168 """An account whose evidence could not be read for this page; never shown as empty.""" 

169 

170 account_id: str 

171 reason: UnavailableReason 

172 

173 

174class AccountOverviewPage(Value): 

175 items: tuple[AccountOverview, ...] 

176 next_before_account_id: str | None = None 

177 unavailable_accounts: tuple[AccountUnavailable, ...] = () 

178 

179 

180class OrderView(Value): 

181 client_id: str 

182 symbol: str 

183 side: str 

184 status: str 

185 quantity: Quantity 

186 filled_quantity: Quantity 

187 limit_price: Positive | None 

188 average_fill_price: Positive | None 

189 broker_id: str | None 

190 created_at: AwareDatetime 

191 # How the order went out: its type and session, the guru's price, and how far above it a 

192 # buy was allowed to pay. 

193 order_type: Literal["market", "limit", "stop"] | None = None 

194 # A stop order's price: the order sells once the stock falls to it (ADR-0015). 

195 stop_price: Positive | None = None 

196 session: str | None = None 

197 source_price: Positive | None = None 

198 entry_tolerance_pct: Quantity | None = None 

199 submitted_at: AwareDatetime | None = None 

200 # The quote when it was sent, for "your limit was $201.00; PM was offered at $208.86". 

201 quote_bid: Quantity | None = None 

202 quote_ask: Quantity | None = None 

203 # Why it ended unfilled: CopyTrading's own cancel (timeout, replaced_by_sell, 

204 # copying_stopped), Alpaca's (cancelled_at_broker, expired), or rejected. 

205 cancel_reason: str | None = None 

206 # Alpaca's own words when it refused the order ("insufficient buying power"). 

207 reject_reason: str | None = None 

208 ended_at: AwareDatetime | None = None 

209 # Which of the post's calls this order places, and for a buy what the call asked for, what 

210 # the account's limits allowed of it, and the limit that cut it (ADR-0010). 

211 instruction_index: int 

212 requested_usd: Positive | None 

213 budget_usd: Positive | None 

214 limited_by: BuyLimit | None = None 

215 

216 

217class LimitHit(Value): 

218 """The limit a skipped call would have passed, with its numbers.""" 

219 

220 part: int 

221 scope: Literal["symbol", "total"] 

222 current: Quantity 

223 proposed: Quantity 

224 limit: Quantity 

225 

226 

227type Step = Literal[ 

228 "received", 

229 "held", 

230 "resumed", 

231 "skipped", 

232 "sized", 

233 "sent", 

234 "accepted", 

235 "partially_filled", 

236 "filled", 

237 "cancel_requested", 

238 "cancelled", 

239 "expired", 

240 "rejected", 

241 "failed", 

242] 

243 

244 

245class TimelineStep(Value): 

246 """One moment of a post's trip through an account, read from the account's journal.""" 

247 

248 step: Step 

249 at: AwareDatetime 

250 client_id: str | None = None 

251 reason: str | None = None 

252 quantity: Quantity | None = None 

253 price: Positive | None = None 

254 

255 

256class LaterBuy(Value): 

257 """A sell skipped because every buy it would have sold was posted after it.""" 

258 

259 part: int 

260 bought_at: AwareDatetime 

261 

262 

263class NamedBuy(Value): 

264 """A sell held because none of the account's buys is at the price it names (ADR-0010): the 

265 guru's buy at that price, and why the account holds none of it.""" 

266 

267 part: int 

268 #: When the guru posted the buy; None when no buy at that price ever reached this account. 

269 posted_at: AwareDatetime | None 

270 #: "sold" when its shares were already sold, "not_filled" when its order never filled, else 

271 #: the reason the buy was refused ("daily_entry_cap", ...). None when it never reached here. 

272 outcome: str | None 

273 

274 

275class DestinationView(Value): 

276 account_id: str 

277 environment: str 

278 status: str 

279 instruction_outcomes: tuple[str, ...] 

280 # How each stop the post set went, as the instructions' outcomes do. 

281 stop_outcomes: tuple[str, ...] = () 

282 limits_hit: tuple[LimitHit, ...] 

283 later_buys: tuple[LaterBuy, ...] = () 

284 named_buys: tuple[NamedBuy, ...] = () 

285 orders: tuple[OrderView, ...] 

286 timeline: tuple[TimelineStep, ...] = () 

287 

288 

289class AccountEventView(Value): 

290 sequence: int 

291 at: AwareDatetime 

292 kind: str 

293 message_id: str | None = None 

294 order_id: str | None = None 

295 reason: str | None = None 

296 status: str | None = None 

297 # Limits the owner changed while copying, each with its value before and after. 

298 changes: tuple[LimitChange, ...] = () 

299 

300 

301class AccountEventPage(Value): 

302 account_id: str 

303 items: tuple[AccountEventView, ...] 

304 next_before_seq: int | None = None 

305 

306 

307def _gain(price: Decimal | None, cost: Decimal | None, qty: Decimal) -> Decimal | None: 

308 if price is None or cost is None: 

309 return None 

310 return ((price - cost) * qty).quantize(Decimal("0.01")) 

311 

312 

313def _buy_view( 

314 entry: str, 

315 remaining: Decimal, 

316 guru_price: Decimal, 

317 snapshot: LedgerSnapshot, 

318 current_price: Decimal | None, 

319) -> LotBuyView: 

320 order = snapshot.orders.get(entry) 

321 message = snapshot.messages.get(order.message_id) if order is not None else None 

322 price = order.filled_avg_price if order is not None else None 

323 return LotBuyView( 

324 order_id=entry, 

325 source_id=message.key if message is not None else None, 

326 posted_at=message.timestamp if message is not None else None, 

327 excerpt=excerpt(message.text) if message is not None else None, 

328 bought_at=order.created_at if order is not None else None, 

329 # What the buy brought in: a coin's fill less the fee Alpaca kept of it. 

330 bought_qty=order.received_qty if order is not None else remaining, 

331 remaining_qty=remaining, 

332 guru_price=guru_price, 

333 price=price, 

334 unrealized_pl=_gain(current_price, price, remaining), 

335 ) 

336 

337 

338def _lot_view( 

339 key: str, lot: OwnedLot, snapshot: LedgerSnapshot, current_price: Decimal | None 

340) -> LotView: 

341 """A lot is keyed by the buy order that opened it, which names the post it came from.""" 

342 order = snapshot.orders.get(key) 

343 message = snapshot.messages.get(order.message_id) if order is not None else None 

344 return LotView( 

345 lot_id=key, 

346 source_id=message.key if message is not None else None, 

347 guru_id=message.guru if message is not None else None, 

348 posted_at=message.timestamp if message is not None else None, 

349 excerpt=excerpt(message.text) if message is not None else None, 

350 bought_at=order.created_at if order is not None else None, 

351 original_qty=lot.original_qty, 

352 remaining_qty=lot.remaining_qty, 

353 average_price=lot.average_price, 

354 unrealized_pl=_gain(current_price, lot.average_price, lot.remaining_qty), 

355 buys=tuple( 

356 _buy_view( 

357 entry, 

358 lot.entry_remaining[entry], 

359 lot.entry_prices[entry], 

360 snapshot, 

361 current_price, 

362 ) 

363 for entry in lot.entries(key) 

364 if lot.entry_remaining.get(entry, Decimal(0)) > 0 

365 ), 

366 ) 

367 

368 

369def _lot_order(lot: LotView) -> tuple[bool, dt.datetime, str]: 

370 """Oldest first; a lot without its buy record goes last.""" 

371 earliest = dt.datetime.min.replace(tzinfo=dt.UTC) 

372 return (lot.bought_at is None, lot.bought_at or earliest, lot.lot_id) 

373 

374 

375def excerpt(text: str) -> str | None: 

376 words = " ".join(text.split()) 

377 if not words: 377 ↛ 378line 377 didn't jump to line 378 because the condition on line 377 was never true

378 return None 

379 return words if len(words) <= EXCERPT_LENGTH else words[: EXCERPT_LENGTH - 1].rstrip() + "…" 

380 

381 

382def _position_stops(snapshot: LedgerSnapshot, symbol: str) -> tuple[StopView, ...]: 

383 """The stops guarding a stock's shares, lowest price first. A stop is `working` while a stop 

384 order for it is open at Alpaca; between sessions it waits to be placed again (ADR-0015).""" 

385 views = [] 

386 for rule in snapshot.stops.values(): 386 ↛ 387line 386 didn't jump to line 387 because the loop on line 386 never started

387 lot = snapshot.lots.get(rule.lot_id) 

388 if rule.symbol != symbol or lot is None: 

389 continue 

390 views.append( 

391 StopView( 

392 stop_price=rule.stop_price, 

393 quantity=lot.remaining_of(rule.entries), 

394 working=any( 

395 order.stop_rule == rule.key and order.pending 

396 for order in snapshot.orders.values() 

397 ), 

398 source_id=rule.message_id, 

399 ) 

400 ) 

401 return tuple(sorted(views, key=lambda view: view.stop_price)) 

402 

403 

404def account_overview( 

405 snapshot: LedgerSnapshot, 

406 inspection: OwnershipInspection | None, 

407 *, 

408 local_account_id: str, 

409 active_configuration: bool, 

410 readiness: str, 

411 balance: AccountBalanceView | None, 

412 last_activity_at: dt.datetime | None = None, 

413 recovery_preference: str | None = None, 

414) -> AccountOverview: 

415 """One account from its record. An account in the setup passes the setup's recovery 

416 preference; a record no setup names shows the one it last ran with.""" 

417 if snapshot.account_id is None or snapshot.environment is None: 417 ↛ 418line 417 didn't jump to line 418 because the condition on line 417 was never true

418 raise RuntimeError("Account evidence has no verified identity") 

419 held = {item.symbol: item for item in inspection.broker_positions} if inspection else {} 

420 owned: dict[str, Decimal] = {} 

421 lots: dict[str, list[LotView]] = {} 

422 for key, lot in snapshot.lots.items(): 

423 owned[lot.symbol] = owned.get(lot.symbol, Decimal(0)) + lot.remaining_qty 

424 if lot.remaining_qty > 0: 

425 price = held[lot.symbol].current_price if lot.symbol in held else None 

426 lots.setdefault(lot.symbol, []).append(_lot_view(key, lot, snapshot, price)) 

427 broker = {symbol: item.qty for symbol, item in held.items()} 

428 symbols = sorted(set(owned) | set(snapshot.external_positions) | set(broker)) 

429 positions = tuple( 

430 PositionView( 

431 symbol=symbol, 

432 owned_qty=owned.get(symbol, Decimal(0)), 

433 external_qty=snapshot.external_positions[symbol].qty 

434 if symbol in snapshot.external_positions 

435 else Decimal(0), 

436 broker_qty=str(broker[symbol]) if symbol in broker else None, 

437 lots=tuple(sorted(lots.get(symbol, ()), key=_lot_order)), 

438 stops=_position_stops(snapshot, symbol), 

439 **(held[symbol].model_dump(include=set(Position.VALUATION)) if symbol in held else {}), 

440 ) 

441 for symbol in symbols 

442 ) 

443 incidents = tuple( 

444 sorted( 

445 [ 

446 item.incident_id 

447 for item in snapshot.ownership_incidents.values() 

448 if not item.resolved 

449 ] 

450 + [item.client_id for item in snapshot.late_order_incidents.values() if item.unresolved] 

451 ) 

452 ) 

453 app_cost = sum( 

454 (lot.remaining_qty * lot.average_price for lot in snapshot.lots.values()), Decimal(0) 

455 ) 

456 return AccountOverview( 

457 account_id=local_account_id, 

458 environment=snapshot.environment, 

459 active_configuration=active_configuration, 

460 broker_identity=snapshot.account_id, 

461 entry_permission=snapshot.control.entry_permission, 

462 recovery_preference=recovery_preference or snapshot.control.recovery_preference, 

463 readiness=readiness, 

464 account_risk_status=inspection.account_risk_status if inspection else "unavailable", 

465 account_risk_reason=inspection.account_risk_reason if inspection else "not_checked", 

466 account_activity_status=inspection.account_activity_status if inspection else "unavailable", 

467 account_activity_reason=inspection.account_activity_reason if inspection else "not_checked", 

468 total_exposure_usd=inspection.total_exposure_usd if inspection else None, 

469 app_cost_basis_usd=app_cost, 

470 positions=positions, 

471 unresolved_incidents=incidents, 

472 ownership_incidents=tuple( 

473 OwnershipIncidentView( 

474 incident_id=item.incident_id, 

475 symbol=item.symbol, 

476 expected_qty=item.expected_qty, 

477 actual_qty=str(item.actual_qty), 

478 observed_at=item.observed_at, 

479 cause=item.cause, 

480 ) 

481 for item in snapshot.ownership_incidents.values() 

482 if not item.resolved 

483 ), 

484 pending_orders=sum(order.pending for order in snapshot.orders.values()), 

485 balance=balance, 

486 last_activity_at=last_activity_at, 

487 ) 

488 

489 

490_ENDED: dict[str, Step] = {"canceled": "cancelled", "expired": "expired", "rejected": "rejected"} 

491_UPDATES = {"partially_filled", "filled", "cancelled", "expired", "rejected"} 

492_STEP_ORDER: tuple[Step, ...] = ( 

493 "received", 

494 "held", 

495 "resumed", 

496 "skipped", 

497 "sized", 

498 "sent", 

499 "accepted", 

500 "partially_filled", 

501 "filled", 

502 "cancel_requested", 

503 "cancelled", 

504 "expired", 

505 "rejected", 

506 "failed", 

507) 

508_FILLS: dict[str, Step] = {"partially_filled": "partially_filled", "filled": "filled"} 

509 

510 

511def _timeline( 

512 events: tuple[JournalEvent, ...], resumes: tuple[dt.datetime, ...] 

513) -> tuple[TimelineStep, ...]: 

514 """A post's steps in one account, in the order they happened. A resume between the post 

515 reaching the account and its first decision means the buy was held for the owner.""" 

516 steps: list[TimelineStep] = [] 

517 seen: set[tuple[str, str]] = set() 

518 for event in events: 

519 payload, at = event.payload, event.at 

520 match payload: 

521 case Message(): 

522 steps.append(TimelineStep(step="received", at=at)) 

523 case SkippedEvent(): 

524 steps.append(TimelineStep(step="skipped", at=at, reason=payload.reason)) 

525 case OrderPrepared(): 

526 steps.append( 

527 TimelineStep( 

528 step="sized", 

529 at=at, 

530 client_id=payload.client_id, 

531 quantity=payload.qty, 

532 price=payload.limit_price or payload.stop_price, 

533 ) 

534 ) 

535 case SubmitStarted(): 

536 steps.append(TimelineStep(step="sent", at=at, client_id=payload.client_id)) 

537 case BrokerAcknowledged(): 

538 steps.append(TimelineStep(step="accepted", at=at, client_id=payload.client_id)) 

539 case CancelRequested(): 

540 steps.append( 

541 TimelineStep( 

542 step="cancel_requested", 

543 at=at, 

544 client_id=payload.client_id, 

545 reason=payload.reason, 

546 ) 

547 ) 

548 case SubmitError() | SubmissionAborted(): 

549 reason = ( 

550 payload.reason if isinstance(payload, SubmissionAborted) else "submit_error" 

551 ) 

552 steps.append( 

553 TimelineStep(step="failed", at=at, client_id=payload.client_id, reason=reason) 

554 ) 

555 case OrderUpdate(): 

556 status = payload.status.value 

557 step = _FILLS.get(status) or _ENDED.get(status) 

558 key = (payload.client_id, f"{status}:{payload.filled_qty}") 

559 if step is None or key in seen: 

560 continue 

561 seen.add(key) 

562 steps.append( 

563 TimelineStep( 

564 step=step, 

565 at=at, 

566 client_id=payload.client_id, 

567 quantity=payload.filled_qty if step in _FILLS.values() else None, 

568 price=payload.filled_avg_price, 

569 ) 

570 ) 

571 case _: 

572 continue 

573 # Alpaca's answer to a submit can already carry the fill, written just before the 

574 # acknowledgement: the order was accepted no later than its first update. 

575 first_update: dict[str, dt.datetime] = {} 

576 for step in steps: 

577 if step.client_id is not None and step.step in _UPDATES: 

578 first_update.setdefault(step.client_id, step.at) 

579 steps = [ 

580 step.model_copy(update={"at": min(step.at, first_update[step.client_id])}) 

581 if step.step == "accepted" and step.client_id in first_update 

582 else step 

583 for step in steps 

584 ] 

585 received = next((step.at for step in steps if step.step == "received"), None) 

586 decided = next((step.at for step in steps if step.step in {"sized", "skipped", "failed"}), None) 

587 if received is not None and decided is not None: 

588 held = [at for at in resumes if received <= at <= decided] 

589 if held: 

590 steps.append(TimelineStep(step="held", at=received, reason="waiting_for_resume")) 

591 steps.append(TimelineStep(step="resumed", at=held[0])) 

592 # Steps recorded in the same instant read in the order they happen. 

593 order = {name: index for index, name in enumerate(_STEP_ORDER)} 

594 return tuple(sorted(steps, key=lambda step: (step.at, order[step.step]))) 

595 

596 

597# Orders cancelled before the reason was recorded: a cancel of CopyTrading's own unfilled order this 

598# long after it went out is read as the order timeout, by far the usual cause; newer orders say. 

599_TIMEOUT_EVIDENCE_SECONDS = 30 

600 

601 

602def older_cancel_reason(submitted_at: object, cancelled_at: dt.datetime) -> str: 

603 if isinstance(submitted_at, dt.datetime): 

604 if (cancelled_at - submitted_at).total_seconds() >= _TIMEOUT_EVIDENCE_SECONDS: 

605 return "timeout" 

606 return "cancel_requested" 

607 

608 

609def _order_detail(order_events: tuple[JournalEvent, ...]) -> dict[str, object]: 

610 """What the journal adds to an order: how it went out, the quote then, and how it ended.""" 

611 detail: dict[str, object] = {} 

612 requested: str | None = None 

613 for event in order_events: 

614 payload = event.payload 

615 match payload: 

616 case OrderPrepared(): 

617 detail.update( 

618 order_type=payload.type, 

619 stop_price=payload.stop_price, 

620 session=payload.session.value, 

621 source_price=payload.source_price, 

622 entry_tolerance_pct=payload.entry_tolerance_pct, 

623 ) 

624 case SubmitStarted(): 

625 detail["submitted_at"] = payload.submit_started_at 

626 case SubmissionQuote(): 

627 detail.update(quote_bid=payload.quote.bid, quote_ask=payload.quote.ask) 

628 case SubmitError() if payload.reason: 

629 detail["reject_reason"] = payload.reason 

630 case CancelRequested(): 

631 requested = payload.reason or older_cancel_reason( 

632 detail.get("submitted_at"), event.at 

633 ) 

634 case OrderUpdate() if payload.status.value in _ENDED: 

635 status = payload.status.value 

636 detail["ended_at"] = event.at 

637 if status == "canceled": 637 ↛ 640line 637 didn't jump to line 640 because the condition on line 637 was always true

638 detail["cancel_reason"] = requested or "cancelled_at_broker" 

639 else: 

640 detail["cancel_reason"] = status 

641 case _: 

642 continue 

643 return detail 

644 

645 

646def destination_views( 

647 snapshot: LedgerSnapshot, 

648 source_ids: set[str], 

649 events: tuple[JournalEvent, ...] = (), 

650) -> dict[str, DestinationView]: 

651 if snapshot.account_id is None or snapshot.environment is None: 651 ↛ 652line 651 didn't jump to line 652 because the condition on line 651 was never true

652 return {} 

653 views: dict[str, DestinationView] = {} 

654 # Posts the owner has acted on by hand: a call held for approval is then no longer waiting. 

655 approved = { 

656 command.source_id 

657 for command in snapshot.manual_commands.values() 

658 if command.state == "prepared" 

659 } 

660 by_message: dict[str, list[JournalEvent]] = {} 

661 by_order: dict[str, list[JournalEvent]] = {} 

662 resumes: list[dt.datetime] = [] 

663 for event in events: 

664 payload = event.payload 

665 if isinstance(payload, AccountControlChanged): 

666 if payload.result.command.action == "resume": 

667 resumes.append(payload.result.applied_at) 

668 continue 

669 message_id = getattr(payload, "message_id", None) 

670 if message_id is not None: 

671 by_message.setdefault(message_id, []).append(event) 

672 client_id = getattr(payload, "client_id", None) 

673 if client_id is not None: 

674 by_order.setdefault(client_id, []).append(event) 

675 for message in snapshot.messages.values(): 

676 source_id = f"{message.source}:{message.channel_id}:{message.id}" 

677 if source_id not in source_ids: 

678 continue 

679 orders = tuple( 

680 OrderView( 

681 client_id=order.client_id, 

682 symbol=order.symbol, 

683 side=order.side, 

684 status=order.status.value, 

685 quantity=order.qty, 

686 filled_quantity=order.filled_qty, 

687 limit_price=order.limit_price, 

688 stop_price=order.stop_price, 

689 average_fill_price=order.filled_avg_price, 

690 broker_id=order.broker_id, 

691 created_at=order.created_at, 

692 instruction_index=order.instruction_index, 

693 requested_usd=order.requested_usd, 

694 budget_usd=order.budget_usd, 

695 limited_by=order.limited_by, 

696 ).model_copy(update=_order_detail(tuple(by_order.get(order.client_id, ())))) 

697 for order in snapshot.orders.values() 

698 if order.message_id == message.key and not _sent_again(order, message) 

699 ) 

700 views[source_id] = DestinationView( 

701 account_id=message.destination.connection.account_id, 

702 environment=snapshot.environment, 

703 status=message.status, 

704 instruction_outcomes=tuple( 

705 _outcome(part, approved=source_id in approved) for part in message.parts 

706 ), 

707 stop_outcomes=tuple(_outcome(part, approved=False) for part in message.stop_parts), 

708 limits_hit=tuple( 

709 LimitHit(part=index, **exposure.model_dump()) 

710 for index, part in enumerate(message.parts) 

711 if isinstance(part, Skipped) 

712 for exposure in part.exposure 

713 ), 

714 later_buys=tuple( 

715 LaterBuy(part=index, bought_at=part.bought_at) 

716 for index, part in enumerate(message.parts) 

717 if isinstance(part, Skipped) and part.bought_at is not None 

718 ), 

719 named_buys=tuple( 

720 _named_buy(snapshot, message, index) 

721 for index, part in enumerate(message.parts) 

722 if isinstance(part, Skipped) and part.reason == "named_buy_not_held" 

723 ), 

724 orders=orders, 

725 timeline=_timeline(tuple(by_message.get(message.key, ())), tuple(resumes)), 

726 ) 

727 return views 

728 

729 

730def _named_buy(snapshot: LedgerSnapshot, sell: MessageRecord, part: int) -> NamedBuy: 

731 """The guru's latest buy, posted before the sell, of the stock at the buy price the sell names, 

732 and what came of it in this account.""" 

733 named = sell.instructions[part] 

734 found: tuple[MessageRecord, int] | None = None 

735 for message in snapshot.messages.values(): 

736 if message.source_key != sell.source_key or message.timestamp >= sell.timestamp: 

737 continue 

738 for index, call in enumerate(message.instructions): 

739 if ( 

740 call.action == "buy" 

741 and call.symbol == named.symbol 

742 and call.price == named.entry_price 

743 ): 

744 if found is None or message.timestamp > found[0].timestamp: 744 ↛ 738line 744 didn't jump to line 738 because the condition on line 744 was always true

745 found = (message, index) 

746 if found is None: 

747 return NamedBuy(part=part, posted_at=None, outcome=None) 

748 message, index = found 

749 progress = message.parts[index] 

750 if isinstance(progress, Skipped): 

751 outcome: str | None = progress.reason 

752 elif isinstance(progress, OrderLinked): 752 ↛ 756line 752 didn't jump to line 756 because the condition on line 752 was always true

753 order = snapshot.orders.get(progress.client_id) 

754 outcome = "sold" if order is not None and order.filled_qty > 0 else "not_filled" 

755 else: 

756 outcome = None 

757 return NamedBuy(part=part, posted_at=message.timestamp, outcome=outcome) 

758 

759 

760def _sent_again(order: OrderRecord, message: MessageRecord) -> bool: 

761 """A copied sell's attempt that was stopped before it reached Alpaca and is being tried again: 

762 the call's later attempt stands for it in Activity.""" 

763 return ( 

764 order.status is OrderStatus.ABORTED_BEFORE_SUBMIT 

765 and order.side == "sell" 

766 and order.stop_rule is None 

767 and order.client_id.startswith(copy_client_id(message.key, order.instruction_index)) 

768 and message.parts[order.instruction_index] != OrderLinked(client_id=order.client_id) 

769 ) 

770 

771 

772def _outcome(part: InstructionProgress, *, approved: bool) -> str: 

773 if isinstance(part, Pending) and part.waiting is not None: 

774 # A sell with no fresh bid yet: still working, waiting for a price to sell at. 

775 return "waiting_for_quote" 

776 if not isinstance(part, Skipped): 

777 return part.kind 

778 if part.reason == "approval_required" and approved: 

779 return "approved_by_owner" 

780 return part.reason 

781 

782 

783def event_page( 

784 account_id: str, rows: tuple[tuple[int, JournalEvent], ...], limit: int 

785) -> AccountEventPage: 

786 items = tuple(_event_view(seq, event) for seq, event in rows) 

787 return AccountEventPage( 

788 account_id=account_id, 

789 items=items, 

790 next_before_seq=items[-1].sequence if len(items) == limit else None, 

791 ) 

792 

793 

794def _event_view(seq: int, event: JournalEvent) -> AccountEventView: 

795 payload = event.payload 

796 if isinstance(payload, AccountControlChanged): 

797 # The action says what the owner changed; a recovery change also says to what. 

798 command = payload.result.command 

799 return AccountEventView( 

800 sequence=seq, 

801 at=event.at, 

802 kind=payload.kind, 

803 reason=command.action, 

804 status=command.recovery_preference, 

805 ) 

806 if isinstance(payload, LimitsChanged): 

807 return AccountEventView( 

808 sequence=seq, at=event.at, kind=payload.kind, changes=payload.changes 

809 ) 

810 return AccountEventView( 

811 sequence=seq, 

812 at=event.at, 

813 kind=payload.kind, 

814 message_id=getattr(payload, "message_id", None), 

815 order_id=getattr(payload, "client_id", None), 

816 reason=getattr(payload, "reason", None), 

817 status=str(getattr(payload, "status", "")) or None, 

818 ) 

819 

820 

821def with_live_facts( 

822 overview: AccountOverview, 

823 account: Account, 

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

825 observed_at: dt.datetime, 

826) -> AccountOverview: 

827 """A paused account's retained overview with what the broker reports now: its balance, and 

828 each position's shares and valuation, the owner's own included. Nothing about ownership or 

829 incidents changes; those are the ledger's.""" 

830 held = {position.symbol: position for position in positions} 

831 views: list[PositionView] = [] 

832 for view in overview.positions: 

833 position = held.pop(view.symbol, None) 

834 if position is None: 834 ↛ 835line 834 didn't jump to line 835 because the condition on line 834 was never true

835 views.append(view) 

836 continue 

837 price = position.current_price 

838 lots = tuple( 

839 lot.model_copy( 

840 update={ 

841 "unrealized_pl": _gain(price, lot.average_price, lot.remaining_qty), 

842 "buys": tuple( 

843 buy.model_copy( 

844 update={"unrealized_pl": _gain(price, buy.price, buy.remaining_qty)} 

845 ) 

846 for buy in lot.buys 

847 ), 

848 } 

849 ) 

850 if price is not None 

851 else lot 

852 for lot in view.lots 

853 ) 

854 views.append( 

855 view.model_copy( 

856 update={ 

857 "broker_qty": str(position.qty), 

858 "lots": lots, 

859 **position.model_dump(include=set(Position.VALUATION)), 

860 } 

861 ) 

862 ) 

863 views.extend( 

864 PositionView( 

865 symbol=symbol, 

866 owned_qty=Decimal(0), 

867 external_qty=Decimal(0), 

868 broker_qty=str(position.qty), 

869 **position.model_dump(include=set(Position.VALUATION)), 

870 ) 

871 for symbol, position in held.items() 

872 ) 

873 exposure = sum( 

874 (abs(position.market_value) for position in positions if position.market_value is not None), 

875 Decimal(0), 

876 ) 

877 return overview.model_copy( 

878 update={ 

879 "positions": tuple(sorted(views, key=lambda item: item.symbol)), 

880 "balance": account_balance(account, observed_at), 

881 "total_exposure_usd": exposure, 

882 } 

883 )