@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
@@ -0,0 +1,483 @@
1
+ """Built-in free market-data fallback for dsh_kline.
2
+
3
+ FTShare is the primary, promoted provider. This module is a *fallback* that
4
+ keeps basic broad-market data visible when the current FTShare plan cannot
5
+ serve it (anonymous/free tier without HK/US/index entitlements).
6
+
7
+ Design rules (mirror docs/provider-adaptation.md):
8
+ - Small, explicit registries only. No runtime discovery; no remote data ever
9
+ adds a URL or executes code.
10
+ - Public, key-less HTTP endpoints only (Eastmoney daily K-lines and Tencent
11
+ JSON K-line/quote feeds). No scraping of HTML.
12
+ - Every row keeps the canonical OHLCV shape (close-time, unix seconds) and the
13
+ response carries ``source`` + ``source_url`` so callers can label the data as
14
+ free fallback instead of silently pretending it came from FTShare.
15
+ - Bounded requests, short in-process cache, silent degradation on failure:
16
+ a transient free-source error must never break the primary chart.
17
+
18
+ This module is provider-neutral at the row level and imports nothing from
19
+ tools.fetch (which imports this module for fallback wiring).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import math
26
+ import re
27
+ import threading
28
+ import time
29
+ import urllib.parse
30
+ import urllib.request
31
+ from datetime import datetime, timezone, timedelta
32
+ from typing import Any, Mapping
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Registries (small and explicit)
36
+ # ---------------------------------------------------------------------------
37
+
38
+ _CN_TZ = timezone(timedelta(hours=8))
39
+ _HK_TZ = timezone(timedelta(hours=8))
40
+ _US_TZ = timezone(timedelta(hours=-5)) # EST; used only for weekday calendar math
41
+
42
+ _HTTP_TIMEOUT_SECONDS = 8.0
43
+ _CACHE_TTL_SECONDS = 60.0
44
+ _CACHE_MAX_ENTRIES = 96
45
+
46
+ _USER_AGENT = (
47
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
48
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
49
+ )
50
+
51
+ # Eastmoney broad-market indices that the FTShare free/anonymous tier commonly
52
+ # cannot serve. key = dsh_kline canonical symbol, value = eastmoney secid.
53
+ EM_INDEX_SECIDS: dict[str, str] = {
54
+ "000001.XSHG": "1.000001", # 上证指数
55
+ "000016.XSHG": "1.000016", # 上证50
56
+ "000300.XSHG": "1.000300", # 沪深300
57
+ "000905.XSHG": "1.000905", # 中证500
58
+ "000906.XSHG": "1.000906", # 中证800
59
+ "000852.XSHG": "1.000852", # 中证1000
60
+ "399001.XSHE": "0.399001", # 深证成指
61
+ "399006.XSHE": "0.399006", # 创业板指
62
+ "100.HSI": "100.HSI", # 恒生指数
63
+ "100.NDX": "100.NDX", # 纳斯达克100
64
+ }
65
+
66
+ EM_INDEX_NAMES: dict[str, str] = {
67
+ "000001.XSHG": "上证指数",
68
+ "000016.XSHG": "上证50",
69
+ "000300.XSHG": "沪深300",
70
+ "000905.XSHG": "中证500",
71
+ "000906.XSHG": "中证800",
72
+ "000852.XSHG": "中证1000",
73
+ "399001.XSHE": "深证成指",
74
+ "399006.XSHE": "创业板指",
75
+ "100.HSI": "恒生指数",
76
+ "100.NDX": "纳斯达克100",
77
+ }
78
+
79
+ # Tencent quote codes for the real-time broad-market ticker strip.
80
+ # key = dsh_kline canonical symbol.
81
+ TENCENT_TICKER_SOURCES: dict[str, dict[str, str]] = {
82
+ "100.HSI": {"code": "hkHSI", "market": "HK", "name": "恒生指数", "timezone": "Asia/Hong_Kong", "open": "09:30", "close": "16:00"},
83
+ "100.NDX": {"code": "usNDX", "market": "US", "name": "纳斯达克100", "timezone": "America/New_York", "open": "09:30", "close": "16:00"},
84
+ "000001.XSHG": {"code": "s_sh000001", "market": "CN", "name": "上证指数", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
85
+ "000300.XSHG": {"code": "s_sh000300", "market": "CN", "name": "沪深300", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
86
+ "399001.XSHE": {"code": "s_sz399001", "market": "CN", "name": "深证成指", "timezone": "Asia/Shanghai", "open": "09:30", "close": "15:00"},
87
+ }
88
+
89
+ SOURCE_URL = "https://push2his.eastmoney.com"
90
+ TENCENT_SOURCE_URL = "https://qt.gtimg.cn"
91
+ SOURCE_LABEL = "东方财富免费行情"
92
+ TENCENT_LABEL = "腾讯免费行情"
93
+
94
+ _cache_lock = threading.Lock()
95
+ _cache: dict[tuple[str, str], tuple[float, Any]] = {}
96
+
97
+
98
+ def _cache_get(key: tuple[str, str]) -> Any | None:
99
+ with _cache_lock:
100
+ entry = _cache.get(key)
101
+ if entry is None:
102
+ return None
103
+ stamp, value = entry
104
+ if time.time() - stamp > _CACHE_TTL_SECONDS:
105
+ _cache.pop(key, None)
106
+ return None
107
+ return value
108
+
109
+
110
+ def _cache_set(key: tuple[str, str], value: Any) -> None:
111
+ with _cache_lock:
112
+ if len(_cache) >= _CACHE_MAX_ENTRIES:
113
+ oldest = min(_cache, key=lambda item: _cache[item][0])
114
+ _cache.pop(oldest, None)
115
+ _cache[key] = (time.time(), value)
116
+
117
+
118
+ def _http_get_json(url: str, *, referer: str | None = "https://quote.eastmoney.com/") -> Any | None:
119
+ headers = {"User-Agent": _USER_AGENT}
120
+ if referer:
121
+ headers["Referer"] = referer
122
+ request = urllib.request.Request(url, headers=headers)
123
+ try:
124
+ with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT_SECONDS) as response:
125
+ raw = response.read()
126
+ return json.loads(raw.decode("utf-8", errors="replace"))
127
+ except Exception: # noqa: BLE001 - fallback must degrade silently
128
+ return None
129
+
130
+
131
+ def _http_get_text(url: str) -> str | None:
132
+ request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
133
+ try:
134
+ with urllib.request.urlopen(request, timeout=_HTTP_TIMEOUT_SECONDS) as response:
135
+ return response.read().decode("gbk", errors="replace")
136
+ except Exception: # noqa: BLE001
137
+ return None
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Eastmoney daily K-line fallback (broad-market indices)
142
+ # ---------------------------------------------------------------------------
143
+
144
+
145
+ def _em_date_to_seconds(date_text: str, timezone_name: str = "Asia/Shanghai") -> int:
146
+ """Parse YYYY-MM-DD into a close-time unix-second (day bars close same day)."""
147
+ try:
148
+ parsed = datetime.strptime(str(date_text)[:10], "%Y-%m-%d")
149
+ except (TypeError, ValueError):
150
+ return 0
151
+ if timezone_name == "Asia/Hong_Kong":
152
+ local = parsed.replace(tzinfo=_HK_TZ)
153
+ elif timezone_name == "America/New_York":
154
+ local = parsed.replace(hour=16, tzinfo=_US_TZ)
155
+ else:
156
+ local = parsed.replace(hour=15, tzinfo=_CN_TZ)
157
+ return int(local.timestamp())
158
+
159
+
160
+ def _parse_em_kline_payload(payload: Any, timezone_name: str) -> list[dict[str, Any]]:
161
+ """Parse eastmoney push2his klines into canonical OHLCV rows."""
162
+ rows: list[dict[str, Any]] = []
163
+ try:
164
+ data = payload.get("data") or {}
165
+ klines = data.get("klines") or []
166
+ except AttributeError:
167
+ return rows
168
+ for line in klines:
169
+ parts = str(line).split(",")
170
+ if len(parts) < 6:
171
+ continue
172
+ # fields2=f51(date),f52(open),f53(close),f54(high),f55(low),f56(volume)
173
+ date_text, open_px, close_px, high_px, low_px = parts[:5]
174
+ volume = parts[5] if len(parts) > 5 else ""
175
+ timestamp = _em_date_to_seconds(date_text, timezone_name)
176
+ if not timestamp:
177
+ continue
178
+ try:
179
+ row = {
180
+ "time": timestamp,
181
+ "open": float(open_px),
182
+ "high": float(high_px),
183
+ "low": float(low_px),
184
+ "close": float(close_px),
185
+ "volume": float(volume) if str(volume).replace(".", "", 1).isdigit() else 0.0,
186
+ }
187
+ except (TypeError, ValueError):
188
+ continue
189
+ rows.append(row)
190
+ rows.sort(key=lambda item: int(item["time"]))
191
+ return rows
192
+
193
+
194
+ def fetch_em_index_daily(symbol: str, *, limit: int = 120) -> list[dict[str, Any]] | None:
195
+ """Fetch broad-market index daily K-lines from Eastmoney.
196
+
197
+ Only symbols present in EM_INDEX_SECIDS are routed here. Returns canonical
198
+ rows (oldest → newest) or None when unavailable.
199
+
200
+ The upstream API is inconsistent across backend nodes about whether
201
+ ``lmt`` counts from the beginning or the end of the requested range, so we
202
+ always request a *recent* window that comfortably covers ``limit`` bars and
203
+ slice the newest ones from the response.
204
+ """
205
+ secid = EM_INDEX_SECIDS.get(str(symbol or "").strip().upper())
206
+ if not secid:
207
+ return None
208
+ wanted = max(2, min(int(limit), 4000))
209
+ cache_key = ("em_index_daily", f"{secid}:{wanted}")
210
+ cached = _cache_get(cache_key)
211
+ if cached is not None:
212
+ return cached
213
+ # ~365 calendar days per year; daily bars ≈ 244/year. A factor of 2 gives
214
+ # headroom for weekends/holidays without bloating the response.
215
+ calendar_days = max(30, int(wanted * 1.7))
216
+ beg_date = (datetime.now(_CN_TZ) - timedelta(days=calendar_days)).strftime("%Y%m%d")
217
+ query = urllib.parse.urlencode(
218
+ {
219
+ "secid": secid,
220
+ "fields1": "f1,f2,f3,f4,f5,f6",
221
+ "fields2": "f51,f52,f53,f54,f55,f56,f57",
222
+ "klt": "101",
223
+ "fqt": "0",
224
+ "beg": beg_date,
225
+ "end": "20500101",
226
+ "lmt": str(wanted * 3),
227
+ }
228
+ )
229
+ url = f"{SOURCE_URL}/api/qt/stock/kline/get?{query}"
230
+ payload = _http_get_json(url)
231
+ rows = _parse_em_kline_payload(payload, "Asia/Shanghai")
232
+ if len(rows) < 2:
233
+ return None
234
+ result = rows[-wanted:]
235
+ _cache_set(cache_key, result)
236
+ return result
237
+
238
+
239
+ def em_symbol_supported(symbol: str) -> bool:
240
+ return str(symbol or "").strip().upper() in EM_INDEX_SECIDS
241
+
242
+
243
+ # Tencent historical K-lines. The explicit index registry stays narrow, while
244
+ # A-share stocks are accepted only when the caller supplied a fully qualified
245
+ # Shanghai/Shenzhen equity identity (see ``_tencent_stock_code`` below).
246
+ # Tencent's bar array is [date, open, close, high, low, volume].
247
+ _TENCENT_KLINE_CODES: dict[str, str] = {
248
+ "100.HSI": "hkHSI",
249
+ "100.NDX": "usNDX",
250
+ "000001.XSHG": "sh000001",
251
+ "000016.XSHG": "sh000016",
252
+ "000300.XSHG": "sh000300",
253
+ "000905.XSHG": "sh000905",
254
+ "000906.XSHG": "sh000906",
255
+ "000852.XSHG": "sh000852",
256
+ "399001.XSHE": "sz399001",
257
+ "399006.XSHE": "sz399006",
258
+ }
259
+
260
+
261
+ def _parse_tencent_kline_payload(payload: Any, timezone_name: str, series: str | tuple[str, ...]) -> list[dict[str, Any]]:
262
+ """Parse one of the explicitly requested Tencent K-line series names."""
263
+ rows: list[dict[str, Any]] = []
264
+ try:
265
+ data = payload.get("data") or {}
266
+ except AttributeError:
267
+ return rows
268
+ names = (series,) if isinstance(series, str) else series
269
+ for _code, node in data.items():
270
+ # node: {"day"|"qfqday"|"hfqday": [[date, open, close, high, low, volume], ...]}
271
+ bars = next((node.get(name) for name in names if isinstance(node, Mapping) and isinstance(node.get(name), list)), None)
272
+ if not isinstance(bars, list):
273
+ continue
274
+ for bar in bars:
275
+ if not isinstance(bar, (list, tuple)) or len(bar) < 6:
276
+ continue
277
+ date_text, open_px, close_px, high_px, low_px, volume = bar[:6]
278
+ timestamp = _em_date_to_seconds(str(date_text), timezone_name)
279
+ if not timestamp:
280
+ continue
281
+ try:
282
+ opened, high, low, closed = map(float, (open_px, high_px, low_px, close_px))
283
+ traded = float(volume)
284
+ except (TypeError, ValueError):
285
+ continue
286
+ if (
287
+ not all(math.isfinite(value) for value in (opened, high, low, closed, traded))
288
+ or min(opened, high, low, closed) <= 0 or traded < 0
289
+ or high < max(opened, low, closed) or low > min(opened, high, closed)
290
+ ):
291
+ continue
292
+ rows.append({"time": timestamp, "open": opened, "high": high, "low": low,
293
+ "close": closed, "volume": traded})
294
+ rows.sort(key=lambda item: int(item["time"]))
295
+ return rows
296
+
297
+
298
+ def fetch_tencent_index_daily(symbol: str, *, limit: int = 120) -> list[dict[str, Any]] | None:
299
+ """Fetch broad-market index daily K-lines from Tencent (fallback feed).
300
+
301
+ Mirrors ``fetch_em_index_daily`` in behavior and return shape. Returns
302
+ canonical rows (oldest → newest) or None when unavailable.
303
+ """
304
+ canonical = str(symbol or "").strip().upper()
305
+ code = _TENCENT_KLINE_CODES.get(canonical)
306
+ if not code:
307
+ return None
308
+ wanted = max(2, min(int(limit), 4000))
309
+ cache_key = ("tencent_index_daily", f"{code}:{wanted}")
310
+ cached = _cache_get(cache_key)
311
+ if cached is not None:
312
+ return cached
313
+ # Tencent returns the requested number of bars counting backwards from today.
314
+ url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},qfq"
315
+ payload = _http_get_json(url, referer=None)
316
+ timezone_name = "Asia/Hong_Kong" if canonical == "100.HSI" else "America/New_York" if canonical == "100.NDX" else "Asia/Shanghai"
317
+ # Tencent returns qfqday for some indices and unadjusted day for others;
318
+ # index corporate-action adjustment is not applicable, so either verified
319
+ # series is acceptable here. Stock calls below remain exact by adjustment.
320
+ rows = _parse_tencent_kline_payload(payload, timezone_name, ("qfqday", "day"))
321
+ if len(rows) < 2:
322
+ return None
323
+ result = rows[-wanted:]
324
+ _cache_set(cache_key, result)
325
+ return result
326
+
327
+
328
+ _TENCENT_STOCK_SYMBOL = re.compile(r"(\d{6})\.(XSHG|XSHE)$")
329
+ _TENCENT_STOCK_PREFIXES = {
330
+ "XSHG": ("600", "601", "603", "605", "688", "689"),
331
+ "XSHE": ("000", "001", "002", "003", "300", "301", "302"),
332
+ }
333
+ _TENCENT_ADJUSTMENT_SERIES = {
334
+ "none": ("", "day"),
335
+ "forward": ("qfq", "qfqday"),
336
+ "backward": ("hfq", "hfqday"),
337
+ }
338
+
339
+
340
+ def _tencent_stock_code(symbol: str) -> str | None:
341
+ """Map only explicit, supported A-share equities to Tencent's code form."""
342
+ match = _TENCENT_STOCK_SYMBOL.fullmatch(str(symbol or "").strip().upper())
343
+ if not match:
344
+ return None
345
+ code, market = match.groups()
346
+ if not code.startswith(_TENCENT_STOCK_PREFIXES[market]):
347
+ return None
348
+ return ("sh" if market == "XSHG" else "sz") + code
349
+
350
+
351
+ def fetch_tencent_stock_daily(symbol: str, *, limit: int = 120, adjust: str = "none") -> list[dict[str, Any]] | None:
352
+ """Fetch qualified沪深 A-share daily K-lines from Tencent's public JSON feed.
353
+
354
+ This is a bounded second fallback after BaoStock. It supports only daily
355
+ source bars and preserves the caller's explicit adjustment selection; the
356
+ higher-level provider aggregates week/month/quarter/year intervals locally.
357
+ """
358
+ code = _tencent_stock_code(symbol)
359
+ adjustment = _TENCENT_ADJUSTMENT_SERIES.get(str(adjust or "").strip().lower())
360
+ if not code or adjustment is None:
361
+ return None
362
+ mode, series = adjustment
363
+ wanted = max(2, min(int(limit), 4000))
364
+ cache_key = ("tencent_stock_daily", f"{code}:{wanted}:{mode or 'none'}")
365
+ cached = _cache_get(cache_key)
366
+ if cached is not None:
367
+ return cached
368
+ # An empty mode deliberately leaves the final comma: Tencent then returns
369
+ # the unadjusted ``day`` series instead of a default qfq series.
370
+ url = f"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param={code},day,,,{wanted},{mode}"
371
+ payload = _http_get_json(url, referer=None)
372
+ rows = _parse_tencent_kline_payload(payload, "Asia/Shanghai", series)
373
+ if len(rows) < 2:
374
+ return None
375
+ result = rows[-wanted:]
376
+ _cache_set(cache_key, result)
377
+ return result
378
+
379
+
380
+ # ---------------------------------------------------------------------------
381
+ # Tencent real-time quote ticker
382
+ # ---------------------------------------------------------------------------
383
+
384
+ _TENCENT_FIELD_COUNT_MIN = 6
385
+
386
+
387
+ def _parse_tencent_index(code: str, market: str, text: str) -> dict[str, Any] | None:
388
+ """Parse qt.gtimg response for the configured index quote codes.
389
+
390
+ Field layouts differ by market family (verified live):
391
+ - CN index (s_sh000001 …): name/code/close/change/change_pct at idx1..5.
392
+ - HK index (hkHSI): close at idx3, prev close at idx4, tail carries change.
393
+ - US index (usNDX): close at idx3, prev close at idx4.
394
+ We compute change from prev close when present, else trust the given amount.
395
+ """
396
+ if not text:
397
+ return None
398
+ match = re.search(r'="([^"]+)"', text)
399
+ if not match:
400
+ return None
401
+ fields = match.group(1).split("~")
402
+ if len(fields) < _TENCENT_FIELD_COUNT_MIN:
403
+ return None
404
+ try:
405
+ close = float(fields[3])
406
+ except (TypeError, ValueError, IndexError):
407
+ return None
408
+ if close <= 0:
409
+ return None
410
+ name = fields[1] if len(fields) > 1 and fields[1] else code
411
+ if market == "CN":
412
+ # CN: idx4 = change amount, idx5 = change_pct; prev close is derived.
413
+ try:
414
+ change = float(fields[4])
415
+ change_pct = float(fields[5])
416
+ except (TypeError, ValueError, IndexError):
417
+ return None
418
+ previous = close - change if change else close
419
+ else:
420
+ # HK/US: idx4 = previous close; change is derived.
421
+ try:
422
+ previous = float(fields[4])
423
+ except (TypeError, ValueError, IndexError):
424
+ return None
425
+ if previous <= 0:
426
+ return None
427
+ change = close - previous
428
+ change_pct = change / previous * 100.0
429
+ return {
430
+ "market": market,
431
+ "symbol": code,
432
+ "name": name,
433
+ "close": round(close, 3),
434
+ "change": round(change, 3),
435
+ "change_pct": round(change_pct, 3),
436
+ "time": int(time.time()),
437
+ }
438
+
439
+
440
+ def fetch_tencent_ticker_items() -> list[dict[str, Any]]:
441
+ """Fetch real-time broad-index quotes for the bottom market strip.
442
+
443
+ Returns the same item shape the FTShare ticker path uses, so the view
444
+ renders identically. Empty list when the source is unreachable.
445
+ """
446
+ cache_key = ("tencent_ticker", "all")
447
+ cached = _cache_get(cache_key)
448
+ if cached is not None:
449
+ return cached
450
+ items: list[dict[str, Any]] = []
451
+ for symbol, source in TENCENT_TICKER_SOURCES.items():
452
+ url = f"{TENCENT_SOURCE_URL}/q={source['code']}"
453
+ text = _http_get_text(url)
454
+ item = _parse_tencent_index(source["code"], source["market"], text or "")
455
+ if item is not None:
456
+ item["symbol"] = symbol # canonical dsh_kline symbol for click-through
457
+ item["name"] = source["name"]
458
+ # Carry session metadata so the caller can label delayed/closed
459
+ # without owning the market-hours table.
460
+ item["session_timezone"] = source.get("timezone", "Asia/Shanghai")
461
+ item["session_open"] = source.get("open", "09:30")
462
+ item["session_close"] = source.get("close", "15:00")
463
+ items.append(item)
464
+ _cache_set(cache_key, items)
465
+ return items
466
+
467
+
468
+ def tencent_symbols() -> list[str]:
469
+ return list(TENCENT_TICKER_SOURCES.keys())
470
+
471
+
472
+ def free_source_status() -> dict[str, Any]:
473
+ """Safe capability summary for the built-in free feeds (no keys/secrets)."""
474
+ return {
475
+ "available": True,
476
+ "source": "builtin_free",
477
+ "label": "内置免费行情(东财 / 腾讯)",
478
+ "index_kline_symbols": sorted(EM_INDEX_NAMES.keys()),
479
+ "index_kline_count": len(EM_INDEX_NAMES),
480
+ "ticker_symbols": tencent_symbols(),
481
+ "ticker_count": len(tencent_symbols()),
482
+ "note": "仅供免费基础体验,行情可能延迟,请勿用于交易决策。正式/实时数据请使用 FTShare。",
483
+ }
package/tools/lines.py ADDED
@@ -0,0 +1,91 @@
1
+ """Explicit, snapshot-scoped horizontal lines; no market fetches or auto levels."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import math
7
+ import secrets
8
+ from typing import Any, Literal
9
+
10
+ LINE_COMMAND = "DRAW_HORIZONTAL_LINE"
11
+ MAX_LINES = 60
12
+ COLORS = {"info", "success", "warning", "danger"}
13
+ COLOR_ALIASES = {"blue": "info", "蓝色": "info", "green": "success", "绿色": "success",
14
+ "orange": "warning", "橙色": "warning", "red": "danger", "红色": "danger"}
15
+ ColorInput = Literal["info", "success", "warning", "danger", "blue", "green", "orange", "red", "蓝色", "绿色", "橙色", "红色"]
16
+
17
+
18
+ class LineError(ValueError):
19
+ def __init__(self, code: str, message: str) -> None:
20
+ super().__init__(message)
21
+ self.code = code
22
+
23
+
24
+ def horizontal_lines(payload: dict[str, Any]) -> list[dict[str, Any]]:
25
+ return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == LINE_COMMAND])
26
+
27
+
28
+ def validate_line_fields(*, price: float | None = None, name: str | None = None,
29
+ color: str | None = None, request_id: str | None = None) -> tuple[float | None, str | None, str | None]:
30
+ """Shared field validation; normalize colors without creating throwaway drawings."""
31
+ if price is not None:
32
+ if isinstance(price, bool) or not isinstance(price, (int, float)) or not math.isfinite(price) or price <= 0:
33
+ raise LineError("invalid_price", "价格必须是大于零的有限数值。")
34
+ if name is not None:
35
+ if not isinstance(name, str) or len(name.strip()) > 48 or any(ord(c) < 32 for c in name):
36
+ raise LineError("invalid_name", "名称最多 48 个字符,不能包含控制字符。")
37
+ name = name.strip()
38
+ if color is not None:
39
+ if not isinstance(color, str):
40
+ raise LineError("invalid_color", "颜色必须为支持的颜色名称。")
41
+ color = COLOR_ALIASES.get(color.strip().lower(), color.strip().lower())
42
+ if color not in COLORS:
43
+ raise LineError("invalid_color", "颜色请选择蓝色/info、绿色/success、橙色/warning 或红色/danger。")
44
+ if request_id is not None and (not isinstance(request_id, str) or not 1 <= len(request_id) <= 128):
45
+ raise LineError("invalid_request_id", "request_id 必须是 1 至 128 个字符。")
46
+ return float(price) if price is not None else None, name, color
47
+
48
+
49
+ def edit_horizontal_line(
50
+ payload: dict[str, Any], action: str, *, line_id: str | None = None,
51
+ price: float | None = None, name: str | None = None,
52
+ color: str | None = None, request_id: str | None = None,
53
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
54
+ """Return a copy; failed validation never mutates the source chart."""
55
+ price, name, color = validate_line_fields(price=price, name=name, color=color, request_id=request_id)
56
+ result = deepcopy(payload)
57
+ commands = result.get("chartCommands", [])
58
+ if action == "create":
59
+ if price is None:
60
+ raise LineError("invalid_price", "创建水平线需要指定价格。")
61
+ line = {"type": LINE_COMMAND, "id": "line_" + secrets.token_hex(12),
62
+ "price": float(price), "label": name or "", "color": color or "info"}
63
+ if request_id:
64
+ line["create_request_id"] = request_id
65
+ # Retrying against the same snapshot also keeps a stable line ID.
66
+ line["id"] = "line_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
67
+ previous = next((c for c in commands if c.get("type") == LINE_COMMAND
68
+ and c.get("create_request_id") == request_id), None)
69
+ if previous:
70
+ if any(previous.get(k) != line[k] for k in ("price", "label", "color")):
71
+ raise LineError("request_conflict", "同一 request_id 的绘图参数不同,请使用新的 request_id。")
72
+ return result, deepcopy(previous)
73
+ if len(horizontal_lines(result)) >= MAX_LINES:
74
+ raise LineError("too_many_lines", "当前图表最多保存 60 条 AI 水平线。")
75
+ commands.append(line)
76
+ elif action in {"update", "delete"}:
77
+ line = next((c for c in commands if c.get("type") == LINE_COMMAND and c.get("id") == line_id), None)
78
+ if line is None:
79
+ raise LineError("line_not_found", "当前图表不存在该水平线,请先读取当前图表中的水平线 ID。")
80
+ if action == "delete":
81
+ commands.remove(line)
82
+ else:
83
+ if price is None and name is None and color is None:
84
+ raise LineError("empty_update", "请至少指定价格、名称或颜色中的一项。")
85
+ if price is not None: line["price"] = float(price)
86
+ if name is not None: line["label"] = name
87
+ if color is not None: line["color"] = color
88
+ else:
89
+ raise LineError("invalid_action", "不支持的水平线操作。")
90
+ result["chartCommands"] = commands
91
+ return result, deepcopy(line)
@@ -0,0 +1,66 @@
1
+ """Transparent close-vs-four-back nine count; no retrospective erasure."""
2
+ from __future__ import annotations
3
+
4
+ from tools.closed_daily import closed_daily
5
+ from tools.lines import LineError
6
+
7
+ RULE_VERSION = "nine_count_v1"
8
+
9
+
10
+ def nine_count(rows, *, symbol: str, interval: str = "day", source_interval: str | None = "day",
11
+ interval_value: int | None = 1, provider: str | None = None,
12
+ display_bars: int = 120, known_gap_indexes: tuple[int, ...] = (), now=None):
13
+ if type(display_bars) is not int or not 30 <= display_bars <= 240:
14
+ raise LineError("invalid_nine_count_range", "九转展示范围必须为30至240根日线。")
15
+ candles, metadata = closed_daily(rows, symbol=symbol, interval=interval,
16
+ source_interval=source_interval, interval_value=interval_value,
17
+ provider=provider, now=now)
18
+ candles = candles[-4000:]
19
+ gap_indexes = set(known_gap_indexes)
20
+ if any(type(i) is not int or i <= 0 or i >= len(candles) for i in gap_indexes):
21
+ raise LineError("invalid_known_gap", "已知缺失区间索引超出已加载日线范围。")
22
+ marks = []
23
+ events = []
24
+ direction = None
25
+ count = 0
26
+ completed = False
27
+ # The first observed run can predate the loaded prefix. Do not guess its count.
28
+ censored = True
29
+ encountered_censored_prefix = False
30
+ segment_start = 0
31
+ for i, bar in enumerate(candles):
32
+ if i in gap_indexes:
33
+ segment_start = i
34
+ direction, count, completed, censored = None, 0, False, True
35
+ if i - segment_start < 4:
36
+ continue
37
+ compare = bar["close"] - candles[i - 4]["close"]
38
+ side = "up" if compare > 0 else "down" if compare < 0 else None
39
+ if side is None:
40
+ direction, count, completed, censored = None, 0, False, False
41
+ continue
42
+ if side != direction:
43
+ direction, count, completed = side, 0, False
44
+ # A reversal gives a known restart point, even at the loaded edge.
45
+ if direction is not None and i > segment_start + 4:
46
+ censored = False
47
+ if censored or completed:
48
+ if censored:
49
+ encountered_censored_prefix = True
50
+ continue
51
+ count += 1
52
+ mark = {"time": bar["time"], "index": i, "direction": side, "count": count,
53
+ "label": str(count), "price": bar["high"] if side == "up" else bar["low"]}
54
+ marks.append(mark)
55
+ if count == 9:
56
+ completed = True
57
+ events.append({"time": bar["time"], "direction": side,
58
+ "label": "上涨九转计数完成" if side == "up" else "下跌九转计数完成"})
59
+ first = max(0, len(candles) - display_bars)
60
+ visible = [m for m in marks if m["index"] >= first]
61
+ return {"rule_version": RULE_VERSION, "as_of": metadata["as_of"], "data_quality": metadata,
62
+ "display_bars": display_bars, "loaded_bars": len(candles), "marks": visible,
63
+ "events": [e for e in events if e["time"] >= (candles[first]["time"] if candles else 0)],
64
+ "total_marks": len(marks), "truncated": len(visible) < len(marks),
65
+ "limitations": (["left_boundary_run_censored_until_interruption"] if encountered_censored_prefix else [])
66
+ + (["known_gaps_segmented"] if gap_indexes else [])}