"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(live): advisory provider registry, public enforcement aliases, exception sanitization
shadowinlifee5ca46aa6a0a
diff --git a/agent/src/live/advisory/__init__.py b/agent/src/live/advisory/__init__.pyindex e2d30e4ce..131527026 100644--- a/agent/src/live/advisory/__init__.py+++ b/agent/src/live/advisory/__init__.py@@ -68,9 +68,9 @@ class AdvisoryContext:side: ``"buy"`` or ``"sell"``.notional_usd: Order notional in USD.account_equity: Current account equity in USD.- account_drawdown: Current drawdown as a fraction (0.0 = no drawdown,- 1.0 = fully drawn down). Approximated from mandate funding when- the broker does not supply a high-water mark.+ utilization_ratio: Funding utilization as a fraction (0.0 = unused,+ 1.0 = fully utilized). Approximated from mandate funding cap+ when the broker does not supply a high-water mark.open_position_count: Number of currently open positions.total_exposure_usd: Sum of all open position market values in USD.funding_usd: Mandate's ``account_funding_usd`` (the committed capital@@ -81,7 +81,7 @@ class AdvisoryContext:side: strnotional_usd: floataccount_equity: float- account_drawdown: float+ utilization_ratio: floatopen_position_count: inttotal_exposure_usd: floatfunding_usd: float@@ -217,10 +217,11 @@ class AdvisoryOrchestrator:"advisory provider %s failed: %s",getattr(provider, "provider_id", "<unknown>"),exc,+ exc_info=True,)result = AdvisoryResult(verdict=Verdict.REVIEW_UNAVAILABLE,- summary=f"provider error: {exc}",+ summary=f"provider error: {type(exc).__name__}",provider=getattr(provider, "provider_id", "<unknown>"),)results.append(result)@@ -232,6 +233,33 @@ class AdvisoryOrchestrator:)+# -- Provider registry -------------------------------------------------------++_advisory_providers: list[PreTradeAdvisoryInterface] = []+++def register_advisory_provider(provider: PreTradeAdvisoryInterface) -> None:+ """Register an advisory provider to be consulted on each review.++ Providers are consulted in registration order. Call+ :func:`clear_advisory_providers` to remove all registered providers.++ Args:+ provider: An advisory provider instance.+ """+ _advisory_providers.append(provider)+++def clear_advisory_providers() -> None:+ """Remove all registered advisory providers."""+ _advisory_providers.clear()+++def get_advisory_providers() -> list[PreTradeAdvisoryInterface]:+ """Return a copy of the current advisory provider list."""+ return list(_advisory_providers)++__all__ = ["AdvisoryContext","AdvisoryOrchestrator",@@ -239,4 +267,7 @@ __all__ = ["AggregatedVerdict","PreTradeAdvisoryInterface","Verdict",+ "clear_advisory_providers",+ "get_advisory_providers",+ "register_advisory_provider",]diff --git a/agent/src/live/enforcement.py b/agent/src/live/enforcement.pyindex c0668ada1..3e3e614fb 100644--- a/agent/src/live/enforcement.py+++ b/agent/src/live/enforcement.py@@ -707,3 +707,12 @@ def market_cap_usd(symbol: str, asset_class: AssetClass) -> float | None:cap = info.get("marketCap")parsed = _as_float(cap)return parsed if parsed and parsed > 0 else None+++# -- Public aliases for cross-module use (advisory layer) --------------------+# These expose internal helpers to the advisory module without requiring+# callers to import underscore-prefixed private names.++account_balance_market_value = _account_balance_market_value+coerce_position_rows = _coerce_position_rows+positions_market_value = _positions_market_valuediff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.pyindex d3d4e31e2..6c24b3277 100644--- a/agent/src/live/order_guard.py+++ b/agent/src/live/order_guard.py@@ -46,6 +46,7 @@ from src.live.advisory import (AdvisoryContext,AdvisoryOrchestrator,Verdict,+ get_advisory_providers,)from src.live.audit import LiveActionEvent, write_live_actionfrom src.live.enforcement import (@@ -393,23 +394,30 @@ class LiveOrderGuardTool(MCPRemoteTool):if env_val not in _ADVISORY_TRUTHY:return None+ providers = get_advisory_providers()+ if not providers:+ logger.info(+ "advisory enabled but no providers registered — skipping review"+ )+ return None+try:from src.live.enforcement import (- _account_balance_market_value,- _coerce_position_rows,- _positions_market_value,+ account_balance_market_value,+ coerce_position_rows,+ positions_market_value,)- equity = _account_balance_market_value(balance) or 0.0- exposure = _positions_market_value(positions) or 0.0+ equity = account_balance_market_value(balance) or 0.0+ exposure = positions_market_value(positions) or 0.0funding_usd = mandate.hard_caps.account_funding_usdif equity > 0 and funding_usd > 0:- drawdown = max(0.0, 1.0 - equity / funding_usd)+ utilization = max(0.0, 1.0 - equity / funding_usd)else:- drawdown = 0.0+ utilization = 0.0- pos_rows = _coerce_position_rows(positions)+ pos_rows = coerce_position_rows(positions)open_count = len(pos_rows) if pos_rows is not None else 0context = AdvisoryContext(@@ -417,16 +425,13 @@ class LiveOrderGuardTool(MCPRemoteTool):side=intent.side,notional_usd=intent.notional_usd or 0.0,account_equity=equity,- account_drawdown=drawdown,+ utilization_ratio=utilization,open_position_count=open_count,total_exposure_usd=exposure,funding_usd=funding_usd,)- orchestrator = AdvisoryOrchestrator([])- if not orchestrator.providers:- return None-+ orchestrator = AdvisoryOrchestrator(providers)aggregated = orchestrator.review(context)return {"verdict": aggregated.verdict.value,@@ -443,11 +448,11 @@ class LiveOrderGuardTool(MCPRemoteTool):],}except Exception as exc:- logger.warning("advisory review failed: %s", exc)+ logger.warning("advisory review failed: %s", exc, exc_info=True)return {"verdict": Verdict.REVIEW_UNAVAILABLE.value,"concerns": [],- "error": str(exc),+ "error": type(exc).__name__,}def _deny(diff --git a/agent/tests/test_advisory.py b/agent/tests/test_advisory.pyindex 5fe6537f6..50825732b 100644--- a/agent/tests/test_advisory.py+++ b/agent/tests/test_advisory.py@@ -22,6 +22,8 @@ from src.live.advisory import (AdvisoryResult,AggregatedVerdict,Verdict,+ clear_advisory_providers,+ register_advisory_provider,)from src.live.advisory.mock import MockAdvisoryfrom src.live.mandate.model import (@@ -153,7 +155,7 @@ def _make_context(**overrides: Any) -> AdvisoryContext:"side": "buy","notional_usd": 100.0,"account_equity": 5000.0,- "account_drawdown": 0.0,+ "utilization_ratio": 0.0,"open_position_count": 0,"total_exposure_usd": 0.0,"funding_usd": 5000.0,@@ -310,34 +312,31 @@ def test_gate_advisory_enabled_with_mock_provider(provider_id="test_mock",)- original_init = AdvisoryOrchestrator.__init__+ register_advisory_provider(mock_provider)+ try:+ _write_mandate(live_runtime, _mandate())+ adapter = _MockAdapter()+ guard = _guard(adapter)- def _patched_init(self: AdvisoryOrchestrator, providers: list) -> None:- original_init(self, [mock_provider])-- monkeypatch.setattr(AdvisoryOrchestrator, "__init__", _patched_init)-- _write_mandate(live_runtime, _mandate())- adapter = _MockAdapter()- guard = _guard(adapter)-- out = json.loads(- guard.execute(- symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0+ out = json.loads(+ guard.execute(+ symbol="AAPL", side="buy", instrument_type="equity", notional_usd=100.0+ ))- )-- assert out.get("status") == "ok"- assert len(adapter.order_calls) == 1- live_action = out.get("live_action")- assert live_action is not None- gate_decision = live_action["gate_decision"]- assert "advisory" in gate_decision["checked_limits"]-- advisory = gate_decision["advisory"]- assert advisory is not None- assert advisory["verdict"] == "approve_with_concerns"- assert "high concentration" in advisory["concerns"]- assert len(advisory["results"]) == 1- assert advisory["results"][0]["provider"] == "test_mock"+ assert out.get("status") == "ok"+ assert len(adapter.order_calls) == 1++ live_action = out.get("live_action")+ assert live_action is not None+ gate_decision = live_action["gate_decision"]+ assert "advisory" in gate_decision["checked_limits"]++ advisory = gate_decision["advisory"]+ assert advisory is not None+ assert advisory["verdict"] == "approve_with_concerns"+ assert "high concentration" in advisory["concerns"]+ assert len(advisory["results"]) == 1+ assert advisory["results"][0]["provider"] == "test_mock"+ finally:+ clear_advisory_providers()