@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.
- package/CHANGELOG.md +601 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +116 -0
- package/README.md +115 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +43 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/index.js +62 -0
- package/lib/client/mode-preferences.js +28 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +96 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +42 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17382 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +14 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +13 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +6 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +153 -4
- package/requirements.txt +6 -0
- package/screenshots.json +11 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- package/view/vendor/klinecharts.min.js +7 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Finite price-domain retracements. No pivot discovery or pixel interpolation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import math
|
|
7
|
+
import secrets
|
|
8
|
+
|
|
9
|
+
from tools.lines import LineError, validate_line_fields
|
|
10
|
+
from tools.trend_lines import resolve_anchor_time
|
|
11
|
+
|
|
12
|
+
FIBONACCI_COMMAND = "DRAW_AGENT_FIBONACCI"
|
|
13
|
+
DEFAULT_RATIOS = [0, .236, .382, .5, .618, .786, 1]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def validate_ratios(ratios):
|
|
17
|
+
if (not isinstance(ratios, list) or not 1 <= len(ratios) <= 16
|
|
18
|
+
or any(type(r) not in (int, float) or not math.isfinite(r) or not 0 <= r <= 1 for r in ratios)
|
|
19
|
+
or any(a >= b for a, b in zip(ratios, ratios[1:]))):
|
|
20
|
+
raise LineError("invalid_fibonacci_ratios", "回撤比例需为1至16个递增、不重复的0至1有限数值;未自动排序。")
|
|
21
|
+
return [float(r) for r in ratios]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def fibonacci_levels(start_price, end_price, ratios):
|
|
25
|
+
start, _, _ = validate_line_fields(price=start_price)
|
|
26
|
+
end, _, _ = validate_line_fields(price=end_price)
|
|
27
|
+
if start == end:
|
|
28
|
+
raise LineError("zero_fibonacci_range", "两个锚点价格不能相同。")
|
|
29
|
+
levels = [{"ratio": r, "price": end - r * (end - start)} for r in validate_ratios(ratios)]
|
|
30
|
+
if any(not math.isfinite(p["price"]) or p["price"] <= 0 for p in levels):
|
|
31
|
+
raise LineError("invalid_fibonacci_price", "回撤价位必须为大于零的有限数值。")
|
|
32
|
+
return levels
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def edit_fibonacci(payload, action, *, fibonacci_id=None, start_time=None, start_price=None,
|
|
36
|
+
end_time=None, end_price=None, ratios=None, name=None, color=None, request_id=None):
|
|
37
|
+
result = deepcopy(payload)
|
|
38
|
+
commands = result.get("chartCommands", [])
|
|
39
|
+
previous = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("id") == fibonacci_id), None)
|
|
40
|
+
if action in {"update", "delete"} and previous is None:
|
|
41
|
+
raise LineError("fibonacci_not_found", "当前快照不存在该 AI 斐波那契对象,请先读取对象 ID。")
|
|
42
|
+
if action == "delete":
|
|
43
|
+
commands.remove(previous)
|
|
44
|
+
return result, deepcopy(previous)
|
|
45
|
+
if action not in {"create", "update"}:
|
|
46
|
+
raise LineError("invalid_action", "不支持的斐波那契操作。")
|
|
47
|
+
values = (start_time, start_price, end_time, end_price)
|
|
48
|
+
if action == "create" and any(v is None for v in values):
|
|
49
|
+
raise LineError("missing_anchor", "需要明确的两个时间和价格锚点,不自动选择最近高低点。")
|
|
50
|
+
if action == "update" and all(v is None for v in (*values, ratios, name, color)):
|
|
51
|
+
raise LineError("empty_update", "请至少修改锚点、比例、名称或颜色。")
|
|
52
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
53
|
+
anchors = []
|
|
54
|
+
for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price)):
|
|
55
|
+
old = previous[key] if previous else {}
|
|
56
|
+
value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
|
|
57
|
+
anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
|
|
58
|
+
start, end = anchors
|
|
59
|
+
if start["time"] >= end["time"]:
|
|
60
|
+
raise LineError("invalid_anchor_order", "斐波那契起点必须早于终点;未自动交换锚点。")
|
|
61
|
+
ratios = validate_ratios(ratios if ratios is not None else previous["ratios"] if previous else DEFAULT_RATIOS)
|
|
62
|
+
obj = {"type": FIBONACCI_COMMAND, "id": previous["id"] if previous else "fib_" + secrets.token_hex(12),
|
|
63
|
+
"interval": payload.get("interval"), "from": start, "to": end, "ratios": ratios,
|
|
64
|
+
"levels": fibonacci_levels(start["price"], end["price"], ratios), "geometry_basis": "linear_price_retracement",
|
|
65
|
+
"label": name if name is not None else previous["label"] if previous else "",
|
|
66
|
+
"color": color if color is not None else previous["color"] if previous else "info"}
|
|
67
|
+
if previous and previous.get("create_request_id"):
|
|
68
|
+
obj["create_request_id"] = previous["create_request_id"]
|
|
69
|
+
if action == "create":
|
|
70
|
+
if request_id:
|
|
71
|
+
obj["create_request_id"] = request_id
|
|
72
|
+
obj["id"] = "fib_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
73
|
+
retry = next((c for c in commands if c.get("type") == FIBONACCI_COMMAND and c.get("create_request_id") == request_id), None)
|
|
74
|
+
if retry:
|
|
75
|
+
if any(retry.get(k) != obj[k] for k in ("from", "to", "ratios", "label", "color")):
|
|
76
|
+
raise LineError("request_conflict", "同一 request_id 的斐波那契参数不同。")
|
|
77
|
+
return result, deepcopy(retry)
|
|
78
|
+
if sum(c.get("type") == FIBONACCI_COMMAND for c in commands) >= 30:
|
|
79
|
+
raise LineError("too_many_fibonacci", "当前图表最多保存30组 AI 斐波那契对象。")
|
|
80
|
+
commands.append(obj)
|
|
81
|
+
else:
|
|
82
|
+
commands[commands.index(previous)] = obj
|
|
83
|
+
return result, deepcopy(obj)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Bounded, keyless Tencent HK/US daily history; no FTShare or A-share routes.
|
|
2
|
+
|
|
3
|
+
Prices are vendor-adjusted; volumes remain historical session shares, including
|
|
4
|
+
across splits. A day is anchored at 16:00 exchange time (not an execution tick).
|
|
5
|
+
See docs/free-foreign-daily.md for the verified contract and coverage limits.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from datetime import datetime, timedelta
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urlencode
|
|
17
|
+
from urllib.request import Request, urlopen
|
|
18
|
+
from zoneinfo import ZoneInfo
|
|
19
|
+
|
|
20
|
+
from tools.free_sources import _cache_get, _cache_set
|
|
21
|
+
|
|
22
|
+
SOURCE_URL = "https://gu.qq.com/"
|
|
23
|
+
_BASE = "https://web.ifzq.gtimg.cn/appstock/app/"
|
|
24
|
+
_PAGE_SIZE = 640
|
|
25
|
+
_MAX_PAGES = 8
|
|
26
|
+
_MAX_BYTES = 2_000_000
|
|
27
|
+
_TIMEOUT = 6
|
|
28
|
+
_AGENT = "Mozilla/5.0 FT-KLine/0.6"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def foreign_market(symbol: str) -> str | None:
|
|
32
|
+
if re.fullmatch(r"\d{5}\.HK", symbol):
|
|
33
|
+
return "HK"
|
|
34
|
+
if re.fullmatch(r"[A-Z][A-Z0-9]*(?:[.-][A-Z0-9]+)*\.US", symbol) and len(symbol) <= 28:
|
|
35
|
+
return "US"
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _read(url: str, *, text: bool = False) -> Any:
|
|
40
|
+
try:
|
|
41
|
+
request = Request(url, headers={"User-Agent": _AGENT, "Referer": SOURCE_URL})
|
|
42
|
+
with urlopen(request, timeout=_TIMEOUT) as response:
|
|
43
|
+
raw = response.read(_MAX_BYTES + 1)
|
|
44
|
+
if len(raw) > _MAX_BYTES:
|
|
45
|
+
return None
|
|
46
|
+
return raw.decode("gbk") if text else json.loads(raw.decode("utf-8"))
|
|
47
|
+
except Exception: # Public fallback failure must not break the primary provider.
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _us_code(root: str) -> str | None:
|
|
52
|
+
key = ("tencent_us_identity", root)
|
|
53
|
+
cached = _cache_get(key)
|
|
54
|
+
if cached:
|
|
55
|
+
return cached
|
|
56
|
+
# The quote supplies only an identifier, never a URL or executable input.
|
|
57
|
+
quote = _read("https://qt.gtimg.cn/q=" + "us" + root, text=True)
|
|
58
|
+
if not isinstance(quote, str):
|
|
59
|
+
return None
|
|
60
|
+
lines = re.findall(r'v_us[A-Za-z0-9_.-]+="([^"\r\n]*)";', quote)
|
|
61
|
+
if len(lines) != 1:
|
|
62
|
+
return None
|
|
63
|
+
fields = lines[0].split("~")
|
|
64
|
+
identity = fields[2] if len(fields) > 2 else ""
|
|
65
|
+
if identity not in {root + suffix for suffix in (".OQ", ".N", ".AM")}:
|
|
66
|
+
return None
|
|
67
|
+
code = "us" + identity
|
|
68
|
+
_cache_set(key, code)
|
|
69
|
+
return code
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _parse_page(payload: Any, code: str, series: str, zone: ZoneInfo, now: datetime,
|
|
73
|
+
allow_negative: bool) -> tuple[list[dict], str | None] | None:
|
|
74
|
+
if not isinstance(payload, dict) or payload.get("code") != 0:
|
|
75
|
+
return None
|
|
76
|
+
data = payload.get("data")
|
|
77
|
+
node = data.get(code) if isinstance(data, dict) else None
|
|
78
|
+
bars = node.get(series) if isinstance(node, dict) else None
|
|
79
|
+
if not isinstance(bars, list) or len(bars) > _PAGE_SIZE + 1:
|
|
80
|
+
return None
|
|
81
|
+
rows = []
|
|
82
|
+
reason = None
|
|
83
|
+
previous = ""
|
|
84
|
+
for bar in bars:
|
|
85
|
+
try:
|
|
86
|
+
if not isinstance(bar, list) or len(bar) < 6:
|
|
87
|
+
return None
|
|
88
|
+
day = datetime.strptime(bar[0], "%Y-%m-%d")
|
|
89
|
+
if day.strftime("%Y-%m-%d") != bar[0] or bar[0] <= previous:
|
|
90
|
+
return None
|
|
91
|
+
previous = bar[0]
|
|
92
|
+
o, c, h, l, volume = map(float, bar[1:6])
|
|
93
|
+
if not all(math.isfinite(x) for x in (o, c, h, l, volume)) or volume < 0:
|
|
94
|
+
return None
|
|
95
|
+
if l > min(o, c) or h < max(o, c) or l > h:
|
|
96
|
+
return None
|
|
97
|
+
if min(o, c, h, l) <= 0:
|
|
98
|
+
if not allow_negative:
|
|
99
|
+
return None
|
|
100
|
+
# Cumulative cash adjustments can make early HK qfq negative.
|
|
101
|
+
# Keep only the contiguous newer positive-price tail, never
|
|
102
|
+
# delete an interior invalid row and silently bridge a gap.
|
|
103
|
+
rows.clear()
|
|
104
|
+
reason = "non_positive_adjusted_prices"
|
|
105
|
+
continue
|
|
106
|
+
close = day.replace(hour=16, tzinfo=zone)
|
|
107
|
+
cutoff = close + (timedelta(minutes=15) if zone.key == "Asia/Hong_Kong" else timedelta())
|
|
108
|
+
if cutoff > now:
|
|
109
|
+
continue # Do not expose an unfinished daily candle as final.
|
|
110
|
+
rows.append({"time": int(close.timestamp()), "open": o, "close": c,
|
|
111
|
+
"high": h, "low": l, "volume": volume})
|
|
112
|
+
except (TypeError, ValueError, OverflowError):
|
|
113
|
+
return None
|
|
114
|
+
return rows, reason
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def fetch_foreign_daily(symbol: str, *, limit: int = 220, adjust: str = "none") -> dict | None:
|
|
118
|
+
market = foreign_market(symbol)
|
|
119
|
+
if market is None or adjust not in {"none", "forward", "backward"}:
|
|
120
|
+
return None
|
|
121
|
+
if market == "US" and adjust == "backward":
|
|
122
|
+
return None
|
|
123
|
+
wanted = max(2, min(int(limit), 4000))
|
|
124
|
+
key = ("tencent_foreign_daily", f"{symbol}:{wanted}:{adjust}")
|
|
125
|
+
cached = _cache_get(key)
|
|
126
|
+
if cached is not None:
|
|
127
|
+
return deepcopy(cached)
|
|
128
|
+
code = "hk" + symbol[:5] if market == "HK" else _us_code(symbol[:-3])
|
|
129
|
+
if not code:
|
|
130
|
+
return None
|
|
131
|
+
mode, series = {"none": ("", "day"), "forward": ("qfq", "qfqday"),
|
|
132
|
+
"backward": ("hfq", "hfqday")}[adjust]
|
|
133
|
+
route = "kline/kline" if not mode else ("hkfqkline/get" if market == "HK" else "usfqkline/get")
|
|
134
|
+
zone = ZoneInfo("Asia/Hong_Kong" if market == "HK" else "America/New_York")
|
|
135
|
+
now = datetime.now(zone)
|
|
136
|
+
end = ""
|
|
137
|
+
collected: dict[int, dict] = {}
|
|
138
|
+
reason = "page_limit"
|
|
139
|
+
pages = 0
|
|
140
|
+
for _ in range(_MAX_PAGES):
|
|
141
|
+
# Each older page overlaps the preceding boundary. Verify that prices
|
|
142
|
+
# and share counts use the same basis before joining the two pages.
|
|
143
|
+
count = min(_PAGE_SIZE, max(3, wanted - len(collected) + 2))
|
|
144
|
+
url = _BASE + route + "?" + urlencode({"param": f"{code},day,,{end},{count},{mode}"})
|
|
145
|
+
parsed = _parse_page(_read(url), code, series, zone, now, adjust == "forward")
|
|
146
|
+
pages += 1
|
|
147
|
+
if parsed is None:
|
|
148
|
+
reason = "source_unavailable_or_invalid"
|
|
149
|
+
break
|
|
150
|
+
rows, boundary = parsed
|
|
151
|
+
if not rows:
|
|
152
|
+
reason = boundary or "source_history_exhausted"
|
|
153
|
+
break
|
|
154
|
+
if end and datetime.fromtimestamp(rows[-1]["time"], zone).date().isoformat() > end:
|
|
155
|
+
reason = "source_ignored_history_boundary"
|
|
156
|
+
break
|
|
157
|
+
if collected and min(collected) not in {row["time"] for row in rows}:
|
|
158
|
+
reason = "missing_page_overlap"
|
|
159
|
+
break
|
|
160
|
+
if any(stamp in collected and collected[stamp] != row for stamp, row in ((r["time"], r) for r in rows)):
|
|
161
|
+
reason = "inconsistent_page_basis"
|
|
162
|
+
break
|
|
163
|
+
oldest = min(collected) if collected else None
|
|
164
|
+
if oldest is not None and rows[0]["time"] >= oldest:
|
|
165
|
+
reason = "source_history_exhausted"
|
|
166
|
+
break
|
|
167
|
+
collected.update((row["time"], row) for row in rows)
|
|
168
|
+
if len(collected) >= wanted:
|
|
169
|
+
reason = "requested_count_reached"
|
|
170
|
+
break
|
|
171
|
+
if boundary:
|
|
172
|
+
reason = boundary
|
|
173
|
+
break
|
|
174
|
+
end = datetime.fromtimestamp(rows[0]["time"], zone).date().isoformat()
|
|
175
|
+
rows = sorted(collected.values(), key=lambda row: row["time"])[-wanted:]
|
|
176
|
+
if len(rows) < 2:
|
|
177
|
+
return None
|
|
178
|
+
result = {"rows": rows, "history_complete": len(rows) >= wanted,
|
|
179
|
+
"history_start": rows[0]["time"], "history_end": rows[-1]["time"],
|
|
180
|
+
"coverage_reason": reason, "history_pages": pages,
|
|
181
|
+
"volume_unit": "shares", "volume_adjustment": "historical_session_shares",
|
|
182
|
+
"price_adjustment": adjust, "timestamp_convention": "session_date_at_16_local",
|
|
183
|
+
"source_symbol": code, "exchange_timezone": zone.key}
|
|
184
|
+
_cache_set(key, deepcopy(result))
|
|
185
|
+
return result
|