Coverage for execution/accounts_io.py: 100%

38 statements  

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

1"""Reading the account registry (V6.6.5, #349): `$AQ_ACCOUNTS_FILE`, else `accounts.json` at the repo root (gitignored; 

2`accounts.example.json` is the tracked template). No file means the default account only, today's single deployment.""" 

3 

4from __future__ import annotations 

5 

6import json 

7import os 

8from collections.abc import Mapping 

9from pathlib import Path 

10from typing import Any 

11 

12from execution.accounts import Account, account_output_paths, apply_risk_overrides, parse_accounts, resolve_account 

13 

14__all__ = ["ACCOUNT_SECRETS", "accounts_file", "account_status_rows", "load_accounts", "load_account_config", "requested_account_id"] 

15 

16 

17def accounts_file(root: Path) -> Path: 

18 return Path(os.environ.get("AQ_ACCOUNTS_FILE") or (Path(root) / "accounts.json")) 

19 

20 

21def load_accounts(root: Path, base_phase_v2: Mapping[str, Any] | None = None) -> tuple[Account, ...]: 

22 """The registry's accounts, the default first. A missing file is the default alone; an unreadable or invalid one 

23 raises, because a deployment that asked for an account must not quietly run as another.""" 

24 path = accounts_file(root) 

25 if not path.exists(): 

26 return parse_accounts({}, base_phase_v2) 

27 return parse_accounts(json.loads(path.read_text(encoding="utf-8")), base_phase_v2) 

28 

29 

30def requested_account_id(parameter: str | None = None) -> str: 

31 """`AQ_ACCOUNT`, else the Lean parameter `aq-account`, else "" (the default account).""" 

32 return (os.environ.get("AQ_ACCOUNT") or parameter or "").strip() 

33 

34 

35def load_account_config(config: Mapping[str, Any], account_id: str | None, root: Path) -> dict[str, Any]: 

36 """The config one account runs on: a copy with its `phase_v2` through `apply_risk_overrides`, the function main.py 

37 applies at startup, so an offline evaluation (`aq evaluate --account`) judges the limits the deployment trades with.""" 

38 out = dict(config) 

39 account = resolve_account(load_accounts(root, config.get("phase_v2", {})), account_id) 

40 out["phase_v2"] = apply_risk_overrides(config.get("phase_v2", {}), account) 

41 return out 

42 

43 

44ACCOUNT_SECRETS: dict[str, tuple[str, ...]] = { 

45 "paper": (), 

46 "coinbase": ("COINBASE_API_KEY", "COINBASE_API_SECRET"), 

47 "interactive_brokers": ("IB_ACCOUNT", "IB_USER_NAME", "IB_PASSWORD"), 

48} 

49 

50 

51def account_status_rows(root: Path, accounts: tuple[Account, ...]) -> list[dict[str, Any]]: 

52 """One row per account: broker, environment, mode, capital, its secrets (names and whether they resolve, never values), 

53 and its last state file's reconciliation (`aq accounts status`, `GET /api/accounts`).""" 

54 from execution.secrets_io import all_secret_status 

55 

56 rows: list[dict[str, Any]] = [] 

57 for account in accounts: 

58 needed = ACCOUNT_SECRETS.get(account.broker, ()) 

59 secrets = all_secret_status(account.id, needed) if needed else [] 

60 state = account_output_paths(Path(root), account)["state_path"] 

61 reconciliation = None 

62 if state.exists(): 

63 try: 

64 reconciliation = (json.loads(state.read_text(encoding="utf-8")).get("reconciliation") or {}).get("breach") 

65 except (OSError, ValueError, AttributeError): 

66 reconciliation = None 

67 rows.append({ 

68 "id": account.id, "broker": account.broker, "environment": account.lean_environment, "mode": account.mode or "(config)", 

69 "capital_usd": account.capital_usd, "overrides": len(account.risk_overrides), "description": account.description, 

70 "secrets": f"{sum(1 for row in secrets if row['resolved'])}/{len(needed)}", "secrets_missing": [row["name"] for row in secrets if not row["resolved"]], 

71 "state": state.relative_to(Path(root)).as_posix() if state.exists() else "-", "reconciliation_breach": reconciliation, 

72 }) 

73 return rows