ZhuLinsen/daily_stock_analysis · error · RuntimeError

Longbridge QuoteContext not available

Error message

Longbridge QuoteContext not available

What it means

Raised when LongbridgeFetcher._get_ctx() returns None, i.e. a Longbridge QuoteContext could not be created. This almost always means the Longbridge SDK is not installed or credentials (LONGBRIDGE_APP_KEY / LONGBRIDGE_APP_SECRET / LONGBRIDGE_ACCESS_TOKEN) are missing/invalid, so the quote context was never initialized.

Source

Thrown at data_provider/longbridge_fetcher.py:881

    # ------------------------------------------------------------------
    # BaseFetcher abstract methods (historical daily data)
    # ------------------------------------------------------------------

    def _fetch_raw_data(
        self, stock_code: str, start_date: str, end_date: str
    ) -> pd.DataFrame:
        """Fetch historical candlesticks from Longbridge."""
        if not self.is_available_for_request("daily_data"):
            raise RuntimeError("Longbridge temporarily unavailable for daily_data")

        symbol = _to_longbridge_symbol(stock_code)
        if symbol is None:
            raise ValueError(f"Cannot convert {stock_code} to Longbridge symbol")

        ctx = self._get_ctx()
        if ctx is None:
            raise RuntimeError("Longbridge QuoteContext not available")

        from longbridge.openapi import Period, AdjustType

        start_dt = datetime.strptime(start_date, "%Y-%m-%d").date()
        end_dt = datetime.strptime(end_date, "%Y-%m-%d").date()

        try:
            candles = ctx.history_candlesticks_by_date(
                symbol,
                Period.Day,
                AdjustType.ForwardAdjust,
                start_dt,
                end_dt,
            )
        except Exception as e:
            if self._is_connection_error(e):
                self._mark_connection_cooldown(e)
            raise

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Set the Longbridge credentials (app key, app secret, access token) in the environment/.env and confirm the longbridge package is installed.
  2. Call the fetcher's availability check (is_available_for_request / credentials probe) before routing requests to LongbridgeFetcher, and drop it from the provider chain when unavailable.
  3. If the context creation previously failed, investigate the underlying error logged during initialization instead of retrying blindly.

Example fix

# before
df = longbridge_fetcher.get_stock_data("00700.HK", start, end)  # RuntimeError: QuoteContext not available

# after
if longbridge_fetcher._get_ctx() is not None:
    df = longbridge_fetcher.get_stock_data("00700.HK", start, end)
else:
    df = manager.get_stock_data("00700.HK", start, end)  # fallback provider
Defensive patterns

Strategy: validation

Validate before calling

ctx = longbridge_fetcher._get_ctx()
if ctx is None:
    logger.warning("Longbridge unavailable; skipping provider")
    # route to manager fallback instead of calling the fetcher

Try / catch

try:
    df = longbridge_fetcher.get_stock_data(code, start, end)
except RuntimeError as e:
    if "QuoteContext not available" in str(e):
        df = manager.get_stock_data(code, start, end)
    else:
        raise

Prevention

When it happens

Trigger: Calling _fetch_raw_data on LongbridgeFetcher after the context initialization failed or was skipped: SDK import failure, missing token env vars, or an earlier failed _get_ctx() that left the context as None.

Common situations: Deploying without Longbridge credentials in .env; LongbridgeFetcher left in the data source chain although the account has no API access; SDK version change breaking context creation; token expired/revoked.

Related errors


AI-assisted analysis of ZhuLinsen/daily_stock_analysis@5159bd72e8 (2026-08-15). Data as JSON: /api/errors/8d6a3819e3f9a7d1. Report an issue: GitHub.