@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,260 @@
1
+ """Read-only, rule-based three-anchor channel candidates on loaded candles.
2
+
3
+ This module proposes geometry for human review. It neither publishes drawings
4
+ nor claims that a candidate is the uniquely correct technical-analysis channel.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from collections import Counter
9
+ import math
10
+ from statistics import median
11
+
12
+ from core.rows import RowsValidationError, validate_rows
13
+ from tools.lines import LineError
14
+ from tools.pivots import confirmed_pivots
15
+
16
+ RULE_VERSION = "confirmed_pivots_v3"
17
+ MIN_TOTAL_MOVE_FRACTION = 0.03
18
+ MAX_EXCESS_TO_WIDTH = 0.25
19
+ MAX_OUTSIDE_BAR_FRACTION = 0.20
20
+ MAX_WIDTH_FRACTION = 0.12
21
+ MAX_WIDTH_TO_BASE_MOVE = 2.0
22
+ MAX_CURRENT_END_AGE_BARS = 8
23
+ SAME_FAMILY_SLOPE_TOLERANCE = 0.10
24
+ SAME_FAMILY_WIDTH_TOLERANCE = 0.10
25
+
26
+
27
+ def _measure_region(rows, *, first, start_price, slope, width, direction, start, stop):
28
+ """Measure actual wicks against index-based edges, including any extension."""
29
+ maximum = 0.0
30
+ outside_count = 0
31
+ latest_close_position = None
32
+ for index in range(start, stop):
33
+ base = start_price + slope * (index - first)
34
+ upper, lower = (base + width, base) if direction == "ascending" else (base, base - width)
35
+ row = rows[index]
36
+ excess = max(0.0, row["high"] - upper, lower - row["low"])
37
+ if not all(math.isfinite(value) for value in (base, upper, lower, excess)) or lower <= 0:
38
+ return None
39
+ maximum = max(maximum, excess)
40
+ outside_count += excess > max(upper, lower) * 1e-12
41
+ tolerance = max(upper, lower) * 1e-12
42
+ latest_close_position = ("above_projected_upper" if row["close"] > upper + tolerance else
43
+ "below_projected_lower" if row["close"] < lower - tolerance else "inside")
44
+ return {"bar_count": stop - start, "outside_bar_count": outside_count,
45
+ "outside_bar_fraction": outside_count / (stop - start) if stop > start else 0.0,
46
+ "max_wick_excess_price": maximum, "max_wick_excess_to_width": maximum / width,
47
+ "latest_close_position": latest_close_position}
48
+
49
+
50
+ def _same_geometric_family(candidate, representative):
51
+ """Collapse near-identical alternatives built around the same parallel pivot."""
52
+ anchors, other = candidate["anchors"], representative["anchors"]
53
+ if (candidate["direction"] != representative["direction"]
54
+ or anchors["parallel"]["time"] != other["parallel"]["time"]):
55
+ return False
56
+ slope_scale = max(abs(candidate["slope_per_bar"]), abs(representative["slope_per_bar"]))
57
+ width_scale = max(candidate["width"], representative["width"])
58
+ return (abs(candidate["slope_per_bar"] - representative["slope_per_bar"])
59
+ <= SAME_FAMILY_SLOPE_TOLERANCE * slope_scale
60
+ and abs(candidate["width"] - representative["width"])
61
+ <= SAME_FAMILY_WIDTH_TOLERANCE * width_scale)
62
+
63
+
64
+ def channel_candidates(
65
+ rows,
66
+ *,
67
+ direction="both",
68
+ lookback_bars=120,
69
+ left_bars=2,
70
+ right_bars=2,
71
+ min_span_bars=12,
72
+ limit=3,
73
+ scope="current",
74
+ ):
75
+ """Propose channels from two confirmed same-side pivots and one opposite pivot.
76
+
77
+ Ascending channels use two rising pivot lows as the base and a pivot high
78
+ between them as the parallel anchor; descending channels are symmetric.
79
+ All coordinates are candle-index based, never elapsed-time or screen pixels.
80
+ The anchor interval is measured in full. Current proposals must have a
81
+ recent confirmed end pivot and pass an explicit arithmetic extension check
82
+ through the latest loaded bar. Historical proposals never infer a current
83
+ breakout. Neither scope confirms professional pattern quality.
84
+ """
85
+ if not isinstance(direction, str) or direction not in {"ascending", "descending", "both"}:
86
+ raise LineError("invalid_channel_candidate_direction", "direction 只能是 ascending、descending 或 both。")
87
+ if not isinstance(scope, str) or scope not in {"current", "historical"}:
88
+ raise LineError("invalid_channel_candidate_scope", "scope 只能是 current 或 historical。")
89
+ if type(lookback_bars) is not int or not 30 <= lookback_bars <= 300:
90
+ raise LineError("invalid_channel_candidate_lookback", "lookback_bars 必须是30至300的整数。")
91
+ if type(min_span_bars) is not int or not 10 <= min_span_bars <= 100 or min_span_bars >= lookback_bars:
92
+ raise LineError("invalid_channel_candidate_span", "min_span_bars 必须是10至100且小于 lookback_bars。")
93
+ if type(limit) is not int or not 1 <= limit <= 5:
94
+ raise LineError("invalid_channel_candidate_limit", "limit 必须是1至5的整数。")
95
+ if type(left_bars) is not int or not 1 <= left_bars <= 20 or type(right_bars) is not int or not 1 <= right_bars <= 20:
96
+ raise LineError("invalid_pivot_window", "left_bars 和 right_bars 必须是1至20的整数。")
97
+ # The pivot helper validates window parameters and does not use incomplete
98
+ # right-hand windows. Its 50-candidate cap bounds pair enumeration.
99
+ try:
100
+ candles = validate_rows(rows, min_len=max(min_span_bars + 1, left_bars + right_bars + 1))
101
+ except RowsValidationError:
102
+ raise LineError("insufficient_channel_candidate_history", "当前已加载K线不足以计算通道候选;未补取行情。") from None
103
+ selected = candles[-lookback_bars:]
104
+ if any(row["low"] <= 0 or row["high"] < max(row["open"], row["close"], row["low"])
105
+ or row["low"] > min(row["open"], row["close"]) for row in selected):
106
+ raise LineError("invalid_channel_candidate_data", "通道候选需要高低价为正且 OHLC 一致的K线;未忽略异常柱。")
107
+ pivot_result = confirmed_pivots(selected, left_bars=left_bars, right_bars=right_bars, limit=50)
108
+ index_by_time = {row["time"]: index for index, row in enumerate(selected)}
109
+ pivots = {side: [] for side in ("high", "low")}
110
+ for pivot in pivot_result["candidates"]:
111
+ pivots[pivot["side"]].append((index_by_time[int(pivot["time"])], pivot["price"]))
112
+
113
+ candidates = []
114
+ rejection_counts = Counter()
115
+ considered_anchor_pairs = 0
116
+ for trend in (("ascending", "low", "high"), ("descending", "high", "low")):
117
+ name, base_side, opposite_side = trend
118
+ if direction not in {"both", name}:
119
+ continue
120
+ base_pivots = pivots[base_side]
121
+ for first_pos, (first, start_price) in enumerate(base_pivots):
122
+ for last, end_price in base_pivots[first_pos + 1:]:
123
+ span = last - first
124
+ if span < min_span_bars:
125
+ continue
126
+ considered_anchor_pairs += 1
127
+ slope = (end_price - start_price) / span
128
+ move_fraction = abs(end_price - start_price) / start_price
129
+ if (name == "ascending" and slope <= 0) or (name == "descending" and slope >= 0):
130
+ rejection_counts["wrong_direction"] += 1
131
+ continue
132
+ if move_fraction < MIN_TOTAL_MOVE_FRACTION:
133
+ rejection_counts["weak_base_move"] += 1
134
+ continue
135
+ opposite = []
136
+ for index, price in pivots[opposite_side]:
137
+ if first < index < last:
138
+ base_at_pivot = start_price + slope * (index - first)
139
+ width = (price - base_at_pivot) * (1 if name == "ascending" else -1)
140
+ if math.isfinite(width) and width > 0:
141
+ opposite.append((width, index, price))
142
+ if not opposite:
143
+ rejection_counts["no_interior_opposite_pivot"] += 1
144
+ continue
145
+ # The widest confirmed opposite pivot makes the parallel edge;
146
+ # stable tie-breaking favors the earlier pivot.
147
+ width, parallel_index, parallel_price = max(opposite, key=lambda value: (value[0], -value[1]))
148
+ median_close = median(row["close"] for row in selected[first:last + 1])
149
+ width_fraction = width / median_close
150
+ width_to_base_move = width / abs(end_price - start_price)
151
+ if not math.isfinite(width_fraction) or width_fraction > MAX_WIDTH_FRACTION:
152
+ rejection_counts["too_wide_vs_price"] += 1
153
+ continue
154
+ if not math.isfinite(width_to_base_move) or width_to_base_move > MAX_WIDTH_TO_BASE_MOVE:
155
+ rejection_counts["too_wide_vs_base_move"] += 1
156
+ continue
157
+ anchor_measurement = _measure_region(selected, first=first, start_price=start_price,
158
+ slope=slope, width=width, direction=name, start=first, stop=last + 1)
159
+ if (anchor_measurement is None or
160
+ anchor_measurement["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH):
161
+ rejection_counts["anchor_interval_boundary_breach"] += 1
162
+ continue
163
+ if anchor_measurement["outside_bar_fraction"] > MAX_OUTSIDE_BAR_FRACTION:
164
+ rejection_counts["too_many_anchor_interval_breaches"] += 1
165
+ continue
166
+ age = len(selected) - 1 - last
167
+ if scope == "current" and age > MAX_CURRENT_END_AGE_BARS:
168
+ rejection_counts["end_anchor_too_old"] += 1
169
+ continue
170
+ post_end = {"evaluated": False, "reason": "historical_scope_no_current_inference"}
171
+ if scope == "current":
172
+ measured = _measure_region(selected, first=first, start_price=start_price,
173
+ slope=slope, width=width, direction=name, start=last + 1, stop=len(selected))
174
+ if measured is None:
175
+ rejection_counts["invalid_post_end_projection"] += 1
176
+ continue
177
+ if (measured["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH
178
+ or measured["latest_close_position"] != "inside"):
179
+ rejection_counts["post_end_boundary_breach"] += 1
180
+ continue
181
+ post_end = {"evaluated": True, "basis": "arithmetic_extension_not_pattern_confirmation",
182
+ **measured}
183
+ anchors = {
184
+ "from": {"time": selected[first]["time"], "price": start_price, "ohlc_field": base_side},
185
+ "to": {"time": selected[last]["time"], "price": end_price, "ohlc_field": base_side},
186
+ "parallel": {"time": selected[parallel_index]["time"], "price": parallel_price,
187
+ "ohlc_field": opposite_side},
188
+ }
189
+ candidates.append({
190
+ "direction": name,
191
+ "anchors": anchors,
192
+ "span_bars": span + 1,
193
+ "bars_since_end": age,
194
+ "slope_per_bar": slope,
195
+ "width": width,
196
+ "width_fraction_of_median_close": width_fraction,
197
+ "width_to_base_move": width_to_base_move,
198
+ "base_move_fraction": move_fraction,
199
+ "max_wick_excess_price": anchor_measurement["max_wick_excess_price"],
200
+ "max_wick_excess_to_width": anchor_measurement["max_wick_excess_to_width"],
201
+ "outside_bar_count": anchor_measurement["outside_bar_count"],
202
+ "outside_bar_fraction": anchor_measurement["outside_bar_fraction"],
203
+ "post_end": post_end,
204
+ "scope": scope,
205
+ "anchor_rule": "two_confirmed_same_side_pivots_plus_widest_interior_opposite_pivot",
206
+ "measurement_range": "anchor_interval_inclusive_post_end_separate",
207
+ "_end_index": last,
208
+ })
209
+ # Newer, more compact, less-violated candidates first. No opaque score.
210
+ candidates.sort(key=lambda item: (-item["_end_index"], item["max_wick_excess_to_width"],
211
+ item["width_to_base_move"], -item["span_bars"],
212
+ item["direction"], item["anchors"]["from"]["time"]))
213
+ qualified_before_dedup = len(candidates)
214
+ distinct = []
215
+ seen_families = set()
216
+ for candidate in candidates:
217
+ del candidate["_end_index"]
218
+ family = (candidate["direction"], candidate["anchors"]["to"]["time"],
219
+ candidate["anchors"]["parallel"]["time"])
220
+ if family in seen_families or any(_same_geometric_family(candidate, kept) for kept in distinct):
221
+ continue
222
+ seen_families.add(family)
223
+ distinct.append(candidate)
224
+ return {
225
+ "rule_version": RULE_VERSION,
226
+ "direction": direction,
227
+ "scope": scope,
228
+ "lookback_bars": lookback_bars,
229
+ "left_bars": left_bars,
230
+ "right_bars": right_bars,
231
+ "min_span_bars": min_span_bars,
232
+ "considered_anchor_pairs": considered_anchor_pairs,
233
+ "rejection_counts": dict(sorted(rejection_counts.items())),
234
+ "qualified_before_dedup": qualified_before_dedup,
235
+ "deduplicated_count": qualified_before_dedup - len(distinct),
236
+ "candidate_count": len(distinct),
237
+ "returned": min(limit, len(distinct)),
238
+ "truncated": len(distinct) > limit,
239
+ "no_candidate_reason": "no_anchor_triple_passed_rules" if not distinct else None,
240
+ "no_candidate_explanation": ("没有三锚点组合同时满足全部筛选规则;不能据此推断近期没有已确认拐点,或真实走势不存在通道。"
241
+ if not distinct else None),
242
+ "pivot_scan": {"considered": pivot_result["candidate_count"],
243
+ "total": pivot_result["total_candidates"], "truncated": pivot_result["truncated"],
244
+ "recent_confirmed_high_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
245
+ for index, _ in pivots["high"]),
246
+ "recent_confirmed_low_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
247
+ for index, _ in pivots["low"])},
248
+ "candidates": distinct[:limit],
249
+ "thresholds": {"min_total_move_fraction": MIN_TOTAL_MOVE_FRACTION,
250
+ "max_wick_excess_to_width": MAX_EXCESS_TO_WIDTH,
251
+ "max_outside_bar_fraction": MAX_OUTSIDE_BAR_FRACTION,
252
+ "max_width_fraction_of_median_close": MAX_WIDTH_FRACTION,
253
+ "max_width_to_base_move": MAX_WIDTH_TO_BASE_MOVE,
254
+ "max_current_end_age_bars": MAX_CURRENT_END_AGE_BARS,
255
+ "same_family_slope_tolerance": SAME_FAMILY_SLOPE_TOLERANCE,
256
+ "same_family_width_tolerance": SAME_FAMILY_WIDTH_TOLERANCE},
257
+ "limitations": ["geometry_only_requires_result_review", "confirmed_pivots_lag_right_bars",
258
+ "arithmetic_extension_not_breakout_confirmation", "no_drawing_created"],
259
+ "drawing_created": False,
260
+ }
@@ -0,0 +1,82 @@
1
+ """Read-only arithmetic for a host-chosen channel, not fitting or recognition."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime
5
+ import math
6
+ from typing import Any
7
+
8
+ from tools.channels import channel_geometry
9
+ from tools.lines import LineError, validate_line_fields
10
+ from tools.trend_lines import CN_TZ, resolve_anchor_time
11
+
12
+
13
+ def preview_channel(rows: list[dict], interval: str, *, start_time: str, start_price: float,
14
+ end_time: str, end_price: float, parallel_time: str, parallel_price: float,
15
+ bar_limit: int = 200) -> dict[str, Any]:
16
+ """Rows have already passed live-observation validation; never fetch or publish."""
17
+ if isinstance(bar_limit, bool) or not isinstance(bar_limit, int) or not 1 <= bar_limit <= 4000:
18
+ raise LineError("invalid_preview_limit", "bar_limit 为1至4000整数;汇总始终核对完整起止区间。")
19
+ source = {"interval": interval, "chartCommands": [{"type": "SET_CANDLES", "rows": rows}]}
20
+ anchors = []
21
+ for timestamp, price in ((start_time, start_price), (end_time, end_price), (parallel_time, parallel_price)):
22
+ price, _, _ = validate_line_fields(price=price)
23
+ if price is None:
24
+ raise LineError("invalid_price", "三个锚点都需要明确的有限正价格。")
25
+ anchors.append({"time": resolve_anchor_time(source, timestamp), "price": price})
26
+ start, end, parallel = anchors
27
+ geometry = channel_geometry(source, start, end, parallel)
28
+ region = [row for row in rows if start["time"] <= row["time"] <= end["time"]]
29
+ if len(region) > 4000:
30
+ raise LineError("measurement_capacity", "通道核对区间超过4000根;未使用截断样本代替全区间。")
31
+ # Only numerical roundoff, not a subjective touch/fitting tolerance. Keep
32
+ # signed raw distances unrounded and expose the allowance used by counts.
33
+ scale = max(*(a["price"] for edge in ("upper", "lower") for a in geometry[edge].values()),
34
+ *(row[field] for row in region for field in ("low", "high")))
35
+ epsilon = scale * 1e-12
36
+ measured = []
37
+ for index, row in enumerate(region):
38
+ upper = geometry["upper"]["from"]["price"] + geometry["slope_per_bar"] * index
39
+ lower = geometry["lower"]["from"]["price"] + geometry["slope_per_bar"] * index
40
+ values = {"high_minus_upper": row["high"] - upper, "low_minus_lower": row["low"] - lower,
41
+ "body_high_minus_upper": max(row["open"], row["close"]) - upper,
42
+ "body_low_minus_lower": min(row["open"], row["close"]) - lower}
43
+ if not all(math.isfinite(v) for v in (upper, lower, *values.values())):
44
+ raise LineError("nonfinite_channel_measurement", "通道偏差计算超出有限数值范围,未输出部分核对结果。")
45
+ try:
46
+ instant = datetime.fromtimestamp(row["time"], CN_TZ)
47
+ date, iso = instant.date().isoformat(), instant.isoformat(timespec="seconds")
48
+ except (ValueError, OverflowError, OSError):
49
+ date, iso = None, None
50
+ measured.append({"time": row["time"], "date": date, "iso": iso,
51
+ "bar_offset": index, "upper_price": upper, "lower_price": lower,
52
+ "ohlc": {k: row[k] for k in ("open", "high", "low", "close")}, **values})
53
+ summary = {}
54
+ for key, field, sign in (("wick_above", "high_minus_upper", 1), ("wick_below", "low_minus_lower", -1),
55
+ ("body_above", "body_high_minus_upper", 1), ("body_below", "body_low_minus_lower", -1)):
56
+ distances = [bar[field] * sign for bar in measured]
57
+ maximum = max(distances)
58
+ witness = measured[distances.index(maximum)]
59
+ summary[key] = {"bar_count": sum(d > epsilon for d in distances),
60
+ "max_price_excess": max(0, maximum),
61
+ "max_excess_witness": {k: witness[k] for k in ("time", "date", "iso", "bar_offset")}
62
+ if maximum > epsilon else None}
63
+ provenance = []
64
+ by_time = {r["time"]: r for r in region}
65
+ for anchor in anchors:
66
+ row = by_time[anchor["time"]]
67
+ provenance.append({**anchor, "exact_matching_ohlc_fields": [k for k in ("open", "high", "low", "close")
68
+ if row[k] == anchor["price"]],
69
+ "price_origin": "caller_supplied_not_selected_by_plugin"})
70
+ return {"schema_version": 1, "evidence_scope": "loaded_browser_candles",
71
+ "range_policy": "inclusive_start_end_only_no_extension", "bar_count": len(region),
72
+ "anchors": dict(zip(("from", "to", "parallel"), provenance)), "geometry": geometry,
73
+ "numeric_policy": {"arithmetic": "float64_unrounded_signed_distances",
74
+ "count_roundoff_allowance": epsilon, "allowance_basis": "max_boundary_and_region_wick_price_times_1e-12",
75
+ "meaning": "numerical_roundoff_only_not_market_touch_tolerance"},
76
+ "distance_convention": "positive high_minus_upper is above; negative low_minus_lower is below; body fields use open/close extrema",
77
+ "summary": summary, "bars": measured[:bar_limit],
78
+ "bar_selection": {"total": len(measured), "returned": min(bar_limit, len(measured)),
79
+ "truncated": len(measured) > bar_limit, "order": "ascending", "sample": "first_limit",
80
+ "summary_scope": "full_inclusive_region"},
81
+ "pattern_classification": "not_provided", "touch_count": "not_provided",
82
+ "quality_score": "not_provided", "drawing_created": False, "render_verified": False}
@@ -0,0 +1,104 @@
1
+ """Three-anchor, finite parallel price channels on the chart's candle-index axis."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import math
7
+ import secrets
8
+ from typing import Any
9
+
10
+ from tools.lines import LineError, validate_line_fields
11
+ from tools.trend_lines import resolve_anchor_time
12
+
13
+ CHANNEL_COMMAND = "DRAW_AGENT_CHANNEL"
14
+ MAX_CHANNELS = 30
15
+
16
+
17
+ def channels(payload: dict[str, Any]) -> list[dict[str, Any]]:
18
+ return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == CHANNEL_COMMAND])
19
+
20
+
21
+ def channel_geometry(payload: dict[str, Any], start: dict, end: dict, parallel: dict) -> dict[str, Any]:
22
+ rows = next((c.get("rows", []) for c in payload.get("chartCommands", []) if c.get("type") == "SET_CANDLES"), [])
23
+ times = [r["time"] for r in rows]
24
+ if any(times.count(a["time"]) != 1 for a in (start, end, parallel)) or any(a >= b for a, b in zip(times, times[1:])):
25
+ raise LineError("invalid_channel_rows", "通道需要唯一、按时间递增的 K 线锚点。")
26
+ if start["time"] >= end["time"]:
27
+ raise LineError("invalid_anchor_order", "通道起点必须早于终点,未自动交换锚点。")
28
+ if not start["time"] <= parallel["time"] <= end["time"]:
29
+ raise LineError("parallel_anchor_outside", "第三点必须位于起止时间范围内;请明确指定,不自动挪动。")
30
+ i, j, k = (times.index(a["time"]) for a in (start, end, parallel))
31
+ # Candles are equally spaced on screen, even across weekends/holidays.
32
+ slope = (end["price"] - start["price"]) / (j - i)
33
+ offset = parallel["price"] - (start["price"] + slope * (k - i))
34
+ tolerance = max(start["price"], end["price"], parallel["price"]) * 1e-12
35
+ if not math.isfinite(offset) or abs(offset) <= tolerance:
36
+ raise LineError("zero_channel_width", "第三点落在基准线上,不能形成有宽度的通道。")
37
+ other = {"from": {"time": start["time"], "price": start["price"] + offset},
38
+ "to": {"time": end["time"], "price": end["price"] + offset}}
39
+ if any(not math.isfinite(a["price"]) or a["price"] <= 0 for a in other.values()):
40
+ raise LineError("invalid_channel_boundary", "推导后的平行边界价格必须大于零且有限,请调整第三点。")
41
+ base = {"from": deepcopy(start), "to": deepcopy(end)}
42
+ upper, lower = (other, base) if offset > 0 else (base, other)
43
+ return {"upper": upper, "lower": lower, "width": abs(offset), "signed_offset": offset,
44
+ "slope_per_bar": slope, "direction": "ascending" if slope > 0 else "descending" if slope < 0 else "horizontal",
45
+ "geometry_basis": "candle_index_linear_price"}
46
+
47
+
48
+ def edit_channel(
49
+ payload: dict[str, Any], action: str, *, channel_id: str | None = None,
50
+ start_time: str | None = None, start_price: float | None = None,
51
+ end_time: str | None = None, end_price: float | None = None,
52
+ parallel_time: str | None = None, parallel_price: float | None = None,
53
+ name: str | None = None, color: str | None = None,
54
+ show_midline: bool | None = None, request_id: str | None = None,
55
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
56
+ result = deepcopy(payload)
57
+ commands = result.get("chartCommands", [])
58
+ previous = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("id") == channel_id), None)
59
+ if action in {"update", "delete"} and previous is None:
60
+ raise LineError("channel_not_found", "当前快照不存在该 AI 通道,请先读取通道 ID。")
61
+ if action == "delete":
62
+ commands.remove(previous); result["chartCommands"] = commands
63
+ return result, deepcopy(previous)
64
+ if action not in {"create", "update"}:
65
+ raise LineError("invalid_action", "不支持的通道操作。")
66
+ values = (start_time, start_price, end_time, end_price, parallel_time, parallel_price)
67
+ if action == "create" and any(v is None for v in values):
68
+ raise LineError("missing_anchor", "创建通道需要基准线两点及第三个平行边界锚点,每点明确时间和价格。")
69
+ if action == "update" and all(v is None for v in (*values, name, color, show_midline)):
70
+ raise LineError("empty_update", "请至少修改一个锚点、名称、颜色或中线开关。")
71
+ if show_midline is not None and not isinstance(show_midline, bool):
72
+ raise LineError("invalid_midline", "show_midline 必须是布尔值。")
73
+ _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
74
+ anchors = []
75
+ for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price), ("parallel", parallel_time, parallel_price)):
76
+ old = previous.get(key, {}) if previous else {}
77
+ value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
78
+ anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
79
+ start, end, parallel = anchors
80
+ geometry = channel_geometry(payload, start, end, parallel)
81
+ channel = {"type": CHANNEL_COMMAND, "id": previous["id"] if previous else "channel_" + secrets.token_hex(12),
82
+ "interval": payload.get("interval"), "from": start, "to": end, "parallel": parallel,
83
+ "label": name if name is not None else previous["label"] if previous else "",
84
+ "color": color if color is not None else previous["color"] if previous else "info",
85
+ "show_midline": show_midline if show_midline is not None else previous["show_midline"] if previous else True,
86
+ **geometry}
87
+ if previous and previous.get("create_request_id"):
88
+ channel["create_request_id"] = previous["create_request_id"]
89
+ if action == "create":
90
+ if request_id:
91
+ channel["create_request_id"] = request_id
92
+ channel["id"] = "channel_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
93
+ retry = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("create_request_id") == request_id), None)
94
+ if retry:
95
+ if any(retry.get(k) != channel[k] for k in ("from", "to", "parallel", "label", "color", "show_midline")):
96
+ raise LineError("request_conflict", "同一 request_id 的通道参数不同,请使用新的 request_id。")
97
+ return result, deepcopy(retry)
98
+ if len(channels(result)) >= MAX_CHANNELS:
99
+ raise LineError("too_many_channels", "当前图表最多保存 30 个 AI 通道。")
100
+ commands.append(channel)
101
+ else:
102
+ commands[commands.index(previous)] = channel
103
+ result["chartCommands"] = commands
104
+ return result, deepcopy(channel)