Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(futu): expose seven extended read-only connector endpoints

549236606-ossc6258088f673
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4a13005b..fb02d92d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,34 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **Futu connector — extended read endpoints.** The Futu (`futu-api`) connector
+ exposes seven new read-only functions covering the gaps left by the original
+ five endpoints:
+ - `get_rehab(symbol)` — dividend / split / rights-issue adjustment factors for
+ accurate forward-adjusted close prices in backtests.
+ - `get_capital_flow(symbol, period_type)` — historical main-flow time series
+ (super / big / mid / small inflow buckets) for institutional-flow analysis.
+ - `get_capital_distribution(symbol)` — today's live in-flow vs out-flow snapshot.
+ - `get_history_deals(start, end, code)` — historical fill records for true
+ cost-basis reconstruction in shadow-account workflows. Single-query window
+ capped at 360 days by the upstream SDK.
+ - `get_acc_cash_flow(clearing_date)` — account cash-flow movements for capital
+ management review.
+ - `get_financials(symbol, statement_type)` — financial statements (income /
+ balance / cash flow) for fundamental analysis.
+ - `get_earnings_calendar(market, begin_date, end_date)` — upcoming earnings
+ with EPS / revenue consensus for earnings-season planning.
+ Each function is read-only, fail-closed, and routed through the same
+ `_quote_ctx` / `_trade_ctx` / `_assert_gateway` envelope as the existing five,
+ so missing data and missing privileges degrade to a clean error payload. New
+ capabilities are exposed as `trading_rehab`, `trading_capital_flow`,
+ `trading_capital_distribution`, `trading_history_deals`,
+ `trading_acc_cash_flow`, `trading_financials`, and `trading_earnings_calendar`
+ BaseTool subclasses. The `futu-api` SDK is loaded lazily: the SDK is required
+ only when one of these endpoints (or the existing account / position / order
+ surface) is actually called.
+
## [0.1.13] — 2026-08-10
Rolls up 408 commits / 162 merged pull requests since 0.1.12.
diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.py
index b3fda5bb4..d3dfa148e 100644
--- a/agent/src/tools/trading_connector_tool.py
+++ b/agent/src/tools/trading_connector_tool.py
@@ -28,10 +28,17 @@ from src.trading.service import (
etoro_copy_precheck,
etoro_copy_start,
get_account,
+ get_acc_cash_flow,
+ get_capital_distribution,
+ get_capital_flow,
+ get_earnings_calendar,
+ get_financials,
get_history,
+ get_history_deals,
get_open_orders,
get_positions,
get_quote,
+ get_rehab,
place_order,
search_instruments,
)
@@ -428,6 +435,269 @@ class TradingHistoryTool(BaseTool):
return _json_result({"status": "error", "error": str(exc)})
+class TradingRehabTool(BaseTool):
+ """Read dividend / split adjustment factors for a symbol.
+
+ Use the returned adjustment factors to compute forward-adjusted close prices
+ so backtests don't show dividend-driven gaps. Read-only.
+ """
+
+ name = "trading_rehab"
+ description = "Read dividend / split / rights-issue adjustment factors for a symbol from the selected trading connector profile. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ },
+ "required": ["symbol"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read rehab adjustment factors."""
+ try:
+ return _json_result(
+ get_rehab(
+ str(kwargs["symbol"]),
+ _connection(kwargs.get("connection")),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingCapitalFlowTool(BaseTool):
+ """Read historical main-flow (super/big/mid/small) time series for a symbol.
+
+ Tracks institutional vs retail capital inflow / outflow across
+ intraday / daily / weekly / monthly buckets. Read-only.
+ """
+
+ name = "trading_capital_flow"
+ description = "Read historical capital flow time series (institutional / retail inflow-outflow) for a symbol. period_type: INTRADAY/DAY/WEEK/MONTH. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ "period_type": {
+ "type": "string",
+ "default": "INTRADAY",
+ "description": "Aggregation window: INTRADAY / DAY / WEEK / MONTH.",
+ },
+ },
+ "required": ["symbol"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read capital flow time series."""
+ try:
+ return _json_result(
+ get_capital_flow(
+ str(kwargs["symbol"]),
+ _connection(kwargs.get("connection")),
+ period_type=str(kwargs.get("period_type") or "INTRADAY"),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingCapitalDistributionTool(BaseTool):
+ """Read the LATEST capital in-flow vs out-flow snapshot for a symbol.
+
+ Today's running tally of super/big/mid/small buys vs sells. Use it to spot
+ when institutions are accumulating or distributing right now. Read-only.
+ """
+
+ name = "trading_capital_distribution"
+ description = "Read today's capital in-flow vs out-flow snapshot (super/big/mid/small buckets) for a symbol. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ },
+ "required": ["symbol"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read today's capital distribution snapshot."""
+ try:
+ return _json_result(
+ get_capital_distribution(
+ str(kwargs["symbol"]),
+ _connection(kwargs.get("connection")),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingHistoryDealsTool(BaseTool):
+ """Read historical FILL records (executed deals) for shadow-account analysis.
+
+ Unlike history_order_list_query (returns intent), this returns only orders
+ that ACTUALLY filled — with fill price, qty, counter broker, fee, settlement
+ date. Required for true cost-basis reconstruction. Read-only.
+ """
+
+ name = "trading_history_deals"
+ description = "Read historical FILL records (executed deals) for shadow-account cost-basis reconstruction. start/end YYYY-MM-DD; max window 360 days. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ "start": {"type": "string", "description": "Start date YYYY-MM-DD."},
+ "end": {"type": "string", "description": "End date YYYY-MM-DD."},
+ "code": {
+ "type": "string",
+ "default": "",
+ "description": "Optional Futu instrument code (e.g. HK.00700). Empty = all symbols.",
+ },
+ },
+ "required": ["start", "end"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read historical fill records."""
+ try:
+ return _json_result(
+ get_history_deals(
+ str(kwargs["start"]),
+ str(kwargs["end"]),
+ _connection(kwargs.get("connection")),
+ code=str(kwargs.get("code") or ""),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingAccCashFlowTool(BaseTool):
+ """Read account cash-flow movements for a clearing date.
+
+ Tracks deposit / withdrawal / FX conversion / buy-sell settlement /
+ margin interest / dividends received / fees. Read-only.
+ """
+
+ name = "trading_acc_cash_flow"
+ description = "Read account cash-flow movements for a clearing date (YYYY-MM-DD): deposit, withdrawal, FX, settlement, fees. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ "clearing_date": {
+ "type": "string",
+ "description": "Clearing date YYYY-MM-DD.",
+ },
+ },
+ "required": ["clearing_date"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read account cash-flow for one clearing date."""
+ try:
+ return _json_result(
+ get_acc_cash_flow(
+ str(kwargs["clearing_date"]),
+ _connection(kwargs.get("connection")),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingFinancialsTool(BaseTool):
+ """Read financial statements (income / balance / cash flow) for a symbol.
+
+ Returns structure_list (field definitions) + report_list (period values).
+ Read-only.
+ """
+
+ name = "trading_financials"
+ description = "Read financial statements (INCOME / BALANCE / CASH_FLOW) for a symbol. Returns structure_list + report_list across N periods. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ "statement_type": {
+ "type": "string",
+ "default": "INCOME",
+ "description": "Statement type: INCOME / BALANCE / CASH_FLOW.",
+ },
+ "num": {"type": "integer", "default": 20, "description": "Maximum periods."},
+ },
+ "required": ["symbol"],
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read financial statements."""
+ try:
+ return _json_result(
+ get_financials(
+ str(kwargs["symbol"]),
+ _connection(kwargs.get("connection")),
+ statement_type=str(kwargs.get("statement_type") or "INCOME"),
+ num=int(kwargs.get("num") or 20),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingEarningsCalendarTool(BaseTool):
+ """Read upcoming earnings-release dates with EPS / revenue consensus.
+
+ Used to plan earnings-season trades (vol crush, surprise, IV rank).
+ Read-only.
+ """
+
+ name = "trading_earnings_calendar"
+ description = "Read upcoming earnings calendar (code, name, EPS/revenue forecast, IV, IV rank) for US / HK. begin/end YYYY-MM-DD. Read-only."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TradingQuoteTool.parameters["properties"],
+ "market": {"type": "string", "default": "US", "description": "US or HK."},
+ "begin_date": {"type": "string", "default": "", "description": "Begin YYYY-MM-DD."},
+ "end_date": {"type": "string", "default": "", "description": "End YYYY-MM-DD."},
+ },
+ }
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Read earnings calendar."""
+ try:
+ return _json_result(
+ get_earnings_calendar(
+ _connection(kwargs.get("connection")),
+ market=str(kwargs.get("market") or "US"),
+ begin_date=str(kwargs.get("begin_date") or ""),
+ end_date=str(kwargs.get("end_date") or ""),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
class TradingPlaceOrderTool(BaseTool):
"""Place an order through a trading connector profile.
diff --git a/agent/src/trading/connectors/futu/__init__.py b/agent/src/trading/connectors/futu/__init__.py
index 959ca177c..21945cf64 100644
--- a/agent/src/trading/connectors/futu/__init__.py
+++ b/agent/src/trading/connectors/futu/__init__.py
@@ -25,10 +25,17 @@ from src.trading.connectors.futu.sdk import (
config_path,
futu_available,
get_account_snapshot,
+ get_acc_cash_flow,
+ get_capital_distribution,
+ get_capital_flow,
+ get_earnings_calendar,
+ get_financials,
get_historical_bars,
+ get_history_deals,
get_open_orders,
get_positions,
get_quote,
+ get_rehab,
load_config,
save_config,
)
@@ -43,10 +50,17 @@ __all__ = [
"config_path",
"futu_available",
"get_account_snapshot",
+ "get_acc_cash_flow",
+ "get_capital_distribution",
+ "get_capital_flow",
+ "get_earnings_calendar",
+ "get_financials",
"get_historical_bars",
+ "get_history_deals",
"get_open_orders",
"get_positions",
"get_quote",
+ "get_rehab",
"load_config",
"save_config",
]
diff --git a/agent/src/trading/connectors/futu/profiles.py b/agent/src/trading/connectors/futu/profiles.py
index d09cf2968..0bed8d905 100644
--- a/agent/src/trading/connectors/futu/profiles.py
+++ b/agent/src/trading/connectors/futu/profiles.py
@@ -9,7 +9,18 @@ trade environment (``SIMULATE`` vs ``REAL``) and the account is resolved by its
from __future__ import annotations
-from src.trading.types import READ_CAPABILITIES, TradingProfile
+from src.trading.types import (
+ FUTU_EXTENDED_READ_CAPABILITIES,
+ READ_CAPABILITIES,
+ TradingProfile,
+)
+
+# Profiles exposed by this connector. The extended Futu-only read capabilities
+# (rehab, capital flow, history deals, etc.) are appended to every profile so
+# the agent loop can see them in capability listings — but the service layer
+# still returns a clean "unsupported" response for any profile that lacks the
+# runtime SDK call.
+_FUTU_READS = READ_CAPABILITIES + FUTU_EXTENDED_READ_CAPABILITIES
FUTU_PROFILES: tuple[TradingProfile, ...] = (
TradingProfile(
@@ -18,7 +29,7 @@ FUTU_PROFILES: tuple[TradingProfile, ...] = (
label="Futu Paper · futu-api",
environment="paper",
transport="broker_sdk",
- capabilities=READ_CAPABILITIES,
+ capabilities=_FUTU_READS,
readonly=True,
config={"profile": "paper", "filter_trdmarket": "HK"},
notes=(
@@ -34,7 +45,7 @@ FUTU_PROFILES: tuple[TradingProfile, ...] = (
label="Futu Live · futu-api Read-Only",
environment="live",
transport="broker_sdk",
- capabilities=READ_CAPABILITIES,
+ capabilities=_FUTU_READS,
readonly=True,
config={"profile": "live-readonly", "filter_trdmarket": "HK"},
notes=(
@@ -49,7 +60,7 @@ FUTU_PROFILES: tuple[TradingProfile, ...] = (
label="Futu Paper · futu-api Trading",
environment="paper",
transport="broker_sdk",
- capabilities=READ_CAPABILITIES + ("orders.place",),
+ capabilities=_FUTU_READS + ("orders.place",),
readonly=False,
config={"profile": "paper", "filter_trdmarket": "HK"},
notes=(
@@ -66,7 +77,7 @@ FUTU_PROFILES: tuple[TradingProfile, ...] = (
label="Futu Live · futu-api Trading",
environment="live",
transport="broker_sdk",
- capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ capabilities=_FUTU_READS + ("orders.place.requires_mandate",),
readonly=False,
config={"profile": "live", "filter_trdmarket": "HK"},
notes=(
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.py
index 930609bee..937fd306b 100644
--- a/agent/src/trading/connectors/futu/sdk.py
+++ b/agent/src/trading/connectors/futu/sdk.py
@@ -393,6 +393,303 @@ def get_historical_bars(
_close(quote_ctx)
+# ---------------------------------------------------------------------------
+# Extended read-only data: rehab, capital flow, history deals, earnings
+# calendar, account cash flow, and financial statements. All read-only, no
+# order placement. These unlock fundamental analysis, attribution, and
+# shadow-account workflows that the original five endpoints do not cover.
+# ---------------------------------------------------------------------------
+
+
+def get_rehab(
+ symbol: str, *, config: FutuConfig | None = None, **_: Any
+) -> dict[str, Any]:
+ """Fetch dividend / split / rights-issue adjustment factors for ``symbol``.
+
+ Args:
+ symbol: Futu instrument code, e.g. ``HK.00700`` / ``US.AAPL``.
+ config: Effective connector config; loaded from disk when omitted.
+
+ Returns:
+ Dict containing ``status`` and ``ex_dividend_events`` — a list of
+ adjustment-factor rows (ex-date, cash dividend, share ratio, forward
+ and backward adjustment factors A/B). Pass these into a backtest engine
+ to compute forward-adjusted close prices and avoid dividend-driven gaps.
+ """
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ rows = _records(_unwrap(quote_ctx.get_rehab(code)))
+ return {
+ "status": "ok",
+ "symbol": code,
+ "ex_dividend_events": rows,
+ }
+ finally:
+ _close(quote_ctx)
+
+
+def get_capital_flow(
+ symbol: str,
+ *,
+ config: FutuConfig | None = None,
+ period_type: str = "INTRADAY",
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical capital flow for ``symbol``.
+
+ Args:
+ symbol: Futu instrument code, e.g. ``HK.00700``.
+ period_type: ``INTRADAY`` / ``DAY`` / ``WEEK`` / ``MONTH``.
+ config: Effective connector config; loaded from disk when omitted.
+
+ Returns:
+ Dict containing ``status``, ``symbol``, ``period_type``, and
+ ``flows`` (a list of intraday/daily main-flow rows with super/big/mid/small
+ inflow buckets). Use the ``super_in_flow`` + ``big_in_flow`` columns to
+ gauge institutional activity.
+ """
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ rows = _records(
+ _unwrap(quote_ctx.get_capital_flow(code, period_type=period_type))
+ )
+ return {
+ "status": "ok",
+ "symbol": code,
+ "period_type": period_type,
+ "flows": rows,
+ }
+ finally:
+ _close(quote_ctx)
+
+
+def get_capital_distribution(
+ symbol: str, *, config: FutuConfig | None = None, **_: Any
+) -> dict[str, Any]:
+ """Fetch today's live capital distribution snapshot for ``symbol``.
+
+ Returns the latest in-flow vs out-flow split across super/big/mid/small
+ buckets — useful for live "are institutions accumulating right now?" checks.
+ """
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ rows = _records(_unwrap(quote_ctx.get_capital_distribution(code)))
+ return {
+ "status": "ok",
+ "symbol": code,
+ "distribution": rows,
+ }
+ finally:
+ _close(quote_ctx)
+
+
+def get_history_deals(
+ start: str,
+ end: str,
+ *,
+ config: FutuConfig | None = None,
+ code: str = "",
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical FILL records (executed deals) for shadow-account analysis.
+
+ Unlike ``history_order_list_query`` (which returns intent), this returns only
+ orders that ACTUALLY filled, with fill price, qty, counter broker, fee, and
+ settlement date. Required for true cost-basis reconstruction.
+
+ Args:
+ start: Start date string ``YYYY-MM-DD`` (Futu caps single-query window at
+ 360 days).
+ end: End date string ``YYYY-MM-DD`` (inclusive). Pass empty string for
+ "today".
+ code: Optional Futu instrument code filter, e.g. ``HK.00700``. Empty
+ string returns fills across all symbols.
+ config: Effective connector config; loaded from disk when omitted.
+
+ Returns:
+ Dict containing ``status``, ``start``, ``end``, ``code``, and ``deals``
+ — a list of fill records with deal_id, order_id, code, qty, price,
+ trd_side, create_time, counter_broker_name.
+ """
+ cfg = config or load_config()
+ trade_ctx = _trade_ctx(cfg)
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+ kwargs: dict[str, Any] = dict(trd_env=trd_env, acc_id=acc_id)
+ if code:
+ kwargs["code"] = code.strip().upper()
+ else:
+ kwargs["code"] = ""
+ rows = _records(
+ _unwrap(trade_ctx.history_deal_list_query(start=start, end=end, **kwargs))
+ )
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "start": start,
+ "end": end,
+ "deals": [_deal_to_dict(row) for row in rows],
+ }
+ finally:
+ _close(trade_ctx)
+
+
+def get_acc_cash_flow(
+ clearing_date: str,
+ *,
+ config: FutuConfig | None = None,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch account cash-flow movements for a given clearing date ``YYYY-MM-DD``.
+
+ Useful for capital management review: deposit, withdrawal, FX conversion,
+ buy/sell settlement, margin interest, dividends received, fees, etc.
+ """
+ cfg = config or load_config()
+ trade_ctx = _trade_ctx(cfg)
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+ rows = _records(
+ _unwrap(
+ trade_ctx.get_acc_cash_flow(
+ clearing_date=clearing_date, trd_env=trd_env, acc_id=acc_id
+ )
+ )
+ )
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "clearing_date": clearing_date,
+ "cash_flows": rows,
+ }
+ finally:
+ _close(trade_ctx)
+
+
+def get_financials(
+ symbol: str,
+ *,
+ config: FutuConfig | None = None,
+ statement_type: str = "INCOME",
+ num: int = 20,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch financial statements (income / balance / cash flow / key ratios) for ``symbol``.
+
+ Args:
+ symbol: Futu instrument code, e.g. ``HK.00700`` / ``US.AAPL``.
+ statement_type: ``INCOME`` / ``BALANCE`` / ``CASH_FLOW``. Maps to
+ Futu's integer statement_type codes (1/2/3). Default ``INCOME``.
+ num: Maximum number of statements to return.
+ config: Effective connector config; loaded from disk when omitted.
+
+ Returns:
+ Dict containing ``status``, ``symbol``, ``statement_type``, and
+ ``structure_list`` + ``report_list`` — flat row dictionaries keyed by
+ field name (e.g. ``"营业总收入"``) for O(1) lookups, plus a list of raw
+ report dicts for full inspection.
+ """
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ # statement_type token → integer code (Futu SDK uses int enums).
+ st_int_map = {"INCOME": 1, "BALANCE": 2, "CASH_FLOW": 3, "KEY_RATIO": 4}
+ st_value = st_int_map.get(statement_type.upper(), 1)
+ ret_tuple = quote_ctx.get_financials_statements(
+ code=code,
+ statement_type=st_value,
+ num=num,
+ )
+ # SDK returns (ret_code, dict) where dict carries next_key / structure_list /
+ # report_list_*
+ ok_code = ret_tuple[0]
+ payload = (
+ ret_tuple[1]
+ if len(ret_tuple) > 1 and isinstance(ret_tuple[1], dict)
+ else {}
+ )
+ structure_list = payload.get("structure_list", [])
+ # Pull all reports across pages? For v1 we return the first page only;
+ # caller can re-invoke with next_key for more.
+ report_lists = [
+ payload.get("report_list", []),
+ payload.get("report_list_annual", []),
+ payload.get("report_list_quarter", []),
+ ]
+ merged_reports: list[Any] = []
+ for rl in report_lists:
+ if rl:
+ merged_reports.extend(rl)
+ futu = _require_futu()
+ return {
+ "status": "ok" if ok_code == getattr(futu, "RET_OK", 0) else "error",
+ "symbol": code,
+ "statement_type": statement_type.upper(),
+ "next_key": payload.get("next_key"),
+ "structure_list": structure_list,
+ "report_list": merged_reports,
+ }
+ finally:
+ _close(quote_ctx)
+
+
+def get_earnings_calendar(
+ *,
+ config: FutuConfig | None = None,
+ market: str = "US",
+ begin_date: str = "",
+ end_date: str = "",
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch upcoming earnings-release dates and EPS / revenue consensus.
+
+ Args:
+ market: ``US`` / ``HK``.
+ begin_date: Start ``YYYY-MM-DD``. Defaults to today.
+ end_date: End ``YYYY-MM-DD``. Defaults to begin_date + 30 days.
+ config: Effective connector config; loaded from disk when omitted.
+
+ Returns:
+ Dict with ``status``, ``market``, ``begin_date``, ``end_date``, and
+ ``events`` — list of upcoming earnings with code, name, earnings_date,
+ eps_predict, eps_actual, revenue_predict, revenue_actual, iv, iv_rank.
+ """
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ futu = _require_futu()
+ market_attr = "US" if market.upper() == "US" else "HK"
+ m = getattr(futu.Market, market_attr)
+ ret_tuple = quote_ctx.get_earnings_calendar(
+ market=m,
+ begin_date=begin_date or None,
+ end_date=end_date or None,
+ )
+ ok_value = getattr(_require_futu(), "RET_OK", 0)
+ ok = ret_tuple[0]
+ events = ret_tuple[1] if len(ret_tuple) > 1 else []
+ return {
+ "status": "ok" if ok == ok_value else "error",
+ "market": market.upper(),
+ "begin_date": begin_date,
+ "end_date": end_date,
+ "events": events if events is not None else [],
+ }
+ finally:
+ _close(quote_ctx)
# ---------------------------------------------------------------------------
# Order placement (paper SIMULATE + live REAL, fail-closed)
# ---------------------------------------------------------------------------
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 73966d683..da4700679 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -229,6 +229,180 @@ def get_history(
return _unsupported(profile, "history.read")
+# ---------------------------------------------------------------------------
+# Extended read-only data: rehab, capital flow, history deals, earnings
+# calendar, financials, and account cash flow. These unlock fundamental
+# analysis, attribution, and shadow-account workflows for connectors that
+# expose them. Other SDK connectors fall back to a clean "unsupported"
+# response when the corresponding SDK function is absent.
+# ---------------------------------------------------------------------------
+
+
+def get_rehab(symbol: str, profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:
+ """Dividend / split adjustment factors for ``symbol``."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "rehab.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_rehab", None)
+ if fn is None:
+ return _unsupported(profile, "rehab.read")
+ return _with_profile(
+ profile,
+ fn(symbol, config=module.build_config(profile.config, overrides)),
+ )
+
+
+def get_capital_flow(
+ symbol: str,
+ profile_id: str | None = None,
+ *,
+ period_type: str = "INTRADAY",
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Historical main-flow time series for ``symbol``."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "capital_flow.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_capital_flow", None)
+ if fn is None:
+ return _unsupported(profile, "capital_flow.read")
+ return _with_profile(
+ profile,
+ fn(
+ symbol,
+ config=module.build_config(profile.config, overrides),
+ period_type=period_type,
+ ),
+ )
+
+
+def get_capital_distribution(
+ symbol: str, profile_id: str | None = None, **overrides: Any
+) -> dict[str, Any]:
+ """Latest capital in-flow vs out-flow snapshot for ``symbol``."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "capital_distribution.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_capital_distribution", None)
+ if fn is None:
+ return _unsupported(profile, "capital_distribution.read")
+ return _with_profile(
+ profile,
+ fn(symbol, config=module.build_config(profile.config, overrides)),
+ )
+
+
+def get_history_deals(
+ start: str,
+ end: str,
+ profile_id: str | None = None,
+ *,
+ code: str = "",
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Historical FILL records for shadow-account analysis."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "history_deals.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_history_deals", None)
+ if fn is None:
+ return _unsupported(profile, "history_deals.read")
+ return _with_profile(
+ profile,
+ fn(
+ start,
+ end,
+ config=module.build_config(profile.config, overrides),
+ code=code,
+ ),
+ )
+
+
+def get_acc_cash_flow(
+ clearing_date: str,
+ profile_id: str | None = None,
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Account cash-flow movements for ``clearing_date`` (YYYY-MM-DD)."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "acc_cash_flow.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_acc_cash_flow", None)
+ if fn is None:
+ return _unsupported(profile, "acc_cash_flow.read")
+ return _with_profile(
+ profile,
+ fn(
+ clearing_date,
+ config=module.build_config(profile.config, overrides),
+ ),
+ )
+
+
+def get_financials(
+ symbol: str,
+ profile_id: str | None = None,
+ *,
+ statement_type: str = "INCOME",
+ num: int = 20,
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Financial statements (income / balance / cash flow) for ``symbol``."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "financials.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_financials", None)
+ if fn is None:
+ return _unsupported(profile, "financials.read")
+ return _with_profile(
+ profile,
+ fn(
+ symbol,
+ config=module.build_config(profile.config, overrides),
+ statement_type=statement_type,
+ num=num,
+ ),
+ )
+
+
+def get_earnings_calendar(
+ profile_id: str | None = None,
+ *,
+ market: str = "US",
+ begin_date: str = "",
+ end_date: str = "",
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Upcoming earnings calendar for ``market`` (US / HK)."""
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "earnings_calendar.read")
+ module = _sdk_module(profile.connector)
+ fn = getattr(module, "get_earnings_calendar", None)
+ if fn is None:
+ return _unsupported(profile, "earnings_calendar.read")
+ return _with_profile(
+ profile,
+ fn(
+ config=module.build_config(profile.config, overrides),
+ market=market,
+ begin_date=begin_date,
+ end_date=end_date,
+ ),
+ )
+
+
+# ---------------------------------------------------------------------------
+# End extended read-only data section.
+# ---------------------------------------------------------------------------
+
+
#: Connector → (instrument type, fixed asset class | None). ``None`` asset class
#: means "infer from the symbol's market" (multi-market equity connectors).
#: ``mt5`` is deliberately absent: its symbols split into forex pairs vs CFDs,
diff --git a/agent/src/trading/types.py b/agent/src/trading/types.py
index d9c57db94..d27a36741 100644
--- a/agent/src/trading/types.py
+++ b/agent/src/trading/types.py
@@ -16,6 +16,23 @@ READ_CAPABILITIES = (
"history.read",
)
+# Capability strings for connector-specific extended read endpoints that are
+# exposed by some connectors (Futu today; could be added to others later) but
+# not by the shared broker_sdk baseline. Connnectors that implement any of
+# these should append them — never ``READ_CAPABILITIES`` — to the profile's
+# ``capabilities`` tuple. Service-layer wrappers fall back to a clean
+# "unsupported" response when the capability is missing, so omitting them
+# from ``READ_CAPABILITIES`` keeps the capability list honest.
+FUTU_EXTENDED_READ_CAPABILITIES = (
+ "rehab.read",
+ "capital_flow.read",
+ "capital_distribution.read",
+ "history_deals.read",
+ "acc_cash_flow.read",
+ "financials.read",
+ "earnings_calendar.read",
+)
+
@dataclass(frozen=True)
class TradingProfile:
@@ -49,3 +66,4 @@ class TradingProfile:
payload["capabilities"] = list(self.capabilities)
payload["selected"] = selected
return payload
+
diff --git a/agent/tests/test_futu_extended_reads.py b/agent/tests/test_futu_extended_reads.py
new file mode 100644
index 000000000..b205c0fe7
--- /dev/null
+++ b/agent/tests/test_futu_extended_reads.py
@@ -0,0 +1,354 @@
+"""Tests for the extended read-only Futu (moomoo) connector endpoints.
+
+These endpoints — rehab factors, capital flow, capital distribution, history
+deals, account cash flow, financials, and earnings calendar — are exposed by
+the Futu broker_sdk connector via ``futu-api``. The connector wraps each SDK
+call with a fail-closed envelope; these tests pin the contract so future
+refactors can't silently change parameter routing or break the agent tool
+surface.
+
+The tests mock the SDK (``futu``) and the OpenD context objects via
+``monkeypatch``. No real OpenD, no real Futu credentials, no network.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from src.trading.connectors.futu import sdk as futu_sdk
+from src.trading.connectors.futu import profiles as futu_profiles
+
+
+# ---------------------------------------------------------------------------
+# Shared test fixtures: a fake Futu SDK + OpenD contexts.
+# ---------------------------------------------------------------------------
+
+
+class _FakeKLType:
+ K_1M = "K_1M"
+ K_DAY = "K_DAY"
+
+
+class _FakeFutu:
+ KLType = _FakeKLType
+ RET_OK = 0
+
+ class Market:
+ US = "US"
+ HK = "HK"
+
+
+class _FakeQuoteCtx:
+ def __init__(self, *, handlers: dict[tuple[str, ...], Any] | None = None) -> None:
+ self.handlers = handlers or {}
+ self.calls: list[tuple[str, tuple]] = []
+
+ def get_rehab(self, code):
+ self.calls.append(("get_rehab", (code,)))
+ return self.handlers.get(("get_rehab", code))
+
+ def get_capital_flow(self, code, period_type=None):
+ self.calls.append(("get_capital_flow", (code, period_type)))
+ return self.handlers.get(("get_capital_flow", code))
+
+ def get_capital_distribution(self, code):
+ self.calls.append(("get_capital_distribution", (code,)))
+ return self.handlers.get(("get_capital_distribution", code))
+
+ def get_financials_statements(self, code, statement_type=None, num=None):
+ self.calls.append(("get_financials_statements", (code, statement_type, num)))
+ return self.handlers.get(("get_financials_statements", code))
+
+ def get_earnings_calendar(self, market=None, begin_date=None, end_date=None):
+ self.calls.append(("get_earnings_calendar", (market, begin_date, end_date)))
+ return self.handlers.get(("get_earnings_calendar",))
+
+
+class _FakeTradeCtx:
+ def __init__(self, *, handlers: dict[tuple[str, ...], Any] | None = None) -> None:
+ self.handlers = handlers or {}
+ self.calls: list[tuple[str, tuple]] = []
+
+ def history_deal_list_query(self, start=None, end=None, trd_env=None, acc_id=None, code=""):
+ self.calls.append(("history_deal_list_query", (start, end, trd_env, acc_id, code)))
+ return self.handlers.get(("history_deal_list_query", code))
+
+ def get_acc_cash_flow(self, clearing_date=None, trd_env=None, acc_id=None):
+ self.calls.append(("get_acc_cash_flow", (clearing_date, trd_env, acc_id)))
+ return self.handlers.get(("get_acc_cash_flow", clearing_date))
+
+
+def base_futu_cfg(monkeypatch) -> futu_sdk.FutuConfig:
+ """A FutuConfig that skips the gateway TCP probe in every test."""
+ monkeypatch.setattr(futu_sdk, "_assert_gateway", lambda cfg: None)
+ return futu_sdk.FutuConfig(host="127.0.0.1", port=11111, profile="live-readonly")
+
+
+def patched_futu(monkeypatch):
+ """Install a minimal fake ``futu`` module so ``_require_futu()`` succeeds."""
+ monkeypatch.setattr(futu_sdk, "_require_futu", lambda: _FakeFutu)
+ return _FakeFutu
+
+
+# ---------------------------------------------------------------------------
+# get_rehab
+# ---------------------------------------------------------------------------
+
+
+def test_get_rehab_returns_status_ok_with_events(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ """get_rehab unwraps the SDK tuple and copies ``ex_dividend_events`` through."""
+ payload = [{"ex_div_date": "2025-05-15", "per_cash_div": 1.5}]
+ quote_ctx = _FakeQuoteCtx(handlers={("get_rehab", "HK.00700"): (0, payload)})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ result = futu_sdk.get_rehab("HK.00700", config=base_futu_cfg)
+
+ assert result["status"] == "ok"
+ assert result["symbol"] == "HK.00700"
+ assert result["ex_dividend_events"] == payload
+ assert quote_ctx.calls == [("get_rehab", ("HK.00700",))]
+
+
+def test_get_rehab_handles_empty_payload(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ """No adjustment events (the common case) returns an empty list, not null."""
+ quote_ctx = _FakeQuoteCtx(handlers={("get_rehab", "HK.03690"): (0, [])})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ result = futu_sdk.get_rehab("HK.03690", config=base_futu_cfg)
+
+ assert result["status"] == "ok"
+ assert result["ex_dividend_events"] == []
+
+
+# ---------------------------------------------------------------------------
+# get_capital_flow
+# ---------------------------------------------------------------------------
+
+
+def test_get_capital_flow_passes_period_type_through(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ """Period token (INTRADAY/DAY/WEEK/MONTH) is forwarded to the SDK verbatim."""
+ quote_ctx = _FakeQuoteCtx(handlers={("get_capital_flow", "HK.03690"): (0, [])})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ futu_sdk.get_capital_flow("HK.03690", config=base_futu_cfg, period_type="WEEK")
+
+ assert quote_ctx.calls == [("get_capital_flow", ("HK.03690", "WEEK"))]
+
+
+def test_get_capital_flow_defaults_to_intraday(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ quote_ctx = _FakeQuoteCtx(handlers={("get_capital_flow", "US.AAPL"): (0, [])})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ futu_sdk.get_capital_flow("US.AAPL", config=base_futu_cfg)
+
+ assert quote_ctx.calls[0][1][1] == "INTRADAY"
+
+
+# ---------------------------------------------------------------------------
+# get_capital_distribution
+# ---------------------------------------------------------------------------
+
+
+def test_get_capital_distribution_returns_single_row_snapshot(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ row = {"capital_in_super": 1.0, "capital_out_small": 2.0, "update_time": "2026-08-18T10:00:00"}
+ quote_ctx = _FakeQuoteCtx(handlers={("get_capital_distribution", "HK.00700"): (0, [row])})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ result = futu_sdk.get_capital_distribution("HK.00700", config=base_futu_cfg)
+
+ assert result["status"] == "ok"
+ assert result["symbol"] == "HK.00700"
+ assert result["distribution"] == [row]
+
+
+# ---------------------------------------------------------------------------
+# get_history_deals
+# ---------------------------------------------------------------------------
+
+
+def test_get_history_deals_resolves_account_and_passes_dates(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ deal = {"deal_id": "abc", "code": "HK.00700", "qty": 100.0, "price": 350.0, "trd_side": "BUY"}
+ trade_ctx = _FakeTradeCtx(handlers={("history_deal_list_query", ""): (0, [deal])})
+ monkeypatch.setattr(futu_sdk, "_trade_ctx", lambda cfg: trade_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+ monkeypatch.setattr(futu_sdk, "_resolve_acc_id", lambda cfg, ctx: 1001)
+ monkeypatch.setattr(futu_sdk, "_trd_env_enum", lambda cfg: _FakeFutu.KLType.K_DAY) # any sentinel
+
+ result = futu_sdk.get_history_deals("2026-01-01", "2026-08-18", config=base_futu_cfg)
+
+ assert result["status"] == "ok"
+ assert result["start"] == "2026-01-01"
+ assert result["end"] == "2026-08-18"
+ # Don't pin the exact row shape: _deal_to_dict enriches each row with
+ # fields like order_id / create_time that we didn't mock. Just assert one
+ # of our seed fields survived the round-trip.
+ assert len(result["deals"]) == 1
+ assert result["deals"][0]["code"] == "HK.00700"
+ assert result["deals"][0]["trd_side"] == "BUY"
+
+
+def test_get_history_deals_scopes_by_code_when_provided(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ trade_ctx = _FakeTradeCtx(handlers={("history_deal_list_query", "HK.00700"): (0, [])})
+ monkeypatch.setattr(futu_sdk, "_trade_ctx", lambda cfg: trade_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+ monkeypatch.setattr(futu_sdk, "_resolve_acc_id", lambda cfg, ctx: 1001)
+ monkeypatch.setattr(futu_sdk, "_trd_env_enum", lambda cfg: None)
+
+ futu_sdk.get_history_deals("2026-01-01", "2026-08-18", config=base_futu_cfg, code="HK.00700")
+
+ # code should be uppercased and passed through
+ assert trade_ctx.calls == [
+ ("history_deal_list_query", ("2026-01-01", "2026-08-18", None, 1001, "HK.00700"))
+ ]
+
+
+# ---------------------------------------------------------------------------
+# get_acc_cash_flow
+# ---------------------------------------------------------------------------
+
+
+def test_get_acc_cash_flow_routes_to_trade_context(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ flow = {"cashflow_type": "DEPOSIT", "cashflow_amount": 10000.0, "currency": "HKD"}
+ trade_ctx = _FakeTradeCtx(handlers={("get_acc_cash_flow", "2026-08-01"): (0, [flow])})
+ monkeypatch.setattr(futu_sdk, "_trade_ctx", lambda cfg: trade_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+ monkeypatch.setattr(futu_sdk, "_resolve_acc_id", lambda cfg, ctx: 1001)
+ monkeypatch.setattr(futu_sdk, "_trd_env_enum", lambda cfg: None)
+
+ result = futu_sdk.get_acc_cash_flow("2026-08-01", config=base_futu_cfg)
+
+ assert result["status"] == "ok"
+ assert result["clearing_date"] == "2026-08-01"
+ assert result["cash_flows"] == [flow]
+
+
+# ---------------------------------------------------------------------------
+# get_financials
+# ---------------------------------------------------------------------------
+
+
+def test_get_financials_maps_statement_type_tokens_to_int_codes(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ """INCOME / BALANCE / CASH_FLOW map to 1 / 2 / 3 on the SDK wire."""
+ quote_ctx = _FakeQuoteCtx(handlers={("get_financials_statements", "HK.00700"): (0, {"structure_list": [], "report_list": []})})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ futu_sdk.get_financials("HK.00700", config=base_futu_cfg, statement_type="BALANCE")
+
+ # statement_type 2 == BALANCE
+ assert quote_ctx.calls[0][1][1] == 2
+
+
+def test_get_financials_unknown_statement_type_defaults_to_income(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ quote_ctx = _FakeQuoteCtx(handlers={("get_financials_statements", "HK.00700"): (0, {"structure_list": [], "report_list": []})})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ futu_sdk.get_financials("HK.00700", config=base_futu_cfg, statement_type="BOGUS")
+
+ assert quote_ctx.calls[0][1][1] == 1 # INCOME default
+
+
+# ---------------------------------------------------------------------------
+# get_earnings_calendar
+# ---------------------------------------------------------------------------
+
+
+def test_get_earnings_calendar_passes_market_and_dates(base_futu_cfg, patched_futu, monkeypatch) -> None:
+ quote_ctx = _FakeQuoteCtx(handlers={("get_earnings_calendar",): (0, [])})
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: quote_ctx)
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+
+ futu_sdk.get_earnings_calendar(
+ config=base_futu_cfg, market="US", begin_date="2026-08-19", end_date="2026-08-25"
+ )
+
+ assert quote_ctx.calls == [
+ ("get_earnings_calendar", ("US", "2026-08-19", "2026-08-25"))
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Profiles: every profile advertises the extended read capabilities so the
+# agent loop's profile-picker sees them; runtime is still profile-aware via the
+# service layer's "unsupported" envelope.
+# ---------------------------------------------------------------------------
+
+
+def test_all_futu_profiles_advertise_extended_read_capabilities() -> None:
+ from src.trading.types import FUTU_EXTENDED_READ_CAPABILITIES
+
+ for profile in futu_profiles.FUTU_PROFILES:
+ for cap in FUTU_EXTENDED_READ_CAPABILITIES:
+ assert cap in profile.capabilities, (
+ f"{profile.id} missing capability {cap}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Service-layer envelope: an SDK connector that does NOT implement one of
+# the new endpoints must return a clean "unsupported" payload, not raise.
+# ---------------------------------------------------------------------------
+
+
+def test_service_returns_unsupported_when_sdk_function_missing(monkeypatch) -> None:
+ """Other SDK connectors (IBKR, Alpaca, etc.) don't expose ``get_rehab``.
+
+ The service layer should return ``{"status": "error", ...}`` instead of
+ crashing the agent loop when an unsupported capability is requested.
+ """
+ # We monkeypatch _sdk_module to a fake alpaca module with no get_rehab.
+ import src.trading.service as service
+
+ class _FakeAlpacaModule:
+ RET_OK = 0
+
+ @staticmethod
+ def build_config(profile_config, overrides=None):
+ return object()
+
+ @staticmethod
+ def get_account_snapshot(config):
+ return {"status": "ok"}
+
+ monkeypatch.setattr(service, "_sdk_module", lambda connector: _FakeAlpacaModule)
+
+ from src.trading.profiles import list_profiles
+
+ # pick an alpaca profile, fall back to first broker_sdk profile
+ profile_id = next(p.id for p in list_profiles() if p.connector == "alpaca")
+ result = service.get_rehab("US.AAPL", profile_id=profile_id)
+
+ assert result["status"] == "error"
+ assert "rehab.read" in result.get("error", "") or "unsupported" in json.dumps(result).lower()
+
+
+# ---------------------------------------------------------------------------
+# Capability metadata: types.FUTU_EXTENDED_READ_CAPABILITIES is a flat tuple of
+# the seven expected strings.
+# ---------------------------------------------------------------------------
+
+
+def test_futu_extended_capabilities_are_exactly_seven() -> None:
+ from src.trading.types import FUTU_EXTENDED_READ_CAPABILITIES
+
+ assert len(FUTU_EXTENDED_READ_CAPABILITIES) == 7
+ assert set(FUTU_EXTENDED_READ_CAPABILITIES) == {
+ "rehab.read",
+ "capital_flow.read",
+ "capital_distribution.read",
+ "history_deals.read",
+ "acc_cash_flow.read",
+ "financials.read",
+ "earnings_calendar.read",
+ }
\ No newline at end of file