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

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 (211) hide show
  1. package/CHANGELOG.md +611 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.md +13 -0
  4. package/README.en.md +171 -0
  5. package/README.md +170 -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 +77 -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.11.md +21 -0
  50. package/docs/release-acceptance-v0.6.2.md +31 -0
  51. package/docs/release-acceptance-v0.6.3.md +25 -0
  52. package/docs/release-acceptance-v0.6.4.md +24 -0
  53. package/docs/release-acceptance-v0.6.5.md +21 -0
  54. package/docs/release-acceptance-v0.6.6.md +21 -0
  55. package/docs/release-acceptance-v0.6.7.md +18 -0
  56. package/docs/release-acceptance-v0.6.8.md +18 -0
  57. package/docs/release-acceptance-v0.6.9.md +98 -0
  58. package/docs/release-notes-v0.5.0.md +23 -0
  59. package/docs/release-notes-v0.6.0.md +11 -0
  60. package/docs/release-notes-v0.6.1.md +20 -0
  61. package/docs/release-notes-v0.6.10.md +11 -0
  62. package/docs/release-notes-v0.6.11.md +16 -0
  63. package/docs/release-notes-v0.6.2.md +14 -0
  64. package/docs/release-notes-v0.6.3.md +26 -0
  65. package/docs/release-notes-v0.6.4.md +12 -0
  66. package/docs/release-notes-v0.6.5.md +13 -0
  67. package/docs/release-notes-v0.6.6.md +13 -0
  68. package/docs/release-notes-v0.6.7.md +17 -0
  69. package/docs/release-notes-v0.6.8.md +10 -0
  70. package/docs/release-notes-v0.6.9.md +16 -0
  71. package/lib/candle-sequence.js +15 -0
  72. package/lib/chart-adjustment.js +7 -0
  73. package/lib/chart-annotations.js +33 -0
  74. package/lib/chart-applications.js +171 -0
  75. package/lib/chart-context.js +164 -0
  76. package/lib/chart-observation.js +251 -0
  77. package/lib/chart-service-status.js +82 -0
  78. package/lib/chart-source-status.js +39 -0
  79. package/lib/chart-sources.js +354 -0
  80. package/lib/client/BetterSidebarTab.js +70 -0
  81. package/lib/client/ClassicShell.js +254 -0
  82. package/lib/client/KlineContent.js +155 -0
  83. package/lib/client/PanelHost.js +46 -0
  84. package/lib/client/chart-apply.js +73 -0
  85. package/lib/client/chart-context.js +233 -0
  86. package/lib/client/chart-handoff.js +34 -0
  87. package/lib/client/chart-session-resolver.js +74 -0
  88. package/lib/client/client-context.js +1 -0
  89. package/lib/client/conversation.js +88 -0
  90. package/lib/client/default-tab.js +83 -0
  91. package/lib/client/embed.js +50 -0
  92. package/lib/client/generated-view.js +12983 -0
  93. package/lib/client/horizontal-lines.js +19 -0
  94. package/lib/client/host-options.js +41 -0
  95. package/lib/client/host-panels.js +111 -0
  96. package/lib/client/index.js +77 -0
  97. package/lib/client/mode-preferences.js +48 -0
  98. package/lib/client/native-sidebar-contract.js +45 -0
  99. package/lib/client/native-sidebar-register.js +133 -0
  100. package/lib/client/native-sidebar-services.js +1 -0
  101. package/lib/client/native-sidebar.js +98 -0
  102. package/lib/client/sidebar-integration.js +93 -0
  103. package/lib/client/ui-onboarding.js +48 -0
  104. package/lib/client/version.js +14 -0
  105. package/lib/client.js +17581 -0
  106. package/lib/client.js.map +1 -0
  107. package/lib/drawing-feedback.js +284 -0
  108. package/lib/fibonacci.js +18 -0
  109. package/lib/ftshare-settings-bridge.js +159 -0
  110. package/lib/index.js +279 -0
  111. package/lib/labeled-polyline.js +17 -0
  112. package/lib/pattern-groups.js +91 -0
  113. package/lib/price-bands.js +55 -0
  114. package/lib/price-series.js +47 -0
  115. package/lib/price-sticks.js +32 -0
  116. package/lib/types/candle-sequence.d.ts +2 -0
  117. package/lib/types/chart-adjustment.d.ts +2 -0
  118. package/lib/types/chart-annotations.d.ts +4 -0
  119. package/lib/types/chart-applications.d.ts +26 -0
  120. package/lib/types/chart-context.d.ts +14 -0
  121. package/lib/types/chart-observation.d.ts +8 -0
  122. package/lib/types/chart-service-status.d.ts +22 -0
  123. package/lib/types/chart-source-status.d.ts +47 -0
  124. package/lib/types/chart-sources.d.ts +25 -0
  125. package/lib/types/client/BetterSidebarTab.d.ts +12 -0
  126. package/lib/types/client/ClassicShell.d.ts +4 -0
  127. package/lib/types/client/KlineContent.d.ts +37 -0
  128. package/lib/types/client/PanelHost.d.ts +25 -0
  129. package/lib/types/client/chart-apply.d.ts +13 -0
  130. package/lib/types/client/chart-context.d.ts +23 -0
  131. package/lib/types/client/chart-handoff.d.ts +5 -0
  132. package/lib/types/client/chart-session-resolver.d.ts +2 -0
  133. package/lib/types/client/client-context.d.ts +16 -0
  134. package/lib/types/client/conversation.d.ts +43 -0
  135. package/lib/types/client/default-tab.d.ts +3 -0
  136. package/lib/types/client/embed.d.ts +37 -0
  137. package/lib/types/client/generated-view.d.ts +2 -0
  138. package/lib/types/client/horizontal-lines.d.ts +1 -0
  139. package/lib/types/client/host-options.d.ts +38 -0
  140. package/lib/types/client/host-panels.d.ts +55 -0
  141. package/lib/types/client/index.d.ts +4 -0
  142. package/lib/types/client/mode-preferences.d.ts +25 -0
  143. package/lib/types/client/native-sidebar-contract.d.ts +52 -0
  144. package/lib/types/client/native-sidebar-register.d.ts +46 -0
  145. package/lib/types/client/native-sidebar-services.d.ts +45 -0
  146. package/lib/types/client/native-sidebar.d.ts +47 -0
  147. package/lib/types/client/sidebar-integration.d.ts +12 -0
  148. package/lib/types/client/ui-onboarding.d.ts +7 -0
  149. package/lib/types/client/version.d.ts +1 -0
  150. package/lib/types/drawing-feedback.d.ts +5 -0
  151. package/lib/types/fibonacci.d.ts +5 -0
  152. package/lib/types/ftshare-settings-bridge.d.ts +50 -0
  153. package/lib/types/index.d.ts +26 -0
  154. package/lib/types/labeled-polyline.d.ts +11 -0
  155. package/lib/types/pattern-groups.d.ts +2 -0
  156. package/lib/types/price-bands.d.ts +3 -0
  157. package/lib/types/price-series.d.ts +5 -0
  158. package/lib/types/price-sticks.d.ts +3 -0
  159. package/package.json +155 -4
  160. package/requirements.txt +6 -0
  161. package/screenshots.json +8 -0
  162. package/scripts/bootstrap.sh +5 -0
  163. package/scripts/dsh-bootstrap.mjs +179 -0
  164. package/scripts/dsh-mcp-plugin.mjs +27 -0
  165. package/scripts/run-dsh-kline.mjs +658 -0
  166. package/scripts/run-dsh-kline.sh +5 -0
  167. package/server.py +1755 -0
  168. package/tools/__init__.py +0 -0
  169. package/tools/annotations.py +119 -0
  170. package/tools/automatic_analysis.py +158 -0
  171. package/tools/baostock_source.py +176 -0
  172. package/tools/calc.py +39 -0
  173. package/tools/channel_candidates.py +260 -0
  174. package/tools/channel_preview.py +82 -0
  175. package/tools/channels.py +104 -0
  176. package/tools/chart_applications.py +204 -0
  177. package/tools/chart_context.py +186 -0
  178. package/tools/chart_edits.py +363 -0
  179. package/tools/chart_functions.py +451 -0
  180. package/tools/chart_indicators.py +65 -0
  181. package/tools/chart_measurements.py +84 -0
  182. package/tools/chart_source_status.py +32 -0
  183. package/tools/chart_sources.py +31 -0
  184. package/tools/closed_daily.py +68 -0
  185. package/tools/draw.py +410 -0
  186. package/tools/drawing_feedback.py +45 -0
  187. package/tools/drawing_interaction.py +117 -0
  188. package/tools/drawing_verification.py +141 -0
  189. package/tools/fetch.py +4680 -0
  190. package/tools/fibonacci.py +83 -0
  191. package/tools/foreign_daily.py +185 -0
  192. package/tools/free_sources.py +483 -0
  193. package/tools/lines.py +91 -0
  194. package/tools/nine_count.py +66 -0
  195. package/tools/pattern_groups.py +103 -0
  196. package/tools/pivots.py +60 -0
  197. package/tools/polylines.py +131 -0
  198. package/tools/price_bands.py +165 -0
  199. package/tools/price_patterns.py +311 -0
  200. package/tools/price_series.py +162 -0
  201. package/tools/price_sticks.py +114 -0
  202. package/tools/range_candidates.py +170 -0
  203. package/tools/recent_drawing_candidates.py +123 -0
  204. package/tools/rectangles.py +76 -0
  205. package/tools/regression_channels.py +87 -0
  206. package/tools/ta_functions.py +228 -0
  207. package/tools/trend_lines.py +106 -0
  208. package/tools/watchlist.py +149 -0
  209. package/view/ft-logo.jpg +0 -0
  210. package/view/kline.html +12436 -0
  211. package/view/vendor/klinecharts.min.js +7 -0
@@ -0,0 +1,170 @@
1
+ """Read-only candidates for a *current* horizontal trading range.
2
+
3
+ This is a bounded geometry heuristic, not a breakout signal or a professional
4
+ pattern verdict. It is deliberately separate from the guarded rectangle editor.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from statistics import median
10
+
11
+ from core.rows import RowsValidationError, validate_rows
12
+ from tools.lines import LineError
13
+
14
+ RULE_VERSION = "current_range_wick_envelope_v1"
15
+ DEFAULT_WINDOW_SIZES = (20, 30, 40, 60)
16
+ MIN_WIDTH_FRACTION = 0.005
17
+ MAX_WIDTH_FRACTION = 0.12
18
+ TOUCH_DISTANCE_TO_WIDTH = 0.10
19
+ MIN_TOUCH_SEPARATION_BARS = 3
20
+ MAX_CLOSE_DRIFT_TO_WIDTH = 0.50
21
+ MAX_FITTED_DRIFT_TO_WIDTH = 0.50
22
+ RECENT_BARS = 10
23
+ MAX_RECENT_DRIFT_TO_WIDTH = 0.50
24
+
25
+
26
+ def _separated_touch_indexes(indexes):
27
+ kept = []
28
+ for index in indexes:
29
+ if not kept or index - kept[-1] >= MIN_TOUCH_SEPARATION_BARS:
30
+ kept.append(index)
31
+ return kept
32
+
33
+
34
+ def _fitted_drift_to_width(closes, width):
35
+ count = len(closes)
36
+ x_mean = (count - 1) / 2
37
+ y_mean = math.fsum(closes) / count
38
+ denominator = math.fsum((index - x_mean) ** 2 for index in range(count))
39
+ slope = math.fsum((index - x_mean) * (price - y_mean)
40
+ for index, price in enumerate(closes)) / denominator
41
+ return abs(slope * (count - 1)) / width
42
+
43
+
44
+ def range_candidates(rows, *, window_sizes=DEFAULT_WINDOW_SIZES, limit=3):
45
+ """Return up to ``limit`` boxed-range proposals ending at the latest bar.
46
+
47
+ Candidate edges are the actual highest high and lowest low of each fixed
48
+ window. Both edges need at least two separated wick touches; a narrow band
49
+ alone is insufficient. Close drift and fitted close slope must each use no
50
+ more than half the band width, both across the full window and the recent
51
+ ten-bar tail. No projection or chart mutation occurs.
52
+ """
53
+ if (not isinstance(window_sizes, (tuple, list)) or not window_sizes
54
+ or len(window_sizes) > 8 or any(type(size) is not int or not 16 <= size <= 120 for size in window_sizes)
55
+ or len(set(window_sizes)) != len(window_sizes)):
56
+ raise LineError("invalid_range_candidate_windows", "window_sizes 必须是1至8个互异的16至120整数。")
57
+ if type(limit) is not int or not 1 <= limit <= 5:
58
+ raise LineError("invalid_range_candidate_limit", "limit 必须是1至5的整数。")
59
+ windows = tuple(sorted(window_sizes))
60
+ try:
61
+ candles = validate_rows(rows, min_len=min(windows))
62
+ except RowsValidationError:
63
+ raise LineError("insufficient_range_candidate_history", "已加载K线不足以计算平台区间候选;未补取行情。") from None
64
+ # A corrupt candle must not become an envelope boundary or a fake touch.
65
+ recent = candles[-max(windows):]
66
+ if any(row["low"] <= 0 or row["high"] < max(row["open"], row["close"], row["low"])
67
+ or row["low"] > min(row["open"], row["close"]) for row in recent):
68
+ raise LineError("invalid_range_candidate_data", "平台候选需要高低价为正且 OHLC 一致的K线;未忽略异常柱。")
69
+
70
+ candidates = []
71
+ evaluated_windows = []
72
+ for size in windows:
73
+ if size > len(candles):
74
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "insufficient_history"})
75
+ continue
76
+ segment = candles[-size:]
77
+ high_index = max(range(size), key=lambda index: segment[index]["high"])
78
+ low_index = min(range(size), key=lambda index: segment[index]["low"])
79
+ upper = segment[high_index]["high"]
80
+ lower = segment[low_index]["low"]
81
+ width = upper - lower
82
+ center = median(row["close"] for row in segment)
83
+ if not math.isfinite(width) or width <= 0 or center <= 0:
84
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "invalid_width"})
85
+ continue
86
+ width_fraction = width / center
87
+ if not MIN_WIDTH_FRACTION <= width_fraction <= MAX_WIDTH_FRACTION:
88
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "width_fraction_outside"})
89
+ continue
90
+ upper_touches = _separated_touch_indexes([
91
+ index for index, row in enumerate(segment)
92
+ if upper - row["high"] <= width * TOUCH_DISTANCE_TO_WIDTH
93
+ ])
94
+ lower_touches = _separated_touch_indexes([
95
+ index for index, row in enumerate(segment)
96
+ if row["low"] - lower <= width * TOUCH_DISTANCE_TO_WIDTH
97
+ ])
98
+ if len(upper_touches) < 2 or len(lower_touches) < 2:
99
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "insufficient_edge_touches"})
100
+ continue
101
+ closes = [row["close"] for row in segment]
102
+ close_drift = abs(closes[-1] - closes[0]) / width
103
+ fitted_drift = _fitted_drift_to_width(closes, width)
104
+ recent_closes = closes[-min(RECENT_BARS, size // 2):]
105
+ recent_close_drift = abs(recent_closes[-1] - recent_closes[0]) / width
106
+ recent_fitted_drift = _fitted_drift_to_width(recent_closes, width)
107
+ if not all(math.isfinite(value) for value in (close_drift, fitted_drift,
108
+ recent_close_drift, recent_fitted_drift)):
109
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "nonfinite_drift"})
110
+ continue
111
+ if close_drift > MAX_CLOSE_DRIFT_TO_WIDTH or fitted_drift > MAX_FITTED_DRIFT_TO_WIDTH:
112
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "full_window_drift"})
113
+ continue
114
+ if (recent_close_drift > MAX_RECENT_DRIFT_TO_WIDTH
115
+ or recent_fitted_drift > MAX_RECENT_DRIFT_TO_WIDTH):
116
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "recent_directional_move"})
117
+ continue
118
+ evaluated_windows.append({"window_bars": size, "accepted": True, "reason": None})
119
+ candidates.append({
120
+ "start_time": segment[0]["time"], "end_time": segment[-1]["time"],
121
+ "lower_price": lower, "upper_price": upper, "bar_count": size,
122
+ "upper_source_time": segment[high_index]["time"],
123
+ "lower_source_time": segment[low_index]["time"],
124
+ "width_fraction_of_median_close": width_fraction,
125
+ "upper_touch_count": len(upper_touches), "lower_touch_count": len(lower_touches),
126
+ "upper_touch_times": [segment[index]["time"] for index in upper_touches],
127
+ "lower_touch_times": [segment[index]["time"] for index in lower_touches],
128
+ "close_drift_to_width": close_drift, "fitted_close_drift_to_width": fitted_drift,
129
+ "recent_close_drift_to_width": recent_close_drift,
130
+ "recent_fitted_close_drift_to_width": recent_fitted_drift,
131
+ "boundary_rule": "full_window_max_high_min_low",
132
+ "status": "geometry_candidate_requires_review",
133
+ })
134
+ # Prefer more repeated boundary contact, flatter closes, then longer spans.
135
+ candidates.sort(key=lambda item: (-(item["upper_touch_count"] + item["lower_touch_count"]),
136
+ item["fitted_close_drift_to_width"], -item["bar_count"]))
137
+ # Overlapping windows often describe the exact same price box. Present one
138
+ # representative instead of spending the result limit on duplicate geometry.
139
+ unique_candidates = []
140
+ seen_boundaries = set()
141
+ for candidate in candidates:
142
+ boundaries = (candidate["lower_price"], candidate["upper_price"], candidate["end_time"])
143
+ if boundaries in seen_boundaries:
144
+ continue
145
+ seen_boundaries.add(boundaries)
146
+ unique_candidates.append(candidate)
147
+ return {
148
+ "rule_version": RULE_VERSION,
149
+ "window_sizes": list(windows),
150
+ "end_policy": "latest_loaded_bar_only",
151
+ "candidate_count": len(unique_candidates), "returned": min(limit, len(unique_candidates)),
152
+ "truncated": len(unique_candidates) > limit,
153
+ "duplicates_suppressed": len(candidates) - len(unique_candidates),
154
+ "no_candidate_reason": "no_window_passed_rules" if not unique_candidates else None,
155
+ "evaluated_windows": evaluated_windows,
156
+ "candidates": unique_candidates[:limit],
157
+ "thresholds": {
158
+ "width_fraction_of_median_close": [MIN_WIDTH_FRACTION, MAX_WIDTH_FRACTION],
159
+ "touch_distance_to_width": TOUCH_DISTANCE_TO_WIDTH,
160
+ "minimum_separated_touches_per_edge": 2,
161
+ "minimum_touch_separation_bars": MIN_TOUCH_SEPARATION_BARS,
162
+ "maximum_close_drift_to_width": MAX_CLOSE_DRIFT_TO_WIDTH,
163
+ "maximum_fitted_close_drift_to_width": MAX_FITTED_DRIFT_TO_WIDTH,
164
+ "recent_bars": RECENT_BARS,
165
+ "maximum_recent_drift_to_width": MAX_RECENT_DRIFT_TO_WIDTH,
166
+ },
167
+ "limitations": ["current_window_only", "geometry_only_requires_result_review",
168
+ "no_breakout_signal", "no_drawing_created"],
169
+ "drawing_created": False,
170
+ }
@@ -0,0 +1,123 @@
1
+ """Recent, confirmed daily anchors for ordinary drawing tools.
2
+
3
+ These are geometric suggestions, not wave labels or trading signals. A direct
4
+ drawing request permits the host to choose the newest suitable result and
5
+ continue through the guarded chart edit; analysis-only requests do not.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import numpy as np
12
+ import talib
13
+
14
+ from tools.closed_daily import closed_daily
15
+ from tools.lines import LineError
16
+ from tools.pivots import confirmed_pivots
17
+
18
+ RULE_VERSION = "recent_drawing_v2"
19
+ TYPES = {"horizontal", "trend", "fibonacci", "abc"}
20
+
21
+
22
+ def recent_drawing_candidates(rows, *, symbol: str, provider: str | None,
23
+ interval: str = "day", source_interval: str | None = "day",
24
+ interval_value: int | None = 1, drawing_type: str,
25
+ lookback_bars: int = 120, max_candidates: int = 5, now=None):
26
+ if drawing_type not in TYPES:
27
+ raise LineError("unsupported_auto_drawing", "该绘图类型没有自动选点规则。")
28
+ if type(lookback_bars) is not int or not 30 <= lookback_bars <= 300:
29
+ raise LineError("invalid_auto_drawing_range", "自动选点观察范围须为30至300根日线。")
30
+ if type(max_candidates) is not int or not 1 <= max_candidates <= 5:
31
+ raise LineError("invalid_auto_drawing_limit", "自动选点最多返回1至5个候选。")
32
+ closed, quality = closed_daily(rows, symbol=symbol, provider=provider, interval=interval,
33
+ source_interval=source_interval, interval_value=interval_value, now=now)
34
+ if quality["market"] is None:
35
+ raise LineError("unsupported_auto_drawing_market", "自动选点仅支持 A/港/美股日线;仍可手动绘图。")
36
+ window = closed[-min(4000, lookback_bars):]
37
+ if len(window) < 35:
38
+ raise LineError("insufficient_auto_drawing_history", "自动选点需要至少35根已收盘日线;仍可手动绘图。")
39
+ pivots = confirmed_pivots(window, left_bars=2, right_bars=2, mode="both", limit=50)["candidates"]
40
+ # A wide bar can be both a high and a low pivot. Its ordering is unknown.
41
+ ambiguous = {p["time"] for p in pivots if sum(q["time"] == p["time"] for q in pivots) > 1}
42
+ pivots = [p for p in pivots if p["time"] not in ambiguous]
43
+ index_by_time = {str(row["time"]): index for index, row in enumerate(window)}
44
+ atr_values = talib.ATR(np.array([float(r["high"]) for r in window]),
45
+ np.array([float(r["low"]) for r in window]),
46
+ np.array([float(r["close"]) for r in window]), timeperiod=14)
47
+ atr = float(atr_values[-1])
48
+ if not math.isfinite(atr) or atr <= 0:
49
+ raise LineError("auto_drawing_atr_unavailable", "近期波动数据不足,无法可靠自动选点;仍可手动绘图。")
50
+ candidates = []
51
+ def add(points, side):
52
+ if any(index_by_time.get(p["time"]) is None for p in points):
53
+ return
54
+ indexes = [index_by_time[p["time"]] for p in points]
55
+ if len(window) - 1 - indexes[-1] > 30:
56
+ return
57
+ if any(b - a < 3 for a, b in zip(indexes, indexes[1:])):
58
+ return
59
+ candidates.append({"side": side, "anchors": [{"time": int(p["time"]), "price": p["price"]} for p in points],
60
+ "latest_anchor_time": int(points[-1]["time"]),
61
+ "latest_anchor_bars_ago": len(window) - 1 - indexes[-1]})
62
+ if drawing_type == "horizontal":
63
+ for pivot in pivots:
64
+ add([pivot], pivot["side"])
65
+ elif drawing_type == "trend":
66
+ for side in ("high", "low"):
67
+ same = [p for p in pivots if p["side"] == side]
68
+ for first, second in zip(same, same[1:]):
69
+ add([first, second], side)
70
+ elif drawing_type == "abc":
71
+ # Three labelled endpoints only describe two legs. Require the prior
72
+ # origin as well so A, B and C end three completed, alternating legs.
73
+ for start in range(len(pivots) - 3):
74
+ origin, a, b, c = pivots[start:start + 4]
75
+ points = (origin, a, b, c)
76
+ if any(left["side"] == right["side"] for left, right in zip(points, points[1:])):
77
+ continue
78
+ indexes = [index_by_time.get(p["time"]) for p in points]
79
+ if any(index is None for index in indexes) or any(y - x < 3 for x, y in zip(indexes, indexes[1:])):
80
+ continue
81
+ if indexes[-1] - indexes[0] > 120:
82
+ continue
83
+ known_at = indexes[-1] + 2
84
+ if known_at >= len(atr_values):
85
+ continue
86
+ reference_atr = float(atr_values[known_at])
87
+ if not math.isfinite(reference_atr) or reference_atr <= 0:
88
+ continue
89
+ first_leg = abs(a["price"] - origin["price"])
90
+ retrace = abs(b["price"] - a["price"])
91
+ final_leg = abs(c["price"] - b["price"])
92
+ if first_leg < 2 * reference_atr or not .3 <= retrace / first_leg <= .8:
93
+ continue
94
+ if not .8 <= final_leg / first_leg <= 2.5:
95
+ continue
96
+ if origin["side"] == "high":
97
+ if b["price"] >= origin["price"] or c["price"] >= a["price"] - .25 * reference_atr:
98
+ continue
99
+ side = "abc_down"
100
+ else:
101
+ if b["price"] <= origin["price"] or c["price"] <= a["price"] + .25 * reference_atr:
102
+ continue
103
+ side = "abc_up"
104
+ before = len(candidates)
105
+ add((a, b, c), side)
106
+ if len(candidates) > before:
107
+ candidates[-1]["origin"] = {"time": int(origin["time"]), "price": origin["price"]}
108
+ else:
109
+ width = 2
110
+ for start in range(len(pivots) - width + 1):
111
+ points = pivots[start:start + width]
112
+ if any(a["side"] == b["side"] for a, b in zip(points, points[1:])):
113
+ continue
114
+ if any(abs(a["price"] - b["price"]) < atr for a, b in zip(points, points[1:])):
115
+ continue
116
+ add(points, "swing")
117
+ candidates.sort(key=lambda item: (item["latest_anchor_time"],
118
+ abs(item["anchors"][-1]["price"] - item["anchors"][0]["price"])), reverse=True)
119
+ candidates = candidates[:max_candidates]
120
+ return {"rule_version": RULE_VERSION, "drawing_type": drawing_type, "as_of": quality["as_of"],
121
+ "data_quality": quality, "lookback_bars": lookback_bars, "candidate_count": len(candidates),
122
+ "candidates": candidates, "limitations": ["confirmed_pivots_only", "abc_price_geometry_not_elliott_validation"]
123
+ if drawing_type == "abc" else ["confirmed_pivots_only"]}
@@ -0,0 +1,76 @@
1
+ """Explicit price/time platform rectangles; no automatic range identification."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import secrets
7
+ from typing import Any
8
+
9
+ from tools.lines import LineError, validate_line_fields
10
+ from tools.trend_lines import resolve_anchor_time
11
+
12
+ RECTANGLE_COMMAND = "DRAW_AGENT_RECTANGLE"
13
+ MAX_RECTANGLES = 30
14
+
15
+
16
+ def rectangles(payload: dict[str, Any]) -> list[dict[str, Any]]:
17
+ return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == RECTANGLE_COMMAND])
18
+
19
+
20
+ def edit_rectangle(
21
+ payload: dict[str, Any], action: str, *, rectangle_id: str | None = None,
22
+ start_time: str | None = None, end_time: str | None = None,
23
+ lower_price: float | None = None, upper_price: float | None = None,
24
+ name: str | None = None, color: str | None = None,
25
+ show_fill: bool | None = None, request_id: str | None = None,
26
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
27
+ """Return a new snapshot; invalid partial edits never modify the old rectangle."""
28
+ result = deepcopy(payload)
29
+ commands = result.get("chartCommands", [])
30
+ previous = next((c for c in commands if c.get("type") == RECTANGLE_COMMAND and c.get("id") == rectangle_id), None)
31
+ if action in {"update", "delete"} and previous is None:
32
+ raise LineError("rectangle_not_found", "当前快照不存在该 AI 平台框,请先读取平台框 ID。")
33
+ if action == "delete":
34
+ commands.remove(previous); result["chartCommands"] = commands
35
+ return result, deepcopy(previous)
36
+ if action not in {"create", "update"}:
37
+ raise LineError("invalid_action", "不支持的平台框操作。")
38
+ if action == "create" and any(v is None for v in (start_time, end_time, lower_price, upper_price)):
39
+ raise LineError("missing_bounds", "创建平台框需要明确起止时间、下沿和上沿价格。")
40
+ if action == "update" and all(v is None for v in (start_time, end_time, lower_price, upper_price, name, color, show_fill)):
41
+ raise LineError("empty_update", "请至少修改时间范围、价格边界、名称、颜色或填充开关。")
42
+ if show_fill is not None and not isinstance(show_fill, bool):
43
+ raise LineError("invalid_fill", "show_fill 必须是布尔值。")
44
+ _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
45
+ lower, _, _ = validate_line_fields(price=lower_price if lower_price is not None else previous["lower_price"])
46
+ upper, _, _ = validate_line_fields(price=upper_price if upper_price is not None else previous["upper_price"])
47
+ start = resolve_anchor_time(payload, start_time) if start_time is not None else previous["start_time"]
48
+ end = resolve_anchor_time(payload, end_time) if end_time is not None else previous["end_time"]
49
+ if start >= end:
50
+ raise LineError("invalid_anchor_order", "平台框起点必须早于终点;未自动交换时间。")
51
+ if lower >= upper:
52
+ raise LineError("invalid_price_bounds", "平台框下沿必须低于上沿;不接受零高度,也不自动交换价格。")
53
+ rectangle = {"type": RECTANGLE_COMMAND, "id": previous["id"] if previous else "rect_" + secrets.token_hex(12),
54
+ "interval": payload.get("interval"), "start_time": start, "end_time": end,
55
+ "lower_price": lower, "upper_price": upper,
56
+ "label": name if name is not None else previous["label"] if previous else "",
57
+ "color": color if color is not None else previous["color"] if previous else "info",
58
+ "show_fill": show_fill if show_fill is not None else previous["show_fill"] if previous else True}
59
+ if previous and previous.get("create_request_id"):
60
+ rectangle["create_request_id"] = previous["create_request_id"]
61
+ if action == "create":
62
+ if request_id:
63
+ rectangle["create_request_id"] = request_id
64
+ rectangle["id"] = "rect_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
65
+ retry = next((c for c in commands if c.get("type") == RECTANGLE_COMMAND and c.get("create_request_id") == request_id), None)
66
+ if retry:
67
+ if any(retry.get(k) != rectangle[k] for k in ("start_time", "end_time", "lower_price", "upper_price", "label", "color", "show_fill")):
68
+ raise LineError("request_conflict", "同一 request_id 的平台框参数不同,请使用新的 request_id。")
69
+ return result, deepcopy(retry)
70
+ if len(rectangles(result)) >= MAX_RECTANGLES:
71
+ raise LineError("too_many_rectangles", "当前图表最多保存 30 个 AI 平台框。")
72
+ commands.append(rectangle)
73
+ else:
74
+ commands[commands.index(previous)] = rectangle
75
+ result["chartCommands"] = commands
76
+ return result, deepcopy(rectangle)
@@ -0,0 +1,87 @@
1
+ """Deterministic linear-regression channel statistics over an explicit bar range."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+
6
+ from core.rows import RowsValidationError, validate_rows
7
+ from tools.lines import LineError
8
+
9
+ MIN_REGRESSION_BARS = 10
10
+ MAX_REGRESSION_BARS = 4000
11
+
12
+
13
+ def regression_channel(rows, *, start_time, end_time, multiplier=2.0):
14
+ """Fit close ~ candle-index over an inclusive explicit range.
15
+
16
+ The channel boundaries are regression line +/- multiplier * population RMS
17
+ residual. It returns statistics only and never creates a chart drawing.
18
+ """
19
+ if type(start_time) is not int or type(end_time) is not int or start_time >= end_time:
20
+ raise LineError("invalid_regression_range", "回归区间起点必须早于终点且对应明确的K线。")
21
+ if type(multiplier) not in (int, float) or not math.isfinite(multiplier) or not 0.5 <= multiplier <= 5:
22
+ raise LineError("invalid_regression_multiplier", "multiplier 必须是0.5至5之间的有限数值。")
23
+ try:
24
+ candles = validate_rows(rows, min_len=MIN_REGRESSION_BARS)
25
+ except RowsValidationError:
26
+ raise LineError("insufficient_regression_history", "当前已加载K线不足10根,无法计算回归通道;未补取行情。") from None
27
+
28
+ indexes = {int(row["time"]): index for index, row in enumerate(candles)}
29
+ if start_time not in indexes or end_time not in indexes:
30
+ raise LineError("regression_anchor_not_found", "回归区间两端必须精确对应当前已加载K线;未吸附或补取行情。")
31
+ first, last = indexes[start_time], indexes[end_time]
32
+ if first >= last:
33
+ raise LineError("invalid_regression_range", "回归区间起点必须早于终点;未自动交换。")
34
+ selected = candles[first:last + 1]
35
+ if len(selected) < MIN_REGRESSION_BARS:
36
+ raise LineError("insufficient_regression_range", "指定区间至少需要10根已加载K线。")
37
+ if len(selected) > MAX_REGRESSION_BARS:
38
+ raise LineError("regression_range_too_large", "指定回归区间最多4000根已加载K线。")
39
+
40
+ prices = [float(row["close"]) for row in selected]
41
+ if any(not math.isfinite(price) or price <= 0 for price in prices):
42
+ raise LineError("invalid_regression_data", "回归区间收盘价必须为大于零的有限数值。")
43
+
44
+ count = len(prices)
45
+ x_mean = (count - 1) / 2
46
+ y_mean = math.fsum(prices) / count
47
+ denominator = math.fsum((index - x_mean) ** 2 for index in range(count))
48
+ slope = math.fsum((index - x_mean) * (price - y_mean)
49
+ for index, price in enumerate(prices)) / denominator
50
+ intercept = y_mean - slope * x_mean
51
+ fitted = [intercept + slope * index for index in range(count)]
52
+ residuals = [price - estimate for price, estimate in zip(prices, fitted)]
53
+ residual_variance = math.fsum(value * value for value in residuals) / count
54
+ residual_stddev = math.sqrt(max(0.0, residual_variance))
55
+ total_variance = math.fsum((price - y_mean) ** 2 for price in prices)
56
+ residual_sum_squares = math.fsum(value * value for value in residuals)
57
+ r_squared = 1.0 if total_variance == 0 else 1 - residual_sum_squares / total_variance
58
+ width = multiplier * residual_stddev
59
+ line_start, line_end = fitted[0], fitted[-1]
60
+ result = {
61
+ "start_time": start_time,
62
+ "end_time": end_time,
63
+ "bar_count": count,
64
+ "price_source": "close",
65
+ "x_axis": "loaded_candle_index",
66
+ "fit": "ordinary_least_squares",
67
+ "slope_per_bar": slope,
68
+ "regression_start_price": line_start,
69
+ "regression_end_price": line_end,
70
+ "residual_stddev_population": residual_stddev,
71
+ "multiplier": float(multiplier),
72
+ "channel_width": width,
73
+ "upper_start_price": line_start + width,
74
+ "upper_end_price": line_end + width,
75
+ "lower_start_price": line_start - width,
76
+ "lower_end_price": line_end - width,
77
+ "r_squared": min(1.0, max(0.0, r_squared)),
78
+ "direction": "ascending" if slope > 0 else "descending" if slope < 0 else "horizontal",
79
+ "boundary_rule": "ols_close_plus_minus_multiplier_times_population_rms_residual",
80
+ "automatic_anchor_selection": False,
81
+ }
82
+ if any(not math.isfinite(value) for key, value in result.items()
83
+ if key not in {"start_time", "end_time", "bar_count", "price_source", "x_axis", "fit", "direction", "boundary_rule", "automatic_anchor_selection"}):
84
+ raise LineError("invalid_regression_result", "回归计算产生非有限数值,未保存结果。")
85
+ if result["lower_start_price"] <= 0 or result["lower_end_price"] <= 0:
86
+ raise LineError("invalid_regression_boundary", "回归下轨必须保持正价格;请调整区间或 multiplier。")
87
+ return result