@ftshare-lab/dsh-kline 0.0.0-stage → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +611 -0
- package/LICENSE +21 -0
- package/PROVENANCE.md +13 -0
- package/README.en.md +171 -0
- package/README.md +170 -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 +77 -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.11.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.11.md +16 -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/PanelHost.js +46 -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/host-options.js +41 -0
- package/lib/client/host-panels.js +111 -0
- package/lib/client/index.js +77 -0
- package/lib/client/mode-preferences.js +48 -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 +98 -0
- package/lib/client/sidebar-integration.js +93 -0
- package/lib/client/ui-onboarding.js +48 -0
- package/lib/client/version.js +14 -0
- package/lib/client.js +17581 -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/PanelHost.d.ts +25 -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 +16 -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/host-options.d.ts +38 -0
- package/lib/types/client/host-panels.d.ts +55 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/mode-preferences.d.ts +25 -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 +7 -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 +155 -4
- package/requirements.txt +6 -0
- package/screenshots.json +8 -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,451 @@
|
|
|
1
|
+
"""Versioned deterministic functions on an explicitly aligned live-chart snapshot.
|
|
2
|
+
|
|
3
|
+
Results are host/view scoped, immutable, bounded, and never apply a drawing.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from copy import deepcopy
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from time import perf_counter
|
|
12
|
+
from typing import Annotated, Literal
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
15
|
+
|
|
16
|
+
import chart_service
|
|
17
|
+
from core.adjustment import normalize_adjustment
|
|
18
|
+
from tools.chart_context import read_chart_context
|
|
19
|
+
from tools.channels import CHANNEL_COMMAND, edit_channel
|
|
20
|
+
from tools.fibonacci import DEFAULT_RATIOS, FIBONACCI_COMMAND, edit_fibonacci
|
|
21
|
+
from tools.lines import LineError
|
|
22
|
+
from tools.rectangles import RECTANGLE_COMMAND, edit_rectangle
|
|
23
|
+
from tools.polylines import LabeledPoint, POLYLINE_COMMAND, edit_polyline
|
|
24
|
+
from tools.pivots import confirmed_pivots
|
|
25
|
+
from tools.automatic_analysis import AUTOMATIC_ANALYSES, analyze_automatic, candidate_function_for_kind, candidate_edit_parameters
|
|
26
|
+
from tools.regression_channels import regression_channel
|
|
27
|
+
from tools.price_series import PriceCondition, PriceSource, SERIES_COMMAND, calculate_price_series, edit_price_series
|
|
28
|
+
from tools.annotations import edit_annotation, _validate_content
|
|
29
|
+
from tools.price_bands import BAND_COMMAND, calculate_price_band, edit_price_band
|
|
30
|
+
from tools.price_sticks import STICKS_COMMAND, calculate_price_sticks, edit_price_sticks
|
|
31
|
+
from tools.trend_lines import resolve_anchor_time
|
|
32
|
+
|
|
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"]
|
|
34
|
+
VERSION = "1"
|
|
35
|
+
ANALYSIS_ONLY = {"pivot_candidates", "regression_channel"} | AUTOMATIC_ANALYSES.keys()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _version(function):
|
|
39
|
+
return AUTOMATIC_ANALYSES[function].version if function in AUTOMATIC_ANALYSES else VERSION
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
FUNCTIONS = {
|
|
43
|
+
"fibonacci_retracement": ("fibonacci_retracement", edit_fibonacci,
|
|
44
|
+
("start_time", "start_price", "end_time", "end_price"), ("ratios",)),
|
|
45
|
+
"parallel_channel": ("channel", edit_channel,
|
|
46
|
+
("start_time", "start_price", "end_time", "end_price", "parallel_time", "parallel_price"), ()),
|
|
47
|
+
"range_box": ("rectangle", edit_rectangle,
|
|
48
|
+
("start_time", "end_time", "lower_price", "upper_price"), ()),
|
|
49
|
+
"labeled_polyline": ("labeled_polyline", edit_polyline, ("points",), ()),
|
|
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),
|
|
53
|
+
"regression_channel": ("regression_channel", None, ("start_time", "end_time"), ("multiplier",)),
|
|
54
|
+
**{name: (name, None, spec.required, spec.optional) for name, spec in AUTOMATIC_ANALYSES.items()
|
|
55
|
+
if name != "recent_drawing_candidates"},
|
|
56
|
+
"price_series_line": ("series_line", edit_price_series, ("value_source",), ("condition",)),
|
|
57
|
+
"conditional_annotation": ("annotation_kind_parameter", edit_annotation,
|
|
58
|
+
("annotation_kind", "anchor_source", "condition"), ("annotation_text", "annotation_value", "annotation_icon")),
|
|
59
|
+
"price_band": ("price_band", edit_price_band, ("upper_source", "lower_source"), ("condition",)),
|
|
60
|
+
"price_sticks": ("price_sticks", edit_price_sticks, ("start_source", "end_source"), ("condition",)),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ChartFunctionParameters(BaseModel):
|
|
65
|
+
model_config = ConfigDict(extra="forbid")
|
|
66
|
+
start_time: str | None = None
|
|
67
|
+
end_time: str | None = None
|
|
68
|
+
start_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
|
|
69
|
+
end_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
|
|
70
|
+
parallel_time: str | None = None
|
|
71
|
+
parallel_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
|
|
72
|
+
lower_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
|
|
73
|
+
upper_price: float | None = Field(default=None, gt=0, allow_inf_nan=False, strict=True)
|
|
74
|
+
ratios: list[Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)]] | None = Field(default=None, min_length=1, max_length=16)
|
|
75
|
+
price_scale: Literal["linear"] = "linear"
|
|
76
|
+
points: list[LabeledPoint] | None = Field(default=None, min_length=2, max_length=8,
|
|
77
|
+
description="时间递增、组内标签唯一的2至8个明确锚点;不是自动识浪")
|
|
78
|
+
left_bars: int | None = Field(default=None, strict=True, ge=1, le=20, description="左侧比较K线数;默认2")
|
|
79
|
+
right_bars: int | None = Field(default=None, strict=True, ge=1, le=20, description="右侧确认K线数;默认2")
|
|
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/港/美股单日线")
|
|
84
|
+
limit: int | None = Field(default=None, strict=True, ge=1, le=50, description="最多返回最新候选数;默认20")
|
|
85
|
+
multiplier: float | None = Field(default=None, strict=True, ge=0.5, le=5, allow_inf_nan=False,
|
|
86
|
+
description="回归上下轨距离倍数;默认2,乘以回归残差总体RMS")
|
|
87
|
+
direction: Literal["ascending", "descending", "both"] | None = Field(default=None, description="通道候选方向;默认both")
|
|
88
|
+
scope: Literal["current", "historical"] | None = Field(default=None, description="通道候选范围;默认current,仅历史回看时选historical")
|
|
89
|
+
lookback_bars: int | None = Field(default=None, strict=True, ge=30, le=300, description="最近已加载K线根数;默认120")
|
|
90
|
+
min_span_bars: int | None = Field(default=None, strict=True, ge=10, le=100, description="两基准锚点最小间隔;默认12")
|
|
91
|
+
max_candidates: int | None = Field(default=None, strict=True, ge=1, le=5, description="最多返回候选数;默认3")
|
|
92
|
+
window_sizes: list[Annotated[int, Field(strict=True, ge=16, le=120)]] | None = Field(
|
|
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)
|
|
98
|
+
value_source: PriceSource | None = Field(default=None, description="序列线取值:OHLC、SMA 或 EMA(close, 2至200根)")
|
|
99
|
+
condition: PriceCondition | None = Field(default=None, description="可选价格条件;不接受宿主传入行情数组或代码")
|
|
100
|
+
anchor_source: PriceSource | None = Field(default=None, description="条件标注所用价格锚点,取最新一根满足条件的已加载K线")
|
|
101
|
+
annotation_kind: Literal["text_annotation", "number_annotation", "icon_annotation"] | None = None
|
|
102
|
+
annotation_text: str | None = Field(default=None, min_length=1, max_length=120)
|
|
103
|
+
annotation_value: float | None = Field(default=None, strict=True, allow_inf_nan=False)
|
|
104
|
+
annotation_icon: Literal["arrow_up", "arrow_down", "diamond"] | None = None
|
|
105
|
+
upper_source: PriceSource | None = Field(default=None, description="带状填充上边界价格来源")
|
|
106
|
+
lower_source: PriceSource | None = Field(default=None, description="带状填充下边界价格来源")
|
|
107
|
+
start_source: PriceSource | None = Field(default=None, description="逐K线柱线起点价格来源")
|
|
108
|
+
end_source: PriceSource | None = Field(default=None, description="逐K线柱线终点价格来源")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def list_functions():
|
|
112
|
+
schema = ChartFunctionParameters.model_json_schema()
|
|
113
|
+
properties = schema["properties"]
|
|
114
|
+
return {"schema_version": 1, "functions": [
|
|
115
|
+
{"name": name, "version": _version(name), "drawing_kind": None if name in ANALYSIS_ONLY else kind, "required_parameters": list(required),
|
|
116
|
+
"result_usage": "analysis_only" if name in ANALYSIS_ONLY else "guarded_drawing",
|
|
117
|
+
"optional_parameters": list(optional) + ([] if name in ANALYSIS_ONLY else ["price_scale"]),
|
|
118
|
+
"defaults": ({"left_bars": 2, "right_bars": 2, "mode": "both", "limit": 20}
|
|
119
|
+
if name == "pivot_candidates" else
|
|
120
|
+
deepcopy(AUTOMATIC_ANALYSES[name].defaults) if name in AUTOMATIC_ANALYSES else
|
|
121
|
+
{"multiplier": 2.0} if name == "regression_channel" else
|
|
122
|
+
{"condition": None, "price_scale": "linear"} if name == "price_series_line" else
|
|
123
|
+
{"selection": "latest_match", "price_scale": "linear"} if name == "conditional_annotation" else
|
|
124
|
+
{"condition": None, "price_scale": "linear"} if name in {"price_band", "price_sticks"} else
|
|
125
|
+
{"price_scale": "linear", **({"ratios": list(DEFAULT_RATIOS)} if name == "fibonacci_retracement" else {})}),
|
|
126
|
+
"limits": {"loaded_bars": 4000, "automatic_anchor_selection": False,
|
|
127
|
+
"price_scale": "linear", "time": "exact_loaded_bar", "applies_chart": False,
|
|
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],
|
|
133
|
+
"rule": "strict_local_extremum", "ties": "equal_neighbor_is_not_a_pivot",
|
|
134
|
+
"requires_complete_right_window": True} if name == "pivot_candidates" else
|
|
135
|
+
{"minimum_range_bars": 10, "maximum_range_bars": 4000,
|
|
136
|
+
"price_source": "close", "x_axis": "loaded_candle_index",
|
|
137
|
+
"boundary_rule": "ols_close_plus_minus_multiplier_times_population_rms_residual",
|
|
138
|
+
"automatic_anchor_selection": False} if name == "regression_channel" else
|
|
139
|
+
{"lookback_bars": [30, 300], "pivot_window_bars": [1, 20],
|
|
140
|
+
"minimum_anchor_span_bars": [10, 100], "candidate_limit": [1, 5],
|
|
141
|
+
"anchor_rule": "two_confirmed_same_side_pivots_plus_widest_interior_opposite_pivot",
|
|
142
|
+
"automatic_anchor_selection": "candidates_only_not_drawing",
|
|
143
|
+
"current_end_age_bars": 8, "max_width_fraction_of_median_close": 0.12,
|
|
144
|
+
"max_width_to_base_move": 2.0,
|
|
145
|
+
"max_outside_bar_fraction": 0.20,
|
|
146
|
+
"same_family_slope_tolerance": 0.10,
|
|
147
|
+
"same_family_width_tolerance": 0.10,
|
|
148
|
+
"current_post_end_check": "arithmetic_extension_to_latest_not_breakout_confirmation",
|
|
149
|
+
"requires_result_review": True, "direct_request_may_select_latest": True} if name == "channel_candidates" else
|
|
150
|
+
{"window_size_bars": [16, 120], "candidate_limit": [1, 5],
|
|
151
|
+
"end_policy": "latest_loaded_bar_only",
|
|
152
|
+
"boundary_rule": "full_window_max_high_min_low",
|
|
153
|
+
"requires_separated_touches_on_both_edges": True,
|
|
154
|
+
"checks_full_and_recent_close_drift": True,
|
|
155
|
+
"automatic_anchor_selection": "candidates_only_not_drawing",
|
|
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
|
|
166
|
+
{"maximum_series_objects": 8, "value_sources": ["open", "high", "low", "close", "sma_close", "ema_close"],
|
|
167
|
+
"sma_period": [2, 200], "ema_period": [2, 200], "conditions": ["gt", "gte", "lt", "lte"],
|
|
168
|
+
"zero_matches": "do_not_draw", "pane": "candle"} if name == "price_series_line" else
|
|
169
|
+
{"selection": "latest_matched_loaded_bar_only", "maximum_annotations": 80,
|
|
170
|
+
"value_sources": ["open", "high", "low", "close", "sma_close", "ema_close"],
|
|
171
|
+
"conditions": ["gt", "gte", "lt", "lte"], "zero_matches": "do_not_draw",
|
|
172
|
+
"content_rule": "exactly_one_matching_annotation_text_value_or_icon"}
|
|
173
|
+
if name == "conditional_annotation" else
|
|
174
|
+
{"maximum_band_objects": 4, "boundary_rule": "upper_strictly_above_lower_on_every_matched_bar",
|
|
175
|
+
"zero_matches": "do_not_draw", "pane": "candle", "conditions": ["gt", "gte", "lt", "lte"]}
|
|
176
|
+
if name == "price_band" else
|
|
177
|
+
{"maximum_stick_objects": 4, "zero_length": "omitted", "pane": "candle",
|
|
178
|
+
"value_sources": ["open", "high", "low", "close", "sma_close", "ema_close"],
|
|
179
|
+
"conditions": ["gt", "gte", "lt", "lte"]} if name == "price_sticks" else {})},
|
|
180
|
+
"parameter_schema": {"type": "object", "additionalProperties": False, "required": list(required),
|
|
181
|
+
"properties": {key: properties[key] for key in
|
|
182
|
+
(*required, *optional, *(() if name in ANALYSIS_ONLY else ("price_scale",)))},
|
|
183
|
+
**({"$defs": schema["$defs"]} if name in {"labeled_polyline", "price_series_line", "conditional_annotation", "price_band", "price_sticks"} else {})}}
|
|
184
|
+
for name, (kind, _, required, optional) in FUNCTIONS.items()],
|
|
185
|
+
"workflow": "get_chart_context -> run_chart_function -> prepare_chart_edit(result_ref) -> apply_chart_edit -> get_chart_edit_status",
|
|
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",
|
|
187
|
+
"pattern_quality_verified": False}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _hash(value):
|
|
191
|
+
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _data_identity(context):
|
|
195
|
+
return {key: context.get(key) for key in ("symbol", "interval", "interval_value", "data_provenance")} | {
|
|
196
|
+
"adjust": normalize_adjustment(context.get("adjust")), "candles": context["candles"]}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _binding(context):
|
|
200
|
+
return {"host_process_id": chart_service.HOST_PROCESS_ID,
|
|
201
|
+
**{k: context[k] for k in ("context_ref", "conversation_id", "view_id")},
|
|
202
|
+
"data_fingerprint": _hash(_data_identity(context))}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _directory(context):
|
|
206
|
+
return chart_service.RUNTIME_DIR / "functions" / str(chart_service.HOST_PROCESS_ID) / context["context_ref"]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _calculate(payload, function, parameters, *, candles=None, context=None):
|
|
210
|
+
if function not in FUNCTIONS:
|
|
211
|
+
raise LineError("unknown_chart_function", "未知函数,请查询 list_chart_functions;不执行任意公式或代码。")
|
|
212
|
+
kind, editor, required, optional = FUNCTIONS[function]
|
|
213
|
+
values = parameters.model_dump(exclude_none=True)
|
|
214
|
+
values.pop("price_scale")
|
|
215
|
+
if values.keys() - set(required + optional):
|
|
216
|
+
raise LineError("invalid_function_parameters", "参数不适用于该函数。")
|
|
217
|
+
if any(k not in values for k in required):
|
|
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}
|
|
229
|
+
if function == "pivot_candidates":
|
|
230
|
+
rows = candles
|
|
231
|
+
if not isinstance(rows, list):
|
|
232
|
+
raise LineError("pivot_data_unavailable", "当前图没有可读取的已加载K线,未补取行情。")
|
|
233
|
+
result = confirmed_pivots(rows, left_bars=values.get("left_bars", 2),
|
|
234
|
+
right_bars=values.get("right_bars", 2), mode=values.get("mode", "both"),
|
|
235
|
+
limit=values.get("limit", 20))
|
|
236
|
+
normalized = {"left_bars": result["left_bars"], "right_bars": result["right_bars"],
|
|
237
|
+
"mode": result["mode"], "limit": result["limit"]}
|
|
238
|
+
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
239
|
+
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear",
|
|
240
|
+
"summary": {k: deepcopy(v) for k, v in result.items() if k not in normalized}}
|
|
241
|
+
if function == "regression_channel":
|
|
242
|
+
start = resolve_anchor_time(payload, values["start_time"])
|
|
243
|
+
end = resolve_anchor_time(payload, values["end_time"])
|
|
244
|
+
result = regression_channel(candles, start_time=start, end_time=end,
|
|
245
|
+
multiplier=values.get("multiplier", 2.0))
|
|
246
|
+
normalized = {"start_time": str(start), "end_time": str(end), "multiplier": result["multiplier"]}
|
|
247
|
+
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
248
|
+
"result_usage": "analysis_only", "parameters": normalized, "price_scale": "linear",
|
|
249
|
+
"summary": result}
|
|
250
|
+
if function == "price_series_line":
|
|
251
|
+
if not isinstance(candles, list) or values.get("value_source") is None:
|
|
252
|
+
raise LineError("price_series_data_unavailable", "当前图没有可读取的已加载K线,未补取行情。")
|
|
253
|
+
source = PriceSource.model_validate(values["value_source"])
|
|
254
|
+
condition = PriceCondition.model_validate(values["condition"]) if values.get("condition") is not None else None
|
|
255
|
+
calculation = calculate_price_series(candles, source, condition)
|
|
256
|
+
return {"function": function, "function_version": _version(function), "kind": kind,
|
|
257
|
+
"result_usage": "guarded_drawing", "parameters": {"value_source": source.model_dump(exclude_none=True),
|
|
258
|
+
"condition": condition.model_dump(exclude_none=True) if condition else None},
|
|
259
|
+
"price_scale": "linear", "summary": calculation["summary"],
|
|
260
|
+
"render_values": calculation["values"]}
|
|
261
|
+
if function == "conditional_annotation":
|
|
262
|
+
annotation_kind = values["annotation_kind"]
|
|
263
|
+
source = PriceSource.model_validate(values["anchor_source"])
|
|
264
|
+
condition = PriceCondition.model_validate(values["condition"])
|
|
265
|
+
content_key = {"text_annotation": "annotation_text", "number_annotation": "annotation_value",
|
|
266
|
+
"icon_annotation": "annotation_icon"}[annotation_kind]
|
|
267
|
+
if content_key not in values or set(values) & {"annotation_text", "annotation_value", "annotation_icon"} != {content_key}:
|
|
268
|
+
raise LineError("invalid_conditional_annotation_content", "请只填写对应标注类型的一项文字、数值或图标内容。")
|
|
269
|
+
content_text, content_value = _validate_content(annotation_kind, values.get("annotation_text"),
|
|
270
|
+
values.get("annotation_value"), values.get("annotation_icon"))
|
|
271
|
+
if annotation_kind == "text_annotation": values[content_key] = content_text
|
|
272
|
+
elif annotation_kind == "number_annotation": values[content_key] = content_value
|
|
273
|
+
calculation = calculate_price_series(candles, source, condition)
|
|
274
|
+
matches = [index for index, value in enumerate(calculation["values"]) if value is not None]
|
|
275
|
+
drawing_parameters = None
|
|
276
|
+
if matches:
|
|
277
|
+
index = matches[-1]
|
|
278
|
+
drawing_parameters = {"anchor_time": str(candles[index]["time"]),
|
|
279
|
+
"anchor_price": calculation["values"][index], content_key: values[content_key]}
|
|
280
|
+
# Reuse the existing annotation editor for content and exact-bar validation.
|
|
281
|
+
editor_arguments = {"kind": annotation_kind, "anchor_time": drawing_parameters["anchor_time"],
|
|
282
|
+
"anchor_price": drawing_parameters["anchor_price"],
|
|
283
|
+
{"annotation_text": "text", "annotation_value": "value",
|
|
284
|
+
"annotation_icon": "icon"}[content_key]: values[content_key]}
|
|
285
|
+
_, annotation = edit_annotation(payload, "create", **editor_arguments)
|
|
286
|
+
drawing_parameters["anchor_price"] = annotation["price"]
|
|
287
|
+
return {"function": function, "function_version": VERSION, "kind": annotation_kind,
|
|
288
|
+
"result_usage": "guarded_drawing", "parameters": {"annotation_kind": annotation_kind,
|
|
289
|
+
"anchor_source": source.model_dump(exclude_none=True),
|
|
290
|
+
"condition": condition.model_dump(exclude_none=True), content_key: values[content_key]},
|
|
291
|
+
"drawing_parameters": drawing_parameters, "price_scale": "linear",
|
|
292
|
+
"summary": {**calculation["summary"], "selection_rule": "latest_matched_loaded_bar_only",
|
|
293
|
+
"selected_time": drawing_parameters["anchor_time"] if drawing_parameters else None,
|
|
294
|
+
"selected_price": drawing_parameters["anchor_price"] if drawing_parameters else None,
|
|
295
|
+
"bars_ago": len(candles) - 1 - matches[-1] if matches else None}}
|
|
296
|
+
if function == "price_band":
|
|
297
|
+
upper_source = PriceSource.model_validate(values["upper_source"])
|
|
298
|
+
lower_source = PriceSource.model_validate(values["lower_source"])
|
|
299
|
+
condition = PriceCondition.model_validate(values["condition"]) if values.get("condition") is not None else None
|
|
300
|
+
calculated = calculate_price_band(candles, upper_source, lower_source, condition)
|
|
301
|
+
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
302
|
+
"result_usage": "guarded_drawing", "parameters": {
|
|
303
|
+
"upper_source": upper_source.model_dump(exclude_none=True),
|
|
304
|
+
"lower_source": lower_source.model_dump(exclude_none=True),
|
|
305
|
+
"condition": condition.model_dump(exclude_none=True) if condition else None},
|
|
306
|
+
"price_scale": "linear", "summary": calculated["summary"],
|
|
307
|
+
"render_upper_values": calculated["upper_values"],
|
|
308
|
+
"render_lower_values": calculated["lower_values"]}
|
|
309
|
+
if function == "price_sticks":
|
|
310
|
+
start_source = PriceSource.model_validate(values["start_source"])
|
|
311
|
+
end_source = PriceSource.model_validate(values["end_source"])
|
|
312
|
+
condition = PriceCondition.model_validate(values["condition"]) if values.get("condition") is not None else None
|
|
313
|
+
calculated = calculate_price_sticks(candles, start_source, end_source, condition)
|
|
314
|
+
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
315
|
+
"result_usage": "guarded_drawing", "parameters": {
|
|
316
|
+
"start_source": start_source.model_dump(exclude_none=True),
|
|
317
|
+
"end_source": end_source.model_dump(exclude_none=True),
|
|
318
|
+
"condition": condition.model_dump(exclude_none=True) if condition else None},
|
|
319
|
+
"price_scale": "linear", "summary": calculated["summary"],
|
|
320
|
+
"render_start_values": calculated["start_values"],
|
|
321
|
+
"render_end_values": calculated["end_values"]}
|
|
322
|
+
# Editors already implement all geometry/anchor validation. Work only on a
|
|
323
|
+
# temporary copy; never publish their temporary IDs or duplicate the math.
|
|
324
|
+
command = {"channel": CHANNEL_COMMAND, "rectangle": RECTANGLE_COMMAND, "fibonacci_retracement": FIBONACCI_COMMAND,
|
|
325
|
+
"labeled_polyline": POLYLINE_COMMAND}[kind]
|
|
326
|
+
calculation_input = {**payload, "chartCommands": [c for c in payload["chartCommands"] if c.get("type") != command]}
|
|
327
|
+
_, obj = editor(calculation_input, "create", **values)
|
|
328
|
+
normalized = {}
|
|
329
|
+
if kind == "labeled_polyline":
|
|
330
|
+
normalized = {"points": [{**p, "time": str(p["time"])} for p in obj["points"]]}
|
|
331
|
+
summary = {"points": deepcopy(obj["points"]), "point_count": len(obj["points"]), "automatic_wave_recognition": False}
|
|
332
|
+
elif kind == "rectangle":
|
|
333
|
+
normalized = {k: str(obj[k]) if k.endswith("_time") else obj[k] for k in required}
|
|
334
|
+
summary = {k: obj[k] for k in required}
|
|
335
|
+
else:
|
|
336
|
+
for prefix, key in (("start", "from"), ("end", "to"), ("parallel", "parallel")):
|
|
337
|
+
if key in obj:
|
|
338
|
+
normalized.update({prefix + "_time": str(obj[key]["time"]), prefix + "_price": obj[key]["price"]})
|
|
339
|
+
summary = {k: deepcopy(obj[k]) for k in ("from", "to", "parallel", "levels", "upper", "lower", "width", "direction") if k in obj}
|
|
340
|
+
if kind == "fibonacci_retracement": normalized["ratios"] = obj["ratios"]
|
|
341
|
+
return {"function": function, "function_version": VERSION, "kind": kind,
|
|
342
|
+
"result_usage": "guarded_drawing",
|
|
343
|
+
"parameters": normalized, "price_scale": "linear", "summary": summary}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def run_function(context_ref, expected_revision, chart_session, symbol, function, parameters):
|
|
347
|
+
from tools.chart_edits import require_alignment
|
|
348
|
+
started = perf_counter()
|
|
349
|
+
# MCP validates this model before dispatch, but the browser workbench sends
|
|
350
|
+
# JSON directly through the local chart service. Both entrances must use
|
|
351
|
+
# the same parameter contract before any calculation or result is stored.
|
|
352
|
+
if not isinstance(parameters, ChartFunctionParameters):
|
|
353
|
+
try:
|
|
354
|
+
parameters = ChartFunctionParameters.model_validate(parameters)
|
|
355
|
+
except ValidationError:
|
|
356
|
+
raise LineError("invalid_function_parameters", "绘图函数参数无效,请核对函数目录中的参数类型与范围。") from None
|
|
357
|
+
context = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
|
|
358
|
+
if type(expected_revision) is not int or context["revision"] != expected_revision:
|
|
359
|
+
raise LineError("chart_context_revision_conflict", "当前观察版本已改变,请重新读取当前图。")
|
|
360
|
+
payload = chart_service.read_chart_snapshot(chart_session)
|
|
361
|
+
if payload is None: raise LineError("chart_session_not_found", "当前命名来源不存在。")
|
|
362
|
+
require_alignment(context, payload, chart_session, symbol)
|
|
363
|
+
calculation = _calculate(payload, function, parameters, candles=context["candles"], context=context)
|
|
364
|
+
record = {"schema_version": 1, "binding": _binding(context), **calculation}
|
|
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):
|
|
366
|
+
raise LineError("chart_function_result_too_large", "函数结果超出本阶段容量限制,未保存或绘图。")
|
|
367
|
+
result_ref = _hash(record)
|
|
368
|
+
refreshed = read_chart_context(context_ref, candle_scope="loaded", limit=4000)
|
|
369
|
+
if refreshed["revision"] != expected_revision or _binding(refreshed) != record["binding"]:
|
|
370
|
+
raise LineError("chart_context_revision_conflict", "计算期间当前图已变化,未保存结果。")
|
|
371
|
+
directory = _directory(context)
|
|
372
|
+
path = directory / (result_ref + ".json")
|
|
373
|
+
if not path.exists():
|
|
374
|
+
if directory.exists() and sum(1 for _ in directory.glob("*.json")) >= 64:
|
|
375
|
+
raise LineError("chart_function_capacity", "当前视图已保存64个函数结果,不自动丢弃旧引用。")
|
|
376
|
+
chart_service._atomic_runtime_json(path, record)
|
|
377
|
+
else:
|
|
378
|
+
try:
|
|
379
|
+
if json.loads(path.read_text(encoding="utf-8")) != record: raise ValueError("conflict")
|
|
380
|
+
except (OSError, ValueError):
|
|
381
|
+
raise LineError("chart_function_result_invalid", "已保存结果无效,未覆盖旧引用。") from None
|
|
382
|
+
return {"ok": True, "result_ref": result_ref, "function": function,
|
|
383
|
+
"function_version": calculation["function_version"],
|
|
384
|
+
"result_usage": calculation["result_usage"],
|
|
385
|
+
"kind": calculation["kind"], "parameters": calculation["parameters"], "summary": calculation["summary"],
|
|
386
|
+
"data_fingerprint": record["binding"]["data_fingerprint"],
|
|
387
|
+
"data_scope": {k: context.get(k) for k in ("symbol", "interval", "interval_value", "adjust", "loaded_range")},
|
|
388
|
+
"calculation_ms": round((perf_counter() - started) * 1000, 3),
|
|
389
|
+
"chart_modified": False, "render_verified": False, "pattern_quality_verified": False}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _read_result_record(result_ref, context, kind):
|
|
393
|
+
if not isinstance(result_ref, str) or not re.fullmatch(r"[a-f0-9]{64}", result_ref):
|
|
394
|
+
raise LineError("invalid_function_result_ref", "请使用 run_chart_function 返回的完整结果引用。")
|
|
395
|
+
path = _directory(context) / (result_ref + ".json")
|
|
396
|
+
try:
|
|
397
|
+
if path.stat().st_size > 262144: raise ValueError("size")
|
|
398
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
399
|
+
if _hash(record) != result_ref or record["schema_version"] != 1: raise ValueError("hash")
|
|
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")
|
|
401
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
402
|
+
raise LineError("chart_function_result_unavailable", "结果引用不存在或已失效;不能借用其他视图或宿主的结果。") from None
|
|
403
|
+
if (record["binding"] != _binding(context) or record.get("function_version") != _version(record.get("function"))
|
|
404
|
+
or record.get("function") not in FUNCTIONS or record.get("kind") != kind):
|
|
405
|
+
raise LineError("chart_function_result_mismatch", "结果的行情、归属、版本或图形类型已不匹配,请重新计算。")
|
|
406
|
+
return record
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def resolve_result(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"]}
|
|
414
|
+
if record.get("result_usage") != "guarded_drawing":
|
|
415
|
+
raise LineError("chart_function_result_not_drawable", "该函数结果仅供分析,不能作为绘图几何引用。")
|
|
416
|
+
if kind == "series_line":
|
|
417
|
+
if not isinstance(record.get("render_values"), list) or not any(v is not None for v in record["render_values"]):
|
|
418
|
+
raise LineError("empty_price_series", "条件没有命中可绘制K线,未创建空图形。")
|
|
419
|
+
return {"source": deepcopy(record["parameters"]["value_source"]),
|
|
420
|
+
"condition": deepcopy(record["parameters"]["condition"]),
|
|
421
|
+
"values": deepcopy(record["render_values"])}
|
|
422
|
+
if record["function"] == "conditional_annotation":
|
|
423
|
+
if not isinstance(record.get("drawing_parameters"), dict):
|
|
424
|
+
raise LineError("no_conditional_match", "条件未命中已加载K线,未创建标注。")
|
|
425
|
+
return deepcopy(record["drawing_parameters"])
|
|
426
|
+
if kind == "price_band":
|
|
427
|
+
upper, lower = record.get("render_upper_values"), record.get("render_lower_values")
|
|
428
|
+
if not isinstance(upper, list) or not isinstance(lower, list) or not any(v is not None for v in upper):
|
|
429
|
+
raise LineError("empty_price_band", "条件没有命中可填充K线,未创建空带。")
|
|
430
|
+
return {"upper_source": deepcopy(record["parameters"]["upper_source"]),
|
|
431
|
+
"lower_source": deepcopy(record["parameters"]["lower_source"]),
|
|
432
|
+
"condition": deepcopy(record["parameters"]["condition"]),
|
|
433
|
+
"upper_values": deepcopy(upper), "lower_values": deepcopy(lower)}
|
|
434
|
+
if kind == "price_sticks":
|
|
435
|
+
start, end = record.get("render_start_values"), record.get("render_end_values")
|
|
436
|
+
if not isinstance(start, list) or not isinstance(end, list) or not any(v is not None for v in start):
|
|
437
|
+
raise LineError("empty_price_sticks", "条件没有命中可绘制柱线,未创建空对象。")
|
|
438
|
+
return {"start_source": deepcopy(record["parameters"]["start_source"]),
|
|
439
|
+
"end_source": deepcopy(record["parameters"]["end_source"]),
|
|
440
|
+
"condition": deepcopy(record["parameters"]["condition"]),
|
|
441
|
+
"start_values": deepcopy(start), "end_values": deepcopy(end)}
|
|
442
|
+
return deepcopy(record["parameters"])
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def resolve_selected_candidate(result_ref, context, kind, number):
|
|
446
|
+
"""Resolve one reviewed 1-based candidate; never alters a chart by itself."""
|
|
447
|
+
function = candidate_function_for_kind(kind)
|
|
448
|
+
record = _read_result_record(result_ref, context, function)
|
|
449
|
+
if record.get("result_usage") != "analysis_only":
|
|
450
|
+
raise LineError("candidate_result_not_analysis", "该引用不是只读候选结果。")
|
|
451
|
+
return candidate_edit_parameters(kind, record.get("summary", {}), number)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Internal browser bridge for TA-Lib chart indicators on already loaded rows.
|
|
2
|
+
|
|
3
|
+
This is not an MCP analysis tool. It never fetches or publishes a chart.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from core.rows import validate_rows
|
|
12
|
+
from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION
|
|
13
|
+
from tools.draw import SUPPORTED_INDICATORS, build_chart_commands
|
|
14
|
+
from tools.price_series import candle_sequence_hash
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _period(value: Any, name: str, maximum: int = 200) -> int:
|
|
18
|
+
if type(value) is not int or not 2 <= value <= maximum:
|
|
19
|
+
raise ValueError(f"{name} must be an integer from 2 to {maximum}")
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def calculate_chart_indicators(
|
|
24
|
+
*, rows: Any, expected_hash: str, indicators: list[str],
|
|
25
|
+
ma_periods: list[int], volume_ma: int, boll_period: int,
|
|
26
|
+
boll_std: float, rsi_period: int, atr_period: int, ema_period: int = 20,
|
|
27
|
+
) -> dict[str, Any]:
|
|
28
|
+
if not isinstance(rows, list) or not 2 <= len(rows) <= 4000:
|
|
29
|
+
raise ValueError("indicator rows must contain 2..4000 loaded candles")
|
|
30
|
+
normalized = validate_rows(rows, min_len=2)
|
|
31
|
+
if len(normalized) != len(rows):
|
|
32
|
+
raise ValueError("indicator rows must not be normalized, dropped or deduplicated")
|
|
33
|
+
actual_hash = candle_sequence_hash(normalized)
|
|
34
|
+
if not isinstance(expected_hash, str) or expected_hash != actual_hash:
|
|
35
|
+
raise ValueError("indicator source hash does not match current loaded candles")
|
|
36
|
+
if (not isinstance(indicators, list) or len(indicators) > len(SUPPORTED_INDICATORS)
|
|
37
|
+
or any(not isinstance(name, str) or name not in SUPPORTED_INDICATORS for name in indicators)
|
|
38
|
+
or len(set(indicators)) != len(indicators)):
|
|
39
|
+
raise ValueError("unsupported or duplicate indicator name")
|
|
40
|
+
if (not isinstance(ma_periods, list) or not 1 <= len(ma_periods) <= 8
|
|
41
|
+
or len(set(ma_periods)) != len(ma_periods)):
|
|
42
|
+
raise ValueError("ma_periods must contain 1..8 distinct periods")
|
|
43
|
+
periods = [_period(value, "ma_period", 400) for value in ma_periods]
|
|
44
|
+
volume_ma = _period(volume_ma, "volume_ma")
|
|
45
|
+
boll_period = _period(boll_period, "boll_period")
|
|
46
|
+
rsi_period = _period(rsi_period, "rsi_period")
|
|
47
|
+
atr_period = _period(atr_period, "atr_period")
|
|
48
|
+
ema_period = _period(ema_period, "ema_period")
|
|
49
|
+
if type(boll_std) not in (int, float) or not math.isfinite(boll_std) or not 0.5 <= boll_std <= 5:
|
|
50
|
+
raise ValueError("boll_std must be a finite number from 0.5 to 5")
|
|
51
|
+
commands = build_chart_commands(
|
|
52
|
+
normalized, indicators=indicators, ma_periods=periods,
|
|
53
|
+
ema_period=ema_period,
|
|
54
|
+
volume_ma=volume_ma, boll_period=boll_period, boll_std=boll_std,
|
|
55
|
+
rsi_period=rsi_period, atr_period=atr_period,
|
|
56
|
+
)
|
|
57
|
+
return {
|
|
58
|
+
"ok": True,
|
|
59
|
+
"calculation_engine": {"name": "TA-Lib", "wrapper_version": ENGINE_VERSION,
|
|
60
|
+
"native_version": NATIVE_VERSION},
|
|
61
|
+
"source_hash": actual_hash,
|
|
62
|
+
"loaded_bars": len(normalized),
|
|
63
|
+
"chartCommands": [command for command in commands if command["type"] == "SET_INDICATOR_SERIES"],
|
|
64
|
+
"chart_modified": False,
|
|
65
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Exact measurements of a host-selected loaded region; no pattern recognition."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from tools.lines import LineError
|
|
9
|
+
from tools.trend_lines import CN_TZ, resolve_anchor_time
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _boundary_witness(region: list[dict], values: list[float], price: float,
|
|
13
|
+
fields: tuple[str, ...]) -> dict[str, Any]:
|
|
14
|
+
"""One bounded arithmetic witness, not a selected drawing/pattern anchor.
|
|
15
|
+
|
|
16
|
+
Validated rows are time-ordered. Report the first matching bar and count all
|
|
17
|
+
matching bars, without implying a unique extremum or dumping thousands of ties.
|
|
18
|
+
"""
|
|
19
|
+
index = next(i for i, value in enumerate(values) if value == price)
|
|
20
|
+
row = region[index]
|
|
21
|
+
try:
|
|
22
|
+
instant = datetime.fromtimestamp(row["time"], CN_TZ)
|
|
23
|
+
date, iso = instant.date().isoformat(), instant.isoformat(timespec="seconds")
|
|
24
|
+
except (ValueError, OverflowError, OSError):
|
|
25
|
+
date, iso = None, None
|
|
26
|
+
return {"price": price, "time": row["time"], "date": date, "iso": iso,
|
|
27
|
+
"source_fields": [field for field in fields if row[field] == price],
|
|
28
|
+
"matched_bar_count": sum(value == price for value in values)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def measure_chart_region(rows: list[dict], interval: str, start_time: str, end_time: str) -> dict[str, Any]:
|
|
32
|
+
source = {"interval": interval, "chartCommands": [{"type": "SET_CANDLES", "rows": rows}]}
|
|
33
|
+
start = resolve_anchor_time(source, start_time)
|
|
34
|
+
end = resolve_anchor_time(source, end_time)
|
|
35
|
+
if start > end:
|
|
36
|
+
raise LineError("invalid_measurement_range", "测量起点必须不晚于终点;未交换日期或重新取数。")
|
|
37
|
+
region = [row for row in rows if start <= row["time"] <= end]
|
|
38
|
+
if len(region) > 4000:
|
|
39
|
+
raise LineError("measurement_capacity", "测量区域超过4000根K线;未拿截断样本冒充完整区域。")
|
|
40
|
+
body_low = [min(row["open"], row["close"]) for row in region]
|
|
41
|
+
body_high = [max(row["open"], row["close"]) for row in region]
|
|
42
|
+
envelope_low, envelope_high = min(body_low), max(body_high)
|
|
43
|
+
overlap_low, overlap_high = max(body_low), min(body_high)
|
|
44
|
+
wick_low = [row["low"] for row in region]
|
|
45
|
+
wick_high = [row["high"] for row in region]
|
|
46
|
+
relation = "empty" if overlap_low > overlap_high else "point" if overlap_low == overlap_high else "range"
|
|
47
|
+
volumes = [row["volume"] for row in region]
|
|
48
|
+
increasing = sum(right > left for left, right in zip(volumes, volumes[1:]))
|
|
49
|
+
decreasing = sum(right < left for left, right in zip(volumes, volumes[1:]))
|
|
50
|
+
change = (volumes[-1] / volumes[0] - 1) * 100 if volumes[0] > 0 else None
|
|
51
|
+
if change is not None and not math.isfinite(change):
|
|
52
|
+
change = None
|
|
53
|
+
return {
|
|
54
|
+
"evidence_scope": "loaded_browser_candles", "pattern_classification": "not_provided",
|
|
55
|
+
"start_time": start, "end_time": end, "bar_count": len(region),
|
|
56
|
+
"wick_envelope": {"lower_price": min(wick_low), "upper_price": max(wick_high)},
|
|
57
|
+
"body_envelope": {"meaning": "contains_all_open_close_bodies",
|
|
58
|
+
"lower_price": envelope_low, "upper_price": envelope_high},
|
|
59
|
+
"body_overlap": {"meaning": "intersection_shared_by_every_body",
|
|
60
|
+
"exists": overlap_low <= overlap_high, "has_positive_height": overlap_low < overlap_high,
|
|
61
|
+
"lower_price": overlap_low if overlap_low <= overlap_high else None,
|
|
62
|
+
"upper_price": overlap_high if overlap_low <= overlap_high else None},
|
|
63
|
+
"boundary_evidence": {
|
|
64
|
+
"schema_version": 1, "scope": "selected_region_only",
|
|
65
|
+
"tie_policy": "first_matching_bar_with_total_count",
|
|
66
|
+
"wick_envelope": {
|
|
67
|
+
"lower": _boundary_witness(region, wick_low, min(wick_low), ("low",)),
|
|
68
|
+
"upper": _boundary_witness(region, wick_high, max(wick_high), ("high",))},
|
|
69
|
+
"body_envelope": {
|
|
70
|
+
"lower": _boundary_witness(region, body_low, envelope_low, ("open", "close")),
|
|
71
|
+
"upper": _boundary_witness(region, body_high, envelope_high, ("open", "close"))},
|
|
72
|
+
"body_overlap": {
|
|
73
|
+
"relation": relation,
|
|
74
|
+
"comparison": "lower_greater_than_upper" if relation == "empty" else
|
|
75
|
+
"lower_equals_upper" if relation == "point" else "lower_less_than_upper",
|
|
76
|
+
"lower_candidate": _boundary_witness(region, body_low, overlap_low, ("open", "close")),
|
|
77
|
+
"upper_candidate": _boundary_witness(region, body_high, overlap_high, ("open", "close"))},
|
|
78
|
+
},
|
|
79
|
+
"volume_changes": {"first": volumes[0], "last": volumes[-1], "first_to_last_pct": change,
|
|
80
|
+
"increasing_steps": increasing, "decreasing_steps": decreasing,
|
|
81
|
+
"equal_steps": len(volumes) - 1 - increasing - decreasing,
|
|
82
|
+
"strictly_decreasing": decreasing == len(volumes) - 1 if len(volumes) > 1 else None,
|
|
83
|
+
"non_increasing": increasing == 0 if len(volumes) > 1 else None},
|
|
84
|
+
}
|