diff --git a/backend_api_python/app/services/strategy_runtime/price_freshness.py b/backend_api_python/app/services/strategy_runtime/price_freshness.py index 4b04a611e..cc94e7ca9 100644 --- a/backend_api_python/app/services/strategy_runtime/price_freshness.py +++ b/backend_api_python/app/services/strategy_runtime/price_freshness.py @@ -37,7 +37,7 @@ def execution_price_age_limit(key, fallback, execution_mode="live"): return fallback -def daily_signal_wait_reason(candidates, prices, seen_at, *, clock, max_age, quotes, now, execution_mode="live"): +def daily_signal_wait_reason(candidates, prices, seen_at, *, clock, max_age, quotes, now, execution_mode="live", skip_unavailable=False): """Describe the exact missing execution quotes without weakening freshness.""" missing = sorted(str(member["key"]) for member in candidates if ( str(member["key"]) not in prices @@ -52,7 +52,8 @@ def daily_signal_wait_reason(candidates, prices, seen_at, *, clock, max_age, quo observed = quote_timestamp(quote.get("quote_time")) age = f"{max(0, int(pd.Timestamp(now).timestamp() - observed))}s" if observed else "unknown" details.append(f"{key}[source={quote.get('quote_source') or 'unknown'},age={age}]") - return f"Daily signal waiting for fresh quotes: {len(missing)}/{len(candidates)}; " + ", ".join(details) + action = "skipping unavailable quotes" if skip_unavailable and len(missing) < len(candidates) else "waiting for fresh quotes" + return f"Daily signal {action}: {len(missing)}/{len(candidates)}; " + ", ".join(details) def filter_execution_prices(prices, equity_quotes, *, now, execution_mode): diff --git a/backend_api_python/app/services/trading_executor.py b/backend_api_python/app/services/trading_executor.py index 98fc84a0c..3520f15e2 100644 --- a/backend_api_python/app/services/trading_executor.py +++ b/backend_api_python/app/services/trading_executor.py @@ -1573,14 +1573,18 @@ def wake_for_closed_bar(event) -> None: ) ) if daily_policy: + daily_quotes_available = any( + str(member["key"]) in active_prices for member in daily_members + ) wait_reason = daily_signal_wait_reason( daily_members, active_prices, last_price_seen_at, clock=time.monotonic(), max_age=price_stale_after, quotes=equity_quotes, now=pd.Timestamp.now(tz="UTC"), execution_mode=execution_mode, + skip_unavailable=True, ) if wait_reason: - signal_data_error = "marketData.incomplete_market_data" + signal_data_error = "" if daily_quotes_available else "marketData.incomplete_market_data" if not daily_wait_reason or time.monotonic() - daily_wait_logged_at >= 60: append_strategy_log(strategy_id, "warning", wait_reason) daily_wait_logged_at = time.monotonic() @@ -1596,7 +1600,7 @@ def wake_for_closed_bar(event) -> None: signal_session, daily_policy[0], ) - and not wait_reason + and daily_quotes_available ) if frame_advanced or schedule_due: begin_signal_cycle = getattr( @@ -1624,6 +1628,22 @@ def wake_for_closed_bar(event) -> None: ) not in protected ] if daily_policy: + skipped_intents = [ + intent for intent in intents if str(intent.symbol) not in active_prices + ] + intents = [intent for intent in intents if str(intent.symbol) in active_prices] + if skipped_intents: + session.context.update_order_statuses({ + intent.client_order_id: { + "client_order_id": intent.client_order_id, + "status": "rejected", + "reason": "marketData.incomplete_market_data", + } + for intent in skipped_intents if intent.client_order_id + }) + append_strategy_log(strategy_id, "warning", + f"Daily signal skipped {len(skipped_intents)} order intent(s) without fresh quotes: " + + ", ".join(sorted({str(intent.symbol) for intent in skipped_intents})[:10])) append_strategy_log(strategy_id, "info", f"Daily signal evaluated: session={signal_session.date()}, " f"instruments={len(daily_members)}, intents={len(intents)}, " diff --git a/backend_api_python/tests/test_daily_partial_quotes.py b/backend_api_python/tests/test_daily_partial_quotes.py new file mode 100644 index 000000000..682f4734b --- /dev/null +++ b/backend_api_python/tests/test_daily_partial_quotes.py @@ -0,0 +1,141 @@ +"""Exercise the real executor loop with a stubbed isolated strategy process.""" + +from contextlib import nullcontext +from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import Mock + +import pandas as pd +import pytest + +from app.services import market_schedule, trading_executor as runtime +from app.services.strategy_runtime import candle_readiness +from app.services.strategy_v2.models import InstrumentSpec, StrategyManifest, SubscriptionSpec, UniverseSpec + + +@pytest.mark.parametrize("market,symbols,hour", [ + ("HKStock", ["00700.HK", "00005.HK"], 2), + ("USStock", ["AAPL", "MSFT"], 15), +]) +@pytest.mark.parametrize("unavailable", ["stale", "missing", "unknown", "all", "recovered"]) +def test_daily_partial_quotes_skip_orders_without_blocking_other_members(monkeypatch, market, symbols, hour, unavailable): + now = pd.Timestamp(f"2026-11-25T{hour:02d}:00:00Z") + tick = [100.0] + + class Clock(datetime): + @classmethod + def now(cls, tz=None): + return now.to_pydatetime().astimezone(tz or timezone.utc) + + class Timestamp(pd.Timestamp): + @classmethod + def now(cls, tz=None): + return now.tz_convert(tz or "UTC") + + proxy = Mock(wraps=pd) + proxy.Timestamp = Timestamp + proxy.DataFrame = pd.DataFrame + monkeypatch.setattr(runtime, "pd", proxy) + for module in (runtime, candle_readiness, market_schedule): + monkeypatch.setattr(module, "datetime", Clock) + monkeypatch.setattr(runtime, "time", SimpleNamespace(monotonic=lambda: tick[0], time=lambda: now.timestamp())) + monkeypatch.setenv("BAR_CLOSE_EVENT_SCHEDULER_ENABLED", "0") + monkeypatch.setenv("EQUITY_QUOTE_MAX_AGE_MINUTES", "16") + specs = tuple(InstrumentSpec(market=market, symbol=symbol, market_type="spot") for symbol in symbols) + members = [{**spec.metadata(), "key": spec.key} for spec in specs] + keys = [spec.key for spec in specs] + manifest = StrategyManifest(2, "fixture", "portfolio", UniverseSpec("static", instruments=specs), + (SubscriptionSpec(instruments=specs),), (), warmup_bars=2) + program = SimpleNamespace(manifest=manifest, has_handler=lambda _: False, namespace={}) + monkeypatch.setattr(runtime, "inspect_strategy_v2", lambda _: program) + frame = pd.DataFrame({"open": 100., "high": 101., "low": 99., "close": 100., "volume": 1.}, + index=pd.date_range("2026-11-20", "2026-11-24", freq="B")) + frames = {key: frame for key in keys} + monkeypatch.setattr(runtime.StrategyV2BacktestService, "resolve_candidates", lambda *a, **kw: (members, 0)) + monkeypatch.setattr(runtime.StrategyV2BacktestService, "fetch_frequency_frames", lambda *a, **kw: ({"1d": frames}, [])) + + def quotes(*args, **kwargs): + output = {symbols[0]: {"last": 100., "quote_time": now.timestamp(), "quote_source": "test"}} + if unavailable == "recovered": + return {symbol: dict(output[symbols[0]]) for symbol in symbols} if tick[0] >= 220 else {} + if unavailable == "all": + return {} + if unavailable != "missing": + output[symbols[1]] = {"last": 100., "quote_time": now.timestamp() - 1077 if unavailable == "stale" else 0, + "quote_source": "test"} + return output + + monkeypatch.setattr(runtime.DataSourceFactory, "get_tickers", quotes) + intents = [SimpleNamespace(symbol=key, position_side="", signal_time=None, client_order_id=f"order-{i}") + for i, key in enumerate(keys)] + session = Mock() + session.context.order_references.return_value = set() + session.context.order_status_snapshot.return_value = {} + session.evaluate_equity_risk.return_value = ([], [], "") + session.evaluate_protections.return_value = [] + session.pending_protection_exit_symbols.return_value = set() + session.process.return_value = (intents, [], frame.index[-1]) + session.session_snapshot.return_value = {} + monkeypatch.setattr(runtime, "StrategyV2LiveSession", Mock(return_value=session)) + monkeypatch.setattr(runtime, "build_runtime_event_bus", Mock(return_value=Mock())) + executor = runtime.TradingExecutor(external_bar_triggers=False) + strategy = {"id": 1, "user_id": 1, "execution_mode": "live", "initial_capital": 1000, "market_category": market} + positions = {keys[1]: {"amount": 1., "avg_cost": 90., "last_price": 100.}} + monkeypatch.setattr(executor, "_load_strategy", lambda _: strategy) + monkeypatch.setattr(executor, "_load_source", lambda _: (1, "fixture")) + monkeypatch.setattr(executor, "_load_schedule_timezone", lambda _: "UTC") + monkeypatch.setattr(executor, "_positions_by_symbol", lambda *a, **kw: positions) + monkeypatch.setattr(executor, "_calculate_current_equity", lambda *a, **kw: 1000.) + monkeypatch.setattr(executor, "_register_event_subscriptions", lambda *a: None) + monkeypatch.setattr("app.services.live_trading.records.mark_live_positions", Mock()) + monkeypatch.setattr(executor, "_mark_stopped", Mock()) + heartbeat, submit, logs = Mock(), Mock(return_value=True), Mock() + monkeypatch.setattr(executor, "_heartbeat", heartbeat) + monkeypatch.setattr(executor, "_execute_strategy_v2_intent", submit) + monkeypatch.setattr(runtime, "append_strategy_log", logs) + monkeypatch.setattr(runtime, "ensure_strategy_run", lambda **kw: SimpleNamespace(strategy_run_id=1, runtime_epoch=1)) + monkeypatch.setattr(runtime, "finish_strategy_run", Mock()) + store = Mock() + store.load.return_value = {} + monkeypatch.setattr(runtime, "RuntimeStateStore", lambda **kw: store) + monkeypatch.setattr(runtime, "OrderIntentService", Mock()) + monkeypatch.setattr(runtime, "persist_cancellations", Mock()) + batches = Mock(side_effect=lambda **kw: nullcontext("batch")) + monkeypatch.setattr(runtime, "rebalance_batch", batches) + cycles = iter([True, True, False]) + monkeypatch.setattr(executor, "_is_strategy_running", lambda *a: next(cycles)) + try: + for _ in executor._run_strategy_loop(1): + tick[0] += 60 + finally: + executor.close() + assert not executor._last_exit_reason, logs.call_args_list + executor._mark_stopped.assert_not_called() + assert session.synchronize_positions.call_args.args[0] == positions + assert session.synchronize_positions.call_args.kwargs["available_cash"] == (900 if unavailable == "recovered" else 0) + if unavailable == "all": + session.process.assert_not_called() + submit.assert_not_called() + batches.assert_not_called() + assert heartbeat.call_args.kwargs["status"] == "degraded" + assert "Daily signal waiting for fresh quotes: 2/2" in str(logs.call_args_list) + elif unavailable == "recovered": + session.process.assert_called_once() + assert submit.call_count == 2 + assert {call.kwargs["intent"].symbol for call in submit.call_args_list} == set(keys) + assert "Daily signal quote requirements recovered" in str(logs.call_args_list) + assert heartbeat.call_args.kwargs["status"] == "healthy" + else: + session.process.assert_called_once() + assert session.process.call_args.kwargs["universe_members"] == keys + assert set(session.process.call_args.args[0]) == set(keys) + submit.assert_called_once() + assert submit.call_args.kwargs["intent"].symbol == keys[0] + assert submit.call_args.kwargs["current_price_override"] == 100. + statuses = {key: value for call in session.context.update_order_statuses.call_args_list + for key, value in call.args[0].items()} + assert statuses["order-1"]["status"] == "rejected" + assert statuses["order-0"]["status"] == "submitted" + assert heartbeat.call_args.kwargs["status"] == "healthy" + assert "Daily signal skipping unavailable quotes: 1/2" in str(logs.call_args_list) + assert "Daily signal skipped 1 order intent(s)" in str(logs.call_args_list) diff --git a/docs/trading/LIVE_TRADING_SAFETY.md b/docs/trading/LIVE_TRADING_SAFETY.md index d9e3dcf9f..61f0047a4 100644 --- a/docs/trading/LIVE_TRADING_SAFETY.md +++ b/docs/trading/LIVE_TRADING_SAFETY.md @@ -180,6 +180,8 @@ Broker-equity runtime prices retain the provider's observation timestamp through ## Large equity universes and market-data diagnosis +Live US/HK daily strategies without explicit schedules no longer wait for every constituent to have a fresh execution quote. If at least one ready constituent has a valid quote, the strategy evaluates its complete historical panel and universe, then skips each generated order whose symbol lacks a valid execution quote. This applies to entries, additions and exits; skipped intents are reported in logs and marked rejected in the session, without creating pending broker orders. Existing positions and universe membership are not removed, and normal cash/budget guards remain enforced. The signal bar is consumed once, so skipped orders are not automatically replayed when quotes recover during the same bar; the strategy reconsiders them on its next signal. If all constituent quotes are unavailable, evaluation waits and retries. Historical-candle readiness, quote-age/session checks, and runtime protection rules are unchanged. + HK execution quotes use Tencent batches of at most 100 unique symbols, with a 15-second process-local cache shared by batch consumers. Concurrent batch consumers reuse cached results. Responses are matched by security code, not response order. A failed batch ends that fetch pass; missing quotes remain unavailable and are retried on the next cycle instead of falling back to hundreds of individual requests. Tencent HK slash-separated timestamps and compact A-share timestamps are parsed in UTC+8; missing or malformed times remain unknown. Cache reuse never renews the observation time or bypasses freshness/session checks. This reduces a 702-symbol cold quote pass to eight HTTP requests, not a guaranteed latency or data-coverage SLA. Deploy the backend and trading workers together; no migration is required. Live US/HK daily warmup accepts the declared number of distinct, valid OHLC bars even when a newer listing does not cover the full padded calendar lookback. This exception is limited to runtime warmup; historical backtests still require their requested window. Latest completed-session checks, warmup readiness, and execution-quote freshness remain enforced. A successful HTTP response does not prove that a candle is current. diff --git a/docs/trading/LIVE_TRADING_SAFETY_CN.md b/docs/trading/LIVE_TRADING_SAFETY_CN.md index 3a1190164..30d35fe69 100644 --- a/docs/trading/LIVE_TRADING_SAFETY_CN.md +++ b/docs/trading/LIVE_TRADING_SAFETY_CN.md @@ -132,6 +132,8 @@ JEV 是一种 System One 模型:它针对整理好的状态与类型化问题 ## 大型股票池与行情排查 +没有显式定时调度的美股、港股日线实盘策略,不再等待整个股票池的执行报价全部有效。只要至少一个已就绪标的有有效报价,就使用完整历史行情和股票池计算信号,再逐笔跳过缺少有效执行报价的订单,包括开仓、加仓和退出。跳过原因写入日志,会话中的订单状态记为拒绝,不创建待提交券商订单。不会删除已有持仓或股票池成员,原有可用资金和预算检查仍然生效。该信号柱只处理一次,报价在同一根日线内恢复后不会自动补追跳过的订单,后续由策略在下一次信号重新判断。若所有标的都没有有效报价,则继续等待重试。历史 K 线就绪、报价时效与交易时段检查以及运行时保护规则保持不变。 + 港股执行报价通过腾讯批量获取,每批最多 100 个去重后的标的,批量调用者共享进程内 15 秒缓存,并发调用复用缓存结果。响应按证券代码匹配,不依赖返回顺序。批次失败时结束本轮取价,缺失报价保持不可用,下一轮重试,不退回数百次逐只请求。腾讯港股带斜杠的时间和 A 股紧凑格式时间均按 UTC+8 解析;缺失或格式错误的时间仍视为未知。缓存不会刷新原始报价时间,也不会绕过新鲜度和交易时段检查。702 只股票的完整冷取价由 702 次请求缩减为 8 次,不代表接口时延或覆盖率保证。部署时同步更新后端和交易 Worker,无需数据库迁移。 股票实盘的执行报价有效期可在“系统设置 → 实盘交易 → 报价最大允许延迟(分钟)”调整,对应 `EQUITY_QUOTE_MAX_AGE_MINUTES`,允许 1–60 的整数,默认 16 分钟。它同时适用于股票开仓、日线调仓、本地止盈止损和组合风控;股票接收缓存使用相同窗口,避免被加密货币的短超时提前拦截。保存后需重启交易及策略运行 Worker,无需数据库迁移。默认值兼容 15 分钟延迟行情,但不会使其变成实时行情;止损可能滞后,参考价也可能与成交价不同。仍检查原始行情时间、未来时间及当前连续交易时段;命中缓存不刷新原始时间。延迟源在开盘或午后开市初段仍可能等待本时段报价到达。加密货币、回测和仅通知模式的规则不变。