@dsh-ft/dsh-fft-paper-trading 0.7.0 → 0.7.1
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.
- package/lib/client.js +9 -1
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +47 -0
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +107 -201
- package/node_modules/@ftshare-lab/dsh-kline/README.md +106 -216
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +3 -2
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +103 -11
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +8 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +11 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +6 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +2971 -835
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +35 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +91 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +25 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +5 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +4 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +38 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +55 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +13 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +3 -9
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +2 -0
- package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +4 -1
- package/node_modules/@ftshare-lab/dsh-kline/server.py +46 -25
- package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +158 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +30 -12
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +53 -68
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +3 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +68 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +18 -2
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +2 -2
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +2 -3
- package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +66 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +103 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +12 -6
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +311 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +1 -1
- package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +123 -0
- package/package.json +2 -2
- package/src/client/index.js +8 -0
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
|
@@ -22,8 +22,7 @@ from tools.lines import LineError
|
|
|
22
22
|
from tools.rectangles import RECTANGLE_COMMAND, edit_rectangle
|
|
23
23
|
from tools.polylines import LabeledPoint, POLYLINE_COMMAND, edit_polyline
|
|
24
24
|
from tools.pivots import confirmed_pivots
|
|
25
|
-
from tools.
|
|
26
|
-
from tools.range_candidates import DEFAULT_WINDOW_SIZES, range_candidates
|
|
25
|
+
from tools.automatic_analysis import AUTOMATIC_ANALYSES, analyze_automatic, candidate_function_for_kind, candidate_edit_parameters
|
|
27
26
|
from tools.regression_channels import regression_channel
|
|
28
27
|
from tools.price_series import PriceCondition, PriceSource, SERIES_COMMAND, calculate_price_series, edit_price_series
|
|
29
28
|
from tools.annotations import edit_annotation, _validate_content
|
|
@@ -31,13 +30,13 @@ from tools.price_bands import BAND_COMMAND, calculate_price_band, edit_price_ban
|
|
|
31
30
|
from tools.price_sticks import STICKS_COMMAND, calculate_price_sticks, edit_price_sticks
|
|
32
31
|
from tools.trend_lines import resolve_anchor_time
|
|
33
32
|
|
|
34
|
-
FunctionName = Literal["fibonacci_retracement", "parallel_channel", "range_box", "labeled_polyline", "pivot_candidates", "regression_channel", "channel_candidates", "range_candidates", "price_series_line", "conditional_annotation", "price_band", "price_sticks"]
|
|
33
|
+
FunctionName = Literal["fibonacci_retracement", "parallel_channel", "range_box", "labeled_polyline", "pivot_candidates", "recent_drawing_candidates", "regression_channel", "channel_candidates", "range_candidates", "price_pattern_candidates", "nine_count", "price_series_line", "conditional_annotation", "price_band", "price_sticks"]
|
|
35
34
|
VERSION = "1"
|
|
36
|
-
ANALYSIS_ONLY = {"pivot_candidates", "regression_channel"
|
|
35
|
+
ANALYSIS_ONLY = {"pivot_candidates", "regression_channel"} | AUTOMATIC_ANALYSES.keys()
|
|
37
36
|
|
|
38
37
|
|
|
39
38
|
def _version(function):
|
|
40
|
-
return
|
|
39
|
+
return AUTOMATIC_ANALYSES[function].version if function in AUTOMATIC_ANALYSES else VERSION
|
|
41
40
|
|
|
42
41
|
|
|
43
42
|
FUNCTIONS = {
|
|
@@ -49,10 +48,11 @@ FUNCTIONS = {
|
|
|
49
48
|
("start_time", "end_time", "lower_price", "upper_price"), ()),
|
|
50
49
|
"labeled_polyline": ("labeled_polyline", edit_polyline, ("points",), ()),
|
|
51
50
|
"pivot_candidates": ("pivot_candidates", None, (), ("left_bars", "right_bars", "mode", "limit")),
|
|
51
|
+
"recent_drawing_candidates": ("recent_drawing_candidates", None,
|
|
52
|
+
AUTOMATIC_ANALYSES["recent_drawing_candidates"].required, AUTOMATIC_ANALYSES["recent_drawing_candidates"].optional),
|
|
52
53
|
"regression_channel": ("regression_channel", None, ("start_time", "end_time"), ("multiplier",)),
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
"range_candidates": ("range_candidates", None, (), ("window_sizes", "max_candidates")),
|
|
54
|
+
**{name: (name, None, spec.required, spec.optional) for name, spec in AUTOMATIC_ANALYSES.items()
|
|
55
|
+
if name != "recent_drawing_candidates"},
|
|
56
56
|
"price_series_line": ("series_line", edit_price_series, ("value_source",), ("condition",)),
|
|
57
57
|
"conditional_annotation": ("annotation_kind_parameter", edit_annotation,
|
|
58
58
|
("annotation_kind", "anchor_source", "condition"), ("annotation_text", "annotation_value", "annotation_icon")),
|
|
@@ -78,6 +78,9 @@ class ChartFunctionParameters(BaseModel):
|
|
|
78
78
|
left_bars: int | None = Field(default=None, strict=True, ge=1, le=20, description="左侧比较K线数;默认2")
|
|
79
79
|
right_bars: int | None = Field(default=None, strict=True, ge=1, le=20, description="右侧确认K线数;默认2")
|
|
80
80
|
mode: Literal["high", "low", "both"] | None = Field(default=None, description="返回局部高点、低点或两者;默认both")
|
|
81
|
+
drawing_type: Literal["horizontal", "trend", "fibonacci", "abc"] | None = None
|
|
82
|
+
closed_daily_only: bool | None = Field(default=None, strict=True,
|
|
83
|
+
description="只使用可确认收盘的 A/港/美股单日线")
|
|
81
84
|
limit: int | None = Field(default=None, strict=True, ge=1, le=50, description="最多返回最新候选数;默认20")
|
|
82
85
|
multiplier: float | None = Field(default=None, strict=True, ge=0.5, le=5, allow_inf_nan=False,
|
|
83
86
|
description="回归上下轨距离倍数;默认2,乘以回归残差总体RMS")
|
|
@@ -88,6 +91,10 @@ class ChartFunctionParameters(BaseModel):
|
|
|
88
91
|
max_candidates: int | None = Field(default=None, strict=True, ge=1, le=5, description="最多返回候选数;默认3")
|
|
89
92
|
window_sizes: list[Annotated[int, Field(strict=True, ge=16, le=120)]] | None = Field(
|
|
90
93
|
default=None, min_length=1, max_length=8, description="平台候选窗口根数;默认20、30、40、60;不得重复")
|
|
94
|
+
pattern_types: list[Literal["double_top", "double_bottom", "head_shoulders_top", "head_shoulders_bottom", "platform"]] | None = Field(default=None, min_length=1, max_length=5)
|
|
95
|
+
anchor_times: list[int] | None = Field(default=None, min_length=3, max_length=5,
|
|
96
|
+
description="用户按时间顺序指定的形态锚点,仍须通过标准规则验证")
|
|
97
|
+
display_bars: int | None = Field(default=None, strict=True, ge=30, le=240)
|
|
91
98
|
value_source: PriceSource | None = Field(default=None, description="序列线取值:OHLC、SMA 或 EMA(close, 2至200根)")
|
|
92
99
|
condition: PriceCondition | None = Field(default=None, description="可选价格条件;不接受宿主传入行情数组或代码")
|
|
93
100
|
anchor_source: PriceSource | None = Field(default=None, description="条件标注所用价格锚点,取最新一根满足条件的已加载K线")
|
|
@@ -110,17 +117,19 @@ def list_functions():
|
|
|
110
117
|
"optional_parameters": list(optional) + ([] if name in ANALYSIS_ONLY else ["price_scale"]),
|
|
111
118
|
"defaults": ({"left_bars": 2, "right_bars": 2, "mode": "both", "limit": 20}
|
|
112
119
|
if name == "pivot_candidates" else
|
|
120
|
+
deepcopy(AUTOMATIC_ANALYSES[name].defaults) if name in AUTOMATIC_ANALYSES else
|
|
113
121
|
{"multiplier": 2.0} if name == "regression_channel" else
|
|
114
|
-
{"direction": "both", "scope": "current", "lookback_bars": 120, "left_bars": 2, "right_bars": 2,
|
|
115
|
-
"min_span_bars": 12, "max_candidates": 3} if name == "channel_candidates" else
|
|
116
|
-
{"window_sizes": list(DEFAULT_WINDOW_SIZES), "max_candidates": 3} if name == "range_candidates" else
|
|
117
122
|
{"condition": None, "price_scale": "linear"} if name == "price_series_line" else
|
|
118
123
|
{"selection": "latest_match", "price_scale": "linear"} if name == "conditional_annotation" else
|
|
119
124
|
{"condition": None, "price_scale": "linear"} if name in {"price_band", "price_sticks"} else
|
|
120
125
|
{"price_scale": "linear", **({"ratios": list(DEFAULT_RATIOS)} if name == "fibonacci_retracement" else {})}),
|
|
121
126
|
"limits": {"loaded_bars": 4000, "automatic_anchor_selection": False,
|
|
122
127
|
"price_scale": "linear", "time": "exact_loaded_bar", "applies_chart": False,
|
|
123
|
-
**({"
|
|
128
|
+
**({"closed_daily_only": True, "recent_confirmed_pivots": True,
|
|
129
|
+
"automatic_anchor_selection": "candidates_only_not_drawing",
|
|
130
|
+
"candidate_limit": [1, 5], "applies_chart": False,
|
|
131
|
+
"direct_request_may_select_latest": True} if name == "recent_drawing_candidates" else
|
|
132
|
+
{"window_bars": [1, 20], "candidate_limit": [1, 50],
|
|
124
133
|
"rule": "strict_local_extremum", "ties": "equal_neighbor_is_not_a_pivot",
|
|
125
134
|
"requires_complete_right_window": True} if name == "pivot_candidates" else
|
|
126
135
|
{"minimum_range_bars": 10, "maximum_range_bars": 4000,
|
|
@@ -137,14 +146,23 @@ def list_functions():
|
|
|
137
146
|
"same_family_slope_tolerance": 0.10,
|
|
138
147
|
"same_family_width_tolerance": 0.10,
|
|
139
148
|
"current_post_end_check": "arithmetic_extension_to_latest_not_breakout_confirmation",
|
|
140
|
-
"
|
|
149
|
+
"requires_result_review": True, "direct_request_may_select_latest": True} if name == "channel_candidates" else
|
|
141
150
|
{"window_size_bars": [16, 120], "candidate_limit": [1, 5],
|
|
142
151
|
"end_policy": "latest_loaded_bar_only",
|
|
143
152
|
"boundary_rule": "full_window_max_high_min_low",
|
|
144
153
|
"requires_separated_touches_on_both_edges": True,
|
|
145
154
|
"checks_full_and_recent_close_drift": True,
|
|
146
155
|
"automatic_anchor_selection": "candidates_only_not_drawing",
|
|
147
|
-
"
|
|
156
|
+
"requires_result_review": True, "direct_request_may_select_latest": True} if name == "range_candidates" else
|
|
157
|
+
{"market": ["CN", "HK", "US"], "interval": "single_daily_only",
|
|
158
|
+
"lookback_bars": [60, 300], "candidate_limit": [1, 5],
|
|
159
|
+
"pivot_window": [2, 2], "atr_period": 14, "breakout_buffer_atr": 0.25,
|
|
160
|
+
"confirmation": "two_consecutive_closed_daily_closes",
|
|
161
|
+
"requires_result_review": True, "direct_request_may_select_latest": True} if name == "price_pattern_candidates" else
|
|
162
|
+
{"market": ["CN", "HK", "US"], "interval": "single_daily_only",
|
|
163
|
+
"display_bars": [30, 240], "comparison_lag": 4,
|
|
164
|
+
"completed_count": 9, "repeat_while_same_direction": False,
|
|
165
|
+
"requires_result_review": True, "direct_request_may_apply": True} if name == "nine_count" else
|
|
148
166
|
{"maximum_series_objects": 8, "value_sources": ["open", "high", "low", "close", "sma_close", "ema_close"],
|
|
149
167
|
"sma_period": [2, 200], "ema_period": [2, 200], "conditions": ["gt", "gte", "lt", "lte"],
|
|
150
168
|
"zero_matches": "do_not_draw", "pane": "candle"} if name == "price_series_line" else
|
|
@@ -165,7 +183,7 @@ def list_functions():
|
|
|
165
183
|
**({"$defs": schema["$defs"]} if name in {"labeled_polyline", "price_series_line", "conditional_annotation", "price_band", "price_sticks"} else {})}}
|
|
166
184
|
for name, (kind, _, required, optional) in FUNCTIONS.items()],
|
|
167
185
|
"workflow": "get_chart_context -> run_chart_function -> prepare_chart_edit(result_ref) -> apply_chart_edit -> get_chart_edit_status",
|
|
168
|
-
"analysis_only_workflow": "get_chart_context -> run_chart_function
|
|
186
|
+
"analysis_only_workflow": "get_chart_context -> run_chart_function; inspect analysis. A direct drawing request authorizes the first suitable candidate without another confirmation; analysis-only or proposal-first requests do not. All automatic candidates use candidate_result_ref, candidate_number and user_confirmed_candidate=true after selection. Nine-count marks use a current result_ref. Both then use prepare/apply/status; historical anchors do not prove a current breakout",
|
|
169
187
|
"pattern_quality_verified": False}
|
|
170
188
|
|
|
171
189
|
|
|
@@ -188,7 +206,7 @@ def _directory(context):
|
|
|
188
206
|
return chart_service.RUNTIME_DIR / "functions" / str(chart_service.HOST_PROCESS_ID) / context["context_ref"]
|
|
189
207
|
|
|
190
208
|
|
|
191
|
-
def _calculate(payload, function, parameters, *, candles=None):
|
|
209
|
+
def _calculate(payload, function, parameters, *, candles=None, context=None):
|
|
192
210
|
if function not in FUNCTIONS:
|
|
193
211
|
raise LineError("unknown_chart_function", "未知函数,请查询 list_chart_functions;不执行任意公式或代码。")
|
|
194
212
|
kind, editor, required, optional = FUNCTIONS[function]
|
|
@@ -198,6 +216,16 @@ def _calculate(payload, function, parameters, *, candles=None):
|
|
|
198
216
|
raise LineError("invalid_function_parameters", "参数不适用于该函数。")
|
|
199
217
|
if any(k not in values for k in required):
|
|
200
218
|
raise LineError("missing_anchor", "缺少明确锚点或边界;请向用户澄清,不自动选择。")
|
|
219
|
+
if function in AUTOMATIC_ANALYSES:
|
|
220
|
+
if not isinstance(context, dict):
|
|
221
|
+
raise LineError("daily_analysis_unavailable", "当前图缺少可核对的已加载日线。")
|
|
222
|
+
result, normalized = analyze_automatic(function, candles, symbol=context.get("symbol"),
|
|
223
|
+
interval=context.get("interval"), source_interval=context.get("source_interval"),
|
|
224
|
+
interval_value=context.get("interval_value"),
|
|
225
|
+
provider=context.get("data_provenance", {}).get("provider"),
|
|
226
|
+
volume_unit=context.get("display_volume_unit"), parameters=values)
|
|
227
|
+
return {"function": function, "function_version": _version(function), "kind": kind,
|
|
228
|
+
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear", "summary": result}
|
|
201
229
|
if function == "pivot_candidates":
|
|
202
230
|
rows = candles
|
|
203
231
|
if not isinstance(rows, list):
|
|
@@ -219,33 +247,6 @@ def _calculate(payload, function, parameters, *, candles=None):
|
|
|
219
247
|
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
220
248
|
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear",
|
|
221
249
|
"summary": result}
|
|
222
|
-
if function == "channel_candidates":
|
|
223
|
-
if not isinstance(candles, list):
|
|
224
|
-
raise LineError("channel_candidate_data_unavailable", "当前图没有可读取的已加载K线,未补取行情。")
|
|
225
|
-
result = channel_candidates(candles, direction=values.get("direction", "both"),
|
|
226
|
-
scope=values.get("scope", "current"),
|
|
227
|
-
lookback_bars=values.get("lookback_bars", 120),
|
|
228
|
-
left_bars=values.get("left_bars", 2),
|
|
229
|
-
right_bars=values.get("right_bars", 2),
|
|
230
|
-
min_span_bars=values.get("min_span_bars", 12),
|
|
231
|
-
limit=values.get("max_candidates", 3))
|
|
232
|
-
normalized = {"direction": result["direction"], "scope": result["scope"],
|
|
233
|
-
"lookback_bars": result["lookback_bars"],
|
|
234
|
-
"left_bars": result["left_bars"], "right_bars": result["right_bars"],
|
|
235
|
-
"min_span_bars": result["min_span_bars"], "max_candidates": values.get("max_candidates", 3)}
|
|
236
|
-
return {"function": function, "function_version": _version(function), "kind": kind,
|
|
237
|
-
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear",
|
|
238
|
-
"summary": result}
|
|
239
|
-
if function == "range_candidates":
|
|
240
|
-
if not isinstance(candles, list):
|
|
241
|
-
raise LineError("range_candidate_data_unavailable", "当前图没有可读取的已加载K线,未补取行情。")
|
|
242
|
-
result = range_candidates(candles, window_sizes=values.get("window_sizes", DEFAULT_WINDOW_SIZES),
|
|
243
|
-
limit=values.get("max_candidates", 3))
|
|
244
|
-
normalized = {"window_sizes": result["window_sizes"],
|
|
245
|
-
"max_candidates": values.get("max_candidates", 3)}
|
|
246
|
-
return {"function": function, "function_version": _version(function), "kind": kind,
|
|
247
|
-
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear",
|
|
248
|
-
"summary": result}
|
|
249
250
|
if function == "price_series_line":
|
|
250
251
|
if not isinstance(candles, list) or values.get("value_source") is None:
|
|
251
252
|
raise LineError("price_series_data_unavailable", "当前图没有可读取的已加载K线,未补取行情。")
|
|
@@ -359,9 +360,9 @@ def run_function(context_ref, expected_revision, chart_session, symbol, function
|
|
|
359
360
|
payload = chart_service.read_chart_snapshot(chart_session)
|
|
360
361
|
if payload is None: raise LineError("chart_session_not_found", "当前命名来源不存在。")
|
|
361
362
|
require_alignment(context, payload, chart_session, symbol)
|
|
362
|
-
calculation = _calculate(payload, function, parameters, candles=context["candles"])
|
|
363
|
+
calculation = _calculate(payload, function, parameters, candles=context["candles"], context=context)
|
|
363
364
|
record = {"schema_version": 1, "binding": _binding(context), **calculation}
|
|
364
|
-
if len(json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()) > (262144 if function in {"price_series_line", "price_band", "price_sticks"} else 32768):
|
|
365
|
+
if len(json.dumps(record, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()) > (262144 if function in {"price_series_line", "price_band", "price_sticks", "price_pattern_candidates", "nine_count"} else 32768):
|
|
365
366
|
raise LineError("chart_function_result_too_large", "函数结果超出本阶段容量限制,未保存或绘图。")
|
|
366
367
|
result_ref = _hash(record)
|
|
367
368
|
refreshed = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
|
|
@@ -396,7 +397,7 @@ def _read_result_record(result_ref, context, kind):
|
|
|
396
397
|
if path.stat().st_size > 262144: raise ValueError("size")
|
|
397
398
|
record = json.loads(path.read_text(encoding="utf-8"))
|
|
398
399
|
if _hash(record) != result_ref or record["schema_version"] != 1: raise ValueError("hash")
|
|
399
|
-
if record.get("function") not in {"price_series_line", "price_band", "price_sticks"} and path.stat().st_size > 32768: raise ValueError("size")
|
|
400
|
+
if record.get("function") not in {"price_series_line", "price_band", "price_sticks", "price_pattern_candidates", "nine_count"} and path.stat().st_size > 32768: raise ValueError("size")
|
|
400
401
|
except (OSError, ValueError, TypeError, KeyError):
|
|
401
402
|
raise LineError("chart_function_result_unavailable", "结果引用不存在或已失效;不能借用其他视图或宿主的结果。") from None
|
|
402
403
|
if (record["binding"] != _binding(context) or record.get("function_version") != _version(record.get("function"))
|
|
@@ -406,7 +407,10 @@ def _read_result_record(result_ref, context, kind):
|
|
|
406
407
|
|
|
407
408
|
|
|
408
409
|
def resolve_result(result_ref, context, kind):
|
|
409
|
-
record = _read_result_record(result_ref, context, kind)
|
|
410
|
+
record = _read_result_record(result_ref, context, "nine_count" if kind == "nine_count" else kind)
|
|
411
|
+
if kind == "nine_count" and record.get("function") == "nine_count":
|
|
412
|
+
return {"marks": deepcopy(record["summary"]["marks"]), "events": deepcopy(record["summary"]["events"]),
|
|
413
|
+
"as_of": record["summary"]["as_of"], "rule_version": record["summary"]["rule_version"]}
|
|
410
414
|
if record.get("result_usage") != "guarded_drawing":
|
|
411
415
|
raise LineError("chart_function_result_not_drawable", "该函数结果仅供分析,不能作为绘图几何引用。")
|
|
412
416
|
if kind == "series_line":
|
|
@@ -440,27 +444,8 @@ def resolve_result(result_ref, context, kind):
|
|
|
440
444
|
|
|
441
445
|
def resolve_selected_candidate(result_ref, context, kind, number):
|
|
442
446
|
"""Resolve one reviewed 1-based candidate; never alters a chart by itself."""
|
|
443
|
-
|
|
444
|
-
raise LineError("invalid_candidate_selection", "请指定通道或平台结果中的第1至5个候选。")
|
|
445
|
-
function = "channel_candidates" if kind == "channel" else "range_candidates"
|
|
447
|
+
function = candidate_function_for_kind(kind)
|
|
446
448
|
record = _read_result_record(result_ref, context, function)
|
|
447
449
|
if record.get("result_usage") != "analysis_only":
|
|
448
450
|
raise LineError("candidate_result_not_analysis", "该引用不是只读候选结果。")
|
|
449
|
-
|
|
450
|
-
if not isinstance(candidates, list) or number > len(candidates):
|
|
451
|
-
raise LineError("candidate_not_found", "所选候选不存在;请重新核对结果序号。")
|
|
452
|
-
selected = candidates[number - 1]
|
|
453
|
-
if kind == "channel":
|
|
454
|
-
anchors = selected.get("anchors", {})
|
|
455
|
-
try:
|
|
456
|
-
return {prefix + "_time": str(anchors[key]["time"])
|
|
457
|
-
for prefix, key in (("start", "from"), ("end", "to"), ("parallel", "parallel"))} | {
|
|
458
|
-
prefix + "_price": anchors[key]["price"]
|
|
459
|
-
for prefix, key in (("start", "from"), ("end", "to"), ("parallel", "parallel"))}
|
|
460
|
-
except (TypeError, KeyError):
|
|
461
|
-
raise LineError("candidate_result_invalid", "候选锚点不完整,未准备绘图。") from None
|
|
462
|
-
try:
|
|
463
|
-
return {"start_time": str(selected["start_time"]), "end_time": str(selected["end_time"]),
|
|
464
|
-
"lower_price": selected["lower_price"], "upper_price": selected["upper_price"]}
|
|
465
|
-
except (TypeError, KeyError):
|
|
466
|
-
raise LineError("candidate_result_invalid", "候选边界不完整,未准备绘图。") from None
|
|
451
|
+
return candidate_edit_parameters(kind, record.get("summary", {}), number)
|
|
@@ -23,7 +23,7 @@ def _period(value: Any, name: str, maximum: int = 200) -> int:
|
|
|
23
23
|
def calculate_chart_indicators(
|
|
24
24
|
*, rows: Any, expected_hash: str, indicators: list[str],
|
|
25
25
|
ma_periods: list[int], volume_ma: int, boll_period: int,
|
|
26
|
-
boll_std: float, rsi_period: int, atr_period: int,
|
|
26
|
+
boll_std: float, rsi_period: int, atr_period: int, ema_period: int = 20,
|
|
27
27
|
) -> dict[str, Any]:
|
|
28
28
|
if not isinstance(rows, list) or not 2 <= len(rows) <= 4000:
|
|
29
29
|
raise ValueError("indicator rows must contain 2..4000 loaded candles")
|
|
@@ -45,10 +45,12 @@ def calculate_chart_indicators(
|
|
|
45
45
|
boll_period = _period(boll_period, "boll_period")
|
|
46
46
|
rsi_period = _period(rsi_period, "rsi_period")
|
|
47
47
|
atr_period = _period(atr_period, "atr_period")
|
|
48
|
+
ema_period = _period(ema_period, "ema_period")
|
|
48
49
|
if type(boll_std) not in (int, float) or not math.isfinite(boll_std) or not 0.5 <= boll_std <= 5:
|
|
49
50
|
raise ValueError("boll_std must be a finite number from 0.5 to 5")
|
|
50
51
|
commands = build_chart_commands(
|
|
51
52
|
normalized, indicators=indicators, ma_periods=periods,
|
|
53
|
+
ema_period=ema_period,
|
|
52
54
|
volume_ma=volume_ma, boll_period=boll_period, boll_std=boll_std,
|
|
53
55
|
rsi_period=rsi_period, atr_period=atr_period,
|
|
54
56
|
)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Conservative exchange-local closed daily bars for read-only analyses."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from datetime import datetime, time, timezone
|
|
5
|
+
from zoneinfo import ZoneInfo
|
|
6
|
+
|
|
7
|
+
from core.rows import RowsValidationError, validate_rows
|
|
8
|
+
from tools.lines import LineError
|
|
9
|
+
|
|
10
|
+
MARKETS = {
|
|
11
|
+
"CN": (ZoneInfo("Asia/Shanghai"), time(15, 40)),
|
|
12
|
+
"HK": (ZoneInfo("Asia/Hong_Kong"), time(16, 20)),
|
|
13
|
+
"US": (ZoneInfo("America/New_York"), time(16, 10)),
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def market_for_symbol(symbol: str) -> str | None:
|
|
18
|
+
suffix = str(symbol or "").upper().rsplit(".", 1)[-1]
|
|
19
|
+
return "CN" if suffix in {"XSHG", "XSHE", "SH", "SZ"} else suffix if suffix in {"HK", "US"} else None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def closed_daily(rows, *, symbol: str, interval: str, source_interval: str | None = None,
|
|
23
|
+
interval_value: int | None = 1, provider: str | None = None,
|
|
24
|
+
now: datetime | None = None):
|
|
25
|
+
if interval != "day" or source_interval not in {None, "day"} or interval_value != 1:
|
|
26
|
+
raise LineError("daily_analysis_only", "形态与九转首版仅支持单日线;请在当前图切换后重新分析。")
|
|
27
|
+
try:
|
|
28
|
+
candles = validate_rows(rows, min_len=1)
|
|
29
|
+
except RowsValidationError:
|
|
30
|
+
raise LineError("daily_analysis_unavailable", "当前图缺少有效的已加载日线。") from None
|
|
31
|
+
market = market_for_symbol(symbol)
|
|
32
|
+
clock = now or datetime.now(timezone.utc)
|
|
33
|
+
if clock.tzinfo is None:
|
|
34
|
+
raise ValueError("now must be timezone-aware")
|
|
35
|
+
quality = []
|
|
36
|
+
if market is None:
|
|
37
|
+
quality.append("market_unknown_current_day_excluded")
|
|
38
|
+
# UTC prior days are surely historical regardless of the exchange zone.
|
|
39
|
+
cutoff_date = clock.astimezone(timezone.utc).date()
|
|
40
|
+
accepted = [r for r in candles if datetime.fromtimestamp(r["time"], timezone.utc).date() < cutoff_date]
|
|
41
|
+
return accepted, {"market": None, "timezone": None, "as_of": accepted[-1]["time"] if accepted else None,
|
|
42
|
+
"quality": quality, "excluded": len(candles) - len(accepted)}
|
|
43
|
+
zone, close_time = MARKETS[market]
|
|
44
|
+
local = clock.astimezone(zone)
|
|
45
|
+
accepted = []
|
|
46
|
+
for row in candles:
|
|
47
|
+
bar = datetime.fromtimestamp(row["time"], zone)
|
|
48
|
+
utc_day = datetime.fromtimestamp(row["time"], timezone.utc).date()
|
|
49
|
+
if bar.date() < local.date() and utc_day == local.date():
|
|
50
|
+
# A date-only UTC-midnight stamp for today's US session appears as
|
|
51
|
+
# yesterday evening in New York. It is not proof of a closed bar.
|
|
52
|
+
quality.append("date_semantics_uncertain_current_day_excluded")
|
|
53
|
+
elif bar.date() < local.date():
|
|
54
|
+
accepted.append(row)
|
|
55
|
+
elif bar.date() > local.date():
|
|
56
|
+
quality.append("future_daily_bar_excluded")
|
|
57
|
+
elif provider in {None, "unknown", "external"}:
|
|
58
|
+
quality.append("source_unknown_current_day_excluded")
|
|
59
|
+
elif bar.time() < time(9, 0) or bar.time() > time(23, 0):
|
|
60
|
+
quality.append("date_semantics_uncertain_current_day_excluded")
|
|
61
|
+
elif local.time() >= close_time:
|
|
62
|
+
accepted.append(row)
|
|
63
|
+
else:
|
|
64
|
+
quality.append("current_day_not_conservatively_closed")
|
|
65
|
+
return accepted, {"market": market, "timezone": zone.key,
|
|
66
|
+
"as_of": accepted[-1]["time"] if accepted else None,
|
|
67
|
+
"quality": sorted(set(quality)), "excluded": len(candles) - len(accepted),
|
|
68
|
+
"cutoff_local": close_time.strftime("%H:%M")}
|
|
@@ -16,12 +16,14 @@ from core.calc import (
|
|
|
16
16
|
DEFAULT_KDJ,
|
|
17
17
|
DEFAULT_MACD,
|
|
18
18
|
DEFAULT_MA_PERIODS,
|
|
19
|
+
DEFAULT_EMA_PERIOD,
|
|
19
20
|
DEFAULT_RSI_PERIOD,
|
|
20
21
|
DEFAULT_VOLUME_MA,
|
|
21
22
|
series_atr,
|
|
22
23
|
series_boll,
|
|
23
24
|
series_kdj,
|
|
24
25
|
series_ma,
|
|
26
|
+
series_ema,
|
|
25
27
|
series_macd,
|
|
26
28
|
series_rsi,
|
|
27
29
|
series_vwap,
|
|
@@ -30,7 +32,7 @@ from core.calc import (
|
|
|
30
32
|
from core.rows import validate_rows
|
|
31
33
|
from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION
|
|
32
34
|
|
|
33
|
-
SUPPORTED_INDICATORS = ("ma", "vwap", "vol", "macd", "kdj", "boll", "rsi", "atr")
|
|
35
|
+
SUPPORTED_INDICATORS = ("ma", "ema", "vwap", "vol", "macd", "kdj", "boll", "rsi", "atr")
|
|
34
36
|
|
|
35
37
|
|
|
36
38
|
def _safe_https_url(value: Any) -> str | None:
|
|
@@ -118,7 +120,7 @@ def _normalize_comparisons(comparisons: Any) -> list[dict[str, Any]]:
|
|
|
118
120
|
if not isinstance(comparisons, list):
|
|
119
121
|
return []
|
|
120
122
|
normalized: list[dict[str, Any]] = []
|
|
121
|
-
for item in comparisons[:
|
|
123
|
+
for item in comparisons[:12]:
|
|
122
124
|
if not isinstance(item, dict):
|
|
123
125
|
continue
|
|
124
126
|
symbol = str(item.get("symbol") or "").strip()
|
|
@@ -134,6 +136,9 @@ def _normalize_comparisons(comparisons: Any) -> list[dict[str, Any]]:
|
|
|
134
136
|
"symbol": symbol[:48],
|
|
135
137
|
"name": str(item.get("name") or symbol)[:120],
|
|
136
138
|
"rows": normalized_rows,
|
|
139
|
+
"exchange_timezone": str(item.get("exchange_timezone") or "")[:64],
|
|
140
|
+
"interval": str(item.get("interval") or "day")[:16],
|
|
141
|
+
"visible": item.get("visible") is not False,
|
|
137
142
|
}
|
|
138
143
|
)
|
|
139
144
|
return normalized
|
|
@@ -144,6 +149,7 @@ def build_chart_commands(
|
|
|
144
149
|
*,
|
|
145
150
|
indicators: list[str] | None = None,
|
|
146
151
|
ma_periods: list[int] | None = None,
|
|
152
|
+
ema_period: int = DEFAULT_EMA_PERIOD,
|
|
147
153
|
marks: Any = None,
|
|
148
154
|
lines: Any = None,
|
|
149
155
|
boll_period: int = DEFAULT_BOLL_PERIOD,
|
|
@@ -188,6 +194,14 @@ def build_chart_commands(
|
|
|
188
194
|
}
|
|
189
195
|
)
|
|
190
196
|
|
|
197
|
+
if "ema" in inds:
|
|
198
|
+
cmds.append({
|
|
199
|
+
"type": "SET_INDICATOR_SERIES", "name": "ema", "pane": "candle",
|
|
200
|
+
"params": {"period": int(ema_period)},
|
|
201
|
+
"data": {"ema": _map_to_str_keys(series_ema(rows, ema_period))},
|
|
202
|
+
"note": "data keys are unix seconds; view multiplies by 1000 for klinecharts",
|
|
203
|
+
})
|
|
204
|
+
|
|
191
205
|
if "vwap" in inds:
|
|
192
206
|
cmds.append(
|
|
193
207
|
{
|
|
@@ -329,6 +343,7 @@ def draw_kline(
|
|
|
329
343
|
indicators: list[str] | None = None,
|
|
330
344
|
indicators_explicit: bool | None = None,
|
|
331
345
|
ma_periods: list[int] | None = None,
|
|
346
|
+
ema_period: int = DEFAULT_EMA_PERIOD,
|
|
332
347
|
marks: Any = None,
|
|
333
348
|
lines: Any = None,
|
|
334
349
|
comparisons: Any = None,
|
|
@@ -352,6 +367,7 @@ def draw_kline(
|
|
|
352
367
|
norm,
|
|
353
368
|
indicators=inds,
|
|
354
369
|
ma_periods=ma_periods,
|
|
370
|
+
ema_period=ema_period,
|
|
355
371
|
marks=marks,
|
|
356
372
|
lines=lines,
|
|
357
373
|
boll_period=boll_period,
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"""Whitelisted browser object observations; never upgrade them to pixel verification."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
-
KINDS = {"horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks"}
|
|
4
|
+
KINDS = {"horizontal_line", "trend_line", "channel", "rectangle", "fibonacci_retracement", "labeled_polyline", "text_annotation", "number_annotation", "icon_annotation", "series_line", "price_band", "price_sticks", "price_pattern", "nine_count"}
|
|
5
5
|
REASONS = {
|
|
6
6
|
"created": {"overlay_registered", "outside_time_viewport", "indicator_registered"},
|
|
7
|
-
"hidden": {"period_mismatch", "anchors_not_loaded"},
|
|
7
|
+
"hidden": {"period_mismatch", "anchors_not_loaded", "snapshot_outside_loaded_history"},
|
|
8
8
|
"removed": {"overlay_removed", "indicator_removed"},
|
|
9
9
|
"failed": {"invalid_geometry", "overlay_missing", "overlay_mismatch", "overlay_still_present", "creation_failed", "indicator_missing", "indicator_still_present"},
|
|
10
10
|
"unknown": {"overlay_api_unavailable", "overlay_lookup_failed", "overlay_mismatch", "context_not_ready", "application_rolled_back", "rollback_unknown", "indicator_api_unavailable"},
|
|
@@ -4671,9 +4671,8 @@ def fetch_security_workspace(symbol: str, *, name: str | None = None, refresh: b
|
|
|
4671
4671
|
def fetch_comparison_candles(symbol: str, *, limit: int = 390) -> dict[str, Any]:
|
|
4672
4672
|
"""Fetch daily comparison data without silently changing instrument type.
|
|
4673
4673
|
|
|
4674
|
-
The browser normalizes successful series against
|
|
4675
|
-
close.
|
|
4676
|
-
error as ``fetch_candles`` until a verified A-share index source is wired.
|
|
4674
|
+
The browser normalizes successful series against a common trading-day
|
|
4675
|
+
close. Stocks, ETFs and supported indexes use the same fetch path.
|
|
4677
4676
|
"""
|
|
4678
4677
|
sym = _canonical_market_symbol(symbol)
|
|
4679
4678
|
if not sym:
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Transparent close-vs-four-back nine count; no retrospective erasure."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from tools.closed_daily import closed_daily
|
|
5
|
+
from tools.lines import LineError
|
|
6
|
+
|
|
7
|
+
RULE_VERSION = "nine_count_v1"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def nine_count(rows, *, symbol: str, interval: str = "day", source_interval: str | None = "day",
|
|
11
|
+
interval_value: int | None = 1, provider: str | None = None,
|
|
12
|
+
display_bars: int = 120, known_gap_indexes: tuple[int, ...] = (), now=None):
|
|
13
|
+
if type(display_bars) is not int or not 30 <= display_bars <= 240:
|
|
14
|
+
raise LineError("invalid_nine_count_range", "九转展示范围必须为30至240根日线。")
|
|
15
|
+
candles, metadata = closed_daily(rows, symbol=symbol, interval=interval,
|
|
16
|
+
source_interval=source_interval, interval_value=interval_value,
|
|
17
|
+
provider=provider, now=now)
|
|
18
|
+
candles = candles[-4000:]
|
|
19
|
+
gap_indexes = set(known_gap_indexes)
|
|
20
|
+
if any(type(i) is not int or i <= 0 or i >= len(candles) for i in gap_indexes):
|
|
21
|
+
raise LineError("invalid_known_gap", "已知缺失区间索引超出已加载日线范围。")
|
|
22
|
+
marks = []
|
|
23
|
+
events = []
|
|
24
|
+
direction = None
|
|
25
|
+
count = 0
|
|
26
|
+
completed = False
|
|
27
|
+
# The first observed run can predate the loaded prefix. Do not guess its count.
|
|
28
|
+
censored = True
|
|
29
|
+
encountered_censored_prefix = False
|
|
30
|
+
segment_start = 0
|
|
31
|
+
for i, bar in enumerate(candles):
|
|
32
|
+
if i in gap_indexes:
|
|
33
|
+
segment_start = i
|
|
34
|
+
direction, count, completed, censored = None, 0, False, True
|
|
35
|
+
if i - segment_start < 4:
|
|
36
|
+
continue
|
|
37
|
+
compare = bar["close"] - candles[i - 4]["close"]
|
|
38
|
+
side = "up" if compare > 0 else "down" if compare < 0 else None
|
|
39
|
+
if side is None:
|
|
40
|
+
direction, count, completed, censored = None, 0, False, False
|
|
41
|
+
continue
|
|
42
|
+
if side != direction:
|
|
43
|
+
direction, count, completed = side, 0, False
|
|
44
|
+
# A reversal gives a known restart point, even at the loaded edge.
|
|
45
|
+
if direction is not None and i > segment_start + 4:
|
|
46
|
+
censored = False
|
|
47
|
+
if censored or completed:
|
|
48
|
+
if censored:
|
|
49
|
+
encountered_censored_prefix = True
|
|
50
|
+
continue
|
|
51
|
+
count += 1
|
|
52
|
+
mark = {"time": bar["time"], "index": i, "direction": side, "count": count,
|
|
53
|
+
"label": str(count), "price": bar["high"] if side == "up" else bar["low"]}
|
|
54
|
+
marks.append(mark)
|
|
55
|
+
if count == 9:
|
|
56
|
+
completed = True
|
|
57
|
+
events.append({"time": bar["time"], "direction": side,
|
|
58
|
+
"label": "上涨九转计数完成" if side == "up" else "下跌九转计数完成"})
|
|
59
|
+
first = max(0, len(candles) - display_bars)
|
|
60
|
+
visible = [m for m in marks if m["index"] >= first]
|
|
61
|
+
return {"rule_version": RULE_VERSION, "as_of": metadata["as_of"], "data_quality": metadata,
|
|
62
|
+
"display_bars": display_bars, "loaded_bars": len(candles), "marks": visible,
|
|
63
|
+
"events": [e for e in events if e["time"] >= (candles[first]["time"] if candles else 0)],
|
|
64
|
+
"total_marks": len(marks), "truncated": len(visible) < len(marks),
|
|
65
|
+
"limitations": (["left_boundary_run_censored_until_interruption"] if encountered_censored_prefix else [])
|
|
66
|
+
+ (["known_gaps_segmented"] if gap_indexes else [])}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Atomic snapshot objects for reviewed price patterns and nine counts."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
from tools.lines import LineError, validate_line_fields
|
|
9
|
+
|
|
10
|
+
PATTERN_COMMAND = "DRAW_AGENT_PRICE_PATTERN"
|
|
11
|
+
NINE_COMMAND = "DRAW_AGENT_NINE_COUNT"
|
|
12
|
+
MAX_PATTERNS = 20
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _hash(value):
|
|
16
|
+
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
17
|
+
separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _valid_time(value, times):
|
|
21
|
+
return type(value) is int and value in times
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def edit_pattern_group(payload, action, *, kind, group_id=None, pattern=None, marks=None,
|
|
25
|
+
events=None, rule_version=None, as_of=None, name=None, color=None, request_id=None):
|
|
26
|
+
if kind not in {"price_pattern", "nine_count"}:
|
|
27
|
+
raise LineError("invalid_pattern_group", "未知形态组类型。")
|
|
28
|
+
command = PATTERN_COMMAND if kind == "price_pattern" else NINE_COMMAND
|
|
29
|
+
result = deepcopy(payload)
|
|
30
|
+
commands = result.get("chartCommands", [])
|
|
31
|
+
rows = next((c.get("rows", []) for c in commands if c.get("type") == "SET_CANDLES"), [])
|
|
32
|
+
times = {r["time"] for r in rows}
|
|
33
|
+
matches = [c for c in commands if c.get("type") == command and c.get("id") == group_id]
|
|
34
|
+
if len(matches) > 1:
|
|
35
|
+
raise LineError("ambiguous_drawing_id", "该组对象 ID 不唯一。")
|
|
36
|
+
previous = matches[0] if matches else None
|
|
37
|
+
if action != "create" and previous is None:
|
|
38
|
+
raise LineError("pattern_group_not_found", "当前图没有该组对象。")
|
|
39
|
+
if action == "delete":
|
|
40
|
+
if any(v is not None for v in (pattern, marks, events, rule_version, as_of, name, color)):
|
|
41
|
+
raise LineError("invalid_edit_fields", "删除组对象只能提供对象 ID。")
|
|
42
|
+
commands.remove(previous)
|
|
43
|
+
return result, deepcopy(previous)
|
|
44
|
+
if action not in {"create", "update"}:
|
|
45
|
+
raise LineError("invalid_action", "不支持的组对象操作。")
|
|
46
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
47
|
+
supplied = pattern is not None if kind == "price_pattern" else marks is not None
|
|
48
|
+
if action == "create" and not supplied:
|
|
49
|
+
raise LineError("analysis_result_required", "保存分析结果必须提供当前有效引用。")
|
|
50
|
+
if not supplied and any(v is not None for v in (events, rule_version, as_of)):
|
|
51
|
+
raise LineError("analysis_result_required", "更新几何必须重新分析并提供完整结果引用。")
|
|
52
|
+
if action == "update" and not supplied and name is None and color is None:
|
|
53
|
+
raise LineError("empty_update", "请提供名称、颜色或新分析结果。")
|
|
54
|
+
if supplied:
|
|
55
|
+
if not isinstance(rule_version, str) or rule_version not in {"price_patterns_v1", "nine_count_v1"}:
|
|
56
|
+
raise LineError("invalid_pattern_version", "规则版本无效。")
|
|
57
|
+
if not _valid_time(as_of, times):
|
|
58
|
+
raise LineError("analysis_result_stale", "分析截止日已不在当前加载范围,请重新分析。")
|
|
59
|
+
if kind == "price_pattern":
|
|
60
|
+
if not isinstance(pattern, dict) or pattern.get("type") not in {"double_top", "double_bottom", "head_shoulders_top", "head_shoulders_bottom", "platform"}:
|
|
61
|
+
raise LineError("invalid_pattern_geometry", "价格形态结构无效。")
|
|
62
|
+
anchors = pattern.get("anchors")
|
|
63
|
+
if not isinstance(anchors, list) or any(not isinstance(a, dict) or not _valid_time(a.get("time"), times) for a in anchors):
|
|
64
|
+
raise LineError("analysis_result_stale", "形态锚点已不在当前加载范围,请重新分析。")
|
|
65
|
+
if pattern["type"] == "platform" and pattern.get("box", {}).get("start_time") not in times:
|
|
66
|
+
raise LineError("analysis_result_stale", "平台形成区间已不在当前加载范围,请重新分析。")
|
|
67
|
+
geometry = {"pattern": deepcopy(pattern)}
|
|
68
|
+
else:
|
|
69
|
+
if not isinstance(marks, list) or not 1 <= len(marks) <= 240 or not isinstance(events, list):
|
|
70
|
+
raise LineError("invalid_nine_geometry", "九转标注序列无效。")
|
|
71
|
+
if any(not isinstance(m, dict) or not _valid_time(m.get("time"), times)
|
|
72
|
+
or m.get("direction") not in {"up", "down"} or type(m.get("count")) is not int
|
|
73
|
+
or not 1 <= m["count"] <= 9 for m in marks):
|
|
74
|
+
raise LineError("invalid_nine_geometry", "九转标注与当前日线不一致。")
|
|
75
|
+
geometry = {"marks": deepcopy(marks), "events": deepcopy(events)}
|
|
76
|
+
else:
|
|
77
|
+
geometry = {"pattern": deepcopy(previous["pattern"])} if kind == "price_pattern" else {
|
|
78
|
+
"marks": deepcopy(previous["marks"]), "events": deepcopy(previous["events"])}
|
|
79
|
+
rule_version, as_of = previous["rule_version"], previous["as_of"]
|
|
80
|
+
obj = {"type": command, "id": previous["id"] if previous else ("pattern_" if kind == "price_pattern" else "nine_") + _hash(request_id or "")[:24],
|
|
81
|
+
"interval": payload.get("interval"), "rule_version": rule_version, "as_of": as_of,
|
|
82
|
+
"geometry_hash": _hash({"rule_version": rule_version, "as_of": as_of, **geometry}),
|
|
83
|
+
"bar_count": len(geometry["marks"]) if kind == "nine_count" else len(geometry["pattern"].get("anchors", [])),
|
|
84
|
+
"label": name if name is not None else previous.get("label", "") if previous else "",
|
|
85
|
+
"color": color if color is not None else previous.get("color", "info") if previous else "info", **geometry}
|
|
86
|
+
if previous and previous.get("create_request_id"):
|
|
87
|
+
obj["create_request_id"] = previous["create_request_id"]
|
|
88
|
+
if action == "create":
|
|
89
|
+
if not request_id:
|
|
90
|
+
raise LineError("request_id_required", "组对象创建需要稳定请求 ID。")
|
|
91
|
+
obj["create_request_id"] = request_id
|
|
92
|
+
retry = next((c for c in commands if c.get("type") == command and c.get("create_request_id") == request_id), None)
|
|
93
|
+
if retry:
|
|
94
|
+
if retry != obj:
|
|
95
|
+
raise LineError("request_conflict", "同一请求 ID 的组对象参数不同。")
|
|
96
|
+
return result, deepcopy(retry)
|
|
97
|
+
limit = MAX_PATTERNS if kind == "price_pattern" else 1
|
|
98
|
+
if sum(c.get("type") == command and c.get("interval") == payload.get("interval") for c in commands) >= limit:
|
|
99
|
+
raise LineError("too_many_pattern_groups", "当前图的形态或九转组对象已达上限。")
|
|
100
|
+
commands.append(obj)
|
|
101
|
+
else:
|
|
102
|
+
commands[commands.index(previous)] = obj
|
|
103
|
+
return result, deepcopy(obj)
|