Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
141 commits
Select commit Hold shift + click to select a range
46577ab
feat: expand factor research and quick trade depth
tianhe Nov 1, 2026
bab1a3a
fix(quick-trade): normalize derivative order book units
tianhe Nov 1, 2026
235a5d7
docs(api): refresh OpenAPI export
tianhe Nov 1, 2026
5d64dac
security: harden secret handling and webhooks
tianhe Nov 1, 2026
aead75c
security: prevent exception detail exposure
tianhe Nov 1, 2026
05acff0
ci: satisfy quick trade size guardrail
tianhe Nov 1, 2026
1743af9
feat(research): add custom factor AI and crypto history paging
tianhe Nov 2, 2026
24a3f79
fix(research): avoid backtracking in factor JSON parsing
tianhe Nov 3, 2026
a1b97f6
chore: sync main into test
tianhe Nov 3, 2026
465f38d
feat: harden research, trading, and deployment flows
tianhe Nov 4, 2026
4dbc25a
fix(ci): restore backend quality gates
tianhe Nov 4, 2026
bf0cbaa
fix(market): preserve exact crypto product identity
tianhe Nov 4, 2026
f99ea50
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 4, 2026
c89626e
security(api): hide internal exception details
tianhe Nov 4, 2026
a8c3971
feat(api): harden analysis reports and public errors
tianhe Nov 4, 2026
7ac898d
Merge remote-tracking branch 'origin/main' into pr349-dco-fix
tianhe Nov 4, 2026
1e7a409
fix(ci): keep fast analysis within quality baseline
tianhe Nov 4, 2026
7acfb09
feat(ai): modernize scheduled monitor reports
tianhe Nov 5, 2026
7f62304
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 5, 2026
59cd27c
feat(market): generate localized share drafts
tianhe Nov 5, 2026
24b43fc
fix(security): sanitize share generation errors
tianhe Nov 5, 2026
35b1f59
fix(market): satisfy share draft quality checks
tianhe Nov 5, 2026
3ef8a2e
fix(runtime): harden marketplace metrics and evaluator capacity
tianhe Nov 5, 2026
d7291e2
fix(security): prevent exception detail exposure
tianhe Nov 5, 2026
d5e45bb
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 5, 2026
ef6ef1f
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 6, 2026
f787087
feat: harden asset identity and live recovery
tianhe Nov 6, 2026
6c24643
fix: restore backend CI quality gates
tianhe Nov 6, 2026
ec4f61d
fix: sanitize asset resolution errors
tianhe Nov 6, 2026
65705a9
fix: align agent contracts and runtime tests
tianhe Nov 6, 2026
7900f32
test: refresh hardened runtime fixtures
tianhe Nov 6, 2026
0e464f9
feat: harden strategy candle readiness and recovery
tianhe Nov 6, 2026
7c677e5
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 6, 2026
bf5b56c
fix(backtest): align crypto candle coverage boundaries (#359)
brokermr810 Nov 8, 2026
4d43538
fix(trading): normalize Binance protection orders
tianhe Nov 10, 2026
b50e459
fix(trading): snap Bitget and Bybit native protection prices to the tick
aliassar Nov 10, 2026
c4bf901
fix(trading): normalize protection orders across venues
tianhe Nov 11, 2026
08dbf0c
Merge branch 'main' into test
brokermr810 Nov 11, 2026
a2c968c
fix(trading): enforce run-scoped liquidation risk stops
tianhe Nov 11, 2026
ed391bf
fix(grid): support legacy recovery engines
tianhe Nov 11, 2026
80fcf31
fix(runtime): separate strategy lifecycle generations
tianhe Nov 11, 2026
06564e3
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 11, 2026
49276ac
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 13, 2026
06d0f26
fix(trading): reconcile protection fills and spot residuals
tianhe Nov 13, 2026
464683e
fix(db): prevent runtime lock convoys
tianhe Nov 14, 2026
914d20d
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 14, 2026
3b4be44
fix(security): harden sandbox and credential redaction
tianhe Nov 15, 2026
c893423
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 15, 2026
b4e6218
Merge branch 'main' into test
brokermr810 Nov 15, 2026
717e47f
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 15, 2026
c11275c
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 16, 2026
5da181d
fix(security): harden strategy execution boundaries
tianhe Nov 19, 2026
6bb83d4
fix(ci): keep quick trade route within guardrail
tianhe Nov 19, 2026
ee58c42
fix(security): document isolated exec boundary
tianhe Nov 19, 2026
f45e136
fix(security): prevent market data error disclosure
tianhe Nov 19, 2026
ce65bce
fix(sandbox): classify native loader memory failures
tianhe Nov 19, 2026
ef4ef76
docs: align repository and sandbox architecture maps
tianhe Nov 19, 2026
ae8f414
fix(sandbox): accept decimal position values
tianhe Nov 19, 2026
7e75542
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 19, 2026
9918457
fix(runtime): allow two-minute sandbox requests and preserve failures
tianhe Nov 19, 2026
bcd49ab
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 19, 2026
012303f
fix(config): align packaged sandbox environment defaults
tianhe Nov 19, 2026
4ca78a1
fix(research): support China equities in research reports
tianhe Nov 19, 2026
5842f38
feat(protection): reconcile partial exits and native rule semantics
tianhe Nov 19, 2026
5910642
feat(library): publish indicator and Strategy API V2 examples
tianhe Nov 19, 2026
cc677c1
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 19, 2026
256a713
fix(protection): compare native exit fractions exactly
tianhe Nov 19, 2026
0202e55
fix(research): report A-share evidence and data gaps accurately
tianhe Nov 19, 2026
dccc5da
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 19, 2026
81f18c2
fix(trading): suppress repeated residual exit orders and alerts
tianhe Nov 21, 2026
ff92d91
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 21, 2026
4b43c65
fix(grid): validate funded ladder before initial position
tianhe Nov 21, 2026
6a0c865
fix(notifications): unify strategy outcomes and branded multilingual …
tianhe Nov 21, 2026
64b9c04
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 21, 2026
2fa3365
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 21, 2026
4eceed0
fix(trading): correct stop and rebalance notification schema queries
tianhe Nov 21, 2026
d3d979f
fix(trading): preserve lifetime equity and clear closing precision tails
tianhe Nov 21, 2026
11ca4c0
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 21, 2026
8709bf8
fix(trading): reuse confirmed exchange order pnl without expiry
tianhe Nov 21, 2026
f7d5499
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 21, 2026
8312df4
fix(runtime): acknowledge distributed startup before completing commands
tianhe Nov 22, 2026
a706af9
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 22, 2026
2141799
test(runtime): align command fencing assertions with distributed claims
tianhe Nov 22, 2026
b951421
perf(runtime): reduce strategy history loading and health query overhead
tianhe Nov 22, 2026
f273971
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 22, 2026
1c48928
fix(trading): preserve grid protection and reconcile uncertain submis…
tianhe Nov 22, 2026
5b1af76
fix(research): strengthen cross-market fundamentals and event evidence
tianhe Nov 22, 2026
fce342f
test: align grid recovery regressions
tianhe Nov 22, 2026
80874ce
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 25, 2026
e1fa7b7
fix(grid): resolve orders missing from open orders on verify
Mystery01092000 Nov 24, 2026
cdbe569
fix(grid): reconcile residual orders in bounded worker audits
tianhe Nov 25, 2026
0e7208b
fix(marketplace): add author filters and balanced recommendations
tianhe Nov 25, 2026
9e9a6a7
fix(ai): keep ordinary crypto strategy generation venue independent
tianhe Nov 25, 2026
9ee91f5
fix(reports): split oversized PDF table rows across pages
tianhe Nov 25, 2026
4725b11
fix(indicators): align library scripts with safe runtime APIs
tianhe Nov 25, 2026
018fe40
fix(trading): harden session execution and fill reconciliation
tianhe Nov 25, 2026
af3b82e
fix(api): keep generated OpenAPI contract in sync
tianhe Nov 25, 2026
5b50f3c
fix(runtime): prevent rebalance replay after worker restart
tianhe Nov 25, 2026
0ea7a3e
chore: sync merged main history into test
tianhe Nov 25, 2026
a7626dc
fix(sandbox): warm NumPy modules before applying isolation
tianhe Nov 26, 2026
fdb6c66
feat(platform): add Forthright integration and advertisement settings
tianhe Nov 26, 2026
b809146
chore: sync merged main history into test
tianhe Nov 26, 2026
dfffa54
fix(ci): declare Forthright API tags and escape encoding fixtures
tianhe Nov 26, 2026
c0c30d6
fix(security): bound public inputs and document broker signature risks
tianhe Nov 27, 2026
2a43abe
fix(brokers): preserve equity identity and reconcile account fills
tianhe Nov 27, 2026
a0f7f5a
chore: sync merged main history into test
tianhe Nov 27, 2026
e740435
fix(brokers): normalize HK-prefixed securities and deduplicate search
tianhe Nov 27, 2026
2829b74
fix(brokers): reconcile delayed Forthright execution fees
tianhe Nov 27, 2026
405f3b7
chore: sync merged main history into test
tianhe Nov 27, 2026
12e0a24
fix(strategy): unify HK pool and position identities
tianhe Nov 27, 2026
71ade8b
chore: sync merged main history into test
tianhe Nov 27, 2026
5fa8e9b
perf(strategy): vectorize causal Bollinger series
tianhe Nov 27, 2026
e993a45
fix(runtime): improve equity warmup caching and quote diagnostics
tianhe Nov 27, 2026
1fa5e12
feat(trading): configure equity execution quote freshness
tianhe Nov 27, 2026
fe75f8e
chore: sync merged main history into test
tianhe Nov 27, 2026
dd0dc0b
test(settings): align curated equity quote policy contract
tianhe Nov 27, 2026
caec302
fix(trading): coordinate exchange REST limits and startup recovery
tianhe Nov 27, 2026
36f583b
chore: sync merged main history into test
tianhe Nov 27, 2026
f15cc33
fix(ci): align readiness tests and harden exchange guard identifiers
tianhe Nov 27, 2026
05bf386
fix(runtime): recover strategies after exchange cooldowns
tianhe Nov 27, 2026
646c87e
chore: sync merged main history into test
tianhe Nov 27, 2026
07eda14
fix(ws): use Binance USD-M /market stream path for swap feeds
buildwithpnj Nov 28, 2026
7e0ad10
fix(ws): migrate Binance futures private stream routing
tianhe Nov 28, 2026
2eb37fa
chore: sync merged main history into test
tianhe Nov 28, 2026
ff6a56e
fix(streams): recover subscriptions and validate live feed readiness
tianhe Nov 28, 2026
0c9c19c
chore: sync merged main history into test
tianhe Nov 28, 2026
132d466
fix(trading): reject unsafe sizing and invalid broker order values
tianhe Nov 28, 2026
86e4423
fix(security): return fixed order validation error identifiers
tianhe Nov 28, 2026
5ae3c8a
chore: exclude local design and visual QA artifacts
tianhe Nov 28, 2026
8dd038a
fix(strategy): reject non-finite order sizing and arithmetic overflow
tianhe Nov 28, 2026
a46efc5
chore: synchronize test with merged main
tianhe Nov 29, 2026
6eeec45
fix(quick-trade): support native trailing stop protection
PranavHariharan19 Nov 28, 2026
fd6edc2
fix(trading): enforce and reconcile attached protection across order …
tianhe Nov 29, 2026
7a66f88
fix(quick-trade): retire protection waits for rejected entries
tianhe Nov 29, 2026
951b38c
fix(trading): verify bracket children and preserve concurrent metadata
tianhe Nov 29, 2026
a93972b
fix(security): return public protection validation codes
tianhe Nov 29, 2026
51f928a
feat(trading): extend native protection and verify broker child orders
tianhe Nov 29, 2026
ee7d3cb
fix(market-data): batch HK quotes and preserve Tencent timestamps
tianhe Nov 30, 2026
e5644df
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 30, 2026
aa6900e
fix(runtime): skip unavailable quotes in daily equity orders
tianhe Nov 30, 2026
72b3a24
Merge remote-tracking branch 'origin/main' into test
tianhe Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
24 changes: 22 additions & 2 deletions backend_api_python/app/services/trading_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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(
Expand Down Expand Up @@ -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)}, "
Expand Down
141 changes: 141 additions & 0 deletions backend_api_python/tests/test_daily_partial_quotes.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 2 additions & 0 deletions docs/trading/LIVE_TRADING_SAFETY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions docs/trading/LIVE_TRADING_SAFETY_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 分钟延迟行情,但不会使其变成实时行情;止损可能滞后,参考价也可能与成交价不同。仍检查原始行情时间、未来时间及当前连续交易时段;命中缓存不刷新原始时间。延迟源在开盘或午后开市初段仍可能等待本时段报价到达。加密货币、回测和仅通知模式的规则不变。
Expand Down