@dsh-ft/dsh-fft-paper-trading 0.7.1 → 0.7.2

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 (130) hide show
  1. package/lib/client.js +1 -1
  2. package/package.json +1 -4
  3. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
  4. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  5. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  6. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
  7. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
  8. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
  9. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  10. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  11. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
  12. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  13. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  14. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  15. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
  16. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  17. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  18. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  78. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  79. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  80. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
  81. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  82. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  83. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  85. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
  86. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  87. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  121. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  122. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  123. package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
  124. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  125. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  126. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  127. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  128. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  129. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  130. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,119 +0,0 @@
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)
@@ -1,158 +0,0 @@
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
@@ -1,176 +0,0 @@
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)
@@ -1,39 +0,0 @@
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