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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/lib/client.js +9 -1
  2. package/package.json +2 -5
  3. package/src/client/index.js +8 -0
  4. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -564
  5. package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
  6. package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
  7. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -265
  8. package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -281
  9. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -686
  10. package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
  11. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
  12. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3783
  13. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
  14. package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
  15. package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
  16. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -683
  17. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
  18. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -241
  25. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
  26. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
  27. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -349
  28. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -15445
  29. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -252
  30. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
  31. package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
  32. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -14
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -39
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -13
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -13
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
  73. package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
  74. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
  75. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
  76. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
  77. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
  78. package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -136
  79. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
  80. package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
  81. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
  82. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
  83. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -655
  84. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
  85. package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1734
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -345
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -466
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -63
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
  101. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -394
  102. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
  103. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
  104. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
  105. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4681
  106. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
  107. package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
  108. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
  109. package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
  110. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
  111. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -125
  112. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
  113. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
  114. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
  115. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
  116. package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
  117. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
  118. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
  119. package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
  120. package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
  121. package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
  122. package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
@@ -1,170 +0,0 @@
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_human_review",
168
- "no_breakout_signal", "no_drawing_created"],
169
- "drawing_created": False,
170
- }
@@ -1,76 +0,0 @@
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)
@@ -1,87 +0,0 @@
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
@@ -1,228 +0,0 @@
1
- """Read-only, current-chart-bound access to the complete pinned TA-Lib catalog."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- import math
7
- from time import perf_counter
8
-
9
- import chart_service
10
- from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION, calculate, catalog
11
- from tools.chart_context import read_chart_context
12
- from tools.chart_edits import require_alignment
13
- from tools.chart_functions import _binding, _hash
14
- from tools.lines import LineError
15
-
16
-
17
- CATALOG = catalog()
18
- CATALOG_BY_NAME = {item["name"]: item for item in CATALOG}
19
- MAX_RESULT_BYTES = 1024 * 1024
20
- MAX_RESULTS_PER_VIEW = 16
21
-
22
-
23
- def list_ta_catalog(*, group: str | None = None, query: str | None = None,
24
- offset: int = 0, limit: int = 25) -> dict:
25
- if type(offset) is not int or offset < 0 or type(limit) is not int or not 1 <= limit <= 50:
26
- raise LineError("invalid_ta_pagination", "TA-Lib 目录分页参数无效。")
27
- if group is not None and (not isinstance(group, str) or len(group) > 64):
28
- raise LineError("invalid_ta_group", "TA-Lib 函数组别无效。")
29
- if query is not None and (not isinstance(query, str) or len(query) > 64):
30
- raise LineError("invalid_ta_query", "TA-Lib 搜索词无效。")
31
- matches = [entry for entry in CATALOG
32
- if (not group or entry["group"].casefold() == group.casefold())
33
- and (not query or query.casefold() in (entry["name"] + " " + entry["display_name"]).casefold())]
34
- return {"ok": True, "engine": "TA-Lib", "engine_version": ENGINE_VERSION, "native_version": NATIVE_VERSION,
35
- "total_catalog": len(CATALOG), "total_matches": len(matches), "offset": offset, "limit": limit,
36
- "groups": sorted({entry["group"] for entry in CATALOG}),
37
- "functions": [{key: entry[key] for key in ("name", "group", "display_name", "input_names", "parameters",
38
- "output_names", "function_flags")}
39
- for entry in matches[offset:offset + limit]],
40
- "result_usage": "analysis_only", "chart_modified": False}
41
-
42
-
43
- def _context(context_ref, expected_revision, chart_session, symbol):
44
- context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
45
- if type(expected_revision) is not int or context["revision"] != expected_revision:
46
- raise LineError("chart_context_revision_conflict", "当前图观察版本已改变,请重新读取。")
47
- payload = chart_service.read_chart_snapshot(chart_session)
48
- if payload is None:
49
- raise LineError("chart_session_not_found", "当前图来源不存在。")
50
- require_alignment(context, payload, chart_session, symbol)
51
- if context["candle_selection"]["truncated"] or not context["candles"]:
52
- raise LineError("ta_candles_unavailable", "仅支持当前图1至4000根完整已加载K线,不截断计算。")
53
- return context
54
-
55
-
56
- def _directory(context):
57
- return chart_service.RUNTIME_DIR / "ta_functions" / str(chart_service.HOST_PROCESS_ID) / context["context_ref"]
58
-
59
-
60
- def _aligned_outputs(record, context, names):
61
- times = record.get("times")
62
- outputs = record.get("outputs")
63
- return (isinstance(times, list) and times == [row["time"] for row in context["candles"]]
64
- and isinstance(outputs, dict)
65
- and all(isinstance(outputs.get(name), list) and len(outputs[name]) == len(times) for name in names))
66
-
67
-
68
- def _positive(value):
69
- return type(value) in (int, float) and math.isfinite(value) and value > 0
70
-
71
-
72
- def _renderable_line(record, context):
73
- """Only a finite, positive SMA/EMA(close) series fits the current price-line contract."""
74
- parameters = record.get("parameters")
75
- period = parameters.get("timeperiod") if isinstance(parameters, dict) else None
76
- if not (record.get("function") in {"SMA", "EMA"} and type(period) is int and 2 <= period <= 200
77
- and record.get("price_sources") in ({}, {"price": "close"})
78
- and _aligned_outputs(record, context, ("real",))):
79
- return False
80
- values = record["outputs"]["real"]
81
- return any(value is not None for value in values) and all(value is None or _positive(value) for value in values)
82
-
83
-
84
- def _renderable_bbands(record, context):
85
- params = record.get("parameters")
86
- if not (record.get("function") == "BBANDS" and isinstance(params, dict)
87
- and type(params.get("timeperiod")) is int and 2 <= params["timeperiod"] <= 200
88
- and type(params.get("matype")) is int and params["matype"] == 0
89
- and all(type(params.get(key)) in (int, float) and math.isfinite(params[key])
90
- and 0 < params[key] <= 5 for key in ("nbdevup", "nbdevdn"))
91
- and record.get("price_sources") in ({}, {"price": "close"})
92
- and _aligned_outputs(record, context, ("upperband", "middleband", "lowerband"))):
93
- return False
94
- outputs = record["outputs"]
95
- triples = zip(outputs["upperband"], outputs["middleband"], outputs["lowerband"])
96
- valid = 0
97
- for upper, middle, lower in triples:
98
- if upper is middle is lower is None:
99
- continue
100
- if not (_positive(upper) and _positive(middle) and _positive(lower)
101
- and upper > middle > lower):
102
- return False
103
- valid += 1
104
- return valid > 0
105
-
106
-
107
- def _load_record(context, result_ref, expected_revision):
108
- if not isinstance(result_ref, str) or len(result_ref) != 64 or any(c not in "0123456789abcdef" for c in result_ref):
109
- raise LineError("invalid_ta_result_ref", "TA-Lib 结果引用无效。")
110
- path = _directory(context) / f"{result_ref}.json"
111
- try:
112
- if path.stat().st_size > MAX_RESULT_BYTES:
113
- raise ValueError("size")
114
- record = json.loads(path.read_text(encoding="utf-8"))
115
- if _hash(record) != result_ref or record.get("schema_version") != 1:
116
- raise ValueError("hash")
117
- except (OSError, ValueError, TypeError):
118
- raise LineError("ta_result_unavailable", "结果引用不存在或已失效。") from None
119
- if (record.get("engine") != "TA-Lib" or record.get("engine_version") != ENGINE_VERSION
120
- or record.get("native_version") != NATIVE_VERSION or record.get("result_usage") != "analysis_only"
121
- or record.get("binding") != _binding(context)
122
- or record.get("observation_revision") != expected_revision):
123
- raise LineError("ta_result_mismatch", "结果与当前标的、周期、行情或视图不匹配,请重新计算。")
124
- return record
125
-
126
-
127
- def resolve_ta_drawing(result_ref, context, kind):
128
- """Explicitly promote an allowlisted bound TA result into guarded price geometry."""
129
- record = _load_record(context, result_ref, context["revision"])
130
- if kind == "series_line" and _renderable_line(record, context):
131
- return {"source": {"kind": record["function"].lower(), "period": record["parameters"]["timeperiod"]},
132
- "condition": None, "values": list(record["outputs"]["real"])}
133
- if kind == "price_band" and _renderable_bbands(record, context):
134
- params = record["parameters"]
135
- source = {"kind": "bbands", "period": params["timeperiod"],
136
- "deviation_up": params["nbdevup"], "deviation_down": params["nbdevdn"], "matype": 0}
137
- return {"upper_source": {**source, "output": "upperband"},
138
- "lower_source": {**source, "output": "lowerband"}, "condition": None,
139
- "upper_values": list(record["outputs"]["upperband"]),
140
- "middle_values": list(record["outputs"]["middleband"]),
141
- "lower_values": list(record["outputs"]["lowerband"])}
142
- raise LineError("ta_result_not_drawable", "仅支持当前图的有限 SMA/EMA(close) 单线或 BBANDS(close, SMA中轨) 三线价带;请核对函数、输入、参数与目标图形。")
143
-
144
-
145
- def run_ta(context_ref, expected_revision, chart_session, symbol, name, parameters=None,
146
- price_sources=None, periods_constant=14):
147
- started = perf_counter()
148
- if not isinstance(name, str) or name not in CATALOG_BY_NAME:
149
- raise LineError("unknown_ta_function", "未知 TA-Lib 函数,请先查询 list_ta_functions。")
150
- context = _context(context_ref, expected_revision, chart_session, symbol)
151
- try:
152
- info, values = calculate(name, context["candles"], parameters=parameters,
153
- price_sources=price_sources, periods_constant=periods_constant)
154
- except Exception as exc:
155
- if isinstance(exc, RuntimeError):
156
- raise
157
- raise LineError("invalid_ta_parameters", f"TA-Lib 参数或输入无效:{exc}") from None
158
- rows = context["candles"]
159
- summaries = {}
160
- any_finite = False
161
- for output_name, series in values.items():
162
- valid = [(index, value) for index, value in enumerate(series) if value is not None]
163
- any_finite |= bool(valid)
164
- summaries[output_name] = {
165
- "first_valid": {"index": valid[0][0], "time": rows[valid[0][0]]["time"]} if valid else None,
166
- "latest": {"index": valid[-1][0], "time": rows[valid[-1][0]]["time"],
167
- "value": valid[-1][1]} if valid else None,
168
- "valid_count": len(valid), "nonzero_count": sum(value != 0 for _, value in valid),
169
- }
170
- record = {"schema_version": 1, "engine": "TA-Lib", "engine_version": ENGINE_VERSION,
171
- "native_version": NATIVE_VERSION, "binding": _binding(context),
172
- "observation_revision": expected_revision, "function": name,
173
- "parameters": {**info["parameters"], **(parameters or {})},
174
- "price_sources": price_sources or {}, "periods_constant": periods_constant if name == "MAVP" else None,
175
- "times": [row["time"] for row in rows], "outputs": values, "summary": summaries,
176
- "result_usage": "analysis_only"}
177
- encoded = json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
178
- if len(encoded) > MAX_RESULT_BYTES:
179
- raise LineError("ta_result_too_large", "TA-Lib 结果超过本地容量限制,未保存。")
180
- result_ref = _hash(record)
181
- refreshed = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
182
- if refreshed["revision"] != expected_revision or _binding(refreshed) != record["binding"]:
183
- raise LineError("chart_context_revision_conflict", "计算期间当前图已改变,未保存结果。")
184
- directory = _directory(context)
185
- path = directory / f"{result_ref}.json"
186
- if not path.exists():
187
- existing = sorted(directory.glob("*.json"), key=lambda item: (item.stat().st_mtime_ns, item.name)) if directory.exists() else []
188
- if len(existing) >= MAX_RESULTS_PER_VIEW:
189
- try:
190
- for expired in existing[:len(existing) - MAX_RESULTS_PER_VIEW + 1]:
191
- expired.unlink()
192
- except OSError:
193
- raise LineError("ta_result_capacity", "当前图的临时结果容量已满,无法淘汰旧结果。") from None
194
- chart_service._atomic_runtime_json(path, record)
195
- else:
196
- try:
197
- if json.loads(path.read_text(encoding="utf-8")) != record:
198
- raise ValueError("collision")
199
- except (OSError, ValueError):
200
- raise LineError("ta_result_invalid", "已保存 TA 结果无效,未覆盖。") from None
201
- return {"ok": True, "engine": "TA-Lib", "engine_version": ENGINE_VERSION,
202
- "native_version": NATIVE_VERSION, "result_ref": result_ref, "function": name,
203
- "parameters": record["parameters"], "price_sources": record["price_sources"],
204
- "status": "ok" if any_finite else "no_finite_output", "summary": summaries,
205
- "loaded_bars": len(rows), "data_fingerprint": record["binding"]["data_fingerprint"],
206
- "data_scope": {key: context.get(key) for key in ("symbol", "interval", "interval_value", "adjust", "loaded_range")},
207
- "result_usage": "analysis_only", "chart_modified": False, "render_verified": False,
208
- "selectable_render_targets": ([{"kind": "series_line", "output_name": "real"}]
209
- if _renderable_line(record, context) else
210
- [{"kind": "price_band", "output_names": ["upperband", "middleband", "lowerband"]}]
211
- if _renderable_bbands(record, context) else []),
212
- "calculation_ms": round((perf_counter() - started) * 1000, 3)}
213
-
214
-
215
- def read_ta(context_ref, expected_revision, chart_session, symbol, result_ref, output_name,
216
- offset=0, limit=200):
217
- if type(offset) is not int or offset < 0 or type(limit) is not int or not 1 <= limit <= 250:
218
- raise LineError("invalid_ta_pagination", "TA-Lib 结果分页参数无效。")
219
- context = _context(context_ref, expected_revision, chart_session, symbol)
220
- record = _load_record(context, result_ref, expected_revision)
221
- series = record.get("outputs", {}).get(output_name) if isinstance(output_name, str) else None
222
- times = record.get("times")
223
- if not isinstance(series, list) or not isinstance(times, list) or len(series) != len(times):
224
- raise LineError("ta_output_unknown", "结果不存在此输出名称。")
225
- return {"ok": True, "result_ref": result_ref, "function": record["function"],
226
- "output_name": output_name, "total": len(series), "offset": offset, "limit": limit,
227
- "items": [{"time": times[i], "value": series[i]} for i in range(offset, min(offset + limit, len(series)))],
228
- "result_usage": "analysis_only", "chart_modified": False}