Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
139 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
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
37 changes: 36 additions & 1 deletion backend_api_python/app/data_sources/hk_stock.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import time

from app.data_sources.base import BaseDataSource
from app.data_sources.tencent import normalize_hk_code, fetch_quote, parse_quote_to_ticker, fetch_kline, tencent_kline_rows_to_dicts
from app.data_sources.tencent import normalize_hk_code, fetch_quote, fetch_quotes, parse_quote_to_ticker, fetch_kline, tencent_kline_rows_to_dicts
from app.data_sources.asia_stock_kline import (
normalize_chart_timeframe,
fetch_twelvedata_klines,
Expand All @@ -35,12 +35,47 @@ class HKStockDataSource(BaseDataSource):
name = "HKStock/multi-source"
_tencent_backoff_lock = threading.Lock()
_tencent_blocked_until = 0.0
_quote_lock = threading.Lock()
_quote_cache: Dict[str, tuple[float, Dict[str, Any]]] = {}

def get_tickers(self, symbols: List[str]) -> Dict[str, Dict[str, Any]]:
"""Reuse short-lived batches without changing provider observation times."""
codes = {symbol: normalize_hk_code(symbol) for symbol in symbols if symbol}
with self._quote_lock:
now = time.monotonic()
for code, (expires, _) in list(self._quote_cache.items()):
if expires <= now:
del self._quote_cache[code]
quotes = {code: dict(value[1]) for code, value in self._quote_cache.items()}
missing = list(dict.fromkeys(code for code in codes.values() if code not in quotes))
for offset in range(0, len(missing), 100):
batch = missing[offset:offset + 100]
try:
raw = fetch_quotes(batch)
except Exception as exc:
logger.warning("HK quote batch failed (%s); retrying on next cycle", type(exc).__name__)
break
for code in batch:
if not raw.get(code):
continue
ticker = self._quote_from_parts(code, raw[code])
quotes[code] = ticker
if ticker.get("last", 0) > 0 and ticker.get("quote_time", 0) > 0:
self._quote_cache[code] = (time.monotonic() + 15.0, dict(ticker))
return {
symbol: dict(quotes.get(code) or {"last": 0, "symbol": code})
for symbol, code in codes.items()
}

def get_ticker(self, symbol: str) -> Dict[str, Any]:
code = normalize_hk_code(symbol)
parts = fetch_quote(code)
if not parts:
return {"last": 0, "symbol": code}
return self._quote_from_parts(code, parts)

@staticmethod
def _quote_from_parts(code: str, parts: List[str]) -> Dict[str, Any]:
t = parse_quote_to_ticker(parts)
return {
"last": t.get("last", 0),
Expand Down
43 changes: 39 additions & 4 deletions backend_api_python/app/data_sources/tencent.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from __future__ import annotations

from datetime import datetime
import re
from typing import Any, Dict, List, Optional

import requests
Expand Down Expand Up @@ -72,6 +73,36 @@ def _lower_code(code: str) -> str:
return (code or "").strip().lower()


def fetch_quotes(codes: List[str], timeout: int = 5) -> Dict[str, List[str]]:
"""Fetch one bounded batch, matching responses by code rather than order.

The caller retries missing quotes on its next cycle instead of expanding a
failed batch into hundreds of individual requests.
"""
requested = list(dict.fromkeys(_lower_code(code) for code in codes if code))
if not requested:
return {}
if len(requested) > 100 or any(not re.fullmatch(r"hk\d{5}", code) for code in requested):
raise ValueError("Expected at most 100 canonical HK quote codes")
assert_fd_available("Tencent quote batch")
get_tencent_limiter().wait()
with requests.get(
"https://qt.gtimg.cn/q=" + ",".join(requested),
headers=get_request_headers(referer="https://qt.gtimg.cn/"),
timeout=timeout,
) as resp:
resp.raise_for_status()
resp.encoding = "gbk"
text = resp.text or ""
output = {}
for match in re.finditer(r'v_(hk\d{5})="([^"\r\n]*)"', text):
code, payload = match.groups()
parts = payload.split("~")
if code in requested and len(parts) > 5 and parts[2] == code[2:]:
output[code.upper()] = parts
return output


@retry_with_backoff(max_attempts=3, base_delay=1.2, max_delay=8.0, exceptions=(Exception,))
def fetch_quote(code: str, timeout: int = 8) -> Optional[List[str]]:
"""
Expand Down Expand Up @@ -133,10 +164,14 @@ def _f(i: int, default: float = 0.0) -> float:
# Indices are not fully consistent across markets; keep conservative.
high = _f(33, last_) if len(parts) > 33 else last_
low = _f(34, last_) if len(parts) > 34 else last_
try:
observed = datetime.strptime(parts[30], "%Y%m%d%H%M%S")
except (IndexError, TypeError, ValueError):
observed = None
observed = None
raw_time = str(parts[30] or "").strip() if len(parts) > 30 else ""
for fmt in ("%Y%m%d%H%M%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d %H:%M:%S"):
try:
observed = datetime.strptime(raw_time, fmt)
break
except ValueError:
continue

return {
"symbol": symbol,
Expand Down
192 changes: 192 additions & 0 deletions backend_api_python/tests/test_hk_quote_batches.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""HK provider timestamps and bounded quote collection for large universes."""

from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace

import pandas as pd
import pytest
import requests

from app.data_sources import hk_stock, tencent
from app.data_sources.factory import DataSourceFactory
from app.services.strategy_runtime.price_freshness import filter_execution_prices


def parts(code="00700", timestamp="2026/11/30 11:50:10", price="355.8"):
values = [""] * 35
values[1:6] = ["Test", code, price, "350", "351"]
values[30] = timestamp
return values


@pytest.fixture(autouse=True)
def reset_cache(monkeypatch):
monkeypatch.setattr(hk_stock.HKStockDataSource, "_quote_cache", {})
monkeypatch.delenv("EQUITY_QUOTE_MAX_AGE_MINUTES", raising=False)


@pytest.mark.parametrize("stamp", [
"2026/11/30 11:50:10", "20261130115010", "2026-11-30 11:50:10",
])
def test_hk_and_cn_timestamp_formats_preserve_provider_time(stamp):
quote = tencent.parse_quote_to_ticker(parts(timestamp=stamp))
assert quote["quote_time"] == pd.Timestamp("2026-11-30T03:50:10Z").timestamp()


@pytest.mark.parametrize("stamp", ["", "garbage", "2026/02/30 10:00:00", "11:50:10"])
def test_invalid_time_stays_unknown(stamp):
assert tencent.parse_quote_to_ticker(parts(timestamp=stamp))["quote_time"] == 0
assert tencent.parse_quote_to_ticker(parts()[:6])["quote_time"] == 0


def test_batch_response_identity_missing_and_unrequested_symbols(monkeypatch):
body = '\n'.join([
'v_hk00005="' + '~'.join(parts("00005", price="100")) + '";',
'v_hk00700="' + '~'.join(parts()) + '";',
'v_hk00001="' + '~'.join(parts("00002")) + '";',
'v_hk00999="' + '~'.join(parts("00999")) + '";',
'v_hk00003="";',
])
calls, waits = [], []

class Response:
text = body

def __enter__(self):
return self

def __exit__(self, *args):
return False

def raise_for_status(self):
pass

def get(url, **kwargs):
calls.append((url, kwargs))
return Response()

monkeypatch.setattr(tencent.requests, "get", get)
monkeypatch.setattr(tencent, "assert_fd_available", lambda *_: None)
monkeypatch.setattr(tencent, "get_tencent_limiter", lambda: SimpleNamespace(wait=lambda: waits.append(1)))
result = tencent.fetch_quotes(["HK00700", "HK00005", "HK00001", "HK00003", "hk00700"])
assert set(result) == {"HK00700", "HK00005"}
assert result["HK00005"][3] == "100"
assert len(calls) == len(waits) == 1
assert calls[0][0].endswith("q=hk00700,hk00005,hk00001,hk00003")
assert calls[0][1]["timeout"] == 5


def test_702_quotes_use_eight_batches_through_factory(monkeypatch):
calls = []

def fetch(codes):
calls.append(codes)
return {code: parts(code[2:]) for code in codes}

monkeypatch.setattr(hk_stock, "fetch_quotes", fetch)
monkeypatch.setattr(hk_stock, "fetch_quote", lambda *_: pytest.fail("single-symbol fallback"))
symbols = [f"{number:05d}.HK" for number in range(1, 703)]
quotes = DataSourceFactory.get_tickers("HKStock", symbols)
assert len(quotes) == 702
assert [len(batch) for batch in calls] == [100] * 7 + [2]
assert all(quote["quote_time"] > 0 for quote in quotes.values())
assert quotes["00001.HK"]["symbol"] == "HK00001"


def test_missing_quotes_do_not_expand_into_single_requests(monkeypatch):
calls = []

def fetch(codes):
calls.append(codes)
return {"HK00700": parts()}

monkeypatch.setattr(hk_stock, "fetch_quotes", fetch)
monkeypatch.setattr(hk_stock, "fetch_quote", lambda *_: pytest.fail("single-symbol fallback"))
result = DataSourceFactory.get_tickers("HKStock", ["00700.HK", "00005.HK"])
assert len(calls) == 1
assert result["00700.HK"]["last"] == 355.8
assert result["00005.HK"]["last"] == 0


def test_failed_batch_preserves_completed_batch_and_stops_fanout(monkeypatch):
calls = []

def fetch(codes):
calls.append(codes)
if len(calls) == 2:
raise requests.Timeout()
return {code: parts(code[2:]) for code in codes}

monkeypatch.setattr(hk_stock, "fetch_quotes", fetch)
monkeypatch.setattr(hk_stock, "fetch_quote", lambda *_: pytest.fail("single-symbol fallback"))
result = DataSourceFactory.get_tickers("HKStock", [f"{i:05d}.HK" for i in range(1, 703)])
assert len(calls) == 2
assert sum(quote["last"] > 0 for quote in result.values()) == 100


def test_cache_shared_across_instances_preserves_observation_and_expires(monkeypatch):
clock, calls = [100.0], []
monkeypatch.setattr(hk_stock.time, "monotonic", lambda: clock[0])

def fetch(codes):
calls.append(codes)
return {code: parts(code[2:]) for code in codes}

monkeypatch.setattr(hk_stock, "fetch_quotes", fetch)
first = hk_stock.HKStockDataSource().get_tickers(["700", "00700.HK"])
assert calls == [["HK00700"]]
first["700"]["last"] = 1
clock[0] += 14
again = hk_stock.HKStockDataSource().get_tickers(["00700.HK"])["00700.HK"]
assert len(calls) == 1
assert again["last"] == 355.8
assert again["quote_time"] == first["00700.HK"]["quote_time"]
clock[0] += 2
hk_stock.HKStockDataSource().get_tickers(["00700.HK"])
assert len(calls) == 2


def test_concurrent_consumers_share_one_batch(monkeypatch):
calls = []

def fetch(codes):
calls.append(codes)
return {code: parts(code[2:]) for code in codes}

monkeypatch.setattr(hk_stock, "fetch_quotes", fetch)
with ThreadPoolExecutor(max_workers=4) as pool:
results = list(pool.map(lambda _: hk_stock.HKStockDataSource().get_tickers(["00700.HK"]), range(4)))
assert len(calls) == 1
assert all(result["00700.HK"]["last"] == 355.8 for result in results)


def test_parsed_hk_quote_passes_freshness_but_old_or_unknown_time_does_not():
key = "HKStock:00700.HK"
now = pd.Timestamp("2026-11-30T03:51:00Z")
for stamp, accepted in [("2026/11/30 11:50:10", True), ("2026/11/30 11:30:00", False), ("", False)]:
quote = hk_stock.HKStockDataSource._quote_from_parts("HK00700", parts(timestamp=stamp))
result = filter_execution_prices({key: quote["last"]}, {key: quote}, now=now, execution_mode="live")
assert bool(result) is accepted


def test_unknown_time_is_retried_and_runtime_recovers(monkeypatch):
from app.services.trading_executor import TradingExecutor
from app.services.strategy_runtime.price_freshness import daily_signal_wait_reason

timestamp = [""]
monkeypatch.setattr(hk_stock, "fetch_quotes", lambda codes: {
code: parts(code[2:], timestamp=timestamp[0]) for code in codes
})
members = [{"key": "HKStock:00700.HK", "market": "HKStock", "symbol": "00700.HK"}]
now = pd.Timestamp("2026-11-30T03:51:00Z")
quotes = {}
prices = TradingExecutor._live_prices(members, equity_quotes=quotes)
accepted = filter_execution_prices(prices, quotes, now=now, execution_mode="live")
reason = daily_signal_wait_reason(members, accepted, {}, clock=1, max_age=960, quotes=quotes, now=now)
assert "1/1" in reason and "age=unknown" in reason
timestamp[0] = "2026/11/30 11:50:10"
prices = TradingExecutor._live_prices(members, equity_quotes=quotes)
accepted = filter_execution_prices(prices, quotes, now=now, execution_mode="live")
assert accepted == {"HKStock:00700.HK": 355.8}
assert daily_signal_wait_reason(members, accepted, {"HKStock:00700.HK": 1},
clock=1, max_age=960, quotes=quotes, now=now) == ""
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

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.

Daily runtime requests share normalized start dates and completed-session cutoffs across startup clocks. The process cache retains up to `STRATEGY_SHARED_FRAME_CACHE_MAX_SIZE` streams (default 4096), subject to `STRATEGY_SHARED_FRAME_CACHE_MAX_BYTES` (default 256 MiB). Each worker has its own bound. Redis reuse still depends on cache configuration and expiration; this is not a durable historical-data store. Crypto and intraday window rules are unchanged.
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 模型:它针对整理好的状态与类型化问题

## 大型股票池与行情排查

港股执行报价通过腾讯批量获取,每批最多 100 个去重后的标的,批量调用者共享进程内 15 秒缓存,并发调用复用缓存结果。响应按证券代码匹配,不依赖返回顺序。批次失败时结束本轮取价,缺失报价保持不可用,下一轮重试,不退回数百次逐只请求。腾讯港股带斜杠的时间和 A 股紧凑格式时间均按 UTC+8 解析;缺失或格式错误的时间仍视为未知。缓存不会刷新原始报价时间,也不会绕过新鲜度和交易时段检查。702 只股票的完整冷取价由 702 次请求缩减为 8 次,不代表接口时延或覆盖率保证。部署时同步更新后端和交易 Worker,无需数据库迁移。

股票实盘的执行报价有效期可在“系统设置 → 实盘交易 → 报价最大允许延迟(分钟)”调整,对应 `EQUITY_QUOTE_MAX_AGE_MINUTES`,允许 1–60 的整数,默认 16 分钟。它同时适用于股票开仓、日线调仓、本地止盈止损和组合风控;股票接收缓存使用相同窗口,避免被加密货币的短超时提前拦截。保存后需重启交易及策略运行 Worker,无需数据库迁移。默认值兼容 15 分钟延迟行情,但不会使其变成实时行情;止损可能滞后,参考价也可能与成交价不同。仍检查原始行情时间、未来时间及当前连续交易时段;命中缓存不刷新原始时间。延迟源在开盘或午后开市初段仍可能等待本时段报价到达。加密货币、回测和仅通知模式的规则不变。

港股、美股日线运行预热以声明的有效 K 线数量为准:较新上市的股票即使不足预留的完整日历区间,只要已有足量、去重且 OHLC 有效的历史柱,也可以参与预热。这项例外只用于运行预热,历史回测仍检查请求区间。最新完成交易日、预热就绪以及执行报价的新鲜度检查继续生效;接口成功返回不代表 K 线已经更新。
Expand Down