Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(live): direct-SDK bounded-autonomy order gate + HK/CN universe

Haozhe Wu0df32f2eb3d3
diff --git a/agent/src/live/audit.py b/agent/src/live/audit.py
index 8e1c4e9e5..422a2cb75 100644
--- a/agent/src/live/audit.py
+++ b/agent/src/live/audit.py
@@ -70,6 +70,7 @@ _LEDGER_FILENAME = "audit.jsonl"
#: Canonical live-action kinds (SPEC §5).
LiveActionKind = Literal[
"order_placed",
+ "order_cancelled",
"order_rejected",
"mandate_committed",
"breach",
diff --git a/agent/src/live/daily_count.py b/agent/src/live/daily_count.py
new file mode 100644
index 000000000..d4d1395c9
--- /dev/null
+++ b/agent/src/live/daily_count.py
@@ -0,0 +1,54 @@
+"""Per-broker daily order counter (UTC calendar day, atomic write).
+
+Shared by every live order path (the MCP ``LiveOrderGuardTool`` keeps its own
+in-class copy for now; the direct-SDK gate uses these helpers). The counter is
+advisory defense-in-depth — the broker enforces the real ceiling — so any
+read failure reads as ``0`` (fail-open on the count only, never on the order).
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+
+from src.live.paths import broker_dir
+
+_COUNTER_FILENAME = "trade_counter.json"
+
+
+def _counter_path(broker: str):
+ return broker_dir(broker) / _COUNTER_FILENAME
+
+
+def _utc_today() -> str:
+ """Return today's UTC calendar date as ``YYYY-MM-DD``."""
+ return datetime.now(timezone.utc).date().isoformat()
+
+
+def read_daily_count(broker: str) -> int:
+ """Return today's order count for ``broker`` (UTC rollover; 0 on any miss)."""
+ path = _counter_path(broker)
+ if not path.is_file():
+ return 0
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return 0
+ if not isinstance(raw, dict) or raw.get("date") != _utc_today():
+ return 0
+ try:
+ return int(raw.get("count", 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+def increment_daily_count(broker: str) -> int:
+ """Persist ``broker``'s incremented count for today (atomic). Returns new count."""
+ today = _utc_today()
+ count = read_daily_count(broker) + 1
+ path = _counter_path(broker)
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ tmp = path.with_name(f".{path.name}.tmp")
+ tmp.write_text(json.dumps({"date": today, "count": count}, ensure_ascii=False), encoding="utf-8")
+ tmp.replace(path)
+ return count
diff --git a/agent/src/live/enforcement.py b/agent/src/live/enforcement.py
index ac2d6fec3..c0668ada1 100644
--- a/agent/src/live/enforcement.py
+++ b/agent/src/live/enforcement.py
@@ -57,7 +57,11 @@ class UniverseDataUnavailable(Exception):
_ASSET_CLASS_MARKET: dict[AssetClass, str] = {
AssetClass.US_EQUITY: "us_equity",
AssetClass.US_ETF: "us_equity",
+ AssetClass.HK_EQUITY: "hk_equity",
AssetClass.CRYPTO: "crypto",
+ # CN_EQUITY has no loader market wired here, so market-cap / liquidity floors
+ # for A-shares fail closed (deny) rather than wave through — intentional. If
+ # ever wired, the registry's A-share market key is "a_share" (not "cn_equity").
}
#: Breach ``kind`` values. ``universe``/``instrument`` are structural (DENY);
@@ -103,6 +107,12 @@ class OrderIntent:
notional_usd: Order notional in USD when derivable.
quantity: Share/contract/coin quantity when notional is not given.
instrument_type: Mapped :class:`~src.live.mandate.model.InstrumentType`.
+ asset_class: Explicit universe :class:`~src.live.mandate.model.AssetClass`
+ when the caller can determine the market (multi-market connectors:
+ an ``EQUITY`` may be US, HK or A-share). When ``None`` the gate falls
+ back to the instrument-type default (US-centric), preserving the
+ single-market behavior. Carrying it explicitly is what lets the
+ mandate gate distinguish e.g. an HK equity from a US equity.
"""
symbol: str
@@ -110,6 +120,7 @@ class OrderIntent:
notional_usd: float | None
quantity: float | None
instrument_type: InstrumentType
+ asset_class: AssetClass | None = None
@dataclass(frozen=True)
@@ -430,8 +441,10 @@ def check_mandate(
)
# 3. Asset-class allowance (universe bucket). OPTION has no bucket and is
- # governed by allowed_instruments alone.
- asset_class = _INSTRUMENT_ASSET_CLASS.get(intent.instrument_type)
+ # governed by allowed_instruments alone. An explicit intent.asset_class
+ # (multi-market connectors: US/HK/CN equities) wins over the instrument
+ # default so the gate buckets HK/A-share correctly.
+ asset_class = intent.asset_class or _INSTRUMENT_ASSET_CLASS.get(intent.instrument_type)
if asset_class is not None and asset_class not in universe.asset_classes:
return _breach(
broker=broker, remote_tool=remote_tool, intent=intent,
diff --git a/agent/src/live/mandate/model.py b/agent/src/live/mandate/model.py
index 563e80c7b..fc0a4dce1 100644
--- a/agent/src/live/mandate/model.py
+++ b/agent/src/live/mandate/model.py
@@ -28,6 +28,8 @@ class AssetClass(str, Enum):
US_EQUITY = "us_equity"
US_ETF = "us_etf"
+ HK_EQUITY = "hk_equity"
+ CN_EQUITY = "cn_equity"
CRYPTO = "crypto"
diff --git a/agent/src/live/order_guard.py b/agent/src/live/order_guard.py
index a2185db6c..9e496cff1 100644
--- a/agent/src/live/order_guard.py
+++ b/agent/src/live/order_guard.py
@@ -55,13 +55,11 @@ from src.live.extractors import get_extractor
from src.live.halt import halt_flag_set
from src.live.mandate.model import MANDATE_SCHEMA_VERSION, Mandate
from src.live.mandate.store import load_mandate
-from src.live.paths import broker_dir
+from src.live.daily_count import increment_daily_count, read_daily_count
from src.tools.mcp import MCPRemoteTool, MCPRemoteToolSpec, MCPServerAdapter
logger = logging.getLogger(__name__)
-_COUNTER_FILENAME = "trade_counter.json"
-
#: Frozen marker key the api_server SSE relay reads off the returned tool_result
#: to emit a ``live.action`` event without touching the agent loop.
LIVE_ACTION_RESULT_KEY = "live_action"
@@ -485,43 +483,13 @@ class LiveOrderGuardTool(MCPRemoteTool):
# -- daily counter ------------------------------------------------------
- def _counter_path(self):
- """Return the per-broker ``trade_counter.json`` path."""
- return broker_dir(self.broker) / _COUNTER_FILENAME
-
def _read_daily_count(self) -> int:
- """Return today's order count from the persisted counter (UTC rollover).
-
- A missing/unreadable counter, or one stamped with a previous UTC date,
- reads as ``0``. Parse failure reads as ``0`` (the count is advisory; the
- broker enforces the hard ceiling).
- """
- path = self._counter_path()
- if not path.is_file():
- return 0
- try:
- raw = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, ValueError):
- return 0
- if not isinstance(raw, dict) or raw.get("date") != _utc_today():
- return 0
- try:
- return int(raw.get("count", 0))
- except (TypeError, ValueError):
- return 0
+ """Return today's order count via the shared per-broker counter."""
+ return read_daily_count(self.broker)
def _increment_daily_count(self) -> None:
- """Persist today's incremented order count (UTC rollover, atomic write)."""
- today = _utc_today()
- count = self._read_daily_count() + 1
- path = self._counter_path()
- path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
- tmp = path.with_name(f".{path.name}.tmp")
- tmp.write_text(
- json.dumps({"date": today, "count": count}, ensure_ascii=False),
- encoding="utf-8",
- )
- tmp.replace(path)
+ """Increment today's order count via the shared per-broker counter."""
+ increment_daily_count(self.broker)
# -- audit + misc -------------------------------------------------------
@@ -721,11 +689,6 @@ def _price_from_quote_dict(quote: dict) -> float | None:
return None
-def _utc_today() -> str:
- """Return today's UTC calendar date as ``YYYY-MM-DD``."""
- return datetime.now(timezone.utc).date().isoformat()
-
-
def _describe_intent(intent: OrderIntent | None) -> str | None:
"""Render a human-readable normalized intent for the audit record."""
if intent is None:
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
index 5f8a78cd4..ff1723b7f 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -23,16 +23,30 @@ from src.live.classification import ToolClass, classify_tool
from src.live.halt import halt_flag_set
from src.live.order_guard import LiveOrderGuardTool
from src.tools.mcp import MCPRemoteTool
+from src.trading.connectors.alpaca.classification import ALPACA_TOOL_CLASS
+from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASS
+from src.trading.connectors.futu.classification import FUTU_TOOL_CLASS
from src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS
+from src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASS
+from src.trading.connectors.okx.classification import OKX_TOOL_CLASS
from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASS
+from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
logger = logging.getLogger(__name__)
#: Per-broker curated classification maps (Tier 2). Keyed by broker name; an
-#: aliased server key resolves to its broker via :func:`_broker_for`.
+#: aliased server key resolves to its broker via :func:`_broker_for`. Order-
+#: mutating ops are pinned WRITE so the live gate fails closed; an op absent
+#: from its broker map and not annotated read-only resolves to UNKNOWN → WRITE.
_BROKER_CURATED_MAPS = {
"robinhood": ROBINHOOD_TOOL_CLASS,
"ibkr": IBKR_TOOL_CLASS,
+ "tiger": TIGER_TOOL_CLASS,
+ "longbridge": LONGBRIDGE_TOOL_CLASS,
+ "alpaca": ALPACA_TOOL_CLASS,
+ "okx": OKX_TOOL_CLASS,
+ "binance": BINANCE_TOOL_CLASS,
+ "futu": FUTU_TOOL_CLASS,
}
diff --git a/agent/src/live/sdk_order_gate.py b/agent/src/live/sdk_order_gate.py
new file mode 100644
index 000000000..fa0abae04
--- /dev/null
+++ b/agent/src/live/sdk_order_gate.py
@@ -0,0 +1,353 @@
+"""Pre-trade mandate gate for DIRECT-SDK connectors (SPEC Mandate Enforcement §3).
+
+The MCP :class:`~src.live.order_guard.LiveOrderGuardTool` gates Robinhood by
+wrapping a remote MCP tool. Direct-SDK connectors (tiger / alpaca / okx /
+binance / futu) place orders through a normal Python call, not an MCP tool, so
+they need a function-based gate with the SAME ceremony, all fail-closed before
+any order reaches the broker:
+
+1. ``load_mandate`` — no valid mandate / unknown schema version → DENY.
+2. expiry — past ``consent.expires_at`` → DENY (routes to re-auth).
+3. ``halt_flag_set`` — kill switch tripped → DENY, no broker call.
+4. notional normalization — a ``quantity`` order is priced (connector quote →
+ data loaders) and enforced on the LARGER of explicit notional and
+ ``quantity × price``; fail-closed DENY when unpriceable.
+5. read positions + balance via the connector's own READ functions.
+6. ``check_mandate`` — ALLOW → ``connector.place_order`` / DENY (structural) /
+ PAUSE_FOR_REAUTH (quantitative).
+
+A daily count is consumed only on a confirmed ALLOW whose ``place_order``
+returned a non-error envelope. Every decision writes one audit event and the
+returned payload carries the redacted record under ``live_action``.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from src.live.audit import LiveActionEvent, write_live_action
+from src.live.daily_count import increment_daily_count, read_daily_count
+from src.live.enforcement import (
+ BREACH_KIND_INSTRUMENT,
+ BREACH_KIND_UNIVERSE,
+ OrderIntent,
+ check_mandate,
+ instrument_asset_class,
+ last_price_usd,
+)
+from src.live.halt import halt_flag_set
+from src.live.mandate.model import MANDATE_SCHEMA_VERSION, Mandate
+from src.live.mandate.store import load_mandate
+
+logger = logging.getLogger(__name__)
+
+LIVE_ACTION_RESULT_KEY = "live_action"
+_REMOTE_TOOL = "place_order"
+
+_DECISION_ALLOW = "allow"
+_DECISION_DENY = "deny"
+_DECISION_PAUSE = "pause_for_reauth"
+
+
+def execute_live_order(
+ *,
+ broker: str,
+ connector_module: Any,
+ config: Any,
+ intent: OrderIntent,
+ place_kwargs: dict[str, Any],
+ session_id: str = "",
+) -> dict[str, Any]:
+ """Run the live mandate gate around a direct-SDK ``place_order``.
+
+ Args:
+ broker: Broker key (mandate/halt/counter/audit are keyed by this).
+ connector_module: The connector's ``sdk`` module (provides
+ ``place_order``/``get_positions``/``get_account_snapshot``/``get_quote``).
+ config: The connector config object for a LIVE profile.
+ intent: Normalized :class:`OrderIntent` built from the tool args.
+ place_kwargs: Keyword args forwarded verbatim to ``connector_module.place_order``
+ on ALLOW (``symbol``/``side``/``quantity``/``notional``/``order_type``/
+ ``limit_price``/``time_in_force``).
+ session_id: Originating session id, stamped onto audit events.
+
+ Returns:
+ On ALLOW: the connector's ``place_order`` result dict (with a
+ ``live_action`` record attached). Otherwise a refusal envelope
+ ``{"status":"blocked","decision",...}``.
+ """
+ broker = (broker or "").strip().lower()
+
+ mandate = load_mandate(broker)
+ if mandate is None or mandate.schema_version != MANDATE_SCHEMA_VERSION:
+ return _deny(broker, session_id, "no valid mandate on file", ["mandate"], mandate, intent=None)
+
+ if _is_expired(mandate):
+ return _deny(broker, session_id, "mandate expired — re-authorize", ["mandate", "expiry"], mandate, intent=None, reauth=True)
+
+ if halt_flag_set(broker):
+ return _deny(broker, session_id, "live trading halted", ["mandate", "expiry", "halt_flag"], mandate, intent=None)
+
+ normalized = _normalize_notional(intent, connector_module, config)
+ if normalized is None:
+ return _deny(
+ broker, session_id, "quantity order notional could not be priced (fail-closed)",
+ ["mandate", "expiry", "halt_flag", "quote"], mandate, intent=intent,
+ )
+ intent = normalized
+
+ positions = _safe_read(connector_module, "get_positions", config)
+ balance = _safe_read(connector_module, "get_account_snapshot", config)
+ daily_count = read_daily_count(broker)
+
+ breach = check_mandate(
+ mandate, intent, positions, balance,
+ broker=broker, remote_tool=_REMOTE_TOOL, daily_count=daily_count,
+ )
+
+ if breach is None:
+ return _allow(broker, session_id, connector_module, config, intent, place_kwargs, mandate)
+
+ reauth = breach.kind not in (BREACH_KIND_UNIVERSE, BREACH_KIND_INSTRUMENT)
+ return _deny_breach(broker, session_id, breach, mandate, intent, reauth)
+
+
+# --------------------------------------------------------------------------- #
+# Decision helpers
+# --------------------------------------------------------------------------- #
+
+
+def _allow(broker, session_id, connector_module, config, intent, place_kwargs, mandate) -> dict[str, Any]:
+ """Execute the order; consume a count + audit only on a non-error result."""
+ try:
+ result = connector_module.place_order(config, **place_kwargs)
+ except Exception as exc: # noqa: BLE001 - a connector raise must not escape the gate
+ logger.warning("live place_order raised for %s: %s", broker, exc)
+ result = {"status": "error", "error": str(exc)}
+
+ is_error = not isinstance(result, dict) or str(result.get("status", "")).lower() != "ok"
+ checked = [
+ "mandate", "expiry", "halt_flag", "exclude_symbols", "allowed_instruments",
+ "asset_classes", "max_order_notional_usd", "max_total_exposure_usd",
+ "max_leverage", "max_trades_per_day", "account_funding_usd", "universe_floors",
+ ]
+ if is_error:
+ record = _audit(
+ broker, session_id, kind="order_rejected", outcome="error", mandate=mandate, intent=intent,
+ broker_request=dict(place_kwargs), broker_response=result if isinstance(result, dict) else {"raw": result},
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ error=_error_message(result),
+ )
+ else:
+ increment_daily_count(broker)
+ record = _audit(
+ broker, session_id, kind="order_placed", outcome="accepted", mandate=mandate, intent=intent,
+ broker_request=dict(place_kwargs), broker_response=result,
+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},
+ )
+ if isinstance(result, dict) and record is not None:
+ result = {**result, LIVE_ACTION_RESULT_KEY: record}
+ return result if isinstance(result, dict) else {"status": "error", "error": "non-dict broker result"}
+
+
+def _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False) -> dict[str, Any]:
+ """Audit + return a refusal for a pre-check / structural DENY."""
+ record = _audit(
+ broker, session_id, kind="order_rejected", outcome="blocked", mandate=mandate, intent=intent,
+ broker_request=None, broker_response=None,
+ gate_decision={"allowed": False, "decision": _DECISION_DENY, "checked_limits": checked},
+ error=reason,
+ )
+ return _refusal(broker, decision=_DECISION_DENY, reason=reason, reauth=reauth, record=record)
+
+
+def _deny_breach(broker, session_id, breach, mandate, intent, reauth) -> dict[str, Any]:
+ """Audit + return a refusal for a ``check_mandate`` breach."""
+ decision = _DECISION_PAUSE if reauth else _DECISION_DENY
+ record = _audit(
+ broker, session_id, kind="breach", outcome="blocked", mandate=mandate, intent=intent,
+ broker_request=None, broker_response=None,
+ gate_decision={
+ "allowed": False, "decision": decision, "limit": breach.limit, "kind": breach.kind,
+ "limit_value": breach.limit_value, "attempted_value": breach.attempted_value,
+ },
+ error=breach.detail or f"order breaches {breach.limit}",
+ )
+ return _refusal(
+ broker, decision=decision, reason=breach.detail or f"order breaches {breach.limit}",
+ reauth=reauth, breach=breach, record=record,
+ )
+
+
+def _refusal(broker, *, decision, reason, reauth, breach=None, record=None) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "status": "blocked",
+ "decision": decision,
+ "reason": reason,
+ "broker": broker,
+ "requires_reauthorization": reauth,
+ }
+ if record is not None:
+ payload[LIVE_ACTION_RESULT_KEY] = record
+ if breach is not None:
+ payload["breach"] = {
+ "broker": breach.broker, "limit": breach.limit, "limit_value": breach.limit_value,
+ "attempted_value": breach.attempted_value, "overage": breach.overage,
+ "kind": breach.kind, "detail": breach.detail,
+ "proposed_action": {
+ "symbol": breach.proposed_action.symbol, "side": breach.proposed_action.side,
+ "notional_usd": breach.proposed_action.notional_usd, "quantity": breach.proposed_action.quantity,
+ "instrument_type": breach.proposed_action.instrument_type.value,
+ },
+ }
+ return payload
+
+
+# --------------------------------------------------------------------------- #
+# Notional normalization + reads
+# --------------------------------------------------------------------------- #
+
+
+def _normalize_notional(intent: OrderIntent, connector_module: Any, config: Any) -> OrderIntent | None:
+ """Stamp a single authoritative ``notional_usd`` (quantity → priced).
+
+ Currency note: the connector quote is the broker's native currency (HKD for
+ HK, CNH for A-share). The mandate caps are USD; treating a local-currency
+ figure as USD OVER-states USD exposure for HKD/CNH (≈7-8x), so the caps bind
+ CONSERVATIVELY (over-deny, never under-deny). FX normalization is a follow-up
+ before HK/CN are promoted past the structural asset-class gate.
+ """
+ if intent.quantity is None:
+ return intent
+ price = _quote_price(intent, connector_module, config)
+ if price is None:
+ return None
+ implied = intent.quantity * price
+ if implied != implied or implied <= 0:
+ return None
+ explicit = intent.notional_usd if intent.notional_usd is not None else 0.0
+ enforced = max(float(explicit), implied)
+ return OrderIntent(
+ symbol=intent.symbol, side=intent.side, notional_usd=enforced,
+ quantity=intent.quantity, instrument_type=intent.instrument_type, asset_class=intent.asset_class,
+ )
+
+
+def _quote_price(intent: OrderIntent, connector_module: Any, config: Any) -> float | None:
+ """Live USD price for the intent symbol: connector quote first, loaders next."""
+ broker_price = _connector_quote_price(connector_module, config, intent.symbol)
+ if broker_price is not None:
+ return broker_price
+ asset_class = intent.asset_class or instrument_asset_class(intent.instrument_type)
+ if asset_class is None:
+ return None
+ try:
+ return last_price_usd(intent.symbol, asset_class)
+ except Exception as exc: # noqa: BLE001 - loader failure → fail-closed
+ logger.warning("loader quote failed for %s: %s", intent.symbol, exc)
+ return None
+
+
+def _connector_quote_price(connector_module: Any, config: Any, symbol: str) -> float | None:
+ """Parse a positive price from the connector's ``get_quote`` envelope."""
+ getter = getattr(connector_module, "get_quote", None)
+ if getter is None:
+ return None
+ try:
+ result = getter(symbol, config=config)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("connector quote failed for %s: %s", symbol, exc)
+ return None
+ if not isinstance(result, dict) or str(result.get("status", "")).lower() == "error":
+ return None
+ quote = result.get("quote")
+ if not isinstance(quote, dict):
+ return None
+ for key in ("last", "ask", "bid", "close"):
+ if key in quote:
+ try:
+ value = float(quote[key])
+ except (TypeError, ValueError):
+ continue
+ if value == value and value > 0:
+ return value
+ return None
+
+
+def _safe_read(connector_module: Any, fn_name: str, config: Any) -> object:
+ """Call a connector read fn, returning ``None`` on any error (fail-closed)."""
+ fn = getattr(connector_module, fn_name, None)
+ if fn is None:
+ return None
+ try:
+ result = fn(config)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("connector read %s failed: %s", fn_name, exc)
+ return None
+ if isinstance(result, dict) and str(result.get("status", "")).lower() == "error":
+ return None
+ return result
+
+
+# --------------------------------------------------------------------------- #
+# Audit + misc
+# --------------------------------------------------------------------------- #
+
+
+def _audit(broker, session_id, *, kind, outcome, mandate, intent, broker_request, broker_response, gate_decision, error=None) -> dict | None:
+ consent = mandate.consent if mandate is not None else None
+ try:
+ event = LiveActionEvent(
+ kind=kind, # type: ignore[arg-type]
+ session_id=session_id,
+ outcome=outcome, # type: ignore[arg-type]
+ server=broker,
+ remote_tool=_REMOTE_TOOL,
+ intent_normalized=_describe_intent(intent),
+ mandate_snapshot_ref=consent.consent_token_sha256 if consent else None,
+ consent_record_ref=consent.account_ref if consent else None,
+ broker_request=broker_request,
+ broker_response=broker_response,
+ gate_decision=gate_decision,
+ error=error,
+ )
+ try:
+ return write_live_action(event, event_callback=None, trace_writer=None)
+ except TypeError:
+ return write_live_action(event)
+ except Exception as exc: # auditing must never block a decision
+ logger.warning("live-action audit write failed (%s): %s", kind, exc)
+ return None
+
+
+def _is_expired(mandate: Mandate) -> bool:
+ raw = mandate.consent.expires_at
+ try:
+ expires = datetime.fromisoformat(raw)
+ except (TypeError, ValueError):
+ return True
+ if expires.tzinfo is None:
+ expires = expires.replace(tzinfo=timezone.utc)
+ return datetime.now(timezone.utc) >= expires
+
+
+def _error_message(result: object) -> str:
+ if isinstance(result, dict):
+ for key in ("error", "message", "detail"):
+ value = result.get(key)
+ if isinstance(value, str) and value:
+ return value
+ return "broker order returned an error"
+
+
+def _describe_intent(intent: OrderIntent | None) -> str | None:
+ if intent is None:
+ return None
+ size = (
+ f"${intent.notional_usd:g}" if intent.notional_usd is not None
+ else f"{intent.quantity:g} units" if intent.quantity is not None
+ else "?"
+ )
+ return f"{intent.side} {size} {intent.symbol} ({intent.instrument_type.value})"
diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.py
new file mode 100644
index 000000000..462c43ce9
--- /dev/null
+++ b/agent/tests/test_sdk_connectors.py
@@ -0,0 +1,463 @@
+"""Tests for the direct-SDK trading connectors (Tiger, Longbridge).
+
+Layer A is read-only; these tests exercise the parts that do not require the
+optional broker SDKs or live credentials: profile registration, the paper/live
+identity guard, config resolution, read/write classification, secret redaction,
+and the service dispatch degrading cleanly when nothing is configured.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from src.live.classification import ToolClass
+from src.trading import profiles, service
+from src.trading.connectors.alpaca import sdk as al
+from src.trading.connectors.alpaca.classification import ALPACA_TOOL_CLASS
+from src.trading.connectors.binance import sdk as bn
+from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASS
+from src.trading.connectors.futu import sdk as ft
+from src.trading.connectors.futu.classification import FUTU_TOOL_CLASS
+from src.trading.connectors.longbridge import sdk as lb
+from src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASS
+from src.trading.connectors.okx import sdk as ox
+from src.trading.connectors.okx.classification import OKX_TOOL_CLASS
+from src.trading.connectors.tiger import sdk as tg
+from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
+
+pytestmark = pytest.mark.unit
+
+
+# --------------------------------------------------------------------------- #
+# Profile registration
+# --------------------------------------------------------------------------- #
+
+
+def test_sdk_profiles_registered() -> None:
+ """All six broker connectors register paper and read-only live profiles."""
+ ids = {p.id for p in profiles.list_profiles()}
+ assert {
+ "tiger-paper-sdk", "tiger-live-sdk-readonly",
+ "longbridge-paper-sdk", "longbridge-live-sdk-readonly",
+ "alpaca-paper-sdk", "alpaca-live-sdk-readonly",
+ "okx-paper-sdk", "okx-live-sdk-readonly",
+ "binance-paper-sdk", "binance-live-sdk-readonly",
+ "futu-paper-sdk", "futu-live-sdk-readonly",
+ } <= ids
+
+
+ "profile_id, connector, environment",
+ [
+ ("tiger-paper-sdk", "tiger", "paper"),
+ ("tiger-live-sdk-readonly", "tiger", "live"),
+ ("longbridge-paper-sdk", "longbridge", "paper"),
+ ("longbridge-live-sdk-readonly", "longbridge", "live"),
+ ("alpaca-paper-sdk", "alpaca", "paper"),
+ ("alpaca-live-sdk-readonly", "alpaca", "live"),
+ ("okx-paper-sdk", "okx", "paper"),
+ ("okx-live-sdk-readonly", "okx", "live"),
+ ("binance-paper-sdk", "binance", "paper"),
+ ("binance-live-sdk-readonly", "binance", "live"),
+ ("futu-paper-sdk", "futu", "paper"),
+ ("futu-live-sdk-readonly", "futu", "live"),
+ ],
+)
+def test_sdk_profiles_are_readonly_broker_sdk(profile_id, connector, environment) -> None:
+ """Layer A profiles are broker_sdk transport and strictly read-only."""
+ profile = profiles.profile_by_id(profile_id)
+ assert profile.connector == connector
+ assert profile.environment == environment
+ assert profile.transport == "broker_sdk"
+ assert profile.readonly is True
+ # No order-placing / mandate-gated capability is advertised in Layer A.
+ assert not any(".place" in cap or "requires_mandate" in cap for cap in profile.capabilities)
+
+
+# --------------------------------------------------------------------------- #
+# Tiger paper/live identity guard (17-digit account rule)
+# --------------------------------------------------------------------------- #
+
+
+ "account, is_paper",
+ [
+ ("20191106192858300", True), # 17-digit paper
+ ("51230321", False), # prime/standard
+ ("U12300123", False), # global
+ ("", False),
+ ("2019110619285830", False), # 16 digits
+ ("201911061928583000", False), # 18 digits
+ ],
+)
+def test_tiger_is_paper_account(account, is_paper) -> None:
+ assert tg.is_paper_account(account) is is_paper
+
+
+def test_tiger_paper_profile_rejects_live_account() -> None:
+ """A paper profile pointed at a non-17-digit account fails closed."""
+ cfg = tg.TigerConfig(tiger_id="x", private_key_path="x", account="U12300123", profile="paper")
+ with pytest.raises(tg.TigerProfileMismatchError):
+ tg._assert_profile(cfg)
+
+
+def test_tiger_live_profile_rejects_paper_account() -> None:
+ """A live profile pointed at a 17-digit paper account fails closed."""
+ cfg = tg.TigerConfig(tiger_id="x", private_key_path="x", account="20191106192858300", profile="live-readonly")
+ with pytest.raises(tg.TigerProfileMismatchError):
+ tg._assert_profile(cfg)
+
+
+def test_tiger_paper_profile_accepts_paper_account() -> None:
+ cfg = tg.TigerConfig(tiger_id="x", private_key_path="x", account="20191106192858300", profile="paper")
+ tg._assert_profile(cfg) # must not raise
+
+
+# --------------------------------------------------------------------------- #
+# Config resolution
+# --------------------------------------------------------------------------- #
+
+
+def test_tiger_build_config_merges_profile_then_overrides(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(tg, "get_runtime_root", lambda: tmp_path)
+ cfg = tg.build_config({"profile": "paper"}, {"account": "20191106192858300"})
+ assert cfg.profile == "paper"
+ assert cfg.account == "20191106192858300"
+
+
+def test_tiger_invalid_profile_rejected() -> None:
+ with pytest.raises(tg.TigerConfigError):
+ tg.TigerConfig.from_mapping({"profile": "live-trade-now"})
+
+
+def test_longbridge_build_config_and_region(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)
+ cfg = lb.build_config({"profile": "live-readonly", "region": "cn"}, None)
+ assert cfg.profile == "live-readonly"
+ assert cfg.region == "cn"
+
+
+def test_longbridge_invalid_region_rejected() -> None:
+ with pytest.raises(lb.LongbridgeConfigError):
+ lb.LongbridgeConfig.from_mapping({"region": "moon"})
+
+
+def test_longbridge_public_config_redacts_secrets() -> None:
+ """Secret material must never appear in a status payload."""
+ cfg = lb.LongbridgeConfig(app_key="abcd1234", app_secret="supersecret", access_token="tok-123")
+ pub = lb._public_config(cfg)
+ assert pub["app_secret"] == "***redacted***"
+ assert pub["access_token"] == "***redacted***"
+ assert "supersecret" not in str(pub)
+ assert "tok-123" not in str(pub)
+ assert pub["app_key"].endswith("***")
+
+
+# --------------------------------------------------------------------------- #
+# Read/write classification (live gate input)
+# --------------------------------------------------------------------------- #
+
+
+def test_tiger_order_ops_classified_write() -> None:
+ for name in ("place_order", "cancel_order", "modify_order"):
+ assert TIGER_TOOL_CLASS[name] is ToolClass.WRITE
+ for name in ("get_assets", "get_positions", "get_bars"):
+ assert TIGER_TOOL_CLASS[name] is ToolClass.READ
+
+
+def test_longbridge_order_ops_classified_write() -> None:
+ for name in ("submit_order", "cancel_order", "replace_order"):
+ assert LONGBRIDGE_TOOL_CLASS[name] is ToolClass.WRITE
+ for name in ("account_balance", "stock_positions", "candlesticks"):
+ assert LONGBRIDGE_TOOL_CLASS[name] is ToolClass.READ
+
+
+# --------------------------------------------------------------------------- #
+# Service dispatch degrades cleanly when nothing is configured
+# --------------------------------------------------------------------------- #
+
+
+def test_service_check_connection_unconfigured_tiger(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(tg, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("tiger-paper-sdk")
+ assert result["status"] == "error"
+ assert "not configured" in result["error"]
+ assert result["connector"] == "tiger"
+ assert result["transport"] == "broker_sdk"
+
+
+def test_service_check_connection_unconfigured_longbridge(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(lb, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("longbridge-paper-sdk")
+ assert result["status"] == "error"
+ assert "not configured" in result["error"]
+ assert result["connector"] == "longbridge"
+ assert result["transport"] == "broker_sdk"
+
+
+# --------------------------------------------------------------------------- #
+# Alpaca
+# --------------------------------------------------------------------------- #
+
+
+def test_alpaca_paper_live_host_and_flag() -> None:
+ assert al.AlpacaConfig(profile="paper").is_paper is True
+ assert al.AlpacaConfig(profile="paper").host == al.PAPER_HOST
+ assert al.AlpacaConfig(profile="live-readonly").is_paper is False
+ assert al.AlpacaConfig(profile="live-readonly").host == al.LIVE_HOST
+
+
+def test_alpaca_invalid_feed_rejected() -> None:
+ with pytest.raises(al.AlpacaConfigError):
+ al.AlpacaConfig.from_mapping({"feed": "nasdaq"})
+
+
+def test_alpaca_redacts_secrets() -> None:
+ cfg = al.AlpacaConfig(api_key="AKFOURCHARS", secret_key="topsecret")
+ pub = al._public_config(cfg)
+ assert pub["secret_key"] == "***redacted***"
+ assert "topsecret" not in str(pub)
+ assert pub["api_key"].endswith("***")
+
+
+def test_alpaca_classification() -> None:
+ assert ALPACA_TOOL_CLASS["submit_order"] is ToolClass.WRITE
+ assert ALPACA_TOOL_CLASS["cancel_order_by_id"] is ToolClass.WRITE
+ assert ALPACA_TOOL_CLASS["get_account"] is ToolClass.READ
+
+
+def test_alpaca_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(al, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("alpaca-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "alpaca"
+ assert result["transport"] == "broker_sdk"
+
+
+# --------------------------------------------------------------------------- #
+# OKX
+# --------------------------------------------------------------------------- #
+
+
+def test_okx_flag_mapping() -> None:
+ assert ox.OKXConfig(profile="paper").flag == "1"
+ assert ox.OKXConfig(profile="live-readonly").flag == "0"
+ assert ox.OKXConfig(profile="live").flag == "0"
+
+
+def test_okx_redacts_secrets() -> None:
+ cfg = ox.OKXConfig(api_key="KEYFOURXX", api_secret="sec", passphrase="pass")
+ pub = ox._public_config(cfg)
+ assert pub["api_secret"] == "***redacted***"
+ assert pub["passphrase"] == "***redacted***"
+ assert "sec" not in str(pub) or pub["api_secret"] == "***redacted***"
+
+
+def test_okx_classification() -> None:
+ assert OKX_TOOL_CLASS["place_order"] is ToolClass.WRITE
+ assert OKX_TOOL_CLASS["cancel_order"] is ToolClass.WRITE
+ assert OKX_TOOL_CLASS["get_account_balance"] is ToolClass.READ
+
+
+def test_okx_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(ox, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("okx-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "okx"
+
+
+# --------------------------------------------------------------------------- #
+# Binance
+# --------------------------------------------------------------------------- #
+
+
+def test_binance_testnet_host_mapping() -> None:
+ assert bn.BinanceConfig(profile="paper").is_testnet is True
+ assert "testnet" in bn.BinanceConfig(profile="paper").host
+ assert bn.BinanceConfig(profile="live-readonly").is_testnet is False
+ assert bn.BinanceConfig(profile="live-readonly").host == "https://api.binance.com"
+
+
+def test_binance_classification() -> None:
+ assert BINANCE_TOOL_CLASS["create_order"] is ToolClass.WRITE
+ assert BINANCE_TOOL_CLASS["cancel_order"] is ToolClass.WRITE
+ assert BINANCE_TOOL_CLASS["fetch_balance"] is ToolClass.READ
+
+
+def test_binance_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(bn, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("binance-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "binance"
+
+
+# --------------------------------------------------------------------------- #
+# Futu (local OpenD gateway)
+# --------------------------------------------------------------------------- #
+
+
+def test_futu_trd_env_mapping() -> None:
+ assert ft.FutuConfig(profile="paper").trd_env_name == "SIMULATE"
+ assert ft.FutuConfig(profile="live-readonly").trd_env_name == "REAL"
+
+
+def test_futu_classification() -> None:
+ assert FUTU_TOOL_CLASS["place_order"] is ToolClass.WRITE
+ assert FUTU_TOOL_CLASS["modify_order"] is ToolClass.WRITE
+ assert FUTU_TOOL_CLASS["unlock_trade"] is ToolClass.WRITE
+ assert FUTU_TOOL_CLASS["position_list_query"] is ToolClass.READ
+
+
+def test_futu_service_unconfigured_gateway_down(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(ft, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("futu-paper-sdk")
+ # OpenD gateway is not running in CI → clean error, not a crash.
+ assert result["status"] == "error"
+ assert result["connector"] == "futu"
+ assert result["transport"] == "broker_sdk"
+
+
+def test_binance_redacts_secrets() -> None:
+ cfg = bn.BinanceConfig(api_key="ABCD1234", api_secret="topsecret")
+ pub = bn._public_config(cfg)
+ assert pub["api_secret"] == "***redacted***"
+ assert "topsecret" not in str(pub)
+ assert pub["api_key"].endswith("***")
+
+
+def test_binance_assert_host_consistent_profiles_pass() -> None:
+ """Host property is the guard: paper→testnet host, live→api.binance.com.
+
+ The host is derived from the profile (paper→``testnet_host``,
+ live→``api.binance.com``), so a paper profile structurally cannot resolve to
+ the live host. ``_assert_host`` is defense-in-depth over that derivation and
+ must accept both consistent profiles without raising.
+ """
+ bn._assert_host(bn.BinanceConfig(profile="paper"))
+ bn._assert_host(bn.BinanceConfig(profile="live-readonly"))
+ assert "testnet" in bn.BinanceConfig(profile="paper").host
+ assert bn.BinanceConfig(profile="live-readonly").host == "https://api.binance.com"
+
+
+def test_okx_invalid_profile_rejected() -> None:
+ with pytest.raises(ox.OKXConfigError):
+ ox.OKXConfig.from_mapping({"profile": "go-live-now"})
+
+
+# --------------------------------------------------------------------------- #
+# Live gate: order ops are WRITE-pinned through the real classifier + registry
+# --------------------------------------------------------------------------- #
+
+
+ "broker, order_op",
+ [
+ ("tiger", "place_order"),
+ ("longbridge", "submit_order"),
+ ("alpaca", "submit_order"),
+ ("okx", "place_order"),
+ ("binance", "create_order"),
+ ("futu", "place_order"),
+ ],
+)
+def test_order_ops_write_pinned_via_registry(broker, order_op) -> None:
+ """Every broker's order op resolves WRITE through the shared classifier."""
+ from src.live import registry
+ from src.live.classification import classify_tool
+
+ curated = registry._BROKER_CURATED_MAPS[broker]
+ assert classify_tool(order_op, None, curated) is ToolClass.WRITE
+
+
+def test_unknown_op_does_not_classify_read() -> None:
+ """An unmapped op resolves to UNKNOWN (never READ); the registry then treats
+ UNKNOWN as WRITE (fail-closed) when wrapping the live channel."""
+ from src.live import registry
+ from src.live.classification import classify_tool
+
+ curated = registry._BROKER_CURATED_MAPS["okx"]
+ verdict = classify_tool("some_unmapped_future_tool", None, curated)
+ assert verdict is not ToolClass.READ
+ assert verdict in (ToolClass.WRITE, ToolClass.UNKNOWN)
+
+
+# --------------------------------------------------------------------------- #
+# Period mapping (generic token → per-SDK token)
+# --------------------------------------------------------------------------- #
+
+
+def test_period_maps_distinguish_minute_from_month() -> None:
+ """The 1m (minute) vs 1M (month) tokens must not collide in any map."""
+ assert tg._PERIOD_MAP["1m"] == "1min" and tg._PERIOD_MAP["1M"] == "month"
+ assert ox._BAR_MAP["1m"] == "1m" and ox._BAR_MAP["1M"] == "1M"
+ assert ft._KLTYPE_MAP["1m"] == "K_1M" and ft._KLTYPE_MAP["1M"] == "K_MON"
+
+
+# --------------------------------------------------------------------------- #
+# Read-path mapping with stubbed SDK clients (no broker SDK installed)
+# --------------------------------------------------------------------------- #
+
+
+class _FakeLbTrade:
+ def today_orders(self):
+ return [
+ {"order_id": "1", "symbol": "700.HK", "status": "NewStatus", "quantity": 100},
+ {"order_id": "2", "symbol": "700.HK", "status": "FilledStatus", "quantity": 100},
+ {"order_id": "3", "symbol": "AAPL.US", "status": "CanceledStatus", "quantity": 5},
+ ]
+
+
+def test_longbridge_open_orders_filters_terminal(monkeypatch) -> None:
+ monkeypatch.setattr(lb, "_trade_context", lambda cfg: _FakeLbTrade())
+ out = lb.get_open_orders(lb.LongbridgeConfig(app_key="k", app_secret="s", access_token="t"))
+ ids = [o["order_id"] for o in out["open_orders"]]
+ assert ids == ["1"] # filled + cancelled dropped
+
+
+def test_longbridge_status_normalization_variants() -> None:
+ """Terminal-status filtering must work across SDK string forms."""
+ for terminal in ("Filled", "FilledStatus", "OrderStatus.Filled", "CANCELED", "Rejected"):
+ assert not lb._is_open_order({"status": terminal})
+ for live in ("NewStatus", "PartialFilledStatus", "PartialFilled", "WaitToNew"):
+ assert lb._is_open_order({"status": live})
+
+
+class _FakeTigerQuote:
+ def __init__(self) -> None:
+ self.calls: list[dict] = []
+
+ def get_bars(self, symbols, period=None, limit=None):
+ self.calls.append({"period": period, "limit": limit})
+ return []
+
+
+def test_tiger_history_month_does_not_collapse_to_minute(monkeypatch) -> None:
+ """Regression: ``1M`` (month) must map to ``month``, not ``1min``."""
+ fake = _FakeTigerQuote()
+ monkeypatch.setattr(tg, "_quote_client", lambda cfg: fake)
+ monkeypatch.setattr(tg, "_assert_profile", lambda cfg: None)
+ cfg = tg.TigerConfig(tiger_id="x", private_key_path="x", account="20191106192858300", profile="paper")
+ tg.get_historical_bars("AAPL", config=cfg, period="1M", limit=12)
+ assert fake.calls[-1]["period"] == "month"
+ assert fake.calls[-1]["limit"] == 12
+
+
+def test_trading_history_tool_exposes_period_and_limit() -> None:
+ from src.tools.trading_connector_tool import TradingHistoryTool
+
+ props = TradingHistoryTool.parameters["properties"]
+ assert "period" in props and "limit" in props
+
+
+class _FakeOkxMarket:
+ def get_candlesticks(self, instId=None, bar=None, limit=None):
+ return {"code": "0", "data": [["1700000000000", "100", "110", "90", "105", "12", "1200", "1200", "1"]]}
+
+
+def test_okx_history_maps_candles_and_period(monkeypatch) -> None:
+ monkeypatch.setattr(ox, "_market_client", lambda cfg: _FakeOkxMarket())
+ out = ox.get_historical_bars("BTC-USDT", config=ox.OKXConfig(api_key="k", api_secret="s", passphrase="p"), period="1h")
+ assert out["period"] == "1h" and out["bar"] == "1H"
+ assert len(out["bars"]) == 1
+ bar = out["bars"][0]
+ assert bar["open"] == "100" and bar["close"] == "105" and bar["confirm"] == "1"
diff --git a/agent/tests/test_sdk_order_gate.py b/agent/tests/test_sdk_order_gate.py
new file mode 100644
index 000000000..01c828cfb
--- /dev/null
+++ b/agent/tests/test_sdk_order_gate.py
@@ -0,0 +1,342 @@
+"""Tests for the direct-SDK live order gate + service order routing (Layer B/C).
+
+The gate is the red-line code: live orders must pass mandate + kill-switch +
+fail-closed pre-trade checks before any broker call. These tests use a fake
+connector module + a stubbed mandate/halt so they need no broker SDK.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from src.live import sdk_order_gate as gate
+from src.live.enforcement import OrderIntent
+from src.live.mandate.model import (
+ AssetClass,
+ ConsentMeta,
+ HardCaps,
+ InstrumentType,
+ Mandate,
+ UniverseConstraint,
+)
+from src.trading import service
+
+pytestmark = pytest.mark.unit
+
+
+class _FakeConnector:
+ """Minimal connector module stand-in capturing place_order calls."""
+
+ def __init__(self, *, positions=None, balance=None, quote_last=100.0):
+ self.placed: list[dict] = []
+ self._positions = positions if positions is not None else {"status": "ok", "positions": []}
+ self._balance = balance if balance is not None else {"status": "ok", "account": {}}
+ self._quote_last = quote_last
+
+ def place_order(self, config, **kwargs):
+ self.placed.append(kwargs)
+ return {"status": "ok", "order_id": "OID-1", **kwargs}
+
+ def get_positions(self, config):
+ return self._positions
+
+ def get_account_snapshot(self, config):
+ return self._balance
+
+ def get_quote(self, symbol, *, config=None):
+ return {"status": "ok", "symbol": symbol, "quote": {"last": self._quote_last}}
+
+
+def _mandate(*, max_order=1_000_000.0, assets=(AssetClass.US_EQUITY,), instruments=(InstrumentType.EQUITY,)):
+ return Mandate(
+ schema_version=1,
+ hard_caps=HardCaps(
+ account_funding_usd=1_000_000.0,
+ max_order_notional_usd=max_order,
+ max_total_exposure_usd=1_000_000.0,
+ max_leverage=2.0,
+ allowed_instruments=tuple(instruments),
+ max_trades_per_day=100,
+ ),
+ universe=UniverseConstraint(
+ asset_classes=tuple(assets),
+ min_market_cap_usd=None,
+ min_avg_daily_volume_usd=None,
+ exclude_symbols=(),
+ ),
+ consent=ConsentMeta(
+ created_at="2026-01-01T00:00:00+00:00",
+ consent_token_sha256="deadbeef",
+ broker="alpaca",
+ account_ref="acct-1",
+ expires_at="2999-01-01T00:00:00+00:00",
+ ),
+ )
+
+
+def _patch_gate(monkeypatch, *, mandate, halted=False):
+ monkeypatch.setattr(gate, "load_mandate", lambda broker: mandate)
+ monkeypatch.setattr(gate, "halt_flag_set", lambda broker: halted)
+ monkeypatch.setattr(gate, "write_live_action", lambda *a, **k: {"audited": True})
+ monkeypatch.setattr(gate, "read_daily_count", lambda broker: 0)
+ monkeypatch.setattr(gate, "increment_daily_count", lambda broker: 1)
+
+
+def _intent(notional=500.0, qty=None, asset=AssetClass.US_EQUITY):
+ return OrderIntent(
+ symbol="AAPL", side="buy", notional_usd=notional, quantity=qty,
+ instrument_type=InstrumentType.EQUITY, asset_class=asset,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Gate decisions
+# --------------------------------------------------------------------------- #
+
+
+def test_gate_denies_without_mandate(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=None)
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "blocked" and out["decision"] == "deny"
+ assert "mandate" in out["reason"]
+ assert conn.placed == [] # never reached the broker
+
+
+def test_gate_denies_on_halt(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate(), halted=True)
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "blocked"
+ assert "halt" in out["reason"].lower()
+ assert conn.placed == []
+
+
+def test_gate_allows_in_bounds_and_places(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(notional=500.0), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "ok" and out["order_id"] == "OID-1"
+ assert len(conn.placed) == 1 # forwarded to broker
+ assert "live_action" in out
+
+
+def test_gate_blocks_oversized_order(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate(max_order=100.0))
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(notional=5000.0), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 5000.0},
+ )
+ assert out["status"] == "blocked"
+ assert out["decision"] in ("pause_for_reauth", "deny")
+ assert conn.placed == [] # breach → never placed
+
+
+def test_gate_blocks_disallowed_asset_class(monkeypatch) -> None:
+ # Mandate allows only US equity; an HK-equity order must be denied structurally.
+ _patch_gate(monkeypatch, mandate=_mandate(assets=(AssetClass.US_EQUITY,)))
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="tiger", connector_module=conn, config=object(),
+ intent=_intent(asset=AssetClass.HK_EQUITY),
+ place_kwargs={"symbol": "700.HK", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "blocked" and out["decision"] == "deny"
+ assert conn.placed == []
+
+
+def test_gate_quantity_order_priced_and_enforced(monkeypatch) -> None:
+ # quantity-only order: gate prices via connector quote (last=100) → 10*100=1000 notional.
+ _patch_gate(monkeypatch, mandate=_mandate(max_order=500.0))
+ conn = _FakeConnector(quote_last=100.0)
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(notional=None, qty=10.0),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "quantity": 10.0},
+ )
+ # 1000 > max_order 500 → blocked
+ assert out["status"] == "blocked"
+ assert conn.placed == []
+
+
+# --------------------------------------------------------------------------- #
+# Service routing
+# --------------------------------------------------------------------------- #
+
+
+def test_service_place_order_paper_is_direct(monkeypatch) -> None:
+ """Paper profile places directly (sandbox), bypassing the live gate."""
+ conn = _FakeConnector()
+ monkeypatch.setattr(service, "_sdk_module", lambda c: conn)
+ monkeypatch.setattr(conn, "build_config", lambda *a, **k: object(), raising=False)
+ # build_config is called on the module; give the fake one.
+ conn.build_config = lambda profile_config, overrides: object()
+ out = service.place_order("AAPL", "alpaca-paper-trade", side="buy", quantity=1)
+ assert out["status"] == "ok"
+ assert len(conn.placed) == 1
+ assert out["environment"] == "paper"
+
+
+def test_service_place_order_live_routes_through_gate(monkeypatch) -> None:
+ """Live profile routes through the gate; no mandate → blocked, not placed."""
+ conn = _FakeConnector()
+ conn.build_config = lambda profile_config, overrides: object()
+ monkeypatch.setattr(service, "_sdk_module", lambda c: conn)
+ monkeypatch.setattr("src.live.sdk_order_gate.load_mandate", lambda broker: None)
+ monkeypatch.setattr("src.live.sdk_order_gate.write_live_action", lambda *a, **k: {"audited": True})
+ out = service.place_order("AAPL", "alpaca-live-trade", side="buy", notional=500.0)
+ assert out["status"] == "blocked"
+ assert conn.placed == []
+ assert out["environment"] == "live"
+
+
+def test_no_longbridge_live_trade_profile() -> None:
+ from src.trading import profiles
+
+ ids = {p.id for p in profiles.list_profiles()}
+ assert "longbridge-paper-trade" in ids
+ assert "longbridge-live-trade" not in ids # capped: no live order placement
+
+
+def test_trade_profiles_have_place_capability() -> None:
+ from src.trading import profiles
+
+ for pid in ("alpaca-live-trade", "okx-live-trade", "binance-live-trade", "futu-live-trade", "tiger-live-trade"):
+ prof = profiles.profile_by_id(pid)
+ assert prof.readonly is False
+ assert any("requires_mandate" in c for c in prof.capabilities)
+
+
+# --------------------------------------------------------------------------- #
+# Gate edges: expiry, count-only-on-success, connector raise, unpriceable qty
+# --------------------------------------------------------------------------- #
+
+
+def _expired_mandate():
+ m = _mandate()
+ return Mandate(
+ schema_version=1, hard_caps=m.hard_caps, universe=m.universe,
+ consent=ConsentMeta(
+ created_at="2020-01-01T00:00:00+00:00", consent_token_sha256="x",
+ broker="alpaca", account_ref="a", expires_at="2020-02-01T00:00:00+00:00",
+ ),
+ )
+
+
+def test_gate_denies_expired_mandate(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_expired_mandate())
+ conn = _FakeConnector()
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=conn, config=object(),
+ intent=_intent(), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "blocked" and out["requires_reauthorization"] is True
+ assert conn.placed == []
+
+
+def test_gate_count_consumed_only_on_success(monkeypatch) -> None:
+ increments: list[str] = []
+ monkeypatch.setattr(gate, "load_mandate", lambda b: _mandate())
+ monkeypatch.setattr(gate, "halt_flag_set", lambda b: False)
+ monkeypatch.setattr(gate, "write_live_action", lambda *a, **k: {"audited": True})
+ monkeypatch.setattr(gate, "read_daily_count", lambda b: 0)
+ monkeypatch.setattr(gate, "increment_daily_count", lambda b: increments.append(b))
+
+ # Connector returns an error envelope → no count consumed.
+ class _ErrConn(_FakeConnector):
+ def place_order(self, config, **kwargs):
+ return {"status": "error", "error": "broker rejected"}
+
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=_ErrConn(), config=object(),
+ intent=_intent(), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "error"
+ assert increments == [] # failed placement must not consume a daily count
+
+
+def test_gate_connector_raise_is_caught(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+
+ class _RaiseConn(_FakeConnector):
+ def place_order(self, config, **kwargs):
+ raise RuntimeError("sdk boom")
+
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=_RaiseConn(), config=object(),
+ intent=_intent(), place_kwargs={"symbol": "AAPL", "side": "buy", "notional": 500.0},
+ )
+ assert out["status"] == "error" # raise converted to error envelope, not propagated
+
+
+def test_gate_quantity_unpriceable_denies(monkeypatch) -> None:
+ _patch_gate(monkeypatch, mandate=_mandate())
+
+ class _NoQuoteConn(_FakeConnector):
+ def get_quote(self, symbol, *, config=None):
+ return {"status": "error", "error": "no quote"}
+
+ # Force the loader fallback to also fail so pricing is impossible.
+ monkeypatch.setattr("src.live.sdk_order_gate.last_price_usd", lambda *a, **k: None)
+ out = gate.execute_live_order(
+ broker="alpaca", connector_module=_NoQuoteConn(), config=object(),
+ intent=_intent(notional=None, qty=5.0),
+ place_kwargs={"symbol": "AAPL", "side": "buy", "quantity": 5.0},
+ )
+ assert out["status"] == "blocked" and "priced" in out["reason"]
+
+
+# --------------------------------------------------------------------------- #
+# Connector order-method validation (fail-closed, no SDK needed)
+# --------------------------------------------------------------------------- #
+
+
+def test_longbridge_place_order_paper_only_guard() -> None:
+ from src.trading.connectors.longbridge import sdk as lb
+
+ cfg = lb.LongbridgeConfig(app_key="k", app_secret="s", access_token="t", profile="live-readonly")
+ out = lb.place_order(cfg, symbol="700.HK", side="buy", quantity=100)
+ assert out["status"] == "error" and "paper" in out["error"].lower()
+ out2 = lb.cancel_order(cfg, "OID", symbol="700.HK")
+ assert out2["status"] == "error" and "paper" in out2["error"].lower()
+
+
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge"])
+def test_connector_place_order_rejects_bad_side(connector) -> None:
+ import importlib
+
+ mod = importlib.import_module(f"src.trading.connectors.{connector}.sdk")
+ cfg = mod.build_config({"profile": "paper"}, None)
+ out = mod.place_order(cfg, symbol="AAPL", side="hold", quantity=1)
+ assert out["status"] == "error"
+
+
[email protected]("connector", ["tiger", "alpaca", "okx", "binance", "futu", "longbridge"])
+def test_connector_place_order_rejects_both_qty_and_notional(connector) -> None:
+ import importlib
+
+ mod = importlib.import_module(f"src.trading.connectors.{connector}.sdk")
+ cfg = mod.build_config({"profile": "paper"}, None)
+ out = mod.place_order(cfg, symbol="AAPL", side="buy", quantity=1, notional=100)
+ assert out["status"] == "error"
+
+
+def test_okx_order_result_rejects_failed_scode() -> None:
+ from src.trading.connectors.okx import sdk as ox
+
+ cfg = ox.OKXConfig(api_key="k", api_secret="s", passphrase="p")
+ # A 200 envelope (code 0) whose per-order sCode != 0 is a FAILED order.
+ failed = ox._order_result(cfg, {"code": "0", "data": [{"sCode": "51008", "sMsg": "insufficient"}]}, symbol="BTC-USDT", side="buy", order_type="market", time_in_force="day")
+ assert failed["status"] == "error"
+ ok = ox._order_result(cfg, {"code": "0", "data": [{"ordId": "O1", "sCode": "0"}]}, symbol="BTC-USDT", side="buy", order_type="market", time_in_force="day")
+ assert ok["status"] == "ok" and ok["order_id"] == "O1"