@dsh-ft/dsh-fft-paper-trading 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +1 -1
- package/package.json +1 -4
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
- package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
"""Read-only, rule-based three-anchor channel candidates on loaded candles.
|
|
2
|
-
|
|
3
|
-
This module proposes geometry for human review. It neither publishes drawings
|
|
4
|
-
nor claims that a candidate is the uniquely correct technical-analysis channel.
|
|
5
|
-
"""
|
|
6
|
-
from __future__ import annotations
|
|
7
|
-
|
|
8
|
-
from collections import Counter
|
|
9
|
-
import math
|
|
10
|
-
from statistics import median
|
|
11
|
-
|
|
12
|
-
from core.rows import RowsValidationError, validate_rows
|
|
13
|
-
from tools.lines import LineError
|
|
14
|
-
from tools.pivots import confirmed_pivots
|
|
15
|
-
|
|
16
|
-
RULE_VERSION = "confirmed_pivots_v3"
|
|
17
|
-
MIN_TOTAL_MOVE_FRACTION = 0.03
|
|
18
|
-
MAX_EXCESS_TO_WIDTH = 0.25
|
|
19
|
-
MAX_OUTSIDE_BAR_FRACTION = 0.20
|
|
20
|
-
MAX_WIDTH_FRACTION = 0.12
|
|
21
|
-
MAX_WIDTH_TO_BASE_MOVE = 2.0
|
|
22
|
-
MAX_CURRENT_END_AGE_BARS = 8
|
|
23
|
-
SAME_FAMILY_SLOPE_TOLERANCE = 0.10
|
|
24
|
-
SAME_FAMILY_WIDTH_TOLERANCE = 0.10
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def _measure_region(rows, *, first, start_price, slope, width, direction, start, stop):
|
|
28
|
-
"""Measure actual wicks against index-based edges, including any extension."""
|
|
29
|
-
maximum = 0.0
|
|
30
|
-
outside_count = 0
|
|
31
|
-
latest_close_position = None
|
|
32
|
-
for index in range(start, stop):
|
|
33
|
-
base = start_price + slope * (index - first)
|
|
34
|
-
upper, lower = (base + width, base) if direction == "ascending" else (base, base - width)
|
|
35
|
-
row = rows[index]
|
|
36
|
-
excess = max(0.0, row["high"] - upper, lower - row["low"])
|
|
37
|
-
if not all(math.isfinite(value) for value in (base, upper, lower, excess)) or lower <= 0:
|
|
38
|
-
return None
|
|
39
|
-
maximum = max(maximum, excess)
|
|
40
|
-
outside_count += excess > max(upper, lower) * 1e-12
|
|
41
|
-
tolerance = max(upper, lower) * 1e-12
|
|
42
|
-
latest_close_position = ("above_projected_upper" if row["close"] > upper + tolerance else
|
|
43
|
-
"below_projected_lower" if row["close"] < lower - tolerance else "inside")
|
|
44
|
-
return {"bar_count": stop - start, "outside_bar_count": outside_count,
|
|
45
|
-
"outside_bar_fraction": outside_count / (stop - start) if stop > start else 0.0,
|
|
46
|
-
"max_wick_excess_price": maximum, "max_wick_excess_to_width": maximum / width,
|
|
47
|
-
"latest_close_position": latest_close_position}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _same_geometric_family(candidate, representative):
|
|
51
|
-
"""Collapse near-identical alternatives built around the same parallel pivot."""
|
|
52
|
-
anchors, other = candidate["anchors"], representative["anchors"]
|
|
53
|
-
if (candidate["direction"] != representative["direction"]
|
|
54
|
-
or anchors["parallel"]["time"] != other["parallel"]["time"]):
|
|
55
|
-
return False
|
|
56
|
-
slope_scale = max(abs(candidate["slope_per_bar"]), abs(representative["slope_per_bar"]))
|
|
57
|
-
width_scale = max(candidate["width"], representative["width"])
|
|
58
|
-
return (abs(candidate["slope_per_bar"] - representative["slope_per_bar"])
|
|
59
|
-
<= SAME_FAMILY_SLOPE_TOLERANCE * slope_scale
|
|
60
|
-
and abs(candidate["width"] - representative["width"])
|
|
61
|
-
<= SAME_FAMILY_WIDTH_TOLERANCE * width_scale)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def channel_candidates(
|
|
65
|
-
rows,
|
|
66
|
-
*,
|
|
67
|
-
direction="both",
|
|
68
|
-
lookback_bars=120,
|
|
69
|
-
left_bars=2,
|
|
70
|
-
right_bars=2,
|
|
71
|
-
min_span_bars=12,
|
|
72
|
-
limit=3,
|
|
73
|
-
scope="current",
|
|
74
|
-
):
|
|
75
|
-
"""Propose channels from two confirmed same-side pivots and one opposite pivot.
|
|
76
|
-
|
|
77
|
-
Ascending channels use two rising pivot lows as the base and a pivot high
|
|
78
|
-
between them as the parallel anchor; descending channels are symmetric.
|
|
79
|
-
All coordinates are candle-index based, never elapsed-time or screen pixels.
|
|
80
|
-
The anchor interval is measured in full. Current proposals must have a
|
|
81
|
-
recent confirmed end pivot and pass an explicit arithmetic extension check
|
|
82
|
-
through the latest loaded bar. Historical proposals never infer a current
|
|
83
|
-
breakout. Neither scope confirms professional pattern quality.
|
|
84
|
-
"""
|
|
85
|
-
if not isinstance(direction, str) or direction not in {"ascending", "descending", "both"}:
|
|
86
|
-
raise LineError("invalid_channel_candidate_direction", "direction 只能是 ascending、descending 或 both。")
|
|
87
|
-
if not isinstance(scope, str) or scope not in {"current", "historical"}:
|
|
88
|
-
raise LineError("invalid_channel_candidate_scope", "scope 只能是 current 或 historical。")
|
|
89
|
-
if type(lookback_bars) is not int or not 30 <= lookback_bars <= 300:
|
|
90
|
-
raise LineError("invalid_channel_candidate_lookback", "lookback_bars 必须是30至300的整数。")
|
|
91
|
-
if type(min_span_bars) is not int or not 10 <= min_span_bars <= 100 or min_span_bars >= lookback_bars:
|
|
92
|
-
raise LineError("invalid_channel_candidate_span", "min_span_bars 必须是10至100且小于 lookback_bars。")
|
|
93
|
-
if type(limit) is not int or not 1 <= limit <= 5:
|
|
94
|
-
raise LineError("invalid_channel_candidate_limit", "limit 必须是1至5的整数。")
|
|
95
|
-
if type(left_bars) is not int or not 1 <= left_bars <= 20 or type(right_bars) is not int or not 1 <= right_bars <= 20:
|
|
96
|
-
raise LineError("invalid_pivot_window", "left_bars 和 right_bars 必须是1至20的整数。")
|
|
97
|
-
# The pivot helper validates window parameters and does not use incomplete
|
|
98
|
-
# right-hand windows. Its 50-candidate cap bounds pair enumeration.
|
|
99
|
-
try:
|
|
100
|
-
candles = validate_rows(rows, min_len=max(min_span_bars + 1, left_bars + right_bars + 1))
|
|
101
|
-
except RowsValidationError:
|
|
102
|
-
raise LineError("insufficient_channel_candidate_history", "当前已加载K线不足以计算通道候选;未补取行情。") from None
|
|
103
|
-
selected = candles[-lookback_bars:]
|
|
104
|
-
if any(row["low"] <= 0 or row["high"] < max(row["open"], row["close"], row["low"])
|
|
105
|
-
or row["low"] > min(row["open"], row["close"]) for row in selected):
|
|
106
|
-
raise LineError("invalid_channel_candidate_data", "通道候选需要高低价为正且 OHLC 一致的K线;未忽略异常柱。")
|
|
107
|
-
pivot_result = confirmed_pivots(selected, left_bars=left_bars, right_bars=right_bars, limit=50)
|
|
108
|
-
index_by_time = {row["time"]: index for index, row in enumerate(selected)}
|
|
109
|
-
pivots = {side: [] for side in ("high", "low")}
|
|
110
|
-
for pivot in pivot_result["candidates"]:
|
|
111
|
-
pivots[pivot["side"]].append((index_by_time[int(pivot["time"])], pivot["price"]))
|
|
112
|
-
|
|
113
|
-
candidates = []
|
|
114
|
-
rejection_counts = Counter()
|
|
115
|
-
considered_anchor_pairs = 0
|
|
116
|
-
for trend in (("ascending", "low", "high"), ("descending", "high", "low")):
|
|
117
|
-
name, base_side, opposite_side = trend
|
|
118
|
-
if direction not in {"both", name}:
|
|
119
|
-
continue
|
|
120
|
-
base_pivots = pivots[base_side]
|
|
121
|
-
for first_pos, (first, start_price) in enumerate(base_pivots):
|
|
122
|
-
for last, end_price in base_pivots[first_pos + 1:]:
|
|
123
|
-
span = last - first
|
|
124
|
-
if span < min_span_bars:
|
|
125
|
-
continue
|
|
126
|
-
considered_anchor_pairs += 1
|
|
127
|
-
slope = (end_price - start_price) / span
|
|
128
|
-
move_fraction = abs(end_price - start_price) / start_price
|
|
129
|
-
if (name == "ascending" and slope <= 0) or (name == "descending" and slope >= 0):
|
|
130
|
-
rejection_counts["wrong_direction"] += 1
|
|
131
|
-
continue
|
|
132
|
-
if move_fraction < MIN_TOTAL_MOVE_FRACTION:
|
|
133
|
-
rejection_counts["weak_base_move"] += 1
|
|
134
|
-
continue
|
|
135
|
-
opposite = []
|
|
136
|
-
for index, price in pivots[opposite_side]:
|
|
137
|
-
if first < index < last:
|
|
138
|
-
base_at_pivot = start_price + slope * (index - first)
|
|
139
|
-
width = (price - base_at_pivot) * (1 if name == "ascending" else -1)
|
|
140
|
-
if math.isfinite(width) and width > 0:
|
|
141
|
-
opposite.append((width, index, price))
|
|
142
|
-
if not opposite:
|
|
143
|
-
rejection_counts["no_interior_opposite_pivot"] += 1
|
|
144
|
-
continue
|
|
145
|
-
# The widest confirmed opposite pivot makes the parallel edge;
|
|
146
|
-
# stable tie-breaking favors the earlier pivot.
|
|
147
|
-
width, parallel_index, parallel_price = max(opposite, key=lambda value: (value[0], -value[1]))
|
|
148
|
-
median_close = median(row["close"] for row in selected[first:last + 1])
|
|
149
|
-
width_fraction = width / median_close
|
|
150
|
-
width_to_base_move = width / abs(end_price - start_price)
|
|
151
|
-
if not math.isfinite(width_fraction) or width_fraction > MAX_WIDTH_FRACTION:
|
|
152
|
-
rejection_counts["too_wide_vs_price"] += 1
|
|
153
|
-
continue
|
|
154
|
-
if not math.isfinite(width_to_base_move) or width_to_base_move > MAX_WIDTH_TO_BASE_MOVE:
|
|
155
|
-
rejection_counts["too_wide_vs_base_move"] += 1
|
|
156
|
-
continue
|
|
157
|
-
anchor_measurement = _measure_region(selected, first=first, start_price=start_price,
|
|
158
|
-
slope=slope, width=width, direction=name, start=first, stop=last + 1)
|
|
159
|
-
if (anchor_measurement is None or
|
|
160
|
-
anchor_measurement["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH):
|
|
161
|
-
rejection_counts["anchor_interval_boundary_breach"] += 1
|
|
162
|
-
continue
|
|
163
|
-
if anchor_measurement["outside_bar_fraction"] > MAX_OUTSIDE_BAR_FRACTION:
|
|
164
|
-
rejection_counts["too_many_anchor_interval_breaches"] += 1
|
|
165
|
-
continue
|
|
166
|
-
age = len(selected) - 1 - last
|
|
167
|
-
if scope == "current" and age > MAX_CURRENT_END_AGE_BARS:
|
|
168
|
-
rejection_counts["end_anchor_too_old"] += 1
|
|
169
|
-
continue
|
|
170
|
-
post_end = {"evaluated": False, "reason": "historical_scope_no_current_inference"}
|
|
171
|
-
if scope == "current":
|
|
172
|
-
measured = _measure_region(selected, first=first, start_price=start_price,
|
|
173
|
-
slope=slope, width=width, direction=name, start=last + 1, stop=len(selected))
|
|
174
|
-
if measured is None:
|
|
175
|
-
rejection_counts["invalid_post_end_projection"] += 1
|
|
176
|
-
continue
|
|
177
|
-
if (measured["max_wick_excess_to_width"] > MAX_EXCESS_TO_WIDTH
|
|
178
|
-
or measured["latest_close_position"] != "inside"):
|
|
179
|
-
rejection_counts["post_end_boundary_breach"] += 1
|
|
180
|
-
continue
|
|
181
|
-
post_end = {"evaluated": True, "basis": "arithmetic_extension_not_pattern_confirmation",
|
|
182
|
-
**measured}
|
|
183
|
-
anchors = {
|
|
184
|
-
"from": {"time": selected[first]["time"], "price": start_price, "ohlc_field": base_side},
|
|
185
|
-
"to": {"time": selected[last]["time"], "price": end_price, "ohlc_field": base_side},
|
|
186
|
-
"parallel": {"time": selected[parallel_index]["time"], "price": parallel_price,
|
|
187
|
-
"ohlc_field": opposite_side},
|
|
188
|
-
}
|
|
189
|
-
candidates.append({
|
|
190
|
-
"direction": name,
|
|
191
|
-
"anchors": anchors,
|
|
192
|
-
"span_bars": span + 1,
|
|
193
|
-
"bars_since_end": age,
|
|
194
|
-
"slope_per_bar": slope,
|
|
195
|
-
"width": width,
|
|
196
|
-
"width_fraction_of_median_close": width_fraction,
|
|
197
|
-
"width_to_base_move": width_to_base_move,
|
|
198
|
-
"base_move_fraction": move_fraction,
|
|
199
|
-
"max_wick_excess_price": anchor_measurement["max_wick_excess_price"],
|
|
200
|
-
"max_wick_excess_to_width": anchor_measurement["max_wick_excess_to_width"],
|
|
201
|
-
"outside_bar_count": anchor_measurement["outside_bar_count"],
|
|
202
|
-
"outside_bar_fraction": anchor_measurement["outside_bar_fraction"],
|
|
203
|
-
"post_end": post_end,
|
|
204
|
-
"scope": scope,
|
|
205
|
-
"anchor_rule": "two_confirmed_same_side_pivots_plus_widest_interior_opposite_pivot",
|
|
206
|
-
"measurement_range": "anchor_interval_inclusive_post_end_separate",
|
|
207
|
-
"_end_index": last,
|
|
208
|
-
})
|
|
209
|
-
# Newer, more compact, less-violated candidates first. No opaque score.
|
|
210
|
-
candidates.sort(key=lambda item: (-item["_end_index"], item["max_wick_excess_to_width"],
|
|
211
|
-
item["width_to_base_move"], -item["span_bars"],
|
|
212
|
-
item["direction"], item["anchors"]["from"]["time"]))
|
|
213
|
-
qualified_before_dedup = len(candidates)
|
|
214
|
-
distinct = []
|
|
215
|
-
seen_families = set()
|
|
216
|
-
for candidate in candidates:
|
|
217
|
-
del candidate["_end_index"]
|
|
218
|
-
family = (candidate["direction"], candidate["anchors"]["to"]["time"],
|
|
219
|
-
candidate["anchors"]["parallel"]["time"])
|
|
220
|
-
if family in seen_families or any(_same_geometric_family(candidate, kept) for kept in distinct):
|
|
221
|
-
continue
|
|
222
|
-
seen_families.add(family)
|
|
223
|
-
distinct.append(candidate)
|
|
224
|
-
return {
|
|
225
|
-
"rule_version": RULE_VERSION,
|
|
226
|
-
"direction": direction,
|
|
227
|
-
"scope": scope,
|
|
228
|
-
"lookback_bars": lookback_bars,
|
|
229
|
-
"left_bars": left_bars,
|
|
230
|
-
"right_bars": right_bars,
|
|
231
|
-
"min_span_bars": min_span_bars,
|
|
232
|
-
"considered_anchor_pairs": considered_anchor_pairs,
|
|
233
|
-
"rejection_counts": dict(sorted(rejection_counts.items())),
|
|
234
|
-
"qualified_before_dedup": qualified_before_dedup,
|
|
235
|
-
"deduplicated_count": qualified_before_dedup - len(distinct),
|
|
236
|
-
"candidate_count": len(distinct),
|
|
237
|
-
"returned": min(limit, len(distinct)),
|
|
238
|
-
"truncated": len(distinct) > limit,
|
|
239
|
-
"no_candidate_reason": "no_anchor_triple_passed_rules" if not distinct else None,
|
|
240
|
-
"no_candidate_explanation": ("没有三锚点组合同时满足全部筛选规则;不能据此推断近期没有已确认拐点,或真实走势不存在通道。"
|
|
241
|
-
if not distinct else None),
|
|
242
|
-
"pivot_scan": {"considered": pivot_result["candidate_count"],
|
|
243
|
-
"total": pivot_result["total_candidates"], "truncated": pivot_result["truncated"],
|
|
244
|
-
"recent_confirmed_high_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
|
|
245
|
-
for index, _ in pivots["high"]),
|
|
246
|
-
"recent_confirmed_low_count": sum(len(selected) - 1 - index <= MAX_CURRENT_END_AGE_BARS
|
|
247
|
-
for index, _ in pivots["low"])},
|
|
248
|
-
"candidates": distinct[:limit],
|
|
249
|
-
"thresholds": {"min_total_move_fraction": MIN_TOTAL_MOVE_FRACTION,
|
|
250
|
-
"max_wick_excess_to_width": MAX_EXCESS_TO_WIDTH,
|
|
251
|
-
"max_outside_bar_fraction": MAX_OUTSIDE_BAR_FRACTION,
|
|
252
|
-
"max_width_fraction_of_median_close": MAX_WIDTH_FRACTION,
|
|
253
|
-
"max_width_to_base_move": MAX_WIDTH_TO_BASE_MOVE,
|
|
254
|
-
"max_current_end_age_bars": MAX_CURRENT_END_AGE_BARS,
|
|
255
|
-
"same_family_slope_tolerance": SAME_FAMILY_SLOPE_TOLERANCE,
|
|
256
|
-
"same_family_width_tolerance": SAME_FAMILY_WIDTH_TOLERANCE},
|
|
257
|
-
"limitations": ["geometry_only_requires_result_review", "confirmed_pivots_lag_right_bars",
|
|
258
|
-
"arithmetic_extension_not_breakout_confirmation", "no_drawing_created"],
|
|
259
|
-
"drawing_created": False,
|
|
260
|
-
}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
"""Read-only arithmetic for a host-chosen channel, not fitting or recognition."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from datetime import datetime
|
|
5
|
-
import math
|
|
6
|
-
from typing import Any
|
|
7
|
-
|
|
8
|
-
from tools.channels import channel_geometry
|
|
9
|
-
from tools.lines import LineError, validate_line_fields
|
|
10
|
-
from tools.trend_lines import CN_TZ, resolve_anchor_time
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def preview_channel(rows: list[dict], interval: str, *, start_time: str, start_price: float,
|
|
14
|
-
end_time: str, end_price: float, parallel_time: str, parallel_price: float,
|
|
15
|
-
bar_limit: int = 200) -> dict[str, Any]:
|
|
16
|
-
"""Rows have already passed live-observation validation; never fetch or publish."""
|
|
17
|
-
if isinstance(bar_limit, bool) or not isinstance(bar_limit, int) or not 1 <= bar_limit <= 4000:
|
|
18
|
-
raise LineError("invalid_preview_limit", "bar_limit 为1至4000整数;汇总始终核对完整起止区间。")
|
|
19
|
-
source = {"interval": interval, "chartCommands": [{"type": "SET_CANDLES", "rows": rows}]}
|
|
20
|
-
anchors = []
|
|
21
|
-
for timestamp, price in ((start_time, start_price), (end_time, end_price), (parallel_time, parallel_price)):
|
|
22
|
-
price, _, _ = validate_line_fields(price=price)
|
|
23
|
-
if price is None:
|
|
24
|
-
raise LineError("invalid_price", "三个锚点都需要明确的有限正价格。")
|
|
25
|
-
anchors.append({"time": resolve_anchor_time(source, timestamp), "price": price})
|
|
26
|
-
start, end, parallel = anchors
|
|
27
|
-
geometry = channel_geometry(source, start, end, parallel)
|
|
28
|
-
region = [row for row in rows if start["time"] <= row["time"] <= end["time"]]
|
|
29
|
-
if len(region) > 4000:
|
|
30
|
-
raise LineError("measurement_capacity", "通道核对区间超过4000根;未使用截断样本代替全区间。")
|
|
31
|
-
# Only numerical roundoff, not a subjective touch/fitting tolerance. Keep
|
|
32
|
-
# signed raw distances unrounded and expose the allowance used by counts.
|
|
33
|
-
scale = max(*(a["price"] for edge in ("upper", "lower") for a in geometry[edge].values()),
|
|
34
|
-
*(row[field] for row in region for field in ("low", "high")))
|
|
35
|
-
epsilon = scale * 1e-12
|
|
36
|
-
measured = []
|
|
37
|
-
for index, row in enumerate(region):
|
|
38
|
-
upper = geometry["upper"]["from"]["price"] + geometry["slope_per_bar"] * index
|
|
39
|
-
lower = geometry["lower"]["from"]["price"] + geometry["slope_per_bar"] * index
|
|
40
|
-
values = {"high_minus_upper": row["high"] - upper, "low_minus_lower": row["low"] - lower,
|
|
41
|
-
"body_high_minus_upper": max(row["open"], row["close"]) - upper,
|
|
42
|
-
"body_low_minus_lower": min(row["open"], row["close"]) - lower}
|
|
43
|
-
if not all(math.isfinite(v) for v in (upper, lower, *values.values())):
|
|
44
|
-
raise LineError("nonfinite_channel_measurement", "通道偏差计算超出有限数值范围,未输出部分核对结果。")
|
|
45
|
-
try:
|
|
46
|
-
instant = datetime.fromtimestamp(row["time"], CN_TZ)
|
|
47
|
-
date, iso = instant.date().isoformat(), instant.isoformat(timespec="seconds")
|
|
48
|
-
except (ValueError, OverflowError, OSError):
|
|
49
|
-
date, iso = None, None
|
|
50
|
-
measured.append({"time": row["time"], "date": date, "iso": iso,
|
|
51
|
-
"bar_offset": index, "upper_price": upper, "lower_price": lower,
|
|
52
|
-
"ohlc": {k: row[k] for k in ("open", "high", "low", "close")}, **values})
|
|
53
|
-
summary = {}
|
|
54
|
-
for key, field, sign in (("wick_above", "high_minus_upper", 1), ("wick_below", "low_minus_lower", -1),
|
|
55
|
-
("body_above", "body_high_minus_upper", 1), ("body_below", "body_low_minus_lower", -1)):
|
|
56
|
-
distances = [bar[field] * sign for bar in measured]
|
|
57
|
-
maximum = max(distances)
|
|
58
|
-
witness = measured[distances.index(maximum)]
|
|
59
|
-
summary[key] = {"bar_count": sum(d > epsilon for d in distances),
|
|
60
|
-
"max_price_excess": max(0, maximum),
|
|
61
|
-
"max_excess_witness": {k: witness[k] for k in ("time", "date", "iso", "bar_offset")}
|
|
62
|
-
if maximum > epsilon else None}
|
|
63
|
-
provenance = []
|
|
64
|
-
by_time = {r["time"]: r for r in region}
|
|
65
|
-
for anchor in anchors:
|
|
66
|
-
row = by_time[anchor["time"]]
|
|
67
|
-
provenance.append({**anchor, "exact_matching_ohlc_fields": [k for k in ("open", "high", "low", "close")
|
|
68
|
-
if row[k] == anchor["price"]],
|
|
69
|
-
"price_origin": "caller_supplied_not_selected_by_plugin"})
|
|
70
|
-
return {"schema_version": 1, "evidence_scope": "loaded_browser_candles",
|
|
71
|
-
"range_policy": "inclusive_start_end_only_no_extension", "bar_count": len(region),
|
|
72
|
-
"anchors": dict(zip(("from", "to", "parallel"), provenance)), "geometry": geometry,
|
|
73
|
-
"numeric_policy": {"arithmetic": "float64_unrounded_signed_distances",
|
|
74
|
-
"count_roundoff_allowance": epsilon, "allowance_basis": "max_boundary_and_region_wick_price_times_1e-12",
|
|
75
|
-
"meaning": "numerical_roundoff_only_not_market_touch_tolerance"},
|
|
76
|
-
"distance_convention": "positive high_minus_upper is above; negative low_minus_lower is below; body fields use open/close extrema",
|
|
77
|
-
"summary": summary, "bars": measured[:bar_limit],
|
|
78
|
-
"bar_selection": {"total": len(measured), "returned": min(bar_limit, len(measured)),
|
|
79
|
-
"truncated": len(measured) > bar_limit, "order": "ascending", "sample": "first_limit",
|
|
80
|
-
"summary_scope": "full_inclusive_region"},
|
|
81
|
-
"pattern_classification": "not_provided", "touch_count": "not_provided",
|
|
82
|
-
"quality_score": "not_provided", "drawing_created": False, "render_verified": False}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
"""Three-anchor, finite parallel price channels on the chart's candle-index axis."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
import hashlib
|
|
6
|
-
import math
|
|
7
|
-
import secrets
|
|
8
|
-
from typing import Any
|
|
9
|
-
|
|
10
|
-
from tools.lines import LineError, validate_line_fields
|
|
11
|
-
from tools.trend_lines import resolve_anchor_time
|
|
12
|
-
|
|
13
|
-
CHANNEL_COMMAND = "DRAW_AGENT_CHANNEL"
|
|
14
|
-
MAX_CHANNELS = 30
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def channels(payload: dict[str, Any]) -> list[dict[str, Any]]:
|
|
18
|
-
return deepcopy([c for c in payload.get("chartCommands", []) if c.get("type") == CHANNEL_COMMAND])
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def channel_geometry(payload: dict[str, Any], start: dict, end: dict, parallel: dict) -> dict[str, Any]:
|
|
22
|
-
rows = next((c.get("rows", []) for c in payload.get("chartCommands", []) if c.get("type") == "SET_CANDLES"), [])
|
|
23
|
-
times = [r["time"] for r in rows]
|
|
24
|
-
if any(times.count(a["time"]) != 1 for a in (start, end, parallel)) or any(a >= b for a, b in zip(times, times[1:])):
|
|
25
|
-
raise LineError("invalid_channel_rows", "通道需要唯一、按时间递增的 K 线锚点。")
|
|
26
|
-
if start["time"] >= end["time"]:
|
|
27
|
-
raise LineError("invalid_anchor_order", "通道起点必须早于终点,未自动交换锚点。")
|
|
28
|
-
if not start["time"] <= parallel["time"] <= end["time"]:
|
|
29
|
-
raise LineError("parallel_anchor_outside", "第三点必须位于起止时间范围内;请明确指定,不自动挪动。")
|
|
30
|
-
i, j, k = (times.index(a["time"]) for a in (start, end, parallel))
|
|
31
|
-
# Candles are equally spaced on screen, even across weekends/holidays.
|
|
32
|
-
slope = (end["price"] - start["price"]) / (j - i)
|
|
33
|
-
offset = parallel["price"] - (start["price"] + slope * (k - i))
|
|
34
|
-
tolerance = max(start["price"], end["price"], parallel["price"]) * 1e-12
|
|
35
|
-
if not math.isfinite(offset) or abs(offset) <= tolerance:
|
|
36
|
-
raise LineError("zero_channel_width", "第三点落在基准线上,不能形成有宽度的通道。")
|
|
37
|
-
other = {"from": {"time": start["time"], "price": start["price"] + offset},
|
|
38
|
-
"to": {"time": end["time"], "price": end["price"] + offset}}
|
|
39
|
-
if any(not math.isfinite(a["price"]) or a["price"] <= 0 for a in other.values()):
|
|
40
|
-
raise LineError("invalid_channel_boundary", "推导后的平行边界价格必须大于零且有限,请调整第三点。")
|
|
41
|
-
base = {"from": deepcopy(start), "to": deepcopy(end)}
|
|
42
|
-
upper, lower = (other, base) if offset > 0 else (base, other)
|
|
43
|
-
return {"upper": upper, "lower": lower, "width": abs(offset), "signed_offset": offset,
|
|
44
|
-
"slope_per_bar": slope, "direction": "ascending" if slope > 0 else "descending" if slope < 0 else "horizontal",
|
|
45
|
-
"geometry_basis": "candle_index_linear_price"}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def edit_channel(
|
|
49
|
-
payload: dict[str, Any], action: str, *, channel_id: str | None = None,
|
|
50
|
-
start_time: str | None = None, start_price: float | None = None,
|
|
51
|
-
end_time: str | None = None, end_price: float | None = None,
|
|
52
|
-
parallel_time: str | None = None, parallel_price: float | None = None,
|
|
53
|
-
name: str | None = None, color: str | None = None,
|
|
54
|
-
show_midline: bool | None = None, request_id: str | None = None,
|
|
55
|
-
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
56
|
-
result = deepcopy(payload)
|
|
57
|
-
commands = result.get("chartCommands", [])
|
|
58
|
-
previous = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("id") == channel_id), None)
|
|
59
|
-
if action in {"update", "delete"} and previous is None:
|
|
60
|
-
raise LineError("channel_not_found", "当前快照不存在该 AI 通道,请先读取通道 ID。")
|
|
61
|
-
if action == "delete":
|
|
62
|
-
commands.remove(previous); result["chartCommands"] = commands
|
|
63
|
-
return result, deepcopy(previous)
|
|
64
|
-
if action not in {"create", "update"}:
|
|
65
|
-
raise LineError("invalid_action", "不支持的通道操作。")
|
|
66
|
-
values = (start_time, start_price, end_time, end_price, parallel_time, parallel_price)
|
|
67
|
-
if action == "create" and any(v is None for v in values):
|
|
68
|
-
raise LineError("missing_anchor", "创建通道需要基准线两点及第三个平行边界锚点,每点明确时间和价格。")
|
|
69
|
-
if action == "update" and all(v is None for v in (*values, name, color, show_midline)):
|
|
70
|
-
raise LineError("empty_update", "请至少修改一个锚点、名称、颜色或中线开关。")
|
|
71
|
-
if show_midline is not None and not isinstance(show_midline, bool):
|
|
72
|
-
raise LineError("invalid_midline", "show_midline 必须是布尔值。")
|
|
73
|
-
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
74
|
-
anchors = []
|
|
75
|
-
for key, time, price in (("from", start_time, start_price), ("to", end_time, end_price), ("parallel", parallel_time, parallel_price)):
|
|
76
|
-
old = previous.get(key, {}) if previous else {}
|
|
77
|
-
value, _, _ = validate_line_fields(price=price if price is not None else old.get("price"))
|
|
78
|
-
anchors.append({"time": resolve_anchor_time(payload, time) if time is not None else old["time"], "price": value})
|
|
79
|
-
start, end, parallel = anchors
|
|
80
|
-
geometry = channel_geometry(payload, start, end, parallel)
|
|
81
|
-
channel = {"type": CHANNEL_COMMAND, "id": previous["id"] if previous else "channel_" + secrets.token_hex(12),
|
|
82
|
-
"interval": payload.get("interval"), "from": start, "to": end, "parallel": parallel,
|
|
83
|
-
"label": name if name is not None else previous["label"] if previous else "",
|
|
84
|
-
"color": color if color is not None else previous["color"] if previous else "info",
|
|
85
|
-
"show_midline": show_midline if show_midline is not None else previous["show_midline"] if previous else True,
|
|
86
|
-
**geometry}
|
|
87
|
-
if previous and previous.get("create_request_id"):
|
|
88
|
-
channel["create_request_id"] = previous["create_request_id"]
|
|
89
|
-
if action == "create":
|
|
90
|
-
if request_id:
|
|
91
|
-
channel["create_request_id"] = request_id
|
|
92
|
-
channel["id"] = "channel_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
93
|
-
retry = next((c for c in commands if c.get("type") == CHANNEL_COMMAND and c.get("create_request_id") == request_id), None)
|
|
94
|
-
if retry:
|
|
95
|
-
if any(retry.get(k) != channel[k] for k in ("from", "to", "parallel", "label", "color", "show_midline")):
|
|
96
|
-
raise LineError("request_conflict", "同一 request_id 的通道参数不同,请使用新的 request_id。")
|
|
97
|
-
return result, deepcopy(retry)
|
|
98
|
-
if len(channels(result)) >= MAX_CHANNELS:
|
|
99
|
-
raise LineError("too_many_channels", "当前图表最多保存 30 个 AI 通道。")
|
|
100
|
-
commands.append(channel)
|
|
101
|
-
else:
|
|
102
|
-
commands[commands.index(previous)] = channel
|
|
103
|
-
result["chartCommands"] = commands
|
|
104
|
-
return result, deepcopy(channel)
|