@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10

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.
Files changed (203) hide show
  1. package/CHANGELOG.md +601 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +116 -0
  5. package/README.md +115 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +43 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.2.md +31 -0
  50. package/docs/release-acceptance-v0.6.3.md +25 -0
  51. package/docs/release-acceptance-v0.6.4.md +24 -0
  52. package/docs/release-acceptance-v0.6.5.md +21 -0
  53. package/docs/release-acceptance-v0.6.6.md +21 -0
  54. package/docs/release-acceptance-v0.6.7.md +18 -0
  55. package/docs/release-acceptance-v0.6.8.md +18 -0
  56. package/docs/release-acceptance-v0.6.9.md +98 -0
  57. package/docs/release-notes-v0.5.0.md +23 -0
  58. package/docs/release-notes-v0.6.0.md +11 -0
  59. package/docs/release-notes-v0.6.1.md +20 -0
  60. package/docs/release-notes-v0.6.10.md +11 -0
  61. package/docs/release-notes-v0.6.2.md +14 -0
  62. package/docs/release-notes-v0.6.3.md +26 -0
  63. package/docs/release-notes-v0.6.4.md +12 -0
  64. package/docs/release-notes-v0.6.5.md +13 -0
  65. package/docs/release-notes-v0.6.6.md +13 -0
  66. package/docs/release-notes-v0.6.7.md +17 -0
  67. package/docs/release-notes-v0.6.8.md +10 -0
  68. package/docs/release-notes-v0.6.9.md +16 -0
  69. package/lib/candle-sequence.js +15 -0
  70. package/lib/chart-adjustment.js +7 -0
  71. package/lib/chart-annotations.js +33 -0
  72. package/lib/chart-applications.js +171 -0
  73. package/lib/chart-context.js +164 -0
  74. package/lib/chart-observation.js +251 -0
  75. package/lib/chart-service-status.js +82 -0
  76. package/lib/chart-source-status.js +39 -0
  77. package/lib/chart-sources.js +354 -0
  78. package/lib/client/BetterSidebarTab.js +70 -0
  79. package/lib/client/ClassicShell.js +254 -0
  80. package/lib/client/KlineContent.js +155 -0
  81. package/lib/client/chart-apply.js +73 -0
  82. package/lib/client/chart-context.js +233 -0
  83. package/lib/client/chart-handoff.js +34 -0
  84. package/lib/client/chart-session-resolver.js +74 -0
  85. package/lib/client/client-context.js +1 -0
  86. package/lib/client/conversation.js +88 -0
  87. package/lib/client/default-tab.js +83 -0
  88. package/lib/client/embed.js +50 -0
  89. package/lib/client/generated-view.js +12983 -0
  90. package/lib/client/horizontal-lines.js +19 -0
  91. package/lib/client/index.js +62 -0
  92. package/lib/client/mode-preferences.js +28 -0
  93. package/lib/client/native-sidebar-contract.js +45 -0
  94. package/lib/client/native-sidebar-register.js +133 -0
  95. package/lib/client/native-sidebar-services.js +1 -0
  96. package/lib/client/native-sidebar.js +96 -0
  97. package/lib/client/sidebar-integration.js +93 -0
  98. package/lib/client/ui-onboarding.js +42 -0
  99. package/lib/client/version.js +14 -0
  100. package/lib/client.js +17382 -0
  101. package/lib/client.js.map +1 -0
  102. package/lib/drawing-feedback.js +284 -0
  103. package/lib/fibonacci.js +18 -0
  104. package/lib/ftshare-settings-bridge.js +159 -0
  105. package/lib/index.js +279 -0
  106. package/lib/labeled-polyline.js +17 -0
  107. package/lib/pattern-groups.js +91 -0
  108. package/lib/price-bands.js +55 -0
  109. package/lib/price-series.js +47 -0
  110. package/lib/price-sticks.js +32 -0
  111. package/lib/types/candle-sequence.d.ts +2 -0
  112. package/lib/types/chart-adjustment.d.ts +2 -0
  113. package/lib/types/chart-annotations.d.ts +4 -0
  114. package/lib/types/chart-applications.d.ts +26 -0
  115. package/lib/types/chart-context.d.ts +14 -0
  116. package/lib/types/chart-observation.d.ts +8 -0
  117. package/lib/types/chart-service-status.d.ts +22 -0
  118. package/lib/types/chart-source-status.d.ts +47 -0
  119. package/lib/types/chart-sources.d.ts +25 -0
  120. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  121. package/lib/types/client/ClassicShell.d.ts +4 -0
  122. package/lib/types/client/KlineContent.d.ts +37 -0
  123. package/lib/types/client/chart-apply.d.ts +13 -0
  124. package/lib/types/client/chart-context.d.ts +23 -0
  125. package/lib/types/client/chart-handoff.d.ts +5 -0
  126. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  127. package/lib/types/client/client-context.d.ts +14 -0
  128. package/lib/types/client/conversation.d.ts +43 -0
  129. package/lib/types/client/default-tab.d.ts +3 -0
  130. package/lib/types/client/embed.d.ts +37 -0
  131. package/lib/types/client/generated-view.d.ts +2 -0
  132. package/lib/types/client/horizontal-lines.d.ts +1 -0
  133. package/lib/types/client/index.d.ts +4 -0
  134. package/lib/types/client/mode-preferences.d.ts +13 -0
  135. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  136. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  137. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  138. package/lib/types/client/native-sidebar.d.ts +47 -0
  139. package/lib/types/client/sidebar-integration.d.ts +12 -0
  140. package/lib/types/client/ui-onboarding.d.ts +6 -0
  141. package/lib/types/client/version.d.ts +1 -0
  142. package/lib/types/drawing-feedback.d.ts +5 -0
  143. package/lib/types/fibonacci.d.ts +5 -0
  144. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  145. package/lib/types/index.d.ts +26 -0
  146. package/lib/types/labeled-polyline.d.ts +11 -0
  147. package/lib/types/pattern-groups.d.ts +2 -0
  148. package/lib/types/price-bands.d.ts +3 -0
  149. package/lib/types/price-series.d.ts +5 -0
  150. package/lib/types/price-sticks.d.ts +3 -0
  151. package/package.json +153 -4
  152. package/requirements.txt +6 -0
  153. package/screenshots.json +11 -0
  154. package/scripts/bootstrap.sh +5 -0
  155. package/scripts/dsh-bootstrap.mjs +179 -0
  156. package/scripts/dsh-mcp-plugin.mjs +27 -0
  157. package/scripts/run-dsh-kline.mjs +658 -0
  158. package/scripts/run-dsh-kline.sh +5 -0
  159. package/server.py +1755 -0
  160. package/tools/__init__.py +0 -0
  161. package/tools/annotations.py +119 -0
  162. package/tools/automatic_analysis.py +158 -0
  163. package/tools/baostock_source.py +176 -0
  164. package/tools/calc.py +39 -0
  165. package/tools/channel_candidates.py +260 -0
  166. package/tools/channel_preview.py +82 -0
  167. package/tools/channels.py +104 -0
  168. package/tools/chart_applications.py +204 -0
  169. package/tools/chart_context.py +186 -0
  170. package/tools/chart_edits.py +363 -0
  171. package/tools/chart_functions.py +451 -0
  172. package/tools/chart_indicators.py +65 -0
  173. package/tools/chart_measurements.py +84 -0
  174. package/tools/chart_source_status.py +32 -0
  175. package/tools/chart_sources.py +31 -0
  176. package/tools/closed_daily.py +68 -0
  177. package/tools/draw.py +410 -0
  178. package/tools/drawing_feedback.py +45 -0
  179. package/tools/drawing_interaction.py +117 -0
  180. package/tools/drawing_verification.py +141 -0
  181. package/tools/fetch.py +4680 -0
  182. package/tools/fibonacci.py +83 -0
  183. package/tools/foreign_daily.py +185 -0
  184. package/tools/free_sources.py +483 -0
  185. package/tools/lines.py +91 -0
  186. package/tools/nine_count.py +66 -0
  187. package/tools/pattern_groups.py +103 -0
  188. package/tools/pivots.py +60 -0
  189. package/tools/polylines.py +131 -0
  190. package/tools/price_bands.py +165 -0
  191. package/tools/price_patterns.py +311 -0
  192. package/tools/price_series.py +162 -0
  193. package/tools/price_sticks.py +114 -0
  194. package/tools/range_candidates.py +170 -0
  195. package/tools/recent_drawing_candidates.py +123 -0
  196. package/tools/rectangles.py +76 -0
  197. package/tools/regression_channels.py +87 -0
  198. package/tools/ta_functions.py +228 -0
  199. package/tools/trend_lines.py +106 -0
  200. package/tools/watchlist.py +149 -0
  201. package/view/ft-logo.jpg +0 -0
  202. package/view/kline.html +12436 -0
  203. package/view/vendor/klinecharts.min.js +7 -0
package/tools/fetch.py ADDED
@@ -0,0 +1,4680 @@
1
+ """Optional ftshare-backed candle fetch.
2
+
3
+ ftshare is an *optional* dependency:
4
+ - installed → fetch_candles works
5
+ - missing → returns structured error `ftshare_not_installed`
6
+
7
+ Discovery order:
8
+ 1. already importable ``ftshare`` from the active Python environment
9
+ 2. optional ``FTSHARE_SDK_SRC`` env pointing to a package checkout
10
+
11
+ This module never searches for or imports another MCP repository.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import csv
18
+ import json
19
+ import io
20
+ import re
21
+ import sys
22
+ import stat
23
+ import tempfile
24
+ import threading
25
+ import time
26
+ import zipfile
27
+ from copy import deepcopy
28
+ from datetime import datetime, time as clock_time, timedelta, timezone
29
+ from importlib.metadata import PackageNotFoundError, version as distribution_version
30
+ from pathlib import Path
31
+ from typing import Any, Mapping, Sequence
32
+ from urllib.request import Request, urlopen
33
+ from xml.etree import ElementTree
34
+ from zoneinfo import ZoneInfo
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
37
+ from tools.baostock_source import SOURCE as BAOSTOCK_SOURCE, SOURCE_URL as BAOSTOCK_SOURCE_URL, eligible_stock_code, fetch_stock_daily
38
+
39
+ try: # Built-in free fallback source; never required for the FTShare path.
40
+ from tools.free_sources import (
41
+ EM_INDEX_NAMES,
42
+ SOURCE_LABEL,
43
+ SOURCE_URL,
44
+ TENCENT_LABEL,
45
+ TENCENT_SOURCE_URL,
46
+ fetch_em_index_daily,
47
+ fetch_tencent_index_daily,
48
+ fetch_tencent_stock_daily,
49
+ fetch_tencent_ticker_items,
50
+ )
51
+ except Exception: # noqa: BLE001 - degrade to FTShare-only when the module is missing
52
+ EM_INDEX_NAMES = {}
53
+ SOURCE_LABEL = ""
54
+ SOURCE_URL = ""
55
+ TENCENT_LABEL = ""
56
+ TENCENT_SOURCE_URL = ""
57
+ fetch_em_index_daily = None
58
+ fetch_tencent_index_daily = None
59
+ fetch_tencent_stock_daily = None
60
+ fetch_tencent_ticker_items = None
61
+
62
+
63
+ _SYMBOL_SEARCH_CACHE_TTL_SECONDS = 300.0
64
+ _SYMBOL_SEARCH_CACHE_MAX_ENTRIES = 96
65
+ _symbol_search_cache: dict[tuple[str, int], tuple[float, dict[str, Any]]] = {}
66
+ _SECURITY_WORKSPACE_CACHE_TTL_SECONDS = 300.0
67
+ _security_workspace_cache: dict[str, tuple[float, dict[str, Any]]] = {}
68
+ _MARKET_PULSE_CACHE_TTL_SECONDS = 90.0
69
+ _MARKET_PULSE_SECTION_TTL_SECONDS = 90.0
70
+ _market_pulse_cache: tuple[float, dict[str, Any]] | None = None
71
+ # The market workspace deliberately loads sections in several independent
72
+ # requests so one slow endpoint cannot block the others. A single whole-pulse
73
+ # cache entry cannot serve those partial requests, so without a per-section
74
+ # cache every panel switch, tab revisit and manual refresh re-ran the same
75
+ # upstream calls. Keeping one short-lived entry per section makes the split
76
+ # requests cheap while preserving the per-section response shape.
77
+ _market_pulse_section_cache: dict[str, tuple[float, dict[str, Any]]] = {}
78
+ _MARKET_PULSE_SECTIONS = frozenset({"breadth", "flows", "sectors", "concepts", "rankings", "events"})
79
+ # Coalesce concurrent identical requests. The client issues an initial batch,
80
+ # a conditional full fallback and then per-group follow-ups; without this a
81
+ # refresh can run the same upstream call several times at once, which is what
82
+ # produced both the stalls and the intermittent rate-limit failures.
83
+ _market_pulse_section_inflight: dict[str, threading.Lock] = {}
84
+ _market_pulse_inflight_guard = threading.Lock()
85
+ # Index feeds are independently flaky. Keep the last valid snapshot for each
86
+ # named index so one failed endpoint cannot make a stable market grid lose a
87
+ # card on the next refresh. A cached value is explicitly marked stale below.
88
+ _MARKET_TICKER_STALE_TTL_SECONDS = 6 * 60 * 60
89
+ _market_ticker_last_good: dict[str, tuple[float, dict[str, Any]]] = {}
90
+ _market_ticker_cache_lock = threading.Lock()
91
+ # Symbol-name resolution is a presentation-only lookup, but every cache miss is
92
+ # a live provider round trip and market lists repeat symbols heavily across
93
+ # renders; memoize both hits and misses for the life of the process.
94
+ _SYMBOL_NAME_CACHE_MAX_ENTRIES = 512
95
+ _symbol_name_cache: dict[str, str] = {}
96
+ _SECURITY_INTELLIGENCE_CACHE_TTL_SECONDS = 180.0
97
+ _security_intelligence_cache: dict[str, tuple[float, dict[str, Any]]] = {}
98
+ # A short hot cache serves a search-result prefetch immediately when the user
99
+ # opens the same symbol. It is deliberately much shorter than the stale
100
+ # fallback cache below: this is a latency optimization, not an availability
101
+ # substitute for live provider data.
102
+ _CANDLE_CACHE_FRESH_SECONDS = 45.0
103
+ _CANDLE_CACHE_TTL_SECONDS = 15 * 60.0
104
+ _candle_cache: dict[tuple[str, str, int, int, int, str, str], tuple[float, dict[str, Any]]] = {}
105
+ _LAST_FTSHARE_CAPABILITIES: dict[str, str] = {}
106
+ _FTSHARE_TRANSPORT_STATE: dict[str, dict[str, Any]] = {}
107
+
108
+ # This is deliberately a small, explicit registry rather than a runtime
109
+ # discovery mechanism. Only paths verified against the FTShare gateway docs
110
+ # are candidates for automatic fallback; an upstream response can never add a
111
+ # new URL or execute code in this process.
112
+ FT_CONTRACTS: dict[str, dict[str, Any]] = {
113
+ "daily_candles": {
114
+ "doc": "https://market.ft.tech/gateway/doc/p/owq0364i",
115
+ "tier": "free",
116
+ "verified_sdk_version": "1.0.7",
117
+ "candidates": ["http_get", "sdk"],
118
+ "candidate_verification": {"http_get": True, "sdk": True},
119
+ },
120
+ "history_minute_candles": {
121
+ "doc": "https://market.ft.tech/gateway/doc/p/z9lsvrvu",
122
+ "tier": "base+",
123
+ "verified_sdk_version": "1.0.7",
124
+ "candidates": ["http_get", "sdk"],
125
+ "candidate_verification": {"http_get": False, "sdk": False},
126
+ },
127
+ # v4 is a realtime *stock* minute feed. It is intentionally a separate
128
+ # contract from v2 history: v4 has no verified index/ETF equivalent and
129
+ # does not accept a historical date window. The chart uses it for the
130
+ # latest complete A-share session, then pages v2 for older sessions.
131
+ "realtime_minute_candles": {
132
+ "doc": "https://market.ft.tech/gateway/api/v4/market/data/stock-realtime-minute-kline",
133
+ "tier": "api-key",
134
+ "verified_sdk_version": "1.0.7",
135
+ "candidates": ["sdk"],
136
+ "candidate_verification": {"sdk": True},
137
+ },
138
+ "index_daily_candles": {
139
+ "doc": "https://market.ft.tech/gateway/doc/p/gr2q0bjx",
140
+ "tier": "free",
141
+ "verified_sdk_version": "1.0.7",
142
+ "candidates": ["sdk"],
143
+ "candidate_verification": {"sdk": True},
144
+ },
145
+ "index_history_minute_candles": {
146
+ "doc": "https://market.ft.tech/gateway/doc/p/ls85mq5n",
147
+ "tier": "base+",
148
+ "verified_sdk_version": "1.0.7",
149
+ "candidates": ["sdk"],
150
+ "candidate_verification": {"sdk": False},
151
+ },
152
+ # 全球指数日K线(FTShare 免费版套餐内含,覆盖 100.HSI/100.NDX 等)。
153
+ # 该端点只回日K,周/月/季/年在 fetch.py 本地聚合。
154
+ "global_index_daily": {
155
+ "doc": "https://market.ft.tech/gateway/doc/p/pb8eizu3",
156
+ "tier": "free",
157
+ "verified_sdk_version": "1.0.7",
158
+ "candidates": ["sdk"],
159
+ "candidate_verification": {"sdk": True},
160
+ },
161
+ # ETF uses its own documented endpoints. It is intentionally kept
162
+ # separate from stock history: an ETF is a tradable instrument, but not a
163
+ # company and must never be routed through company-information APIs.
164
+ "etf_candles": {
165
+ "doc": "https://market.ft.tech/gateway/doc/p/etf-candlesticks",
166
+ "tier": "free",
167
+ "verified_sdk_version": "1.0.7",
168
+ "candidates": ["sdk"],
169
+ "candidate_verification": {"sdk": True},
170
+ },
171
+ "etf_minutes": {
172
+ "doc": "https://market.ft.tech/gateway/doc/p/etf-minutes",
173
+ "tier": "base+",
174
+ "verified_sdk_version": "1.0.7",
175
+ "candidates": ["sdk"],
176
+ "candidate_verification": {"sdk": True},
177
+ },
178
+ }
179
+ SYMBOL_DIRECTORY_VERSION = 5
180
+ SYMBOL_DIRECTORY_TTL_SECONDS = 24 * 60 * 60
181
+ SYMBOL_DIRECTORY_RETRY_SECONDS = 60 * 60
182
+ # A complete A / HK / US / ETF directory is about 18,500 instruments today.
183
+ # Leave headroom for new listings and a small number of provider duplicates.
184
+ SYMBOL_DIRECTORY_MAX_ITEMS = 50_000
185
+ # HKEX publishes its complete securities master as a small XLSX each trading
186
+ # day. It is a more stable directory source than a quote-page endpoint.
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
+ )
192
+ _HK_DIRECTORY_CATEGORIES = frozenset({"Equity", "Exchange Traded Products", "Real Estate Investment Trusts"})
193
+ CN_BROAD_INDEXES = (
194
+ {"symbol": "000001.XSHG", "name": "上证指数", "market": "CN_INDEX", "aliases": "沪指 上证综指 上证综合指数 shanghai composite"},
195
+ {"symbol": "000016.XSHG", "name": "上证50", "market": "CN_INDEX", "aliases": "上证五十 sse 50"},
196
+ {"symbol": "000010.XSHG", "name": "上证180", "market": "CN_INDEX", "aliases": "上证一百八 sse 180"},
197
+ {"symbol": "000009.XSHG", "name": "上证380", "market": "CN_INDEX", "aliases": "上证三百八 sse 380"},
198
+ {"symbol": "000047.XSHG", "name": "上证全指", "market": "CN_INDEX", "aliases": "上证全指数"},
199
+ {"symbol": "000300.XSHG", "name": "沪深300", "market": "CN_INDEX", "aliases": "沪深三百 csi300 csi 300"},
200
+ {"symbol": "000688.XSHG", "name": "科创50", "market": "CN_INDEX", "aliases": "科创五十 star 50"},
201
+ {"symbol": "000903.XSHG", "name": "中证A100", "market": "CN_INDEX", "aliases": "中证a100 csi a100"},
202
+ {"symbol": "000905.XSHG", "name": "中证500", "market": "CN_INDEX", "aliases": "中证五百 csi500 csi 500"},
203
+ {"symbol": "000906.XSHG", "name": "中证800", "market": "CN_INDEX", "aliases": "中证八百 csi800 csi 800"},
204
+ {"symbol": "000852.XSHG", "name": "中证1000", "market": "CN_INDEX", "aliases": "中证一千 csi1000 csi 1000"},
205
+ {"symbol": "000985.XSHG", "name": "中证全指", "market": "CN_INDEX", "aliases": "中证全指数 csi all share"},
206
+ {"symbol": "399001.XSHE", "name": "深证成指", "market": "CN_INDEX", "aliases": "深指 深成指 shenzhen component"},
207
+ {"symbol": "399005.XSHE", "name": "中小100", "market": "CN_INDEX", "aliases": "中小板100"},
208
+ {"symbol": "399006.XSHE", "name": "创业板指", "market": "CN_INDEX", "aliases": "创业板指数 chinext"},
209
+ {"symbol": "399303.XSHE", "name": "国证2000", "market": "CN_INDEX", "aliases": "国证两千 cn2000"},
210
+ {"symbol": "399310.XSHE", "name": "国证A50", "market": "CN_INDEX", "aliases": "国证a50 cn a50"},
211
+ {"symbol": "899050.BJSE", "name": "北证50", "market": "CN_INDEX", "aliases": "北证五十 beijing 50"},
212
+ )
213
+ CN_BROAD_INDEX_BY_SYMBOL = {item["symbol"]: item for item in CN_BROAD_INDEXES}
214
+
215
+ _SYMBOL_DIRECTORY_SEED = (
216
+ *({key: value for key, value in item.items() if key != "aliases"} for item in CN_BROAD_INDEXES),
217
+ {"symbol": "100.HSI", "name": "恒生指数", "market": "HK_INDEX"},
218
+ {"symbol": "00700.HK", "name": "腾讯控股", "market": "HK"},
219
+ {"symbol": "09988.HK", "name": "阿里巴巴-W", "market": "HK"},
220
+ {"symbol": "AAPL.US", "name": "Apple", "market": "US"},
221
+ {"symbol": "MSFT.US", "name": "Microsoft", "market": "US"},
222
+ {"symbol": "NVDA.US", "name": "NVIDIA", "market": "US"},
223
+ {"symbol": "AMD.US", "name": "超威半导体", "market": "US"},
224
+ {"symbol": "601899.XSHG", "name": "紫金矿业", "market": "CN"},
225
+ {"symbol": "600519.XSHG", "name": "贵州茅台", "market": "CN"},
226
+ {"symbol": "601318.XSHG", "name": "中国平安", "market": "CN"},
227
+ {"symbol": "600036.XSHG", "name": "招商银行", "market": "CN"},
228
+ )
229
+ _BASIC_DIRECTORY = json.loads((Path(__file__).resolve().parent.parent / "config" / "basic-symbols.json").read_text(encoding="utf-8"))
230
+ _SYMBOL_DIRECTORY_SEED = (*_SYMBOL_DIRECTORY_SEED, *_BASIC_DIRECTORY["items"])
231
+ _BUILTIN_SEARCH_ALIASES = {
232
+ **{item["symbol"]: item["aliases"] for item in CN_BROAD_INDEXES},
233
+ "100.HSI": "恒指 hang seng hsi",
234
+ "00700.HK": "腾讯 tencent",
235
+ "09988.HK": "阿里 阿里巴巴 alibaba baba",
236
+ "AAPL.US": "苹果 apple",
237
+ "MSFT.US": "微软 microsoft",
238
+ "NVDA.US": "英伟达 英伟达公司 nvidia",
239
+ "AMD.US": "超威半导体 超微半导体 amd advanced micro devices",
240
+ "601899.XSHG": "紫金 紫金矿业 zijin mining",
241
+ "600519.XSHG": "茅台 贵州茅台 moutai",
242
+ "601318.XSHG": "平安 中国平安 ping an",
243
+ "600036.XSHG": "招行 招商银行 cmb",
244
+ }
245
+
246
+
247
+ def _ftshare_src_candidates() -> list[Path]:
248
+ custom = (os.environ.get("FTSHARE_SDK_SRC") or "").strip()
249
+ if not custom:
250
+ return []
251
+ source = Path(custom).expanduser()
252
+ return [source, source / "src"]
253
+
254
+
255
+ def _path_makes_ftshare_importable(path: Path) -> bool:
256
+ """True if putting ``path`` on sys.path would expose package ftshare."""
257
+ return (path / "ftshare" / "__init__.py").is_file() or (path / "ftshare").is_dir()
258
+
259
+
260
+ def _maybe_inject_local_ftshare() -> str | None:
261
+ """Try to make ``import ftshare`` work. Returns injected path or None."""
262
+ try:
263
+ import ftshare # noqa: F401
264
+
265
+ return None
266
+ except Exception:
267
+ pass
268
+
269
+ for src in _ftshare_src_candidates():
270
+ if not src.exists():
271
+ continue
272
+ # Prefer …/src that contains ftshare/; also accept path that *is* the package parent.
273
+ inject: Path | None = None
274
+ if _path_makes_ftshare_importable(src):
275
+ inject = src
276
+ elif src.name == "ftshare" and _path_makes_ftshare_importable(src.parent):
277
+ inject = src.parent
278
+ if inject is None:
279
+ continue
280
+ s = str(inject.resolve())
281
+ if s not in sys.path:
282
+ sys.path.insert(0, s)
283
+ try:
284
+ import ftshare # noqa: F401
285
+
286
+ return s
287
+ except Exception:
288
+ try:
289
+ sys.path.remove(s)
290
+ except ValueError:
291
+ pass
292
+ continue
293
+ return None
294
+
295
+
296
+ _INJECTED_FTSHARE_PATH = _maybe_inject_local_ftshare()
297
+
298
+ # Credential provenance is intentionally process-local and never returned with
299
+ # a path or a value. It lets the UI explain why FTShare is already connected
300
+ # without guessing at, or scanning, a user's shell, .env files, or keychain.
301
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE: str | None = None
302
+ _FTSHARE_RUNTIME_FILE_KEY: str | None = None
303
+
304
+
305
+ def _memory_only_credentials() -> bool:
306
+ """Whether the embedding host has forbidden every credential-file path.
307
+
308
+ The Codex App adapter sets this before importing the provider. It is an
309
+ opt-in restriction so the established DSH credential precedence remains
310
+ byte-for-byte compatible. In this mode only a process environment value
311
+ (or an adapter-owned in-memory override) can be used; neither the DSH
312
+ bridge nor the plugin credential store is inspected.
313
+ """
314
+ return (os.environ.get("FT_KLINE_CODEX_MEMORY_ONLY") or "").strip() == "1"
315
+
316
+
317
+ def _uses_posix_permissions() -> bool:
318
+ return os.name == "posix"
319
+
320
+
321
+ def _ftshare_key_path() -> Path:
322
+ configured = (os.environ.get("FTSHARE_API_KEY_FILE") or "").strip()
323
+ if configured:
324
+ return Path(configured).expanduser()
325
+ if os.name == "nt":
326
+ local = (os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or "").strip()
327
+ base = Path(local) if local else Path.home() / "AppData" / "Local"
328
+ return base / "dsh_kline" / "ftshare-credentials.json"
329
+ return Path.home() / ".config" / "dsh_kline" / "ftshare-credentials.json"
330
+
331
+
332
+ def _ftshare_settings_key_path() -> Path | None:
333
+ """Credential file published by the DSH FTShare settings bridge.
334
+
335
+ The DSH host writes it when the FTShare settings plugin is installed and
336
+ the launcher points this process at it. Without that file this process
337
+ resolves credentials exactly as it did before the bridge existed.
338
+ """
339
+ configured = (os.environ.get("DSH_KLINE_SETTINGS_KEY_FILE") or "").strip()
340
+ return Path(configured).expanduser() if configured else None
341
+
342
+
343
+ def _ftshare_credential_files() -> tuple[tuple[Path, str], ...]:
344
+ """Credential files in precedence order, each with its provenance label.
345
+
346
+ An explicit ``FTSHARE_API_KEY_FILE`` stays authoritative for hosts and
347
+ tests that set one; otherwise a Key saved in the DSH FTShare settings
348
+ outranks the one this plugin stored for itself.
349
+ """
350
+ if _memory_only_credentials():
351
+ return ()
352
+ explicit = (os.environ.get("FTSHARE_API_KEY_FILE") or "").strip()
353
+ if explicit:
354
+ return ((Path(explicit).expanduser(), "external_file"),)
355
+ files: list[tuple[Path, str]] = []
356
+ bridge = _ftshare_settings_key_path()
357
+ if bridge is not None:
358
+ files.append((bridge, "settings_bridge"))
359
+ files.append((_ftshare_key_path(), "plugin_store"))
360
+ return tuple(files)
361
+
362
+
363
+ def _valid_ftshare_key(value: Any) -> str:
364
+ key = value.strip() if isinstance(value, str) else ""
365
+ if not key or len(key) > 512 or any(ord(char) < 32 or ord(char) == 127 for char in key):
366
+ return ""
367
+ return key
368
+
369
+
370
+ def _read_ftshare_key_file(path: Path) -> str:
371
+ try:
372
+ if not path.is_file() or path.is_symlink():
373
+ return ""
374
+ if _uses_posix_permissions() and stat.S_IMODE(path.stat().st_mode) & 0o077:
375
+ return ""
376
+ payload = json.loads(path.read_text(encoding="utf-8"))
377
+ if not isinstance(payload, Mapping) or type(payload.get("version")) is not int or payload["version"] != 1:
378
+ return ""
379
+ return _valid_ftshare_key(payload.get("api_key"))
380
+ except (OSError, ValueError, TypeError):
381
+ return ""
382
+
383
+
384
+ def _resolve_persisted_ftshare_key() -> tuple[str, str]:
385
+ """Return the first usable file credential, with where it came from."""
386
+ for path, source in _ftshare_credential_files():
387
+ value = _read_ftshare_key_file(path)
388
+ if value:
389
+ return value, source
390
+ return "", ""
391
+
392
+
393
+ def _read_persisted_ftshare_key() -> str:
394
+ return _resolve_persisted_ftshare_key()[0]
395
+
396
+
397
+ def _load_persisted_ftshare_key() -> bool:
398
+ global _FTSHARE_RUNTIME_CREDENTIAL_SOURCE, _FTSHARE_RUNTIME_FILE_KEY
399
+ if _memory_only_credentials() or _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY")):
400
+ return False
401
+ value, source = _resolve_persisted_ftshare_key()
402
+ if not value:
403
+ return False
404
+ os.environ["FTSHARE_API_KEY"] = value
405
+ _FTSHARE_RUNTIME_FILE_KEY = value
406
+ # Preserve the fact that this process itself wrote the saved credential,
407
+ # even when a test/developer chose a custom file path. A fresh process
408
+ # correctly reports that same explicit path as externally managed.
409
+ if _FTSHARE_RUNTIME_CREDENTIAL_SOURCE != "plugin_store":
410
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = source
411
+ return True
412
+
413
+
414
+ def _refresh_persisted_ftshare_key() -> None:
415
+ """Follow file-backed credentials before each FTShare client is created.
416
+
417
+ The DSH bridge can replace or clear its file while this process runs, so a
418
+ Key change applies without restarting the MCP server. A Key the host
419
+ environment supplied or a temporary in-process override is never replaced
420
+ here. The plugin's saved credential remains the lower-priority fallback.
421
+ """
422
+ global _FTSHARE_RUNTIME_CREDENTIAL_SOURCE, _FTSHARE_RUNTIME_FILE_KEY
423
+ if _memory_only_credentials():
424
+ # An environment key is deliberately authoritative in the Codex host.
425
+ # Never replace it with a file-backed DSH/profile credential.
426
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = "environment" if _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY")) else None
427
+ _FTSHARE_RUNTIME_FILE_KEY = None
428
+ return
429
+ source = _FTSHARE_RUNTIME_CREDENTIAL_SOURCE
430
+ current = _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY"))
431
+ if source in {"environment", "session"}:
432
+ return
433
+ if source is None and current:
434
+ return
435
+ if current and current != _FTSHARE_RUNTIME_FILE_KEY:
436
+ # Someone explicitly replaced the environment since our last file
437
+ # load. Never overwrite that new credential with a stale file source.
438
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = None
439
+ _FTSHARE_RUNTIME_FILE_KEY = None
440
+ return
441
+ value, resolved = _resolve_persisted_ftshare_key()
442
+ if value:
443
+ os.environ["FTSHARE_API_KEY"] = value
444
+ # A credential this process saved for itself keeps reporting as the
445
+ # plugin's own, even when it lives at an explicitly configured path; a
446
+ # Key published by the DSH settings always reports its own source.
447
+ if _FTSHARE_RUNTIME_CREDENTIAL_SOURCE != "plugin_store" or resolved == "settings_bridge":
448
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = resolved
449
+ else:
450
+ os.environ.pop("FTSHARE_API_KEY", None)
451
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = None
452
+ _FTSHARE_RUNTIME_FILE_KEY = value or None
453
+ if value != current:
454
+ clear_provider_caches()
455
+
456
+
457
+ def _ftshare_credential_source() -> str:
458
+ """Return safe credential provenance, never a key or filesystem path."""
459
+ if not _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY")):
460
+ return "none"
461
+ return _FTSHARE_RUNTIME_CREDENTIAL_SOURCE or "environment"
462
+
463
+
464
+ def _write_persisted_ftshare_key(value: str) -> None:
465
+ path = _ftshare_key_path()
466
+ if path.is_symlink():
467
+ raise OSError("FTShare credential path must not be a symbolic link")
468
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
469
+ if _uses_posix_permissions():
470
+ os.chmod(path.parent, 0o700)
471
+ descriptor, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
472
+ try:
473
+ if _uses_posix_permissions():
474
+ os.fchmod(descriptor, 0o600)
475
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
476
+ descriptor = -1
477
+ json.dump({"version": 1, "api_key": value}, handle, ensure_ascii=False, separators=(",", ":"))
478
+ handle.flush()
479
+ os.fsync(handle.fileno())
480
+ _replace_credential_file(temp_name, path)
481
+ if _uses_posix_permissions():
482
+ os.chmod(path, 0o600)
483
+ finally:
484
+ if descriptor >= 0:
485
+ os.close(descriptor)
486
+ try:
487
+ os.unlink(temp_name)
488
+ except FileNotFoundError:
489
+ pass
490
+
491
+
492
+ def _replace_credential_file(source: str | Path, destination: str | Path) -> None:
493
+ attempts = 6 if os.name == "nt" else 1
494
+ for attempt in range(attempts):
495
+ try:
496
+ os.replace(source, destination)
497
+ return
498
+ except PermissionError:
499
+ if attempt + 1 == attempts:
500
+ raise
501
+ time.sleep(0.04 * (attempt + 1))
502
+
503
+
504
+ def _remove_persisted_ftshare_key() -> None:
505
+ path = _ftshare_key_path()
506
+ if path.is_symlink():
507
+ raise OSError("FTShare credential path must not be a symbolic link")
508
+ try:
509
+ path.unlink()
510
+ except FileNotFoundError:
511
+ pass
512
+
513
+
514
+ def ftshare_available() -> bool:
515
+ """Check SDK availability without permanently latching a cold-start miss."""
516
+ _load_persisted_ftshare_key()
517
+ for attempt in range(3):
518
+ try:
519
+ import ftshare # noqa: F401
520
+
521
+ return True
522
+ except Exception:
523
+ _maybe_inject_local_ftshare()
524
+ if attempt < 2:
525
+ time.sleep(0.05 * (attempt + 1))
526
+ return False
527
+
528
+
529
+ def _ftshare_market_api(timeout: float) -> Any:
530
+ """Create an SDK client with the process key attached to every request."""
531
+ import ftshare as ft
532
+
533
+ _refresh_persisted_ftshare_key()
534
+ key = _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY"))
535
+ if not key:
536
+ # The SDK also reads the environment: an explicit empty string would
537
+ # otherwise be sent as a malformed key instead of anonymous access.
538
+ os.environ.pop("FTSHARE_API_KEY", None)
539
+ headers = {"FTSHARE_API_KEY": key} if key else None
540
+ return ft.market_api(timeout=timeout, headers=headers)
541
+
542
+
543
+ def _ftshare_contract_status() -> dict[str, dict[str, Any]]:
544
+ return {
545
+ name: {
546
+ "doc": spec["doc"],
547
+ "tier": spec["tier"],
548
+ "transport": _FTSHARE_TRANSPORT_STATE.get(name, {}).get("transport"),
549
+ "last_ok": bool(_FTSHARE_TRANSPORT_STATE.get(name, {}).get("last_ok")),
550
+ "verified_sdk_version": spec["verified_sdk_version"],
551
+ "candidate_verification": dict(spec.get("candidate_verification") or {}),
552
+ }
553
+ for name, spec in FT_CONTRACTS.items()
554
+ }
555
+
556
+
557
+ def ftshare_contract_status() -> dict[str, dict[str, Any]]:
558
+ """Expose safe transport/contract diagnostics without credentials."""
559
+ return deepcopy(_ftshare_contract_status())
560
+
561
+
562
+ def _preferred_ftshare_transport(contract: str) -> str:
563
+ state = _FTSHARE_TRANSPORT_STATE.get(contract) or {}
564
+ transport = state.get("transport")
565
+ return transport if transport in FT_CONTRACTS.get(contract, {}).get("candidates", []) else "auto"
566
+
567
+
568
+ def _is_retryable_ftshare_status(exc: Exception) -> bool:
569
+ raw = str(exc or "")
570
+ return bool(re.search(r"HTTP(?:\s+Error)?\s+(?:404|405|429|5\d\d)", raw, re.IGNORECASE))
571
+
572
+
573
+ def _is_ftshare_contract_mismatch(exc: Exception) -> bool:
574
+ if isinstance(exc, (AttributeError, TypeError)):
575
+ return True
576
+ raw = str(exc or "").lower()
577
+ return any(marker in raw for marker in ("unexpected keyword", "no such endpoint", "method not allowed"))
578
+
579
+
580
+ def _adaptive_ftshare_call(contract: str, market: Any, params: dict[str, Any]) -> Any:
581
+ """Try only registered transports with bounded, auditable fallback.
582
+
583
+ Authentication/plan failures stay on the current transport. A 429 is
584
+ retried on that same transport; contract/path failures may advance to the
585
+ next registered candidate. This is intentionally not self-modifying.
586
+ """
587
+ spec = FT_CONTRACTS[contract]
588
+ candidates = list(spec["candidates"])
589
+ preferred = _preferred_ftshare_transport(contract)
590
+ if preferred != "auto":
591
+ candidates.remove(preferred)
592
+ candidates.insert(0, preferred)
593
+ last_error: Exception | None = None
594
+ for transport in candidates:
595
+ if transport == "http_get":
596
+ get_method = getattr(market, "get", None)
597
+ if not callable(get_method):
598
+ last_error = AttributeError("FTShare GET transport is unavailable")
599
+ continue
600
+ for retry in range(3):
601
+ try:
602
+ request_params = dict(params)
603
+ as_dataframe = request_params.pop("as_dataframe", False)
604
+ if contract == "daily_candles":
605
+ path = "api/v1/market/data/stock-candlesticks"
606
+ if transport == "http_get":
607
+ result = get_method(path, as_dataframe=as_dataframe, **request_params)
608
+ else:
609
+ result = market.stock_candlesticks(**params)
610
+ elif contract == "index_daily_candles":
611
+ path = "api/v1/market/data/index-candlesticks"
612
+ if transport == "http_get":
613
+ result = get_method(path, as_dataframe=as_dataframe, **request_params)
614
+ else:
615
+ result = market.index_candlesticks(**params)
616
+ elif contract == "index_history_minute_candles":
617
+ path = "api/v2/market/data/index_minutes"
618
+ request_params.pop("adjust_kind", None)
619
+ request_params["symbol"] = _short_mainland_symbol(str(request_params["symbol"]))
620
+ if transport == "http_get":
621
+ result = get_method(path, as_dataframe=as_dataframe, **request_params)
622
+ else:
623
+ result = market.index_minutes(as_dataframe=as_dataframe, **request_params)
624
+ elif contract == "realtime_minute_candles":
625
+ # The v4 contract is deliberately narrow: its SDK method
626
+ # accepts ``symbols``, not the v2 history parameters.
627
+ # Do not leak a date window or adjustment flag into v4.
628
+ symbols = request_params.get("symbols")
629
+ method = getattr(market, "stock_realtime_minute_kline", None)
630
+ if not callable(method):
631
+ raise AttributeError("FTShare v4 realtime-minute SDK method is unavailable")
632
+ result = method(symbols=symbols, as_dataframe=as_dataframe)
633
+ else:
634
+ if transport == "http_get":
635
+ path = "api/v2/market/data/stock_minutes"
636
+ request_params["symbol"] = _short_mainland_symbol(str(request_params["symbol"]))
637
+ result = get_method(path, as_dataframe=as_dataframe, **request_params)
638
+ elif callable(getattr(market, "stock_minutes", None)):
639
+ request_params["symbol"] = _short_mainland_symbol(str(request_params["symbol"]))
640
+ result = market.stock_minutes(as_dataframe=as_dataframe, **request_params)
641
+ else:
642
+ legacy_params = dict(params)
643
+ legacy_params.setdefault("interval_unit", "Minute")
644
+ result = market.stock_candlesticks(**legacy_params)
645
+ _FTSHARE_TRANSPORT_STATE[contract] = {"transport": transport, "last_ok": True}
646
+ return result
647
+ except Exception as exc: # noqa: BLE001
648
+ last_error = exc
649
+ status, _message = _classify_ftshare_error(exc)
650
+ if status in {"auth_required", "invalid_key", "capability_limited"}:
651
+ _FTSHARE_TRANSPORT_STATE[contract] = {"transport": transport, "last_ok": False}
652
+ raise
653
+ if status == "rate_limited":
654
+ if retry < 2:
655
+ time.sleep(0.25 * (2**retry))
656
+ continue
657
+ # A rate limit belongs to this transport/account; changing
658
+ # method would only multiply the upstream load.
659
+ _FTSHARE_TRANSPORT_STATE[contract] = {"transport": transport, "last_ok": False}
660
+ raise
661
+ if _is_ftshare_contract_mismatch(exc) or _is_retryable_ftshare_status(exc):
662
+ break
663
+ break
664
+ if last_error is None:
665
+ last_error = RuntimeError(f"FTShare {contract} has no available transport")
666
+ _FTSHARE_TRANSPORT_STATE[contract] = {"transport": None, "last_ok": False}
667
+ raise last_error
668
+
669
+
670
+ def _ftshare_stock_candlesticks(market: Any, **params: Any) -> Any:
671
+ """Call verified daily-K candidates with bounded fallback."""
672
+ return _adaptive_ftshare_call("daily_candles", market, params)
673
+
674
+
675
+ def _short_mainland_symbol(symbol: str) -> str:
676
+ suffixes = {
677
+ ".XSHG": ".SH",
678
+ ".XSHE": ".SZ",
679
+ ".BJSE": ".BJ",
680
+ }
681
+ for long_suffix, short_suffix in suffixes.items():
682
+ if symbol.endswith(long_suffix):
683
+ return symbol[: -len(long_suffix)] + short_suffix
684
+ return symbol
685
+
686
+
687
+ def _ftshare_stock_minutes(market: Any, **params: Any) -> Any:
688
+ """Call verified historical minute-K candidates with bounded fallback."""
689
+ return _adaptive_ftshare_call("history_minute_candles", market, params)
690
+
691
+
692
+ def _ftshare_stock_realtime_minutes(market: Any, *, symbol: str) -> Any:
693
+ """Fetch the current A-share minute session through FTShare v4.
694
+
695
+ V4 is intentionally not a generic replacement for v2: the endpoint is
696
+ realtime-stock-only and exposes ``symbols`` rather than history windows.
697
+ Callers must validate the returned session and use v2 for older bars.
698
+ """
699
+ return _adaptive_ftshare_call(
700
+ "realtime_minute_candles",
701
+ market,
702
+ # The v4 gateway validates this as a JSON array in one query value;
703
+ # handing the SDK a Python list serializes differently and returns 400.
704
+ {"symbols": json.dumps([_short_mainland_symbol(symbol)]), "as_dataframe": False},
705
+ )
706
+
707
+
708
+ def _ftshare_index_candlesticks(market: Any, **params: Any) -> Any:
709
+ """Call the verified A-share index K-line endpoint (SDK 1.0.7)."""
710
+ return _adaptive_ftshare_call("index_daily_candles", market, params)
711
+
712
+
713
+ def _ftshare_index_minutes(market: Any, **params: Any) -> Any:
714
+ """Call the A-share index minute endpoint (SDK 1.0.7, plan dependent)."""
715
+ return _adaptive_ftshare_call("index_history_minute_candles", market, params)
716
+
717
+
718
+ def _ftshare_etf_candlesticks(market: Any, **params: Any) -> Any:
719
+ """Call FTShare's ETF-native daily-history endpoint.
720
+
721
+ Keep this small adapter separate from the stock transport fallback: the
722
+ endpoint has the same candle envelope but a distinct provider contract.
723
+ """
724
+ method = getattr(market, "etf_candlesticks", None)
725
+ if not callable(method):
726
+ raise AttributeError("FTShare etf_candlesticks is unavailable")
727
+ result = method(**params)
728
+ _FTSHARE_TRANSPORT_STATE["etf_candles"] = {"transport": "sdk", "last_ok": True}
729
+ return result
730
+
731
+
732
+ def _ftshare_etf_minutes(market: Any, **params: Any) -> Any:
733
+ """Call ETF minutes without falling back to the stock-minute contract."""
734
+ method = getattr(market, "etf_minutes", None)
735
+ if not callable(method):
736
+ raise AttributeError("FTShare etf_minutes is unavailable")
737
+ result = method(**params)
738
+ _FTSHARE_TRANSPORT_STATE["etf_minutes"] = {"transport": "sdk", "last_ok": True}
739
+ return result
740
+
741
+
742
+ def ftshare_status() -> dict[str, Any]:
743
+ """Return safe provider status without host paths or module locations."""
744
+ _refresh_persisted_ftshare_key()
745
+ _load_persisted_ftshare_key()
746
+ ok = ftshare_available()
747
+ credential_source = _ftshare_credential_source()
748
+ info: dict[str, Any] = {
749
+ "available": ok,
750
+ "configured": credential_source != "none",
751
+ "persistent": credential_source in {"plugin_store", "external_file", "settings_bridge"},
752
+ "credential_source": credential_source,
753
+ # Only a key explicitly saved by this running plugin can be safely
754
+ # removed from this UI. Environment, externally supplied files, and a
755
+ # Key owned by the DSH FTShare settings remain owned by the host/user.
756
+ "can_clear": credential_source == "plugin_store",
757
+ "contracts": _ftshare_contract_status(),
758
+ }
759
+ try:
760
+ import ftshare # noqa: F401
761
+
762
+ try:
763
+ info["distribution_version"] = distribution_version("ftshare")
764
+ except PackageNotFoundError:
765
+ info["distribution_version"] = None
766
+ except Exception:
767
+ info["distribution_version"] = None
768
+ info["sdk_version"] = info.get("distribution_version")
769
+ return info
770
+
771
+
772
+ def clear_provider_caches() -> None:
773
+ """Drop provider-backed caches after a runtime configuration change."""
774
+ global _market_pulse_cache
775
+ _symbol_search_cache.clear()
776
+ _security_workspace_cache.clear()
777
+ _security_intelligence_cache.clear()
778
+ _market_pulse_cache = None
779
+ _market_pulse_section_cache.clear()
780
+ _symbol_name_cache.clear()
781
+ _candle_cache.clear()
782
+
783
+
784
+ def _market_pulse_section_lock(scope: str) -> threading.Lock:
785
+ """Return a stable lock so identical concurrent section loads coalesce."""
786
+ with _market_pulse_inflight_guard:
787
+ lock = _market_pulse_section_inflight.get(scope)
788
+ if lock is None:
789
+ lock = threading.Lock()
790
+ _market_pulse_section_inflight[scope] = lock
791
+ return lock
792
+
793
+
794
+ def _cached_market_pulse_section(scope: str, *, refresh: bool) -> dict[str, Any] | None:
795
+ """Return a still-fresh section payload, or None when it must be refetched."""
796
+ if refresh:
797
+ return None
798
+ entry = _market_pulse_section_cache.get(scope)
799
+ if not entry:
800
+ return None
801
+ cached_at, payload = entry
802
+ if time.time() - cached_at >= _MARKET_PULSE_SECTION_TTL_SECONDS:
803
+ return None
804
+ return deepcopy(payload)
805
+
806
+
807
+ def _set_ftshare_capabilities(capabilities: dict[str, str]) -> None:
808
+ _LAST_FTSHARE_CAPABILITIES.clear()
809
+ _LAST_FTSHARE_CAPABILITIES.update({str(k): str(v) for k, v in capabilities.items()})
810
+
811
+
812
+ def ftshare_capabilities() -> dict[str, str]:
813
+ """Return the last safe capability result without exposing credentials."""
814
+ if _LAST_FTSHARE_CAPABILITIES:
815
+ return dict(_LAST_FTSHARE_CAPABILITIES)
816
+ return {"daily": "not_tested" if ftshare_available() else "unavailable", "minute": "not_tested"}
817
+
818
+
819
+ def data_source_capability_contract() -> dict[str, Any]:
820
+ """Describe UI/MCP domain capabilities without exposing a vendor's internals.
821
+
822
+ The workbench must not infer that a configured source can provide every
823
+ page just because it can return candles. This small contract gives every
824
+ client the same vocabulary, and lets future providers opt into only the
825
+ domains they genuinely implement.
826
+ """
827
+ available = ftshare_available()
828
+ status = "available" if available else "unavailable"
829
+ ftshare = {
830
+ "instrument_directory": status,
831
+ "daily_candles": ftshare_capabilities().get("daily", "not_tested" if available else "unavailable"),
832
+ "minute_candles": ftshare_capabilities().get("minute", "not_tested" if available else "unavailable"),
833
+ "market_indices": status,
834
+ "market_breadth": status,
835
+ "market_rankings": status,
836
+ "market_boards": status,
837
+ "board_members": "source_dependent" if available else "unavailable",
838
+ "company_profile": status,
839
+ "news": status,
840
+ "financials": status,
841
+ "holders": status,
842
+ "stock_flows": status,
843
+ "trading_events": status,
844
+ }
845
+ return {
846
+ "version": 1,
847
+ "providers": {
848
+ "ftshare": ftshare,
849
+ # Caller-supplied OHLCV is deliberately narrow: it can feed
850
+ # analysis and a chart, but must never fabricate a market page.
851
+ "external_rows": {
852
+ "daily_candles": "available",
853
+ "minute_candles": "available",
854
+ "instrument_directory": "unsupported",
855
+ "market_indices": "unsupported",
856
+ "market_breadth": "unsupported",
857
+ "market_rankings": "unsupported",
858
+ "market_boards": "unsupported",
859
+ "board_members": "unsupported",
860
+ "company_profile": "unsupported",
861
+ "news": "unsupported",
862
+ "financials": "unsupported",
863
+ "holders": "unsupported",
864
+ "stock_flows": "unsupported",
865
+ "trading_events": "unsupported",
866
+ },
867
+ },
868
+ }
869
+
870
+
871
+ def ftshare_index_kline_available() -> bool:
872
+ """Whether A-share index K-line history is available from the FTShare adapter.
873
+
874
+ The adapter only calls verified provider contracts (see
875
+ docs/provider-adaptation.md). FTShare SDK 1.0.7 exposes the
876
+ documented A-share index endpoint ``index_candlesticks``
877
+ (api/v1/market/data/index-candlesticks) which was verified with live
878
+ daily data (free tier) and registered in FT_CONTRACTS, so daily-or-larger
879
+ index K-lines are reported available. Index minutes (``index_minutes``)
880
+ stay plan-dependent and are not part of this capability flag.
881
+ """
882
+ return True
883
+
884
+
885
+ def configure_ftshare_api_key(
886
+ api_key: str | None,
887
+ *,
888
+ test_connection: bool = True,
889
+ persist: bool = True,
890
+ ) -> dict[str, Any]:
891
+ """Configure FTShare for this process and optionally persist it locally."""
892
+ global _FTSHARE_RUNTIME_CREDENTIAL_SOURCE, _FTSHARE_RUNTIME_FILE_KEY
893
+ value = (api_key or "").strip()
894
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
895
+ return {"ok": False, "error": "invalid_api_key", "message": "FTShare API Key 包含不可用字符"}
896
+ if len(value) > 512:
897
+ return {"ok": False, "error": "invalid_api_key", "message": "FTShare API Key 长度不受支持"}
898
+ try:
899
+ # A temporary key only changes this process. It must not erase the
900
+ # user's saved credential: that would make a one-off connection test
901
+ # silently break the next DSH restart.
902
+ if persist:
903
+ if value:
904
+ _write_persisted_ftshare_key(value)
905
+ else:
906
+ if _ftshare_credential_source() != "plugin_store":
907
+ return {
908
+ "ok": False,
909
+ "error": "external_credential_managed",
910
+ "message": "当前 FTShare 凭据由宿主环境或外部文件管理,插件不会清除它。",
911
+ }
912
+ _remove_persisted_ftshare_key()
913
+ except OSError:
914
+ return {"ok": False, "error": "credential_persist_failed", "message": "无法保存 FTShare 本机配置"}
915
+ if value:
916
+ os.environ["FTSHARE_API_KEY"] = value
917
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = "plugin_store" if persist else "session"
918
+ else:
919
+ os.environ.pop("FTSHARE_API_KEY", None)
920
+ _FTSHARE_RUNTIME_CREDENTIAL_SOURCE = None
921
+ _FTSHARE_RUNTIME_FILE_KEY = value if persist and value else None
922
+ clear_provider_caches()
923
+
924
+ result: dict[str, Any] = {
925
+ "ok": True,
926
+ "configured": bool(value),
927
+ "source": "ftshare",
928
+ "persistent": bool(value and persist),
929
+ "credential_source": _ftshare_credential_source(),
930
+ "can_clear": bool(value and persist),
931
+ }
932
+ if not test_connection:
933
+ result["message"] = "FTShare 配置已更新(已保存到本机)" if value and persist else "FTShare 配置已更新(仅当前 dsh 进程有效)"
934
+ return result
935
+ connection = test_ftshare_connection()
936
+ result.update({key: value for key, value in connection.items() if key != "ok"})
937
+ result["connection_ok"] = bool(connection.get("ok"))
938
+ result["key_saved"] = bool(value and persist)
939
+ result["ok"] = bool(connection.get("ok"))
940
+ if result["ok"]:
941
+ result["message"] = _ftshare_capability_message(
942
+ connection.get("capabilities") or {},
943
+ persistent=bool(result["persistent"]),
944
+ )
945
+ if not result["ok"]:
946
+ result["message"] = (
947
+ f"FTShare API Key 已{'保存' if result['key_saved'] else '配置'},但校验失败:"
948
+ f"{connection.get('message') or '请检查 Key 和数据权限。'}"
949
+ )
950
+ return result
951
+
952
+
953
+ def _ftshare_capability_message(capabilities: dict[str, str], *, persistent: bool) -> str:
954
+ saved = "已保存" if persistent else "已配置"
955
+ daily = capabilities.get("daily")
956
+ minute = capabilities.get("minute")
957
+ if daily == "available" and minute == "auth_required":
958
+ return "FTShare 日 K 已验证可用;分钟 K 需要配置有效 API Key 及相应数据权限。"
959
+ if daily == "available" and minute in {"insufficient_quota", "capability_limited"}:
960
+ return f"FTShare API Key {saved}并验证通过。当前套餐可使用日 K;分钟 K 暂未开通,请按需升级对应套餐。"
961
+ if daily == "available" and minute == "available":
962
+ return f"FTShare API Key {saved}并验证通过,当前日 K 与分钟 K 均可用。"
963
+ if daily == "available":
964
+ return "FTShare 日 K 已验证可用;分钟 K 暂未验证成功,请稍后重试。"
965
+ return "FTShare 尚未验证到可用行情,请检查连接状态。"
966
+
967
+
968
+ def test_ftshare_connection() -> dict[str, Any]:
969
+ """Probe basic daily access first, then separately probe minute access."""
970
+ if not ftshare_available():
971
+ return {"ok": False, "error": "ftshare_not_installed", "message": "FTShare SDK 未安装"}
972
+ capabilities: dict[str, str] = {"daily": "unavailable", "minute": "not_tested"}
973
+ try:
974
+ market = _ftshare_market_api(timeout=8)
975
+ now = int(time.time() * 1000)
976
+ daily_rows = _ftshare_stock_candlesticks(
977
+ market,
978
+ symbol="600519.XSHG", interval_unit="Day", interval_value=1,
979
+ adjust_kind="none", since_ts_millis=now - 14 * 86_400_000,
980
+ until_ts_millis=now, limit=2, as_dataframe=False,
981
+ )
982
+ if not _normalize_raw(daily_rows):
983
+ _set_ftshare_capabilities(capabilities)
984
+ return {"ok": False, "error": "empty_daily_data", "message": "连接成功,但未返回有效日 K 数据,尚不能确认行情可用。", "capabilities": capabilities}
985
+ capabilities["daily"] = "available"
986
+ try:
987
+ _ftshare_stock_minutes(
988
+ market, symbol="600519.XSHG", interval_value=1,
989
+ adjust_kind="none", since_ts_millis=now - 2 * 86_400_000,
990
+ until_ts_millis=now, limit=1, as_dataframe=False,
991
+ )
992
+ capabilities["minute"] = "available"
993
+ except Exception as exc: # noqa: BLE001
994
+ minute_error, _minute_message = _classify_ftshare_error(exc)
995
+ if minute_error == "invalid_key":
996
+ raise
997
+ capabilities["minute"] = "insufficient_quota" if minute_error == "capability_limited" else minute_error
998
+ _set_ftshare_capabilities(capabilities)
999
+ return {
1000
+ "ok": True,
1001
+ "message": _ftshare_capability_message(
1002
+ capabilities, persistent=bool(_read_persisted_ftshare_key())
1003
+ ),
1004
+ "configured": bool((os.environ.get("FTSHARE_API_KEY") or "").strip()),
1005
+ "capabilities": capabilities,
1006
+ "status": "available" if capabilities["minute"] == "available" else "partial",
1007
+ }
1008
+ except Exception as exc: # noqa: BLE001
1009
+ error, message = _classify_ftshare_error(exc)
1010
+ _set_ftshare_capabilities(capabilities)
1011
+ return {
1012
+ "ok": False,
1013
+ "error": error,
1014
+ "message": message,
1015
+ "configured": bool((os.environ.get("FTSHARE_API_KEY") or "").strip()),
1016
+ "capabilities": capabilities,
1017
+ }
1018
+
1019
+
1020
+ def _classify_ftshare_error(exc: Exception) -> tuple[str, str]:
1021
+ """Turn provider auth failures into stable machine codes and Chinese text."""
1022
+ raw = str(exc or "").strip()
1023
+ configured_key = _valid_ftshare_key(os.environ.get("FTSHARE_API_KEY"))
1024
+ safe_raw = raw.replace(configured_key, "<redacted>") if configured_key else raw
1025
+ status_match = re.search(r"HTTP(?:\s+Error)?\s+(\d{3})", safe_raw, re.IGNORECASE)
1026
+ status = status_match.group(1) if status_match else ""
1027
+ if status in {"401", "403"}:
1028
+ if re.search(r"未携带|缺少|missing|required|not provided", raw, re.IGNORECASE):
1029
+ return "auth_required", "FTShare 未收到 API Key,请检查配置后重试。"
1030
+ if re.search(r"格式|非法|invalid|malformed", raw, re.IGNORECASE):
1031
+ return "invalid_key", "FTShare API Key 校验失败,请检查 Key 是否完整后重试。"
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 当前凭据或套餐无权访问此项数据,请检查该接口的访问权限。"
1036
+ return "auth_required", "FTShare API Key 未通过校验,请检查配置或数据权限。"
1037
+ if status == "429":
1038
+ return "rate_limited", "FTShare 请求过于频繁,请稍后重试。"
1039
+ if status.startswith("5"):
1040
+ return "upstream_error", "FTShare 服务暂时不可用,请稍后重试。"
1041
+ if isinstance(exc, (TimeoutError, ConnectionError)) or re.search(
1042
+ r"timed out|timeout|connection reset|connection refused|name or service not known",
1043
+ safe_raw,
1044
+ re.IGNORECASE,
1045
+ ):
1046
+ return "upstream_unavailable", "FTShare 暂时无法连接,请检查网络后重试。"
1047
+ if isinstance(exc, (AttributeError, TypeError)) or re.search(
1048
+ r"unexpected keyword|no attribute|contract mismatch", safe_raw, re.IGNORECASE
1049
+ ):
1050
+ return "sdk_contract_mismatch", "FTShare SDK 与当前接口契约不一致,请升级插件后重试。"
1051
+ if status == "405":
1052
+ return "ftshare_endpoint_unavailable", "FTShare 分钟线校验接口暂不可用,请稍后重试。"
1053
+ if status == "400":
1054
+ return "request_rejected", "FTShare 接口拒绝了请求,请检查标的市场、代码和参数;这不表示 API Key 无效。"
1055
+ return "ftshare_connection_failed", f"FTShare 连接失败:{safe_raw}"
1056
+
1057
+
1058
+ def _interval_to_sdk(unit: str) -> str:
1059
+ u = (unit or "day").strip().lower()
1060
+ return {
1061
+ "minute": "Minute",
1062
+ "day": "Day",
1063
+ "week": "Week",
1064
+ "month": "Month",
1065
+ # FTShare exposes Month and Year, but not a native quarter enum.
1066
+ # Quarter bars are aggregated from monthly candles below.
1067
+ "quarter": "Month",
1068
+ "year": "Year",
1069
+ }.get(u, "Day")
1070
+
1071
+
1072
+ def _adjust_to_sdk(adjust: str) -> str:
1073
+ value = normalize_adjustment(adjust)
1074
+ if value is None:
1075
+ raise ValueError("unsupported_adjustment")
1076
+ return value
1077
+
1078
+
1079
+ def _normalize_raw(raw: Any) -> list[dict[str, Any]]:
1080
+ """Single ingest path shared with calc/draw (close-time bar, seconds)."""
1081
+ from core.rows import normalize_rows
1082
+
1083
+ # Some FTShare POST endpoints return the decoded service envelope even
1084
+ # with ``as_dataframe=False``; GET endpoints commonly return the extracted
1085
+ # list. Keep the SDK-specific envelope handling at this adapter boundary.
1086
+ payload: Any = raw
1087
+ if isinstance(raw, Mapping):
1088
+ data = raw.get("data")
1089
+ if isinstance(data, list):
1090
+ payload = data
1091
+ elif isinstance(data, Mapping):
1092
+ for key in ("items", "records", "results", "data"):
1093
+ if isinstance(data.get(key), list):
1094
+ payload = data[key]
1095
+ break
1096
+ return normalize_rows(payload)
1097
+
1098
+
1099
+ def _normalize_realtime_minute_raw(raw: Any) -> list[dict[str, Any]]:
1100
+ """Unwrap v4's per-symbol ``items`` envelope into canonical minute rows."""
1101
+ payload: Any = raw
1102
+ if isinstance(raw, Mapping):
1103
+ payload = raw.get("data", raw)
1104
+ if isinstance(payload, list):
1105
+ flattened: list[Any] = []
1106
+ for item in payload:
1107
+ if isinstance(item, Mapping) and isinstance(item.get("items"), list):
1108
+ flattened.extend(item["items"])
1109
+ else:
1110
+ flattened.append(item)
1111
+ return _normalize_raw(flattened)
1112
+ return _normalize_raw(payload)
1113
+
1114
+
1115
+ _CN_SYMBOL_SUFFIXES = {
1116
+ "SH": "XSHG",
1117
+ "XSHG": "XSHG",
1118
+ "SZ": "XSHE",
1119
+ "XSHE": "XSHE",
1120
+ "BJ": "BJSE",
1121
+ "BJSE": "BJSE",
1122
+ }
1123
+
1124
+
1125
+ def _canonical_market_symbol(symbol: str) -> str:
1126
+ """Normalize explicit exchange suffixes without guessing a market.
1127
+
1128
+ A bare six-digit code is intentionally left bare: for example ``000688``
1129
+ can mean the 科创50 index or 国城矿业. Only an explicit exchange-qualified
1130
+ identifier is safe to route to an index endpoint or an equity endpoint.
1131
+ """
1132
+ raw = str(symbol or "").strip().upper()
1133
+ code, separator, suffix = raw.rpartition(".")
1134
+ if separator and code and suffix in _CN_SYMBOL_SUFFIXES:
1135
+ return f"{code}.{_CN_SYMBOL_SUFFIXES[suffix]}"
1136
+ if separator and suffix in {"HK", "HKG"} and code.isdigit() and 1 <= len(code) <= 5:
1137
+ return f"{code.zfill(5)}.HK"
1138
+ if separator and suffix in {"US", "NASDAQ", "NYSE"} and re.fullmatch(r"[A-Z][A-Z0-9._-]{0,15}", code):
1139
+ return f"{code}.US"
1140
+ return raw
1141
+
1142
+
1143
+ def _broad_index_for_symbol(symbol: str) -> Mapping[str, str] | None:
1144
+ return CN_BROAD_INDEX_BY_SYMBOL.get(_canonical_market_symbol(symbol))
1145
+
1146
+
1147
+ def _ambiguous_broad_index_result(symbol: str) -> dict[str, Any] | None:
1148
+ """Require an exchange suffix where a bare code can select a broad index."""
1149
+ raw = str(symbol or "").strip().upper()
1150
+ if "." in raw or len(raw) != 6 or not raw.isdigit():
1151
+ return None
1152
+ matches = [item for item in CN_BROAD_INDEXES if item["symbol"].split(".", 1)[0] == raw]
1153
+ if not matches:
1154
+ return None
1155
+ index = matches[0]
1156
+ return {
1157
+ "ok": False,
1158
+ "error": "ambiguous_symbol",
1159
+ "error_code": "ambiguous_symbol",
1160
+ "message": (
1161
+ f"{raw} is ambiguous: it can identify the {index['name']} broad index "
1162
+ "or an exchange-listed stock. Use a full exchange-qualified symbol."
1163
+ ),
1164
+ "symbol": raw,
1165
+ "index_candidate": {"symbol": index["symbol"], "name": index["name"], "market": "CN_INDEX"},
1166
+ "next_action": "Use the canonical index symbol, or provide the stock's explicit .SH/.SZ/.BJ suffix.",
1167
+ "retryable": False,
1168
+ }
1169
+
1170
+
1171
+ def _index_candles_provider_unavailable_result(symbol: str) -> dict[str, Any]:
1172
+ """Fail closed rather than silently returning a same-code A-share stock."""
1173
+ index = _broad_index_for_symbol(symbol)
1174
+ assert index is not None
1175
+ canonical_symbol = str(index["symbol"])
1176
+ return {
1177
+ "ok": False,
1178
+ "error": "index_candles_provider_unavailable",
1179
+ "error_code": "index_candles_provider_unavailable",
1180
+ "message": (
1181
+ "The installed FTShare SDK exposes this A-share index identity but not a verified "
1182
+ "A-share index K-line history endpoint. No stock fallback was used, so a same-code "
1183
+ "equity cannot be mislabeled as the index."
1184
+ ),
1185
+ "symbol": canonical_symbol,
1186
+ "name": str(index["name"]),
1187
+ "asset_type": "CN_INDEX",
1188
+ "source": "ftshare",
1189
+ "next_action": "Pass verified index OHLCV rows from a provider that supports this index into draw_kline.",
1190
+ "retryable": False,
1191
+ }
1192
+
1193
+
1194
+ def _exchange_timezone(symbol: str) -> str:
1195
+ """Return the IANA trading timezone used for calendar aggregation."""
1196
+ normalized = str(symbol or "").strip().upper()
1197
+ if normalized.endswith((".HK", ".HKG")) or normalized.startswith("100.HSI"):
1198
+ return "Asia/Hong_Kong"
1199
+ if _is_us_symbol(normalized) or normalized in {"100.NDX", "100.SPX", "100.DJIA"}:
1200
+ return "America/New_York"
1201
+ return "Asia/Shanghai"
1202
+
1203
+
1204
+ def _aggregate_quarters(rows: list[dict[str, Any]], *, timezone_name: str = "Asia/Shanghai") -> list[dict[str, Any]]:
1205
+ """Aggregate normalized month candles into chronological calendar quarters."""
1206
+ grouped: dict[tuple[int, int], list[dict[str, Any]]] = {}
1207
+ for row in rows:
1208
+ timestamp = int(row["time"])
1209
+ date = datetime.fromtimestamp(timestamp, tz=ZoneInfo(timezone_name))
1210
+ key = (date.year, (date.month - 1) // 3 + 1)
1211
+ grouped.setdefault(key, []).append(row)
1212
+
1213
+ quarters: list[dict[str, Any]] = []
1214
+ for key in sorted(grouped):
1215
+ bucket = sorted(grouped[key], key=lambda item: int(item["time"]))
1216
+ quarters.append(
1217
+ {
1218
+ "time": int(bucket[-1]["time"]),
1219
+ "open": float(bucket[0]["open"]),
1220
+ "high": max(float(item["high"]) for item in bucket),
1221
+ "low": min(float(item["low"]) for item in bucket),
1222
+ "close": float(bucket[-1]["close"]),
1223
+ "volume": sum(float(item.get("volume") or 0) for item in bucket),
1224
+ }
1225
+ )
1226
+ return quarters
1227
+
1228
+
1229
+ def _is_us_symbol(symbol: str) -> bool:
1230
+ normalized = str(symbol or "").strip().upper()
1231
+ return normalized.endswith((".US", ".NASDAQ", ".NYSE"))
1232
+
1233
+
1234
+ def _is_hk_symbol(symbol: str) -> bool:
1235
+ normalized = str(symbol or "").strip().upper()
1236
+ return normalized.endswith((".HK", ".HKG"))
1237
+
1238
+
1239
+ def _is_etf_symbol(symbol: str) -> bool:
1240
+ """Return whether an explicitly-qualified mainland symbol is an ETF.
1241
+
1242
+ The FTShare ETF endpoint documents Shanghai 5xxxxx and Shenzhen 15/16xxxx
1243
+ identifiers. We deliberately require the exchange suffix: a bare
1244
+ six-digit code can be a mutual fund, an equity, or an ETF and must not be
1245
+ guessed into the wrong data product.
1246
+ """
1247
+ normalized = _canonical_market_symbol(symbol)
1248
+ code, separator, suffix = normalized.rpartition(".")
1249
+ if not separator or not re.fullmatch(r"\d{6}", code):
1250
+ return False
1251
+ return (suffix == "XSHG" and code.startswith("5")) or (
1252
+ suffix == "XSHE" and code.startswith(("15", "16"))
1253
+ )
1254
+
1255
+
1256
+ def _etf_minute_symbol(symbol: str) -> str:
1257
+ """Use the short exchange suffix required by FTShare's ETF minute API."""
1258
+ normalized = _canonical_market_symbol(symbol)
1259
+ if normalized.endswith(".XSHG"):
1260
+ return f"{normalized[:-5]}.SH"
1261
+ if normalized.endswith(".XSHE"):
1262
+ return f"{normalized[:-5]}.SZ"
1263
+ return normalized
1264
+
1265
+
1266
+ def _bare_us_symbol(symbol: str) -> str:
1267
+ return _canonical_market_symbol(symbol).removesuffix(".US")
1268
+
1269
+
1270
+ def _aggregate_interval(
1271
+ rows: list[dict[str, Any]], interval: str, *, timezone_name: str = "America/New_York"
1272
+ ) -> list[dict[str, Any]]:
1273
+ """Aggregate normalized daily rows for a source with daily-only history."""
1274
+ normalized = str(interval or "day").strip().lower()
1275
+ if normalized == "day":
1276
+ return list(rows)
1277
+ grouped: dict[tuple[int, ...], list[dict[str, Any]]] = {}
1278
+ for row in rows:
1279
+ date = datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(timezone_name))
1280
+ if normalized == "week":
1281
+ iso = date.isocalendar()
1282
+ key = (iso.year, iso.week)
1283
+ elif normalized == "month":
1284
+ key = (date.year, date.month)
1285
+ elif normalized == "quarter":
1286
+ key = (date.year, (date.month - 1) // 3 + 1)
1287
+ else:
1288
+ key = (date.year,)
1289
+ grouped.setdefault(key, []).append(row)
1290
+ aggregated: list[dict[str, Any]] = []
1291
+ for key in sorted(grouped):
1292
+ bucket = sorted(grouped[key], key=lambda item: int(item["time"]))
1293
+ aggregated.append(
1294
+ {
1295
+ "time": int(bucket[-1]["time"]),
1296
+ "open": float(bucket[0]["open"]),
1297
+ "high": max(float(item["high"]) for item in bucket),
1298
+ "low": min(float(item["low"]) for item in bucket),
1299
+ "close": float(bucket[-1]["close"]),
1300
+ "volume": sum(float(item.get("volume") or 0.0) for item in bucket),
1301
+ }
1302
+ )
1303
+ return aggregated
1304
+
1305
+
1306
+ def _fetch_us_daily_candles(market: Any, symbol: str, limit: int) -> Any:
1307
+ """Use FTShare's dedicated US history endpoint instead of stock_candlesticks.
1308
+
1309
+ The generic endpoint is optimized for mainland symbols and can return an
1310
+ incomplete US slice. With neither date supplied the live endpoint returns
1311
+ only its latest snapshot, despite the documented full-history default.
1312
+ Supply only the upper bound: the three-day limit applies when BOTH dates
1313
+ are set. Page through that history and trim after interval aggregation.
1314
+ """
1315
+ raw = market.eastmoney_us_stock_daily_ohlc(
1316
+ stock_code=_bare_us_symbol(symbol),
1317
+ end_date=datetime.now(ZoneInfo("America/New_York")).date().isoformat(),
1318
+ all_pages=True,
1319
+ page_size=200,
1320
+ as_dataframe=False,
1321
+ )
1322
+ # This endpoint emits exchange calendar dates, not timestamps. The shared
1323
+ # date-only ingest defaults to China and would shift US bars back a day.
1324
+ if isinstance(raw, list):
1325
+ raw = [dict(row) if isinstance(row, dict) else row for row in raw]
1326
+ for row in raw:
1327
+ if not isinstance(row, dict) or not row.get("date"):
1328
+ continue
1329
+ try:
1330
+ trading_day = datetime.strptime(str(row["date"])[:10], "%Y-%m-%d")
1331
+ row["time"] = int(trading_day.replace(hour=16, tzinfo=ZoneInfo("America/New_York")).timestamp())
1332
+ except (TypeError, ValueError):
1333
+ continue
1334
+ return raw
1335
+
1336
+
1337
+ def _fetch_hk_candles(market: Any, symbol: str, interval: str, limit: int, adjust: str) -> Any:
1338
+ """Use FTShare's dedicated HK history endpoint when it supports the period."""
1339
+ method = getattr(market, "hk_candlesticks", None)
1340
+ if not callable(method):
1341
+ raise AttributeError("FTShare hk_candlesticks is unavailable")
1342
+ normalized = str(interval or "day").strip().lower()
1343
+ if normalized not in {"day", "week", "month", "quarter", "year"}:
1344
+ raise ValueError(f"HK endpoint does not support {normalized}")
1345
+ today = datetime.now(ZoneInfo("Asia/Hong_Kong")).date()
1346
+ # Fetch HK daily bars and aggregate locally. Native long-period responses
1347
+ # have been observed stale; daily history is current and also gives one
1348
+ # consistent source for week/month/quarter/year indicators.
1349
+ days_per_bar = {"day": 1.5, "week": 8, "month": 32, "quarter": 92, "year": 370}[normalized]
1350
+ lookback_days = max(30, int(int(limit) * days_per_bar))
1351
+ adjustment = _adjust_to_sdk(adjust) or "none"
1352
+ # FTShare's HK endpoint accepts compact exchange dates (YYYYMMDD), unlike
1353
+ # its US endpoint. ISO dates yield a 400 even when the account has access.
1354
+ raw = method(
1355
+ trade_code=symbol,
1356
+ interval_unit="day",
1357
+ since_date=(today - timedelta(days=lookback_days)).strftime("%Y%m%d"),
1358
+ until_date=today.strftime("%Y%m%d"),
1359
+ interval_value=1,
1360
+ # ``limit`` applies to the daily source rows, not the requested
1361
+ # aggregate bars. Preserve sufficient complete periods before local
1362
+ # aggregation (for example 20 weeks need far more than 20 daily rows).
1363
+ limit=max(2, min(4000, lookback_days)),
1364
+ adjust_kind=adjustment,
1365
+ as_dataframe=False,
1366
+ )
1367
+ # The current FTShare HK endpoint can return a successful but stale archive
1368
+ # response (for example, 2010 bars for a live request). Treat that as an
1369
+ # upstream failure so the view never labels unrelated stale data as current.
1370
+ rows = _normalize_raw(raw)
1371
+ if len(rows) < 2:
1372
+ raise RuntimeError("FTShare HK history returned fewer than two valid candles")
1373
+ latest = datetime.fromtimestamp(int(rows[-1]["time"]), tz=ZoneInfo("Asia/Hong_Kong")).date()
1374
+ if latest < datetime.now(ZoneInfo("Asia/Hong_Kong")).date() - timedelta(days=45):
1375
+ raise RuntimeError(f"FTShare HK history is stale (latest bar: {latest.isoformat()})")
1376
+ return raw
1377
+
1378
+
1379
+ def _until_ms() -> int:
1380
+ # Stable-ish now; callers can still pass their own window via limit.
1381
+ return int(time.time() * 1000)
1382
+
1383
+
1384
+ def _history_since_ms(limit: int, interval: str) -> int:
1385
+ """Return a conservative single-page start within FTShare's 12-month cap."""
1386
+ normalized = str(interval or "day").strip().lower()
1387
+ days_per_bar = {
1388
+ "day": 3,
1389
+ "week": 10,
1390
+ "month": 32,
1391
+ "quarter": 92,
1392
+ "year": 370,
1393
+ }.get(normalized, 3)
1394
+ lookback_days = min(360, max(2, int(limit or 220) * days_per_bar))
1395
+ return max(_until_ms() - lookback_days * 86_400_000, 0)
1396
+
1397
+
1398
+ def _fetch_calendar_history(
1399
+ fetch_page: Any, market: Any, *, symbol: str, interval: str,
1400
+ adjust_kind: str, limit: int,
1401
+ ) -> list[dict[str, Any]]:
1402
+ """Page disjoint daily history, then aggregate once in exchange time.
1403
+
1404
+ Provider weekly/monthly bars can represent overlapping partial periods at
1405
+ page boundaries. They cannot safely be summed or timestamp-deduplicated.
1406
+ One extra output bucket ensures the oldest requested period is complete.
1407
+ Empty history, no progress, and bounded work are the only stop conditions;
1408
+ a short page is not evidence that older history does not exist.
1409
+ """
1410
+ requested = max(2, int(limit or 220))
1411
+ until_ms = _until_ms()
1412
+ by_time: dict[int, dict[str, Any]] = {}
1413
+ aggregated: list[dict[str, Any]] = []
1414
+ for _page in range(64):
1415
+ raw = fetch_page(
1416
+ market, symbol=symbol, interval_unit="Day", interval_value=1,
1417
+ adjust_kind=adjust_kind, since_ts_millis=max(0, until_ms - 360 * 86_400_000),
1418
+ # FTShare stock/index candlesticks accepts at most 1,000 rows per
1419
+ # request. Keep long ranges paged rather than sending the former
1420
+ # 4,000-row local display limit to the provider (HTTP 400).
1421
+ until_ts_millis=until_ms, limit=1000, as_dataframe=False,
1422
+ )
1423
+ chunk = _normalize_raw(raw)
1424
+ if not chunk:
1425
+ break
1426
+ previous_count = len(by_time)
1427
+ by_time.update((int(row["time"]), row) for row in chunk)
1428
+ daily = [by_time[key] for key in sorted(by_time)]
1429
+ aggregated = _aggregate_interval(daily, interval, timezone_name=_exchange_timezone(symbol))
1430
+ target = requested if interval == "day" else requested + 1
1431
+ if len(aggregated) >= target:
1432
+ break
1433
+ next_until = min(int(row["time"]) for row in chunk) * 1000 - 1
1434
+ if len(by_time) == previous_count or next_until <= 0 or next_until >= until_ms:
1435
+ break
1436
+ until_ms = next_until
1437
+ return aggregated[-requested:]
1438
+
1439
+
1440
+ def _fetch_generic_history(
1441
+ market: Any,
1442
+ *,
1443
+ symbol: str,
1444
+ interval: str,
1445
+ interval_unit: str,
1446
+ interval_value: int,
1447
+ adjust_kind: str,
1448
+ limit: int,
1449
+ ) -> list[dict[str, Any]]:
1450
+ """Fetch authoritative daily rows before any calendar aggregation."""
1451
+ return _fetch_calendar_history(
1452
+ _ftshare_stock_candlesticks, market, symbol=symbol, interval=interval,
1453
+ adjust_kind=adjust_kind, limit=limit,
1454
+ )
1455
+
1456
+
1457
+ def _fetch_etf_history(
1458
+ market: Any,
1459
+ *,
1460
+ symbol: str,
1461
+ interval: str,
1462
+ adjust_kind: str,
1463
+ limit: int,
1464
+ ) -> list[dict[str, Any]]:
1465
+ """Fetch ETF daily bars before calendar aggregation, just like equities."""
1466
+ return _fetch_calendar_history(
1467
+ _ftshare_etf_candlesticks, market, symbol=symbol, interval=interval,
1468
+ adjust_kind=adjust_kind, limit=limit,
1469
+ )
1470
+
1471
+
1472
+ def _fetch_global_index_history(
1473
+ market: Any,
1474
+ *,
1475
+ symbol: str,
1476
+ interval: str,
1477
+ limit: int,
1478
+ ) -> list[dict[str, Any]]:
1479
+ """Fetch FTShare global-index history (endpoint global_index_daily_kline).
1480
+
1481
+ The endpoint only serves daily bars for secids like ``100.HSI`` /
1482
+ ``100.NDX``. Larger periods are aggregated by the caller from this daily
1483
+ series, so we fetch a generous daily window and let the shared
1484
+ ``_aggregate_interval`` trim to the requested bar count.
1485
+
1486
+ Returns SDK rows (pre-normalization), newest-first as delivered.
1487
+ """
1488
+ requested = max(2, int(limit or 220))
1489
+ # Daily lookback factor per requested period: ~1 day bar per calendar day
1490
+ # is not enough for weekly/monthly aggregation, so overfetch generously.
1491
+ days_per_bar = {
1492
+ "day": 2,
1493
+ "week": 12,
1494
+ "month": 50,
1495
+ "quarter": 150,
1496
+ "year": 560,
1497
+ }.get(str(interval or "day").strip().lower(), 2)
1498
+ daily_limit = min(5000, max(requested * days_per_bar, requested + 10))
1499
+ return market.global_index_daily_kline(
1500
+ secid=symbol,
1501
+ limit=daily_limit,
1502
+ as_dataframe=False,
1503
+ )
1504
+
1505
+
1506
+ def _fetch_index_history(
1507
+ market: Any,
1508
+ *,
1509
+ symbol: str,
1510
+ interval: str,
1511
+ interval_unit: str,
1512
+ interval_value: int,
1513
+ adjust_kind: str,
1514
+ limit: int,
1515
+ ) -> list[dict[str, Any]]:
1516
+ """Page A-share index daily-or-larger history (SDK endpoint index_candlesticks).
1517
+
1518
+ Same daily pagination and exchange-calendar aggregation as the stock path.
1519
+ """
1520
+ return _fetch_calendar_history(
1521
+ _ftshare_index_candlesticks, market, symbol=symbol, interval=interval,
1522
+ adjust_kind=adjust_kind, limit=limit,
1523
+ )
1524
+
1525
+
1526
+ def _fetch_index_history_minutes(
1527
+ market: Any,
1528
+ *,
1529
+ symbol: str,
1530
+ interval_value: int,
1531
+ adjust_kind: str,
1532
+ sessions: int,
1533
+ limit: int,
1534
+ exchange_timezone: str,
1535
+ ) -> list[dict[str, Any]]:
1536
+ """Page A-share index minute history session-by-session (SDK index_minutes).
1537
+
1538
+ Mirrors the stock minute walker; availability depends on the plan (the free
1539
+ tier returns 401 auth_required and is surfaced as a capability message).
1540
+ """
1541
+ cutoff = _latest_session_close_millis(exchange_timezone)
1542
+ unique: dict[int, dict[str, Any]] = {}
1543
+ page_window_days = 2
1544
+ max_pages = max(8, sessions * 3 + 2)
1545
+ for _page in range(max_pages):
1546
+ page = _ftshare_index_minutes(
1547
+ market,
1548
+ symbol=symbol,
1549
+ interval_value=interval_value,
1550
+ since_ts_millis=max(0, cutoff - page_window_days * 86_400_000),
1551
+ until_ts_millis=cutoff,
1552
+ limit=min(500, max(limit, sessions * 250)),
1553
+ as_dataframe=False,
1554
+ )
1555
+ chunk = _complete_intraday_bars(_normalize_raw(page), interval_value=interval_value)
1556
+ complete_dates = _complete_intraday_session_dates(
1557
+ chunk, timezone_name=exchange_timezone, interval_value=interval_value,
1558
+ )
1559
+ chunk = [
1560
+ row for row in chunk
1561
+ if datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date() in complete_dates
1562
+ ]
1563
+ if not chunk:
1564
+ # Empty pages also occur on exchange holidays. Advance by whole
1565
+ # sessions rather than retrying a boundary timestamp indefinitely.
1566
+ cutoff = _previous_weekday_session_close_millis(
1567
+ datetime.fromtimestamp(cutoff / 1000, tz=ZoneInfo(exchange_timezone)).date(),
1568
+ exchange_timezone,
1569
+ )
1570
+ continue
1571
+ chunk_dates = {
1572
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
1573
+ for row in chunk
1574
+ }
1575
+ known_dates = {
1576
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
1577
+ for row in unique.values()
1578
+ }
1579
+ if known_dates and not (chunk_dates - known_dates):
1580
+ break
1581
+ for row in chunk:
1582
+ unique[int(row["time"])] = row
1583
+ local_dates = {
1584
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
1585
+ for row in unique.values()
1586
+ }
1587
+ if len(local_dates) >= sessions:
1588
+ break
1589
+ # Do not page from the first 5-minute bar (09:35). FTShare then
1590
+ # returns only an overlapping 09:30--09:35 boundary bar. Page from
1591
+ # the preceding trading-day close so every request starts on a clean
1592
+ # session boundary and can contribute complete historical days.
1593
+ cutoff = _previous_weekday_session_close_millis(min(chunk_dates), exchange_timezone)
1594
+ return list(unique.values())
1595
+
1596
+
1597
+ def _symbol_name(market: Any, symbol: str) -> str:
1598
+ normalized = str(symbol or "").strip().upper()
1599
+ # Resolving a bare code costs a live HTTP round trip. Market sections such
1600
+ # as the 龙虎榜 list repeat the same symbols on every refresh, so memoize
1601
+ # the answer for the life of the process instead of paying that cost once
1602
+ # per row per render. Negative results are cached too: a code the provider
1603
+ # does not know would otherwise be retried on every single refresh.
1604
+ if normalized in _symbol_name_cache:
1605
+ return _symbol_name_cache[normalized]
1606
+ resolved = _resolve_symbol_name(market, symbol)
1607
+ # The local directory seed is authoritative and tiny; never let a provider
1608
+ # answer evict those entries from the bounded cache.
1609
+ if len(_symbol_name_cache) >= _SYMBOL_NAME_CACHE_MAX_ENTRIES:
1610
+ _symbol_name_cache.clear()
1611
+ _symbol_name_cache[normalized] = resolved
1612
+ return resolved
1613
+
1614
+
1615
+ def _resolve_symbol_name(market: Any, symbol: str) -> str:
1616
+ normalized = str(symbol or "").strip().upper()
1617
+ # Codes such as 000001 are ambiguous in vendor search (it can resolve to
1618
+ # 平安银行). The candle request has already selected the index endpoint, so
1619
+ # retain the canonical index identity instead of relabeling its chart.
1620
+ if normalized in COMPARISON_INDEX_NAMES:
1621
+ return COMPARISON_INDEX_NAMES[normalized]
1622
+ for item in _SYMBOL_DIRECTORY_SEED:
1623
+ if normalized == str(item["symbol"]).upper():
1624
+ return str(item["name"])
1625
+ try:
1626
+ cached = _read_symbol_directory_cache()
1627
+ code = str(symbol or "").split(".")[0]
1628
+ for item in list(cached.get("items") or []) if isinstance(cached, Mapping) else []:
1629
+ if not isinstance(item, Mapping):
1630
+ continue
1631
+ candidate_symbol = _canonical_market_symbol(
1632
+ _canonical_directory_symbol(
1633
+ item.get("symbol") or item.get("code") or item.get("stock_code"),
1634
+ market=item.get("market") or item.get("board"),
1635
+ )
1636
+ )
1637
+ candidate_name = str(item.get("name") or item.get("stock_name") or "").strip()
1638
+ if candidate_symbol == normalized and candidate_name and candidate_name.upper() not in {normalized, code.upper()}:
1639
+ return candidate_name
1640
+ except Exception:
1641
+ pass
1642
+ # The directory refresh runs in the background. Resolve a just-opened
1643
+ # mainland symbol immediately when it is not in the previous snapshot,
1644
+ # instead of making the chart wait for a full directory rebuild.
1645
+ if market is not None and re.fullmatch(r"\d{6}\.(XSHG|XSHE|BJSE)", normalized):
1646
+ try:
1647
+ lookup = getattr(market, "company_list", None)
1648
+ rows = lookup(stock_code=normalized.split(".", 1)[0], as_dataframe=False) if callable(lookup) else []
1649
+ for item in _rows_from_directory_response(rows):
1650
+ candidate_name = str(item.get("stock_name") or item.get("name") or "").strip()
1651
+ if candidate_name and candidate_name.upper() not in {normalized, normalized.split(".", 1)[0]}:
1652
+ return candidate_name
1653
+ except Exception:
1654
+ pass
1655
+ # Some newly listed or renamed securities are not yet in the company
1656
+ # directory endpoint. The documented security search is a narrow,
1657
+ # exact-code fallback for presentation labels only.
1658
+ try:
1659
+ search = getattr(market, "search", None)
1660
+ rows = search(query=normalized.split(".", 1)[0], limit=1, as_dataframe=False) if callable(search) else []
1661
+ for item in _workspace_rows(rows):
1662
+ candidate_name = str(_workspace_value(item, "name", "stock_name", "symbol_name") or "").strip()
1663
+ if candidate_name and candidate_name.upper() not in {normalized, normalized.split(".", 1)[0]}:
1664
+ return candidate_name
1665
+ except Exception:
1666
+ pass
1667
+ return symbol
1668
+
1669
+
1670
+ def _ftshare_unavailable_result() -> dict[str, Any]:
1671
+ """Return one consistent optional-dependency error for data tools.
1672
+
1673
+ The message intentionally exposes no interpreter path or candidate
1674
+ directory list; host-specific diagnostics are intentionally not returned.
1675
+ """
1676
+ return {
1677
+ "ok": False,
1678
+ "error": "ftshare_not_installed",
1679
+ "message": (
1680
+ "ftshare is not importable in this MCP process. "
1681
+ "Install the FTShare SDK with the interpreter that starts this MCP "
1682
+ "(see scripts/bootstrap.sh), or supply your own OHLCV rows through "
1683
+ "analyze_kline_rows."
1684
+ ),
1685
+ }
1686
+
1687
+
1688
+ def _candle_cache_key(
1689
+ symbol: str, interval: str, interval_value: int, session_count: int, limit: int, adjust: str,
1690
+ transport: str = "auto",
1691
+ ) -> tuple[str, str, int, int, int, str, str]:
1692
+ return (
1693
+ str(symbol).strip().upper(),
1694
+ str(interval).strip().lower(),
1695
+ int(interval_value),
1696
+ int(session_count),
1697
+ int(limit),
1698
+ str(adjust).strip().lower(),
1699
+ str(transport or "auto").strip().lower(),
1700
+ )
1701
+
1702
+
1703
+ def _cache_candles(key: tuple[str, str, int, int, int, str, str], payload: dict[str, Any]) -> None:
1704
+ if payload.get("ok") and isinstance(payload.get("rows"), list) and len(payload["rows"]) >= 2:
1705
+ _candle_cache[key] = (time.time(), deepcopy(payload))
1706
+
1707
+
1708
+ def _compatible_candle_cache_entry(
1709
+ key: tuple[str, str, int, int, int, str, str],
1710
+ ) -> tuple[tuple[str, str, int, int, int, str, str], tuple[float, dict[str, Any]]] | None:
1711
+ """Return the exact or smallest compatible larger candle response."""
1712
+ cached = _candle_cache.get(key)
1713
+ if cached:
1714
+ return key, cached
1715
+
1716
+ # A larger daily response contains all history needed by a smaller view.
1717
+ # Limit is intentionally the only relaxed part of the cache key: mixing
1718
+ # different intervals, sessions, or adjustments would change the series.
1719
+ compatible = [
1720
+ (candidate_key, candidate)
1721
+ for candidate_key, candidate in _candle_cache.items()
1722
+ if candidate_key[:5] == key[:5]
1723
+ and candidate_key[5] == key[5]
1724
+ and candidate_key[6] == key[6]
1725
+ and candidate_key[4] >= key[4]
1726
+ ]
1727
+ if not compatible:
1728
+ return None
1729
+ return min(compatible, key=lambda item: (item[0][4] - key[4], -item[1][0]))
1730
+
1731
+
1732
+ def _recent_candle_cache(key: tuple[str, str, int, int, int, str, str]) -> dict[str, Any] | None:
1733
+ """Return a compatible provider result only while it is still hot."""
1734
+ match = _compatible_candle_cache_entry(key)
1735
+ if match is None:
1736
+ return None
1737
+ source_key, (cached_at, payload) = match
1738
+ age = max(0, int(time.time() - cached_at))
1739
+ if age > _CANDLE_CACHE_FRESH_SECONDS:
1740
+ return None
1741
+ fresh = deepcopy(payload)
1742
+ fresh.update(
1743
+ {
1744
+ "ok": True,
1745
+ "cached": True,
1746
+ "cache_age_seconds": age,
1747
+ "freshness": "recent_memory_cache",
1748
+ "message": "Using candles fetched moments ago from the in-memory cache.",
1749
+ }
1750
+ )
1751
+ if source_key != key:
1752
+ fresh["cache_source_limit"] = source_key[4]
1753
+ return fresh
1754
+
1755
+
1756
+ def _cached_candle_fallback(
1757
+ key: tuple[str, str, int, int, int, str, str], error: Exception | str
1758
+ ) -> dict[str, Any] | None:
1759
+ match = _compatible_candle_cache_entry(key)
1760
+ if match is None:
1761
+ return None
1762
+ source_key, (cached_at, payload) = match
1763
+ age = max(0, int(time.time() - cached_at))
1764
+ if age > _CANDLE_CACHE_TTL_SECONDS:
1765
+ _candle_cache.pop(source_key, None)
1766
+ return None
1767
+ fallback = deepcopy(payload)
1768
+ fallback.update(
1769
+ {
1770
+ "ok": True,
1771
+ "status": "stale",
1772
+ "cached": True,
1773
+ "cache_age_seconds": age,
1774
+ "freshness": "recent_cached_fallback",
1775
+ "message": "FTShare is temporarily unavailable; showing the most recent cached candles.",
1776
+ "upstream_error": str(error)[:500],
1777
+ }
1778
+ )
1779
+ if source_key != key:
1780
+ fallback["cache_source_limit"] = source_key[4]
1781
+ return fallback
1782
+
1783
+
1784
+ def _symbol_directory_cache_path() -> Path:
1785
+ configured = (os.environ.get("DSH_KLINE_CACHE_DIR") or "").strip()
1786
+ root = Path(configured).expanduser() if configured else Path.home() / ".cache" / "dsh_kline"
1787
+ return root / f"symbol-directory-v{SYMBOL_DIRECTORY_VERSION}.json"
1788
+
1789
+
1790
+ def _read_symbol_directory_cache() -> dict[str, Any] | None:
1791
+ path = _symbol_directory_cache_path()
1792
+ try:
1793
+ payload = json.loads(path.read_text(encoding="utf-8"))
1794
+ except (OSError, ValueError, TypeError):
1795
+ return None
1796
+ if not isinstance(payload, dict) or payload.get("version") != SYMBOL_DIRECTORY_VERSION:
1797
+ return None
1798
+ if not isinstance(payload.get("items"), list):
1799
+ return None
1800
+ return payload
1801
+
1802
+
1803
+ def _write_symbol_directory_cache(payload: dict[str, Any]) -> bool:
1804
+ """Persist the directory snapshot; return True only when it reached disk.
1805
+
1806
+ Previously this swallowed every OSError. A sandbox or read-only runtime
1807
+ then produced a *successful-looking* refresh that never persisted, so the
1808
+ process kept serving a stale snapshot while reporting fresh data. Callers
1809
+ now surface the failure instead of hiding it.
1810
+ """
1811
+ path = _symbol_directory_cache_path()
1812
+ try:
1813
+ path.parent.mkdir(parents=True, exist_ok=True)
1814
+ temporary = path.with_suffix(".tmp")
1815
+ temporary.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
1816
+ temporary.replace(path)
1817
+ return True
1818
+ except OSError as exc:
1819
+ # A read-only runtime can still serve the fetched directory to this
1820
+ # session, but the caller must know it will not survive a restart.
1821
+ payload["persisted"] = False
1822
+ payload["persist_error"] = f"{type(exc).__name__}: {exc}"
1823
+ return False
1824
+
1825
+
1826
+ def _rows_from_directory_response(raw: Any, *, _depth: int = 0) -> list[Mapping[str, Any]]:
1827
+ """Extract provider rows from the bounded envelope shapes seen in SDK 1.0.7."""
1828
+ if isinstance(raw, list):
1829
+ return [item for item in raw if isinstance(item, Mapping)]
1830
+ if isinstance(raw, Mapping) and _depth < 4:
1831
+ for key in ("records", "items", "data", "results", "rows", "list"):
1832
+ if key not in raw:
1833
+ continue
1834
+ rows = _rows_from_directory_response(raw.get(key), _depth=_depth + 1)
1835
+ if rows:
1836
+ return rows
1837
+ return []
1838
+
1839
+
1840
+ def _canonical_directory_symbol(symbol: Any, *, market: Any = None, default_market: str = "") -> str:
1841
+ """Normalize vendor directory identifiers to the symbols accepted by candles."""
1842
+ value = str(symbol or "").strip()
1843
+ if not value:
1844
+ return ""
1845
+ market_text = str(market or "").strip().upper()
1846
+ default_text = str(default_market or "").strip().upper()
1847
+ # Eastmoney's U.S. directory uses secid=105.AAPL and market=105. The
1848
+ # candle endpoint expects AAPL.US (or another documented U.S. suffix).
1849
+ if default_text == "US" or market_text == "105" or value.upper().startswith("105."):
1850
+ code = value.split(".", 1)[1] if "." in value else value
1851
+ return f"{code.upper()}.US"
1852
+ # FTShare's directory commonly uses .SH/.SZ/.BJ while candle requests and
1853
+ # the browser workspace use .XSHG/.XSHE/.BJSE. Normalize once at the
1854
+ # directory boundary so names resolve consistently everywhere.
1855
+ canonical = _canonical_market_symbol(value)
1856
+ # `company_list` returns bare mainland codes. Here the source is an equity
1857
+ # directory (not an ambiguous user request), so conventional exchange
1858
+ # routing is safe and lets its names match candle symbols.
1859
+ if (default_text == "CN" or market_text == "CN") and re.fullmatch(r"\d{6}", canonical):
1860
+ suffix = "XSHG" if canonical.startswith(("6", "9")) else "BJSE" if canonical.startswith(("4", "8")) else "XSHE"
1861
+ return f"{canonical}.{suffix}"
1862
+ return canonical
1863
+
1864
+
1865
+ def _directory_items(rows: Any, default_market: str) -> list[dict[str, str]]:
1866
+ """Reduce a provider directory to the fields needed for local search."""
1867
+ items: list[dict[str, str]] = []
1868
+ for row in _rows_from_directory_response(rows):
1869
+ symbol = next(
1870
+ (
1871
+ row.get(key)
1872
+ for key in (
1873
+ "symbol", "symbol_id", "stock_code", "code", "secid", "index_code",
1874
+ "ticker", "trade_code", "fund_code",
1875
+ )
1876
+ if row.get(key) not in (None, "")
1877
+ ),
1878
+ None,
1879
+ )
1880
+ name = next(
1881
+ (
1882
+ row.get(key)
1883
+ for key in ("name", "stock_name", "security_name", "index_name", "symbol_name", "fund_name")
1884
+ if row.get(key) not in (None, "")
1885
+ ),
1886
+ None,
1887
+ )
1888
+ if symbol is None or name is None:
1889
+ continue
1890
+ market = row.get("market") or row.get("board") or default_market
1891
+ # Eastmoney splits U.S. listings into several numeric market buckets
1892
+ # (105/106/107). They are all one searchable U.S. universe here.
1893
+ normalized_market = "US" if default_market == "US" or str(market).strip().upper() == "105" else str(market).strip()
1894
+ normalized_symbol = _canonical_directory_symbol(symbol, market=market, default_market=default_market)
1895
+ item = {"symbol": normalized_symbol, "name": str(name).strip(), "market": normalized_market}
1896
+ aliases = row.get("aliases") or row.get("alias")
1897
+ if aliases:
1898
+ item["aliases"] = str(aliases).strip()
1899
+ items.append(item)
1900
+ return [item for item in items if item["symbol"] and item["name"]]
1901
+
1902
+
1903
+ def _merge_symbol_directory(*groups: list[dict[str, str]]) -> list[dict[str, str]]:
1904
+ seen: dict[str, dict[str, str]] = {}
1905
+ merged: list[dict[str, str]] = []
1906
+ for group in groups:
1907
+ for item in group:
1908
+ symbol = str(item.get("symbol") or "").strip()
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
1918
+ continue
1919
+ normalized = {
1920
+ "symbol": symbol,
1921
+ "name": str(item.get("name") or symbol).strip(),
1922
+ "market": str(item.get("market") or "OTHER").strip(),
1923
+ }
1924
+ aliases = str(item.get("aliases") or "").strip()
1925
+ if aliases:
1926
+ normalized["aliases"] = aliases
1927
+ seen[symbol] = normalized
1928
+ merged.append(normalized)
1929
+ return sorted(merged, key=lambda item: (item["market"], item["symbol"]))
1930
+
1931
+
1932
+ def _xlsx_shared_strings(archive: zipfile.ZipFile) -> list[str]:
1933
+ """Read XLSX shared strings using only the standard library."""
1934
+ try:
1935
+ root = ElementTree.fromstring(archive.read("xl/sharedStrings.xml"))
1936
+ except KeyError:
1937
+ return []
1938
+ namespace = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
1939
+ return ["".join(node.text or "" for node in entry.iter(f"{namespace}t")) for entry in root.iter(f"{namespace}si")]
1940
+
1941
+
1942
+ def _xlsx_cell_value(cell: ElementTree.Element, shared_strings: list[str], namespace: str) -> str:
1943
+ value = cell.findtext(f"{namespace}v")
1944
+ if cell.get("t") == "s" and value is not None:
1945
+ try:
1946
+ return shared_strings[int(value)]
1947
+ except (IndexError, ValueError):
1948
+ return ""
1949
+ if cell.get("t") == "inlineStr":
1950
+ return "".join(node.text or "" for node in cell.iter(f"{namespace}t"))
1951
+ return str(value or "")
1952
+
1953
+
1954
+ def _fetch_hk_symbol_directory() -> list[dict[str, str]]:
1955
+ """Read HKEX's official full-security list into a compact HK directory.
1956
+
1957
+ The spreadsheet includes derivatives and debt instruments. Search keeps
1958
+ equities, exchange-traded products and REITs, which are the securities the
1959
+ HK candle route can meaningfully open from this plugin.
1960
+ """
1961
+ last_error: Exception | None = None
1962
+ payload: bytes | None = None
1963
+ for attempt in range(3):
1964
+ try:
1965
+ request = Request(_HK_DIRECTORY_URL, headers={"User-Agent": "dsh-kline/0.2"})
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")
1970
+ break
1971
+ except OSError as exc:
1972
+ last_error = exc
1973
+ if attempt < 2:
1974
+ time.sleep(0.5 * (attempt + 1))
1975
+ if not payload:
1976
+ raise OSError(f"HKEX securities list download failed: {last_error}")
1977
+
1978
+ namespace = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
1979
+ with zipfile.ZipFile(io.BytesIO(payload)) as archive:
1980
+ shared_strings = _xlsx_shared_strings(archive)
1981
+ worksheet = ElementTree.fromstring(archive.read("xl/worksheets/sheet1.xml"))
1982
+
1983
+ header: dict[str, int] | None = None
1984
+ items: list[dict[str, str]] = []
1985
+ for row in worksheet.iter(f"{namespace}row"):
1986
+ values: dict[int, str] = {}
1987
+ for cell in row.iter(f"{namespace}c"):
1988
+ reference = str(cell.get("r") or "")
1989
+ column_letters = "".join(char for char in reference if char.isalpha())
1990
+ if not column_letters:
1991
+ continue
1992
+ column = 0
1993
+ for char in column_letters:
1994
+ column = column * 26 + ord(char.upper()) - ord("A") + 1
1995
+ values[column - 1] = _xlsx_cell_value(cell, shared_strings, namespace).strip()
1996
+ if not values:
1997
+ continue
1998
+ if header is None:
1999
+ reverse = {value: index for index, value in values.items()}
2000
+ if {"Stock Code", "Name of Securities", "Category"} <= set(reverse):
2001
+ header = reverse
2002
+ continue
2003
+ code = values.get(header["Stock Code"], "").strip()
2004
+ name = values.get(header["Name of Securities"], "").strip()
2005
+ category = values.get(header["Category"], "").strip()
2006
+ if code.isdigit() and name and category in _HK_DIRECTORY_CATEGORIES:
2007
+ items.append({"symbol": f"{code.zfill(5)}.HK", "name": name, "market": "HK"})
2008
+ if not items:
2009
+ raise ValueError("HKEX securities list contained no searchable Hong Kong instruments")
2010
+ return items
2011
+
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
+
2043
+ def _fetch_us_symbol_directory(market: Any) -> list[dict[str, str]]:
2044
+ """Page the US directory with pacing instead of triggering a gateway burst."""
2045
+ method = getattr(market, "eastmoney_us_stock_list", None)
2046
+ if not callable(method):
2047
+ raise AttributeError("eastmoney_us_stock_list is unavailable in the installed FTShare client")
2048
+ items: list[dict[str, str]] = []
2049
+ for page in range(1, 200):
2050
+ last_error: Exception | None = None
2051
+ rows: list[Mapping[str, Any]] | None = None
2052
+ for attempt in range(4):
2053
+ try:
2054
+ raw = method(as_dataframe=False, page=page, page_size=200)
2055
+ rows = _rows_from_directory_response(raw)
2056
+ break
2057
+ except Exception as exc: # noqa: BLE001 - normalize FTShare's typed HTTP errors
2058
+ last_error = exc
2059
+ if not _is_retryable_ftshare_status(exc) or attempt == 3:
2060
+ break
2061
+ time.sleep(0.8 * (attempt + 1))
2062
+ if rows is None:
2063
+ raise OSError(f"US directory page {page} failed: {last_error}")
2064
+ items.extend(_directory_items(rows, "US"))
2065
+ if len(rows) < 200:
2066
+ return items
2067
+ # The endpoint permits full pagination but rejects rapid bursts. This
2068
+ # only runs in the deferred directory refresh, never per keystroke.
2069
+ time.sleep(0.8)
2070
+ raise OSError("US directory exceeded the pagination safety limit")
2071
+
2072
+
2073
+ def _directory_coverage(
2074
+ items: list[dict[str, str]],
2075
+ *,
2076
+ complete_markets: set[str] | None = None,
2077
+ partial_markets: set[str] | None = None,
2078
+ ) -> dict[str, dict[str, Any]]:
2079
+ """Expose coverage claims separately from cached search candidates."""
2080
+ complete = complete_markets or set()
2081
+ partial = partial_markets or set()
2082
+ counts: dict[str, int] = {}
2083
+ for item in items:
2084
+ market = str(item.get("market") or "OTHER")
2085
+ counts[market] = counts.get(market, 0) + 1
2086
+ markets = set(counts) | complete | partial
2087
+ return {
2088
+ market: {
2089
+ "count": counts.get(market, 0),
2090
+ "complete": market in complete,
2091
+ "status": "complete" if market in complete else "partial",
2092
+ }
2093
+ for market in sorted(markets)
2094
+ }
2095
+
2096
+
2097
+ def register_symbol_directory(
2098
+ items: Any,
2099
+ *,
2100
+ source: str,
2101
+ source_version: str | None = None,
2102
+ complete_markets: list[str] | None = None,
2103
+ ttl_seconds: int = SYMBOL_DIRECTORY_TTL_SECONDS,
2104
+ ) -> dict[str, Any]:
2105
+ """Persist a directory supplied by a host or another MCP data provider.
2106
+
2107
+ This server intentionally does not invoke peer MCP servers itself. The host
2108
+ fetches its preferred directory and registers it here; the MCP App then
2109
+ searches the local snapshot without another vendor round trip.
2110
+ """
2111
+ provider = str(source or "").strip()
2112
+ if not provider:
2113
+ return {"ok": False, "error": "invalid_source", "message": "source is required"}
2114
+ normalized = _merge_symbol_directory(_directory_items(items, "OTHER"))
2115
+ if not normalized:
2116
+ return {
2117
+ "ok": False,
2118
+ "error": "invalid_directory",
2119
+ "message": "items must include at least one symbol/code and name entry",
2120
+ }
2121
+ if len(normalized) > SYMBOL_DIRECTORY_MAX_ITEMS:
2122
+ return {
2123
+ "ok": False,
2124
+ "error": "directory_too_large",
2125
+ "message": f"directory exceeds {SYMBOL_DIRECTORY_MAX_ITEMS} items",
2126
+ "count": len(normalized),
2127
+ }
2128
+
2129
+ now = int(time.time())
2130
+ ttl = max(300, min(int(ttl_seconds or SYMBOL_DIRECTORY_TTL_SECONDS), 7 * 24 * 60 * 60))
2131
+ claimed_complete = {str(value).strip() for value in (complete_markets or []) if str(value).strip()}
2132
+ payload = {
2133
+ "ok": True,
2134
+ "version": SYMBOL_DIRECTORY_VERSION,
2135
+ "generated_at": now,
2136
+ "expires_at": now + ttl,
2137
+ "items": normalized,
2138
+ "count": len(normalized),
2139
+ "source": "external",
2140
+ "provider_mode": "external",
2141
+ "provider_id": provider[:120],
2142
+ "source_version": str(source_version or "")[:120],
2143
+ "coverage": _directory_coverage(normalized, complete_markets=claimed_complete),
2144
+ "stale": False,
2145
+ "refreshed": True,
2146
+ "needs_external_refresh": False,
2147
+ }
2148
+ _write_symbol_directory_cache(payload)
2149
+ return payload
2150
+
2151
+
2152
+ def symbol_directory(*, force_refresh: bool = False) -> dict[str, Any]:
2153
+ """Refresh a local directory from provider and independent public listings.
2154
+
2155
+ The chart app stores this compact name/code directory in localStorage. It is
2156
+ deliberately separate from quotes and their data-source permissions.
2157
+ """
2158
+ now = int(time.time())
2159
+ cached = _read_symbol_directory_cache()
2160
+ cached_expires = int(cached.get("expires_at") or 0) if cached else 0
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
+ ):
2167
+ # Always merge the built-in seed into a cache hit. The seed carries
2168
+ # curated entries (broad indexes, common ETFs) that provider routes may
2169
+ # not cover at all, and returning the cached snapshot verbatim meant a
2170
+ # seed update could not reach clients until the next full refresh.
2171
+ cached_items = list(cached.get("items") or [])
2172
+ merged = _merge_symbol_directory(cached_items, [dict(item) for item in _SYMBOL_DIRECTORY_SEED])
2173
+ if merged != cached_items:
2174
+ return {
2175
+ **cached,
2176
+ "items": merged,
2177
+ "count": len(merged),
2178
+ "coverage": _directory_coverage(
2179
+ merged,
2180
+ complete_markets={
2181
+ market
2182
+ for market, state in (cached.get("coverage") or {}).items()
2183
+ if isinstance(state, Mapping) and state.get("complete")
2184
+ },
2185
+ ),
2186
+ "ok": True,
2187
+ "stale": False,
2188
+ "refreshed": False,
2189
+ }
2190
+ return {**cached, "ok": True, "stale": False, "refreshed": False}
2191
+
2192
+ # An external directory is host-owned. Keep it searchable when it expires;
2193
+ # only the provider that created it can authoritatively refresh it.
2194
+ if cached and cached.get("provider_mode") == "external":
2195
+ return {
2196
+ **cached,
2197
+ "ok": True,
2198
+ "stale": True,
2199
+ "refreshed": False,
2200
+ "needs_external_refresh": True,
2201
+ "message": "External directory has expired; ask the host to refresh and register a new snapshot.",
2202
+ }
2203
+
2204
+ seed = [dict(item) for item in _SYMBOL_DIRECTORY_SEED]
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
2213
+ source_specs = (
2214
+ # The default endpoint page is intentionally small. Request all pages
2215
+ # so a code-only chart can still be labelled from the local directory
2216
+ # without making a second lookup during rendering.
2217
+ ("company_list", "CN", {"all_pages": True, "page_size": 200}, True),
2218
+ ("index_description_all", "CN_INDEX", {}, True),
2219
+ # Exchange-traded funds live on the fund routes, not company_list, so a
2220
+ # watchlist full of ETFs previously could not resolve any of its names.
2221
+ # `fund_list` is the whole public-fund universe, not the exchange ETF
2222
+ # directory. The dedicated endpoint is compact and has the canonical
2223
+ # exchange symbols used by the ETF candle API.
2224
+ ("etf_description_all", "ETF", {}, True),
2225
+ )
2226
+ fetched_groups: list[list[dict[str, str]]] = []
2227
+ errors: list[str] = ["FTShare client unavailable; public directories remain enabled."] if client_unavailable else []
2228
+ completed_markets: set[str] = set()
2229
+ for method_name, default_market, kwargs, is_complete in source_specs:
2230
+ method = getattr(market, method_name, None)
2231
+ if not callable(method):
2232
+ errors.append(f"{method_name}: unavailable in installed FTShare client")
2233
+ continue
2234
+ # The gateway rate-limits aggressively; a single 429 previously cost the
2235
+ # whole mainland directory until the next scheduled refresh. Retry with
2236
+ # a short backoff so one transient rejection cannot blank the directory.
2237
+ for attempt in range(3):
2238
+ try:
2239
+ group = _directory_items(method(as_dataframe=False, **kwargs), default_market)
2240
+ # A market counts as complete only when rows actually arrived.
2241
+ # ETF labels are a presentation nicety: a plan without fund
2242
+ # access must not hold the mainland directory at the short
2243
+ # retry TTL, so an empty fund route simply stays incomplete.
2244
+ if group and is_complete:
2245
+ completed_markets.add(default_market)
2246
+ fetched_groups.append(group)
2247
+ break
2248
+ except Exception as exc: # noqa: BLE001
2249
+ rate_limited = bool(re.search(r"429", str(exc)))
2250
+ if rate_limited and attempt < 2:
2251
+ time.sleep(0.6 * (attempt + 1))
2252
+ continue
2253
+ errors.append(f"{method_name}: {exc}")
2254
+ break
2255
+
2256
+ # The installed FTShare SDK has no all-HK-instruments endpoint. Keep this
2257
+ # independent from the SDK batch so a temporary public-directory failure
2258
+ # cannot prevent A-share / ETF / US snapshots from being saved.
2259
+ try:
2260
+ hk_group = _fetch_hk_symbol_directory()
2261
+ if hk_group:
2262
+ fetched_groups.append(hk_group)
2263
+ completed_markets.add("HK")
2264
+ except Exception as exc: # noqa: BLE001 - preserve the prior HK snapshot
2265
+ errors.append(f"hk_directory: {exc}")
2266
+
2267
+ try:
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)
2274
+ if us_group:
2275
+ fetched_groups.append(us_group)
2276
+ completed_markets.add("US")
2277
+ except Exception as exc: # noqa: BLE001 - preserve the prior US snapshot
2278
+ errors.append(f"us_directory: {exc}")
2279
+
2280
+ fetched_count = sum(len(group) for group in fetched_groups)
2281
+ # A partial fetch must not be published as a complete 24-hour snapshot.
2282
+ # When one source is rate-limited (an observed HTTP 429 on company_list)
2283
+ # while another succeeds, the old ``if fetched_count`` test still wrote the
2284
+ # result with stale=False and a full-day expiry, which pinned a directory
2285
+ # missing every mainland stock for 24 hours and made search look broken.
2286
+ # Require the primary mainland listing before granting the long TTL.
2287
+ if fetched_count and "CN" in completed_markets:
2288
+ # Refreshes are independent per market. Do not let a rate-limited US
2289
+ # or HK request replace a previously complete market with an empty
2290
+ # list; retain that market's last complete snapshot until its own next
2291
+ # successful refresh.
2292
+ cached_items = list(cached.get("items") or []) if cached else []
2293
+ cached_complete = {
2294
+ market_name
2295
+ for market_name, state in (cached.get("coverage") or {}).items()
2296
+ if isinstance(state, Mapping) and state.get("complete")
2297
+ } if cached else set()
2298
+ retained_items = [
2299
+ item for item in cached_items
2300
+ if str(item.get("market") or "") not in completed_markets
2301
+ ]
2302
+ completed_for_coverage = completed_markets | (cached_complete - completed_markets)
2303
+ items = _merge_symbol_directory(*fetched_groups, retained_items, seed)
2304
+ payload = {
2305
+ "ok": True,
2306
+ "version": SYMBOL_DIRECTORY_VERSION,
2307
+ "generated_at": now,
2308
+ "expires_at": now + SYMBOL_DIRECTORY_TTL_SECONDS,
2309
+ "items": items,
2310
+ "source": "ftshare+public_directories",
2311
+ "provider_mode": "builtin",
2312
+ "provider_id": "FTShare and public symbol directories",
2313
+ "coverage": _directory_coverage(
2314
+ items,
2315
+ complete_markets=completed_for_coverage,
2316
+ partial_markets={item["market"] for item in seed} - completed_for_coverage,
2317
+ ),
2318
+ "stale": False,
2319
+ "refreshed": True,
2320
+ "needs_external_refresh": False,
2321
+ }
2322
+ payload["count"] = len(payload["items"])
2323
+ if errors:
2324
+ payload["warnings"] = errors
2325
+ if not _write_symbol_directory_cache(payload):
2326
+ payload["stale"] = True
2327
+ return payload
2328
+
2329
+ # Incomplete refresh: keep whatever useful rows arrived, but mark the result
2330
+ # stale and retry soon instead of serving a half-empty directory all day.
2331
+ if fetched_count:
2332
+ merged = _merge_symbol_directory(*fetched_groups, list(cached.get("items") or []) if cached else [], seed)
2333
+ partial = {
2334
+ "ok": True,
2335
+ "version": SYMBOL_DIRECTORY_VERSION,
2336
+ "generated_at": now,
2337
+ "expires_at": now + SYMBOL_DIRECTORY_RETRY_SECONDS,
2338
+ "items": merged,
2339
+ "count": len(merged),
2340
+ "source": "public_directories" if market is None else "ftshare+public_directories",
2341
+ "provider_mode": "builtin",
2342
+ "provider_id": "Public symbol directories" if market is None else "FTShare and public symbol directories",
2343
+ "coverage": _directory_coverage(
2344
+ merged,
2345
+ complete_markets=completed_markets,
2346
+ partial_markets={item["market"] for item in seed} - completed_markets,
2347
+ ),
2348
+ "stale": True,
2349
+ "refreshed": False,
2350
+ "needs_external_refresh": False,
2351
+ "message": "Directory sources were only partially available; retrying shortly.",
2352
+ }
2353
+ if errors:
2354
+ partial["refresh_errors"] = errors[:3]
2355
+ _write_symbol_directory_cache(partial)
2356
+ return partial
2357
+
2358
+ items = _merge_symbol_directory(list(cached.get("items") or []) if cached else [], seed)
2359
+ fallback = {
2360
+ "ok": True,
2361
+ "version": SYMBOL_DIRECTORY_VERSION,
2362
+ "generated_at": int(cached.get("generated_at") or now) if cached else now,
2363
+ "expires_at": now + SYMBOL_DIRECTORY_RETRY_SECONDS,
2364
+ "items": items,
2365
+ "count": len(items),
2366
+ "source": "cache" if cached else "seed",
2367
+ "provider_mode": "builtin" if cached else "seed",
2368
+ "provider_id": "FTShare SDK" if cached else "seed",
2369
+ "coverage": _directory_coverage(items, partial_markets={item["market"] for item in seed}),
2370
+ "stale": True,
2371
+ "refreshed": False,
2372
+ "needs_external_refresh": False,
2373
+ "message": "Directory refresh failed; using cached symbols and the built-in directory.",
2374
+ }
2375
+ if errors:
2376
+ fallback["refresh_errors"] = errors[:3]
2377
+ _write_symbol_directory_cache(fallback)
2378
+ return fallback
2379
+
2380
+
2381
+ def search_symbols(query: str, *, limit: int = 8) -> dict[str, Any]:
2382
+ """Search the locally available security directory without a provider call."""
2383
+ q = str(query or "").strip()
2384
+ if not q:
2385
+ return {"ok": False, "error": "invalid_query", "message": "query is required"}
2386
+ lim = max(1, min(int(limit or 8), 20))
2387
+ cache_key = (q.casefold(), lim)
2388
+ now = time.monotonic()
2389
+ cached = _symbol_search_cache.get(cache_key)
2390
+ if cached and now - cached[0] < _SYMBOL_SEARCH_CACHE_TTL_SECONDS:
2391
+ # Return a shallow copy so a caller cannot mutate the shared cache.
2392
+ return {**cached[1], "results": list(cached[1].get("results") or [])}
2393
+
2394
+ query_text = "".join(q.casefold().split())
2395
+ canonical_query = _canonical_market_symbol(q).casefold()
2396
+ # Users should never need to remember our canonical exchange suffixes.
2397
+ # Search all equivalent forms locally: 600036, 600036.SH and
2398
+ # 600036.XSHG are one identity; 700 / 0700 naturally match 00700.HK.
2399
+ query_forms = {query_text, canonical_query}
2400
+ canonical_code = canonical_query.split(".", 1)[0]
2401
+ if canonical_code:
2402
+ query_forms.add(canonical_code)
2403
+ # Hong Kong is normally quoted without the leading zero (e.g. ``700``),
2404
+ # while the official directory uses five digits (``00700.HK``). Treat
2405
+ # both as the same exact code so Tencent wins over incidental substrings.
2406
+ hk_numeric_code = ""
2407
+ if query_text.isdigit() and 1 <= len(query_text) <= 5:
2408
+ hk_numeric_code = query_text.zfill(5)
2409
+ query_forms.add(hk_numeric_code)
2410
+ query_forms.discard("")
2411
+ results: list[dict[str, Any]] = []
2412
+ seen: set[str] = set()
2413
+
2414
+ def add(item: Mapping[str, Any]) -> None:
2415
+ market = item.get("market") or item.get("board")
2416
+ symbol = _canonical_market_symbol(
2417
+ _canonical_directory_symbol(
2418
+ item.get("symbol")
2419
+ or item.get("symbol_id")
2420
+ or item.get("secid")
2421
+ or item.get("stock_code")
2422
+ or item.get("index_code")
2423
+ or item.get("ticker")
2424
+ or item.get("code"),
2425
+ market=market,
2426
+ default_market="US" if str(market or "").strip() == "105" else "",
2427
+ )
2428
+ )
2429
+ if not symbol:
2430
+ return
2431
+ name = next(
2432
+ (
2433
+ item.get(key)
2434
+ for key in ("name", "stock_name", "security_name", "index_name", "symbol_name")
2435
+ if item.get(key)
2436
+ ),
2437
+ symbol,
2438
+ )
2439
+ if symbol in seen:
2440
+ for result in results:
2441
+ if result["symbol"] == symbol and result["name"] == symbol and str(name) != symbol:
2442
+ result["name"] = str(name)
2443
+ break
2444
+ return
2445
+ seen.add(symbol)
2446
+ result: dict[str, Any] = {"symbol": symbol, "name": str(name)}
2447
+ for key in ("board", "close", "change", "change_rate", "market"):
2448
+ if item.get(key) is not None:
2449
+ result[key] = "US" if key == "market" and str(item[key]).strip() == "105" else item[key]
2450
+ results.append(result)
2451
+
2452
+ # Use the last local directory snapshot first. It is available without an
2453
+ # API key and avoids sending every search to FTShare's keyed search route.
2454
+ # Search must stay local and fast. The app refreshes this directory in the
2455
+ # background; never block a keystroke on a full provider-directory request.
2456
+ directory = _read_symbol_directory_cache()
2457
+ directory_items = directory.get("items") if isinstance(directory, Mapping) else None
2458
+ searchable_items = directory_items if isinstance(directory_items, list) else list(_SYMBOL_DIRECTORY_SEED)
2459
+ # Keep built-in aliases in the fallback path and include the seed as a
2460
+ # supplement when a provider directory is partial.
2461
+ for item in [*searchable_items, *_SYMBOL_DIRECTORY_SEED]:
2462
+ if not isinstance(item, Mapping):
2463
+ continue
2464
+ searchable = "".join(
2465
+ f"{item.get('symbol', '')} {item.get('name', '')} {item.get('aliases', '')} "
2466
+ f"{_BUILTIN_SEARCH_ALIASES.get(str(item.get('symbol') or ''), '')}".casefold().split()
2467
+ )
2468
+ if any(term in searchable for term in query_forms):
2469
+ add(item)
2470
+
2471
+ def rank(item: Mapping[str, Any]) -> tuple[int, str, str]:
2472
+ symbol = str(item.get("symbol") or "").casefold()
2473
+ name = str(item.get("name") or "").casefold()
2474
+ code = symbol.split(".", 1)[0]
2475
+ if (
2476
+ query_text in {symbol, name, code}
2477
+ or canonical_query == symbol
2478
+ or (hk_numeric_code and code == hk_numeric_code)
2479
+ ):
2480
+ priority = 0
2481
+ elif code.startswith(query_text) or name.startswith(query_text):
2482
+ priority = 1
2483
+ elif query_text in symbol or query_text in name:
2484
+ priority = 2
2485
+ else:
2486
+ priority = 3
2487
+ return priority, name, symbol
2488
+
2489
+ results.sort(key=rank)
2490
+ results = results[:lim]
2491
+
2492
+ if not results:
2493
+ canonical = _canonical_market_symbol(q)
2494
+ # Explicit market identity is usable even if its directory row is
2495
+ # missing. Never guess a market for an ambiguous bare numeric code.
2496
+ if re.fullmatch(r"(?:\d{6}\.(?:XSHG|XSHE|BJSE)|\d{5}\.HK|[A-Z][A-Z0-9.-]{0,15}\.(?:US|NASDAQ|NYSE))", canonical):
2497
+ add({"symbol": canonical, "name": canonical})
2498
+ results[-1]["verified"] = False
2499
+ source = "directory" if isinstance(directory_items, list) else "builtin"
2500
+ partial = not directory or not directory.get("coverage") or bool(directory.get("stale")) or any(
2501
+ not item.get("complete") for item in (directory.get("coverage") or {}).values()
2502
+ )
2503
+ stale = not directory or bool(directory.get("stale")) or int(directory.get("expires_at") or 0) < time.time()
2504
+ payload = {"ok": True, "query": q, "count": len(results), "results": results, "source": source,
2505
+ "stale": stale, "partial": partial, "basic_directory_version": _BASIC_DIRECTORY["version"]}
2506
+ if not results and (partial or stale):
2507
+ payload["message"] = "未找到匹配标的。可继续输入名称、代码或常用简称。"
2508
+ _symbol_search_cache[cache_key] = (now, payload)
2509
+ if len(_symbol_search_cache) > _SYMBOL_SEARCH_CACHE_MAX_ENTRIES:
2510
+ oldest_key = min(_symbol_search_cache, key=lambda key: _symbol_search_cache[key][0])
2511
+ _symbol_search_cache.pop(oldest_key, None)
2512
+ return {**payload, "results": list(results)}
2513
+
2514
+
2515
+ MARKET_TICKER_SOURCES = (
2516
+ {"market": "CN", "name": "上证指数", "symbol": "000001.XSHG", "kind": "cn_index", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
2517
+ {"market": "CN", "name": "沪深300", "symbol": "000300.XSHG", "kind": "cn_index", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
2518
+ {"market": "CN", "name": "深证成指", "symbol": "399001.XSHE", "kind": "cn_index", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
2519
+ {"market": "CN", "name": "创业板指", "symbol": "399006.XSHE", "kind": "cn_index", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
2520
+ {"market": "HK", "name": "恒生指数", "symbol": "100.HSI", "kind": "global", "timezone": "Asia/Hong_Kong", "open": "09:30", "close": "16:00"},
2521
+ {"market": "US", "name": "纳斯达克100", "symbol": "100.NDX", "kind": "global", "timezone": "America/New_York", "open": "09:30", "close": "16:00"},
2522
+ {"market": "US", "name": "标普500", "symbol": "100.SPX", "kind": "global", "timezone": "America/New_York", "open": "09:30", "close": "16:00"},
2523
+ {"market": "US", "name": "道琼斯", "symbol": "100.DJIA", "kind": "global", "timezone": "America/New_York", "open": "09:30", "close": "16:00"},
2524
+ )
2525
+ # Global index identities (secid "100.*") served by the official FTShare
2526
+ # `global_index_daily_kline` endpoint (free tier, per FTShare docs). Kept as a
2527
+ # small explicit registry; never auto-extended from upstream responses.
2528
+ GLOBAL_INDEX_SOURCES = {
2529
+ "100.HSI": "恒生指数",
2530
+ "100.NDX": "纳斯达克",
2531
+ "100.SPX": "标普500",
2532
+ "100.DJIA": "道琼斯",
2533
+ "100.N225": "日经225",
2534
+ }
2535
+ # Kept as a public compatibility name for integrations that read this mapping.
2536
+ COMPARISON_INDEX_NAMES = {item["symbol"]: item["name"] for item in CN_BROAD_INDEXES}
2537
+
2538
+
2539
+ def _number(value: Any) -> float | None:
2540
+ try:
2541
+ number = float(value)
2542
+ except (TypeError, ValueError):
2543
+ return None
2544
+ return number if number == number else None
2545
+
2546
+
2547
+ def _ticker_timestamp(row: Mapping[str, Any]) -> float:
2548
+ raw = row.get("ts_millis") or row.get("time") or row.get("timestamp")
2549
+ number = _number(raw)
2550
+ if number is not None:
2551
+ return number
2552
+ date = str(row.get("trade_date") or row.get("date") or "")
2553
+ try:
2554
+ return datetime.fromisoformat(date).replace(tzinfo=timezone.utc).timestamp()
2555
+ except ValueError:
2556
+ return 0.0
2557
+
2558
+
2559
+ def _ticker_item(source: Mapping[str, str], raw: Any) -> dict[str, Any] | None:
2560
+ rows = [row for row in raw if isinstance(row, Mapping)] if isinstance(raw, list) else []
2561
+ if not rows:
2562
+ return None
2563
+ rows.sort(key=_ticker_timestamp)
2564
+ latest = rows[-1]
2565
+ close = _number(latest.get("close"))
2566
+ if close is None:
2567
+ return None
2568
+ previous = _number(rows[-2].get("close")) if len(rows) > 1 else None
2569
+ change = _number(latest.get("change_amount"))
2570
+ change_pct = _number(latest.get("change_pct"))
2571
+ if previous not in (None, 0):
2572
+ change = close - previous
2573
+ change_pct = change / previous * 100
2574
+ if change is None or change_pct is None:
2575
+ return None
2576
+ timestamp = _ticker_timestamp(latest)
2577
+ return {
2578
+ "market": source["market"],
2579
+ "symbol": source["symbol"],
2580
+ "name": str(latest.get("name") or source["name"]),
2581
+ "close": close,
2582
+ "change": change,
2583
+ "change_pct": change_pct,
2584
+ "time": int(timestamp / 1000) if timestamp > 10_000_000_000 else int(timestamp),
2585
+ }
2586
+
2587
+
2588
+ def _market_status(source: Mapping[str, str], now: datetime) -> str:
2589
+ """Return the intentionally conservative delayed/closed label for a feed.
2590
+
2591
+ FTShare's compact index endpoints are daily snapshots, so we never label
2592
+ them as real-time. During a local market session the snapshot is useful but
2593
+ delayed; outside it the display is explicitly marked as closed.
2594
+ """
2595
+ try:
2596
+ local_now = now.astimezone(ZoneInfo(source["timezone"]))
2597
+ if local_now.weekday() >= 5:
2598
+ return "closed"
2599
+ open_at = clock_time.fromisoformat(source["open"])
2600
+ close_at = clock_time.fromisoformat(source["close"])
2601
+ return "delayed" if open_at <= local_now.time() <= close_at else "closed"
2602
+ except (KeyError, ValueError):
2603
+ return "delayed"
2604
+
2605
+
2606
+ def _symbol_market_status(symbol: str, now: datetime | None = None) -> str:
2607
+ """Return the market-session state for a symbol without claiming real-time data."""
2608
+ normalized = str(symbol or "").upper()
2609
+ if normalized.endswith((".HK", ".HKG")) or normalized.startswith("100.HSI"):
2610
+ source = {"timezone": "Asia/Hong_Kong", "open": "09:30", "close": "16:00"}
2611
+ elif normalized.endswith((".US", ".NASDAQ", ".NYSE")) or normalized in {"100.NDX", "100.SPX", "100.DJIA"}:
2612
+ source = {"timezone": "America/New_York", "open": "09:30", "close": "16:00"}
2613
+ else:
2614
+ source = {"timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"}
2615
+ return "open" if _market_status(source, now or datetime.now(timezone.utc)) == "delayed" else "closed"
2616
+
2617
+
2618
+ def _candle_freshness(symbol: str, rows: list[dict[str, Any]], *, now: datetime | None = None) -> dict[str, Any]:
2619
+ """Describe candle freshness without claiming a real-time provider feed.
2620
+
2621
+ FTShare OHLCV responses do not expose a universal quote timestamp. We can
2622
+ still report the latest supplied bar and whether it belongs to the current
2623
+ exchange session; callers should treat ``delayed`` as end-of-bar data, not a
2624
+ tick-level quote.
2625
+ """
2626
+ exchange_timezone = _exchange_timezone(symbol)
2627
+ current = now or datetime.now(timezone.utc)
2628
+ local_now = current.astimezone(ZoneInfo(exchange_timezone))
2629
+ latest = max((int(row.get("time") or 0) for row in rows), default=0)
2630
+ if not latest:
2631
+ return {"status": "stale", "as_of": None, "freshness": "no_candle_timestamp", "exchange_timezone": exchange_timezone}
2632
+ latest_local = datetime.fromtimestamp(latest, tz=ZoneInfo(exchange_timezone))
2633
+ market_status = _symbol_market_status(symbol, current)
2634
+ if market_status == "closed":
2635
+ status = "closed"
2636
+ elif latest_local.date() == local_now.date():
2637
+ status = "delayed"
2638
+ else:
2639
+ status = "stale"
2640
+ return {
2641
+ "status": status,
2642
+ "as_of": latest,
2643
+ "freshness": "derived_from_latest_candle",
2644
+ "exchange_timezone": exchange_timezone,
2645
+ }
2646
+
2647
+
2648
+ def _ftshare_ticker_rows(market: Any, source_info: Mapping[str, Any]) -> list[dict[str, Any]] | None:
2649
+ """Official FTShare rows for one bottom-strip index.
2650
+
2651
+ A-share indices use ``index_candlesticks``; global indices (100.*) use
2652
+ ``global_index_daily_kline``. Rows are normalized to the canonical shape
2653
+ and sorted ascending by time, so ``_ticker_item`` can derive the change.
2654
+ """
2655
+ kind = str(source_info.get("kind") or "")
2656
+ try:
2657
+ if kind == "global":
2658
+ raw = market.global_index_daily_kline(secid=source_info["symbol"], limit=5, as_dataframe=False)
2659
+ else:
2660
+ until_ms = _until_ms()
2661
+ raw = market.index_candlesticks(
2662
+ symbol=source_info["symbol"],
2663
+ interval_unit="Day",
2664
+ interval_value=1,
2665
+ adjust_kind="none",
2666
+ since_ts_millis=until_ms - 15 * 86_400_000,
2667
+ until_ts_millis=until_ms,
2668
+ limit=6,
2669
+ as_dataframe=False,
2670
+ )
2671
+ except Exception: # noqa: BLE001 - per-source official ticker failure
2672
+ return None
2673
+ rows = _normalize_raw(raw)
2674
+ return rows if len(rows) >= 2 else None
2675
+
2676
+
2677
+ def _ftshare_ticker_item(market: Any, source_info: Mapping[str, Any], now: datetime) -> dict[str, Any] | None:
2678
+ """Try the official index once; the landing page has a separate fallback."""
2679
+ rows = _ftshare_ticker_rows(market, source_info)
2680
+ item = _ticker_item(source_info, rows) if rows is not None else None
2681
+ if item is not None:
2682
+ item["status"] = _market_status(source_info, now)
2683
+ return item
2684
+
2685
+
2686
+ def _remember_market_ticker(item: Mapping[str, Any], fetched_at: float) -> None:
2687
+ symbol = str(item.get("symbol") or "")
2688
+ if not symbol:
2689
+ return
2690
+ snapshot = deepcopy(dict(item))
2691
+ snapshot.pop("stale", None)
2692
+ with _market_ticker_cache_lock:
2693
+ _market_ticker_last_good[symbol] = (fetched_at, snapshot)
2694
+
2695
+
2696
+ def _last_market_ticker(symbol: str, now: float) -> dict[str, Any] | None:
2697
+ with _market_ticker_cache_lock:
2698
+ entry = _market_ticker_last_good.get(symbol)
2699
+ if entry is None or now - entry[0] > _MARKET_TICKER_STALE_TTL_SECONDS:
2700
+ return None
2701
+ cached = deepcopy(entry[1])
2702
+ cached["stale"] = True
2703
+ return cached
2704
+
2705
+
2706
+ def fetch_market_ticker(symbols: list[str] | tuple[str, ...] | None = None) -> dict[str, Any]:
2707
+ """Fetch a compact A/HK/US index ticker, degrading silently per source.
2708
+
2709
+ With a configured Key, FTShare official feeds are tried first: A-share
2710
+ indices via ``index_candlesticks`` and global indices via
2711
+ ``global_index_daily_kline``. The existing Tencent feed may fill supported
2712
+ gaps when those endpoints fail or no Key is configured. Neither source is
2713
+ guaranteed to return every index; ``missing`` reports the remainder.
2714
+
2715
+ ``symbols`` is intentionally limited to the fixed registry above. The
2716
+ browser uses small, ordered batches on a cold market page so the first
2717
+ available indices can render without waiting for every global endpoint.
2718
+ It is not a general quote-search API.
2719
+ """
2720
+ fetched_at = int(time.time())
2721
+ items_by_symbol: dict[str, dict[str, Any]] = {}
2722
+ sources_used: set[str] = set()
2723
+ now = datetime.now(timezone.utc)
2724
+ requested_symbols = {str(symbol).strip().upper() for symbol in symbols or [] if str(symbol).strip()}
2725
+ source_infos = tuple(
2726
+ source_info for source_info in MARKET_TICKER_SOURCES
2727
+ if not requested_symbols or str(source_info["symbol"]).upper() in requested_symbols
2728
+ )
2729
+
2730
+ # An installed SDK is not an authenticated account. Anonymous FTShare
2731
+ # attempts can stall the first index card before the usable free feed runs.
2732
+ if ftshare_available() and _ftshare_credential_source() != "none":
2733
+ try:
2734
+ market = _ftshare_market_api(timeout=4)
2735
+ for source_info in source_infos:
2736
+ item = _ftshare_ticker_item(market, source_info, now)
2737
+ if item is not None:
2738
+ items_by_symbol[item["symbol"]] = item
2739
+ _remember_market_ticker(item, fetched_at)
2740
+ sources_used.add("ftshare")
2741
+ except Exception:
2742
+ # Continue to per-index free/cache fallback rather than discarding
2743
+ # official rows that were already retrieved successfully.
2744
+ pass
2745
+
2746
+ # Use the free feed only for the indexes FTShare did not return; replacing
2747
+ # the whole strip used to turn a transient single-index error into a five
2748
+ # index response.
2749
+ free_by_symbol: dict[str, dict[str, Any]] = {}
2750
+ if fetch_tencent_ticker_items is not None:
2751
+ try:
2752
+ free_by_symbol = {str(item.get("symbol") or ""): dict(item) for item in fetch_tencent_ticker_items()}
2753
+ except Exception: # noqa: BLE001
2754
+ free_by_symbol = {}
2755
+ source_by_symbol = {str(item["symbol"]): item for item in source_infos}
2756
+ missing: list[dict[str, str]] = []
2757
+ for symbol, source_info in source_by_symbol.items():
2758
+ if symbol in items_by_symbol:
2759
+ continue
2760
+ item = free_by_symbol.get(symbol)
2761
+ if item is not None:
2762
+ item["status"] = _market_status(source_info, now)
2763
+ items_by_symbol[symbol] = item
2764
+ _remember_market_ticker(item, fetched_at)
2765
+ sources_used.add("tencent_free")
2766
+ continue
2767
+ cached = _last_market_ticker(symbol, fetched_at)
2768
+ if cached is not None:
2769
+ cached["status"] = _market_status(source_info, now)
2770
+ items_by_symbol[symbol] = cached
2771
+ sources_used.add("cache")
2772
+ continue
2773
+ missing.append({"symbol": symbol, "name": str(source_info["name"]), "market": str(source_info["market"])})
2774
+
2775
+ items = [items_by_symbol[str(source_info["symbol"])] for source_info in source_infos if str(source_info["symbol"]) in items_by_symbol]
2776
+ if not items:
2777
+ return {"ok": True, "items": [], "missing": missing, "source": "free_unavailable", "updated_at": fetched_at, "status": "unavailable"}
2778
+ statuses = {item.get("status") for item in items}
2779
+ status = "delayed" if "delayed" in statuses else "closed" if statuses else "unavailable"
2780
+ return {"ok": True, "items": items, "missing": missing, "source": "+".join(sorted(sources_used)) or "free_unavailable", "updated_at": fetched_at, "status": status}
2781
+
2782
+
2783
+ def _latest_session_close_millis(timezone_name: str) -> int:
2784
+ """Return the latest weekday close in the exchange timezone.
2785
+
2786
+ FTShare's minute endpoint expects a completed session boundary more
2787
+ reliably than a wall-clock timestamp late at night. Exchange holidays are
2788
+ harmless here: an empty chunk simply advances to the preceding session.
2789
+ """
2790
+ now = datetime.now(ZoneInfo(timezone_name))
2791
+ # US sessions can include 16:00--20:00 ET after-hours bars. Requesting the
2792
+ # fully completed extended session preserves them when FTShare provides
2793
+ # them, while the returned per-bar session label remains the source of truth.
2794
+ close_by_timezone = {
2795
+ "Asia/Shanghai": (15, 0),
2796
+ "Asia/Hong_Kong": (16, 0),
2797
+ "America/New_York": (20, 0),
2798
+ }
2799
+ hour, minute = close_by_timezone.get(timezone_name, (15, 0))
2800
+ candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
2801
+ if now < candidate:
2802
+ candidate -= timedelta(days=1)
2803
+ while candidate.weekday() >= 5:
2804
+ candidate -= timedelta(days=1)
2805
+ return int(candidate.timestamp() * 1000)
2806
+
2807
+
2808
+ def _intraday_session_label(timestamp: int, timezone_name: str) -> str:
2809
+ """Classify a bar by its exchange-local start time without inventing bars."""
2810
+ local = datetime.fromtimestamp(int(timestamp), tz=ZoneInfo(timezone_name)).time()
2811
+ if timezone_name == "America/New_York":
2812
+ if clock_time(4, 0) <= local < clock_time(9, 30):
2813
+ return "pre_market"
2814
+ if clock_time(9, 30) <= local < clock_time(16, 0):
2815
+ return "regular"
2816
+ if clock_time(16, 0) <= local < clock_time(20, 0):
2817
+ return "after_hours"
2818
+ return "overnight"
2819
+ if timezone_name == "Asia/Hong_Kong":
2820
+ if clock_time(9, 30) <= local < clock_time(12, 0):
2821
+ return "morning"
2822
+ if clock_time(13, 0) <= local < clock_time(16, 0):
2823
+ return "afternoon"
2824
+ return "outside_regular"
2825
+ if clock_time(9, 30) <= local < clock_time(11, 30):
2826
+ return "morning"
2827
+ if clock_time(13, 0) <= local < clock_time(15, 0):
2828
+ return "afternoon"
2829
+ return "outside_regular"
2830
+
2831
+
2832
+ def _annotate_intraday_rows(rows: list[dict[str, Any]], *, timezone_name: str, interval_value: int) -> list[dict[str, Any]]:
2833
+ """Attach exact open timestamps when supplied and a display-only session label."""
2834
+ step_seconds = max(1, int(interval_value)) * 60
2835
+ for row in rows:
2836
+ close_time = int(row["time"])
2837
+ start_time = int(row.get("open_time") or (close_time - step_seconds))
2838
+ row["session"] = _intraday_session_label(start_time, timezone_name)
2839
+ return rows
2840
+
2841
+
2842
+ def _complete_intraday_bars(rows: list[dict[str, Any]], *, interval_value: int) -> list[dict[str, Any]]:
2843
+ """Exclude provider boundary rows that are shorter than the requested bar."""
2844
+ expected_seconds = max(1, int(interval_value)) * 60
2845
+ complete: list[dict[str, Any]] = []
2846
+ for row in rows:
2847
+ open_time = row.get("open_time")
2848
+ if open_time is not None:
2849
+ try:
2850
+ if int(row["time"]) - int(open_time) != expected_seconds:
2851
+ continue
2852
+ except (TypeError, ValueError):
2853
+ continue
2854
+ complete.append(row)
2855
+ return complete
2856
+
2857
+
2858
+ def _complete_intraday_session_dates(
2859
+ rows: list[dict[str, Any]], *, timezone_name: str, interval_value: int,
2860
+ ) -> set[Any]:
2861
+ """Return exchange dates that contain a usable, full intraday session.
2862
+
2863
+ The FTShare history API is inclusive at the beginning of a natural-date
2864
+ window. A request ending on Friday can therefore include only a single
2865
+ 15:00 bar from Wednesday. That bar is a valid candle, but it is *not* a
2866
+ day of history and must neither count toward a 5D chart nor become the
2867
+ cursor for the next page.
2868
+
2869
+ We deliberately use both bar count and elapsed session span. This rejects
2870
+ an API boundary bar while tolerating a small number of missing/late bars.
2871
+ """
2872
+ timezone_value = ZoneInfo(timezone_name)
2873
+ grouped: dict[Any, list[dict[str, Any]]] = {}
2874
+ for row in rows:
2875
+ try:
2876
+ date_key = datetime.fromtimestamp(int(row["time"]), tz=timezone_value).date()
2877
+ except (KeyError, TypeError, ValueError, OSError):
2878
+ continue
2879
+ grouped.setdefault(date_key, []).append(row)
2880
+
2881
+ # A normal mainland session has 240 trading minutes. The thresholds for
2882
+ # other exchanges are intentionally conservative because this endpoint can
2883
+ # include pre/post-market rows there. In all cases a lone boundary row
2884
+ # fails both checks.
2885
+ regular_minutes = {
2886
+ "Asia/Shanghai": 240,
2887
+ "Asia/Hong_Kong": 330,
2888
+ "America/New_York": 390,
2889
+ }.get(timezone_name, 240)
2890
+ minimum_bars = max(2, int((regular_minutes / max(1, int(interval_value))) * 0.65))
2891
+ minimum_span_seconds = 3 * 60 * 60
2892
+ valid_dates: set[Any] = set()
2893
+ for date_key, session_rows in grouped.items():
2894
+ ordered = sorted(session_rows, key=lambda item: int(item["time"]))
2895
+ first_open = int(ordered[0].get("open_time") or ordered[0]["time"])
2896
+ last_close = int(ordered[-1]["time"])
2897
+ if len(ordered) >= minimum_bars and last_close - first_open >= minimum_span_seconds:
2898
+ valid_dates.add(date_key)
2899
+ return valid_dates
2900
+
2901
+
2902
+ def _previous_weekday_session_close_millis(session_date: Any, timezone_name: str) -> int:
2903
+ """Return the preceding weekday's exchange close for intraday pagination."""
2904
+ close_by_timezone = {
2905
+ "Asia/Shanghai": (15, 0),
2906
+ "Asia/Hong_Kong": (16, 0),
2907
+ "America/New_York": (20, 0),
2908
+ }
2909
+ hour, minute = close_by_timezone.get(timezone_name, (15, 0))
2910
+ candidate = datetime.combine(session_date, clock_time(hour, minute), tzinfo=ZoneInfo(timezone_name)) - timedelta(days=1)
2911
+ while candidate.weekday() >= 5:
2912
+ candidate -= timedelta(days=1)
2913
+ return int(candidate.timestamp() * 1000)
2914
+
2915
+
2916
+ def _fetch_candles_ftshare(
2917
+ symbol: str,
2918
+ *,
2919
+ interval: str = "day",
2920
+ interval_value: int = 1,
2921
+ session_count: int | None = None,
2922
+ limit: int = 220,
2923
+ adjust: str = "none",
2924
+ ) -> dict[str, Any]:
2925
+ """Fetch OHLCV via ftshare SDK (primary implementation).
2926
+
2927
+ Kept under a private name: ``fetch_candles`` (the public entry) adds a
2928
+ built-in free fallback for broad-market indices on top of this path.
2929
+
2930
+ Notes:
2931
+ - The SDK accepts lowercase adjustment enum values: none/forward/backward.
2932
+ - Quarterly bars are aggregated from monthly candles because FTShare does
2933
+ not expose a native Quarter variant.
2934
+ - ``limit`` is roughly calendar-days lookback on ftshare; we do **not**
2935
+ overfetch/correct here (keep the new MCP thin). Agent wanting N bars
2936
+ should request a larger limit.
2937
+ """
2938
+ normalized_adjust = normalize_adjustment(adjust)
2939
+ if normalized_adjust is None:
2940
+ return adjustment_error()
2941
+ adjust = normalized_adjust
2942
+ sym = _canonical_market_symbol(symbol)
2943
+ if not sym:
2944
+ return {"ok": False, "error": "invalid_symbol", "message": "symbol is required"}
2945
+ if not re.fullmatch(r"[A-Z0-9][A-Z0-9.-]{0,63}", sym):
2946
+ return {"ok": False, "error": "invalid_symbol", "message": f"invalid symbol: {symbol}"}
2947
+ normalized_interval = (interval or "day").strip().lower()
2948
+ supported_intervals = {"minute", "day", "week", "month", "quarter", "year"}
2949
+ if normalized_interval not in supported_intervals:
2950
+ return {
2951
+ "ok": False,
2952
+ "error": "unsupported_interval",
2953
+ "message": f"不支持的 K 线周期“{interval}”。请选择:{'、'.join(sorted(supported_intervals))}。",
2954
+ "supported_intervals": sorted(supported_intervals),
2955
+ }
2956
+ ambiguous = _ambiguous_broad_index_result(sym)
2957
+ if ambiguous is not None:
2958
+ return ambiguous
2959
+ # A-share broad indexes use their own verified candlestick endpoint
2960
+ # (SDK index_candlesticks >= 1.0.0) and must never fall back to a
2961
+ # same-code equity.
2962
+ is_index = _broad_index_for_symbol(sym) is not None
2963
+ # Global indices (100.HSI / 100.NDX / 100.SPX …) use the dedicated
2964
+ # FTShare `global_index_daily_kline` endpoint (free tier per docs).
2965
+ is_global_index = sym in GLOBAL_INDEX_SOURCES
2966
+ is_etf = _is_etf_symbol(sym)
2967
+
2968
+ fetched_at = int(time.time())
2969
+ if not ftshare_available():
2970
+ return _ftshare_unavailable_result()
2971
+
2972
+ import ftshare as ft
2973
+
2974
+ unit = _interval_to_sdk(interval)
2975
+ adj = _adjust_to_sdk(adjust)
2976
+ step = max(1, min(int(interval_value or 1), 240))
2977
+ sessions = max(1, min(int(session_count or 1), 10))
2978
+ lim = max(1, min(int(limit or 220), 4000))
2979
+ exchange_timezone = _exchange_timezone(sym)
2980
+ if normalized_interval == "minute" and _is_us_symbol(sym):
2981
+ return {
2982
+ "ok": False,
2983
+ "error": "intraday_provider_unavailable",
2984
+ "error_code": "intraday_provider_unavailable",
2985
+ "message": "当前 FTShare 股票分钟接口仅支持沪深北标的,不支持美股;这不代表 API Key 无效。",
2986
+ "symbol": sym,
2987
+ "source": "ftshare",
2988
+ "next_action": "请选择美股日线或更长周期;分时数据可通过其他数据源的 rows 接入。",
2989
+ "retryable": False,
2990
+ }
2991
+ if normalized_interval == "minute" and _is_hk_symbol(sym):
2992
+ return {
2993
+ "ok": False,
2994
+ "error": "intraday_provider_unavailable",
2995
+ "error_code": "intraday_provider_unavailable",
2996
+ "message": "The current FTShare Python SDK has no verified Hong Kong minute-candle endpoint.",
2997
+ "symbol": sym,
2998
+ "source": "ftshare",
2999
+ "next_action": "Use daily-or-larger Hong Kong candles, or pass verified minute rows from another provider.",
3000
+ "retryable": False,
3001
+ }
3002
+ if normalized_interval == "minute" and is_global_index:
3003
+ return {
3004
+ "ok": False,
3005
+ "error": "intraday_provider_unavailable",
3006
+ "error_code": "intraday_provider_unavailable",
3007
+ "message": "FTShare global-index K-lines are daily only; minute bars are not served for this index.",
3008
+ "symbol": sym,
3009
+ "source": "ftshare",
3010
+ "next_action": "Use daily-or-larger candles for the global index, or pass verified minute rows from another provider.",
3011
+ "retryable": False,
3012
+ }
3013
+ if is_etf:
3014
+ contract_name = "etf_minutes" if normalized_interval == "minute" else "etf_candles"
3015
+ elif is_index:
3016
+ contract_name = "index_history_minute_candles" if normalized_interval == "minute" else "index_daily_candles"
3017
+ elif is_global_index:
3018
+ contract_name = "global_index_daily"
3019
+ else:
3020
+ contract_name = "history_minute_candles" if normalized_interval == "minute" else "daily_candles"
3021
+ cache_key = _candle_cache_key(
3022
+ sym, normalized_interval, step, sessions, lim, adjust,
3023
+ _preferred_ftshare_transport(contract_name),
3024
+ )
3025
+ fresh_cache = _recent_candle_cache(cache_key)
3026
+ if fresh_cache is not None:
3027
+ return fresh_cache
3028
+
3029
+ market = _ftshare_market_api(timeout=20)
3030
+ raw: Any = None
3031
+ fetch_error: Exception | None = None
3032
+ for attempt in range(2):
3033
+ try:
3034
+ if is_etf and normalized_interval != "minute":
3035
+ raw = _fetch_etf_history(
3036
+ market,
3037
+ symbol=sym,
3038
+ interval=normalized_interval,
3039
+ adjust_kind=adj,
3040
+ limit=lim,
3041
+ )
3042
+ elif is_index:
3043
+ if normalized_interval == "minute":
3044
+ raw = _fetch_index_history_minutes(
3045
+ market,
3046
+ symbol=sym,
3047
+ interval_value=step,
3048
+ adjust_kind=adj,
3049
+ sessions=sessions,
3050
+ limit=lim,
3051
+ exchange_timezone=exchange_timezone,
3052
+ )
3053
+ else:
3054
+ raw = _fetch_index_history(
3055
+ market,
3056
+ symbol=sym,
3057
+ interval=normalized_interval,
3058
+ interval_unit=unit,
3059
+ interval_value=step,
3060
+ adjust_kind=adj,
3061
+ limit=lim,
3062
+ )
3063
+ elif is_global_index:
3064
+ # Global index daily history: the FTShare endpoint returns
3065
+ # daily bars only; weekly/monthly/quarterly/yearly views are
3066
+ # aggregated locally below, mirroring the US daily-only path.
3067
+ raw = _fetch_global_index_history(
3068
+ market,
3069
+ symbol=sym,
3070
+ interval=normalized_interval,
3071
+ limit=lim,
3072
+ )
3073
+ elif _is_us_symbol(sym) and normalized_interval != "minute":
3074
+ raw = _fetch_us_daily_candles(market, sym, lim)
3075
+ elif _is_hk_symbol(sym) and normalized_interval in {"day", "week", "month", "quarter", "year"}:
3076
+ raw = _fetch_hk_candles(market, sym, normalized_interval, lim, adjust)
3077
+ elif normalized_interval == "minute":
3078
+ # FTShare minute history is restricted to short natural-date
3079
+ # windows. Page backwards from the latest session close and retain
3080
+ # the requested number of *trading* sessions after de-duplication.
3081
+ # This is intentionally not a calendar-day slice: a 5D chart means
3082
+ # five sessions even across a weekend.
3083
+ cutoff = _latest_session_close_millis(exchange_timezone)
3084
+ unique: dict[int, dict[str, Any]] = {}
3085
+ # FTShare rejects windows that span more than three natural
3086
+ # days. Keep each page to two days and walk backwards until the
3087
+ # requested number of trading sessions has been collected.
3088
+ page_window_days = 2
3089
+ max_pages = max(8, sessions * 3 + 2)
3090
+ for _page in range(max_pages):
3091
+ chunk: list[dict[str, Any]] = []
3092
+ complete_dates: set[Any] = set()
3093
+ # v4 is the raw one-minute stream for the current A-share
3094
+ # stock session. Do not re-aggregate it: the UI has no
3095
+ # intraday period selector. This endpoint has no adjustment
3096
+ # parameter: adjusted requests must use history, including
3097
+ # when history fails; never relabel the raw realtime feed.
3098
+ # Multi-session history, ETFs and indexes also retain v2.
3099
+ if _page == 0 and not is_etf and sessions == 1 and step == 1 and adj == "none":
3100
+ try:
3101
+ realtime_chunk = _complete_intraday_bars(
3102
+ _normalize_realtime_minute_raw(
3103
+ _ftshare_stock_realtime_minutes(market, symbol=sym)
3104
+ ),
3105
+ interval_value=step,
3106
+ )
3107
+ realtime_dates = _complete_intraday_session_dates(
3108
+ realtime_chunk,
3109
+ timezone_name=exchange_timezone,
3110
+ interval_value=step,
3111
+ )
3112
+ if realtime_dates:
3113
+ chunk = [
3114
+ row for row in realtime_chunk
3115
+ if datetime.fromtimestamp(
3116
+ int(row["time"]), tz=ZoneInfo(exchange_timezone)
3117
+ ).date() in realtime_dates
3118
+ ]
3119
+ complete_dates = realtime_dates
3120
+ except Exception: # noqa: BLE001 - v2 remains the compatibility path
3121
+ pass
3122
+ if not chunk:
3123
+ page = (_ftshare_etf_minutes if is_etf else _ftshare_stock_minutes)(
3124
+ market,
3125
+ symbol=_etf_minute_symbol(sym) if is_etf else sym,
3126
+ interval_value=step,
3127
+ adjust_kind=adj,
3128
+ since_ts_millis=max(
3129
+ 0,
3130
+ cutoff - page_window_days * 86_400_000,
3131
+ ),
3132
+ until_ts_millis=cutoff,
3133
+ limit=min(500, max(lim, sessions * 250)),
3134
+ as_dataframe=False,
3135
+ )
3136
+ chunk = _complete_intraday_bars(_normalize_raw(page), interval_value=step)
3137
+ complete_dates = _complete_intraday_session_dates(
3138
+ chunk, timezone_name=exchange_timezone, interval_value=step,
3139
+ )
3140
+ chunk = [
3141
+ row for row in chunk
3142
+ if datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date() in complete_dates
3143
+ ]
3144
+ if not chunk:
3145
+ cutoff = _previous_weekday_session_close_millis(
3146
+ datetime.fromtimestamp(cutoff / 1000, tz=ZoneInfo(exchange_timezone)).date(),
3147
+ exchange_timezone,
3148
+ )
3149
+ continue
3150
+ chunk_dates = {
3151
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
3152
+ for row in chunk
3153
+ }
3154
+ known_dates = {
3155
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
3156
+ for row in unique.values()
3157
+ }
3158
+ if known_dates and not (chunk_dates - known_dates):
3159
+ break
3160
+ for row in chunk:
3161
+ unique[int(row["time"])] = row
3162
+ local_dates = {
3163
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date()
3164
+ for row in unique.values()
3165
+ }
3166
+ if len(local_dates) >= sessions:
3167
+ break
3168
+ cutoff = _previous_weekday_session_close_millis(min(chunk_dates), exchange_timezone)
3169
+ raw = list(unique.values())
3170
+ else:
3171
+ raw = _fetch_generic_history(
3172
+ market,
3173
+ symbol=sym,
3174
+ interval=normalized_interval,
3175
+ interval_unit=unit,
3176
+ interval_value=step,
3177
+ adjust_kind=adj,
3178
+ limit=lim,
3179
+ )
3180
+ fetch_error = None
3181
+ break
3182
+ except Exception as exc: # noqa: BLE001
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
3187
+ if attempt == 0:
3188
+ time.sleep(0.35)
3189
+ if fetch_error is not None:
3190
+ fallback = _cached_candle_fallback(cache_key, fetch_error)
3191
+ if fallback is not None:
3192
+ return fallback
3193
+ provider_error, provider_message = _classify_ftshare_error(fetch_error)
3194
+ return {
3195
+ "ok": False,
3196
+ "error": provider_error,
3197
+ "error_code": provider_error,
3198
+ "message": provider_message,
3199
+ "symbol": sym,
3200
+ "source": "ftshare",
3201
+ "updated_at": fetched_at,
3202
+ "status": "delayed",
3203
+ "market_status": _symbol_market_status(sym),
3204
+ }
3205
+
3206
+ rows = _normalize_raw(raw)
3207
+ if normalized_interval == "minute" and rows:
3208
+ rows = _annotate_intraday_rows(rows, timezone_name=exchange_timezone, interval_value=step)
3209
+ complete_dates = _complete_intraday_session_dates(
3210
+ rows, timezone_name=exchange_timezone, interval_value=step,
3211
+ )
3212
+ selected_dates = set(sorted(complete_dates)[-sessions:])
3213
+ rows = [
3214
+ row
3215
+ for row in rows
3216
+ if datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(exchange_timezone)).date() in selected_dates
3217
+ ]
3218
+ if (is_etf or _is_us_symbol(sym) or _is_hk_symbol(sym) or is_global_index) and normalized_interval != "minute":
3219
+ # Aggregate the complete daily history first, then apply the requested
3220
+ # number of bars. Trimming raw days before aggregation makes the
3221
+ # oldest requested week/month/quarter/year incomplete.
3222
+ rows = _aggregate_interval(rows, interval, timezone_name=exchange_timezone)[-lim:]
3223
+ elif normalized_interval == "quarter":
3224
+ rows = _aggregate_quarters(rows, timezone_name=exchange_timezone)[-lim:]
3225
+ elif not _is_hk_symbol(sym) and normalized_interval != "minute" and len(rows) > lim:
3226
+ rows = rows[-lim:]
3227
+ if len(rows) < 2:
3228
+ market_data_unavailable = (
3229
+ (_is_hk_symbol(sym) or _is_us_symbol(sym))
3230
+ and normalized_interval != "minute"
3231
+ )
3232
+ empty_error = (
3233
+ "当前 FTShare 暂未返回该港股/美股标的的足够日线数据;请检查标的代码、数据覆盖与账户权限,"
3234
+ "或切换到其他数据源。这不一定是 API Key 配置问题。"
3235
+ if market_data_unavailable
3236
+ else "当前数据源返回的有效 K 线不足两根,请检查标的代码、数据权限或切换数据源后重试。"
3237
+ )
3238
+ fallback = _cached_candle_fallback(cache_key, empty_error)
3239
+ if fallback is not None:
3240
+ return fallback
3241
+ result = {
3242
+ "ok": False,
3243
+ "error": "market_data_unavailable" if market_data_unavailable else "insufficient_candles",
3244
+ "message": empty_error,
3245
+ "symbol": sym,
3246
+ "source": "ftshare",
3247
+ "updated_at": fetched_at,
3248
+ "status": "delayed",
3249
+ "market_status": _symbol_market_status(sym),
3250
+ "transport": _FTSHARE_TRANSPORT_STATE.get(contract_name, {}).get("transport"),
3251
+ }
3252
+ return result
3253
+ name = GLOBAL_INDEX_SOURCES.get(sym) or _symbol_name(market, sym)
3254
+ freshness = _candle_freshness(sym, rows)
3255
+ result = {
3256
+ "ok": True,
3257
+ "symbol": sym,
3258
+ "name": name,
3259
+ "instrument_type": "etf" if is_etf else "index" if (is_index or is_global_index) else "stock",
3260
+ "interval": normalized_interval,
3261
+ "interval_value": step,
3262
+ "session_count": sessions if normalized_interval == "minute" else None,
3263
+ "adjust": (
3264
+ "none"
3265
+ if (_is_us_symbol(sym) and normalized_interval != "minute") or is_global_index
3266
+ else (adjust or "none").strip().lower()
3267
+ ),
3268
+ "count": len(rows),
3269
+ "rows": rows,
3270
+ "source": "ftshare",
3271
+ "updated_at": fetched_at,
3272
+ "status": freshness["status"],
3273
+ "market_status": _symbol_market_status(sym),
3274
+ "exchange_timezone": freshness["exchange_timezone"],
3275
+ "as_of": freshness["as_of"],
3276
+ "freshness": freshness["freshness"],
3277
+ "transport": _FTSHARE_TRANSPORT_STATE.get(contract_name, {}).get("transport", "sdk"),
3278
+ }
3279
+ if _is_us_symbol(sym) and normalized_interval != "minute" and (adjust or "none").strip().lower() != "none":
3280
+ result["adjust_requested"] = (adjust or "none").strip().lower()
3281
+ result["warning"] = "FTShare US daily history is returned unadjusted; adjust was not applied."
3282
+ if is_global_index and adjust != "none":
3283
+ result.update(adjust_requested=adjust, warning="FTShare global-index history is unadjusted; adjust was not applied.")
3284
+ if normalized_interval == "minute":
3285
+ sessions_seen = sorted({str(row.get("session") or "") for row in rows if row.get("session")})
3286
+ result["timestamp_semantics"] = "time is bar close in Unix seconds; open_time is present only when supplied by FTShare."
3287
+ result["sessions"] = sessions_seen
3288
+ _cache_candles(cache_key, result)
3289
+ return result
3290
+
3291
+
3292
+ def _free_index_candles_result(
3293
+ symbol: str, *, interval: str, limit: int, adjust: str
3294
+ ) -> dict[str, Any] | None:
3295
+ """Built-in free fallback for broad-market index daily K-lines.
3296
+
3297
+ Used only when FTShare cannot serve a broad-market index (anonymous/free
3298
+ tier). Returns None when the symbol is not covered or the free source is
3299
+ unavailable, so the caller keeps its original FTShare error untouched.
3300
+ """
3301
+ sym = _canonical_market_symbol(symbol)
3302
+ if not sym:
3303
+ return None
3304
+ if fetch_em_index_daily is None and fetch_tencent_index_daily is None:
3305
+ return None
3306
+ normalized_interval = (interval or "day").strip().lower()
3307
+ if normalized_interval not in {"day", "week", "month", "quarter", "year"}:
3308
+ return None
3309
+ if str(sym).upper() not in EM_INDEX_NAMES:
3310
+ return None
3311
+ fetched_at = int(time.time())
3312
+ # Try Eastmoney first, then Tencent: two independent public feeds make the
3313
+ # free tier resilient to either vendor's transient throttling.
3314
+ free_rows: list[dict[str, Any]] | None = None
3315
+ source_name = ""
3316
+ source_url = ""
3317
+ source_label = ""
3318
+ if fetch_em_index_daily is not None:
3319
+ try:
3320
+ free_rows = fetch_em_index_daily(sym, limit=max(2, min(int(limit), 4000)))
3321
+ except Exception: # noqa: BLE001 - free fallback degrades silently
3322
+ free_rows = None
3323
+ if free_rows and len(free_rows) >= 2:
3324
+ source_name, source_url, source_label = "eastmoney_free", SOURCE_URL, SOURCE_LABEL
3325
+ if (not free_rows or len(free_rows) < 2) and fetch_tencent_index_daily is not None:
3326
+ try:
3327
+ free_rows = fetch_tencent_index_daily(sym, limit=max(2, min(int(limit), 4000)))
3328
+ except Exception: # noqa: BLE001
3329
+ free_rows = None
3330
+ if free_rows and len(free_rows) >= 2:
3331
+ source_name, source_url, source_label = "tencent_free", TENCENT_SOURCE_URL, TENCENT_LABEL
3332
+ if not free_rows or len(free_rows) < 2:
3333
+ return None
3334
+ # Aggregation helpers mirror the FTShare path (week/month/quarter/year).
3335
+ rows = list(free_rows)
3336
+ if normalized_interval == "quarter":
3337
+ rows = _aggregate_quarters(rows, timezone_name="Asia/Shanghai")
3338
+ elif normalized_interval in {"week", "month", "year"}:
3339
+ rows = _aggregate_interval(rows, normalized_interval, timezone_name="Asia/Shanghai")
3340
+ rows = rows[-max(2, min(int(limit), 4000)):]
3341
+ if len(rows) < 2:
3342
+ return None
3343
+ name = EM_INDEX_NAMES.get(str(sym).upper()) or sym
3344
+ freshness = _candle_freshness(sym, rows)
3345
+ return {
3346
+ "ok": True,
3347
+ "symbol": sym,
3348
+ "name": name,
3349
+ "interval": normalized_interval,
3350
+ "interval_value": 1,
3351
+ "session_count": None,
3352
+ "adjust": "none",
3353
+ **({"adjust_requested": adjust, "warning": "Free index history is unadjusted; adjust was not applied."} if adjust != "none" else {}),
3354
+ "count": len(rows),
3355
+ "rows": rows,
3356
+ "source": source_name,
3357
+ "source_url": source_url,
3358
+ "updated_at": fetched_at,
3359
+ "status": freshness["status"],
3360
+ "market_status": _symbol_market_status(sym),
3361
+ "exchange_timezone": freshness["exchange_timezone"],
3362
+ "as_of": freshness["as_of"],
3363
+ "freshness": freshness["freshness"],
3364
+ "notice": (
3365
+ f"当前展示为{source_label}数据(免费大盘行情)。"
3366
+ "接入 FTShare Key 后可获得分钟K、新闻与官方数据能力。"
3367
+ ),
3368
+ "fallback_from": "ftshare",
3369
+ }
3370
+
3371
+
3372
+ def _free_stock_candles_result(
3373
+ symbol: str, *, interval: str, interval_value: int, limit: int, adjust: str,
3374
+ after_ftshare_failure: bool = False,
3375
+ ) -> dict[str, Any] | None:
3376
+ """Bounded BaoStock → Tencent fallback for qualified沪深 A-share history."""
3377
+ sym = _canonical_market_symbol(symbol)
3378
+ normalized_interval = str(interval or "day").strip().lower()
3379
+ if (
3380
+ not eligible_stock_code(sym) or _broad_index_for_symbol(sym) is not None
3381
+ or _is_etf_symbol(sym) or normalized_interval not in {"day", "week", "month", "quarter", "year"}
3382
+ or int(interval_value or 1) != 1
3383
+ ):
3384
+ return None
3385
+ requested = max(2, min(int(limit or 220), 4000))
3386
+ # Aggregate complete daily bars locally. Never combine the two vendors'
3387
+ # rows into one result or mislabel an unsupported adjustment as none.
3388
+ daily_factor = {"day": 1, "week": 6, "month": 26, "quarter": 80, "year": 260}[normalized_interval]
3389
+ source_name, source_url = BAOSTOCK_SOURCE, BAOSTOCK_SOURCE_URL
3390
+ raw = fetch_stock_daily(sym, limit=min(4000, requested * daily_factor + daily_factor), adjust=adjust)
3391
+ if not raw and fetch_tencent_stock_daily is not None:
3392
+ try:
3393
+ raw = fetch_tencent_stock_daily(
3394
+ sym, limit=min(4000, requested * daily_factor + daily_factor), adjust=adjust,
3395
+ )
3396
+ except Exception: # noqa: BLE001 - a public fallback must remain bounded and optional
3397
+ raw = None
3398
+ if raw:
3399
+ source_name, source_url = "tencent_free", TENCENT_SOURCE_URL
3400
+ if not raw:
3401
+ return None
3402
+ rows = _aggregate_interval(raw, normalized_interval, timezone_name="Asia/Shanghai")[-requested:]
3403
+ if len(rows) < 2:
3404
+ return None
3405
+ freshness = _candle_freshness(sym, rows)
3406
+ latest_date = datetime.fromtimestamp(rows[-1]["time"], tz=ZoneInfo("Asia/Shanghai")).date()
3407
+ if (datetime.now(ZoneInfo("Asia/Shanghai")).date() - latest_date).days > 5:
3408
+ freshness["status"] = "stale"
3409
+ freshness["freshness"] = "historical_daily_stale"
3410
+ return {
3411
+ "ok": True,
3412
+ "symbol": sym,
3413
+ "name": next((str(item["name"]) for item in _SYMBOL_DIRECTORY_SEED if item["symbol"] == sym), sym),
3414
+ "instrument_type": "stock",
3415
+ "interval": normalized_interval,
3416
+ "interval_value": 1,
3417
+ "session_count": None,
3418
+ "adjust": adjust,
3419
+ "count": len(rows),
3420
+ "rows": rows,
3421
+ "source": source_name,
3422
+ "source_url": source_url,
3423
+ "updated_at": int(time.time()),
3424
+ "status": freshness["status"],
3425
+ "market_status": _symbol_market_status(sym),
3426
+ "exchange_timezone": freshness["exchange_timezone"],
3427
+ "as_of": freshness["as_of"],
3428
+ "freshness": freshness["freshness"],
3429
+ "requested_count": requested,
3430
+ "history_complete": len(rows) >= requested,
3431
+ **({"fallback_from": "ftshare"} if after_ftshare_failure else {}),
3432
+ }
3433
+
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
+
3470
+ def fetch_candles(
3471
+ symbol: str,
3472
+ *,
3473
+ interval: str = "day",
3474
+ interval_value: int = 1,
3475
+ session_count: int | None = None,
3476
+ limit: int = 220,
3477
+ adjust: str = "none",
3478
+ ) -> dict[str, Any]:
3479
+ """Public candle entry with bounded, explicitly scoped free fallbacks.
3480
+
3481
+ Configured FTShare remains first. Without a key, eligible沪深 A-share
3482
+ stock daily history goes directly to BaoStock and then Tencent's public
3483
+ JSON K-line feed. Indexes use their separate free feeds.
3484
+ """
3485
+ normalized_adjust = normalize_adjustment(adjust)
3486
+ if normalized_adjust is None:
3487
+ return adjustment_error()
3488
+ adjust = normalized_adjust
3489
+ key_configured = _ftshare_credential_source() != "none"
3490
+ stock_options = {"interval": interval, "interval_value": interval_value, "limit": limit, "adjust": adjust}
3491
+ free_stock_eligible = (
3492
+ eligible_stock_code(_canonical_market_symbol(symbol)) is not None
3493
+ and str(interval or "day").strip().lower() in {"day", "week", "month", "quarter", "year"}
3494
+ and int(interval_value or 1) == 1
3495
+ )
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}
3500
+ free_stock = _free_stock_candles_result(symbol, **stock_options)
3501
+ if free_stock is not None:
3502
+ return free_stock
3503
+ if free_stock_eligible:
3504
+ return {
3505
+ "ok": False,
3506
+ "error": "free_stock_unavailable",
3507
+ "error_code": "free_stock_unavailable",
3508
+ "message": "BaoStock 与腾讯公开源暂未返回该标的历史 K 线,请稍后重试。",
3509
+ "attempted_sources": [BAOSTOCK_SOURCE, "tencent_free"],
3510
+ "source_urls": [BAOSTOCK_SOURCE_URL, TENCENT_SOURCE_URL],
3511
+ "ftshare_key_configured": False,
3512
+ }
3513
+ # Use the public index providers before constructing an anonymous
3514
+ # FTShare client. This keeps a key-less request from consuming the
3515
+ # keyed/anonymous SDK path when a supported index is available free.
3516
+ free_index = _free_index_candles_result(symbol, interval=interval, limit=limit, adjust=adjust)
3517
+ if free_index is not None:
3518
+ return free_index
3519
+ primary = _fetch_candles_ftshare(
3520
+ symbol,
3521
+ interval=interval,
3522
+ interval_value=interval_value,
3523
+ session_count=session_count,
3524
+ limit=limit,
3525
+ adjust=adjust,
3526
+ )
3527
+ # Safe, non-secret context for the UI: a missing credential needs different
3528
+ # guidance from a configured account that has hit its plan's rate limit.
3529
+ primary = {**primary, "ftshare_key_configured": key_configured}
3530
+ if primary.get("ok"):
3531
+ actual = len(primary.get("rows") or [])
3532
+ is_intraday = str(interval or "").strip().lower() == "minute"
3533
+ if is_intraday:
3534
+ timezone_name = str(primary.get("exchange_timezone") or "Asia/Shanghai")
3535
+ available_sessions = len({
3536
+ datetime.fromtimestamp(int(row["time"]), tz=ZoneInfo(timezone_name)).date()
3537
+ for row in primary.get("rows") or []
3538
+ })
3539
+ requested_sessions = max(1, min(int(session_count or 1), 10))
3540
+ primary = {
3541
+ **primary,
3542
+ "requested_count": limit,
3543
+ "requested_sessions": requested_sessions,
3544
+ "available_sessions": available_sessions,
3545
+ "history_complete": available_sessions >= requested_sessions,
3546
+ }
3547
+ if available_sessions < requested_sessions and primary.get("rows"):
3548
+ primary["warnings"] = [
3549
+ *primary.get("warnings", []),
3550
+ f"请求 {requested_sessions} 个交易日的分钟线,实际获得 {available_sessions} 个交易日;已仅展示完整分钟 K。",
3551
+ ]
3552
+ else:
3553
+ primary = {**primary, "requested_count": limit, "history_complete": actual >= limit}
3554
+ if not is_intraday and actual < limit and primary.get("rows"):
3555
+ start = int(primary["rows"][0]["time"])
3556
+ primary["history_start"] = start
3557
+ primary["warnings"] = [*primary.get("warnings", []), f"请求 {limit} 根,实际获得 {actual} 根;最早数据为 {datetime.fromtimestamp(start, tz=ZoneInfo('Asia/Shanghai')).date()}。历史覆盖不足,原因尚未确认。"]
3558
+ return primary
3559
+ fallback = _free_index_candles_result(symbol, interval=interval, limit=limit, adjust=adjust)
3560
+ if fallback is not None:
3561
+ return fallback
3562
+ if key_configured:
3563
+ free_stock = _free_stock_candles_result(symbol, **stock_options, after_ftshare_failure=True)
3564
+ if free_stock is not None:
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}
3574
+ return primary
3575
+
3576
+
3577
+ def _workspace_rows(raw: Any) -> list[dict[str, Any]]:
3578
+ return [dict(item) for item in _rows_from_directory_response(raw)]
3579
+
3580
+
3581
+ _US_INCOME_FIELD_MAP = {
3582
+ "revenue": "total_revenue",
3583
+ "tot_revenue": "total_revenue",
3584
+ "net_income": "net_income",
3585
+ "net_incattparesh": "net_income",
3586
+ "gross_profit": "gross_profit",
3587
+ "operating_income": "operating_income",
3588
+ "basic_eps": "basic_eps",
3589
+ "dilute_eps": "diluted_eps",
3590
+ }
3591
+
3592
+
3593
+ def _pivot_us_income_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
3594
+ """Turn FTShare U.S. ``ind_name`` / ``ind_value`` records into report rows."""
3595
+ groups: dict[tuple[str, str], dict[str, Any]] = {}
3596
+ for row in rows:
3597
+ end_date = str(row.get("end_date") or row.get("report_date") or "").strip()
3598
+ period = str(row.get("ind_type") or row.get("report_type") or "").strip()
3599
+ source_name = str(row.get("ind_name") or "").strip().lower()
3600
+ value = row.get("ind_value")
3601
+ target_name = _US_INCOME_FIELD_MAP.get(source_name)
3602
+ if not end_date or not target_name or value in (None, ""):
3603
+ continue
3604
+ item = groups.setdefault(
3605
+ (end_date, period),
3606
+ {
3607
+ "report_date": f"{end_date} {period}".strip(),
3608
+ "end_date": end_date,
3609
+ "report_type": period,
3610
+ "currency": row.get("currency") or row.get("currency_code") or "USD",
3611
+ },
3612
+ )
3613
+ item.setdefault(target_name, value)
3614
+ return [groups[key] for key in sorted(groups, reverse=True)]
3615
+
3616
+
3617
+ def _workspace_value(row: Mapping[str, Any], *keys: str) -> Any:
3618
+ for key in keys:
3619
+ value = row.get(key)
3620
+ if value not in (None, ""):
3621
+ return value
3622
+ return None
3623
+
3624
+
3625
+ def _intelligence_item(row: Mapping[str, Any], *, fallback: str = "--") -> dict[str, str]:
3626
+ """Normalize heterogeneous FTShare rows into a small, stable UI record."""
3627
+ title = _workspace_value(
3628
+ row, "name", "stock_name", "security_name", "sector_name", "industry_name",
3629
+ "concept_name", "title", "event_name", "symbol", "stock_code", "code",
3630
+ )
3631
+ # Capital-flow endpoints use ``main_net`` / ``main_pct`` while quote
3632
+ # endpoints use price-change names. Treating them as one unordered bag
3633
+ # previously selected a stock's close change and discarded its actual
3634
+ # capital flow, which made the sector page appear empty or misleading.
3635
+ value = _workspace_value(
3636
+ row, "main_net", "main_net_inflow", "net_inflow", "net_amount", "net_flow", "amount",
3637
+ "close", "sh_close", "close_price", "event_time",
3638
+ )
3639
+ detail = _workspace_value(
3640
+ row, "reason", "event", "event_type", "industry", "sector", "trade_date",
3641
+ "date", "time", "description", "rank",
3642
+ )
3643
+ change = _workspace_value(
3644
+ row, "main_pct", "main_net_pct", "sh_change_pct", "change_pct", "pct_chg", "change_rate", "pct_change", "change",
3645
+ )
3646
+ numeric_value = _intelligence_number(value)
3647
+ numeric_change = _intelligence_number(change)
3648
+ rendered_value = _display_number(numeric_value) if numeric_value is not None else str(value or "--")
3649
+ rendered_change = _display_percent(numeric_change) if numeric_change is not None else str(change or "")
3650
+ return {
3651
+ "title": str(title or fallback),
3652
+ "value": rendered_value,
3653
+ "detail": str(detail or ""),
3654
+ "change": rendered_change,
3655
+ }
3656
+
3657
+
3658
+ def _intelligence_number(value: Any) -> float | None:
3659
+ """Accept the numeric strings commonly returned by FTShare data APIs."""
3660
+ if isinstance(value, bool) or value in (None, ""):
3661
+ return None
3662
+ try:
3663
+ return float(str(value).strip().replace(",", "").replace("%", ""))
3664
+ except (TypeError, ValueError):
3665
+ return None
3666
+
3667
+
3668
+ def _intelligence_items(rows: list[dict[str, Any]], *, limit: int = 8, fallback: str = "--") -> list[dict[str, str]]:
3669
+ return [_intelligence_item(row, fallback=fallback) for row in rows[:limit]]
3670
+
3671
+
3672
+ def _latest_intelligence_rows(rows: list[dict[str, Any]], *, limit: int = 1) -> list[dict[str, Any]]:
3673
+ """Keep the newest provider records; several FTShare endpoints are oldest-first."""
3674
+ ordered = sorted(
3675
+ rows,
3676
+ key=lambda row: str(_workspace_value(row, "trade_date", "date", "time", "event_time") or ""),
3677
+ reverse=True,
3678
+ )
3679
+ return ordered[:limit]
3680
+
3681
+
3682
+ def _industry_flow_rows(rows: list[dict[str, Any]], *, limit: int = 8) -> list[dict[str, Any]]:
3683
+ """Return the strongest industry flows, never a provider's arbitrary regional prefix."""
3684
+ industries = [row for row in rows if str(_workspace_value(row, "sector_type", "board_type") or "").lower() == "industry"]
3685
+ # Only use untyped rows for older providers. A typed concept or regional
3686
+ # board must never be relabeled as an industry to fill an empty panel.
3687
+ has_types = any(_workspace_value(row, "sector_type", "board_type") for row in rows)
3688
+ candidates = industries if has_types else rows
3689
+ return sorted(
3690
+ candidates,
3691
+ key=lambda row: _intelligence_number(_workspace_value(row, "main_net", "net_inflow", "net_amount")) or float("-inf"),
3692
+ reverse=True,
3693
+ )[:limit]
3694
+
3695
+
3696
+ def _concept_flow_rows(rows: list[dict[str, Any]], *, limit: int = 8) -> list[dict[str, Any]]:
3697
+ """Return concept flows only when the provider explicitly labels them.
3698
+
3699
+ Concepts and industries look similar in a market UI, but they answer
3700
+ different questions. Never relabel an industry or regional board as a
3701
+ concept merely to fill a panel.
3702
+ """
3703
+ concepts = [row for row in rows if str(_workspace_value(row, "sector_type", "board_type") or "").lower() == "concept"]
3704
+ return sorted(
3705
+ concepts,
3706
+ key=lambda row: _intelligence_number(_workspace_value(row, "main_net", "net_inflow", "net_amount")) or float("-inf"),
3707
+ reverse=True,
3708
+ )[:limit]
3709
+
3710
+
3711
+ def _market_board_items(rows: list[dict[str, Any]], *, limit: int = 8) -> list[dict[str, str]]:
3712
+ """Keep the provider's verified board identifier beside its UI summary."""
3713
+ unique_rows = []
3714
+ seen = set()
3715
+ for row in rows:
3716
+ code = str(_workspace_value(row, "sector_code", "board_code", "code") or "").strip().upper()
3717
+ name = str(_workspace_value(row, "sector_name", "board_name", "board", "name") or "").strip()
3718
+ key = f"code:{code}" if code else f"name:{name}"
3719
+ if not name or key in seen:
3720
+ continue
3721
+ seen.add(key)
3722
+ unique_rows.append(row)
3723
+ if len(unique_rows) >= limit:
3724
+ break
3725
+ items = _intelligence_items(unique_rows, limit=limit, fallback="板块")
3726
+ for item, row in zip(items, unique_rows):
3727
+ # The SDK's board endpoint uses board_name, while older providers use
3728
+ # sector_name. Do not replace a real board name with the generic label.
3729
+ item["title"] = str(_workspace_value(row, "sector_name", "board_name", "board", "name") or item["title"])
3730
+ item["board_code"] = str(_workspace_value(row, "sector_code", "board_code", "code") or "")
3731
+ item["board_kind"] = str(_workspace_value(row, "sector_type", "board_type") or "")
3732
+ return items
3733
+
3734
+
3735
+ def _flow_history_items(
3736
+ rows: list[dict[str, Any]], *, limit: int, fallback: str, leader: bool = False,
3737
+ ) -> list[dict[str, str]]:
3738
+ """Render a dated flow history instead of repeating a sector or stock name.
3739
+
3740
+ Both the industry- and stock-flow endpoints return a *time series*. The
3741
+ generic intelligence normalizer used the constant name as each card title,
3742
+ so a user saw six identical "银行" or "招商银行" cards. Make time the
3743
+ primary identity and keep the related leader/price as supporting context.
3744
+ """
3745
+ items: list[dict[str, str]] = []
3746
+ for row in _latest_intelligence_rows(rows, limit=limit):
3747
+ raw_date = _workspace_value(row, "trade_date", "date", "time")
3748
+ if raw_date in (None, ""):
3749
+ # Preserve provider-neutral compatibility for adapters without a
3750
+ # dated history contract.
3751
+ items.append(_intelligence_item(row, fallback=fallback))
3752
+ continue
3753
+ date = str(raw_date).strip()
3754
+ compact_date = f"{date[4:6]}-{date[6:8]}" if re.fullmatch(r"\d{8}", date) else date
3755
+ net = _intelligence_number(_workspace_value(row, "main_net", "main_net_inflow", "net_inflow", "net_amount", "net_flow"))
3756
+ pct = _intelligence_number(_workspace_value(row, "main_pct", "main_net_pct", "change_pct", "pct_chg", "change_rate"))
3757
+ if row.get("change_rate") not in (None, "") and pct is not None:
3758
+ pct *= 100
3759
+ detail_parts: list[str] = []
3760
+ if leader:
3761
+ leader_name = _workspace_value(row, "leader_name", "leader", "leading_stock")
3762
+ leader_change = _intelligence_number(_workspace_value(row, "leader_change_pct", "leader_pct", "leader_change"))
3763
+ if leader_name:
3764
+ leader_label = f"领涨 {leader_name}"
3765
+ if leader_change is not None:
3766
+ leader_label += f" {_display_percent(leader_change)}"
3767
+ detail_parts.append(leader_label)
3768
+ else:
3769
+ close = _intelligence_number(_workspace_value(row, "close_price", "close", "price"))
3770
+ close_change = _intelligence_number(_workspace_value(row, "change_pct", "pct_chg", "change_rate"))
3771
+ if row.get("change_rate") not in (None, "") and close_change is not None:
3772
+ close_change *= 100
3773
+ if close is not None:
3774
+ close_label = f"收盘 {_display_number(close)}"
3775
+ if close_change is not None:
3776
+ close_label += f" · {_display_percent(close_change)}"
3777
+ detail_parts.append(close_label)
3778
+ items.append({
3779
+ "title": compact_date,
3780
+ "value": _display_number(net) if net is not None else "--",
3781
+ "change": _display_percent(pct) if pct is not None else "",
3782
+ "detail": " · ".join(detail_parts),
3783
+ # Net inflow/outflow is the semantic direction of a flow card;
3784
+ # do not let an unrelated price percentage recolor it.
3785
+ "tone": "up" if net is not None and net > 0 else "down" if net is not None and net < 0 else "",
3786
+ })
3787
+ return items
3788
+
3789
+
3790
+ def _market_rank_items(rows: list[dict[str, Any]], *, market: str = "CN", limit: int = 8) -> list[dict[str, str]]:
3791
+ """Normalize a market leaderboard while retaining an actionable symbol."""
3792
+ items: list[dict[str, str]] = []
3793
+ for row in rows[:limit]:
3794
+ item = _intelligence_item(row, fallback="--")
3795
+ raw_symbol = _workspace_value(row, "symbol", "normalized_symbol", "stock_code", "code", "security_code", "ticker")
3796
+ symbol = _canonical_directory_symbol(raw_symbol, market=market, default_market=market)
3797
+ name = _workspace_value(row, "stock_name", "symbol_name", "security_name", "name")
3798
+ price = _workspace_value(row, "latest_price", "price", "current_price", "close", "close_price")
3799
+ change = _workspace_value(row, "change_pct", "pct_chg", "change_rate", "pct_change", "change")
3800
+ rank = _workspace_value(row, "rank", "ranking", "rank_no")
3801
+ heat = _workspace_value(row, "metric_value", "heat", "popularity")
3802
+ if row.get("change_rate") not in (None, "") and _intelligence_number(change) is not None:
3803
+ change = (_intelligence_number(change) or 0) * 100
3804
+ item["title"] = str(name or item["title"])
3805
+ item["symbol"] = symbol
3806
+ item["value"] = _display_number(_intelligence_number(price)) if _intelligence_number(price) is not None else item["value"]
3807
+ item["change"] = _display_percent(_intelligence_number(change)) if _intelligence_number(change) is not None else item["change"]
3808
+ item["detail"] = " · ".join(
3809
+ part for part in (symbol, f"#{rank}" if rank not in (None, "") else "", _display_number(_intelligence_number(heat)) if heat not in (None, "") else "") if part
3810
+ )
3811
+ items.append(item)
3812
+ return items
3813
+
3814
+
3815
+ def _abnormal_trading_items(rows: list[dict[str, Any]], *, market: Any = None, limit: int = 20) -> list[dict[str, str]]:
3816
+ """Normalize 龙虎榜 rows into clickable market activity cards.
3817
+
3818
+ The overview endpoint only provides a list of symbols; the detail endpoint
3819
+ also supplies the brokerage seats needed for a meaningful buy/sell ranking.
3820
+ Keep the compact overview shape when details are unavailable, but expose a
3821
+ five-seat net amount whenever the provider returned one.
3822
+ """
3823
+ items: list[dict[str, str]] = []
3824
+ for row in rows[:limit]:
3825
+ symbol = _canonical_directory_symbol(_workspace_value(row, "symbol", "stock_code", "code"), default_market="CN")
3826
+ change = _intelligence_number(_workspace_value(row, "change_rate", "change_pct", "pct_chg"))
3827
+ if row.get("change_rate") not in (None, "") and change is not None:
3828
+ change *= 100
3829
+ turnover = _intelligence_number(_workspace_value(row, "turnover", "amount", "volume"))
3830
+ name = str(_workspace_value(row, "symbol_name", "stock_name", "name") or "").strip()
3831
+ # Detail rows do not always repeat the security name. Prefer the
3832
+ # overview enrichment above, then use the existing local directory / a
3833
+ # targeted FTShare lookup rather than exposing a bare code as a name.
3834
+ if not name or name.upper() in {symbol.upper(), symbol.split(".", 1)[0].upper()}:
3835
+ resolved = _symbol_name(market, symbol)
3836
+ if resolved and str(resolved).upper() not in {symbol.upper(), symbol.split(".", 1)[0].upper()}:
3837
+ name = str(resolved)
3838
+ item: dict[str, Any] = {
3839
+ "title": name or symbol or "--",
3840
+ "symbol": symbol,
3841
+ "value": _display_number(_intelligence_number(_workspace_value(row, "close", "latest_price", "price"))),
3842
+ "change": _display_percent(change) if change is not None else "",
3843
+ "detail": f"成交额 {_display_number(turnover)}" if turnover is not None else symbol,
3844
+ }
3845
+ seat_nets: dict[str, float] = {}
3846
+ for seat in [*_workspace_rows(_workspace_value(row, "top_buyers")), *_workspace_rows(_workspace_value(row, "top_sellers"))]:
3847
+ name = str(_workspace_value(seat, "name", "broker_name", "seat_name") or "").strip()
3848
+ net = _intelligence_number(_workspace_value(seat, "net", "net_amount", "net_buy"))
3849
+ if not name or net is None:
3850
+ continue
3851
+ # A broker can be present in both lists. It denotes the same seat,
3852
+ # so retain one value rather than counting its net flow twice.
3853
+ previous = seat_nets.get(name)
3854
+ if previous is None or abs(net) > abs(previous):
3855
+ seat_nets[name] = net
3856
+ if seat_nets:
3857
+ five_seat_net = sum(seat_nets.values())
3858
+ item.update({
3859
+ "five_seat_net": _display_number(five_seat_net),
3860
+ "five_seat_net_value": five_seat_net,
3861
+ "five_seat_label": "五席净额",
3862
+ "tone": "up" if five_seat_net > 0 else "down" if five_seat_net < 0 else "",
3863
+ })
3864
+ items.append(item)
3865
+ return items
3866
+
3867
+
3868
+ def _primary_industry(value: Any) -> str:
3869
+ """Turn provider category bundles into one queryable industry label.
3870
+
3871
+ Company metadata sometimes returns a comma-separated set of concepts,
3872
+ indexes and styles. Sector endpoints expect one industry name, so using
3873
+ the entire bundle would make an otherwise available section look broken.
3874
+ """
3875
+ raw = str(value or "").strip()
3876
+ if not raw:
3877
+ return ""
3878
+ return re.split(r"[,,;;、|/]", raw, maxsplit=1)[0].strip()[:80]
3879
+
3880
+
3881
+ def _intelligence_section_state(
3882
+ rows: list[dict[str, Any]], errors: list[dict[str, str]], *, unsupported: bool = False,
3883
+ ) -> dict[str, Any]:
3884
+ if rows:
3885
+ return {"state": "partial" if errors else "available", "errors": errors}
3886
+ if unsupported:
3887
+ return {"state": "unsupported", "errors": errors}
3888
+ return {"state": "error" if errors else "empty", "errors": errors}
3889
+
3890
+
3891
+ def _read_intelligence_section(
3892
+ market_client: Any,
3893
+ errors: dict[str, list[dict[str, str]]],
3894
+ section: str,
3895
+ method_name: str,
3896
+ **kwargs: Any,
3897
+ ) -> list[dict[str, Any]]:
3898
+ """Read an optional FTShare endpoint without breaking adjacent sections."""
3899
+ method = getattr(market_client, method_name, None)
3900
+ if not callable(method):
3901
+ errors.setdefault(section, []).append({"code": "unsupported", "message": f"missing endpoint: {method_name}"})
3902
+ return []
3903
+ for attempt in range(3):
3904
+ try:
3905
+ return _workspace_rows(method(as_dataframe=False, **kwargs))
3906
+ except Exception as exc: # noqa: BLE001 - provider diagnostics become structured states
3907
+ code, message = _classify_ftshare_error(exc)
3908
+ if code == "rate_limited" and attempt < 2:
3909
+ time.sleep(0.15 * (attempt + 1))
3910
+ continue
3911
+ errors.setdefault(section, []).append({"code": code, "message": message})
3912
+ return []
3913
+ return []
3914
+
3915
+
3916
+ def _provider_unavailable_intelligence(kind: str, *, symbol: str = "") -> dict[str, Any]:
3917
+ sections = ("breadth", "flows", "sectors", "concepts", "rankings", "events") if kind == "market_pulse" else ("sector", "flows", "events")
3918
+ key_configured = _ftshare_credential_source() != "none"
3919
+ result = {
3920
+ "ok": True,
3921
+ "source": {"name": "FTShare", "status": "unavailable"},
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",
3925
+ }
3926
+ if symbol:
3927
+ result["symbol"] = symbol
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."}
3930
+ return result
3931
+
3932
+
3933
+ def fetch_market_pulse(*, refresh: bool = False, sections: Sequence[str] | None = None) -> dict[str, Any]:
3934
+ """Return a provider-neutral, best-effort mainland market pulse.
3935
+
3936
+ This is a standalone market-intelligence primitive: the chart UI, an agent,
3937
+ and another MCP client all consume the same compact schema. A missing
3938
+ premium endpoint degrades one section only; it never makes the entire
3939
+ pulse look like a failed data source.
3940
+ """
3941
+ global _market_pulse_cache
3942
+ selected_sections = _MARKET_PULSE_SECTIONS if sections is None else sections
3943
+ requested = {str(section).strip().lower() for section in selected_sections} & _MARKET_PULSE_SECTIONS
3944
+ full_request = requested == _MARKET_PULSE_SECTIONS
3945
+ now = time.time()
3946
+ # Market-intelligence endpoints have no anonymous fallback. Avoid a burst
3947
+ # of doomed requests when the SDK is installed but no key is configured.
3948
+ if not ftshare_available() or _ftshare_credential_source() == "none":
3949
+ return _provider_unavailable_intelligence("market_pulse")
3950
+ if full_request and not refresh and _market_pulse_cache and now - _market_pulse_cache[0] < _MARKET_PULSE_CACHE_TTL_SECONDS:
3951
+ return {**_market_pulse_cache[1], "cached": True}
3952
+ market = _ftshare_market_api(timeout=12)
3953
+ errors: dict[str, list[dict[str, str]]] = {}
3954
+ trade_date = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y%m%d")
3955
+ rank_trade_date = datetime.now(ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d")
3956
+
3957
+ # Each logical group is fetched at most once per TTL window and concurrent
3958
+ # identical group loads share a single upstream attempt. The date keys
3959
+ # participate in the scope so a stale cache can never leak across a session
3960
+ # boundary (the previous day's rows would otherwise be served as today's).
3961
+ def _read_group(name: str, reader: Any) -> Any:
3962
+ scope = f"{name}:{trade_date}"
3963
+ cached = _cached_market_pulse_section(scope, refresh=refresh)
3964
+ if cached is not None:
3965
+ return cached
3966
+ with _market_pulse_section_lock(scope):
3967
+ # Re-check after acquiring: a concurrent caller may have just
3968
+ # populated the entry while this one was waiting.
3969
+ cached = _cached_market_pulse_section(scope, refresh=refresh)
3970
+ if cached is not None:
3971
+ return cached
3972
+ value = reader()
3973
+ return value
3974
+
3975
+ def _load_breadth() -> dict[str, Any]:
3976
+ local: dict[str, list[dict[str, str]]] = {}
3977
+ # SDK 1.x uses the documented words rather than the older U/D aliases.
3978
+ up = _read_intelligence_section(market, local, "breadth", "limit_list", limit_type="up", trade_date=trade_date)
3979
+ down = _read_intelligence_section(market, local, "breadth", "limit_list", limit_type="down", trade_date=trade_date)
3980
+ return {"up": up, "down": down, "errors": local}
3981
+
3982
+ def _load_flows() -> dict[str, Any]:
3983
+ local: dict[str, list[dict[str, str]]] = {}
3984
+ # These endpoints are oldest-first. Request enough rows to locate the
3985
+ # latest market reading rather than displaying January data in September.
3986
+ market_flow = _read_intelligence_section(market, local, "flows", "eastmoney_dapan_flow", limit=500)
3987
+ northbound = _read_intelligence_section(market, local, "flows", "northbound", date=trade_date)
3988
+ southbound = _read_intelligence_section(market, local, "flows", "southbound", date=trade_date)
3989
+ return {"market": market_flow, "northbound": northbound, "southbound": southbound, "errors": local}
3990
+
3991
+ def _load_boards() -> dict[str, Any]:
3992
+ local: dict[str, list[dict[str, str]]] = {}
3993
+ sector = _read_intelligence_section(market, local, "sectors", "eastmoney_sector_flow", limit=500)
3994
+ return {"sectors": sector, "errors": local}
3995
+
3996
+ def _load_rankings() -> dict[str, Any]:
3997
+ local: dict[str, list[dict[str, str]]] = {}
3998
+ hot = _read_intelligence_section(
3999
+ market, local, "rankings", "eastmoney_rank", rank_group="hot", market="A", trade_date=rank_trade_date,
4000
+ )
4001
+ surging = _read_intelligence_section(
4002
+ market, local, "rankings", "eastmoney_rank", rank_group="up", market="A", trade_date=rank_trade_date,
4003
+ )
4004
+ # Eastmoney's ranking endpoint can be temporarily rate-limited even when
4005
+ # its free data exists. Snowball's attention rank is a like-for-like
4006
+ # fallback for the *popularity* view only; it is never mislabeled as a
4007
+ # price-momentum leaderboard.
4008
+ source = "eastmoney"
4009
+ if not hot:
4010
+ hot = _read_intelligence_section(
4011
+ market, local, "rankings", "xueqiu_rank", rank_group="follow", period="total", limit=8,
4012
+ )
4013
+ source = "xueqiu" if hot else ""
4014
+ return {"hot": hot, "surging": surging, "source": source, "errors": local}
4015
+
4016
+ def _load_events() -> dict[str, Any]:
4017
+ local: dict[str, list[dict[str, str]]] = {}
4018
+ abnormal = _read_intelligence_section(market, local, "events", "abnormal_trading_details", date=trade_date, limit=20)
4019
+ # During a trading day the endpoint may expose its latest completed
4020
+ # snapshot without a same-day date key.
4021
+ if not abnormal:
4022
+ abnormal = _read_intelligence_section(market, local, "events", "abnormal_trading_details", limit=20)
4023
+ overview = _read_intelligence_section(market, local, "events", "abnormal_trading_overview", date=trade_date, limit=20)
4024
+ if not overview:
4025
+ overview = _read_intelligence_section(market, local, "events", "abnormal_trading_overview", limit=20)
4026
+ # Details carry the broker-seat ledger but currently omit the security
4027
+ # name. Enrich each detail row from the matching overview row; this is
4028
+ # still one coherent provider snapshot, not a guessed local mapping.
4029
+ if abnormal and overview:
4030
+ overview_by_symbol = {
4031
+ _canonical_directory_symbol(_workspace_value(row, "symbol", "stock_code", "code"), default_market="CN"): row
4032
+ for row in overview
4033
+ }
4034
+ abnormal = [
4035
+ {**overview_by_symbol.get(_canonical_directory_symbol(_workspace_value(row, "symbol", "stock_code", "code"), default_market="CN"), {}), **row}
4036
+ for row in abnormal
4037
+ ]
4038
+ # Older SDKs or temporary provider rollouts may omit the detail route.
4039
+ # The overview remains actionable, but the UI will label it as a plain
4040
+ # symbol list rather than pretend it is a net-flow ranking.
4041
+ if not abnormal:
4042
+ abnormal = overview
4043
+ return {"abnormal": abnormal, "errors": local}
4044
+
4045
+ want_boards = bool({"sectors", "concepts"} & requested)
4046
+ groups: dict[str, dict[str, Any]] = {}
4047
+ group_readers = (
4048
+ ("breadth", _load_breadth, "breadth" in requested),
4049
+ ("flows", _load_flows, "flows" in requested),
4050
+ ("boards", _load_boards, want_boards),
4051
+ ("rankings", _load_rankings, "rankings" in requested),
4052
+ ("events", _load_events, "events" in requested),
4053
+ )
4054
+ for group_name, reader, wanted in group_readers:
4055
+ if not wanted:
4056
+ continue
4057
+ groups[group_name] = _read_group(group_name, reader)
4058
+ for section_errors in (groups[group_name].get("errors") or {}).items():
4059
+ section_key, entries = section_errors
4060
+ if entries:
4061
+ errors.setdefault(section_key, []).extend(entries)
4062
+
4063
+ up_rows = list((groups.get("breadth") or {}).get("up") or [])
4064
+ down_rows = list((groups.get("breadth") or {}).get("down") or [])
4065
+ flow_group = groups.get("flows") or {}
4066
+ market_flow_rows = list(flow_group.get("market") or [])
4067
+ northbound_rows = list(flow_group.get("northbound") or [])
4068
+ southbound_rows = list(flow_group.get("southbound") or [])
4069
+ sector_rows = list((groups.get("boards") or {}).get("sectors") or [])
4070
+ rank_group = groups.get("rankings") or {}
4071
+ hot_rank_rows = list(rank_group.get("hot") or [])
4072
+ surging_rank_rows = list(rank_group.get("surging") or [])
4073
+ hot_rank_source = str(rank_group.get("source") or "")
4074
+ abnormal_rows = list((groups.get("events") or {}).get("abnormal") or [])
4075
+ breadth = [
4076
+ {"title": "涨停", "value": str(len(up_rows)), "detail": "当日涨停池", "change": "", "tone": "up"},
4077
+ {"title": "跌停", "value": str(len(down_rows)), "detail": "当日跌停池", "change": "", "tone": "down"},
4078
+ ]
4079
+ latest_market_rows = _latest_intelligence_rows(market_flow_rows)
4080
+ latest_northbound_rows = _latest_intelligence_rows(northbound_rows)
4081
+ latest_southbound_rows = _latest_intelligence_rows(southbound_rows)
4082
+ industry_rows = _industry_flow_rows(sector_rows)
4083
+ concept_rows = _concept_flow_rows(sector_rows)
4084
+ flow_rows = [*latest_market_rows, *latest_northbound_rows, *latest_southbound_rows]
4085
+ as_of_rows = [*up_rows, *down_rows, *flow_rows, *industry_rows]
4086
+ as_of = _latest_intelligence_rows(as_of_rows)
4087
+ pulse: dict[str, Any] = {"as_of": str(_workspace_value(as_of[0], "trade_date", "date", "time") or trade_date) if as_of else trade_date}
4088
+ if "breadth" in requested:
4089
+ pulse["breadth"] = breadth
4090
+ if "flows" in requested:
4091
+ pulse["flows"] = _intelligence_items(flow_rows, limit=5, fallback="资金流")
4092
+ if "sectors" in requested:
4093
+ pulse["hot_sectors"] = _market_board_items(industry_rows, limit=8)
4094
+ if "concepts" in requested:
4095
+ pulse["hot_concepts"] = _market_board_items(concept_rows, limit=8)
4096
+ if "rankings" in requested:
4097
+ pulse["rankings"] = {
4098
+ "hot": _market_rank_items(hot_rank_rows, market="CN"),
4099
+ "surging": _market_rank_items(surging_rank_rows, market="CN"),
4100
+ "hot_source": hot_rank_source,
4101
+ }
4102
+ if "events" in requested:
4103
+ pulse["abnormal_trading"] = _abnormal_trading_items(abnormal_rows, market=market)
4104
+ result = {
4105
+ "ok": True,
4106
+ "cached": False,
4107
+ "source": {"name": "FTShare", "status": "retrieved", "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")},
4108
+ "market_pulse": pulse,
4109
+ "sections": {
4110
+ "breadth": _intelligence_section_state([*up_rows, *down_rows], errors.get("breadth", [])) if "breadth" in requested else {"state": "deferred", "errors": []},
4111
+ "flows": _intelligence_section_state(flow_rows, errors.get("flows", [])) if "flows" in requested else {"state": "deferred", "errors": []},
4112
+ "sectors": _intelligence_section_state(industry_rows, errors.get("sectors", [])) if "sectors" in requested else {"state": "deferred", "errors": []},
4113
+ "concepts": _intelligence_section_state(concept_rows, errors.get("concepts", [])) if "concepts" in requested else {"state": "deferred", "errors": []},
4114
+ "rankings": _intelligence_section_state([*hot_rank_rows, *surging_rank_rows], errors.get("rankings", [])) if "rankings" in requested else {"state": "deferred", "errors": []},
4115
+ "events": _intelligence_section_state(abnormal_rows, errors.get("events", [])) if "events" in requested else {"state": "deferred", "errors": []},
4116
+ },
4117
+ }
4118
+ if full_request and not any(errors.values()):
4119
+ _market_pulse_cache = (now, result)
4120
+ # Store only groups that actually returned data. Caching an empty result
4121
+ # would pin a transient provider failure for the whole TTL window and turn
4122
+ # a momentary hiccup into a 90-second outage.
4123
+ if not refresh:
4124
+ fresh_at = time.time()
4125
+ for group_name, payload in groups.items():
4126
+ if payload and not payload.get("errors"):
4127
+ _market_pulse_section_cache[f"{group_name}:{trade_date}"] = (fresh_at, deepcopy(payload))
4128
+ return result
4129
+
4130
+
4131
+ def fetch_market_board_detail(
4132
+ name: str, *, board_code: str | None = None, kind: str = "industry", refresh: bool = False,
4133
+ ) -> dict[str, Any]:
4134
+ """Read one board's verified snapshot and available funding history.
4135
+
4136
+ Board identifiers are vendor-specific. We only promise the information
4137
+ that is returned for the selected code; membership is explicitly marked
4138
+ source-dependent until its endpoint accepts the same identifier.
4139
+ """
4140
+ label = str(name or "").strip()[:80]
4141
+ code = str(board_code or "").strip()[:40]
4142
+ requested_kind = str(kind or "industry").strip().lower()
4143
+ if not label and not code:
4144
+ return {"ok": False, "error": "invalid_board", "message": "board name or code is required"}
4145
+ if requested_kind not in {"industry", "concept"}:
4146
+ return {"ok": False, "error": "invalid_board_kind", "message": "board kind must be industry or concept"}
4147
+ if not ftshare_available():
4148
+ return _provider_unavailable_intelligence("market_pulse")
4149
+ market = _ftshare_market_api(timeout=12)
4150
+ errors: dict[str, list[dict[str, str]]] = {}
4151
+ snapshot_rows = _read_intelligence_section(market, errors, "board", "eastmoney_sector_flow", limit=500)
4152
+ board = next((row for row in snapshot_rows if
4153
+ ((code and str(_workspace_value(row, "sector_code", "board_code") or "") == code)
4154
+ or (not code and str(_workspace_value(row, "sector_name", "board_name") or "") == label))
4155
+ and str(_workspace_value(row, "sector_type", "board_type") or "").lower() == requested_kind), None)
4156
+ if board is None:
4157
+ return {
4158
+ "ok": True,
4159
+ "board": {"name": label or code, "code": code, "kind": requested_kind, "snapshot": {}, "history": [], "members": []},
4160
+ "sections": {"board": _intelligence_section_state([], errors.get("board", [])), "members": {"state": "source_dependent", "errors": []}},
4161
+ "source": {"name": "FTShare", "status": "empty"},
4162
+ }
4163
+ resolved_name = str(_workspace_value(board, "sector_name", "board_name") or label)
4164
+ resolved_kind = str(_workspace_value(board, "sector_type", "board_type") or requested_kind).lower()
4165
+ history_rows: list[dict[str, Any]] = []
4166
+ if resolved_kind == "industry":
4167
+ end = datetime.now(ZoneInfo("Asia/Shanghai")).date()
4168
+ history_rows = _read_intelligence_section(
4169
+ market, errors, "board", "ths_industry_daily_flow", sector_name=resolved_name,
4170
+ start_date=(end - timedelta(days=12)).strftime("%Y%m%d"), end_date=end.strftime("%Y%m%d"), limit=10,
4171
+ )
4172
+ snapshot = _intelligence_item(board, fallback=resolved_name)
4173
+ snapshot["title"] = resolved_name
4174
+ return {
4175
+ "ok": True,
4176
+ "board": {
4177
+ "name": resolved_name,
4178
+ "code": str(_workspace_value(board, "sector_code", "board_code") or code),
4179
+ "kind": resolved_kind,
4180
+ "snapshot": snapshot,
4181
+ "history": _flow_history_items(history_rows, limit=6, fallback=resolved_name, leader=True),
4182
+ "members": [],
4183
+ },
4184
+ "sections": {
4185
+ "board": _intelligence_section_state([board, *history_rows], errors.get("board", [])),
4186
+ "members": {"state": "source_dependent", "errors": []},
4187
+ },
4188
+ "source": {"name": "FTShare", "status": "retrieved", "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")},
4189
+ }
4190
+
4191
+
4192
+ def fetch_security_intelligence(symbol: str, *, name: str | None = None, refresh: bool = False) -> dict[str, Any]:
4193
+ """Load sector linkage, capital flow, and event context for one symbol.
4194
+
4195
+ The response is intentionally independent of ``fetch_security_workspace``.
4196
+ It can be shown in the workbench, called by an agent, or composed by a
4197
+ future Market Intelligence Core without coupling to a chart session.
4198
+ """
4199
+ sym = _canonical_market_symbol(symbol)
4200
+ if not sym:
4201
+ return {"ok": False, "error": "invalid_symbol", "message": "symbol is required"}
4202
+ if _broad_index_for_symbol(sym) or sym in GLOBAL_INDEX_SOURCES:
4203
+ return {
4204
+ "ok": True,
4205
+ "symbol": sym,
4206
+ "source": {"name": "FTShare", "status": "not_applicable"},
4207
+ "security_intelligence": {"name": name or sym, "instrument_type": "index", "sector": {}, "flows": [], "events": []},
4208
+ "sections": {section: {"state": "not_applicable", "errors": []} for section in ("sector", "flows", "events")},
4209
+ }
4210
+ if _is_etf_symbol(sym):
4211
+ return {
4212
+ "ok": True,
4213
+ "symbol": sym,
4214
+ "source": {"name": "FTShare", "status": "not_applicable"},
4215
+ "security_intelligence": {"name": name or sym, "instrument_type": "etf", "sector": {}, "flows": [], "events": []},
4216
+ "sections": {"sector": {"state": "not_applicable", "errors": []}, "flows": {"state": "unsupported", "errors": []}, "events": {"state": "not_applicable", "errors": []}},
4217
+ }
4218
+ key = sym.upper()
4219
+ cached = _security_intelligence_cache.get(key)
4220
+ now = time.time()
4221
+ if not refresh and cached and now - cached[0] < _SECURITY_INTELLIGENCE_CACHE_TTL_SECONDS:
4222
+ return {**cached[1], "cached": True}
4223
+ if not ftshare_available():
4224
+ return _provider_unavailable_intelligence("security_intelligence", symbol=sym)
4225
+ market_name = _workspace_market(sym)
4226
+ if market_name != "CN":
4227
+ return {
4228
+ "ok": True,
4229
+ "symbol": sym,
4230
+ "source": {"name": "FTShare", "status": "limited"},
4231
+ "security_intelligence": {"name": name or sym, "instrument_type": "stock", "sector": {}, "flows": [], "events": []},
4232
+ "sections": {section: {"state": "unsupported", "errors": []} for section in ("sector", "flows", "events")},
4233
+ }
4234
+ market = _ftshare_market_api(timeout=12)
4235
+ errors: dict[str, list[dict[str, str]]] = {}
4236
+ code = _cn_stock_code(sym)
4237
+ bare = code.split(".")[0]
4238
+ basic_rows = _read_intelligence_section(market, errors, "sector", "company_list", stock_code=bare, limit=1)
4239
+ industry = _primary_industry(_workspace_value(basic_rows[0], "industry", "industry_name", "sector", "bk")) if basic_rows else ""
4240
+ flow_rows = _read_intelligence_section(market, errors, "flows", "eastmoney_stock_flow", symbol=code, limit=10)
4241
+ if not flow_rows:
4242
+ flow_rows = _read_intelligence_section(market, errors, "flows", "ths_stock_daily_flow", code=bare, limit=10)
4243
+ event_rows = _read_intelligence_section(market, errors, "events", "limit_event_timeline_3s", symbol=code)
4244
+ industry_rows: list[dict[str, Any]] = []
4245
+ peer_rows: list[dict[str, Any]] = []
4246
+ if industry:
4247
+ industry_end = datetime.now(ZoneInfo("Asia/Shanghai")).date()
4248
+ industry_start = industry_end - timedelta(days=10)
4249
+ industry_rows = _read_intelligence_section(
4250
+ market,
4251
+ errors,
4252
+ "sector",
4253
+ "ths_industry_daily_flow",
4254
+ sector_name=industry,
4255
+ start_date=industry_start.strftime("%Y%m%d"),
4256
+ end_date=industry_end.strftime("%Y%m%d"),
4257
+ limit=10,
4258
+ )
4259
+ peer_rows = _read_intelligence_section(market, errors, "sector", "supply_chain_subsubindustry_companies", subindustry_name=industry)
4260
+ intelligence = {
4261
+ "name": name or _symbol_name(market, sym),
4262
+ "instrument_type": "stock",
4263
+ "sector": {
4264
+ "industry": industry or "--",
4265
+ "flow": _flow_history_items(industry_rows, limit=8, fallback=industry or "行业资金", leader=True),
4266
+ "peers": _intelligence_items(peer_rows, limit=12, fallback="同类公司"),
4267
+ },
4268
+ "flows": _flow_history_items(flow_rows, limit=10, fallback="个股资金"),
4269
+ "events": _intelligence_items(event_rows, limit=10, fallback="交易事件"),
4270
+ }
4271
+ result = {
4272
+ "ok": True,
4273
+ "cached": False,
4274
+ "symbol": sym,
4275
+ "source": {"name": "FTShare", "status": "retrieved", "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")},
4276
+ "security_intelligence": intelligence,
4277
+ "sections": {
4278
+ "sector": _intelligence_section_state([*basic_rows, *industry_rows, *peer_rows], errors.get("sector", [])),
4279
+ "flows": _intelligence_section_state(flow_rows, errors.get("flows", [])),
4280
+ "events": _intelligence_section_state(event_rows, errors.get("events", [])),
4281
+ },
4282
+ }
4283
+ if not any(errors.values()):
4284
+ _security_intelligence_cache[key] = (now, result)
4285
+ return result
4286
+
4287
+
4288
+ def _display_number(value: Any) -> str:
4289
+ try:
4290
+ number = float(value)
4291
+ except (TypeError, ValueError):
4292
+ return "--"
4293
+ absolute = abs(number)
4294
+ if absolute >= 100_000_000:
4295
+ return f"{number / 100_000_000:.2f}亿"
4296
+ if absolute >= 10_000:
4297
+ return f"{number / 10_000:.2f}万"
4298
+ return f"{number:,.2f}".rstrip("0").rstrip(".")
4299
+
4300
+
4301
+ def _cn_stock_code(symbol: str) -> str:
4302
+ normalized = str(symbol or "").strip().upper()
4303
+ return normalized.replace(".XSHG", ".SH").replace(".XSHE", ".SZ")
4304
+
4305
+
4306
+ def _workspace_market(symbol: str) -> str:
4307
+ normalized = str(symbol or "").strip().upper()
4308
+ if _is_us_symbol(normalized):
4309
+ return "US"
4310
+ if normalized.endswith((".HK", ".HKG")) or normalized.startswith("100.HSI"):
4311
+ return "HK"
4312
+ return "CN"
4313
+
4314
+
4315
+ def _workspace_news(rows: list[dict[str, Any]]) -> list[dict[str, str]]:
4316
+ """Normalize articles while retaining source provenance when supplied."""
4317
+ items: list[dict[str, str]] = []
4318
+ for row in rows[:12]:
4319
+ title = _workspace_value(row, "title", "news_title", "headline", "name")
4320
+ if not title:
4321
+ continue
4322
+ items.append(
4323
+ {
4324
+ "title": str(title),
4325
+ "time": str(_workspace_value(row, "time", "publish_time", "datetime", "date") or "--"),
4326
+ "summary": str(_workspace_value(row, "summary", "content", "abstract", "digest") or ""),
4327
+ "kind": str(_workspace_value(row, "kind", "source", "media", "category") or "资讯"),
4328
+ "source_url": str(_workspace_value(row, "source_url", "url", "link", "article_url") or ""),
4329
+ "article_id": str(_workspace_value(row, "article_id", "news_id", "id", "uuid") or ""),
4330
+ "entity_id": str(_workspace_value(row, "symbol", "security_id", "entity_id", "stock_code") or ""),
4331
+ }
4332
+ )
4333
+ return items
4334
+
4335
+
4336
+ def _workspace_financials(rows: list[dict[str, Any]]) -> dict[str, Any]:
4337
+ normalized_rows: list[list[str]] = []
4338
+ metrics: list[dict[str, str]] = []
4339
+ for index, row in enumerate(rows[:8]):
4340
+ period = _workspace_value(row, "report_date", "end_date", "period", "report_period", "report_type_cn", "date") or "--"
4341
+ # FTShare's wide A-share income records use t_revenue/n_profit while
4342
+ # other adapters commonly use total_revenue/net_income. Keep both
4343
+ # families so a valid record never becomes a row of placeholder values.
4344
+ revenue = _workspace_value(row, "total_operate_income", "total_revenue", "t_revenue", "revenue", "operating_revenue")
4345
+ profit = _workspace_value(row, "net_profit", "n_profit", "net_income", "netprofit", "parent_netprofit", "parcomp_n_profit")
4346
+ margin = _workspace_value(row, "gross_margin", "grossprofit_margin")
4347
+ cash = _workspace_value(row, "operate_cash_flow", "operating_cash_flow", "cash_from_operations")
4348
+ normalized_rows.append([str(period), _display_number(revenue), _display_number(profit), _display_number(margin), _display_number(cash)])
4349
+ if index == 0:
4350
+ for label, value in (("营业收入", revenue), ("净利润", profit), ("毛利率", margin), ("经营现金流", cash)):
4351
+ if value not in (None, ""):
4352
+ metrics.append({"label": label, "value": _display_number(value)})
4353
+ currency = _workspace_value(rows[0], "currency", "currency_code", "unit", "currency_unit") if rows else None
4354
+ return {"metrics": metrics, "rows": normalized_rows, "unit": str(currency or "未声明")}
4355
+
4356
+
4357
+ def _workspace_holders(rows: list[dict[str, Any]]) -> dict[str, Any]:
4358
+ flattened: list[dict[str, Any]] = []
4359
+ for record in rows:
4360
+ nested = record.get("fen_holders")
4361
+ if isinstance(nested, list):
4362
+ for item in nested:
4363
+ if isinstance(item, Mapping):
4364
+ flattened.append(
4365
+ {
4366
+ **dict(item),
4367
+ "report_date": _workspace_value(record, "report_date", "publish_date", "end_date", "date"),
4368
+ }
4369
+ )
4370
+ else:
4371
+ flattened.append(record)
4372
+ items: list[dict[str, Any]] = []
4373
+ for row in flattened[:10]:
4374
+ name = _workspace_value(row, "holder_name", "shareholder_name", "name", "holder")
4375
+ if not name:
4376
+ continue
4377
+ percent = _workspace_value(row, "hold_ratio", "holding_ratio", "shareholding_ratio", "share_ratio", "percent", "ratio")
4378
+ shares = _workspace_value(row, "hold_amount", "holding_amount", "shareholding", "shares", "hold_num")
4379
+ change = _workspace_value(row, "change_ratio", "change_percentage", "change", "hold_change")
4380
+ try:
4381
+ percent_number = float(percent) if percent not in (None, "") else 0.0
4382
+ except (TypeError, ValueError):
4383
+ percent_number = 0.0
4384
+ items.append({"name": str(name), "percent": percent_number, "shares": _display_number(shares), "change": str(change or "--")})
4385
+ updated = _workspace_value(rows[0], "report_date", "publish_date", "end_date", "date") if rows else None
4386
+ return {"updated_at": str(updated or "--"), "items": items}
4387
+
4388
+
4389
+ def _workspace_overview_metrics(
4390
+ financials: Mapping[str, Any], balance_rows: list[dict[str, Any]], cashflow_rows: list[dict[str, Any]]
4391
+ ) -> list[dict[str, str]]:
4392
+ """Build a compact factual company snapshot from FTShare wide tables."""
4393
+ metrics = list(financials.get("metrics") or [])[:2]
4394
+ balance = balance_rows[0] if balance_rows else {}
4395
+ cashflow = cashflow_rows[0] if cashflow_rows else {}
4396
+ assets = _workspace_value(balance, "t_assets", "total_assets", "assets")
4397
+ liability_ratio = _workspace_value(balance, "asset_liability_ratio", "debt_to_assets")
4398
+ operating_cash = _workspace_value(cashflow, "net_oper_cash_flow", "operate_cash_flow", "operating_cash_flow")
4399
+ if assets not in (None, ""):
4400
+ metrics.append({"label": "总资产", "value": _display_number(assets)})
4401
+ if liability_ratio not in (None, ""):
4402
+ try:
4403
+ metrics.append({"label": "资产负债率", "value": f"{float(liability_ratio):.2f}%"})
4404
+ except (TypeError, ValueError):
4405
+ pass
4406
+ if operating_cash not in (None, ""):
4407
+ metrics.append({"label": "经营现金流", "value": _display_number(operating_cash)})
4408
+ return metrics[:5]
4409
+
4410
+
4411
+ def _display_percent(value: Any) -> str:
4412
+ try:
4413
+ number = float(value)
4414
+ except (TypeError, ValueError):
4415
+ return "--"
4416
+ return f"{number:.2f}%"
4417
+
4418
+
4419
+ def _workspace_overview_details(
4420
+ *,
4421
+ basic: Mapping[str, Any],
4422
+ financial_rows: list[dict[str, Any]],
4423
+ balance_rows: list[dict[str, Any]],
4424
+ cashflow_rows: list[dict[str, Any]],
4425
+ holder_count_rows: list[dict[str, Any]],
4426
+ pledge_rows: list[dict[str, Any]],
4427
+ share_change_rows: list[dict[str, Any]],
4428
+ ) -> list[dict[str, str]]:
4429
+ """Normalize the factual fields that make an equity profile actionable.
4430
+
4431
+ FTShare endpoints use different field names across source families. Keep a
4432
+ compact, de-duplicated list so the frontend can omit unavailable fields
4433
+ instead of rendering a table full of placeholders.
4434
+ """
4435
+ details: list[dict[str, str]] = []
4436
+ seen: set[str] = set()
4437
+
4438
+ def add(label: str, value: Any, *keys: str, style: str = "text", group: str = "经营与资本结构") -> None:
4439
+ candidate = value if value not in (None, "") else _workspace_value(row, *keys)
4440
+ if candidate in (None, "") or label in seen:
4441
+ return
4442
+ rendered = _display_percent(candidate) if style == "percent" else _display_number(candidate) if style == "number" else str(candidate)
4443
+ if rendered == "--":
4444
+ return
4445
+ seen.add(label)
4446
+ details.append({"label": label, "value": rendered, "group": group})
4447
+
4448
+ row: Mapping[str, Any] = basic
4449
+ add("所属板块", None, "bk", group="公司档案")
4450
+ add("主要产品", None, "business_products", group="公司档案")
4451
+ add("成立日期", None, "establish_date", "found_date", "setup_date", "founded_date", group="公司档案")
4452
+ add("注册资本", None, "registered_capital", "reg_capital", "register_capital", style="number", group="公司档案")
4453
+ add("法人代表", None, "legal_representative", "legal_person", "chairman", "representative", group="公司档案")
4454
+ add("注册地", None, "registered_address", "address", "province", "city", group="公司档案")
4455
+ add("主营业务", None, "main_business", "business_scope", "business", "description", group="公司档案")
4456
+
4457
+ row = financial_rows[0] if financial_rows else {}
4458
+ add("最新报告期", None, "report_date", "end_date", "period", "report_period", "report_type_cn", "date")
4459
+ add("营业收入同比", None, "revenue_yoy", "total_revenue_yoy", "yoy_revenue", "operate_income_yoy", style="percent")
4460
+ add("净利润同比", None, "net_profit_yoy", "n_profit_yoy", "yoy_netprofit", "net_income_yoy", style="percent")
4461
+ add("净资产收益率", None, "roe", "roe_weighted", "return_on_equity", style="percent")
4462
+ add("每股收益", None, "basic_eps", "eps", "diluted_eps")
4463
+
4464
+ row = balance_rows[0] if balance_rows else {}
4465
+ add("总负债", None, "t_liabilities", "total_liabilities", "liabilities", style="number")
4466
+ add("归母权益", None, "total_hldr_eqy_exc_min_int", "total_hldr_eqy_inc_min_int", "total_equity", "shareholders_equity", style="number")
4467
+ add("货币资金", None, "money_cap", "cash", "cash_and_equivalents", style="number")
4468
+ add("应收账款", None, "accounts_receivable", "acct_rcv", "receivables", style="number")
4469
+ add("存货", None, "inventories", "inventory", style="number")
4470
+
4471
+ row = cashflow_rows[0] if cashflow_rows else {}
4472
+ add("投资现金流", None, "net_invest_cash_flow", "invest_cash_flow", "cash_from_investment", style="number")
4473
+ add("筹资现金流", None, "net_finance_cash_flow", "finance_cash_flow", "cash_from_financing", style="number")
4474
+ add("期末现金余额", None, "cash_equ_end_period", "cash_end", "ending_cash", style="number")
4475
+
4476
+ row = holder_count_rows[0] if holder_count_rows else {}
4477
+ add("股东户数", None, "holder_num", "holder_count", "holders_num", "shareholder_num", style="number", group="股东与治理")
4478
+ add("股东户数变动", None, "holder_num_change", "holder_change", "change_ratio", "change_percentage", style="percent", group="股东与治理")
4479
+
4480
+ row = pledge_rows[0] if pledge_rows else {}
4481
+ add("股份质押比例", None, "pledge_ratio", "pledged_ratio", "pledge_percent", style="percent", group="股东与治理")
4482
+ add("质押股份", None, "pledge_shares", "pledged_shares", "pledge_amount", style="number", group="股东与治理")
4483
+
4484
+ row = share_change_rows[0] if share_change_rows else {}
4485
+ add("最近增减持日期", None, "change_date", "announce_date", "end_date", "date", group="股东与治理")
4486
+ add("最近增减持比例", None, "change_ratio", "change_percentage", "ratio", style="percent", group="股东与治理")
4487
+ return details[:24]
4488
+
4489
+
4490
+ def _workspace_optional_rows(market: Any, method_name: str, **kwargs: Any) -> list[dict[str, Any]]:
4491
+ """Call an optional FTShare endpoint without making its availability fatal."""
4492
+ method = getattr(market, method_name, None)
4493
+ if not callable(method):
4494
+ return []
4495
+ return _workspace_rows(method(as_dataframe=False, **kwargs))
4496
+
4497
+
4498
+ def fetch_security_workspace(symbol: str, *, name: str | None = None, refresh: bool = False) -> dict[str, Any]:
4499
+ """Load FTShare news and company data into the provider-neutral app schema.
4500
+
4501
+ This is deliberately independent from ``fetch_candles``: a slow or missing
4502
+ company endpoint must never delay the chart. Each section is best-effort,
4503
+ and callers can later replace the same ``security_workspace`` contract with
4504
+ another licensed provider.
4505
+ """
4506
+ sym = str(symbol or "").strip()
4507
+ if not sym:
4508
+ return {"ok": False, "error": "invalid_symbol", "message": "symbol is required"}
4509
+ key = sym.upper()
4510
+ cached = _security_workspace_cache.get(key)
4511
+ now = time.time()
4512
+ if not refresh and cached and now - cached[0] < _SECURITY_WORKSPACE_CACHE_TTL_SECONDS:
4513
+ return {"ok": True, "cached": True, "security_workspace": cached[1]}
4514
+ index = _broad_index_for_symbol(sym) or GLOBAL_INDEX_SOURCES.get(key)
4515
+ if index:
4516
+ if not isinstance(index, Mapping):
4517
+ index = next((item for item in _SYMBOL_DIRECTORY_SEED if item["symbol"] == key), {})
4518
+ workspace = {
4519
+ "symbol": sym, "instrument_type": "index",
4520
+ "source": {"name": "本地标的目录", "status": "reference"},
4521
+ "overview": {"company_name": name or index.get("name") or sym,
4522
+ "market": index.get("market") or "--", "metrics": [], "details": [],
4523
+ "description": "此标的是指数,不是上市公司,不适用公司财报、主营业务或公司股东资料。当前未接入指数编制说明和成分股资料。"},
4524
+ "news": [], "financials": {}, "holders": {}, "errors": [],
4525
+ "sections": {"overview": {"state": "available"}, "news": {"state": "unsupported"},
4526
+ "financials": {"state": "not_applicable"}, "holders": {"state": "not_applicable"}},
4527
+ }
4528
+ return {"ok": True, "cached": False, "security_workspace": workspace}
4529
+ if not ftshare_available():
4530
+ return _ftshare_unavailable_result()
4531
+
4532
+ market = _ftshare_market_api(timeout=12)
4533
+ display_name = str(name or sym)
4534
+ market_name = _workspace_market(sym)
4535
+ try:
4536
+ resolved = _symbol_name(market, sym)
4537
+ if resolved and resolved != sym:
4538
+ display_name = resolved
4539
+ except Exception:
4540
+ pass
4541
+ errors: list[str] = []
4542
+ section_errors: dict[str, list[dict[str, str]]] = {}
4543
+ # FTShare rate limits apply to the account rather than one endpoint. Once
4544
+ # the provider asks us to slow down, do not turn one company page into a
4545
+ # burst of identical requests and errors; the UI will retain available data
4546
+ # and make one background retry after the short cooldown.
4547
+ rate_limited_until = 0.0
4548
+
4549
+ def read_section(section: str, method_name: str, **kwargs: Any) -> list[dict[str, Any]]:
4550
+ nonlocal rate_limited_until
4551
+ if time.monotonic() < rate_limited_until:
4552
+ message = "FTShare 请求过于频繁,请稍后重试。"
4553
+ section_errors.setdefault(section, []).append({"code": "rate_limited", "message": message})
4554
+ errors.append(f"{method_name}: {message}")
4555
+ return []
4556
+ method = getattr(market, method_name, None)
4557
+ if not callable(method):
4558
+ message = f"missing endpoint: {method_name}"
4559
+ section_errors.setdefault(section, []).append({"code": "unsupported", "message": message})
4560
+ errors.append(f"{method_name}: {message}")
4561
+ return []
4562
+ for attempt in range(3):
4563
+ try:
4564
+ return _workspace_rows(method(as_dataframe=False, **kwargs))
4565
+ except Exception as exc:
4566
+ code, message = _classify_ftshare_error(exc)
4567
+ if code == "rate_limited" and attempt < 2:
4568
+ time.sleep(0.2 * (attempt + 1))
4569
+ continue
4570
+ if code == "rate_limited":
4571
+ rate_limited_until = time.monotonic() + 3.0
4572
+ section_errors.setdefault(section, []).append({"code": code, "message": message})
4573
+ errors.append(f"{method_name}: {message}")
4574
+ return []
4575
+ return []
4576
+ news_rows: list[dict[str, Any]] = []
4577
+ financial_rows: list[dict[str, Any]] = []
4578
+ holder_rows: list[dict[str, Any]] = []
4579
+ basic_rows: list[dict[str, Any]] = []
4580
+ balance_rows: list[dict[str, Any]] = []
4581
+ cashflow_rows: list[dict[str, Any]] = []
4582
+ holder_count_rows: list[dict[str, Any]] = []
4583
+ pledge_rows: list[dict[str, Any]] = []
4584
+ share_change_rows: list[dict[str, Any]] = []
4585
+ news_query = f"{display_name} {sym}" if display_name != sym else sym
4586
+ news_rows = read_section("news", "semantic_search_news", query=news_query, limit=12)
4587
+ if market_name == "US":
4588
+ bare = _bare_us_symbol(sym)
4589
+ basic_rows = read_section("overview", "us_basic", stock_code=bare, limit=1)
4590
+ financial_rows = _pivot_us_income_rows(read_section("financials", "us_income", stock_code=bare, limit=200))
4591
+ elif market_name == "CN":
4592
+ code = _cn_stock_code(sym)
4593
+ # Company lookup requires a bare code; financial endpoints use .SH/.SZ.
4594
+ basic_rows = read_section("overview", "company_list", stock_code=code.split(".")[0], limit=1)
4595
+ financial_rows = read_section("financials", "income", stock_code=code, limit=8)
4596
+ holder_rows = read_section("holders", "stock_holders", stock_code=code, limit=10)
4597
+ if market_name == "CN":
4598
+ code = _cn_stock_code(sym)
4599
+ balance_rows = read_section("overview", "balance", stock_code=code, limit=8)
4600
+ cashflow_rows = read_section("overview", "cashflow", stock_code=code, limit=8)
4601
+ for label, method_name, kwargs in (
4602
+ ("holder_count", "stock_holders_number", {"stock_code": code, "limit": 2}),
4603
+ ("pledge", "stock_pledge_detail", {"stock_code": code, "limit": 1}),
4604
+ ("share_change", "stock_share_chg", {"stock_code": code, "limit": 1}),
4605
+ ):
4606
+ rows = read_section("overview", method_name, **kwargs)
4607
+ if label == "holder_count":
4608
+ holder_count_rows = rows
4609
+ elif label == "pledge":
4610
+ pledge_rows = rows
4611
+ else:
4612
+ share_change_rows = rows
4613
+ basic = basic_rows[0] if basic_rows else {}
4614
+ financials = _workspace_financials(financial_rows)
4615
+ overview_metrics = _workspace_overview_metrics(financials, balance_rows, cashflow_rows)
4616
+ overview_details = _workspace_overview_details(
4617
+ basic=basic,
4618
+ financial_rows=financial_rows,
4619
+ balance_rows=balance_rows,
4620
+ cashflow_rows=cashflow_rows,
4621
+ holder_count_rows=holder_count_rows,
4622
+ pledge_rows=pledge_rows,
4623
+ share_change_rows=share_change_rows,
4624
+ )
4625
+ overview = {
4626
+ "company_name": str(_workspace_value(basic, "name", "company_name", "stock_name") or display_name),
4627
+ "market": market_name,
4628
+ "industry": str(_workspace_value(basic, "industry", "sector", "industry_name") or "--"),
4629
+ "listing_date": str(_workspace_value(basic, "listing_date", "list_date", "ipo_date") or "--"),
4630
+ "website": str(_workspace_value(basic, "website", "url", "company_website") or "--"),
4631
+ "employees": str(_workspace_value(basic, "employees", "employee_count") or "--"),
4632
+ "description": str(_workspace_value(basic, "company_profile", "description", "introduction", "business_scope") or "--"),
4633
+ # Company profile fields are not available for every FTShare market
4634
+ # adapter. Reuse factual, latest reported financial metrics rather
4635
+ # than rendering an empty Company page in that case.
4636
+ "metrics": overview_metrics,
4637
+ "details": overview_details,
4638
+ }
4639
+ def section_state(section: str, available: bool, unsupported: bool = False) -> dict[str, Any]:
4640
+ failures = section_errors.get(section, [])
4641
+ return {"state": ("partial" if failures else "available") if available else
4642
+ ("unsupported" if unsupported else "error" if failures else "empty"), "errors": failures}
4643
+
4644
+ workspace = {
4645
+ "symbol": sym,
4646
+ "source": {
4647
+ "name": "FTShare",
4648
+ "updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
4649
+ "status": "retrieved",
4650
+ "retrieved_at": int(time.time()),
4651
+ "query": news_query,
4652
+ },
4653
+ "news": _workspace_news(news_rows),
4654
+ "overview": overview,
4655
+ "financials": financials,
4656
+ "holders": _workspace_holders(holder_rows),
4657
+ "errors": errors,
4658
+ "sections": {
4659
+ "news": section_state("news", bool(news_rows)),
4660
+ "overview": section_state("overview", bool(basic_rows or overview_metrics or overview_details), market_name == "HK"),
4661
+ "financials": section_state("financials", bool(financials["metrics"]), market_name == "HK"),
4662
+ "holders": section_state("holders", bool(holder_rows), market_name in {"HK", "US"}),
4663
+ },
4664
+ }
4665
+ # Failed requests are retryable, not five-minute negative-cache entries.
4666
+ if not errors:
4667
+ _security_workspace_cache[key] = (now, workspace)
4668
+ return {"ok": True, "cached": False, "security_workspace": workspace}
4669
+
4670
+
4671
+ def fetch_comparison_candles(symbol: str, *, limit: int = 390) -> dict[str, Any]:
4672
+ """Fetch daily comparison data without silently changing instrument type.
4673
+
4674
+ The browser normalizes successful series against a common trading-day
4675
+ close. Stocks, ETFs and supported indexes use the same fetch path.
4676
+ """
4677
+ sym = _canonical_market_symbol(symbol)
4678
+ if not sym:
4679
+ return {"ok": False, "error": "invalid_symbol", "message": "symbol is required"}
4680
+ return fetch_candles(sym, interval="day", limit=limit, adjust="none")