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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/lib/client.js +9 -1
  2. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +47 -0
  3. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +107 -201
  4. package/node_modules/@ftshare-lab/dsh-kline/README.md +106 -216
  5. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +3 -2
  6. package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +103 -11
  7. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +8 -0
  8. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
  9. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +1 -1
  10. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +11 -1
  11. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +6 -1
  12. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +2971 -835
  13. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +35 -3
  14. package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +91 -0
  15. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +25 -0
  16. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +5 -0
  17. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +2 -0
  18. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +4 -0
  19. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
  20. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +38 -0
  21. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +55 -0
  22. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +13 -1
  23. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +3 -9
  24. package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +2 -0
  25. package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -6
  26. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +4 -1
  27. package/node_modules/@ftshare-lab/dsh-kline/server.py +46 -25
  28. package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +158 -0
  29. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +1 -1
  30. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +1 -1
  31. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +30 -12
  32. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +53 -68
  33. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +3 -1
  34. package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +68 -0
  35. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +18 -2
  36. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +2 -2
  37. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +2 -3
  38. package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +66 -0
  39. package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +103 -0
  40. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +12 -6
  41. package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +311 -0
  42. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +1 -1
  43. package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +123 -0
  44. package/package.json +2 -2
  45. package/src/client/index.js +8 -0
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PaperKlinePanel.d.ts +0 -15
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/canvas-panel.d.ts +0 -33
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -55
@@ -61,7 +61,8 @@ def resolve_points(payload, points):
61
61
 
62
62
 
63
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):
64
+ point_time=None, point_price=None, name=None, color=None, request_id=None,
65
+ replace_from_result=False):
65
66
  result = deepcopy(payload)
66
67
  commands = result.get("chartCommands", [])
67
68
  matches = [c for c in commands if c.get("type") == POLYLINE_COMMAND and c.get("id") == polyline_id]
@@ -85,10 +86,15 @@ def edit_polyline(payload, action, *, polyline_id=None, points=None, point_label
85
86
  else:
86
87
  # Updating one point must not require the LLM to copy/reconstruct its
87
88
  # neighbours. Full replacement/point insertion/removal are out of scope.
88
- if points is not None:
89
+ if points is not None and not replace_from_result:
89
90
  raise LineError("polyline_replacement_not_supported", "续改请用 point_label 及 point_time / point_price,仅改目标点;不接受整组重写。")
90
- path = validate_stored_points(previous["points"])
91
- if point_label is not None:
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:
92
98
  label = normalize_point_label(point_label)
93
99
  if point_time is None and point_price is None:
94
100
  raise LineError("empty_point_update", "请明确目标点的新时间或价格,不能猜移动幅度。")
@@ -97,9 +103,9 @@ def edit_polyline(payload, action, *, polyline_id=None, points=None, point_label
97
103
  raise LineError("point_not_found", "当前组内不存在该点名;请核对点名,不按位置或近似名称猜点。")
98
104
  if point_time is not None: target["time"] = resolve_anchor_time(payload, point_time)
99
105
  if point_price is not None: target["price"] = validate_line_fields(price=point_price)[0]
100
- elif point_time is not None or point_price is not None:
106
+ elif not replace_from_result and (point_time is not None or point_price is not None):
101
107
  raise LineError("point_label_required", "修改单点必须明确组内 point_label。")
102
- elif name is None and color is None:
108
+ elif not replace_from_result and name is None and color is None:
103
109
  raise LineError("empty_update", "请指定点名及新时间 / 价格,或整组名称 / 颜色。")
104
110
  path = validate_stored_points(path)
105
111
  for point in path: resolve_anchor_time(payload, str(point["time"]))
@@ -0,0 +1,311 @@
1
+ """Causal, read-only daily price patterns. Shared by DSH and Codex hosts."""
2
+ from __future__ import annotations
3
+
4
+ from collections import Counter
5
+ from datetime import datetime
6
+ from math import isfinite
7
+
8
+ import numpy as np
9
+ import talib
10
+
11
+ from tools.closed_daily import closed_daily
12
+ from tools.lines import LineError
13
+ from tools.range_candidates import DEFAULT_WINDOW_SIZES, range_candidates
14
+
15
+ RULE_VERSION = "price_patterns_v1"
16
+ TYPES = ("double_top", "double_bottom", "head_shoulders_top", "head_shoulders_bottom", "platform")
17
+ # The older, geometry-only range proposal tolerates a half-box close drift.
18
+ # A labelled price pattern needs a visibly flatter base. Keep that proposal
19
+ # API unchanged, but reject directional boxes during historical replay.
20
+ MAX_PLATFORM_DRIFT_TO_WIDTH = .35
21
+
22
+
23
+ def _pivots(rows):
24
+ result = {}
25
+ for index in range(2, len(rows) - 2):
26
+ neighbors = rows[index - 2:index] + rows[index + 1:index + 3]
27
+ high = all(rows[index]["high"] > x["high"] for x in neighbors)
28
+ low = all(rows[index]["low"] < x["low"] for x in neighbors)
29
+ if high != low:
30
+ result.setdefault(index + 2, []).append({"index": index, "side": "high" if high else "low",
31
+ "price": rows[index]["high"] if high else rows[index]["low"],
32
+ "time": rows[index]["time"]})
33
+ return result
34
+
35
+
36
+ def _neckline(anchors, index):
37
+ a, b = anchors[1], anchors[3]
38
+ return a["price"] + (b["price"] - a["price"]) * (index - a["index"]) / (b["index"] - a["index"])
39
+
40
+
41
+ def _structure(kind, anchors, atr, rows, reasons):
42
+ top = kind.endswith("top")
43
+ first = anchors[0]["index"]
44
+ # Twenty completed intervals before the anchor require 21 earlier closes.
45
+ # At first == 20, first - 21 would wrap to the final (future) row.
46
+ if first < 21:
47
+ reasons["insufficient_prior_trend"] += 1
48
+ return None
49
+ trend = rows[first - 1]["close"] - rows[first - 21]["close"]
50
+ if (trend if top else -trend) < 2 * atr:
51
+ reasons["prior_trend_below_2_atr"] += 1
52
+ return None
53
+ if kind.startswith("double"):
54
+ a, middle, b = anchors
55
+ gap = b["index"] - a["index"]
56
+ mean = (a["price"] + b["price"]) / 2
57
+ depth = (min(a["price"], b["price"]) - middle["price"]) if top else (middle["price"] - max(a["price"], b["price"]))
58
+ if not 10 <= gap <= 120 or abs(a["price"] - b["price"]) > min(atr, .03 * mean) or depth < 2 * atr:
59
+ reasons["double_geometry_rejected"] += 1
60
+ return None
61
+ neck = middle["price"]
62
+ outer = max(a["price"], b["price"]) if top else min(a["price"], b["price"])
63
+ return {"neckline": {"type": "horizontal", "price": neck}, "outer": outer}
64
+ a, n1, head, n2, b = anchors
65
+ gaps = [anchors[j + 1]["index"] - anchors[j]["index"] for j in range(4)]
66
+ span = b["index"] - a["index"]
67
+ left, right = head["index"] - a["index"], b["index"] - head["index"]
68
+ neck_at_head = _neckline(anchors, head["index"])
69
+ height = (head["price"] - neck_at_head) if top else (neck_at_head - head["price"])
70
+ mean_shoulder = (a["price"] + b["price"]) / 2
71
+ protrudes = min((head["price"] - a["price"] if top else a["price"] - head["price"]),
72
+ (head["price"] - b["price"] if top else b["price"] - head["price"]))
73
+ if (min(gaps) < 3 or not 20 <= span <= 160 or not .5 <= left / right <= 2
74
+ or protrudes < atr or height < 2 * atr or abs(a["price"] - b["price"]) > min(.5 * height, .03 * mean_shoulder)
75
+ or abs(n1["price"] - n2["price"]) > .5 * height):
76
+ reasons["head_shoulders_geometry_rejected"] += 1
77
+ return None
78
+ return {"neckline": {"type": "sloped", "from": {"index": n1["index"], "time": n1["time"], "price": n1["price"]},
79
+ "to": {"index": n2["index"], "time": n2["time"], "price": n2["price"]}},
80
+ "outer": head["price"]}
81
+
82
+
83
+ def _boundary(item, index):
84
+ if item["type"] == "platform":
85
+ return item["box"]
86
+ neck = item["neckline"]
87
+ if neck["type"] == "horizontal":
88
+ return neck["price"]
89
+ a, b = neck["from"], neck["to"]
90
+ return a["price"] + (b["price"] - a["price"]) * (index - a["index"]) / (b["index"] - a["index"])
91
+
92
+
93
+ def _outside(item, row, index, direction):
94
+ base = _boundary(item, index)
95
+ if item["type"] == "platform":
96
+ edge = base["upper_price"] if direction == "up" else base["lower_price"]
97
+ else:
98
+ edge = base
99
+ return row["close"] > edge + item["buffer"] if direction == "up" else row["close"] < edge - item["buffer"]
100
+
101
+
102
+ def _reclaimed(item, row, index):
103
+ base = _boundary(item, index)
104
+ if item["type"] == "platform":
105
+ # Back inside the frozen box, not merely below its upper breakout edge.
106
+ return (row["close"] < base["upper_price"] - item["buffer"] if item["break_direction"] == "up"
107
+ else row["close"] > base["lower_price"] + item["buffer"])
108
+ return (row["close"] > base + item["buffer"] if item["break_direction"] == "down"
109
+ else row["close"] < base - item["buffer"])
110
+
111
+
112
+ def _advance(item, row, index):
113
+ if item["status"] in {"structurally_invalid", "expired", "breakout_failed"}:
114
+ return
115
+ def event(name):
116
+ item["events"].append({"type": name, "time": row["time"], "index": index})
117
+ if item["confirmed_index"] is None:
118
+ if item["type"] != "platform" and ((item["direction"] == "down" and row["high"] > item["outer"] + item["buffer"])
119
+ or (item["direction"] == "up" and row["low"] < item["outer"] - item["buffer"])):
120
+ item["status"] = "structurally_invalid"; item["invalidated_at"] = row["time"]; event("structurally_invalid"); return
121
+ if index - item["available_index"] > 60:
122
+ item["status"] = "expired"; item["invalidated_at"] = row["time"]; event("expired"); return
123
+ direction = item.get("pending_direction") or item["direction"]
124
+ if item["pending_direction"] and _outside(item, row, index, direction):
125
+ item["status"] = "price_confirmed"; item["confirmed_at"] = row["time"]
126
+ item["confirmed_index"] = index; item["break_direction"] = direction
127
+ item["pending_direction"] = None; event("price_confirmed")
128
+ return
129
+ if item["pending_direction"]:
130
+ item["pending_direction"] = None; item["status"] = "candidate"; event("pending_cancelled")
131
+ directions = ("up", "down") if item["type"] == "platform" else (item["direction"],)
132
+ for side in directions:
133
+ if _outside(item, row, index, side):
134
+ item["pending_direction"] = side; item["status"] = "pending_confirmation"; event("pending_confirmation"); break
135
+ return
136
+ age = index - item["confirmed_index"]
137
+ if age > 20 or item["followup_complete"]:
138
+ return
139
+ if _reclaimed(item, row, index):
140
+ item["reclaim_count"] += 1
141
+ if item["reclaim_count"] == 2:
142
+ item["status"] = "breakout_failed"; item["invalidated_at"] = row["time"]; event("breakout_failed")
143
+ return
144
+ else:
145
+ item["reclaim_count"] = 0
146
+ if age == 20:
147
+ item["followup_complete"] = True; event("followup_complete")
148
+
149
+
150
+ def _volume_evidence(rows, item, provider, volume_unit):
151
+ if provider not in {"ftshare", "eastmoney_free", "tencent_free", "builtin_free"} or volume_unit not in {"shares", "lots"}:
152
+ return {"status": "unknown", "reason": "source_or_unit_unverified"}
153
+ i = item["confirmed_index"]
154
+ if i is None or i < 20:
155
+ return {"status": "unknown", "reason": "insufficient_preceding_volume"}
156
+ baseline = [r["volume"] for r in rows[i - 20:i]]
157
+ if any(not isfinite(x) or x < 0 for x in baseline) or sum(baseline) <= 0:
158
+ return {"status": "unknown", "reason": "volume_unavailable"}
159
+ return {"status": "known", "relative_to_preceding_20": rows[i]["volume"] / (sum(baseline) / 20),
160
+ "unit": volume_unit}
161
+
162
+
163
+ def _same_platform_family(a, b):
164
+ """Coalesce near-identical displayed boxes without changing their lifecycle."""
165
+ if a["type"] != "platform" or b["type"] != "platform":
166
+ return False
167
+ tolerance = .25 * min(a["atr"], b["atr"])
168
+ return (a["status"] == b["status"] and a["confirmed_at"] == b["confirmed_at"]
169
+ and a["break_direction"] == b["break_direction"]
170
+ and abs(a["available_index"] - b["available_index"]) <= 3
171
+ and abs(a["box"]["upper_price"] - b["box"]["upper_price"]) <= tolerance
172
+ and abs(a["box"]["lower_price"] - b["box"]["lower_price"]) <= tolerance)
173
+
174
+
175
+ def _alternating_platform_touches(box):
176
+ """A rectangle needs boundary visits in alternating time order.
177
+
178
+ Two upper touches followed by two lower touches describe a directional
179
+ move, even when a broad envelope and its fitted close drift pass.
180
+ """
181
+ touches = sorted([(time, "upper") for time in box["upper_touch_times"]]
182
+ + [(time, "lower") for time in box["lower_touch_times"]])
183
+ if any(touches[i][0] == touches[i - 1][0] for i in range(1, len(touches))):
184
+ return False
185
+ return 1 + sum(touches[i][1] != touches[i - 1][1] for i in range(1, len(touches))) >= 3
186
+
187
+
188
+ def price_pattern_candidates(rows, *, symbol: str, interval: str = "day", source_interval: str | None = "day",
189
+ interval_value: int | None = 1, provider: str | None = None,
190
+ volume_unit: str | None = None, pattern_types=None,
191
+ lookback_bars: int = 240, max_candidates: int = 5,
192
+ anchor_times: tuple[int, ...] | None = None, now: datetime | None = None):
193
+ if type(lookback_bars) is not int or not 60 <= lookback_bars <= 300:
194
+ raise LineError("invalid_pattern_lookback", "价格形态观察范围必须为60至300根日线。")
195
+ if type(max_candidates) is not int or not 1 <= max_candidates <= 5:
196
+ raise LineError("invalid_pattern_limit", "价格形态最多返回1至5个候选。")
197
+ selected = tuple(pattern_types or TYPES)
198
+ if not selected or len(set(selected)) != len(selected) or any(x not in TYPES for x in selected):
199
+ raise LineError("invalid_pattern_types", "形态类型仅支持双顶、双底、头肩顶、头肩底及平台,且不得重复。")
200
+ if anchor_times is not None and (len(anchor_times) not in {3, 5}
201
+ or any(type(t) is not int for t in anchor_times)
202
+ or tuple(sorted(set(anchor_times))) != anchor_times):
203
+ raise LineError("invalid_pattern_anchor_selection", "请按时间顺序选择3个或5个不同的 K 线锚点。")
204
+ candles, metadata = closed_daily(rows, symbol=symbol, interval=interval, source_interval=source_interval,
205
+ interval_value=interval_value, provider=provider, now=now)
206
+ candles = candles[-4000:]
207
+ if len(candles) < 35:
208
+ raise LineError("insufficient_pattern_history", "价格形态需要至少35根已收盘日线,未补取行情。")
209
+ atr_values = talib.ATR(np.asarray([x["high"] for x in candles], dtype=float),
210
+ np.asarray([x["low"] for x in candles], dtype=float),
211
+ np.asarray([x["close"] for x in candles], dtype=float), timeperiod=14)
212
+ pivot_events = _pivots(candles)
213
+ alternating = []
214
+ active = []
215
+ results = []
216
+ reasons = Counter()
217
+ seen = set()
218
+ active_boxes = {}
219
+ for index, row in enumerate(candles):
220
+ atr = float(atr_values[index])
221
+ for pivot in pivot_events.get(index, ()):
222
+ if alternating and alternating[-1]["side"] == pivot["side"]:
223
+ if ((pivot["side"] == "high" and pivot["price"] > alternating[-1]["price"])
224
+ or (pivot["side"] == "low" and pivot["price"] < alternating[-1]["price"])):
225
+ alternating[-1] = pivot
226
+ continue
227
+ alternating.append(pivot)
228
+ alternating = alternating[-5:]
229
+ if not isfinite(atr) or atr <= 0:
230
+ reasons["atr_unavailable"] += 1
231
+ continue
232
+ for size, prefix, side in ((3, "double", "high"), (5, "head_shoulders", "high"),
233
+ (3, "double", "low"), (5, "head_shoulders", "low")):
234
+ kind = prefix + ("_top" if side == "high" else "_bottom")
235
+ if kind not in selected or len(alternating) < size:
236
+ continue
237
+ anchors = alternating[-size:]
238
+ if anchors[0]["side"] != side:
239
+ continue
240
+ key = (kind, tuple(p["index"] for p in anchors))
241
+ if key in seen:
242
+ continue
243
+ seen.add(key)
244
+ shape = _structure(kind, anchors, atr, candles, reasons)
245
+ if shape is None:
246
+ continue
247
+ item = {"type": kind, "anchors": [dict(p) for p in anchors], **shape,
248
+ "direction": "down" if side == "high" else "up", "atr": atr, "buffer": .25 * atr,
249
+ "available_at": row["time"], "available_index": index,
250
+ "as_of": metadata["as_of"], "status": "candidate", "events": [{"type": "candidate", "time": row["time"], "index": index}],
251
+ "pending_direction": None, "break_direction": None, "confirmed_at": None,
252
+ "confirmed_index": None, "invalidated_at": None, "reclaim_count": 0,
253
+ "followup_complete": False}
254
+ active.append(item); results.append(item)
255
+ if "platform" in selected and index >= min(DEFAULT_WINDOW_SIZES) - 1 and isfinite(atr) and atr > 0:
256
+ proposed = range_candidates(candles[max(0, index - max(DEFAULT_WINDOW_SIZES) + 1):index + 1],
257
+ window_sizes=DEFAULT_WINDOW_SIZES, limit=5)
258
+ for box in proposed["candidates"]:
259
+ if any(box[field] > MAX_PLATFORM_DRIFT_TO_WIDTH for field in (
260
+ "close_drift_to_width", "fitted_close_drift_to_width",
261
+ "recent_close_drift_to_width", "recent_fitted_close_drift_to_width")):
262
+ reasons["platform_directional_drift"] += 1
263
+ continue
264
+ if not _alternating_platform_touches(box):
265
+ reasons["platform_non_alternating_touches"] += 1
266
+ continue
267
+ key = (box["lower_price"], box["upper_price"])
268
+ if key in active_boxes:
269
+ continue
270
+ item = {"type": "platform", "anchors": [], "box": {k: box[k] for k in ("start_time", "end_time", "lower_price", "upper_price")},
271
+ "direction": None, "atr": atr, "buffer": .25 * atr,
272
+ "available_at": row["time"], "available_index": index, "as_of": metadata["as_of"],
273
+ "status": "candidate", "events": [{"type": "candidate", "time": row["time"], "index": index}], "pending_direction": None, "break_direction": None,
274
+ "confirmed_at": None, "confirmed_index": None, "invalidated_at": None,
275
+ "reclaim_count": 0, "followup_complete": False}
276
+ active_boxes[key] = item; active.append(item); results.append(item)
277
+ for item in active[:]:
278
+ if index > item["available_index"]:
279
+ _advance(item, row, index)
280
+ if item["status"] in {"structurally_invalid", "expired", "breakout_failed"} or item["followup_complete"]:
281
+ active.remove(item)
282
+ if item["type"] == "platform":
283
+ active_boxes.pop((item["box"]["lower_price"], item["box"]["upper_price"]), None)
284
+ if index > 300:
285
+ results = [r for r in results if r["available_index"] >= index - 300]
286
+ earliest = len(candles) - lookback_bars
287
+ recent = [r for r in results if r["available_index"] >= earliest]
288
+ if anchor_times is not None:
289
+ recent = [r for r in recent if tuple(a["time"] for a in r["anchors"]) == anchor_times]
290
+ if not recent: reasons["manual_selection_not_recognized"] += 1
291
+ recent.sort(key=lambda r: (r["available_index"], r["type"], tuple(a["index"] for a in r["anchors"])), reverse=True)
292
+ distinct = []
293
+ nearby_suppressed = 0
294
+ for item in recent:
295
+ if any(_same_platform_family(item, prior) for prior in distinct):
296
+ nearby_suppressed += 1
297
+ else:
298
+ distinct.append(item)
299
+ recent = distinct
300
+ for item in recent:
301
+ item["volume_evidence"] = _volume_evidence(candles, item, provider, volume_unit)
302
+ item.pop("pending_direction", None); item.pop("reclaim_count", None)
303
+ item.pop("confirmed_index", None); item.pop("available_index", None)
304
+ item.pop("followup_complete", None)
305
+ return {"rule_version": RULE_VERSION, "as_of": metadata["as_of"], "data_quality": metadata,
306
+ "lookback_bars": lookback_bars, "loaded_bars": len(candles),
307
+ "candidate_count": len(recent), "returned": min(len(recent), max_candidates),
308
+ "truncated": len(recent) > max_candidates, "nearby_platforms_suppressed": nearby_suppressed,
309
+ "rejected_reasons": dict(reasons),
310
+ "candidates": recent[:max_candidates], "drawing_created": False,
311
+ "limitations": ["rule_based_geometry_not_trading_forecast"]}
@@ -164,7 +164,7 @@ def range_candidates(rows, *, window_sizes=DEFAULT_WINDOW_SIZES, limit=3):
164
164
  "recent_bars": RECENT_BARS,
165
165
  "maximum_recent_drift_to_width": MAX_RECENT_DRIFT_TO_WIDTH,
166
166
  },
167
- "limitations": ["current_window_only", "geometry_only_requires_human_review",
167
+ "limitations": ["current_window_only", "geometry_only_requires_result_review",
168
168
  "no_breakout_signal", "no_drawing_created"],
169
169
  "drawing_created": False,
170
170
  }
@@ -0,0 +1,123 @@
1
+ """Recent, confirmed daily anchors for ordinary drawing tools.
2
+
3
+ These are geometric suggestions, not wave labels or trading signals. A direct
4
+ drawing request permits the host to choose the newest suitable result and
5
+ continue through the guarded chart edit; analysis-only requests do not.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import numpy as np
12
+ import talib
13
+
14
+ from tools.closed_daily import closed_daily
15
+ from tools.lines import LineError
16
+ from tools.pivots import confirmed_pivots
17
+
18
+ RULE_VERSION = "recent_drawing_v2"
19
+ TYPES = {"horizontal", "trend", "fibonacci", "abc"}
20
+
21
+
22
+ def recent_drawing_candidates(rows, *, symbol: str, provider: str | None,
23
+ interval: str = "day", source_interval: str | None = "day",
24
+ interval_value: int | None = 1, drawing_type: str,
25
+ lookback_bars: int = 120, max_candidates: int = 5, now=None):
26
+ if drawing_type not in TYPES:
27
+ raise LineError("unsupported_auto_drawing", "该绘图类型没有自动选点规则。")
28
+ if type(lookback_bars) is not int or not 30 <= lookback_bars <= 300:
29
+ raise LineError("invalid_auto_drawing_range", "自动选点观察范围须为30至300根日线。")
30
+ if type(max_candidates) is not int or not 1 <= max_candidates <= 5:
31
+ raise LineError("invalid_auto_drawing_limit", "自动选点最多返回1至5个候选。")
32
+ closed, quality = closed_daily(rows, symbol=symbol, provider=provider, interval=interval,
33
+ source_interval=source_interval, interval_value=interval_value, now=now)
34
+ if quality["market"] is None:
35
+ raise LineError("unsupported_auto_drawing_market", "自动选点仅支持 A/港/美股日线;仍可手动绘图。")
36
+ window = closed[-min(4000, lookback_bars):]
37
+ if len(window) < 35:
38
+ raise LineError("insufficient_auto_drawing_history", "自动选点需要至少35根已收盘日线;仍可手动绘图。")
39
+ pivots = confirmed_pivots(window, left_bars=2, right_bars=2, mode="both", limit=50)["candidates"]
40
+ # A wide bar can be both a high and a low pivot. Its ordering is unknown.
41
+ ambiguous = {p["time"] for p in pivots if sum(q["time"] == p["time"] for q in pivots) > 1}
42
+ pivots = [p for p in pivots if p["time"] not in ambiguous]
43
+ index_by_time = {str(row["time"]): index for index, row in enumerate(window)}
44
+ atr_values = talib.ATR(np.array([float(r["high"]) for r in window]),
45
+ np.array([float(r["low"]) for r in window]),
46
+ np.array([float(r["close"]) for r in window]), timeperiod=14)
47
+ atr = float(atr_values[-1])
48
+ if not math.isfinite(atr) or atr <= 0:
49
+ raise LineError("auto_drawing_atr_unavailable", "近期波动数据不足,无法可靠自动选点;仍可手动绘图。")
50
+ candidates = []
51
+ def add(points, side):
52
+ if any(index_by_time.get(p["time"]) is None for p in points):
53
+ return
54
+ indexes = [index_by_time[p["time"]] for p in points]
55
+ if len(window) - 1 - indexes[-1] > 30:
56
+ return
57
+ if any(b - a < 3 for a, b in zip(indexes, indexes[1:])):
58
+ return
59
+ candidates.append({"side": side, "anchors": [{"time": int(p["time"]), "price": p["price"]} for p in points],
60
+ "latest_anchor_time": int(points[-1]["time"]),
61
+ "latest_anchor_bars_ago": len(window) - 1 - indexes[-1]})
62
+ if drawing_type == "horizontal":
63
+ for pivot in pivots:
64
+ add([pivot], pivot["side"])
65
+ elif drawing_type == "trend":
66
+ for side in ("high", "low"):
67
+ same = [p for p in pivots if p["side"] == side]
68
+ for first, second in zip(same, same[1:]):
69
+ add([first, second], side)
70
+ elif drawing_type == "abc":
71
+ # Three labelled endpoints only describe two legs. Require the prior
72
+ # origin as well so A, B and C end three completed, alternating legs.
73
+ for start in range(len(pivots) - 3):
74
+ origin, a, b, c = pivots[start:start + 4]
75
+ points = (origin, a, b, c)
76
+ if any(left["side"] == right["side"] for left, right in zip(points, points[1:])):
77
+ continue
78
+ indexes = [index_by_time.get(p["time"]) for p in points]
79
+ if any(index is None for index in indexes) or any(y - x < 3 for x, y in zip(indexes, indexes[1:])):
80
+ continue
81
+ if indexes[-1] - indexes[0] > 120:
82
+ continue
83
+ known_at = indexes[-1] + 2
84
+ if known_at >= len(atr_values):
85
+ continue
86
+ reference_atr = float(atr_values[known_at])
87
+ if not math.isfinite(reference_atr) or reference_atr <= 0:
88
+ continue
89
+ first_leg = abs(a["price"] - origin["price"])
90
+ retrace = abs(b["price"] - a["price"])
91
+ final_leg = abs(c["price"] - b["price"])
92
+ if first_leg < 2 * reference_atr or not .3 <= retrace / first_leg <= .8:
93
+ continue
94
+ if not .8 <= final_leg / first_leg <= 2.5:
95
+ continue
96
+ if origin["side"] == "high":
97
+ if b["price"] >= origin["price"] or c["price"] >= a["price"] - .25 * reference_atr:
98
+ continue
99
+ side = "abc_down"
100
+ else:
101
+ if b["price"] <= origin["price"] or c["price"] <= a["price"] + .25 * reference_atr:
102
+ continue
103
+ side = "abc_up"
104
+ before = len(candidates)
105
+ add((a, b, c), side)
106
+ if len(candidates) > before:
107
+ candidates[-1]["origin"] = {"time": int(origin["time"]), "price": origin["price"]}
108
+ else:
109
+ width = 2
110
+ for start in range(len(pivots) - width + 1):
111
+ points = pivots[start:start + width]
112
+ if any(a["side"] == b["side"] for a, b in zip(points, points[1:])):
113
+ continue
114
+ if any(abs(a["price"] - b["price"]) < atr for a, b in zip(points, points[1:])):
115
+ continue
116
+ add(points, "swing")
117
+ candidates.sort(key=lambda item: (item["latest_anchor_time"],
118
+ abs(item["anchors"][-1]["price"] - item["anchors"][0]["price"])), reverse=True)
119
+ candidates = candidates[:max_candidates]
120
+ return {"rule_version": RULE_VERSION, "drawing_type": drawing_type, "as_of": quality["as_of"],
121
+ "data_quality": quality, "lookback_bars": lookback_bars, "candidate_count": len(candidates),
122
+ "candidates": candidates, "limitations": ["confirmed_pivots_only", "abc_price_geometry_not_elliott_validation"]
123
+ if drawing_type == "abc" else ["confirmed_pivots_only"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-ft/dsh-fft-paper-trading",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "A-share and commodity futures paper trading for DeepSeek Harness: local ledger, batch orders, review, and FTShare quotes.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -51,7 +51,7 @@
51
51
  "dependencies": {
52
52
  "@dsh-ft/dsh-fft-settings": "^0.7.0",
53
53
  "@dsh-ft/dsh-fft-ftshare": "^0.4.2",
54
- "@ftshare-lab/dsh-kline": ">=0.6.7"
54
+ "@ftshare-lab/dsh-kline": ">=0.6.11"
55
55
  },
56
56
  "bundledDependencies": [
57
57
  "@ftshare-lab/dsh-kline"
@@ -3257,6 +3257,14 @@ window.__ModuleLoader__.load({
3257
3257
  'paperTrading.kline': { kind: 'single', scope: 'root' },
3258
3258
  },
3259
3259
  }, Dashboard))
3260
+ // The declared slot stays empty until dsh_kline fills it through its
3261
+ // optional host contract; without that plugin (or on an older chart) the
3262
+ // rail keeps its built-in simplified chart instead.
3263
+ ctx.inject(['klinePanels'], scope => {
3264
+ const panels = scope.get('klinePanels')
3265
+ if (panels === undefined) return () => {}
3266
+ return panels.mount('paperTrading.kline')
3267
+ })
3260
3268
  }
3261
3269
 
3262
3270
  const inject = ['slots']
@@ -1,15 +0,0 @@
1
- import type { ClientContext } from './host-services';
2
- /**
3
- * Embeddable K-line workspace for the paper-trading panel.
4
- *
5
- * The host declares the `paperTrading.kline` slot and passes the selected
6
- * symbol plus an identity callback. dsh_kline owns the chart, its data source
7
- * and the in-chart search; selecting an instrument there updates the paper
8
- * ticket through `onIdentity`.
9
- */
10
- export declare function PaperKlinePanel({ symbol, onIdentity }: {
11
- symbol?: string;
12
- onIdentity?: (symbol?: string, name?: string) => void;
13
- }): import("react").JSX.Element;
14
- /** Fill the paper-trading chart slot, only when the host declares it. */
15
- export declare function registerPaperTradingHost(ctx: ClientContext): void;
@@ -1,33 +0,0 @@
1
- import type { ClientContext } from './host-services';
2
- /** Panel type registered into a host that provides the free-canvas `canvas` service. */
3
- export declare const KLINE_CANVAS_TYPE = "ft.kline.chart";
4
- /** The transparent per-instance data the canvas hands to a panel body. */
5
- interface CanvasPanelInstance {
6
- id: string;
7
- typeId: string;
8
- title: string;
9
- }
10
- /** Only the public owner props this panel consumes. */
11
- export interface CanvasPanelOwner {
12
- instance?: CanvasPanelInstance;
13
- publish(channel: string, value: unknown): void;
14
- resolve(channel: string): unknown;
15
- read(channel: string): unknown;
16
- /** Host day/night, when the canvas is new enough to expose it. */
17
- colorScheme?(): 'light' | 'dark';
18
- }
19
- /**
20
- * One chart panel on the free canvas.
21
- *
22
- * The canvas hands over its public owner props only, so this component never
23
- * imports the canvas implementation: the selected instrument arrives on the
24
- * `instrument` channel and the chart's own selection is published back on the
25
- * same channel. The chart body is the very component the sidebar tab renders,
26
- * which is what keeps the two visually identical.
27
- */
28
- export declare function KlineCanvasPanel({ owner }: {
29
- owner?: CanvasPanelOwner;
30
- }): import("react").JSX.Element | null;
31
- /** Register the chart panel type and its body, only when the host has a canvas. */
32
- export declare function registerCanvasHost(ctx: ClientContext): void;
33
- export {};
@@ -1,55 +0,0 @@
1
- import type { Sessions } from './conversation';
2
- /**
3
- * The client context `apply` receives — only the members this plugin uses.
4
- *
5
- * Host services are not part of the required surface: each host adapter enters
6
- * them through an optional `ctx.inject([...])` child, so a host without canvas
7
- * or slots loads the plugin exactly as before.
8
- */
9
- export interface ClientContext {
10
- effect(callback: () => () => void, label?: string): void;
11
- inject(deps: string[], callback: (ctx: ClientContext & HostServices) => void): unknown;
12
- get(name: string): unknown;
13
- sessions: Sessions;
14
- }
15
- /** Host services a chart panel can be mounted into. */
16
- export interface HostServices {
17
- /** The host slot registry; canvas and paper-trading both render panels through it. */
18
- slots?: SlotsService;
19
- /** The free-canvas service, present only when the canvas plugin is loaded. */
20
- canvas?: CanvasService;
21
- }
22
- /** The slice of the host `slots` service this plugin registers into. */
23
- export interface SlotsService {
24
- inject(name: string, factory: () => unknown): unknown;
25
- register(options: {
26
- name: string;
27
- key?: string;
28
- id?: string;
29
- order?: number;
30
- label?: string;
31
- }, component: unknown): () => void;
32
- }
33
- /** The slice of the host free-canvas service this plugin registers into. */
34
- export interface CanvasService {
35
- registerType(descriptor: CanvasPanelType): () => void;
36
- }
37
- /** The panel type descriptor a canvas accepts. */
38
- export interface CanvasPanelType {
39
- typeId: string;
40
- title?: string;
41
- icon?: string;
42
- category?: string;
43
- description?: string;
44
- defaultSize?: {
45
- w: number;
46
- h: number;
47
- };
48
- singleton?: boolean;
49
- order?: number;
50
- channels?: {
51
- publishes?: string[];
52
- consumes?: string[];
53
- provides?: string[];
54
- };
55
- }