"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): build the Longbridge SDK config through from_apikey (#1805)
alexwan89a78f37cf1b
diff --git a/agent/backtest/loaders/longbridge.py b/agent/backtest/loaders/longbridge.pyindex 2b1774ead..28a4be6f6 100644--- a/agent/backtest/loaders/longbridge.py+++ b/agent/backtest/loaders/longbridge.py@@ -40,6 +40,7 @@ from src.trading.connectors.longbridge.credentials import (LongbridgeCredentialError,resolve_longbridge_credentials,)+from src.trading.connectors.longbridge.sdk import build_sdk_configlogger = logging.getLogger(__name__)@@ -334,17 +335,20 @@ class LongbridgeLoader:openapi = _require_longbridge()_init_error: str | None = Nonetry:- cfg = openapi.Config(- self._app_key, self._app_secret, self._access_token,+ cfg = build_sdk_config(+ openapi, self._app_key, self._app_secret, self._access_token)ctx = openapi.QuoteContext(cfg)except LongbridgeDependencyError:raise- except Exception:- # Capture only stable text; do NOT raise inside the handler so- # the original exception (which may contain secrets) cannot- # leak into __context__.- _init_error = "Longbridge SDK initialization failed."+ except Exception as exc:+ # Keep only the exception type: its message may carry credentials,+ # but the type alone tells an SDK API change from a bad token. Do+ # NOT raise inside the handler, or the original exception leaks+ # into __context__.+ _init_error = (+ f"Longbridge SDK initialization failed ({type(exc).__name__})."+ )if _init_error is not None:raise NoAvailableSourceError(_init_error)diff --git a/agent/src/trading/connectors/longbridge/sdk.py b/agent/src/trading/connectors/longbridge/sdk.pyindex 5d2c106d9..31f11da16 100644--- a/agent/src/trading/connectors/longbridge/sdk.py+++ b/agent/src/trading/connectors/longbridge/sdk.py@@ -670,19 +670,29 @@ def _require_openapi() -> ModuleType:)-def _build_config(cfg: LongbridgeConfig):- openapi = _require_openapi()- config_cls = getattr(openapi, "Config")- # SDK exposes both a keyword constructor and a ``from_apikey`` factory across- # versions; try the direct constructor, fall back to the factory.- try:- return config_cls(- app_key=cfg.app_key,- app_secret=cfg.app_secret,- access_token=cfg.access_token,- )- except TypeError:- return config_cls.from_apikey(cfg.app_key, cfg.app_secret, cfg.access_token)+def build_sdk_config(+ openapi: Any, app_key: str, app_secret: str, access_token: str+) -> Any:+ """Build a ``longbridge.openapi.Config`` on any SDK in the supported range.++ From 4.0 the SDK refuses direct ``Config(...)`` construction and only offers+ ``Config.from_apikey``; 0.2.x has no ``from_apikey``. ``longbridge>=0.2.5``+ admits both, so pick by capability rather than by version number. Shared by+ this connector and the backtest loader so both follow one rule.++ Args:+ openapi: The SDK ``openapi`` module.+ app_key: Longbridge OpenAPI app key.+ app_secret: Longbridge OpenAPI app secret.+ access_token: Longbridge OpenAPI access token.++ Returns:+ The SDK ``Config`` instance.+ """+ config_cls = openapi.Config+ if hasattr(config_cls, "from_apikey"):+ return config_cls.from_apikey(app_key, app_secret, access_token)+ return config_cls(app_key, app_secret, access_token)def _require_resolved_config(cfg: LongbridgeConfig) -> None:@@ -701,13 +711,17 @@ def _require_resolved_config(cfg: LongbridgeConfig) -> None:def _trade_context(cfg: LongbridgeConfig):_require_resolved_config(cfg)openapi = _require_openapi()- return getattr(openapi, "TradeContext")(_build_config(cfg))+ return getattr(openapi, "TradeContext")(+ build_sdk_config(openapi, cfg.app_key, cfg.app_secret, cfg.access_token)+ )def _quote_context(cfg: LongbridgeConfig):_require_resolved_config(cfg)openapi = _require_openapi()- return getattr(openapi, "QuoteContext")(_build_config(cfg))+ return getattr(openapi, "QuoteContext")(+ build_sdk_config(openapi, cfg.app_key, cfg.app_secret, cfg.access_token)+ )#: Canonical period token → Longbridge ``Period`` attribute name.diff --git a/agent/tests/test_longbridge_loader.py b/agent/tests/test_longbridge_loader.pyindex 61f1d7e54..2e267e5d8 100644--- a/agent/tests/test_longbridge_loader.py+++ b/agent/tests/test_longbridge_loader.py@@ -255,6 +255,59 @@ def test_fetch_combines_all_windows_and_caches_complete_frame(pd.testing.assert_frame_equal(cached[0], result["AAPL"])+def test_fetch_uses_from_apikey_when_sdk_provides_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """SDK 4.0+ refuses ``Config(...)``; the loader must go through the factory."""+ factory_calls: list[tuple[str, ...]] = []+ built = object()++ class Sdk4Config:+ def __new__(cls, *args: object) -> "Sdk4Config":+ raise TypeError("cannot create 'builtins.Config' instances")++ @staticmethod+ def from_apikey(*args: str) -> object:+ factory_calls.append(args)+ return built++ class FakeQuoteContext:+ def __init__(self, config: object) -> None:+ assert config is built++ def history_candlesticks_by_date(+ self, *args: object, **kwargs: object+ ) -> list[SimpleNamespace]:+ return [+ SimpleNamespace(+ timestamp=pd.Timestamp(kwargs["start"]),+ open=10,+ high=11,+ low=9,+ close=10.5,+ volume=100,+ )+ ]++ fake_openapi = SimpleNamespace(+ Config=Sdk4Config,+ QuoteContext=FakeQuoteContext,+ Period=SimpleNamespace(Day="day"),+ AdjustType=SimpleNamespace(NoAdjust="none"),+ )+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)+ monkeypatch.setattr(loader_mod, "loader_cache_get", lambda **kwargs: None)+ monkeypatch.setattr(loader_mod, "loader_cache_put", lambda **kwargs: None)++ result = _configured_loader().fetch(+ ["AAPL"], "2026-01-01", "2026-01-02", interval="1D"+ )++ assert factory_calls == [("key", "secret", "token")]+ assert list(result) == ["AAPL"]+ assert_loader_contract(result["AAPL"], context="longbridge daily via from_apikey")++def test_fetch_rejects_partial_history_when_a_window_fails(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -326,7 +379,9 @@ def test_fetch_redacts_sdk_initialization_exception_and_drops_cause(with pytest.raises(NoAvailableSourceError) as exc_info:_configured_loader().fetch(["AAPL"], "2026-01-01", "2026-01-02")- assert str(exc_info.value) == "Longbridge SDK initialization failed."+ assert str(exc_info.value) == (+ "Longbridge SDK initialization failed (SecretBearingSdkError)."+ )assert secret not in str(exc_info.value)assert exc_info.value.__cause__ is Noneassert exc_info.value.__context__ is Nonediff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex e6d575ddf..3093608b5 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -186,6 +186,32 @@ def test_longbridge_invalid_region_rejected() -> None:lb.LongbridgeConfig.from_mapping({"region": "moon"})+def test_longbridge_quote_context_uses_from_apikey_on_sdk_4(monkeypatch) -> None:+ """SDK 4.0+ refuses ``Config(...)``; the connector must use the factory."""+ factory_calls: list[tuple[str, ...]] = []+ built = object()++ class Sdk4Config:+ def __new__(cls, *args: object, **kwargs: object) -> "Sdk4Config":+ raise TypeError("cannot create 'builtins.Config' instances")++ @staticmethod+ def from_apikey(*args: str) -> object:+ factory_calls.append(args)+ return built++ fake_openapi = SimpleNamespace(+ Config=Sdk4Config, QuoteContext=lambda config: config+ )+ monkeypatch.setattr(lb, "_require_openapi", lambda: fake_openapi)+ cfg = lb.LongbridgeConfig(+ app_key="k", app_secret="s", access_token="t", _credential_source="environment"+ )++ assert lb._quote_context(cfg) is built+ assert factory_calls == [("k", "s", "t")]++def test_longbridge_with_overrides_preserves_atomic_credentials() -> None:cfg = lb.LongbridgeConfig(app_key="atomic-key",