@dsh-ft/dsh-fft-paper-trading 0.6.2 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +25 -0
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +19 -7
- package/node_modules/@ftshare-lab/dsh-kline/README.md +20 -8
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +52 -6
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +185 -7
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +3783 -0
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +2 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +82 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +36 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +59 -44
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +22 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/package.json +18 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +179 -0
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +16 -11
- package/node_modules/@ftshare-lab/dsh-kline/server.py +3 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +143 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +185 -0
- package/package.json +2 -2
|
@@ -14,6 +14,7 @@ This module never searches for or imports another MCP repository.
|
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
16
|
import os
|
|
17
|
+
import csv
|
|
17
18
|
import json
|
|
18
19
|
import io
|
|
19
20
|
import re
|
|
@@ -32,6 +33,7 @@ from urllib.request import Request, urlopen
|
|
|
32
33
|
from xml.etree import ElementTree
|
|
33
34
|
from zoneinfo import ZoneInfo
|
|
34
35
|
from core.adjustment import normalize_adjustment, adjustment_error
|
|
36
|
+
from tools.foreign_daily import fetch_foreign_daily, foreign_market, SOURCE_URL as FOREIGN_SOURCE_URL
|
|
35
37
|
from tools.baostock_source import SOURCE as BAOSTOCK_SOURCE, SOURCE_URL as BAOSTOCK_SOURCE_URL, eligible_stock_code, fetch_stock_daily
|
|
36
38
|
|
|
37
39
|
try: # Built-in free fallback source; never required for the FTShare path.
|
|
@@ -183,6 +185,10 @@ SYMBOL_DIRECTORY_MAX_ITEMS = 50_000
|
|
|
183
185
|
# HKEX publishes its complete securities master as a small XLSX each trading
|
|
184
186
|
# day. It is a more stable directory source than a quote-page endpoint.
|
|
185
187
|
_HK_DIRECTORY_URL = "https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx"
|
|
188
|
+
_US_DIRECTORY_URLS = (
|
|
189
|
+
"https://www.nasdaqtrader.com/dynamic/SymDir/nasdaqlisted.txt",
|
|
190
|
+
"https://www.nasdaqtrader.com/dynamic/SymDir/otherlisted.txt",
|
|
191
|
+
)
|
|
186
192
|
_HK_DIRECTORY_CATEGORIES = frozenset({"Equity", "Exchange Traded Products", "Real Estate Investment Trusts"})
|
|
187
193
|
CN_BROAD_INDEXES = (
|
|
188
194
|
{"symbol": "000001.XSHG", "name": "上证指数", "market": "CN_INDEX", "aliases": "沪指 上证综指 上证综合指数 shanghai composite"},
|
|
@@ -1023,8 +1029,10 @@ def _classify_ftshare_error(exc: Exception) -> tuple[str, str]:
|
|
|
1023
1029
|
return "auth_required", "FTShare 未收到 API Key,请检查配置后重试。"
|
|
1024
1030
|
if re.search(r"格式|非法|invalid|malformed", raw, re.IGNORECASE):
|
|
1025
1031
|
return "invalid_key", "FTShare API Key 校验失败,请检查 Key 是否完整后重试。"
|
|
1026
|
-
if re.search(r"额度|配额|quota|permission|权限|订阅|套餐|upgrade|plan", safe_raw, re.IGNORECASE):
|
|
1027
|
-
|
|
1032
|
+
if re.search(r"额度|配额|quota|permission|route_not_allowed|权限|订阅|套餐|upgrade|plan", safe_raw, re.IGNORECASE):
|
|
1033
|
+
if not configured_key:
|
|
1034
|
+
return "capability_limited", "FTShare 当前匿名访问无权使用此接口;可配置具备相应权限的 Key,或使用其他数据源。"
|
|
1035
|
+
return "capability_limited", "FTShare 当前凭据或套餐无权访问此项数据,请检查该接口的访问权限。"
|
|
1028
1036
|
return "auth_required", "FTShare API Key 未通过校验,请检查配置或数据权限。"
|
|
1029
1037
|
if status == "429":
|
|
1030
1038
|
return "rate_limited", "FTShare 请求过于频繁,请稍后重试。"
|
|
@@ -1042,6 +1050,8 @@ def _classify_ftshare_error(exc: Exception) -> tuple[str, str]:
|
|
|
1042
1050
|
return "sdk_contract_mismatch", "FTShare SDK 与当前接口契约不一致,请升级插件后重试。"
|
|
1043
1051
|
if status == "405":
|
|
1044
1052
|
return "ftshare_endpoint_unavailable", "FTShare 分钟线校验接口暂不可用,请稍后重试。"
|
|
1053
|
+
if status == "400":
|
|
1054
|
+
return "request_rejected", "FTShare 接口拒绝了请求,请检查标的市场、代码和参数;这不表示 API Key 无效。"
|
|
1045
1055
|
return "ftshare_connection_failed", f"FTShare 连接失败:{safe_raw}"
|
|
1046
1056
|
|
|
1047
1057
|
|
|
@@ -1254,7 +1264,7 @@ def _etf_minute_symbol(symbol: str) -> str:
|
|
|
1254
1264
|
|
|
1255
1265
|
|
|
1256
1266
|
def _bare_us_symbol(symbol: str) -> str:
|
|
1257
|
-
return
|
|
1267
|
+
return _canonical_market_symbol(symbol).removesuffix(".US")
|
|
1258
1268
|
|
|
1259
1269
|
|
|
1260
1270
|
def _aggregate_interval(
|
|
@@ -1891,14 +1901,21 @@ def _directory_items(rows: Any, default_market: str) -> list[dict[str, str]]:
|
|
|
1891
1901
|
|
|
1892
1902
|
|
|
1893
1903
|
def _merge_symbol_directory(*groups: list[dict[str, str]]) -> list[dict[str, str]]:
|
|
1894
|
-
seen:
|
|
1904
|
+
seen: dict[str, dict[str, str]] = {}
|
|
1895
1905
|
merged: list[dict[str, str]] = []
|
|
1896
1906
|
for group in groups:
|
|
1897
1907
|
for item in group:
|
|
1898
1908
|
symbol = str(item.get("symbol") or "").strip()
|
|
1899
|
-
if not symbol
|
|
1909
|
+
if not symbol:
|
|
1910
|
+
continue
|
|
1911
|
+
if symbol in seen:
|
|
1912
|
+
existing = seen[symbol]
|
|
1913
|
+
aliases = " ".join(dict.fromkeys(" ".join([existing.get("aliases", ""),
|
|
1914
|
+
str(item.get("aliases") or "").strip(),
|
|
1915
|
+
str(item.get("name") or "").strip() if item.get("name") != existing["name"] else ""]).split()))
|
|
1916
|
+
if aliases:
|
|
1917
|
+
existing["aliases"] = aliases
|
|
1900
1918
|
continue
|
|
1901
|
-
seen.add(symbol)
|
|
1902
1919
|
normalized = {
|
|
1903
1920
|
"symbol": symbol,
|
|
1904
1921
|
"name": str(item.get("name") or symbol).strip(),
|
|
@@ -1907,6 +1924,7 @@ def _merge_symbol_directory(*groups: list[dict[str, str]]) -> list[dict[str, str
|
|
|
1907
1924
|
aliases = str(item.get("aliases") or "").strip()
|
|
1908
1925
|
if aliases:
|
|
1909
1926
|
normalized["aliases"] = aliases
|
|
1927
|
+
seen[symbol] = normalized
|
|
1910
1928
|
merged.append(normalized)
|
|
1911
1929
|
return sorted(merged, key=lambda item: (item["market"], item["symbol"]))
|
|
1912
1930
|
|
|
@@ -1945,8 +1963,10 @@ def _fetch_hk_symbol_directory() -> list[dict[str, str]]:
|
|
|
1945
1963
|
for attempt in range(3):
|
|
1946
1964
|
try:
|
|
1947
1965
|
request = Request(_HK_DIRECTORY_URL, headers={"User-Agent": "dsh-kline/0.2"})
|
|
1948
|
-
with urlopen(request, timeout=
|
|
1949
|
-
payload = response.read()
|
|
1966
|
+
with urlopen(request, timeout=10) as response: # noqa: S310 - fixed official HTTPS URL above
|
|
1967
|
+
payload = response.read(12_000_001)
|
|
1968
|
+
if len(payload) > 12_000_000:
|
|
1969
|
+
raise ValueError("HKEX securities list exceeds the size limit")
|
|
1950
1970
|
break
|
|
1951
1971
|
except OSError as exc:
|
|
1952
1972
|
last_error = exc
|
|
@@ -1990,6 +2010,36 @@ def _fetch_hk_symbol_directory() -> list[dict[str, str]]:
|
|
|
1990
2010
|
return items
|
|
1991
2011
|
|
|
1992
2012
|
|
|
2013
|
+
def _fetch_public_us_symbol_directory() -> list[dict[str, str]]:
|
|
2014
|
+
"""Read Nasdaq's two official exchange listing files without a market key.
|
|
2015
|
+
|
|
2016
|
+
This is a symbol directory, not a quote source or an entitlement claim.
|
|
2017
|
+
Both files must succeed before the supported listing snapshot is complete.
|
|
2018
|
+
"""
|
|
2019
|
+
groups: list[list[dict[str, str]]] = []
|
|
2020
|
+
for url in _US_DIRECTORY_URLS:
|
|
2021
|
+
request = Request(url, headers={"User-Agent": "dsh-kline/0.6"})
|
|
2022
|
+
with urlopen(request, timeout=10) as response: # noqa: S310 - fixed official HTTPS URLs
|
|
2023
|
+
data = response.read(4_000_001)
|
|
2024
|
+
if len(data) > 4_000_000:
|
|
2025
|
+
raise ValueError("US securities directory exceeds the size limit")
|
|
2026
|
+
reader = csv.DictReader(io.StringIO(data.decode("utf-8-sig")), delimiter="|")
|
|
2027
|
+
symbol_field = "Symbol" if "Symbol" in (reader.fieldnames or []) else "ACT Symbol"
|
|
2028
|
+
if not {symbol_field, "Security Name", "Test Issue"} <= set(reader.fieldnames or []):
|
|
2029
|
+
raise ValueError("US securities directory has unexpected columns")
|
|
2030
|
+
items: list[dict[str, str]] = []
|
|
2031
|
+
for row in reader:
|
|
2032
|
+
code = str(row.get(symbol_field) or "").strip().upper()
|
|
2033
|
+
name = str(row.get("Security Name") or "").strip()
|
|
2034
|
+
if row.get("Test Issue") != "N" or not name or not re.fullmatch(r"[A-Z][A-Z0-9.-]{0,15}", code):
|
|
2035
|
+
continue
|
|
2036
|
+
items.append({"symbol": f"{code}.US", "name": name[:255], "market": "US"})
|
|
2037
|
+
if not items:
|
|
2038
|
+
raise ValueError("US securities directory contained no supported listings")
|
|
2039
|
+
groups.append(items)
|
|
2040
|
+
return _merge_symbol_directory(*groups)
|
|
2041
|
+
|
|
2042
|
+
|
|
1993
2043
|
def _fetch_us_symbol_directory(market: Any) -> list[dict[str, str]]:
|
|
1994
2044
|
"""Page the US directory with pacing instead of triggering a gateway burst."""
|
|
1995
2045
|
method = getattr(market, "eastmoney_us_stock_list", None)
|
|
@@ -2100,22 +2150,27 @@ def register_symbol_directory(
|
|
|
2100
2150
|
|
|
2101
2151
|
|
|
2102
2152
|
def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
2103
|
-
"""
|
|
2153
|
+
"""Refresh a local directory from provider and independent public listings.
|
|
2104
2154
|
|
|
2105
2155
|
The chart app stores this compact name/code directory in localStorage. It is
|
|
2106
|
-
deliberately separate from quotes
|
|
2156
|
+
deliberately separate from quotes and their data-source permissions.
|
|
2107
2157
|
"""
|
|
2108
2158
|
now = int(time.time())
|
|
2109
2159
|
cached = _read_symbol_directory_cache()
|
|
2110
2160
|
cached_expires = int(cached.get("expires_at") or 0) if cached else 0
|
|
2111
|
-
|
|
2161
|
+
public_coverage_complete = cached and all(
|
|
2162
|
+
(cached.get("coverage") or {}).get(market, {}).get("complete") for market in ("HK", "US")
|
|
2163
|
+
)
|
|
2164
|
+
if cached and not force_refresh and cached_expires > now and (
|
|
2165
|
+
cached.get("provider_mode") == "external" or public_coverage_complete
|
|
2166
|
+
):
|
|
2112
2167
|
# Always merge the built-in seed into a cache hit. The seed carries
|
|
2113
2168
|
# curated entries (broad indexes, common ETFs) that provider routes may
|
|
2114
2169
|
# not cover at all, and returning the cached snapshot verbatim meant a
|
|
2115
2170
|
# seed update could not reach clients until the next full refresh.
|
|
2116
2171
|
cached_items = list(cached.get("items") or [])
|
|
2117
2172
|
merged = _merge_symbol_directory(cached_items, [dict(item) for item in _SYMBOL_DIRECTORY_SEED])
|
|
2118
|
-
if
|
|
2173
|
+
if merged != cached_items:
|
|
2119
2174
|
return {
|
|
2120
2175
|
**cached,
|
|
2121
2176
|
"items": merged,
|
|
@@ -2147,26 +2202,14 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2147
2202
|
}
|
|
2148
2203
|
|
|
2149
2204
|
seed = [dict(item) for item in _SYMBOL_DIRECTORY_SEED]
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
"count": len(items),
|
|
2159
|
-
"source": "cache" if cached else "seed",
|
|
2160
|
-
"provider_mode": "builtin" if cached else "seed",
|
|
2161
|
-
"provider_id": "FTShare SDK" if cached else "seed",
|
|
2162
|
-
"coverage": _directory_coverage(items, partial_markets={item["market"] for item in seed}),
|
|
2163
|
-
"stale": True,
|
|
2164
|
-
"refreshed": False,
|
|
2165
|
-
"needs_external_refresh": False,
|
|
2166
|
-
"message": "FTShare unavailable; using the last local symbol directory.",
|
|
2167
|
-
}
|
|
2168
|
-
|
|
2169
|
-
market = _ftshare_market_api(timeout=20)
|
|
2205
|
+
# Public HK/US directories do not depend on the FTShare SDK or a key.
|
|
2206
|
+
market = None
|
|
2207
|
+
client_unavailable = False
|
|
2208
|
+
if ftshare_available():
|
|
2209
|
+
try:
|
|
2210
|
+
market = _ftshare_market_api(timeout=20)
|
|
2211
|
+
except Exception: # SDK initialization must not block public directories.
|
|
2212
|
+
client_unavailable = True
|
|
2170
2213
|
source_specs = (
|
|
2171
2214
|
# The default endpoint page is intentionally small. Request all pages
|
|
2172
2215
|
# so a code-only chart can still be labelled from the local directory
|
|
@@ -2181,7 +2224,7 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2181
2224
|
("etf_description_all", "ETF", {}, True),
|
|
2182
2225
|
)
|
|
2183
2226
|
fetched_groups: list[list[dict[str, str]]] = []
|
|
2184
|
-
errors: list[str] = []
|
|
2227
|
+
errors: list[str] = ["FTShare client unavailable; public directories remain enabled."] if client_unavailable else []
|
|
2185
2228
|
completed_markets: set[str] = set()
|
|
2186
2229
|
for method_name, default_market, kwargs, is_complete in source_specs:
|
|
2187
2230
|
method = getattr(market, method_name, None)
|
|
@@ -2222,7 +2265,12 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2222
2265
|
errors.append(f"hk_directory: {exc}")
|
|
2223
2266
|
|
|
2224
2267
|
try:
|
|
2225
|
-
|
|
2268
|
+
try:
|
|
2269
|
+
us_group = _fetch_public_us_symbol_directory()
|
|
2270
|
+
except Exception as public_error:
|
|
2271
|
+
if market is None:
|
|
2272
|
+
raise public_error
|
|
2273
|
+
us_group = _fetch_us_symbol_directory(market)
|
|
2226
2274
|
if us_group:
|
|
2227
2275
|
fetched_groups.append(us_group)
|
|
2228
2276
|
completed_markets.add("US")
|
|
@@ -2259,9 +2307,9 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2259
2307
|
"generated_at": now,
|
|
2260
2308
|
"expires_at": now + SYMBOL_DIRECTORY_TTL_SECONDS,
|
|
2261
2309
|
"items": items,
|
|
2262
|
-
"source": "ftshare",
|
|
2310
|
+
"source": "ftshare+public_directories",
|
|
2263
2311
|
"provider_mode": "builtin",
|
|
2264
|
-
"provider_id": "FTShare
|
|
2312
|
+
"provider_id": "FTShare and public symbol directories",
|
|
2265
2313
|
"coverage": _directory_coverage(
|
|
2266
2314
|
items,
|
|
2267
2315
|
complete_markets=completed_for_coverage,
|
|
@@ -2289,9 +2337,9 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2289
2337
|
"expires_at": now + SYMBOL_DIRECTORY_RETRY_SECONDS,
|
|
2290
2338
|
"items": merged,
|
|
2291
2339
|
"count": len(merged),
|
|
2292
|
-
"source": "ftshare",
|
|
2340
|
+
"source": "public_directories" if market is None else "ftshare+public_directories",
|
|
2293
2341
|
"provider_mode": "builtin",
|
|
2294
|
-
"provider_id": "FTShare
|
|
2342
|
+
"provider_id": "Public symbol directories" if market is None else "FTShare and public symbol directories",
|
|
2295
2343
|
"coverage": _directory_coverage(
|
|
2296
2344
|
merged,
|
|
2297
2345
|
complete_markets=completed_markets,
|
|
@@ -2322,7 +2370,7 @@ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
|
|
|
2322
2370
|
"stale": True,
|
|
2323
2371
|
"refreshed": False,
|
|
2324
2372
|
"needs_external_refresh": False,
|
|
2325
|
-
"message": "
|
|
2373
|
+
"message": "Directory refresh failed; using cached symbols and the built-in directory.",
|
|
2326
2374
|
}
|
|
2327
2375
|
if errors:
|
|
2328
2376
|
fallback["refresh_errors"] = errors[:3]
|
|
@@ -2981,8 +3029,6 @@ def _fetch_candles_ftshare(
|
|
|
2981
3029
|
market = _ftshare_market_api(timeout=20)
|
|
2982
3030
|
raw: Any = None
|
|
2983
3031
|
fetch_error: Exception | None = None
|
|
2984
|
-
us_daily_history_error: Exception | None = None
|
|
2985
|
-
hk_history_error: Exception | None = None
|
|
2986
3032
|
for attempt in range(2):
|
|
2987
3033
|
try:
|
|
2988
3034
|
if is_etf and normalized_interval != "minute":
|
|
@@ -3025,37 +3071,9 @@ def _fetch_candles_ftshare(
|
|
|
3025
3071
|
limit=lim,
|
|
3026
3072
|
)
|
|
3027
3073
|
elif _is_us_symbol(sym) and normalized_interval != "minute":
|
|
3028
|
-
|
|
3029
|
-
raw = _fetch_us_daily_candles(market, sym, lim)
|
|
3030
|
-
except Exception as exc: # noqa: BLE001
|
|
3031
|
-
# The dedicated US endpoint is preferred when it is healthy,
|
|
3032
|
-
# but it has independently returned 5xx responses in
|
|
3033
|
-
# production. Fall back to the generic history endpoint so
|
|
3034
|
-
# daily 10D/30D/YTD charts do not fail while minute data works.
|
|
3035
|
-
us_daily_history_error = exc
|
|
3036
|
-
raw = _fetch_generic_history(
|
|
3037
|
-
market,
|
|
3038
|
-
symbol=sym,
|
|
3039
|
-
interval=normalized_interval,
|
|
3040
|
-
interval_unit=unit,
|
|
3041
|
-
interval_value=step,
|
|
3042
|
-
adjust_kind="none",
|
|
3043
|
-
limit=lim,
|
|
3044
|
-
)
|
|
3074
|
+
raw = _fetch_us_daily_candles(market, sym, lim)
|
|
3045
3075
|
elif _is_hk_symbol(sym) and normalized_interval in {"day", "week", "month", "quarter", "year"}:
|
|
3046
|
-
|
|
3047
|
-
raw = _fetch_hk_candles(market, sym, normalized_interval, lim, adjust)
|
|
3048
|
-
except Exception as exc: # noqa: BLE001
|
|
3049
|
-
hk_history_error = exc
|
|
3050
|
-
raw = _fetch_generic_history(
|
|
3051
|
-
market,
|
|
3052
|
-
symbol=sym,
|
|
3053
|
-
interval=normalized_interval,
|
|
3054
|
-
interval_unit=unit,
|
|
3055
|
-
interval_value=step,
|
|
3056
|
-
adjust_kind=adj,
|
|
3057
|
-
limit=lim,
|
|
3058
|
-
)
|
|
3076
|
+
raw = _fetch_hk_candles(market, sym, normalized_interval, lim, adjust)
|
|
3059
3077
|
elif normalized_interval == "minute":
|
|
3060
3078
|
# FTShare minute history is restricted to short natural-date
|
|
3061
3079
|
# windows. Page backwards from the latest session close and retain
|
|
@@ -3163,6 +3181,9 @@ def _fetch_candles_ftshare(
|
|
|
3163
3181
|
break
|
|
3164
3182
|
except Exception as exc: # noqa: BLE001
|
|
3165
3183
|
fetch_error = exc
|
|
3184
|
+
code, _ = _classify_ftshare_error(exc)
|
|
3185
|
+
if code in {"auth_required", "invalid_key", "capability_limited", "request_rejected", "rate_limited"}:
|
|
3186
|
+
break
|
|
3166
3187
|
if attempt == 0:
|
|
3167
3188
|
time.sleep(0.35)
|
|
3168
3189
|
if fetch_error is not None:
|
|
@@ -3228,10 +3249,6 @@ def _fetch_candles_ftshare(
|
|
|
3228
3249
|
"market_status": _symbol_market_status(sym),
|
|
3229
3250
|
"transport": _FTSHARE_TRANSPORT_STATE.get(contract_name, {}).get("transport"),
|
|
3230
3251
|
}
|
|
3231
|
-
if hk_history_error is not None:
|
|
3232
|
-
result["warning"] = "FTShare HK history was stale or unavailable; generic candle fallback had insufficient data."
|
|
3233
|
-
result["upstream_error"] = str(hk_history_error)[:500]
|
|
3234
|
-
result["fallback"] = "generic_stock_candlesticks"
|
|
3235
3252
|
return result
|
|
3236
3253
|
name = GLOBAL_INDEX_SOURCES.get(sym) or _symbol_name(market, sym)
|
|
3237
3254
|
freshness = _candle_freshness(sym, rows)
|
|
@@ -3259,19 +3276,11 @@ def _fetch_candles_ftshare(
|
|
|
3259
3276
|
"freshness": freshness["freshness"],
|
|
3260
3277
|
"transport": _FTSHARE_TRANSPORT_STATE.get(contract_name, {}).get("transport", "sdk"),
|
|
3261
3278
|
}
|
|
3262
|
-
if us_daily_history_error is not None:
|
|
3263
|
-
result["warning"] = "FTShare US daily history endpoint failed; used generic candle fallback."
|
|
3264
|
-
result["upstream_error"] = str(us_daily_history_error)[:500]
|
|
3265
|
-
result["fallback"] = "generic_stock_candlesticks"
|
|
3266
3279
|
if _is_us_symbol(sym) and normalized_interval != "minute" and (adjust or "none").strip().lower() != "none":
|
|
3267
3280
|
result["adjust_requested"] = (adjust or "none").strip().lower()
|
|
3268
3281
|
result["warning"] = "FTShare US daily history is returned unadjusted; adjust was not applied."
|
|
3269
3282
|
if is_global_index and adjust != "none":
|
|
3270
3283
|
result.update(adjust_requested=adjust, warning="FTShare global-index history is unadjusted; adjust was not applied.")
|
|
3271
|
-
if hk_history_error is not None:
|
|
3272
|
-
result["warning"] = "FTShare HK history endpoint failed; used generic candle fallback."
|
|
3273
|
-
result["upstream_error"] = str(hk_history_error)[:500]
|
|
3274
|
-
result["fallback"] = "generic_stock_candlesticks"
|
|
3275
3284
|
if normalized_interval == "minute":
|
|
3276
3285
|
sessions_seen = sorted({str(row.get("session") or "") for row in rows if row.get("session")})
|
|
3277
3286
|
result["timestamp_semantics"] = "time is bar close in Unix seconds; open_time is present only when supplied by FTShare."
|
|
@@ -3423,6 +3432,41 @@ def _free_stock_candles_result(
|
|
|
3423
3432
|
}
|
|
3424
3433
|
|
|
3425
3434
|
|
|
3435
|
+
def _free_foreign_candles_result(
|
|
3436
|
+
symbol: str, *, interval: str, interval_value: int, limit: int, adjust: str,
|
|
3437
|
+
after_ftshare_failure: bool = False,
|
|
3438
|
+
) -> dict[str, Any] | None:
|
|
3439
|
+
sym = _canonical_market_symbol(symbol)
|
|
3440
|
+
if foreign_market(sym) is None or str(interval).lower() != "day" or int(interval_value or 1) != 1:
|
|
3441
|
+
return None
|
|
3442
|
+
requested = max(2, min(int(limit or 220), 4000))
|
|
3443
|
+
try:
|
|
3444
|
+
history = fetch_foreign_daily(sym, limit=requested, adjust=adjust)
|
|
3445
|
+
except Exception: # Optional public source must never mask the primary error.
|
|
3446
|
+
history = None
|
|
3447
|
+
if not history:
|
|
3448
|
+
return None
|
|
3449
|
+
rows = history["rows"]
|
|
3450
|
+
freshness = _candle_freshness(sym, rows)
|
|
3451
|
+
local_zone = ZoneInfo(history.get("exchange_timezone") or _exchange_timezone(sym))
|
|
3452
|
+
if (datetime.now(local_zone).date() - datetime.fromtimestamp(rows[-1]["time"], local_zone).date()).days > 5:
|
|
3453
|
+
freshness.update(status="stale", freshness="historical_daily_stale")
|
|
3454
|
+
warning = [] if history["history_complete"] else [
|
|
3455
|
+
f"免费日 K 请求 {requested} 根,实际获得 {len(rows)} 根;历史覆盖受公开源限制({history['coverage_reason']})。"
|
|
3456
|
+
]
|
|
3457
|
+
return {
|
|
3458
|
+
**history, "ok": True, "symbol": sym,
|
|
3459
|
+
"name": next((str(item["name"]) for item in _SYMBOL_DIRECTORY_SEED if item["symbol"] == sym), sym),
|
|
3460
|
+
"interval": "day", "interval_value": 1, "session_count": None, "adjust": adjust,
|
|
3461
|
+
"count": len(rows), "requested_count": requested, "source": "tencent_free",
|
|
3462
|
+
"source_url": FOREIGN_SOURCE_URL, "updated_at": int(time.time()),
|
|
3463
|
+
**freshness, "market_status": _symbol_market_status(sym),
|
|
3464
|
+
"notice": "腾讯免费日 K;成交量为历史当日股数,复权仅作用于价格。分钟 K、新闻和板块排行不在此备用源范围。",
|
|
3465
|
+
"warnings": warning,
|
|
3466
|
+
**({"fallback_from": "ftshare"} if after_ftshare_failure else {}),
|
|
3467
|
+
}
|
|
3468
|
+
|
|
3469
|
+
|
|
3426
3470
|
def fetch_candles(
|
|
3427
3471
|
symbol: str,
|
|
3428
3472
|
*,
|
|
@@ -3450,6 +3494,9 @@ def fetch_candles(
|
|
|
3450
3494
|
and int(interval_value or 1) == 1
|
|
3451
3495
|
)
|
|
3452
3496
|
if not key_configured:
|
|
3497
|
+
free_foreign = _free_foreign_candles_result(symbol, **stock_options)
|
|
3498
|
+
if free_foreign is not None:
|
|
3499
|
+
return {**free_foreign, "ftshare_key_configured": False}
|
|
3453
3500
|
free_stock = _free_stock_candles_result(symbol, **stock_options)
|
|
3454
3501
|
if free_stock is not None:
|
|
3455
3502
|
return free_stock
|
|
@@ -3516,6 +3563,14 @@ def fetch_candles(
|
|
|
3516
3563
|
free_stock = _free_stock_candles_result(symbol, **stock_options, after_ftshare_failure=True)
|
|
3517
3564
|
if free_stock is not None:
|
|
3518
3565
|
return free_stock
|
|
3566
|
+
if key_configured:
|
|
3567
|
+
free_foreign = _free_foreign_candles_result(symbol, **stock_options, after_ftshare_failure=True)
|
|
3568
|
+
if free_foreign is not None:
|
|
3569
|
+
return {**free_foreign, "ftshare_key_configured": True}
|
|
3570
|
+
if foreign_market(_canonical_market_symbol(symbol)) == "US" and adjust == "backward":
|
|
3571
|
+
limitation = "美股免费日 K 仅支持不复权和前复权;未将不复权冒充后复权。"
|
|
3572
|
+
primary = {**primary, "free_fallback_limitation": limitation,
|
|
3573
|
+
"message": str(primary.get("message") or "") + " " + limitation}
|
|
3519
3574
|
return primary
|
|
3520
3575
|
|
|
3521
3576
|
|
|
@@ -3860,14 +3915,18 @@ def _read_intelligence_section(
|
|
|
3860
3915
|
|
|
3861
3916
|
def _provider_unavailable_intelligence(kind: str, *, symbol: str = "") -> dict[str, Any]:
|
|
3862
3917
|
sections = ("breadth", "flows", "sectors", "concepts", "rankings", "events") if kind == "market_pulse" else ("sector", "flows", "events")
|
|
3918
|
+
key_configured = _ftshare_credential_source() != "none"
|
|
3863
3919
|
result = {
|
|
3864
3920
|
"ok": True,
|
|
3865
3921
|
"source": {"name": "FTShare", "status": "unavailable"},
|
|
3866
3922
|
"sections": {section: {"state": "unsupported", "errors": []} for section in sections},
|
|
3923
|
+
"ftshare_key_configured": key_configured,
|
|
3924
|
+
"unavailable_reason": "key_not_configured" if not key_configured else "provider_unavailable",
|
|
3867
3925
|
}
|
|
3868
3926
|
if symbol:
|
|
3869
3927
|
result["symbol"] = symbol
|
|
3870
|
-
result[kind] = {"message": "FTShare
|
|
3928
|
+
result[kind] = {"message": "This section needs an FTShare key with access to its endpoint; search and supported key-less candles are independent."
|
|
3929
|
+
if not key_configured else "The FTShare provider is unavailable in this runtime."}
|
|
3871
3930
|
return result
|
|
3872
3931
|
|
|
3873
3932
|
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Bounded, keyless Tencent HK/US daily history; no FTShare or A-share routes.
|
|
2
|
+
|
|
3
|
+
Prices are vendor-adjusted; volumes remain historical session shares, including
|
|
4
|
+
across splits. A day is anchored at 16:00 exchange time (not an execution tick).
|
|
5
|
+
See docs/free-foreign-daily.md for the verified contract and coverage limits.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from datetime import datetime, timedelta
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urlencode
|
|
17
|
+
from urllib.request import Request, urlopen
|
|
18
|
+
from zoneinfo import ZoneInfo
|
|
19
|
+
|
|
20
|
+
from tools.free_sources import _cache_get, _cache_set
|
|
21
|
+
|
|
22
|
+
SOURCE_URL = "https://gu.qq.com/"
|
|
23
|
+
_BASE = "https://web.ifzq.gtimg.cn/appstock/app/"
|
|
24
|
+
_PAGE_SIZE = 640
|
|
25
|
+
_MAX_PAGES = 8
|
|
26
|
+
_MAX_BYTES = 2_000_000
|
|
27
|
+
_TIMEOUT = 6
|
|
28
|
+
_AGENT = "Mozilla/5.0 FT-KLine/0.6"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def foreign_market(symbol: str) -> str | None:
|
|
32
|
+
if re.fullmatch(r"\d{5}\.HK", symbol):
|
|
33
|
+
return "HK"
|
|
34
|
+
if re.fullmatch(r"[A-Z][A-Z0-9]*(?:[.-][A-Z0-9]+)*\.US", symbol) and len(symbol) <= 28:
|
|
35
|
+
return "US"
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _read(url: str, *, text: bool = False) -> Any:
|
|
40
|
+
try:
|
|
41
|
+
request = Request(url, headers={"User-Agent": _AGENT, "Referer": SOURCE_URL})
|
|
42
|
+
with urlopen(request, timeout=_TIMEOUT) as response:
|
|
43
|
+
raw = response.read(_MAX_BYTES + 1)
|
|
44
|
+
if len(raw) > _MAX_BYTES:
|
|
45
|
+
return None
|
|
46
|
+
return raw.decode("gbk") if text else json.loads(raw.decode("utf-8"))
|
|
47
|
+
except Exception: # Public fallback failure must not break the primary provider.
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _us_code(root: str) -> str | None:
|
|
52
|
+
key = ("tencent_us_identity", root)
|
|
53
|
+
cached = _cache_get(key)
|
|
54
|
+
if cached:
|
|
55
|
+
return cached
|
|
56
|
+
# The quote supplies only an identifier, never a URL or executable input.
|
|
57
|
+
quote = _read("https://qt.gtimg.cn/q=" + "us" + root, text=True)
|
|
58
|
+
if not isinstance(quote, str):
|
|
59
|
+
return None
|
|
60
|
+
lines = re.findall(r'v_us[A-Za-z0-9_.-]+="([^"\r\n]*)";', quote)
|
|
61
|
+
if len(lines) != 1:
|
|
62
|
+
return None
|
|
63
|
+
fields = lines[0].split("~")
|
|
64
|
+
identity = fields[2] if len(fields) > 2 else ""
|
|
65
|
+
if identity not in {root + suffix for suffix in (".OQ", ".N", ".AM")}:
|
|
66
|
+
return None
|
|
67
|
+
code = "us" + identity
|
|
68
|
+
_cache_set(key, code)
|
|
69
|
+
return code
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _parse_page(payload: Any, code: str, series: str, zone: ZoneInfo, now: datetime,
|
|
73
|
+
allow_negative: bool) -> tuple[list[dict], str | None] | None:
|
|
74
|
+
if not isinstance(payload, dict) or payload.get("code") != 0:
|
|
75
|
+
return None
|
|
76
|
+
data = payload.get("data")
|
|
77
|
+
node = data.get(code) if isinstance(data, dict) else None
|
|
78
|
+
bars = node.get(series) if isinstance(node, dict) else None
|
|
79
|
+
if not isinstance(bars, list) or len(bars) > _PAGE_SIZE + 1:
|
|
80
|
+
return None
|
|
81
|
+
rows = []
|
|
82
|
+
reason = None
|
|
83
|
+
previous = ""
|
|
84
|
+
for bar in bars:
|
|
85
|
+
try:
|
|
86
|
+
if not isinstance(bar, list) or len(bar) < 6:
|
|
87
|
+
return None
|
|
88
|
+
day = datetime.strptime(bar[0], "%Y-%m-%d")
|
|
89
|
+
if day.strftime("%Y-%m-%d") != bar[0] or bar[0] <= previous:
|
|
90
|
+
return None
|
|
91
|
+
previous = bar[0]
|
|
92
|
+
o, c, h, l, volume = map(float, bar[1:6])
|
|
93
|
+
if not all(math.isfinite(x) for x in (o, c, h, l, volume)) or volume < 0:
|
|
94
|
+
return None
|
|
95
|
+
if l > min(o, c) or h < max(o, c) or l > h:
|
|
96
|
+
return None
|
|
97
|
+
if min(o, c, h, l) <= 0:
|
|
98
|
+
if not allow_negative:
|
|
99
|
+
return None
|
|
100
|
+
# Cumulative cash adjustments can make early HK qfq negative.
|
|
101
|
+
# Keep only the contiguous newer positive-price tail, never
|
|
102
|
+
# delete an interior invalid row and silently bridge a gap.
|
|
103
|
+
rows.clear()
|
|
104
|
+
reason = "non_positive_adjusted_prices"
|
|
105
|
+
continue
|
|
106
|
+
close = day.replace(hour=16, tzinfo=zone)
|
|
107
|
+
cutoff = close + (timedelta(minutes=15) if zone.key == "Asia/Hong_Kong" else timedelta())
|
|
108
|
+
if cutoff > now:
|
|
109
|
+
continue # Do not expose an unfinished daily candle as final.
|
|
110
|
+
rows.append({"time": int(close.timestamp()), "open": o, "close": c,
|
|
111
|
+
"high": h, "low": l, "volume": volume})
|
|
112
|
+
except (TypeError, ValueError, OverflowError):
|
|
113
|
+
return None
|
|
114
|
+
return rows, reason
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def fetch_foreign_daily(symbol: str, *, limit: int = 220, adjust: str = "none") -> dict | None:
|
|
118
|
+
market = foreign_market(symbol)
|
|
119
|
+
if market is None or adjust not in {"none", "forward", "backward"}:
|
|
120
|
+
return None
|
|
121
|
+
if market == "US" and adjust == "backward":
|
|
122
|
+
return None
|
|
123
|
+
wanted = max(2, min(int(limit), 4000))
|
|
124
|
+
key = ("tencent_foreign_daily", f"{symbol}:{wanted}:{adjust}")
|
|
125
|
+
cached = _cache_get(key)
|
|
126
|
+
if cached is not None:
|
|
127
|
+
return deepcopy(cached)
|
|
128
|
+
code = "hk" + symbol[:5] if market == "HK" else _us_code(symbol[:-3])
|
|
129
|
+
if not code:
|
|
130
|
+
return None
|
|
131
|
+
mode, series = {"none": ("", "day"), "forward": ("qfq", "qfqday"),
|
|
132
|
+
"backward": ("hfq", "hfqday")}[adjust]
|
|
133
|
+
route = "kline/kline" if not mode else ("hkfqkline/get" if market == "HK" else "usfqkline/get")
|
|
134
|
+
zone = ZoneInfo("Asia/Hong_Kong" if market == "HK" else "America/New_York")
|
|
135
|
+
now = datetime.now(zone)
|
|
136
|
+
end = ""
|
|
137
|
+
collected: dict[int, dict] = {}
|
|
138
|
+
reason = "page_limit"
|
|
139
|
+
pages = 0
|
|
140
|
+
for _ in range(_MAX_PAGES):
|
|
141
|
+
# Each older page overlaps the preceding boundary. Verify that prices
|
|
142
|
+
# and share counts use the same basis before joining the two pages.
|
|
143
|
+
count = min(_PAGE_SIZE, max(3, wanted - len(collected) + 2))
|
|
144
|
+
url = _BASE + route + "?" + urlencode({"param": f"{code},day,,{end},{count},{mode}"})
|
|
145
|
+
parsed = _parse_page(_read(url), code, series, zone, now, adjust == "forward")
|
|
146
|
+
pages += 1
|
|
147
|
+
if parsed is None:
|
|
148
|
+
reason = "source_unavailable_or_invalid"
|
|
149
|
+
break
|
|
150
|
+
rows, boundary = parsed
|
|
151
|
+
if not rows:
|
|
152
|
+
reason = boundary or "source_history_exhausted"
|
|
153
|
+
break
|
|
154
|
+
if end and datetime.fromtimestamp(rows[-1]["time"], zone).date().isoformat() > end:
|
|
155
|
+
reason = "source_ignored_history_boundary"
|
|
156
|
+
break
|
|
157
|
+
if collected and min(collected) not in {row["time"] for row in rows}:
|
|
158
|
+
reason = "missing_page_overlap"
|
|
159
|
+
break
|
|
160
|
+
if any(stamp in collected and collected[stamp] != row for stamp, row in ((r["time"], r) for r in rows)):
|
|
161
|
+
reason = "inconsistent_page_basis"
|
|
162
|
+
break
|
|
163
|
+
oldest = min(collected) if collected else None
|
|
164
|
+
if oldest is not None and rows[0]["time"] >= oldest:
|
|
165
|
+
reason = "source_history_exhausted"
|
|
166
|
+
break
|
|
167
|
+
collected.update((row["time"], row) for row in rows)
|
|
168
|
+
if len(collected) >= wanted:
|
|
169
|
+
reason = "requested_count_reached"
|
|
170
|
+
break
|
|
171
|
+
if boundary:
|
|
172
|
+
reason = boundary
|
|
173
|
+
break
|
|
174
|
+
end = datetime.fromtimestamp(rows[0]["time"], zone).date().isoformat()
|
|
175
|
+
rows = sorted(collected.values(), key=lambda row: row["time"])[-wanted:]
|
|
176
|
+
if len(rows) < 2:
|
|
177
|
+
return None
|
|
178
|
+
result = {"rows": rows, "history_complete": len(rows) >= wanted,
|
|
179
|
+
"history_start": rows[0]["time"], "history_end": rows[-1]["time"],
|
|
180
|
+
"coverage_reason": reason, "history_pages": pages,
|
|
181
|
+
"volume_unit": "shares", "volume_adjustment": "historical_session_shares",
|
|
182
|
+
"price_adjustment": adjust, "timestamp_convention": "session_date_at_16_local",
|
|
183
|
+
"source_symbol": code, "exchange_timezone": zone.key}
|
|
184
|
+
_cache_set(key, deepcopy(result))
|
|
185
|
+
return result
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dsh-ft/dsh-fft-paper-trading",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "A-share and commodity futures paper trading for DeepSeek Harness: local ledger, batch orders, review, and FTShare quotes.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@dsh-ft/dsh-fft-settings": "^0.5.0",
|
|
53
53
|
"@dsh-ft/dsh-fft-ftshare": "^0.4.0",
|
|
54
|
-
"@ftshare-lab/dsh-kline": "0.6.
|
|
54
|
+
"@ftshare-lab/dsh-kline": ">=0.6.7"
|
|
55
55
|
},
|
|
56
56
|
"bundledDependencies": [
|
|
57
57
|
"@ftshare-lab/dsh-kline"
|