@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +601 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +116 -0
- package/README.md +115 -2
- package/chart_service.py +687 -0
- package/config/basic-symbols.json +570 -0
- package/config/dsh-kline.patch.yml +4 -0
- package/config/dsh-tool-catalog.json +3875 -0
- package/cordis.patch.yml +33 -0
- package/core/__init__.py +0 -0
- package/core/adjustment.py +16 -0
- package/core/calc.py +691 -0
- package/core/rows.py +228 -0
- package/core/ta_engine.py +99 -0
- package/docs/anonymous-market-support.md +33 -0
- package/docs/automatic-drawing.md +24 -0
- package/docs/chart-functions.md +136 -0
- package/docs/drawing-examples.en.md +13 -0
- package/docs/drawing-examples.md +13 -0
- package/docs/embedding.md +43 -0
- package/docs/fixtures/price-pattern-real-v1.json +1 -0
- package/docs/free-foreign-daily.md +44 -0
- package/docs/guide.en.md +232 -0
- package/docs/guide.md +248 -0
- package/docs/images/abc-drawing-v0.5.0.jpg +0 -0
- package/docs/images/channel-drawing-v0.5.0.jpg +0 -0
- package/docs/images/drawing-workbench-v0.5.0.jpg +0 -0
- package/docs/images/dsh-kline-tab-workspace.png +0 -0
- package/docs/images/dsh-market.png +0 -0
- package/docs/images/kline-news.png +0 -0
- package/docs/images/kline-range-stats.png +0 -0
- package/docs/images/kline-support.png +0 -0
- package/docs/images/main-chart-comparison-v0.6.9.png +0 -0
- package/docs/images/market-overview-v0.6.9.png +0 -0
- package/docs/images/natural-language-abc-wolong-2026-10-27.png +0 -0
- package/docs/images/natural-language-descending-channel-wolong-2026-10-27.png +0 -0
- package/docs/images/platform-breakout-msft-v0.6.9.png +0 -0
- package/docs/npm-release.md +33 -0
- package/docs/price-pattern-rules-v1.md +40 -0
- package/docs/price-pattern-samples-v1.md +42 -0
- package/docs/provider-adaptation.md +73 -0
- package/docs/release-acceptance-v0.4.0.md +46 -0
- package/docs/release-acceptance-v0.4.1.md +43 -0
- package/docs/release-acceptance-v0.5.0.md +40 -0
- package/docs/release-acceptance-v0.6.0.md +33 -0
- package/docs/release-acceptance-v0.6.1.md +19 -0
- package/docs/release-acceptance-v0.6.10.md +21 -0
- package/docs/release-acceptance-v0.6.2.md +31 -0
- package/docs/release-acceptance-v0.6.3.md +25 -0
- package/docs/release-acceptance-v0.6.4.md +24 -0
- package/docs/release-acceptance-v0.6.5.md +21 -0
- package/docs/release-acceptance-v0.6.6.md +21 -0
- package/docs/release-acceptance-v0.6.7.md +18 -0
- package/docs/release-acceptance-v0.6.8.md +18 -0
- package/docs/release-acceptance-v0.6.9.md +98 -0
- package/docs/release-notes-v0.5.0.md +23 -0
- package/docs/release-notes-v0.6.0.md +11 -0
- package/docs/release-notes-v0.6.1.md +20 -0
- package/docs/release-notes-v0.6.10.md +11 -0
- package/docs/release-notes-v0.6.2.md +14 -0
- package/docs/release-notes-v0.6.3.md +26 -0
- package/docs/release-notes-v0.6.4.md +12 -0
- package/docs/release-notes-v0.6.5.md +13 -0
- package/docs/release-notes-v0.6.6.md +13 -0
- package/docs/release-notes-v0.6.7.md +17 -0
- package/docs/release-notes-v0.6.8.md +10 -0
- package/docs/release-notes-v0.6.9.md +16 -0
- package/lib/candle-sequence.js +15 -0
- package/lib/chart-adjustment.js +7 -0
- package/lib/chart-annotations.js +33 -0
- package/lib/chart-applications.js +171 -0
- package/lib/chart-context.js +164 -0
- package/lib/chart-observation.js +251 -0
- package/lib/chart-service-status.js +82 -0
- package/lib/chart-source-status.js +39 -0
- package/lib/chart-sources.js +354 -0
- package/lib/client/BetterSidebarTab.js +70 -0
- package/lib/client/ClassicShell.js +254 -0
- package/lib/client/KlineContent.js +155 -0
- package/lib/client/chart-apply.js +73 -0
- package/lib/client/chart-context.js +233 -0
- package/lib/client/chart-handoff.js +34 -0
- package/lib/client/chart-session-resolver.js +74 -0
- package/lib/client/client-context.js +1 -0
- package/lib/client/conversation.js +88 -0
- package/lib/client/default-tab.js +83 -0
- package/lib/client/embed.js +50 -0
- package/lib/client/generated-view.js +12983 -0
- package/lib/client/horizontal-lines.js +19 -0
- package/lib/client/index.js +62 -0
- package/lib/client/mode-preferences.js +28 -0
- package/lib/client/native-sidebar-contract.js +45 -0
- package/lib/client/native-sidebar-register.js +133 -0
- package/lib/client/native-sidebar-services.js +1 -0
- package/lib/client/native-sidebar.js +96 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +42 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17382 -0
- package/lib/client.js.map +1 -0
- package/lib/drawing-feedback.js +284 -0
- package/lib/fibonacci.js +18 -0
- package/lib/ftshare-settings-bridge.js +159 -0
- package/lib/index.js +279 -0
- package/lib/labeled-polyline.js +17 -0
- package/lib/pattern-groups.js +91 -0
- package/lib/price-bands.js +55 -0
- package/lib/price-series.js +47 -0
- package/lib/price-sticks.js +32 -0
- package/lib/types/candle-sequence.d.ts +2 -0
- package/lib/types/chart-adjustment.d.ts +2 -0
- package/lib/types/chart-annotations.d.ts +4 -0
- package/lib/types/chart-applications.d.ts +26 -0
- package/lib/types/chart-context.d.ts +14 -0
- package/lib/types/chart-observation.d.ts +8 -0
- package/lib/types/chart-service-status.d.ts +22 -0
- package/lib/types/chart-source-status.d.ts +47 -0
- package/lib/types/chart-sources.d.ts +25 -0
- package/lib/types/client/BetterSidebarTab.d.ts +12 -0
- package/lib/types/client/ClassicShell.d.ts +4 -0
- package/lib/types/client/KlineContent.d.ts +37 -0
- package/lib/types/client/chart-apply.d.ts +13 -0
- package/lib/types/client/chart-context.d.ts +23 -0
- package/lib/types/client/chart-handoff.d.ts +5 -0
- package/lib/types/client/chart-session-resolver.d.ts +2 -0
- package/lib/types/client/client-context.d.ts +14 -0
- package/lib/types/client/conversation.d.ts +43 -0
- package/lib/types/client/default-tab.d.ts +3 -0
- package/lib/types/client/embed.d.ts +37 -0
- package/lib/types/client/generated-view.d.ts +2 -0
- package/lib/types/client/horizontal-lines.d.ts +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +13 -0
- package/lib/types/client/native-sidebar-contract.d.ts +52 -0
- package/lib/types/client/native-sidebar-register.d.ts +46 -0
- package/lib/types/client/native-sidebar-services.d.ts +45 -0
- package/lib/types/client/native-sidebar.d.ts +47 -0
- package/lib/types/client/sidebar-integration.d.ts +12 -0
- package/lib/types/client/ui-onboarding.d.ts +6 -0
- package/lib/types/client/version.d.ts +1 -0
- package/lib/types/drawing-feedback.d.ts +5 -0
- package/lib/types/fibonacci.d.ts +5 -0
- package/lib/types/ftshare-settings-bridge.d.ts +50 -0
- package/lib/types/index.d.ts +26 -0
- package/lib/types/labeled-polyline.d.ts +11 -0
- package/lib/types/pattern-groups.d.ts +2 -0
- package/lib/types/price-bands.d.ts +3 -0
- package/lib/types/price-series.d.ts +5 -0
- package/lib/types/price-sticks.d.ts +3 -0
- package/package.json +153 -4
- package/requirements.txt +6 -0
- package/screenshots.json +11 -0
- package/scripts/bootstrap.sh +5 -0
- package/scripts/dsh-bootstrap.mjs +179 -0
- package/scripts/dsh-mcp-plugin.mjs +27 -0
- package/scripts/run-dsh-kline.mjs +658 -0
- package/scripts/run-dsh-kline.sh +5 -0
- package/server.py +1755 -0
- package/tools/__init__.py +0 -0
- package/tools/annotations.py +119 -0
- package/tools/automatic_analysis.py +158 -0
- package/tools/baostock_source.py +176 -0
- package/tools/calc.py +39 -0
- package/tools/channel_candidates.py +260 -0
- package/tools/channel_preview.py +82 -0
- package/tools/channels.py +104 -0
- package/tools/chart_applications.py +204 -0
- package/tools/chart_context.py +186 -0
- package/tools/chart_edits.py +363 -0
- package/tools/chart_functions.py +451 -0
- package/tools/chart_indicators.py +65 -0
- package/tools/chart_measurements.py +84 -0
- package/tools/chart_source_status.py +32 -0
- package/tools/chart_sources.py +31 -0
- package/tools/closed_daily.py +68 -0
- package/tools/draw.py +410 -0
- package/tools/drawing_feedback.py +45 -0
- package/tools/drawing_interaction.py +117 -0
- package/tools/drawing_verification.py +141 -0
- package/tools/fetch.py +4680 -0
- package/tools/fibonacci.py +83 -0
- package/tools/foreign_daily.py +185 -0
- package/tools/free_sources.py +483 -0
- package/tools/lines.py +91 -0
- package/tools/nine_count.py +66 -0
- package/tools/pattern_groups.py +103 -0
- package/tools/pivots.py +60 -0
- package/tools/polylines.py +131 -0
- package/tools/price_bands.py +165 -0
- package/tools/price_patterns.py +311 -0
- package/tools/price_series.py +162 -0
- package/tools/price_sticks.py +114 -0
- package/tools/range_candidates.py +170 -0
- package/tools/recent_drawing_candidates.py +123 -0
- package/tools/rectangles.py +76 -0
- package/tools/regression_channels.py +87 -0
- package/tools/ta_functions.py +228 -0
- package/tools/trend_lines.py +106 -0
- package/tools/watchlist.py +149 -0
- package/view/ft-logo.jpg +0 -0
- package/view/kline.html +12436 -0
- package/view/vendor/klinecharts.min.js +7 -0
|
@@ -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)
|
package/tools/pivots.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Deterministic, confirmed local-extremum candidates on loaded candles."""
|
|
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
|
+
|
|
10
|
+
def confirmed_pivots(rows, *, left_bars=2, right_bars=2, mode="both", limit=20):
|
|
11
|
+
"""Return strict local highs/lows with complete left and right windows.
|
|
12
|
+
|
|
13
|
+
Equal highs/lows are deliberately not pivots. Only bars with all right-side
|
|
14
|
+
confirmation bars present are considered. Results are chronological, limited
|
|
15
|
+
to the newest ``limit`` candidates, with no alternation or trend inference.
|
|
16
|
+
"""
|
|
17
|
+
if type(left_bars) is not int or not 1 <= left_bars <= 20:
|
|
18
|
+
raise LineError("invalid_pivot_window", "left_bars 必须是1至20的整数。")
|
|
19
|
+
if type(right_bars) is not int or not 1 <= right_bars <= 20:
|
|
20
|
+
raise LineError("invalid_pivot_window", "right_bars 必须是1至20的整数。")
|
|
21
|
+
if mode not in {"high", "low", "both"}:
|
|
22
|
+
raise LineError("invalid_pivot_mode", "mode 只能是 high、low 或 both。")
|
|
23
|
+
if type(limit) is not int or not 1 <= limit <= 50:
|
|
24
|
+
raise LineError("invalid_pivot_limit", "limit 必须是1至50的整数。")
|
|
25
|
+
try:
|
|
26
|
+
candles = validate_rows(rows, min_len=left_bars + right_bars + 1)
|
|
27
|
+
except RowsValidationError:
|
|
28
|
+
raise LineError("insufficient_pivot_history", "已加载K线不足以提供完整左右确认窗口;未补取行情。") from None
|
|
29
|
+
|
|
30
|
+
candidates = []
|
|
31
|
+
for index in range(left_bars, len(candles) - right_bars):
|
|
32
|
+
row = candles[index]
|
|
33
|
+
left = candles[index - left_bars:index]
|
|
34
|
+
right = candles[index + 1:index + right_bars + 1]
|
|
35
|
+
high = float(row["high"])
|
|
36
|
+
low = float(row["low"])
|
|
37
|
+
if not math.isfinite(high) or not math.isfinite(low):
|
|
38
|
+
raise LineError("invalid_pivot_data", "K线高低价必须是有限数值。")
|
|
39
|
+
neighbors = left + right
|
|
40
|
+
if mode in {"high", "both"} and all(high > float(item["high"]) for item in neighbors):
|
|
41
|
+
candidates.append({"side": "high", "time": str(row["time"]), "price": high,
|
|
42
|
+
"bars_ago": len(candles) - 1 - index})
|
|
43
|
+
if mode in {"low", "both"} and all(low < float(item["low"]) for item in neighbors):
|
|
44
|
+
candidates.append({"side": "low", "time": str(row["time"]), "price": low,
|
|
45
|
+
"bars_ago": len(candles) - 1 - index})
|
|
46
|
+
|
|
47
|
+
selected = candidates[-limit:]
|
|
48
|
+
return {
|
|
49
|
+
"left_bars": left_bars,
|
|
50
|
+
"right_bars": right_bars,
|
|
51
|
+
"mode": mode,
|
|
52
|
+
"limit": limit,
|
|
53
|
+
"candidates": selected,
|
|
54
|
+
"candidate_count": len(selected),
|
|
55
|
+
"total_candidates": len(candidates),
|
|
56
|
+
"truncated": len(selected) < len(candidates),
|
|
57
|
+
"rule": "strict_local_extremum",
|
|
58
|
+
"tie_policy": "equal_neighbor_is_not_a_pivot",
|
|
59
|
+
"confirmation": "complete_right_window_only",
|
|
60
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Explicit labeled time/price paths, not automatic wave recognition."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import secrets
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
9
|
+
|
|
10
|
+
from tools.lines import LineError, validate_line_fields
|
|
11
|
+
from tools.trend_lines import resolve_anchor_time
|
|
12
|
+
|
|
13
|
+
POLYLINE_COMMAND = "DRAW_AGENT_POLYLINE"
|
|
14
|
+
MAX_POINTS = 8
|
|
15
|
+
MAX_POLYLINES = 30
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class LabeledPoint(BaseModel):
|
|
19
|
+
model_config = ConfigDict(extra="forbid")
|
|
20
|
+
label: str = Field(min_length=1, max_length=16, description="点名,组内唯一,例如 A、B、C 或 1、2;不是自动识浪结果")
|
|
21
|
+
time: str = Field(min_length=1, description="已加载 K 线的日期、带时区 ISO 或 Unix 秒字符串")
|
|
22
|
+
price: float = Field(gt=0, allow_inf_nan=False, strict=True)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_point_label(label):
|
|
26
|
+
if (not isinstance(label, str) or not 1 <= len(label.strip()) <= 16
|
|
27
|
+
or any(ord(c) < 32 for c in label)):
|
|
28
|
+
raise LineError("invalid_point_label", "点名需为1至16个字符,不能空白或包含控制字符。")
|
|
29
|
+
return label.strip()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def validate_stored_points(points):
|
|
33
|
+
"""Whitelist canonical object fields; never sort, truncate or repair a path."""
|
|
34
|
+
if not isinstance(points, list) or not 2 <= len(points) <= MAX_POINTS:
|
|
35
|
+
raise LineError("invalid_polyline_points", "折线需要2至8个明确的带标签锚点。")
|
|
36
|
+
cleaned = []
|
|
37
|
+
for point in points:
|
|
38
|
+
if not isinstance(point, dict) or type(point.get("time")) is not int or point["time"] <= 0:
|
|
39
|
+
raise LineError("invalid_polyline_points", "折线锚点时间格式无效。")
|
|
40
|
+
label = normalize_point_label(point.get("label"))
|
|
41
|
+
price, _, _ = validate_line_fields(price=point.get("price"))
|
|
42
|
+
if price is None: raise LineError("invalid_price", "每个折线锚点都需要明确价格。")
|
|
43
|
+
cleaned.append({"label": label, "time": point["time"], "price": price})
|
|
44
|
+
if len({p["label"] for p in cleaned}) != len(cleaned):
|
|
45
|
+
raise LineError("duplicate_point_label", "同组点名必须唯一,不能按重复标签猜点。")
|
|
46
|
+
if any(a["time"] >= b["time"] for a, b in zip(cleaned, cleaned[1:])):
|
|
47
|
+
raise LineError("invalid_anchor_order", "折线锚点时间必须递增;不自动排序或交换点位。")
|
|
48
|
+
return cleaned
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def resolve_points(payload, points):
|
|
52
|
+
if not isinstance(points, list) or not 2 <= len(points) <= MAX_POINTS:
|
|
53
|
+
raise LineError("invalid_polyline_points", "折线需要2至8个明确的带标签锚点。")
|
|
54
|
+
resolved = []
|
|
55
|
+
for raw in points:
|
|
56
|
+
point = raw.model_dump() if isinstance(raw, LabeledPoint) else raw
|
|
57
|
+
if not isinstance(point, dict) or set(point) != {"label", "time", "price"}:
|
|
58
|
+
raise LineError("invalid_polyline_points", "每个锚点只包含 label、time、price。")
|
|
59
|
+
resolved.append({**point, "time": resolve_anchor_time(payload, point["time"])})
|
|
60
|
+
return validate_stored_points(resolved)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def edit_polyline(payload, action, *, polyline_id=None, points=None, point_label=None,
|
|
64
|
+
point_time=None, point_price=None, name=None, color=None, request_id=None,
|
|
65
|
+
replace_from_result=False):
|
|
66
|
+
result = deepcopy(payload)
|
|
67
|
+
commands = result.get("chartCommands", [])
|
|
68
|
+
matches = [c for c in commands if c.get("type") == POLYLINE_COMMAND and c.get("id") == polyline_id]
|
|
69
|
+
if len(matches) > 1:
|
|
70
|
+
raise LineError("ambiguous_drawing_id", "同一对象 ID 不唯一,不能安全修改。")
|
|
71
|
+
previous = matches[0] if matches else None
|
|
72
|
+
if action in {"update", "delete"} and previous is None:
|
|
73
|
+
raise LineError("polyline_not_found", "当前快照不存在该 AI 标注折线,请先读回完整对象 ID。")
|
|
74
|
+
if action == "delete":
|
|
75
|
+
if any(v is not None for v in (points, point_label, point_time, point_price, name, color)):
|
|
76
|
+
raise LineError("invalid_edit_fields", "删除整组只需对象 ID。")
|
|
77
|
+
commands.remove(previous)
|
|
78
|
+
return result, deepcopy(previous)
|
|
79
|
+
if action not in {"create", "update"}:
|
|
80
|
+
raise LineError("invalid_action", "不支持的标注折线操作。")
|
|
81
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
82
|
+
if action == "create":
|
|
83
|
+
if any(v is not None for v in (point_label, point_time, point_price)):
|
|
84
|
+
raise LineError("invalid_edit_fields", "创建需完整 points,单点修改字段只用于更新。")
|
|
85
|
+
path = resolve_points(payload, points)
|
|
86
|
+
else:
|
|
87
|
+
# Updating one point must not require the LLM to copy/reconstruct its
|
|
88
|
+
# neighbours. Full replacement/point insertion/removal are out of scope.
|
|
89
|
+
if points is not None and not replace_from_result:
|
|
90
|
+
raise LineError("polyline_replacement_not_supported", "续改请用 point_label 及 point_time / point_price,仅改目标点;不接受整组重写。")
|
|
91
|
+
if replace_from_result:
|
|
92
|
+
if points is None or any(v is not None for v in (point_label, point_time, point_price)):
|
|
93
|
+
raise LineError("invalid_edit_fields", "结果引用替换整组时不能混用单点修改字段。")
|
|
94
|
+
path = resolve_points(payload, points)
|
|
95
|
+
else:
|
|
96
|
+
path = validate_stored_points(previous["points"])
|
|
97
|
+
if not replace_from_result and point_label is not None:
|
|
98
|
+
label = normalize_point_label(point_label)
|
|
99
|
+
if point_time is None and point_price is None:
|
|
100
|
+
raise LineError("empty_point_update", "请明确目标点的新时间或价格,不能猜移动幅度。")
|
|
101
|
+
target = next((p for p in path if p["label"] == label), None)
|
|
102
|
+
if target is None:
|
|
103
|
+
raise LineError("point_not_found", "当前组内不存在该点名;请核对点名,不按位置或近似名称猜点。")
|
|
104
|
+
if point_time is not None: target["time"] = resolve_anchor_time(payload, point_time)
|
|
105
|
+
if point_price is not None: target["price"] = validate_line_fields(price=point_price)[0]
|
|
106
|
+
elif not replace_from_result and (point_time is not None or point_price is not None):
|
|
107
|
+
raise LineError("point_label_required", "修改单点必须明确组内 point_label。")
|
|
108
|
+
elif not replace_from_result and name is None and color is None:
|
|
109
|
+
raise LineError("empty_update", "请指定点名及新时间 / 价格,或整组名称 / 颜色。")
|
|
110
|
+
path = validate_stored_points(path)
|
|
111
|
+
for point in path: resolve_anchor_time(payload, str(point["time"]))
|
|
112
|
+
obj = {"type": POLYLINE_COMMAND, "id": previous["id"] if previous else "poly_" + secrets.token_hex(12),
|
|
113
|
+
"interval": payload.get("interval"), "points": path,
|
|
114
|
+
"label": name if name is not None else previous["label"] if previous else "",
|
|
115
|
+
"color": color if color is not None else previous["color"] if previous else "info"}
|
|
116
|
+
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
117
|
+
if action == "create":
|
|
118
|
+
if request_id:
|
|
119
|
+
obj["create_request_id"] = request_id
|
|
120
|
+
obj["id"] = "poly_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
121
|
+
retry = next((c for c in commands if c.get("type") == POLYLINE_COMMAND and c.get("create_request_id") == request_id), None)
|
|
122
|
+
if retry:
|
|
123
|
+
if any(retry.get(k) != obj[k] for k in ("points", "label", "color", "interval")):
|
|
124
|
+
raise LineError("request_conflict", "同一 request_id 的标注折线参数不同。")
|
|
125
|
+
return result, deepcopy(retry)
|
|
126
|
+
if sum(c.get("type") == POLYLINE_COMMAND for c in commands) >= MAX_POLYLINES:
|
|
127
|
+
raise LineError("too_many_polylines", "当前图表最多保存30组 AI 标注折线。")
|
|
128
|
+
commands.append(obj)
|
|
129
|
+
else:
|
|
130
|
+
commands[commands.index(previous)] = obj
|
|
131
|
+
return result, deepcopy(obj)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Bounded, candle-aligned fill between two deterministic price sources."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import secrets
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
|
|
13
|
+
from tools.lines import LineError, validate_line_fields
|
|
14
|
+
from tools.price_series import PriceCondition, PriceSource, calculate_price_series, candle_sequence_hash, MAX_SERIES_BARS
|
|
15
|
+
|
|
16
|
+
BAND_COMMAND = "DRAW_AGENT_PRICE_BAND"
|
|
17
|
+
MAX_PRICE_BANDS = 4
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BollBandSource(BaseModel):
|
|
21
|
+
"""Metadata for one selected TA-Lib BBANDS group, not host-supplied prices."""
|
|
22
|
+
model_config = ConfigDict(extra="forbid")
|
|
23
|
+
kind: Literal["bbands"]
|
|
24
|
+
output: Literal["upperband", "lowerband"]
|
|
25
|
+
period: int = Field(strict=True, ge=2, le=200)
|
|
26
|
+
deviation_up: float = Field(gt=0, le=5, allow_inf_nan=False)
|
|
27
|
+
deviation_down: float = Field(gt=0, le=5, allow_inf_nan=False)
|
|
28
|
+
matype: Literal[0] = 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _band_source(value, output):
|
|
32
|
+
if isinstance(value, dict) and value.get("kind") == "bbands":
|
|
33
|
+
source = BollBandSource.model_validate(value).model_dump()
|
|
34
|
+
if source["output"] != output:
|
|
35
|
+
raise LineError("invalid_boll_source", "BOLL 上下轨来源不匹配。")
|
|
36
|
+
return source
|
|
37
|
+
return PriceSource.model_validate(value).model_dump(exclude_none=True)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _middle_values(values, lower, upper):
|
|
41
|
+
if not isinstance(values, list) or len(values) != len(lower):
|
|
42
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨长度与当前K线不一致。")
|
|
43
|
+
for middle, low, high in zip(values, lower, upper):
|
|
44
|
+
if low is None:
|
|
45
|
+
if middle is None: continue
|
|
46
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨空值须与上下轨同步。")
|
|
47
|
+
if (type(middle) not in (int, float) or not math.isfinite(middle)
|
|
48
|
+
or not low < middle < high):
|
|
49
|
+
raise LineError("invalid_boll_middle", "BOLL 中轨必须在有效上下轨之间,空值须同步。")
|
|
50
|
+
return list(values)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def calculate_price_band(rows, upper_source: PriceSource, lower_source: PriceSource,
|
|
54
|
+
condition: PriceCondition | None = None):
|
|
55
|
+
upper = calculate_price_series(rows, upper_source, condition)["values"]
|
|
56
|
+
lower = calculate_price_series(rows, lower_source, condition)["values"]
|
|
57
|
+
upper_values, lower_values = [], []
|
|
58
|
+
for high, low in zip(upper, lower):
|
|
59
|
+
if high is None or low is None:
|
|
60
|
+
upper_values.append(None); lower_values.append(None)
|
|
61
|
+
elif high <= low:
|
|
62
|
+
raise LineError("invalid_price_band_order", "条件命中的上下边界必须严格保持上方高于下方;未交换或忽略交叉K线。")
|
|
63
|
+
else:
|
|
64
|
+
upper_values.append(high); lower_values.append(low)
|
|
65
|
+
matches = sum(value is not None for value in upper_values)
|
|
66
|
+
segments = sum(value is not None and (index == 0 or upper_values[index - 1] is None)
|
|
67
|
+
for index, value in enumerate(upper_values))
|
|
68
|
+
return {"upper_values": upper_values, "lower_values": lower_values,
|
|
69
|
+
"summary": {"loaded_bars": len(rows), "matched_bars": matches,
|
|
70
|
+
"segment_count": segments, "empty": matches == 0,
|
|
71
|
+
"warmup_or_condition_gaps": len(rows) - matches, "drawing_created": False}}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def validate_band_values(upper_values, lower_values, count):
|
|
75
|
+
if (type(count) is not int or not 1 <= count <= MAX_SERIES_BARS
|
|
76
|
+
or not isinstance(upper_values, list) or not isinstance(lower_values, list)
|
|
77
|
+
or len(upper_values) != count or len(lower_values) != count):
|
|
78
|
+
raise LineError("invalid_price_band_values", "带状序列长度与当前K线不一致。")
|
|
79
|
+
for high, low in zip(upper_values, lower_values):
|
|
80
|
+
if high is None and low is None: continue
|
|
81
|
+
if (type(high) not in (int, float) or type(low) not in (int, float)
|
|
82
|
+
or not math.isfinite(high) or not math.isfinite(low) or low <= 0 or high <= low):
|
|
83
|
+
raise LineError("invalid_price_band_values", "带状边界无效或空值未成对出现。")
|
|
84
|
+
if not any(value is not None for value in upper_values):
|
|
85
|
+
raise LineError("empty_price_band", "条件没有命中可填充K线,未创建空带。")
|
|
86
|
+
return list(upper_values), list(lower_values)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def edit_price_band(payload, action, *, band_id=None, upper_source=None, lower_source=None,
|
|
90
|
+
condition=None, upper_values=None, lower_values=None, middle_values=None, name=None, color=None,
|
|
91
|
+
request_id=None):
|
|
92
|
+
result = deepcopy(payload)
|
|
93
|
+
commands = result.get("chartCommands", [])
|
|
94
|
+
rows = next((c.get("rows", []) for c in commands if c.get("type") == "SET_CANDLES"), [])
|
|
95
|
+
matches = [c for c in commands if c.get("type") == BAND_COMMAND and c.get("id") == band_id]
|
|
96
|
+
if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一带状对象 ID 不唯一。")
|
|
97
|
+
previous = matches[0] if matches else None
|
|
98
|
+
if action in {"update", "delete"} and previous is None:
|
|
99
|
+
raise LineError("price_band_not_found", "当前图不存在该 AI 带状对象。")
|
|
100
|
+
if action == "delete":
|
|
101
|
+
if any(value is not None for value in (upper_source, lower_source, condition, upper_values,
|
|
102
|
+
lower_values, middle_values, name, color)):
|
|
103
|
+
raise LineError("invalid_edit_fields", "删除带状对象只需对象 ID。")
|
|
104
|
+
commands.remove(previous)
|
|
105
|
+
return result, deepcopy(previous)
|
|
106
|
+
if action not in {"create", "update"}: raise LineError("invalid_action", "不支持的带状对象操作。")
|
|
107
|
+
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
108
|
+
supplied = [upper_source, lower_source, upper_values, lower_values]
|
|
109
|
+
if action == "create" and any(value is None for value in supplied):
|
|
110
|
+
raise LineError("band_result_required", "创建带状对象必须使用完整函数结果引用。")
|
|
111
|
+
if any(value is None for value in supplied) and any(value is not None for value in supplied):
|
|
112
|
+
raise LineError("band_result_required", "修改边界或条件时须重新运行函数并使用完整结果引用。")
|
|
113
|
+
if all(value is None for value in supplied) and middle_values is not None:
|
|
114
|
+
raise LineError("band_result_required", "修改 BOLL 中轨必须重新运行函数并使用完整结果引用。")
|
|
115
|
+
if action == "update" and all(value is None for value in supplied) and name is None and color is None:
|
|
116
|
+
raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
|
|
117
|
+
if all(value is not None for value in supplied):
|
|
118
|
+
upper_values, lower_values = validate_band_values(upper_values, lower_values, len(rows))
|
|
119
|
+
upper_source = _band_source(upper_source, "upperband")
|
|
120
|
+
lower_source = _band_source(lower_source, "lowerband")
|
|
121
|
+
is_boll = upper_source["kind"] == "bbands"
|
|
122
|
+
if is_boll != (lower_source["kind"] == "bbands"):
|
|
123
|
+
raise LineError("invalid_boll_source", "BOLL 上下轨必须来自同一组计算。")
|
|
124
|
+
if is_boll:
|
|
125
|
+
if (condition is not None or {k: v for k, v in upper_source.items() if k != "output"}
|
|
126
|
+
!= {k: v for k, v in lower_source.items() if k != "output"}):
|
|
127
|
+
raise LineError("invalid_boll_source", "BOLL 上中下轨必须使用同一函数参数且不可附加条件。")
|
|
128
|
+
middle_values = _middle_values(middle_values, lower_values, upper_values)
|
|
129
|
+
elif middle_values is not None:
|
|
130
|
+
raise LineError("invalid_boll_middle", "普通价带不能附带 BOLL 中轨。")
|
|
131
|
+
condition = PriceCondition.model_validate(condition).model_dump(exclude_none=True) if condition is not None else None
|
|
132
|
+
else:
|
|
133
|
+
upper_values, lower_values = validate_band_values(previous["upper_values"], previous["lower_values"], len(rows))
|
|
134
|
+
upper_source, lower_source, condition = previous["upper_source"], previous["lower_source"], previous.get("condition")
|
|
135
|
+
middle_values = previous.get("middle_values")
|
|
136
|
+
obj = {"type": BAND_COMMAND, "id": previous["id"] if previous else "band_" + secrets.token_hex(12),
|
|
137
|
+
"interval": payload.get("interval"), "bar_count": len(rows),
|
|
138
|
+
"row_hash": candle_sequence_hash(rows),
|
|
139
|
+
"upper_source": upper_source, "lower_source": lower_source, "condition": condition,
|
|
140
|
+
"upper_values": upper_values, "lower_values": lower_values,
|
|
141
|
+
"label": name if name is not None else previous.get("label", "") if previous else "",
|
|
142
|
+
"color": color if color is not None else previous.get("color", "info") if previous else "info"}
|
|
143
|
+
if middle_values is not None:
|
|
144
|
+
obj["middle_values"] = middle_values
|
|
145
|
+
obj["band_hash"] = hashlib.sha256(json.dumps({"upper_source": upper_source, "lower_source": lower_source,
|
|
146
|
+
"condition": condition, "upper_values": upper_values, "lower_values": lower_values,
|
|
147
|
+
**({"middle_values": middle_values} if middle_values is not None else {})},
|
|
148
|
+
ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
149
|
+
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
150
|
+
if action == "create":
|
|
151
|
+
if request_id:
|
|
152
|
+
obj["create_request_id"] = request_id
|
|
153
|
+
obj["id"] = "band_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
154
|
+
retry = next((c for c in commands if c.get("type") == BAND_COMMAND and c.get("create_request_id") == request_id), None)
|
|
155
|
+
if retry:
|
|
156
|
+
if any(retry.get(key) != obj.get(key) for key in ("interval", "bar_count", "upper_source", "lower_source",
|
|
157
|
+
"condition", "upper_values", "lower_values", "middle_values", "label", "color")):
|
|
158
|
+
raise LineError("request_conflict", "同一 request_id 的带状参数不同。")
|
|
159
|
+
return result, deepcopy(retry)
|
|
160
|
+
if sum(c.get("type") == BAND_COMMAND for c in commands) >= MAX_PRICE_BANDS:
|
|
161
|
+
raise LineError("too_many_price_bands", "当前图最多保存4个 AI 带状对象。")
|
|
162
|
+
commands.append(obj)
|
|
163
|
+
else:
|
|
164
|
+
commands[commands.index(previous)] = obj
|
|
165
|
+
return result, deepcopy(obj)
|