@dsh-ft/dsh-fft-paper-trading 0.6.0 → 0.6.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.
Files changed (110) hide show
  1. package/README.md +4 -4
  2. package/README.zh.md +4 -4
  3. package/lib/agent/format.d.ts.map +1 -1
  4. package/lib/agent/format.js +4 -0
  5. package/lib/agent/format.js.map +1 -1
  6. package/lib/agent/tools.d.ts.map +1 -1
  7. package/lib/agent/tools.js +5 -3
  8. package/lib/agent/tools.js.map +1 -1
  9. package/lib/client.js +76 -13
  10. package/lib/contract.d.ts.map +1 -1
  11. package/lib/contract.js +3 -1
  12. package/lib/contract.js.map +1 -1
  13. package/lib/core/risk.d.ts.map +1 -1
  14. package/lib/core/risk.js +10 -2
  15. package/lib/core/risk.js.map +1 -1
  16. package/lib/core/views.js +2 -2
  17. package/lib/core/views.js.map +1 -1
  18. package/lib/data/ftshare-trading-calendar.d.ts +47 -12
  19. package/lib/data/ftshare-trading-calendar.d.ts.map +1 -1
  20. package/lib/data/ftshare-trading-calendar.js +156 -44
  21. package/lib/data/ftshare-trading-calendar.js.map +1 -1
  22. package/lib/service/paper-service.d.ts +1 -1
  23. package/lib/service/paper-service.d.ts.map +1 -1
  24. package/lib/service/paper-service.js +24 -12
  25. package/lib/service/paper-service.js.map +1 -1
  26. package/lib/service/rpc.d.ts.map +1 -1
  27. package/lib/service/rpc.js +12 -1
  28. package/lib/service/rpc.js.map +1 -1
  29. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
  30. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
  31. package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
  32. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
  33. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
  34. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
  35. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
  36. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
  69. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
  70. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
  71. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
  72. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
  73. package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
  74. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
  75. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
  76. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
  77. package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
  78. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
  79. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
  80. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
  81. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
  82. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
  83. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
  84. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
  85. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
  97. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
  98. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
  99. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
  100. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
  101. package/package.json +3 -3
  102. package/src/agent/format.ts +3 -0
  103. package/src/agent/tools.ts +5 -3
  104. package/src/client/index.js +75 -12
  105. package/src/contract.ts +3 -1
  106. package/src/core/risk.ts +10 -2
  107. package/src/core/views.ts +2 -2
  108. package/src/data/ftshare-trading-calendar.ts +184 -45
  109. package/src/service/paper-service.ts +22 -19
  110. package/src/service/rpc.ts +12 -1
@@ -0,0 +1,162 @@
1
+ """Deterministic price-series lines on the currently loaded candles only."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import secrets
9
+ import struct
10
+ from typing import Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
13
+
14
+ from core.calc import series_ma
15
+ from core.ta_engine import calculate
16
+ from tools.lines import LineError, validate_line_fields
17
+
18
+ SERIES_COMMAND = "DRAW_AGENT_SERIES_LINE"
19
+ MAX_SERIES_LINES = 8
20
+ MAX_SERIES_BARS = 4000
21
+
22
+
23
+ def candle_sequence_hash(rows):
24
+ """Stable browser-compatible identity for candle-index-aligned drawings."""
25
+ value = 0xcbf29ce484222325
26
+ for row in rows:
27
+ for key in ("time", "open", "high", "low", "close", "volume"):
28
+ for byte in struct.pack(">d", float(row[key])):
29
+ value = ((value ^ byte) * 0x100000001b3) & 0xffffffffffffffff
30
+ return f"{value:016x}"
31
+
32
+
33
+ class PriceSource(BaseModel):
34
+ model_config = ConfigDict(extra="forbid")
35
+ kind: Literal["open", "high", "low", "close", "sma", "ema"]
36
+ period: int | None = Field(default=None, strict=True, ge=2, le=200)
37
+
38
+ @model_validator(mode="after")
39
+ def valid_period(self):
40
+ if (self.kind in {"sma", "ema"}) != (self.period is not None):
41
+ raise ValueError("period is required only for sma or ema")
42
+ return self
43
+
44
+
45
+ class PriceOperand(BaseModel):
46
+ model_config = ConfigDict(extra="forbid")
47
+ source: PriceSource | None = None
48
+ constant: float | None = Field(default=None, strict=True, gt=0, allow_inf_nan=False)
49
+
50
+ @model_validator(mode="after")
51
+ def one_value(self):
52
+ if (self.source is None) == (self.constant is None):
53
+ raise ValueError("exactly one of source or constant is required")
54
+ return self
55
+
56
+
57
+ class PriceCondition(BaseModel):
58
+ model_config = ConfigDict(extra="forbid")
59
+ left: PriceSource
60
+ op: Literal["gt", "gte", "lt", "lte"]
61
+ right: PriceOperand
62
+
63
+
64
+ def _source_values(rows, source: PriceSource):
65
+ if source.kind not in {"sma", "ema"}:
66
+ return [row[source.kind] for row in rows]
67
+ if source.kind == "sma":
68
+ ma = series_ma(rows, [source.period])[f"ma{source.period}"]
69
+ return [ma.get(row["time"]) for row in rows]
70
+ return calculate("EMA", rows, parameters={"timeperiod": source.period})[1]["real"]
71
+
72
+
73
+ def calculate_price_series(rows, source: PriceSource, condition: PriceCondition | None = None):
74
+ if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_SERIES_BARS:
75
+ raise LineError("invalid_price_series_history", "仅支持当前图1至4000根已加载K线,不补取行情。")
76
+ values = _source_values(rows, source)
77
+ left = _source_values(rows, condition.left) if condition else None
78
+ right = (_source_values(rows, condition.right.source) if condition and condition.right.source else
79
+ [condition.right.constant] * len(rows) if condition else None)
80
+ operations = {"gt": lambda a, b: a > b, "gte": lambda a, b: a >= b,
81
+ "lt": lambda a, b: a < b, "lte": lambda a, b: a <= b}
82
+ output = []
83
+ for index, value in enumerate(values):
84
+ allowed = (condition is None or left[index] is not None and right[index] is not None
85
+ and operations[condition.op](left[index], right[index]))
86
+ output.append(float(value) if value is not None and allowed else None)
87
+ matches = sum(value is not None for value in output)
88
+ segments = sum(value is not None and (index == 0 or output[index - 1] is None)
89
+ for index, value in enumerate(output))
90
+ return {"values": output, "summary": {"loaded_bars": len(rows), "matched_bars": matches,
91
+ "segment_count": segments, "empty": matches == 0,
92
+ "warmup_or_condition_gaps": len(rows) - matches, "drawing_created": False}}
93
+
94
+
95
+ def validate_series_values(values, count):
96
+ if (not isinstance(values, list) or len(values) != count or not 1 <= count <= MAX_SERIES_BARS
97
+ or any(value is not None and (type(value) not in (int, float) or not math.isfinite(value) or value <= 0)
98
+ for value in values)):
99
+ raise LineError("invalid_price_series_values", "序列长度、价格或当前K线对齐关系无效。")
100
+ if not any(value is not None for value in values):
101
+ raise LineError("empty_price_series", "条件没有命中可绘制K线,未创建空图形。")
102
+ return list(values)
103
+
104
+
105
+ def edit_price_series(payload, action, *, series_id=None, source=None, condition=None, values=None,
106
+ name=None, color=None, request_id=None):
107
+ result = deepcopy(payload)
108
+ commands = result.get("chartCommands", [])
109
+ rows = next((c["rows"] for c in commands if c.get("type") == "SET_CANDLES"), [])
110
+ matches = [c for c in commands if c.get("type") == SERIES_COMMAND and c.get("id") == series_id]
111
+ if len(matches) > 1:
112
+ raise LineError("ambiguous_drawing_id", "同一序列对象 ID 不唯一,不能安全修改。")
113
+ previous = matches[0] if matches else None
114
+ if action in {"update", "delete"} and previous is None:
115
+ raise LineError("series_line_not_found", "当前快照不存在该 AI 序列线,请先读回对象 ID。")
116
+ if action == "delete":
117
+ if any(item is not None for item in (source, condition, values, name, color)):
118
+ raise LineError("invalid_edit_fields", "删除序列线只需对象 ID。")
119
+ commands.remove(previous)
120
+ return result, deepcopy(previous)
121
+ if action not in {"create", "update"}:
122
+ raise LineError("invalid_action", "不支持的序列线操作。")
123
+ _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
124
+ if action == "create" and (source is None or values is None):
125
+ raise LineError("series_result_required", "创建序列线必须使用函数结果引用。")
126
+ if (source is None) != (values is None):
127
+ raise LineError("series_result_required", "修改计算条件时须重新运行函数并传完整结果引用。")
128
+ if action == "update" and source is None and name is None and color is None:
129
+ raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
130
+ if values is not None:
131
+ clean = validate_series_values(values, len(rows))
132
+ normalized_source = PriceSource.model_validate(source).model_dump(exclude_none=True)
133
+ normalized_condition = (PriceCondition.model_validate(condition).model_dump(exclude_none=True)
134
+ if condition is not None else None)
135
+ else:
136
+ clean = validate_series_values(previous["values"], len(rows))
137
+ normalized_source, normalized_condition = previous["source"], previous.get("condition")
138
+ obj = {"type": SERIES_COMMAND, "id": previous["id"] if previous else "series_" + secrets.token_hex(12),
139
+ "interval": payload.get("interval"), "bar_count": len(rows),
140
+ "row_hash": candle_sequence_hash(rows),
141
+ "source": normalized_source, "condition": normalized_condition, "values": clean,
142
+ "label": name if name is not None else previous.get("label", "") if previous else "",
143
+ "color": color if color is not None else previous.get("color", "info") if previous else "info"}
144
+ obj["series_hash"] = hashlib.sha256(json.dumps({"source": normalized_source, "condition": normalized_condition,
145
+ "values": clean}, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
146
+ if previous and previous.get("create_request_id"):
147
+ obj["create_request_id"] = previous["create_request_id"]
148
+ if action == "create":
149
+ if request_id:
150
+ obj["create_request_id"] = request_id
151
+ obj["id"] = "series_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
152
+ retry = next((c for c in commands if c.get("type") == SERIES_COMMAND and c.get("create_request_id") == request_id), None)
153
+ if retry:
154
+ if any(retry.get(key) != obj[key] for key in ("bar_count", "source", "condition", "values", "label", "color", "interval")):
155
+ raise LineError("request_conflict", "同一 request_id 的序列线参数不同。")
156
+ return result, deepcopy(retry)
157
+ if sum(c.get("type") == SERIES_COMMAND for c in commands) >= MAX_SERIES_LINES:
158
+ raise LineError("too_many_series_lines", "当前图表最多保存8条 AI 序列线。")
159
+ commands.append(obj)
160
+ else:
161
+ commands[commands.index(previous)] = obj
162
+ return result, deepcopy(obj)
@@ -0,0 +1,114 @@
1
+ """Deterministic, bounded per-candle sticks on the current price pane."""
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import secrets
9
+
10
+ from tools.lines import LineError, validate_line_fields
11
+ from tools.price_series import (PriceCondition, PriceSource, MAX_SERIES_BARS,
12
+ calculate_price_series, candle_sequence_hash)
13
+
14
+ STICKS_COMMAND = "DRAW_AGENT_PRICE_STICKS"
15
+ MAX_PRICE_STICKS = 4
16
+
17
+
18
+ def calculate_price_sticks(rows, first_source: PriceSource, second_source: PriceSource,
19
+ condition: PriceCondition | None = None):
20
+ first = calculate_price_series(rows, first_source, condition)["values"]
21
+ second = calculate_price_series(rows, second_source, condition)["values"]
22
+ start, end = [], []
23
+ equal_endpoints = 0
24
+ for one, two in zip(first, second):
25
+ if one is None or two is None or one == two:
26
+ start.append(None)
27
+ end.append(None)
28
+ if one is not None and two is not None: equal_endpoints += 1
29
+ else:
30
+ start.append(one)
31
+ end.append(two)
32
+ matches = sum(value is not None for value in start)
33
+ return {"start_values": start, "end_values": end,
34
+ "summary": {"loaded_bars": len(rows), "matched_bars": matches,
35
+ "empty": matches == 0, "warmup_or_condition_gaps": len(rows) - matches,
36
+ "equal_endpoints_skipped": equal_endpoints, "drawing_created": False}}
37
+
38
+
39
+ def validate_stick_values(start_values, end_values, count):
40
+ if (type(count) is not int or not 1 <= count <= MAX_SERIES_BARS
41
+ or not isinstance(start_values, list) or not isinstance(end_values, list)
42
+ or len(start_values) != count or len(end_values) != count):
43
+ raise LineError("invalid_price_stick_values", "柱线序列长度与当前K线不一致。")
44
+ for start, end in zip(start_values, end_values):
45
+ if start is None and end is None: continue
46
+ if (type(start) not in (int, float) or type(end) not in (int, float)
47
+ or not math.isfinite(start) or not math.isfinite(end)
48
+ or start <= 0 or end <= 0 or start == end):
49
+ raise LineError("invalid_price_stick_values", "柱线端点无效、等价或空值未成对出现。")
50
+ if not any(value is not None for value in start_values):
51
+ raise LineError("empty_price_sticks", "条件没有命中可绘制柱线,未创建空对象。")
52
+ return list(start_values), list(end_values)
53
+
54
+
55
+ def edit_price_sticks(payload, action, *, sticks_id=None, start_source=None, end_source=None,
56
+ condition=None, start_values=None, end_values=None, name=None, color=None,
57
+ request_id=None):
58
+ result = deepcopy(payload)
59
+ commands = result.get("chartCommands", [])
60
+ rows = next((c.get("rows", []) for c in commands if c.get("type") == "SET_CANDLES"), [])
61
+ matches = [c for c in commands if c.get("type") == STICKS_COMMAND and c.get("id") == sticks_id]
62
+ if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一柱线对象 ID 不唯一。")
63
+ previous = matches[0] if matches else None
64
+ if action in {"update", "delete"} and previous is None:
65
+ raise LineError("price_sticks_not_found", "当前图不存在该 AI 柱线对象。")
66
+ if action == "delete":
67
+ if any(value is not None for value in (start_source, end_source, condition, start_values,
68
+ end_values, name, color)):
69
+ raise LineError("invalid_edit_fields", "删除柱线对象只需对象 ID。")
70
+ commands.remove(previous)
71
+ return result, deepcopy(previous)
72
+ if action not in {"create", "update"}: raise LineError("invalid_action", "不支持的柱线对象操作。")
73
+ _, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
74
+ supplied = [start_source, end_source, start_values, end_values]
75
+ if action == "create" and any(value is None for value in supplied):
76
+ raise LineError("sticks_result_required", "创建柱线对象必须使用完整函数结果引用。")
77
+ if any(value is None for value in supplied) and any(value is not None for value in supplied):
78
+ raise LineError("sticks_result_required", "修改端点或条件时须重新运行函数并使用完整结果引用。")
79
+ if action == "update" and all(value is None for value in supplied) and name is None and color is None:
80
+ raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
81
+ if all(value is not None for value in supplied):
82
+ start_values, end_values = validate_stick_values(start_values, end_values, len(rows))
83
+ start_source = PriceSource.model_validate(start_source).model_dump(exclude_none=True)
84
+ end_source = PriceSource.model_validate(end_source).model_dump(exclude_none=True)
85
+ condition = PriceCondition.model_validate(condition).model_dump(exclude_none=True) if condition is not None else None
86
+ else:
87
+ start_values, end_values = validate_stick_values(previous["start_values"], previous["end_values"], len(rows))
88
+ start_source, end_source, condition = previous["start_source"], previous["end_source"], previous.get("condition")
89
+ obj = {"type": STICKS_COMMAND, "id": previous["id"] if previous else "sticks_" + secrets.token_hex(12),
90
+ "interval": payload.get("interval"), "bar_count": len(rows), "row_hash": candle_sequence_hash(rows),
91
+ "start_source": start_source, "end_source": end_source, "condition": condition,
92
+ "start_values": start_values, "end_values": end_values,
93
+ "label": name if name is not None else previous.get("label", "") if previous else "",
94
+ "color": color if color is not None else previous.get("color", "info") if previous else "info"}
95
+ obj["sticks_hash"] = hashlib.sha256(json.dumps({"start_source": start_source, "end_source": end_source,
96
+ "condition": condition, "start_values": start_values, "end_values": end_values},
97
+ ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
98
+ if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
99
+ if action == "create":
100
+ if request_id:
101
+ obj["create_request_id"] = request_id
102
+ obj["id"] = "sticks_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
103
+ retry = next((c for c in commands if c.get("type") == STICKS_COMMAND and c.get("create_request_id") == request_id), None)
104
+ if retry:
105
+ if any(retry.get(key) != obj[key] for key in ("interval", "bar_count", "start_source", "end_source",
106
+ "condition", "start_values", "end_values", "label", "color")):
107
+ raise LineError("request_conflict", "同一 request_id 的柱线参数不同。")
108
+ return result, deepcopy(retry)
109
+ if sum(c.get("type") == STICKS_COMMAND for c in commands) >= MAX_PRICE_STICKS:
110
+ raise LineError("too_many_price_sticks", "当前图最多保存4组 AI 柱线。")
111
+ commands.append(obj)
112
+ else:
113
+ commands[commands.index(previous)] = obj
114
+ return result, deepcopy(obj)
@@ -0,0 +1,170 @@
1
+ """Read-only candidates for a *current* horizontal trading range.
2
+
3
+ This is a bounded geometry heuristic, not a breakout signal or a professional
4
+ pattern verdict. It is deliberately separate from the guarded rectangle editor.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from statistics import median
10
+
11
+ from core.rows import RowsValidationError, validate_rows
12
+ from tools.lines import LineError
13
+
14
+ RULE_VERSION = "current_range_wick_envelope_v1"
15
+ DEFAULT_WINDOW_SIZES = (20, 30, 40, 60)
16
+ MIN_WIDTH_FRACTION = 0.005
17
+ MAX_WIDTH_FRACTION = 0.12
18
+ TOUCH_DISTANCE_TO_WIDTH = 0.10
19
+ MIN_TOUCH_SEPARATION_BARS = 3
20
+ MAX_CLOSE_DRIFT_TO_WIDTH = 0.50
21
+ MAX_FITTED_DRIFT_TO_WIDTH = 0.50
22
+ RECENT_BARS = 10
23
+ MAX_RECENT_DRIFT_TO_WIDTH = 0.50
24
+
25
+
26
+ def _separated_touch_indexes(indexes):
27
+ kept = []
28
+ for index in indexes:
29
+ if not kept or index - kept[-1] >= MIN_TOUCH_SEPARATION_BARS:
30
+ kept.append(index)
31
+ return kept
32
+
33
+
34
+ def _fitted_drift_to_width(closes, width):
35
+ count = len(closes)
36
+ x_mean = (count - 1) / 2
37
+ y_mean = math.fsum(closes) / count
38
+ denominator = math.fsum((index - x_mean) ** 2 for index in range(count))
39
+ slope = math.fsum((index - x_mean) * (price - y_mean)
40
+ for index, price in enumerate(closes)) / denominator
41
+ return abs(slope * (count - 1)) / width
42
+
43
+
44
+ def range_candidates(rows, *, window_sizes=DEFAULT_WINDOW_SIZES, limit=3):
45
+ """Return up to ``limit`` boxed-range proposals ending at the latest bar.
46
+
47
+ Candidate edges are the actual highest high and lowest low of each fixed
48
+ window. Both edges need at least two separated wick touches; a narrow band
49
+ alone is insufficient. Close drift and fitted close slope must each use no
50
+ more than half the band width, both across the full window and the recent
51
+ ten-bar tail. No projection or chart mutation occurs.
52
+ """
53
+ if (not isinstance(window_sizes, (tuple, list)) or not window_sizes
54
+ or len(window_sizes) > 8 or any(type(size) is not int or not 16 <= size <= 120 for size in window_sizes)
55
+ or len(set(window_sizes)) != len(window_sizes)):
56
+ raise LineError("invalid_range_candidate_windows", "window_sizes 必须是1至8个互异的16至120整数。")
57
+ if type(limit) is not int or not 1 <= limit <= 5:
58
+ raise LineError("invalid_range_candidate_limit", "limit 必须是1至5的整数。")
59
+ windows = tuple(sorted(window_sizes))
60
+ try:
61
+ candles = validate_rows(rows, min_len=min(windows))
62
+ except RowsValidationError:
63
+ raise LineError("insufficient_range_candidate_history", "已加载K线不足以计算平台区间候选;未补取行情。") from None
64
+ # A corrupt candle must not become an envelope boundary or a fake touch.
65
+ recent = candles[-max(windows):]
66
+ if any(row["low"] <= 0 or row["high"] < max(row["open"], row["close"], row["low"])
67
+ or row["low"] > min(row["open"], row["close"]) for row in recent):
68
+ raise LineError("invalid_range_candidate_data", "平台候选需要高低价为正且 OHLC 一致的K线;未忽略异常柱。")
69
+
70
+ candidates = []
71
+ evaluated_windows = []
72
+ for size in windows:
73
+ if size > len(candles):
74
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "insufficient_history"})
75
+ continue
76
+ segment = candles[-size:]
77
+ high_index = max(range(size), key=lambda index: segment[index]["high"])
78
+ low_index = min(range(size), key=lambda index: segment[index]["low"])
79
+ upper = segment[high_index]["high"]
80
+ lower = segment[low_index]["low"]
81
+ width = upper - lower
82
+ center = median(row["close"] for row in segment)
83
+ if not math.isfinite(width) or width <= 0 or center <= 0:
84
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "invalid_width"})
85
+ continue
86
+ width_fraction = width / center
87
+ if not MIN_WIDTH_FRACTION <= width_fraction <= MAX_WIDTH_FRACTION:
88
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "width_fraction_outside"})
89
+ continue
90
+ upper_touches = _separated_touch_indexes([
91
+ index for index, row in enumerate(segment)
92
+ if upper - row["high"] <= width * TOUCH_DISTANCE_TO_WIDTH
93
+ ])
94
+ lower_touches = _separated_touch_indexes([
95
+ index for index, row in enumerate(segment)
96
+ if row["low"] - lower <= width * TOUCH_DISTANCE_TO_WIDTH
97
+ ])
98
+ if len(upper_touches) < 2 or len(lower_touches) < 2:
99
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "insufficient_edge_touches"})
100
+ continue
101
+ closes = [row["close"] for row in segment]
102
+ close_drift = abs(closes[-1] - closes[0]) / width
103
+ fitted_drift = _fitted_drift_to_width(closes, width)
104
+ recent_closes = closes[-min(RECENT_BARS, size // 2):]
105
+ recent_close_drift = abs(recent_closes[-1] - recent_closes[0]) / width
106
+ recent_fitted_drift = _fitted_drift_to_width(recent_closes, width)
107
+ if not all(math.isfinite(value) for value in (close_drift, fitted_drift,
108
+ recent_close_drift, recent_fitted_drift)):
109
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "nonfinite_drift"})
110
+ continue
111
+ if close_drift > MAX_CLOSE_DRIFT_TO_WIDTH or fitted_drift > MAX_FITTED_DRIFT_TO_WIDTH:
112
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "full_window_drift"})
113
+ continue
114
+ if (recent_close_drift > MAX_RECENT_DRIFT_TO_WIDTH
115
+ or recent_fitted_drift > MAX_RECENT_DRIFT_TO_WIDTH):
116
+ evaluated_windows.append({"window_bars": size, "accepted": False, "reason": "recent_directional_move"})
117
+ continue
118
+ evaluated_windows.append({"window_bars": size, "accepted": True, "reason": None})
119
+ candidates.append({
120
+ "start_time": segment[0]["time"], "end_time": segment[-1]["time"],
121
+ "lower_price": lower, "upper_price": upper, "bar_count": size,
122
+ "upper_source_time": segment[high_index]["time"],
123
+ "lower_source_time": segment[low_index]["time"],
124
+ "width_fraction_of_median_close": width_fraction,
125
+ "upper_touch_count": len(upper_touches), "lower_touch_count": len(lower_touches),
126
+ "upper_touch_times": [segment[index]["time"] for index in upper_touches],
127
+ "lower_touch_times": [segment[index]["time"] for index in lower_touches],
128
+ "close_drift_to_width": close_drift, "fitted_close_drift_to_width": fitted_drift,
129
+ "recent_close_drift_to_width": recent_close_drift,
130
+ "recent_fitted_close_drift_to_width": recent_fitted_drift,
131
+ "boundary_rule": "full_window_max_high_min_low",
132
+ "status": "geometry_candidate_requires_review",
133
+ })
134
+ # Prefer more repeated boundary contact, flatter closes, then longer spans.
135
+ candidates.sort(key=lambda item: (-(item["upper_touch_count"] + item["lower_touch_count"]),
136
+ item["fitted_close_drift_to_width"], -item["bar_count"]))
137
+ # Overlapping windows often describe the exact same price box. Present one
138
+ # representative instead of spending the result limit on duplicate geometry.
139
+ unique_candidates = []
140
+ seen_boundaries = set()
141
+ for candidate in candidates:
142
+ boundaries = (candidate["lower_price"], candidate["upper_price"], candidate["end_time"])
143
+ if boundaries in seen_boundaries:
144
+ continue
145
+ seen_boundaries.add(boundaries)
146
+ unique_candidates.append(candidate)
147
+ return {
148
+ "rule_version": RULE_VERSION,
149
+ "window_sizes": list(windows),
150
+ "end_policy": "latest_loaded_bar_only",
151
+ "candidate_count": len(unique_candidates), "returned": min(limit, len(unique_candidates)),
152
+ "truncated": len(unique_candidates) > limit,
153
+ "duplicates_suppressed": len(candidates) - len(unique_candidates),
154
+ "no_candidate_reason": "no_window_passed_rules" if not unique_candidates else None,
155
+ "evaluated_windows": evaluated_windows,
156
+ "candidates": unique_candidates[:limit],
157
+ "thresholds": {
158
+ "width_fraction_of_median_close": [MIN_WIDTH_FRACTION, MAX_WIDTH_FRACTION],
159
+ "touch_distance_to_width": TOUCH_DISTANCE_TO_WIDTH,
160
+ "minimum_separated_touches_per_edge": 2,
161
+ "minimum_touch_separation_bars": MIN_TOUCH_SEPARATION_BARS,
162
+ "maximum_close_drift_to_width": MAX_CLOSE_DRIFT_TO_WIDTH,
163
+ "maximum_fitted_close_drift_to_width": MAX_FITTED_DRIFT_TO_WIDTH,
164
+ "recent_bars": RECENT_BARS,
165
+ "maximum_recent_drift_to_width": MAX_RECENT_DRIFT_TO_WIDTH,
166
+ },
167
+ "limitations": ["current_window_only", "geometry_only_requires_human_review",
168
+ "no_breakout_signal", "no_drawing_created"],
169
+ "drawing_created": False,
170
+ }
@@ -0,0 +1,87 @@
1
+ """Deterministic linear-regression channel statistics over an explicit bar range."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+
6
+ from core.rows import RowsValidationError, validate_rows
7
+ from tools.lines import LineError
8
+
9
+ MIN_REGRESSION_BARS = 10
10
+ MAX_REGRESSION_BARS = 4000
11
+
12
+
13
+ def regression_channel(rows, *, start_time, end_time, multiplier=2.0):
14
+ """Fit close ~ candle-index over an inclusive explicit range.
15
+
16
+ The channel boundaries are regression line +/- multiplier * population RMS
17
+ residual. It returns statistics only and never creates a chart drawing.
18
+ """
19
+ if type(start_time) is not int or type(end_time) is not int or start_time >= end_time:
20
+ raise LineError("invalid_regression_range", "回归区间起点必须早于终点且对应明确的K线。")
21
+ if type(multiplier) not in (int, float) or not math.isfinite(multiplier) or not 0.5 <= multiplier <= 5:
22
+ raise LineError("invalid_regression_multiplier", "multiplier 必须是0.5至5之间的有限数值。")
23
+ try:
24
+ candles = validate_rows(rows, min_len=MIN_REGRESSION_BARS)
25
+ except RowsValidationError:
26
+ raise LineError("insufficient_regression_history", "当前已加载K线不足10根,无法计算回归通道;未补取行情。") from None
27
+
28
+ indexes = {int(row["time"]): index for index, row in enumerate(candles)}
29
+ if start_time not in indexes or end_time not in indexes:
30
+ raise LineError("regression_anchor_not_found", "回归区间两端必须精确对应当前已加载K线;未吸附或补取行情。")
31
+ first, last = indexes[start_time], indexes[end_time]
32
+ if first >= last:
33
+ raise LineError("invalid_regression_range", "回归区间起点必须早于终点;未自动交换。")
34
+ selected = candles[first:last + 1]
35
+ if len(selected) < MIN_REGRESSION_BARS:
36
+ raise LineError("insufficient_regression_range", "指定区间至少需要10根已加载K线。")
37
+ if len(selected) > MAX_REGRESSION_BARS:
38
+ raise LineError("regression_range_too_large", "指定回归区间最多4000根已加载K线。")
39
+
40
+ prices = [float(row["close"]) for row in selected]
41
+ if any(not math.isfinite(price) or price <= 0 for price in prices):
42
+ raise LineError("invalid_regression_data", "回归区间收盘价必须为大于零的有限数值。")
43
+
44
+ count = len(prices)
45
+ x_mean = (count - 1) / 2
46
+ y_mean = math.fsum(prices) / count
47
+ denominator = math.fsum((index - x_mean) ** 2 for index in range(count))
48
+ slope = math.fsum((index - x_mean) * (price - y_mean)
49
+ for index, price in enumerate(prices)) / denominator
50
+ intercept = y_mean - slope * x_mean
51
+ fitted = [intercept + slope * index for index in range(count)]
52
+ residuals = [price - estimate for price, estimate in zip(prices, fitted)]
53
+ residual_variance = math.fsum(value * value for value in residuals) / count
54
+ residual_stddev = math.sqrt(max(0.0, residual_variance))
55
+ total_variance = math.fsum((price - y_mean) ** 2 for price in prices)
56
+ residual_sum_squares = math.fsum(value * value for value in residuals)
57
+ r_squared = 1.0 if total_variance == 0 else 1 - residual_sum_squares / total_variance
58
+ width = multiplier * residual_stddev
59
+ line_start, line_end = fitted[0], fitted[-1]
60
+ result = {
61
+ "start_time": start_time,
62
+ "end_time": end_time,
63
+ "bar_count": count,
64
+ "price_source": "close",
65
+ "x_axis": "loaded_candle_index",
66
+ "fit": "ordinary_least_squares",
67
+ "slope_per_bar": slope,
68
+ "regression_start_price": line_start,
69
+ "regression_end_price": line_end,
70
+ "residual_stddev_population": residual_stddev,
71
+ "multiplier": float(multiplier),
72
+ "channel_width": width,
73
+ "upper_start_price": line_start + width,
74
+ "upper_end_price": line_end + width,
75
+ "lower_start_price": line_start - width,
76
+ "lower_end_price": line_end - width,
77
+ "r_squared": min(1.0, max(0.0, r_squared)),
78
+ "direction": "ascending" if slope > 0 else "descending" if slope < 0 else "horizontal",
79
+ "boundary_rule": "ols_close_plus_minus_multiplier_times_population_rms_residual",
80
+ "automatic_anchor_selection": False,
81
+ }
82
+ if any(not math.isfinite(value) for key, value in result.items()
83
+ if key not in {"start_time", "end_time", "bar_count", "price_source", "x_axis", "fit", "direction", "boundary_rule", "automatic_anchor_selection"}):
84
+ raise LineError("invalid_regression_result", "回归计算产生非有限数值,未保存结果。")
85
+ if result["lower_start_price"] <= 0 or result["lower_end_price"] <= 0:
86
+ raise LineError("invalid_regression_boundary", "回归下轨必须保持正价格;请调整区间或 multiplier。")
87
+ return result