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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/CHANGELOG.md +601 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +116 -0
  5. package/README.md +115 -2
  6. package/chart_service.py +687 -0
  7. package/config/basic-symbols.json +570 -0
  8. package/config/dsh-kline.patch.yml +4 -0
  9. package/config/dsh-tool-catalog.json +3875 -0
  10. package/cordis.patch.yml +33 -0
  11. package/core/__init__.py +0 -0
  12. package/core/adjustment.py +16 -0
  13. package/core/calc.py +691 -0
  14. package/core/rows.py +228 -0
  15. package/core/ta_engine.py +99 -0
  16. package/docs/anonymous-market-support.md +33 -0
  17. package/docs/automatic-drawing.md +24 -0
  18. package/docs/chart-functions.md +136 -0
  19. package/docs/drawing-examples.en.md +13 -0
  20. package/docs/drawing-examples.md +13 -0
  21. package/docs/embedding.md +43 -0
  22. package/docs/fixtures/price-pattern-real-v1.json +1 -0
  23. package/docs/free-foreign-daily.md +44 -0
  24. package/docs/guide.en.md +232 -0
  25. package/docs/guide.md +248 -0
  26. package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
  27. package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
  28. package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
  29. package/docs/images/dsh-kline-tab-workspace.png +0 -0
  30. package/docs/images/dsh-market.png +0 -0
  31. package/docs/images/kline-news.png +0 -0
  32. package/docs/images/kline-range-stats.png +0 -0
  33. package/docs/images/kline-support.png +0 -0
  34. package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
  35. package/docs/images/market-overview-v0.6.9.png +0 -0
  36. package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
  37. package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
  38. package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
  39. package/docs/npm-release.md +33 -0
  40. package/docs/price-pattern-rules-v1.md +40 -0
  41. package/docs/price-pattern-samples-v1.md +42 -0
  42. package/docs/provider-adaptation.md +73 -0
  43. package/docs/release-acceptance-v0.4.0.md +46 -0
  44. package/docs/release-acceptance-v0.4.1.md +43 -0
  45. package/docs/release-acceptance-v0.5.0.md +40 -0
  46. package/docs/release-acceptance-v0.6.0.md +33 -0
  47. package/docs/release-acceptance-v0.6.1.md +19 -0
  48. package/docs/release-acceptance-v0.6.10.md +21 -0
  49. package/docs/release-acceptance-v0.6.2.md +31 -0
  50. package/docs/release-acceptance-v0.6.3.md +25 -0
  51. package/docs/release-acceptance-v0.6.4.md +24 -0
  52. package/docs/release-acceptance-v0.6.5.md +21 -0
  53. package/docs/release-acceptance-v0.6.6.md +21 -0
  54. package/docs/release-acceptance-v0.6.7.md +18 -0
  55. package/docs/release-acceptance-v0.6.8.md +18 -0
  56. package/docs/release-acceptance-v0.6.9.md +98 -0
  57. package/docs/release-notes-v0.5.0.md +23 -0
  58. package/docs/release-notes-v0.6.0.md +11 -0
  59. package/docs/release-notes-v0.6.1.md +20 -0
  60. package/docs/release-notes-v0.6.10.md +11 -0
  61. package/docs/release-notes-v0.6.2.md +14 -0
  62. package/docs/release-notes-v0.6.3.md +26 -0
  63. package/docs/release-notes-v0.6.4.md +12 -0
  64. package/docs/release-notes-v0.6.5.md +13 -0
  65. package/docs/release-notes-v0.6.6.md +13 -0
  66. package/docs/release-notes-v0.6.7.md +17 -0
  67. package/docs/release-notes-v0.6.8.md +10 -0
  68. package/docs/release-notes-v0.6.9.md +16 -0
  69. package/lib/candle-sequence.js +15 -0
  70. package/lib/chart-adjustment.js +7 -0
  71. package/lib/chart-annotations.js +33 -0
  72. package/lib/chart-applications.js +171 -0
  73. package/lib/chart-context.js +164 -0
  74. package/lib/chart-observation.js +251 -0
  75. package/lib/chart-service-status.js +82 -0
  76. package/lib/chart-source-status.js +39 -0
  77. package/lib/chart-sources.js +354 -0
  78. package/lib/client/BetterSidebarTab.js +70 -0
  79. package/lib/client/ClassicShell.js +254 -0
  80. package/lib/client/KlineContent.js +155 -0
  81. package/lib/client/chart-apply.js +73 -0
  82. package/lib/client/chart-context.js +233 -0
  83. package/lib/client/chart-handoff.js +34 -0
  84. package/lib/client/chart-session-resolver.js +74 -0
  85. package/lib/client/client-context.js +1 -0
  86. package/lib/client/conversation.js +88 -0
  87. package/lib/client/default-tab.js +83 -0
  88. package/lib/client/embed.js +50 -0
  89. package/lib/client/generated-view.js +12983 -0
  90. package/lib/client/horizontal-lines.js +19 -0
  91. package/lib/client/index.js +62 -0
  92. package/lib/client/mode-preferences.js +28 -0
  93. package/lib/client/native-sidebar-contract.js +45 -0
  94. package/lib/client/native-sidebar-register.js +133 -0
  95. package/lib/client/native-sidebar-services.js +1 -0
  96. package/lib/client/native-sidebar.js +96 -0
  97. package/lib/client/sidebar-integration.js +93 -0
  98. package/lib/client/ui-onboarding.js +42 -0
  99. package/lib/client/version.js +14 -0
  100. package/lib/client.js +17382 -0
  101. package/lib/client.js.map +1 -0
  102. package/lib/drawing-feedback.js +284 -0
  103. package/lib/fibonacci.js +18 -0
  104. package/lib/ftshare-settings-bridge.js +159 -0
  105. package/lib/index.js +279 -0
  106. package/lib/labeled-polyline.js +17 -0
  107. package/lib/pattern-groups.js +91 -0
  108. package/lib/price-bands.js +55 -0
  109. package/lib/price-series.js +47 -0
  110. package/lib/price-sticks.js +32 -0
  111. package/lib/types/candle-sequence.d.ts +2 -0
  112. package/lib/types/chart-adjustment.d.ts +2 -0
  113. package/lib/types/chart-annotations.d.ts +4 -0
  114. package/lib/types/chart-applications.d.ts +26 -0
  115. package/lib/types/chart-context.d.ts +14 -0
  116. package/lib/types/chart-observation.d.ts +8 -0
  117. package/lib/types/chart-service-status.d.ts +22 -0
  118. package/lib/types/chart-source-status.d.ts +47 -0
  119. package/lib/types/chart-sources.d.ts +25 -0
  120. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  121. package/lib/types/client/ClassicShell.d.ts +4 -0
  122. package/lib/types/client/KlineContent.d.ts +37 -0
  123. package/lib/types/client/chart-apply.d.ts +13 -0
  124. package/lib/types/client/chart-context.d.ts +23 -0
  125. package/lib/types/client/chart-handoff.d.ts +5 -0
  126. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  127. package/lib/types/client/client-context.d.ts +14 -0
  128. package/lib/types/client/conversation.d.ts +43 -0
  129. package/lib/types/client/default-tab.d.ts +3 -0
  130. package/lib/types/client/embed.d.ts +37 -0
  131. package/lib/types/client/generated-view.d.ts +2 -0
  132. package/lib/types/client/horizontal-lines.d.ts +1 -0
  133. package/lib/types/client/index.d.ts +4 -0
  134. package/lib/types/client/mode-preferences.d.ts +13 -0
  135. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  136. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  137. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  138. package/lib/types/client/native-sidebar.d.ts +47 -0
  139. package/lib/types/client/sidebar-integration.d.ts +12 -0
  140. package/lib/types/client/ui-onboarding.d.ts +6 -0
  141. package/lib/types/client/version.d.ts +1 -0
  142. package/lib/types/drawing-feedback.d.ts +5 -0
  143. package/lib/types/fibonacci.d.ts +5 -0
  144. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  145. package/lib/types/index.d.ts +26 -0
  146. package/lib/types/labeled-polyline.d.ts +11 -0
  147. package/lib/types/pattern-groups.d.ts +2 -0
  148. package/lib/types/price-bands.d.ts +3 -0
  149. package/lib/types/price-series.d.ts +5 -0
  150. package/lib/types/price-sticks.d.ts +3 -0
  151. package/package.json +153 -4
  152. package/requirements.txt +6 -0
  153. package/screenshots.json +11 -0
  154. package/scripts/bootstrap.sh +5 -0
  155. package/scripts/dsh-bootstrap.mjs +179 -0
  156. package/scripts/dsh-mcp-plugin.mjs +27 -0
  157. package/scripts/run-dsh-kline.mjs +658 -0
  158. package/scripts/run-dsh-kline.sh +5 -0
  159. package/server.py +1755 -0
  160. package/tools/__init__.py +0 -0
  161. package/tools/annotations.py +119 -0
  162. package/tools/automatic_analysis.py +158 -0
  163. package/tools/baostock_source.py +176 -0
  164. package/tools/calc.py +39 -0
  165. package/tools/channel_candidates.py +260 -0
  166. package/tools/channel_preview.py +82 -0
  167. package/tools/channels.py +104 -0
  168. package/tools/chart_applications.py +204 -0
  169. package/tools/chart_context.py +186 -0
  170. package/tools/chart_edits.py +363 -0
  171. package/tools/chart_functions.py +451 -0
  172. package/tools/chart_indicators.py +65 -0
  173. package/tools/chart_measurements.py +84 -0
  174. package/tools/chart_source_status.py +32 -0
  175. package/tools/chart_sources.py +31 -0
  176. package/tools/closed_daily.py +68 -0
  177. package/tools/draw.py +410 -0
  178. package/tools/drawing_feedback.py +45 -0
  179. package/tools/drawing_interaction.py +117 -0
  180. package/tools/drawing_verification.py +141 -0
  181. package/tools/fetch.py +4680 -0
  182. package/tools/fibonacci.py +83 -0
  183. package/tools/foreign_daily.py +185 -0
  184. package/tools/free_sources.py +483 -0
  185. package/tools/lines.py +91 -0
  186. package/tools/nine_count.py +66 -0
  187. package/tools/pattern_groups.py +103 -0
  188. package/tools/pivots.py +60 -0
  189. package/tools/polylines.py +131 -0
  190. package/tools/price_bands.py +165 -0
  191. package/tools/price_patterns.py +311 -0
  192. package/tools/price_series.py +162 -0
  193. package/tools/price_sticks.py +114 -0
  194. package/tools/range_candidates.py +170 -0
  195. package/tools/recent_drawing_candidates.py +123 -0
  196. package/tools/rectangles.py +76 -0
  197. package/tools/regression_channels.py +87 -0
  198. package/tools/ta_functions.py +228 -0
  199. package/tools/trend_lines.py +106 -0
  200. package/tools/watchlist.py +149 -0
  201. package/view/ft-logo.jpg +0 -0
  202. package/view/kline.html +12436 -0
  203. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,363 @@
1
+ """Version-guarded drawing preparation. Never applies a candidate to the live UI."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from typing import Annotated, Any, Literal
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+ import chart_service
13
+ from core.adjustment import normalize_adjustment
14
+ from tools.chart_context import read_chart_context
15
+ from tools.lines import ColorInput, LINE_COMMAND, LineError, edit_horizontal_line, validate_line_fields
16
+ from tools.trend_lines import TREND_COMMAND, edit_trend_line
17
+ from tools.channels import CHANNEL_COMMAND, edit_channel
18
+ from tools.rectangles import RECTANGLE_COMMAND, edit_rectangle
19
+ from tools.fibonacci import FIBONACCI_COMMAND, edit_fibonacci
20
+ from tools.polylines import LabeledPoint, POLYLINE_COMMAND, edit_polyline, normalize_point_label
21
+ from tools.annotations import ANNOTATION_COMMAND, ANNOTATION_KINDS, edit_annotation
22
+ from tools.price_series import SERIES_COMMAND, edit_price_series
23
+ from tools.price_bands import BAND_COMMAND, edit_price_band
24
+ from tools.price_sticks import STICKS_COMMAND, edit_price_sticks
25
+ from tools.pattern_groups import PATTERN_COMMAND, NINE_COMMAND, edit_pattern_group
26
+
27
+ KINDS = {LINE_COMMAND: "horizontal_line", TREND_COMMAND: "trend_line",
28
+ CHANNEL_COMMAND: "channel", RECTANGLE_COMMAND: "rectangle", FIBONACCI_COMMAND: "fibonacci_retracement",
29
+ POLYLINE_COMMAND: "labeled_polyline", ANNOTATION_COMMAND: "annotation", SERIES_COMMAND: "series_line",
30
+ BAND_COMMAND: "price_band", STICKS_COMMAND: "price_sticks",
31
+ PATTERN_COMMAND: "price_pattern", NINE_COMMAND: "nine_count"}
32
+
33
+
34
+ class ChartEdit(BaseModel):
35
+ model_config = ConfigDict(extra="forbid")
36
+ kind: Literal["horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks", "price_pattern", "nine_count", "all_drawings"]
37
+ action: Literal["create", "update", "delete"]
38
+ object_id: str | None = Field(default=None, min_length=1, max_length=128,
39
+ description="修改/删除使用当前观察中的 AI 稳定 ID;创建不填")
40
+ name: str | None = Field(default=None, max_length=48)
41
+ color: ColorInput | None = None
42
+ price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
43
+ start_time: str | None = None
44
+ end_time: str | None = None
45
+ start_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
46
+ end_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
47
+ parallel_time: str | None = None
48
+ parallel_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
49
+ lower_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
50
+ upper_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
51
+ show_midline: bool | None = Field(default=None, strict=True)
52
+ show_fill: bool | None = Field(default=None, strict=True)
53
+ points: list[LabeledPoint] | None = Field(default=None, min_length=2, max_length=8, description="仅用于创建标注折线,续改用单点字段")
54
+ point_label: str | None = Field(default=None, min_length=1, max_length=16, description="更新该对象内的唯一点名,不按索引猜点")
55
+ point_time: str | None = None
56
+ point_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
57
+ anchor_time: str | None = Field(default=None, description="标注锚定的已加载K线日期/时间")
58
+ anchor_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
59
+ annotation_text: str | None = Field(default=None, max_length=120, description="文字标注内容")
60
+ annotation_value: float | None = Field(default=None, allow_inf_nan=False, strict=True, description="数值标注内容,可为负数或零")
61
+ annotation_icon: Literal["arrow_up", "arrow_down", "diamond"] | None = Field(default=None, description="图标标注:向上箭头、向下箭头或菱形")
62
+ ratios: list[Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)]] | None = Field(default=None, min_length=1, max_length=16)
63
+ result_ref: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$",
64
+ description="run_chart_function 返回的结果引用;不能同时指定锚点、边界或比例。名称、颜色可另填。")
65
+ ta_result_ref: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$",
66
+ description="明确选择同一当前图的 SMA/EMA(close) 到 series_line,或 BBANDS(close) 三线到 price_band;不自动绘图。")
67
+ candidate_result_ref: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$",
68
+ description="当前图自动候选的只读引用;用户直接要求自动绘图时可选择第一项")
69
+ candidate_number: int | None = Field(default=None, strict=True, ge=1, le=5,
70
+ description="用户指定或宿主从最新合格结果中选择的候选序号,从1开始")
71
+ user_confirmed_candidate: bool | None = Field(default=None, strict=True,
72
+ description="用户明确要求直接绘图或选定候选时填 true;仅分析/提案请求不可填")
73
+
74
+
75
+ def edit_parameters(edit: ChartEdit) -> dict[str, Any]:
76
+ fields = edit.model_dump(exclude_none=True)
77
+ for key in ("kind", "action", "object_id"): fields.pop(key, None)
78
+ supported = {"name", "color", "result_ref", "ta_result_ref", "candidate_result_ref", "candidate_number", "user_confirmed_candidate"} | {
79
+ "horizontal_line": {"price"},
80
+ "trend_line": {"start_time", "end_time", "start_price", "end_price"},
81
+ "channel": {"start_time", "end_time", "start_price", "end_price", "parallel_time", "parallel_price", "show_midline"},
82
+ "rectangle": {"start_time", "end_time", "lower_price", "upper_price", "show_fill"},
83
+ "fibonacci_retracement": {"start_time", "end_time", "start_price", "end_price", "ratios"},
84
+ "labeled_polyline": {"points", "point_label", "point_time", "point_price"},
85
+ "text_annotation": {"anchor_time", "anchor_price", "annotation_text"},
86
+ "number_annotation": {"anchor_time", "anchor_price", "annotation_value"},
87
+ "icon_annotation": {"anchor_time", "anchor_price", "annotation_icon"},
88
+ "series_line": set(),
89
+ "price_band": set(),
90
+ "price_sticks": set(),
91
+ "price_pattern": set(),
92
+ "nine_count": set(),
93
+ "all_drawings": set(),
94
+ }[edit.kind]
95
+ if fields.keys() - supported or edit.action == "delete" and fields:
96
+ raise LineError("invalid_edit_fields", "参数不适用于该图形;删除只填类型、action,单对象删除另填 object_id。")
97
+ if edit.kind == "labeled_polyline" and edit.action != "create" and (edit.points is not None or edit.result_ref is not None and edit.action != "update"):
98
+ raise LineError("polyline_replacement_not_supported", "标注折线续改使用 point_label 和 point_time / point_price;名称 / 颜色可另填,不重写整组。")
99
+ if edit.kind == "labeled_polyline" and edit.action == "update" and edit.result_ref is not None and any(
100
+ value is not None for value in (edit.point_label, edit.point_time, edit.point_price)):
101
+ raise LineError("conflicting_function_parameters", "整组结果引用不能与单点修改混用。")
102
+ if edit.result_ref is not None and (edit.kind not in {"fibonacci_retracement", "channel", "rectangle", "labeled_polyline", "series_line", "price_band", "price_sticks", "nine_count", *ANNOTATION_KINDS}
103
+ or fields.keys() - {"result_ref", "name", "color", "show_midline", "show_fill"}):
104
+ raise LineError("conflicting_function_parameters", "结果引用与直接锚点、边界或比例互斥;请修改参数后重新运行函数。")
105
+ if edit.ta_result_ref is not None and (edit.kind not in {"series_line", "price_band"} or edit.action not in {"create", "update"}
106
+ or fields.keys() - {"ta_result_ref", "name", "color"}):
107
+ raise LineError("ta_result_not_drawable", "仅允许把明确选定的 SMA/EMA 单线或 BBANDS 三线结果创建或更新为对应图形。")
108
+ candidate_fields = {"candidate_result_ref", "candidate_number", "user_confirmed_candidate"}
109
+ candidate_kinds = {"horizontal_line", "trend_line", "fibonacci_retracement", "labeled_polyline", "channel", "rectangle", "price_pattern"}
110
+ candidate_extras = {"name", "color", "show_midline", "show_fill"} | ({"ratios"} if edit.kind == "fibonacci_retracement" else set())
111
+ if fields.keys() & candidate_fields and (edit.action not in {"create", "update"} or edit.kind not in candidate_kinds
112
+ or not candidate_fields <= fields.keys() or edit.user_confirmed_candidate is not True
113
+ or fields.keys() - candidate_fields - candidate_extras):
114
+ raise LineError("candidate_confirmation_required", "候选绘图需要用户直接绘图请求或明确选定候选,并填写原结果引用、序号及授权标记。")
115
+ if edit.kind == "all_drawings" and (edit.action != "delete" or edit.object_id is not None):
116
+ raise LineError("invalid_object_identity", "清空当前图只使用 all_drawings/delete,不指定单个对象 ID。")
117
+ if edit.kind != "all_drawings" and (edit.action == "create" and edit.object_id is not None or edit.action != "create" and edit.object_id is None):
118
+ raise LineError("invalid_object_identity", "创建不指定 object_id;修改/删除必须使用当前观察中的完整 AI ID。")
119
+ _, name, color = validate_line_fields(name=edit.name, color=edit.color)
120
+ if "name" in fields: fields["name"] = name
121
+ if "color" in fields: fields["color"] = color
122
+ if "point_label" in fields: fields["point_label"] = normalize_point_label(fields["point_label"])
123
+ return fields
124
+
125
+
126
+ def snapshot_inventory(payload: dict) -> list[dict]:
127
+ """Same canonical AI fields exposed by the browser collector; no manual objects."""
128
+ inventory = []
129
+ for cmd in payload.get("chartCommands", []):
130
+ kind = cmd.get("kind") if cmd.get("type") == ANNOTATION_COMMAND and cmd.get("kind") in ANNOTATION_KINDS else KINDS.get(cmd.get("type"))
131
+ if not kind: continue
132
+ item = {"id": cmd.get("id"), "kind": kind, "origin": "ai", "name": cmd.get("label", ""),
133
+ "color": cmd.get("color", "info"), "interval": cmd.get("interval", payload.get("interval"))}
134
+ if kind == "horizontal_line": item["price"] = cmd["price"]
135
+ elif kind == "rectangle":
136
+ item.update({k: cmd[k] for k in ("start_time", "end_time", "lower_price", "upper_price", "show_fill")})
137
+ elif kind == "labeled_polyline": item["points"] = deepcopy(cmd["points"])
138
+ elif kind == "series_line": item.update(series_hash=cmd["series_hash"], bar_count=cmd["bar_count"])
139
+ elif kind == "price_band": item.update(band_hash=cmd["band_hash"], bar_count=cmd["bar_count"])
140
+ elif kind == "price_sticks": item.update(sticks_hash=cmd["sticks_hash"], bar_count=cmd["bar_count"])
141
+ elif kind in {"price_pattern", "nine_count"}:
142
+ item.update(geometry_hash=cmd["geometry_hash"], bar_count=cmd["bar_count"],
143
+ rule_version=cmd["rule_version"], as_of=cmd["as_of"])
144
+ elif kind in ANNOTATION_KINDS:
145
+ item.update(time=cmd["time"], price=cmd["price"])
146
+ if kind == "text_annotation": item["text"] = cmd["text"]
147
+ elif kind == "number_annotation": item["value"] = cmd["value"]
148
+ else: item["icon"] = cmd["icon"]
149
+ else:
150
+ item["points"] = [cmd["from"], cmd["to"]] + ([cmd["parallel"]] if kind == "channel" else [])
151
+ if kind == "channel": item["show_midline"] = cmd["show_midline"]
152
+ if kind == "fibonacci_retracement":
153
+ item.update(ratios=deepcopy(cmd["ratios"]), levels=deepcopy(cmd["levels"]))
154
+ inventory.append(item)
155
+ return inventory
156
+
157
+
158
+ def _unique_inventory(items: list[dict]) -> list[dict]:
159
+ ids = [obj.get("id") for obj in items]
160
+ if any(not isinstance(i, str) or not i for i in ids) or len(set(ids)) != len(ids):
161
+ raise LineError("ambiguous_drawing_id", "当前 AI 图形 ID 缺失或重复,不能安全准备修改。")
162
+ return sorted(items, key=lambda obj: obj["id"])
163
+
164
+
165
+ def require_alignment(context: dict, payload: dict, token: str, symbol: str) -> None:
166
+ from tools.chart_applications import confirmed_source
167
+ from tools.chart_sources import require_confirmed_view_source
168
+ require_confirmed_view_source(payload, context, token)
169
+ if payload.get("drawing_guard") and not confirmed_source(payload, context, token):
170
+ raise LineError("prepared_chart_not_applied", "来源仍是未应用的准备结果,不能把它当作已确认的当前图继续修改。")
171
+ if context["state"] != "ready" or context["candle_selection"]["truncated"]:
172
+ raise LineError("chart_edit_context_not_ready", "当前图未就绪或加载数据超过本阶段核对上限,未准备修改。")
173
+ if (context.get("source_chart_session") != token or context["symbol"].casefold() != symbol.strip().casefold()
174
+ or payload.get("symbol", "").casefold() != context["symbol"].casefold()
175
+ or payload.get("interval") != context["interval"]
176
+ or normalize_adjustment(context.get("adjust")) is None
177
+ or normalize_adjustment(payload.get("adjust")) != normalize_adjustment(context.get("adjust"))):
178
+ raise LineError("chart_snapshot_not_aligned", "来源快照与当前图的标的、周期、复权方式或引用不一致/未知,未使用旧图替代。")
179
+ if context["interval"] == "minute" and (context.get("interval_value") is None
180
+ or payload.get("interval_value") != context["interval_value"]):
181
+ raise LineError("chart_snapshot_not_aligned", "分钟粒度未知或与来源快照不一致,未准备修改。")
182
+ rows = next((c.get("rows", []) for c in payload["chartCommands"] if c.get("type") == "SET_CANDLES"), [])
183
+ projected = [{k: r[k] for k in ("time", "open", "high", "low", "close", "volume")} for r in rows]
184
+ observed = [{k: v for k, v in obj.items() if k not in {"context_editable", "edit_capability"}}
185
+ for obj in context["drawings"] if obj.get("origin") == "ai"]
186
+ if projected != context["candles"] or _unique_inventory(snapshot_inventory(payload)) != _unique_inventory(observed):
187
+ raise LineError("chart_snapshot_not_aligned", "当前图的行情或 AI 图形已偏离来源快照,不能用旧快照覆盖当前状态。")
188
+
189
+
190
+ def _hash(value: Any) -> str:
191
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
192
+
193
+
194
+ def _public_edit_object(kind: str, obj: dict) -> dict:
195
+ if kind not in {"series_line", "price_band", "price_sticks"}:
196
+ return obj
197
+ # Sequence values stay in the candidate snapshot. The host only needs a
198
+ # stable identity, provenance and a checkable count/hash.
199
+ fields = {
200
+ "series_line": ("series_hash", "values"),
201
+ "price_band": ("band_hash", "upper_values"),
202
+ "price_sticks": ("sticks_hash", "start_values"),
203
+ }
204
+ digest_field, count_field = fields[kind]
205
+ visible = ("type", "id", "interval", "bar_count", "row_hash", digest_field,
206
+ "source", "upper_source", "lower_source", "start_source", "end_source",
207
+ "condition", "label", "color")
208
+ return {key: deepcopy(obj[key]) for key in visible if key in obj} | {
209
+ "valid_bars": sum(value is not None for value in obj[count_field])}
210
+
211
+
212
+ def prepare_chart_edit(context_ref: str, expected_revision: int, chart_session: str, symbol: str,
213
+ request_id: str, edit: ChartEdit, *, publish=None) -> dict:
214
+ """Prepare at most one candidate per observed revision; durable fail-closed retry journal.
215
+
216
+ Publication is not live mutation. A browser may change after the last observation;
217
+ candidate snapshots are blocked from ordinary rendering; the separate apply protocol performs live checks.
218
+ """
219
+ if isinstance(expected_revision, bool) or not isinstance(expected_revision, int) or expected_revision <= 0:
220
+ raise LineError("invalid_context_revision", "expected_revision 必须是读回的正整数观察版本。")
221
+ if not isinstance(request_id, str) or not 1 <= len(request_id) <= 128 or any(ord(c) < 32 for c in request_id):
222
+ raise LineError("invalid_request_id", "request_id 必须为1至128字符,同一次请求重试保持不变。")
223
+ params = edit_parameters(edit)
224
+ context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
225
+ if context["revision"] != expected_revision:
226
+ raise LineError("chart_context_revision_conflict", "当前图观察版本已变化,请重新读取并核对用户意图;未准备修改。")
227
+ if edit.result_ref is not None:
228
+ from tools.chart_functions import resolve_result
229
+ params.update(resolve_result(edit.result_ref, context, edit.kind))
230
+ if edit.ta_result_ref is not None:
231
+ from tools.ta_functions import resolve_ta_drawing
232
+ params.update(resolve_ta_drawing(edit.ta_result_ref, context, edit.kind))
233
+ if edit.candidate_result_ref is not None:
234
+ from tools.chart_functions import resolve_selected_candidate
235
+ params.update(resolve_selected_candidate(edit.candidate_result_ref, context, edit.kind, edit.candidate_number))
236
+ # A sequence's full values belong only in the candidate snapshot. The
237
+ # journal/guard bind them by digest so preparation does not echo thousands
238
+ # of prices back into the host conversation.
239
+ guarded_params = {"digest_sha256": _hash(params)} if edit.kind in {
240
+ "series_line", "price_band", "price_sticks", "price_pattern", "nine_count"} else params
241
+ identity = {"context_ref": context_ref, "expected_revision": expected_revision, "chart_session": chart_session,
242
+ "symbol": symbol.strip().casefold(), "kind": edit.kind, "action": edit.action,
243
+ "object_id": edit.object_id, "parameters": guarded_params}
244
+ fingerprint = _hash(identity)
245
+ directory = chart_service.RUNTIME_DIR / "edits" / str(chart_service.HOST_PROCESS_ID) / context_ref
246
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
247
+ lock = directory / "prepare.lock"
248
+ try:
249
+ descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
250
+ except FileExistsError:
251
+ raise LineError("chart_edit_busy", "该视图正在准备修改或存在未确认的中断锁,未并行发布;不要自动删除锁。") from None
252
+ os.close(descriptor)
253
+ try:
254
+ journal = directory / "journal.json"
255
+ try:
256
+ saved = json.loads(journal.read_text(encoding="utf-8")) if journal.exists() else {"entries": []}
257
+ entries = saved["entries"]
258
+ if not isinstance(entries, list) or len(entries) > 64: raise ValueError("invalid journal")
259
+ if any(not isinstance(e, dict) or not isinstance(e.get("request_id"), str)
260
+ or not isinstance(e.get("revision"), int) or isinstance(e["revision"], bool)
261
+ or e.get("status") not in {"preparing", "prepared", "outcome_unknown"}
262
+ or not isinstance(e.get("fingerprint"), str)
263
+ or e["status"] == "prepared" and not isinstance(e.get("result"), dict)
264
+ for e in entries): raise ValueError("invalid entries")
265
+ except (OSError, ValueError, TypeError, KeyError):
266
+ raise LineError("chart_edit_journal_invalid", "修改日志不可用,停止发布,未自动清空或重建历史。") from None
267
+ previous = next((e for e in entries if e["request_id"] == request_id), None)
268
+ if previous:
269
+ if previous["fingerprint"] != fingerprint:
270
+ raise LineError("request_conflict", "同一 request_id 的版本、对象或参数不同,请核对原请求。")
271
+ if previous["status"] != "prepared":
272
+ raise LineError("chart_edit_outcome_unknown", "该请求可能已发布但结果未确认,停止自动重试,避免重复图形。")
273
+ return {**deepcopy(previous["result"]), "replayed": True}
274
+ if any(e["revision"] == expected_revision for e in entries):
275
+ raise LineError("chart_edit_revision_consumed", "该观察版本已有准备结果或未确认请求;不能从同一版本并行创建分支。")
276
+ if len(entries) >= 64:
277
+ raise LineError("chart_edit_capacity", "该视图修改日志已达本阶段上限,停止发布,未自动丢弃重试记录。")
278
+ payload = chart_service.read_chart_snapshot(chart_session)
279
+ if payload is None: raise LineError("chart_session_not_found", "来源快照不属于当前 DSH 实例或不存在。")
280
+ try:
281
+ require_alignment(context, payload, chart_session, symbol)
282
+ except (KeyError, TypeError, AttributeError):
283
+ raise LineError("chart_snapshot_not_aligned", "来源快照字段无法安全核对,未准备修改。") from None
284
+ if edit.object_id is not None and not any(obj.get("origin") == "ai" and obj["kind"] == edit.kind
285
+ and obj["id"] == edit.object_id for obj in context["drawings"]):
286
+ raise LineError("drawing_not_editable", "目标不是当前观察中的该类型 AI 图形,手动/自动对象不允许修改。")
287
+ if edit.object_id is not None and edit.kind in {"channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "series_line", "price_band", "price_sticks", "price_pattern", "nine_count", *ANNOTATION_KINDS}:
288
+ target = next(obj for obj in context["drawings"] if obj.get("origin") == "ai" and obj["id"] == edit.object_id)
289
+ if target.get("interval") != context["interval"]:
290
+ raise LineError("drawing_interval_mismatch", "目标属于其他周期,当前周期不能改写或删除该对象;请明确切回其适用周期,不自动搬锚点。")
291
+ editors = {"horizontal_line": (edit_horizontal_line, "line_id"), "trend_line": (edit_trend_line, "line_id"),
292
+ "channel": (edit_channel, "channel_id"), "rectangle": (edit_rectangle, "rectangle_id"),
293
+ "fibonacci_retracement": (edit_fibonacci, "fibonacci_id"),
294
+ "labeled_polyline": (edit_polyline, "polyline_id"),
295
+ "series_line": (edit_price_series, "series_id"),
296
+ "price_band": (edit_price_band, "band_id"),
297
+ "price_sticks": (edit_price_sticks, "sticks_id"),
298
+ "price_pattern": (edit_pattern_group, "group_id"),
299
+ "nine_count": (edit_pattern_group, "group_id"),
300
+ "text_annotation": (edit_annotation, "annotation_id"),
301
+ "number_annotation": (edit_annotation, "annotation_id"),
302
+ "icon_annotation": (edit_annotation, "annotation_id")}
303
+ if edit.kind == "all_drawings":
304
+ targets = {item["id"] for item in context["drawings"] if item.get("origin") == "ai"
305
+ and item.get("interval") == context["interval"]}
306
+ if not targets:
307
+ raise LineError("drawing_not_found", "当前周期没有可清空的 AI 图形。")
308
+ edited = deepcopy(payload)
309
+ edited["chartCommands"] = [command for command in payload["chartCommands"]
310
+ if not (command.get("type") in KINDS and command.get("id") in targets)]
311
+ obj = {"kind": "all_drawings", "deleted_count": len(targets)}
312
+ else:
313
+ editor, id_key = editors[edit.kind]
314
+ arguments = dict(params)
315
+ if edit.kind == "labeled_polyline" and edit.action == "update" and (edit.result_ref is not None or edit.candidate_result_ref is not None):
316
+ arguments["replace_from_result"] = True
317
+ if edit.kind in ANNOTATION_KINDS:
318
+ arguments["kind"] = edit.kind
319
+ arguments = {({"annotation_text": "text", "annotation_value": "value", "annotation_icon": "icon"}.get(k, k)): v
320
+ for k, v in arguments.items()}
321
+ if edit.kind in {"price_pattern", "nine_count"}:
322
+ arguments["kind"] = edit.kind
323
+ arguments.pop("result_ref", None)
324
+ arguments.pop("ta_result_ref", None)
325
+ for key in ("candidate_result_ref", "candidate_number", "user_confirmed_candidate"):
326
+ arguments.pop(key, None)
327
+ if edit.action == "create": arguments["request_id"] = context_ref + ":" + hashlib.sha256(request_id.encode()).hexdigest()
328
+ else: arguments[id_key] = edit.object_id
329
+ edited, obj = editor(payload, edit.action, **arguments)
330
+ # The new drawing candidate has its own guarded application proof.
331
+ # Do not misidentify it as the unchanged root browser-source token.
332
+ edited.pop("view_source_guard", None)
333
+ refreshed = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
334
+ # Includes viewport/selection/settings, not only instrument and candle range.
335
+ if refreshed["revision"] != expected_revision or any(refreshed[k] != context[k] for k in
336
+ ("symbol", "interval", "interval_value", "adjust", "range_key", "candles", "visible_range", "drawings", "selection", "indicators")):
337
+ raise LineError("chart_context_revision_conflict", "准备期间当前图发生变化,未发布修改。")
338
+ guard = {"protocol": "prepared-only-v1", **identity, "conversation_id": context["conversation_id"],
339
+ "view_id": context["view_id"], "request_id": request_id, "requires_live_apply": True}
340
+ edited.update(drawing_only=True, drawing_parent_session=chart_session, drawing_guard=guard)
341
+ entry = {"request_id": request_id, "revision": expected_revision, "fingerprint": fingerprint, "status": "preparing"}
342
+ entries.append(entry)
343
+ chart_service._atomic_runtime_json(journal, {"entries": entries})
344
+ try:
345
+ token, _ = (publish or chart_service.publish_chart)(edited)
346
+ result = {"ok": True, "scope": "guarded_preparation", "operation_status": "prepared",
347
+ "apply_status": "not_requested", "render_verified": False, "replayed": False,
348
+ "context_ref": context_ref, "expected_revision": expected_revision,
349
+ "conversation_id": context["conversation_id"], "view_id": context["view_id"],
350
+ "chart_session": token, "parent_chart_session": chart_session, "symbol": payload["symbol"],
351
+ "interval": payload["interval"], "request_id": request_id, "edit": {"kind": edit.kind, "action": edit.action},
352
+ "object": _public_edit_object(edit.kind, obj), "drawing_guard": guard,
353
+ "source_snapshot_alignment": "verified_for_preparation"}
354
+ entry.update(status="prepared", result=result)
355
+ chart_service._atomic_runtime_json(journal, {"entries": entries})
356
+ except Exception:
357
+ entry.pop("result", None); entry["status"] = "outcome_unknown"
358
+ try: chart_service._atomic_runtime_json(journal, {"entries": entries})
359
+ except Exception: pass # Durable preparing entry already prevents a duplicate retry.
360
+ raise LineError("chart_edit_outcome_unknown", "准备发布或记录失败,当前网页未修改;发布结果可能不确定,停止自动重试。") from None
361
+ return result
362
+ finally:
363
+ lock.unlink()