"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(live): size MCP buy-limit orders at the worse of quote and limit
cgycorey74c16db6b345
diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.pyindex 88b6c3ea9..0bbd983e4 100644--- a/agent/src/live/order_guard.py+++ b/agent/src/live/order_guard.py@@ -244,6 +244,14 @@ class LiveOrderGuardTool(MCPRemoteTool):return intentprice = self._quote_price(intent)+ # A buy limit is fillable anywhere up to its limit, so the cap must be+ # sized for the worse of the two — same rule as the direct-SDK+ # gate (src.live.sdk_order_gate._implied_notional). Without this the+ # MCP path priced a buy limit at the quote alone, so a limit at 2x the+ # market could fill at twice the authorized notional. Sell limits do+ # not create exposure, so the quote stands there.+ if intent.side == "buy" and intent.limit_price is not None and price is not None:+ price = max(price, intent.limit_price)if price is None:return Noneimplied = intent.quantity * pricediff --git a/agent/src/trading/connectors/robinhood/extractor.py b/agent/src/trading/connectors/robinhood/extractor.pyindex 0e2ef5283..997405b74 100644--- a/agent/src/trading/connectors/robinhood/extractor.py+++ b/agent/src/trading/connectors/robinhood/extractor.py@@ -55,6 +55,10 @@ _NOTIONAL_KEYS = ("notional_usd", "notional", "dollar_amount", "amount")#: Order-size keys for the share/contract/coin quantity path._QUANTITY_KEYS = ("quantity", "qty", "shares", "units")+#: Buy-limit worst-case fill price for notional math. Only the exact+#: normalized name is mapped — never guessed from aliases.+_LIMIT_PRICE_KEY = "limit_price"+def extract_order_intent(remote_name: str, kwargs: dict) -> OrderIntent | None:"""Parse Robinhood ``place_equity_order`` kwargs into a normalized :class:`OrderIntent`.@@ -95,12 +99,27 @@ def extract_order_intent(remote_name: str, kwargs: dict) -> OrderIntent | None:if notional is None and quantity is None:return None+ # A buy limit is fillable anywhere up to its limit: kwargs are forwarded+ # verbatim, so a limit price the gate cannot see is exactly the sizing+ # hole the merged SDK-path fix (789ca2b1) closed. Present-but-unparseable+ # is ambiguous → DENY (fail-closed); absent → None (market-order sizing).+ # Infinity (float overflow, "1e999", "inf") has no finite worst case, so+ # it counts as unparseable too — and must never reach enforcement math+ # or the audit records as an infinite notional.+ if _LIMIT_PRICE_KEY in kwargs:+ limit_price = _first_positive_float(kwargs, (_LIMIT_PRICE_KEY,))+ if limit_price is None or limit_price == float("inf"):+ return None+ else:+ limit_price = None+return OrderIntent(symbol=symbol,side=side,notional_usd=notional,quantity=quantity,instrument_type=instrument,+ limit_price=limit_price,)diff --git a/agent/tests/test_enforcement_l6.py b/agent/tests/test_enforcement_l6.pyindex 702e18654..f2070105b 100644--- a/agent/tests/test_enforcement_l6.py+++ b/agent/tests/test_enforcement_l6.py@@ -114,6 +114,44 @@ def test_extractor_rejects_missing_or_ambiguous_fields() -> None:assert extract_order_intent("place_equity_order", {"symbol": "AAPL", "side": "buy", "instrument_type": "equity"}) is None+def test_extractor_maps_limit_price() -> None:+ """A buy limit's worst-case fill price must reach the+ gate, which sizes the notional at the worse of quote and limit."""+ intent = extract_order_intent(+ "place_equity_order",+ {"symbol": "AAPL", "side": "buy", "instrument_type": "equity",+ "quantity": 5, "limit_price": 200.0},+ )+ assert intent is not None+ assert intent.limit_price == pytest.approx(200.0)+++def test_extractor_limit_price_absent_is_none() -> None:+ """No limit_price kwarg → market-order sizing (intent.limit_price None)."""+ intent = extract_order_intent(+ "place_equity_order",+ {"symbol": "AAPL", "side": "buy", "instrument_type": "equity", "quantity": 5},+ )+ assert intent is not None+ assert intent.limit_price is None+++def test_extractor_rejects_unparseable_limit_price() -> None:+ """A present-but-unparseable limit price is forwarded to the broker verbatim+ and cannot be priced → the whole intent is ambiguous → DENY (fail-closed)."""+ assert extract_order_intent(+ "place_equity_order",+ {"symbol": "AAPL", "side": "buy", "instrument_type": "equity",+ "quantity": 5, "limit_price": "not-a-price"},+ ) is None+ # Non-positive and NaN are equally unusable.+ assert extract_order_intent(+ "place_equity_order",+ {"symbol": "AAPL", "side": "buy", "instrument_type": "equity",+ "quantity": 5, "limit_price": 0},+ ) is None++# --------------------------------------------------------------------------- ## L6 — quantity-only quote derivation through the gate ## --------------------------------------------------------------------------- #@@ -320,3 +358,15 @@ def test_normalization_preserves_a_none_asset_class(live_runtime: Path) -> None:normalized = guard._normalize_intent_notional(intent)assert normalized is not Noneassert normalized.asset_class is None++[email protected]("bad", ["inf", "1e999", float("inf"), "9" * 400])+def test_extractor_rejects_non_finite_limit_price(bad) -> None:+ """A limit price of Infinity (via overflow or 'inf' spellings) has no+ finite worst case, so it must be DENIED at extraction — never allowed to+ reach enforcement math or the audit records as an infinite notional."""+ assert extract_order_intent(+ "place_equity_order",+ {"symbol": "AAPL", "side": "buy", "instrument_type": "equity",+ "quantity": 5, "limit_price": bad},+ ) is Nonediff --git a/agent/tests/test_limit_price_notional.py b/agent/tests/test_limit_price_notional.pyindex 166649eef..9a0651a0a 100644--- a/agent/tests/test_limit_price_notional.py+++ b/agent/tests/test_limit_price_notional.py@@ -1,20 +1,26 @@-"""Buy-limit notional must be sized at the worse of quote and limit (#18).+"""Buy-limit notional must be sized at the worse of quote and limit.A buy limit at 2x the market used to be priced at the quote alone, so itpassed a cap sized for the quote while being fillable at twice theauthorized amount. Sell limits do not create exposure, so the quote stands-there.+there. The MCP gate path (LiveOrderGuardTool via the Robinhood extractor)+must apply the same rule as the direct-SDK gate."""from __future__ import annotations+import json+from datetime import datetime, timedelta, timezone+from pathlib import Pathfrom types import SimpleNamespaceimport pytest+import src.live.paths as pathsimport src.live.sdk_order_gate as sdk_order_gatefrom src.live.enforcement import OrderIntent-from src.live.mandate.model import AssetClass, InstrumentType+from src.live.mandate.model import AssetClass, InstrumentType, MANDATE_SCHEMA_VERSION+from src.tools.mcp import MCPRemoteToolSpecdef _connector(last: float):@@ -63,3 +69,163 @@ def test_sell_limit_keeps_the_quote() -> None:)assert intent is not Noneassert intent.notional_usd == pytest.approx(1000.0)+++# --------------------------------------------------------------------------- #+# MCP gate path (LiveOrderGuardTool) — the same rule as the SDK path, #+# reached through the Robinhood extractor + MCP adapter. #+# --------------------------------------------------------------------------- #+++def live_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setattr(paths, "get_runtime_root", lambda: tmp_path)+ return tmp_path+++class _McpQuoteAdapter:+ """Robinhood-shaped MCP adapter: quote tool + order placement recorder."""++ def __init__(self, *, price: float) -> None:+ self.server_name = "robinhood"+ self._price = price+ self.order_calls: list[dict] = []++ def call_tool(self, remote_name: str, arguments: dict, *, local_name=None) -> dict:+ if remote_name == "get_equity_positions":+ return {"positions": [], "status": "ok"}+ if remote_name == "get_portfolio":+ return {"equity": 5000.0, "status": "ok"}+ if remote_name == "get_equity_quotes":+ return {"status": "ok", "results": [{"symbol": arguments.get("symbol"), "last_price": self._price}]}+ self.order_calls.append({"remote": remote_name, "arguments": arguments})+ return {"status": "ok", "order_id": "rh_test_1", "state": "accepted"}+++def _mcp_spec() -> MCPRemoteToolSpec:+ return MCPRemoteToolSpec(+ server_name="robinhood",+ remote_name="place_equity_order",+ local_name="mcp_robinhood_place_equity_order",+ description="Place an order.",+ parameters={"type": "object", "properties": {}, "additionalProperties": True},+ )+++def _write_mandate(live_runtime: Path, *, max_order_notional_usd: float) -> None:+ broker = live_runtime / "live" / "robinhood"+ broker.mkdir(parents=True, exist_ok=True)+ created = datetime.now(timezone.utc)+ payload = {+ "schema_version": MANDATE_SCHEMA_VERSION,+ "hard_caps": {+ "account_funding_usd": 5000.0,+ "max_order_notional_usd": max_order_notional_usd,+ "max_total_exposure_usd": 5000.0,+ "max_leverage": 1.0,+ "allowed_instruments": ["equity", "etf"],+ "max_trades_per_day": 5,+ },+ "universe": {+ "asset_classes": ["us_equity", "us_etf"],+ "min_market_cap_usd": None,+ "min_avg_daily_volume_usd": None,+ "exclude_symbols": [],+ },+ "consent": {+ "created_at": created.isoformat(),+ "consent_token_sha256": "deadbeef",+ "broker": "robinhood",+ "account_ref": "acct_ref",+ "expires_at": (created + timedelta(days=30)).isoformat(),+ },+ }+ (broker / "mandate.json").write_text(json.dumps(payload), encoding="utf-8")+++def _mcp_guard(live_runtime: Path, adapter, *, max_order_notional_usd: float = 750.0):+ from src.live.order_guard import LiveOrderGuardTool++ _write_mandate(live_runtime, max_order_notional_usd=max_order_notional_usd)+ return LiveOrderGuardTool(adapter, _mcp_spec(), broker="robinhood", session_id="s1")+++def test_mcp_buy_limit_above_quote_is_blocked_at_the_limit(live_runtime: Path) -> None:+ """qty=5, quote=$100, limit=$200, cap=$750: worst-case fill $1000 must be+ enforced at the limit, so the order is BLOCKED, never forwarded."""+ adapter = _McpQuoteAdapter(price=100.0)+ guard = _mcp_guard(live_runtime, adapter, max_order_notional_usd=750.0)++ out = json.loads(+ guard.execute(+ symbol="AAPL", side="buy", instrument_type="equity",+ quantity=5.0, limit_price=200.0, order_type="limit",+ )+ )+ assert out["status"] == "blocked"+ assert out["breach"]["limit"] == "max_order_notional_usd"+ assert out["breach"]["attempted_value"] == pytest.approx(1000.0)+ assert adapter.order_calls == []+++def test_mcp_buy_limit_below_quote_keeps_the_quote(live_runtime: Path) -> None:+ """A limit at or below the market is maximally fillable at the quote, so a+ $80 limit on a $100 quote must be sized at $100, not the (lower) limit."""+ adapter = _McpQuoteAdapter(price=100.0)+ guard = _mcp_guard(live_runtime, adapter, max_order_notional_usd=2000.0)++ out = json.loads(+ guard.execute(+ symbol="AAPL", side="buy", instrument_type="equity",+ quantity=10.0, limit_price=80.0, order_type="limit",+ )+ )+ assert out["status"] == "ok" # 10 * 100 = 1000 <= 2000+ assert len(adapter.order_calls) == 1+++def test_mcp_market_order_without_limit_is_unchanged(live_runtime: Path) -> None:+ adapter = _McpQuoteAdapter(price=100.0)+ guard = _mcp_guard(live_runtime, adapter, max_order_notional_usd=2000.0)++ out = json.loads(+ guard.execute(+ symbol="AAPL", side="buy", instrument_type="equity",+ quantity=10.0,+ )+ )+ assert out["status"] == "ok"+ assert len(adapter.order_calls) == 1+++def test_mcp_sell_limit_keeps_the_quote(live_runtime: Path) -> None:+ """A sell limit does not create exposure, so a $200 sell limit on a $100+ quote must be sized at the quote (mirrors the SDK gate)."""+ adapter = _McpQuoteAdapter(price=100.0)+ guard = _mcp_guard(live_runtime, adapter, max_order_notional_usd=2000.0)++ out = json.loads(+ guard.execute(+ symbol="AAPL", side="sell", instrument_type="equity",+ quantity=5.0, limit_price=200.0, order_type="limit",+ )+ )+ # 5 * 100 = 500 <= 2000 → allowed; the $200 limit must not inflate it.+ assert out["status"] == "ok"+ assert len(adapter.order_calls) == 1+++def test_mcp_garbage_limit_price_denies_fail_closed(live_runtime: Path) -> None:+ """A present-but-unparseable limit price is forwarded to the broker verbatim+ and cannot be priced → DENY (fail-closed), never a wave-through."""+ adapter = _McpQuoteAdapter(price=100.0)+ guard = _mcp_guard(live_runtime, adapter, max_order_notional_usd=2000.0)++ out = json.loads(+ guard.execute(+ symbol="AAPL", side="buy", instrument_type="equity",+ quantity=5.0, limit_price="not-a-price",+ )+ )+ assert out["status"] == "blocked"+ assert adapter.order_calls == []