Coverage for execution/accounts.py: 100%

143 statements  

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

1"""Accounts (V6.6.5, #349): several broker accounts, each its own Lean deployment, without any of them loosening a limit. 

2 

3One Lean process trades one brokerage account. So an account is a deployment: `AQ_ACCOUNT=<id>` (or the Lean parameter 

4`aq-account`) selects it, its secrets come from `AETHER_<ACCOUNT>_*` (`execution/secrets.py`), its state and manual 

5overrides live under `state/accounts/<id>/`, and its audit events carry its id. Its risk overrides may only *tighten* the 

6base config: a smaller drawdown limit, a stricter kill switch, less leverage, live orders off, a lower runtime mode. A 

7looser value is refused when the registry is parsed or applied, never silently used. 

8 

9The default account is today's single deployment, and resolving it changes nothing: the same config dict, the same paths, 

10no `account_id` in the audit payloads. 

11""" 

12 

13from __future__ import annotations 

14 

15import copy 

16import re 

17from collections.abc import Mapping 

18from dataclasses import dataclass, field 

19from pathlib import Path 

20from typing import Any 

21 

22__all__ = [ 

23 "BROKER_ENVIRONMENTS", "MODE_RANK", "OVERRIDE_KEYS", "Account", "DEFAULT_ACCOUNT", "parse_accounts", "resolve_account", "apply_risk_overrides", 

24 "account_state_dir", "override_path", "account_output_paths", "tag_audit_event", "AccountTaggedQueue", 

25] 

26 

27DEFAULT_ID = "default" 

28_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$") 

29BROKER_ENVIRONMENTS: dict[str, tuple[str, ...]] = { 

30 "paper": ("live-paper",), 

31 "coinbase": ("live-coinbase", "live-paper"), 

32 "interactive_brokers": ("live-interactive", "live-interactive-iqfeed", "live-paper"), 

33} 

34MODE_RANK = {"observation": 1, "paper": 2, "live": 3} 

35# phase_v2 key path -> which direction is tighter. "lower": the override must be <= the base; "higher": >= the base; 

36# "false": a boolean that may only be switched off. 

37OVERRIDE_KEYS: dict[str, str] = { 

38 "live.max_allowed_daily_drawdown_pct": "lower", 

39 "live.max_allowed_total_drawdown_pct": "lower", 

40 "dynamic_risk.max_leverage": "lower", 

41 "reconciliation.max_tolerated_drift": "lower", 

42 "risk.kill_switch.min_rolling_sharpe": "higher", 

43 "risk.kill_switch.max_drawdown_velocity_pct_per_bar": "lower", 

44 "risk.kill_switch.max_consecutive_losses": "lower", 

45 "risk.kill_switch.max_slippage_divergence_bps": "lower", 

46 "risk.kill_switch.max_model_age_days": "lower", 

47 "runtime.allow_live_orders": "false", 

48} 

49 

50 

51@dataclass(frozen=True) 

52class Account: 

53 """One deployment. `mode`, when set, may only lower the config's `runtime.mode` (observation < paper < live); 

54 `capital_usd` is the capital the account is funded with, which the readiness scorecard requires for a live account.""" 

55 

56 id: str 

57 broker: str = "paper" 

58 lean_environment: str = "live-paper" 

59 mode: str | None = None 

60 capital_usd: float | None = None 

61 risk_overrides: Mapping[str, Any] = field(default_factory=dict) 

62 description: str = "" 

63 

64 @property 

65 def is_default(self) -> bool: 

66 return self.id == DEFAULT_ID 

67 

68 

69DEFAULT_ACCOUNT = Account(DEFAULT_ID) 

70 

71 

72def _get(tree: Mapping[str, Any], dotted: str) -> Any: 

73 node: Any = tree 

74 for part in dotted.split("."): 

75 if not isinstance(node, Mapping) or part not in node: 

76 return None 

77 node = node[part] 

78 return node 

79 

80 

81def _set(tree: dict[str, Any], dotted: str, value: Any) -> None: 

82 parts = dotted.split(".") 

83 node = tree 

84 for part in parts[:-1]: 

85 child = node.get(part) 

86 if not isinstance(child, dict): 

87 child = {} 

88 node[part] = child 

89 node = child 

90 node[parts[-1]] = value 

91 

92 

93def _check_tighter(key: str, value: Any, base: Any) -> None: 

94 direction = OVERRIDE_KEYS[key] 

95 if direction == "false": 

96 if value is not False: 

97 raise ValueError(f"{key} may only be switched off by an account (got {value!r})") 

98 return 

99 if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value: # NaN != NaN 

100 raise ValueError(f"{key} must be a number (got {value!r})") 

101 if base is None or isinstance(base, bool) or not isinstance(base, (int, float)): 

102 return # no base value to loosen 

103 if direction == "lower" and value > base: 

104 raise ValueError(f"{key}: {value} is looser than the base {base}; an account may only tighten a limit") 

105 if direction == "higher" and value < base: 

106 raise ValueError(f"{key}: {value} is looser than the base {base}; an account may only tighten a limit") 

107 

108 

109def parse_accounts(doc: Mapping[str, Any], base_phase_v2: Mapping[str, Any] | None = None) -> tuple[Account, ...]: 

110 """`{"accounts": [{"id": ..., "broker": ..., ...}]}` to accounts, the default first. Raises ValueError on a bad or 

111 duplicate id, a broker/environment mismatch, `live` on the paper broker, an unknown override key or, given 

112 `base_phase_v2`, an override looser than the base.""" 

113 rows = doc.get("accounts", []) if isinstance(doc, Mapping) else [] 

114 if not isinstance(rows, list): 

115 raise ValueError("accounts must be a list") 

116 accounts: list[Account] = [] 

117 seen: set[str] = set() 

118 for row in rows: 

119 if not isinstance(row, Mapping): 

120 raise ValueError(f"an account must be an object, got {row!r}") 

121 account_id = str(row.get("id", "")) 

122 if not _ID_RE.match(account_id): 

123 raise ValueError(f"bad account id {account_id!r}: lowercase letters, digits, - and _, at most 32") 

124 if account_id in seen: 

125 raise ValueError(f"duplicate account id {account_id!r}") 

126 seen.add(account_id) 

127 broker = str(row.get("broker", "paper")) 

128 if broker not in BROKER_ENVIRONMENTS: 

129 raise ValueError(f"{account_id}: unknown broker {broker!r} (one of {sorted(BROKER_ENVIRONMENTS)})") 

130 environment = str(row.get("lean_environment", BROKER_ENVIRONMENTS[broker][0])) 

131 if environment not in BROKER_ENVIRONMENTS[broker]: 

132 raise ValueError(f"{account_id}: environment {environment!r} does not fit broker {broker!r}") 

133 mode = row.get("mode") 

134 if mode is not None and mode not in MODE_RANK: 

135 raise ValueError(f"{account_id}: mode must be one of {sorted(MODE_RANK)}") 

136 if mode == "live" and (broker == "paper" or environment == "live-paper"): 

137 raise ValueError(f"{account_id}: live mode needs a real brokerage, not the paper one") 

138 capital = row.get("capital_usd") 

139 if capital is not None and (isinstance(capital, bool) or not isinstance(capital, (int, float)) or not capital > 0): 

140 raise ValueError(f"{account_id}: capital_usd must be a positive number") 

141 overrides = dict(row.get("risk_overrides") or {}) 

142 for key, value in overrides.items(): 

143 if key not in OVERRIDE_KEYS: 

144 raise ValueError(f"{account_id}: {key!r} is not an account override (allowed: {sorted(OVERRIDE_KEYS)})") 

145 _check_tighter(key, value, _get(base_phase_v2, key) if base_phase_v2 is not None else None) 

146 accounts.append(Account(account_id, broker, environment, mode, float(capital) if capital is not None else None, overrides, str(row.get("description", "")))) 

147 if DEFAULT_ID in seen: 

148 default = next(account for account in accounts if account.id == DEFAULT_ID) 

149 if default.risk_overrides or default.mode: 

150 raise ValueError("the default account is the base config itself: give overrides to a named account") 

151 return tuple([default] + [account for account in accounts if account.id != DEFAULT_ID]) 

152 return (DEFAULT_ACCOUNT, *accounts) 

153 

154 

155def resolve_account(accounts: tuple[Account, ...], requested: str | None) -> Account: 

156 """The account named `requested`; the default when it is empty. An unknown id raises: a deployment must never run 

157 on another account's settings by a typo.""" 

158 wanted = (requested or "").strip() or DEFAULT_ID 

159 for account in accounts: 

160 if account.id == wanted: 

161 return account 

162 if wanted == DEFAULT_ID: 

163 return DEFAULT_ACCOUNT 

164 raise ValueError(f"unknown account {wanted!r} (registry has {[account.id for account in accounts]})") 

165 

166 

167def apply_risk_overrides(phase_v2: Mapping[str, Any], account: Account) -> dict[str, Any]: 

168 """A deep copy of `phase_v2` with the account's overrides and mode applied; the default account returns an equal 

169 copy. Re-checks every override against this base, so a registry written for another config cannot loosen this one.""" 

170 out = copy.deepcopy(dict(phase_v2)) 

171 if account.is_default: 

172 return out 

173 for key, value in account.risk_overrides.items(): 

174 if key not in OVERRIDE_KEYS: 

175 raise ValueError(f"{account.id}: {key!r} is not an account override") 

176 _check_tighter(key, value, _get(out, key)) 

177 _set(out, key, value) 

178 if account.mode is not None: 

179 current = str(_get(out, "runtime.mode") or "") 

180 if current in MODE_RANK and MODE_RANK[account.mode] < MODE_RANK[current]: 

181 _set(out, "runtime.mode", account.mode) 

182 elif current in MODE_RANK and MODE_RANK[account.mode] > MODE_RANK[current]: 

183 raise ValueError(f"{account.id}: mode {account.mode!r} is looser than the config's {current!r}") 

184 # a backtest (or an unset mode) keeps its own mode: an account describes a deployment 

185 return out 

186 

187 

188def account_state_dir(root: Path, account: Account) -> Path: 

189 """Where an account writes its state: the repo root for the default (today's paths), else `state/accounts/<id>`.""" 

190 return Path(root) if account.is_default else Path(root) / "state" / "accounts" / account.id 

191 

192 

193def override_path(root: Path, account: Account) -> Path: 

194 """The file the manual trade-lock and kill-switch overrides are read from and written to (`aq trade-lock`, the API).""" 

195 return Path(root) / "config.json" if account.is_default else account_state_dir(root, account) / "overrides.json" 

196 

197 

198def account_output_paths(root: Path, account: Account) -> dict[str, Path]: 

199 """The runtime files main.py writes, by name. The default account's are exactly today's.""" 

200 base = account_state_dir(root, account) 

201 grafana = base / "visualization" / "grafana" 

202 return { 

203 "state_path": base / "visualization" / "state.json", 

204 "scene_path": base / "visualization" / "scene.json", 

205 "topology_state_path": base / "visualization" / "topology_state.json", 

206 "grafana_dir": grafana, 

207 "runtime_metrics_path": grafana / "runtime_metrics_snapshot.json", 

208 "runtime_asset_metrics_path": grafana / "runtime_asset_metrics.csv", 

209 "observation_summary_path": grafana / "observation_summary.json", 

210 "observation_equity_curve_path": grafana / "observation_equity_curve.csv", 

211 } 

212 

213 

214def tag_audit_event(event: Mapping[str, Any], account: Account) -> dict[str, Any]: 

215 """The event with `payload.account_id` set for a named account; the default account's events are left as they are.""" 

216 out = dict(event) 

217 if not account.is_default: 

218 out["payload"] = {**dict(event.get("payload") or {}), "account_id": account.id} 

219 return out 

220 

221 

222class AccountTaggedQueue: 

223 """Wraps an audit queue so every event it pushes carries the account id (named accounts only).""" 

224 

225 def __init__(self, queue: Any, account: Account) -> None: 

226 self._queue = queue 

227 self._account = account 

228 

229 def push(self, event: Mapping[str, Any]) -> Any: 

230 return self._queue.push(tag_audit_event(event, self._account)) 

231 

232 def __getattr__(self, name: str) -> Any: 

233 return getattr(self._queue, name)