@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
|
File without changes
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Explicit, time/price anchored text, numeric and icon chart annotations."""
|
|
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
|
+
ANNOTATION_COMMAND = "DRAW_AGENT_ANNOTATION"
|
|
13
|
+
ANNOTATION_KINDS = {"text_annotation", "number_annotation", "icon_annotation"}
|
|
14
|
+
ANNOTATION_ICONS = {"arrow_up", "arrow_down", "diamond"}
|
|
15
|
+
MAX_ANNOTATIONS = 80
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _validate_content(kind, text, value, icon=None):
|
|
19
|
+
if kind == "text_annotation":
|
|
20
|
+
if not isinstance(text, str) or not 1 <= len(text.strip()) <= 120 or any(ord(c) < 32 for c in text):
|
|
21
|
+
raise LineError("invalid_annotation_text", "文字标注需为1至120个字符,且不能包含控制字符。")
|
|
22
|
+
if value is not None or icon is not None: raise LineError("invalid_edit_fields", "文字标注不能设置数值或图标字段。")
|
|
23
|
+
return text.strip(), None
|
|
24
|
+
if kind == "number_annotation":
|
|
25
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
26
|
+
raise LineError("invalid_annotation_value", "数值标注必须是有限数字。")
|
|
27
|
+
if text is not None or icon is not None: raise LineError("invalid_edit_fields", "数值标注不能设置文字或图标字段。")
|
|
28
|
+
return None, float(value)
|
|
29
|
+
if kind == "icon_annotation":
|
|
30
|
+
if icon not in ANNOTATION_ICONS:
|
|
31
|
+
raise LineError("invalid_annotation_icon", "图标标注仅支持 arrow_up、arrow_down 或 diamond。")
|
|
32
|
+
if text is not None or value is not None: raise LineError("invalid_edit_fields", "图标标注不能设置文字或数值字段。")
|
|
33
|
+
return None, None
|
|
34
|
+
raise LineError("invalid_annotation_kind", "不支持的标注类型。")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_annotation(command):
|
|
38
|
+
if not isinstance(command, dict) or command.get("type") != ANNOTATION_COMMAND:
|
|
39
|
+
raise LineError("invalid_annotation", "标注对象格式无效。")
|
|
40
|
+
kind = command.get("kind")
|
|
41
|
+
text, value = _validate_content(kind, command.get("text"), command.get("value"), command.get("icon"))
|
|
42
|
+
time, price = command.get("time"), command.get("price")
|
|
43
|
+
if type(time) is not int or time <= 0 or isinstance(price, bool) or not isinstance(price, (int, float)) or not math.isfinite(price) or price <= 0:
|
|
44
|
+
raise LineError("invalid_annotation_anchor", "标注锚点必须包含有效 K 线时间和大于零的价格。")
|
|
45
|
+
return {"type": ANNOTATION_COMMAND, "kind": kind, "id": command["id"], "interval": command.get("interval"),
|
|
46
|
+
"label": command.get("label", ""), "color": command.get("color", "info"), "time": time,
|
|
47
|
+
"price": float(price), **({"text": text} if kind == "text_annotation" else
|
|
48
|
+
{"value": value} if kind == "number_annotation" else {"icon": command["icon"]})}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def edit_annotation(payload, action, *, kind, annotation_id=None, anchor_time=None, anchor_price=None,
|
|
52
|
+
text=None, value=None, icon=None, name=None, color=None, request_id=None):
|
|
53
|
+
result = deepcopy(payload)
|
|
54
|
+
commands = result.get("chartCommands", [])
|
|
55
|
+
matches = [c for c in commands if c.get("type") == ANNOTATION_COMMAND and c.get("id") == annotation_id]
|
|
56
|
+
if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一标注 ID 不唯一,不能安全修改。")
|
|
57
|
+
previous = matches[0] if matches else None
|
|
58
|
+
if action in {"update", "delete"} and previous is None:
|
|
59
|
+
raise LineError("annotation_not_found", "当前快照不存在该 AI 标注,请先读取完整对象 ID。")
|
|
60
|
+
if previous and previous.get("kind") != kind:
|
|
61
|
+
raise LineError("drawing_kind_mismatch", "标注 ID 与指定类型不一致。")
|
|
62
|
+
if action == "delete":
|
|
63
|
+
if any(v is not None for v in (anchor_time, anchor_price, text, value, icon, name, color)):
|
|
64
|
+
raise LineError("invalid_edit_fields", "删除标注只需对象 ID。")
|
|
65
|
+
commands.remove(previous)
|
|
66
|
+
return result, deepcopy(previous)
|
|
67
|
+
if action not in {"create", "update"} or kind not in ANNOTATION_KINDS:
|
|
68
|
+
raise LineError("invalid_annotation_kind", "不支持的标注类型或操作。")
|
|
69
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
70
|
+
if action == "create":
|
|
71
|
+
if anchor_time is None or anchor_price is None:
|
|
72
|
+
raise LineError("annotation_anchor_required", "创建标注必须明确指定已加载 K 线时间和价格。")
|
|
73
|
+
text, value = _validate_content(kind, text, value, icon)
|
|
74
|
+
timestamp = resolve_anchor_time(payload, anchor_time)
|
|
75
|
+
price, _, _ = validate_line_fields(price=anchor_price)
|
|
76
|
+
if price is None: raise LineError("invalid_annotation_anchor", "标注价格无效。")
|
|
77
|
+
else:
|
|
78
|
+
if anchor_time is None and anchor_price is None and text is None and value is None and icon is None and name is None and color is None:
|
|
79
|
+
raise LineError("empty_update", "请指定标注的新位置、内容、名称或颜色。")
|
|
80
|
+
old = validate_annotation(previous)
|
|
81
|
+
timestamp = resolve_anchor_time(payload, anchor_time) if anchor_time is not None else old["time"]
|
|
82
|
+
price = validate_line_fields(price=anchor_price)[0] if anchor_price is not None else old["price"]
|
|
83
|
+
if kind == "text_annotation":
|
|
84
|
+
if value is not None: raise LineError("invalid_edit_fields", "文字标注不能设置数值字段。")
|
|
85
|
+
content, number = _validate_content(kind, text if text is not None else old.get("text"), None)
|
|
86
|
+
icon = None
|
|
87
|
+
elif kind == "number_annotation":
|
|
88
|
+
if text is not None: raise LineError("invalid_edit_fields", "数值标注不能设置文字字段。")
|
|
89
|
+
content, number = _validate_content(kind, None, value if value is not None else old.get("value"))
|
|
90
|
+
icon = None
|
|
91
|
+
else:
|
|
92
|
+
if text is not None or value is not None: raise LineError("invalid_edit_fields", "图标标注不能设置文字或数值字段。")
|
|
93
|
+
content, number = _validate_content(kind, None, None, icon if icon is not None else old.get("icon"))
|
|
94
|
+
icon = icon if icon is not None else old.get("icon")
|
|
95
|
+
text, value = content, number
|
|
96
|
+
obj = {"type": ANNOTATION_COMMAND, "kind": kind,
|
|
97
|
+
"id": previous["id"] if previous else "ann_" + secrets.token_hex(12),
|
|
98
|
+
"interval": payload.get("interval"), "label": name if name is not None else previous.get("label", "") if previous else "",
|
|
99
|
+
"color": color if color is not None else previous.get("color", "info") if previous else "info",
|
|
100
|
+
"time": timestamp, "price": float(price)}
|
|
101
|
+
if kind == "text_annotation": obj["text"] = text
|
|
102
|
+
elif kind == "number_annotation": obj["value"] = value
|
|
103
|
+
else: obj["icon"] = icon
|
|
104
|
+
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
105
|
+
if action == "create":
|
|
106
|
+
if request_id:
|
|
107
|
+
obj["create_request_id"] = request_id
|
|
108
|
+
obj["id"] = "ann_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
109
|
+
retry = next((c for c in commands if c.get("type") == ANNOTATION_COMMAND and c.get("create_request_id") == request_id), None)
|
|
110
|
+
if retry:
|
|
111
|
+
if any(retry.get(k) != obj[k] for k in ("kind", "label", "color", "time", "price", "text", "value", "icon")):
|
|
112
|
+
raise LineError("request_conflict", "同一 request_id 的标注参数不同。")
|
|
113
|
+
return result, deepcopy(retry)
|
|
114
|
+
if sum(c.get("type") == ANNOTATION_COMMAND for c in commands) >= MAX_ANNOTATIONS:
|
|
115
|
+
raise LineError("too_many_annotations", "当前图表最多保存80个 AI 标注。")
|
|
116
|
+
commands.append(obj)
|
|
117
|
+
else:
|
|
118
|
+
commands[commands.index(previous)] = obj
|
|
119
|
+
return result, deepcopy(obj)
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Shared dispatch contract for automatic drawings in both chart hosts.
|
|
2
|
+
|
|
3
|
+
The recognizers own geometry and ordering. This module owns parameter defaults,
|
|
4
|
+
the closed-daily gate, and the analysis result shape. A new recognizer should be
|
|
5
|
+
registered here before either host exposes it.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from tools.channel_candidates import channel_candidates
|
|
13
|
+
from tools.closed_daily import closed_daily
|
|
14
|
+
from tools.lines import LineError
|
|
15
|
+
from tools.nine_count import nine_count
|
|
16
|
+
from tools.price_patterns import TYPES as PATTERN_TYPES, price_pattern_candidates
|
|
17
|
+
from tools.range_candidates import DEFAULT_WINDOW_SIZES, range_candidates
|
|
18
|
+
from tools.recent_drawing_candidates import recent_drawing_candidates
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class AnalysisSpec:
|
|
23
|
+
required: tuple[str, ...]
|
|
24
|
+
optional: tuple[str, ...]
|
|
25
|
+
selection: str # newest candidate first, or a complete count sequence
|
|
26
|
+
defaults: dict[str, Any]
|
|
27
|
+
version: str = "1"
|
|
28
|
+
drawing_kind: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
AUTOMATIC_ANALYSES = {
|
|
32
|
+
"recent_drawing_candidates": AnalysisSpec(("drawing_type",), ("lookback_bars", "max_candidates"), "first_candidate",
|
|
33
|
+
{"lookback_bars": 120, "max_candidates": 5}),
|
|
34
|
+
"channel_candidates": AnalysisSpec((), ("direction", "scope", "lookback_bars", "left_bars", "right_bars", "min_span_bars", "max_candidates", "closed_daily_only"), "first_candidate",
|
|
35
|
+
{"direction": "both", "scope": "current", "lookback_bars": 120, "left_bars": 2, "right_bars": 2, "min_span_bars": 12, "max_candidates": 3}, "3", "channel"),
|
|
36
|
+
"range_candidates": AnalysisSpec((), ("window_sizes", "max_candidates", "closed_daily_only"), "first_candidate",
|
|
37
|
+
{"window_sizes": list(DEFAULT_WINDOW_SIZES), "max_candidates": 3}, drawing_kind="rectangle"),
|
|
38
|
+
"price_pattern_candidates": AnalysisSpec((), ("pattern_types", "lookback_bars", "max_candidates", "anchor_times"), "first_candidate",
|
|
39
|
+
{"pattern_types": list(PATTERN_TYPES), "lookback_bars": 240, "max_candidates": 5}, drawing_kind="price_pattern"),
|
|
40
|
+
"nine_count": AnalysisSpec((), ("display_bars",), "whole_sequence", {"display_bars": 120}),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
RECENT_DRAWING_KINDS = {"horizontal_line": "horizontal", "trend_line": "trend",
|
|
44
|
+
"fibonacci_retracement": "fibonacci", "labeled_polyline": "abc"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def analyze_automatic(function: str, candles: list[dict[str, Any]], *,
|
|
48
|
+
symbol: str, interval: str, source_interval: str | None,
|
|
49
|
+
interval_value: int | None, provider: str | None,
|
|
50
|
+
volume_unit: str | None = None,
|
|
51
|
+
parameters: dict[str, Any] | None = None) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
52
|
+
"""Return (summary, normalized parameters), without modifying a chart."""
|
|
53
|
+
spec = AUTOMATIC_ANALYSES.get(function)
|
|
54
|
+
if spec is None:
|
|
55
|
+
raise LineError("unknown_chart_function", "未知自动绘图分析函数。")
|
|
56
|
+
values = dict(parameters or {})
|
|
57
|
+
if values.keys() - set(spec.required + spec.optional):
|
|
58
|
+
raise LineError("invalid_function_parameters", "参数不适用于该分析函数。")
|
|
59
|
+
if any(key not in values or values[key] is None for key in spec.required):
|
|
60
|
+
raise LineError("missing_anchor", "缺少必要的绘图类型。")
|
|
61
|
+
effective = {**spec.defaults, **{key: value for key, value in values.items() if value is not None}}
|
|
62
|
+
if not isinstance(candles, list):
|
|
63
|
+
code = ("channel_candidate_data_unavailable" if function == "channel_candidates" else
|
|
64
|
+
"range_candidate_data_unavailable" if function == "range_candidates" else "daily_analysis_unavailable")
|
|
65
|
+
raise LineError(code, "当前图缺少可核对的已加载K线,未补取行情。")
|
|
66
|
+
|
|
67
|
+
common = dict(symbol=symbol, interval=interval, source_interval=source_interval,
|
|
68
|
+
interval_value=interval_value, provider=provider)
|
|
69
|
+
if function == "recent_drawing_candidates":
|
|
70
|
+
result = recent_drawing_candidates(candles, **common, drawing_type=effective["drawing_type"],
|
|
71
|
+
lookback_bars=effective["lookback_bars"], max_candidates=effective["max_candidates"])
|
|
72
|
+
return result, values
|
|
73
|
+
if function == "price_pattern_candidates":
|
|
74
|
+
result = price_pattern_candidates(candles, **common, volume_unit=volume_unit,
|
|
75
|
+
pattern_types=effective["pattern_types"], lookback_bars=effective["lookback_bars"],
|
|
76
|
+
max_candidates=effective["max_candidates"],
|
|
77
|
+
anchor_times=tuple(effective["anchor_times"]) if "anchor_times" in effective else None)
|
|
78
|
+
return result, values
|
|
79
|
+
if function == "nine_count":
|
|
80
|
+
return nine_count(candles, **common, display_bars=effective["display_bars"]), values
|
|
81
|
+
|
|
82
|
+
quality = None
|
|
83
|
+
if effective.get("closed_daily_only"):
|
|
84
|
+
candles, quality = closed_daily(candles, **common)
|
|
85
|
+
if function == "channel_candidates":
|
|
86
|
+
result = channel_candidates(candles, direction=effective["direction"],
|
|
87
|
+
scope=effective["scope"], lookback_bars=effective["lookback_bars"],
|
|
88
|
+
left_bars=effective["left_bars"], right_bars=effective["right_bars"],
|
|
89
|
+
min_span_bars=effective["min_span_bars"], limit=effective["max_candidates"])
|
|
90
|
+
normalized = {key: result[key] for key in ("direction", "scope", "lookback_bars", "left_bars", "right_bars", "min_span_bars")}
|
|
91
|
+
else:
|
|
92
|
+
result = range_candidates(candles, window_sizes=effective["window_sizes"],
|
|
93
|
+
limit=effective["max_candidates"])
|
|
94
|
+
normalized = {"window_sizes": result["window_sizes"]}
|
|
95
|
+
normalized["max_candidates"] = effective["max_candidates"]
|
|
96
|
+
if quality is not None:
|
|
97
|
+
result = {**result, "as_of": quality["as_of"], "data_quality": quality}
|
|
98
|
+
normalized["closed_daily_only"] = True
|
|
99
|
+
return result, normalized
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def stored_automatic_result(function: str, summary: dict[str, Any]) -> dict[str, Any]:
|
|
103
|
+
"""Persist only the immutable material needed by the guarded apply step."""
|
|
104
|
+
if AUTOMATIC_ANALYSES[function].selection == "whole_sequence":
|
|
105
|
+
return {key: summary[key] for key in ("marks", "events", "rule_version", "as_of")}
|
|
106
|
+
return {key: summary[key] for key in ("candidates", "rule_version", "as_of", "drawing_type") if key in summary}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def candidate_function_for_kind(kind: str) -> str:
|
|
110
|
+
if kind in RECENT_DRAWING_KINDS:
|
|
111
|
+
return "recent_drawing_candidates"
|
|
112
|
+
for function, spec in AUTOMATIC_ANALYSES.items():
|
|
113
|
+
if spec.drawing_kind == kind:
|
|
114
|
+
return function
|
|
115
|
+
raise LineError("invalid_candidate_selection", "该图形不支持从候选结果绘制。")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def candidate_edit_parameters(kind: str, summary: dict[str, Any], number: int) -> dict[str, Any]:
|
|
119
|
+
"""Turn a guarded, 1-based candidate selection into editor parameters."""
|
|
120
|
+
candidate_function_for_kind(kind)
|
|
121
|
+
candidates = summary.get("candidates")
|
|
122
|
+
if type(number) is not int or not 1 <= number <= 5 or not isinstance(candidates, list) or number > len(candidates):
|
|
123
|
+
raise LineError("candidate_not_found", "所选候选不存在或不属于当前图。")
|
|
124
|
+
selected = candidates[number - 1]
|
|
125
|
+
if kind in RECENT_DRAWING_KINDS:
|
|
126
|
+
if summary.get("drawing_type") != RECENT_DRAWING_KINDS[kind]:
|
|
127
|
+
raise LineError("candidate_result_mismatch", "候选与当前绘图工具不匹配。")
|
|
128
|
+
anchors = selected.get("anchors") if isinstance(selected, dict) else None
|
|
129
|
+
count = 1 if kind == "horizontal_line" else 3 if kind == "labeled_polyline" else 2
|
|
130
|
+
if not isinstance(anchors, list) or len(anchors) != count or any(
|
|
131
|
+
not isinstance(anchor, dict) or "time" not in anchor or "price" not in anchor for anchor in anchors):
|
|
132
|
+
raise LineError("candidate_result_invalid", "候选锚点不完整。")
|
|
133
|
+
if kind == "horizontal_line":
|
|
134
|
+
return {"price": anchors[0]["price"]}
|
|
135
|
+
if kind == "labeled_polyline":
|
|
136
|
+
return {"points": [{"label": "ABC"[index], "time": str(anchor["time"]), "price": anchor["price"]}
|
|
137
|
+
for index, anchor in enumerate(anchors)]}
|
|
138
|
+
return {"start_time": str(anchors[0]["time"]), "start_price": anchors[0]["price"],
|
|
139
|
+
"end_time": str(anchors[1]["time"]), "end_price": anchors[1]["price"]}
|
|
140
|
+
if kind == "price_pattern":
|
|
141
|
+
try:
|
|
142
|
+
return {"pattern": selected, "rule_version": summary["rule_version"], "as_of": summary["as_of"]}
|
|
143
|
+
except (TypeError, KeyError):
|
|
144
|
+
raise LineError("candidate_result_invalid", "形态候选缺少规则版本或截止日。") from None
|
|
145
|
+
if kind == "channel":
|
|
146
|
+
try:
|
|
147
|
+
anchors = selected["anchors"]
|
|
148
|
+
return {prefix + "_time": str(anchors[key]["time"])
|
|
149
|
+
for prefix, key in (("start", "from"), ("end", "to"), ("parallel", "parallel"))} | {
|
|
150
|
+
prefix + "_price": anchors[key]["price"]
|
|
151
|
+
for prefix, key in (("start", "from"), ("end", "to"), ("parallel", "parallel"))}
|
|
152
|
+
except (TypeError, KeyError):
|
|
153
|
+
raise LineError("candidate_result_invalid", "通道候选锚点不完整。") from None
|
|
154
|
+
try:
|
|
155
|
+
return {"start_time": str(selected["start_time"]), "end_time": str(selected["end_time"]),
|
|
156
|
+
"lower_price": selected["lower_price"], "upper_price": selected["upper_price"]}
|
|
157
|
+
except (TypeError, KeyError):
|
|
158
|
+
raise LineError("candidate_result_invalid", "平台候选边界不完整。") from None
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Bounded, key-less A-share daily candle fallback via BaoStock's public SDK.
|
|
2
|
+
|
|
3
|
+
The SDK keeps a process-global socket and may wait indefinitely for a reply.
|
|
4
|
+
Run each request in a short-lived child process so a failing free service cannot
|
|
5
|
+
block the MCP server or contaminate another chart's provider connection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import importlib.util
|
|
12
|
+
import io
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import socket
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from copy import deepcopy
|
|
23
|
+
from datetime import datetime, timedelta, timezone
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
SOURCE = "baostock_free"
|
|
29
|
+
SOURCE_URL = "https://www.baostock.com/"
|
|
30
|
+
_SHANGHAI = timezone(timedelta(hours=8))
|
|
31
|
+
_MAX_ROWS = 10_000
|
|
32
|
+
_TIMEOUT_SECONDS = 12
|
|
33
|
+
_FIELDS = "date,code,open,high,low,close,volume"
|
|
34
|
+
_ADJUST_FLAGS = {"none": "3", "forward": "2", "backward": "1"}
|
|
35
|
+
_CACHE_TTL_SECONDS = 90
|
|
36
|
+
_CACHE_MAX_ENTRIES = 64
|
|
37
|
+
_cache: dict[tuple[str, int, str], tuple[float, list[dict[str, Any]]]] = {}
|
|
38
|
+
_cache_lock = threading.Lock()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def source_status() -> dict[str, Any]:
|
|
42
|
+
"""Report installed capability without pretending to probe connectivity."""
|
|
43
|
+
return {
|
|
44
|
+
"installed": importlib.util.find_spec("baostock") is not None,
|
|
45
|
+
"capabilities": ["cn_a_share_historical_daily_candles"],
|
|
46
|
+
"requires_key": False,
|
|
47
|
+
"reachability": "not_probed",
|
|
48
|
+
"source_url": SOURCE_URL,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def eligible_stock_code(symbol: str) -> str | None:
|
|
53
|
+
"""Require an explicit exchange and an A-share stock prefix.
|
|
54
|
+
|
|
55
|
+
This deliberately excludes indices, funds, B shares and bare codes. The
|
|
56
|
+
BaoStock query does not accept our canonical symbol suffixes directly.
|
|
57
|
+
"""
|
|
58
|
+
value = str(symbol or "").strip().upper()
|
|
59
|
+
match = re.fullmatch(r"(\d{6})\.(XSHG|XSHE)", value)
|
|
60
|
+
if not match:
|
|
61
|
+
return None
|
|
62
|
+
code, market = match.groups()
|
|
63
|
+
if market == "XSHG" and code.startswith(("600", "601", "603", "605", "688", "689")):
|
|
64
|
+
return f"sh.{code}"
|
|
65
|
+
if market == "XSHE" and code.startswith(("000", "001", "002", "003", "300", "301", "302")):
|
|
66
|
+
return f"sz.{code}"
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _normalize_rows(raw_rows: Any, expected_code: str) -> list[dict[str, Any]]:
|
|
71
|
+
if not isinstance(raw_rows, list) or len(raw_rows) > _MAX_ROWS:
|
|
72
|
+
return []
|
|
73
|
+
rows: list[dict[str, Any]] = []
|
|
74
|
+
seen: set[int] = set()
|
|
75
|
+
for raw in raw_rows:
|
|
76
|
+
if not isinstance(raw, list) or len(raw) != 7 or raw[1] != expected_code:
|
|
77
|
+
return []
|
|
78
|
+
try:
|
|
79
|
+
date = datetime.strptime(raw[0], "%Y-%m-%d").replace(hour=15, tzinfo=_SHANGHAI)
|
|
80
|
+
stamp = int(date.timestamp())
|
|
81
|
+
opened, high, low, closed, volume = map(float, raw[2:])
|
|
82
|
+
except (TypeError, ValueError, OverflowError):
|
|
83
|
+
return []
|
|
84
|
+
if (
|
|
85
|
+
stamp in seen or not all(map(math.isfinite, (opened, high, low, closed, volume)))
|
|
86
|
+
or min(opened, high, low, closed) <= 0 or volume < 0
|
|
87
|
+
or high < max(opened, low, closed) or low > min(opened, high, closed)
|
|
88
|
+
):
|
|
89
|
+
return []
|
|
90
|
+
seen.add(stamp)
|
|
91
|
+
rows.append({"time": stamp, "open": opened, "high": high, "low": low, "close": closed, "volume": volume})
|
|
92
|
+
rows.sort(key=lambda item: item["time"])
|
|
93
|
+
return rows
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def fetch_stock_daily(symbol: str, *, limit: int, adjust: str) -> list[dict[str, Any]] | None:
|
|
97
|
+
"""Return recent normalized daily OHLCV, or None without changing state."""
|
|
98
|
+
code = eligible_stock_code(symbol)
|
|
99
|
+
if not code or adjust not in _ADJUST_FLAGS:
|
|
100
|
+
return None
|
|
101
|
+
wanted = max(2, min(int(limit), 4000))
|
|
102
|
+
cache_key = (code, wanted, adjust)
|
|
103
|
+
with _cache_lock:
|
|
104
|
+
cached = _cache.get(cache_key)
|
|
105
|
+
if cached and time.monotonic() - cached[0] < _CACHE_TTL_SECONDS:
|
|
106
|
+
return deepcopy(cached[1])
|
|
107
|
+
request = {"code": code, "limit": wanted, "adjustflag": _ADJUST_FLAGS[adjust]}
|
|
108
|
+
# The fallback needs no account credential. Do not inherit the host's
|
|
109
|
+
# FTShare key, DSH tokens, or unrelated secrets into the child process.
|
|
110
|
+
child_env = {
|
|
111
|
+
key: value for key, value in os.environ.items()
|
|
112
|
+
if not re.search(r"(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)", key, re.IGNORECASE)
|
|
113
|
+
}
|
|
114
|
+
try:
|
|
115
|
+
process = subprocess.run(
|
|
116
|
+
[sys.executable, str(Path(__file__).resolve()), "--worker"],
|
|
117
|
+
input=json.dumps(request), text=True, capture_output=True,
|
|
118
|
+
timeout=_TIMEOUT_SECONDS, check=False, env=child_env,
|
|
119
|
+
)
|
|
120
|
+
if process.returncode != 0 or len(process.stdout) > 1_500_000:
|
|
121
|
+
return None
|
|
122
|
+
payload = json.loads(process.stdout)
|
|
123
|
+
rows = _normalize_rows(payload.get("rows"), code)
|
|
124
|
+
if len(rows) < 2:
|
|
125
|
+
return None
|
|
126
|
+
result = rows[-wanted:]
|
|
127
|
+
with _cache_lock:
|
|
128
|
+
if len(_cache) >= _CACHE_MAX_ENTRIES:
|
|
129
|
+
oldest = min(_cache, key=lambda item: _cache[item][0])
|
|
130
|
+
_cache.pop(oldest, None)
|
|
131
|
+
_cache[cache_key] = (time.monotonic(), result)
|
|
132
|
+
return deepcopy(result)
|
|
133
|
+
except (OSError, subprocess.TimeoutExpired, ValueError, TypeError):
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _worker() -> int:
|
|
138
|
+
"""Isolated SDK session; all SDK chatter stays out of the JSON protocol."""
|
|
139
|
+
try:
|
|
140
|
+
request = json.load(sys.stdin)
|
|
141
|
+
code = str(request["code"])
|
|
142
|
+
wanted = int(request["limit"])
|
|
143
|
+
flag = str(request["adjustflag"])
|
|
144
|
+
if not re.fullmatch(r"(?:sh|sz)\.\d{6}", code) or not 2 <= wanted <= 4000 or flag not in _ADJUST_FLAGS.values():
|
|
145
|
+
return 1
|
|
146
|
+
import baostock as bs
|
|
147
|
+
|
|
148
|
+
socket.setdefaulttimeout(5)
|
|
149
|
+
end = datetime.now(_SHANGHAI).date()
|
|
150
|
+
start = end - timedelta(days=min(365 * 30, max(365, int(wanted * 1.8))))
|
|
151
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
152
|
+
login = bs.login()
|
|
153
|
+
if str(login.error_code) != "0":
|
|
154
|
+
return 1
|
|
155
|
+
try:
|
|
156
|
+
result = bs.query_history_k_data_plus(
|
|
157
|
+
code, _FIELDS, start_date=start.isoformat(), end_date=end.isoformat(),
|
|
158
|
+
frequency="d", adjustflag=flag,
|
|
159
|
+
)
|
|
160
|
+
if str(result.error_code) != "0" or list(result.fields or []) != _FIELDS.split(","):
|
|
161
|
+
return 1
|
|
162
|
+
rows = []
|
|
163
|
+
while result.next():
|
|
164
|
+
if len(rows) >= _MAX_ROWS:
|
|
165
|
+
return 1
|
|
166
|
+
rows.append(result.get_row_data())
|
|
167
|
+
finally:
|
|
168
|
+
bs.logout()
|
|
169
|
+
sys.stdout.write(json.dumps({"rows": rows}, separators=(",", ":")))
|
|
170
|
+
return 0
|
|
171
|
+
except (Exception, KeyboardInterrupt): # noqa: BLE001 - child must fail closed
|
|
172
|
+
return 1
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
if __name__ == "__main__":
|
|
176
|
+
raise SystemExit(_worker() if sys.argv[1:] == ["--worker"] else 1)
|
package/tools/calc.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Small calculation wrapper used by the standalone dsh_kline MCP server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from core.calc import AVAILABLE_METRICS, calc_metrics as _calc_metrics
|
|
8
|
+
from core.rows import validate_rows
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def run_calc_metrics(
|
|
12
|
+
rows: Any,
|
|
13
|
+
metrics: list[str] | None = None,
|
|
14
|
+
*,
|
|
15
|
+
rsi_period: int = 14,
|
|
16
|
+
boll_period: int = 20,
|
|
17
|
+
boll_std: float = 2.0,
|
|
18
|
+
atr_period: int = 14,
|
|
19
|
+
volume_ma: int = 20,
|
|
20
|
+
ma_periods: list[int] | None = None,
|
|
21
|
+
) -> dict[str, Any]:
|
|
22
|
+
normalized = validate_rows(rows, min_len=2)
|
|
23
|
+
result = _calc_metrics(
|
|
24
|
+
normalized,
|
|
25
|
+
metrics=metrics,
|
|
26
|
+
rsi_period=rsi_period,
|
|
27
|
+
boll_period=boll_period,
|
|
28
|
+
boll_std=boll_std,
|
|
29
|
+
atr_period=atr_period,
|
|
30
|
+
volume_ma=volume_ma,
|
|
31
|
+
ma_periods=ma_periods,
|
|
32
|
+
)
|
|
33
|
+
result["available_metrics"] = list(AVAILABLE_METRICS)
|
|
34
|
+
result["analysis_window"] = {
|
|
35
|
+
"start_time": int(normalized[0]["time"]),
|
|
36
|
+
"end_time": int(normalized[-1]["time"]),
|
|
37
|
+
"bars": len(normalized),
|
|
38
|
+
}
|
|
39
|
+
return result
|