"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(live): wire advisory layer into order gate (opt-in, observational) (#317)
shadowinlife20ea6d6f5a46
diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.pyindex 9e496cff1..d3d4e31e2 100644--- a/agent/src/live/order_guard.py+++ b/agent/src/live/order_guard.py@@ -38,9 +38,15 @@ from __future__ import annotationsimport jsonimport logging+import osfrom datetime import datetime, timezonefrom typing import Any+from src.live.advisory import (+ AdvisoryContext,+ AdvisoryOrchestrator,+ Verdict,+)from src.live.audit import LiveActionEvent, write_live_actionfrom src.live.enforcement import (BREACH_KIND_INSTRUMENT,@@ -74,6 +80,12 @@ _DECISION_ALLOW = "allow"_DECISION_DENY = "deny"_DECISION_PAUSE = "pause_for_reauth"+#: Environment variable controlling advisory review activation.+#: Truthy values (case-insensitive): ``"1"``, ``"true"``, ``"yes"``.+#: Default: off (advisory layer is purely observational and opt-in).+_ADVISORY_ENABLED_ENV = "VIBE_TRADING_ENABLE_ADVISORY"+_ADVISORY_TRUTHY = frozenset({"1", "true", "yes"})+class LiveOrderGuardTool(MCPRemoteTool):"""Mandate-enforcing wrapper for a broker's order-placing remote tool."""@@ -177,7 +189,10 @@ class LiveOrderGuardTool(MCPRemoteTool):)if breach is None:- return self._allow(mandate=mandate, intent=intent, kwargs=kwargs)+ return self._allow(+ mandate=mandate, intent=intent, kwargs=kwargs,+ positions=positions, balance=balance,+ )if breach.kind in (BREACH_KIND_UNIVERSE, BREACH_KIND_INSTRUMENT):return self._deny_breach(breach, mandate=mandate, intent=intent, reauth=False)@@ -288,7 +303,15 @@ class LiveOrderGuardTool(MCPRemoteTool):# -- decision helpers ---------------------------------------------------- def _allow(self, *, mandate: Mandate, intent: OrderIntent, kwargs: dict) -> str:+ def _allow(+ self,+ *,+ mandate: Mandate,+ intent: OrderIntent,+ kwargs: dict,+ positions: object = None,+ balance: object = None,+ ) -> str:"""Forward the order unchanged; consume a count + audit only on success.``MCPServerAdapter.call_tool`` does NOT raise on broker/network failure —@@ -305,6 +328,7 @@ class LiveOrderGuardTool(MCPRemoteTool):under :data:`LIVE_ACTION_RESULT_KEY` so the api_server SSE relay can emita ``live.action`` event without touching the agent loop (H5)."""+ advisory = self._advisory_review(intent, positions, balance, mandate)forwarded = super().execute(**kwargs)broker_response = self._safe_json(forwarded)is_error = self._is_error_envelope(broker_response)@@ -316,6 +340,14 @@ class LiveOrderGuardTool(MCPRemoteTool):"max_leverage", "max_trades_per_day", "account_funding_usd","universe_floors",]+ if advisory is not None:+ checked.append("advisory")+ gate_decision: dict[str, Any] = {+ "allowed": True,+ "decision": _DECISION_ALLOW,+ "checked_limits": checked,+ "advisory": advisory,+ }if is_error:record = self._audit(kind="order_rejected",@@ -324,7 +356,7 @@ class LiveOrderGuardTool(MCPRemoteTool):intent=intent,broker_request=dict(kwargs),broker_response=broker_response,- gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},+ gate_decision=gate_decision,error=self._error_message(broker_response),)else:@@ -337,10 +369,87 @@ class LiveOrderGuardTool(MCPRemoteTool):intent=intent,broker_request=dict(kwargs),broker_response=broker_response,- gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},+ gate_decision=gate_decision,)return self._embed_live_action(forwarded, record)+ # -- advisory review (observational, never blocks) ----------------------++ def _advisory_review(+ self,+ intent: OrderIntent,+ positions: object,+ balance: object,+ mandate: Mandate,+ ) -> dict | None:+ """Run advisory providers if enabled; return verdict dict or None.++ Returns None when advisory is disabled or no providers are configured.+ Returns a dict with ``verdict``, ``concerns``, ``results`` keys otherwise.+ Never raises — all exceptions are caught and converted to+ REVIEW_UNAVAILABLE.+ """+ env_val = os.getenv(_ADVISORY_ENABLED_ENV, "").strip().lower()+ if env_val not in _ADVISORY_TRUTHY:+ return None++ try:+ from src.live.enforcement import (+ _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+ funding_usd = mandate.hard_caps.account_funding_usd++ if equity > 0 and funding_usd > 0:+ drawdown = max(0.0, 1.0 - equity / funding_usd)+ else:+ drawdown = 0.0++ pos_rows = _coerce_position_rows(positions)+ open_count = len(pos_rows) if pos_rows is not None else 0++ context = AdvisoryContext(+ symbol=intent.symbol,+ side=intent.side,+ notional_usd=intent.notional_usd or 0.0,+ account_equity=equity,+ account_drawdown=drawdown,+ open_position_count=open_count,+ total_exposure_usd=exposure,+ funding_usd=funding_usd,+ )++ orchestrator = AdvisoryOrchestrator([])+ if not orchestrator.providers:+ return None++ aggregated = orchestrator.review(context)+ return {+ "verdict": aggregated.verdict.value,+ "concerns": list(aggregated.all_concerns),+ "results": [+ {+ "verdict": r.verdict.value,+ "summary": r.summary,+ "concerns": list(r.concerns),+ "provider": r.provider,+ "confidence": r.confidence,+ }+ for r in aggregated.results+ ],+ }+ except Exception as exc:+ logger.warning("advisory review failed: %s", exc)+ return {+ "verdict": Verdict.REVIEW_UNAVAILABLE.value,+ "concerns": [],+ "error": str(exc),+ }+def _deny(self,*,