@dsh-ft/dsh-fft-paper-trading 0.6.1 → 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 (105) 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/service/paper-service.d.ts +1 -1
  19. package/lib/service/paper-service.d.ts.map +1 -1
  20. package/lib/service/paper-service.js +24 -12
  21. package/lib/service/paper-service.js.map +1 -1
  22. package/lib/service/rpc.d.ts.map +1 -1
  23. package/lib/service/rpc.js +12 -1
  24. package/lib/service/rpc.js.map +1 -1
  25. package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +98 -0
  26. package/node_modules/@ftshare-lab/dsh-kline/README.en.md +116 -26
  27. package/node_modules/@ftshare-lab/dsh-kline/README.md +125 -25
  28. package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +38 -0
  29. package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +3 -9
  30. package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +63 -269
  31. package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +15 -3
  32. package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +99 -0
  33. package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +15 -0
  34. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +33 -0
  35. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +1 -1
  36. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +12 -3
  37. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +91 -2
  38. package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +64 -13
  39. package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +3356 -787
  40. package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +96 -19
  41. package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +18 -0
  42. package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +19 -2
  43. package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +17 -0
  44. package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +55 -0
  45. package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +47 -0
  46. package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +32 -0
  47. package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +2 -0
  48. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +4 -0
  49. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +1 -1
  50. package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +2 -0
  51. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +3 -2
  52. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +1 -1
  53. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +1 -0
  54. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +14 -0
  55. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +11 -3
  56. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +2 -2
  57. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +1 -1
  58. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-services.d.ts +0 -36
  59. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +2 -1
  60. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +35 -4
  61. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +46 -0
  62. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +45 -0
  63. package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +21 -36
  64. package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +5 -0
  65. package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +11 -0
  66. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +3 -0
  67. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +5 -0
  68. package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +3 -0
  69. package/node_modules/@ftshare-lab/dsh-kline/package.json +27 -5
  70. package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +2 -0
  71. package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +27 -0
  72. package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +180 -49
  73. package/node_modules/@ftshare-lab/dsh-kline/server.py +300 -34
  74. package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +119 -0
  75. package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +176 -0
  76. package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +260 -0
  77. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +1 -1
  78. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +22 -3
  79. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +141 -16
  80. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +466 -0
  81. package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +63 -0
  82. package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +3 -0
  83. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +13 -7
  84. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +117 -0
  85. package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +58 -3
  86. package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +164 -40
  87. package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +83 -0
  88. package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +78 -21
  89. package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +60 -0
  90. package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +125 -0
  91. package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +165 -0
  92. package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +162 -0
  93. package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +114 -0
  94. package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +170 -0
  95. package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +87 -0
  96. package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +228 -0
  97. package/package.json +2 -2
  98. package/src/agent/format.ts +3 -0
  99. package/src/agent/tools.ts +5 -3
  100. package/src/client/index.js +75 -12
  101. package/src/contract.ts +3 -1
  102. package/src/core/risk.ts +10 -2
  103. package/src/core/views.ts +2 -2
  104. package/src/service/paper-service.ts +22 -19
  105. package/src/service/rpc.ts +12 -1
@@ -1,18 +1,12 @@
1
1
  - insert:
2
- # This row lives in the bundle patch so `dsh plugin add github:…` gets
3
- # both the sidebar and its MCP service. `ctx.baseUrl` is the profile's
4
- # cordis.yml URL, making the installed package root independent of the
5
- # caller's workspace directory. Hosts with a different layout may provide
6
- # DSH_KLINE_PACKAGE_ROOT as an absolute package directory.
2
+ # DSH anchors relative plugin names beside THIS patch, including nested
3
+ # bundle installations. The module resolves its launcher from import.meta.url.
7
4
  - id: mcp-dsh-kline
8
- name: '@deepseek-ai/dsh-mcp-client'
5
+ name: './scripts/dsh-mcp-plugin.mjs'
9
6
  config:
10
7
  serverName: dsh-kline
11
8
  transport: stdio
12
9
  command: !!js process.execPath
13
- args:
14
- - scripts/run-dsh-kline.mjs
15
- cwd: !!js String(process.env.DSH_KLINE_PACKAGE_ROOT || '').trim() || ((process.platform === 'win32' && /^\/[A-Za-z]:\//.test(decodeURIComponent(new URL('./node_modules/@ftshare-lab/dsh-kline/', ctx.baseUrl).pathname)) && decodeURIComponent(new URL('./node_modules/@ftshare-lab/dsh-kline/', ctx.baseUrl).pathname).slice(1)) || decodeURIComponent(new URL('./node_modules/@ftshare-lab/dsh-kline/', ctx.baseUrl).pathname))
16
10
  env:
17
11
  DSH_KLINE_HOST_PID: !!js String(process.pid)
18
12
  DSH_KLINE_DEFER_BOOTSTRAP: '1'
@@ -13,6 +13,8 @@ from __future__ import annotations
13
13
  import math
14
14
  from typing import Any, Iterable
15
15
 
16
+ from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION, arrays as _ta_arrays, finite_map as _ta_map, talib
17
+
16
18
 
17
19
  # ---------------------------------------------------------------------------
18
20
  # Defaults (shared by calc_metrics + draw_kline)
@@ -49,82 +51,6 @@ def _round(v: float | None, n: int = 4) -> float | None:
49
51
  return round(float(v), n)
50
52
 
51
53
 
52
- def _sma(values: list[float | None], period: int) -> list[float | None]:
53
- out: list[float | None] = [None] * len(values)
54
- if period <= 0:
55
- return out
56
- window = 0.0
57
- count = 0
58
- for i, v in enumerate(values):
59
- if v is None:
60
- # restart window on missing
61
- window = 0.0
62
- count = 0
63
- continue
64
- window += v
65
- count += 1
66
- if count > period:
67
- prev = values[i - period]
68
- if prev is not None:
69
- window -= prev
70
- count = period
71
- if count >= period:
72
- out[i] = window / period
73
- return out
74
-
75
-
76
- def _ema(values: list[float | None], period: int) -> list[float | None]:
77
- """EMA with SMA-of-first-period seed (NOT used by MACD).
78
-
79
- Kept for non-Tongdaxin paths / future helpers. MACD must use `_ema_tdx`.
80
- """
81
- out: list[float | None] = [None] * len(values)
82
- if period <= 0:
83
- return out
84
- k = 2.0 / (period + 1)
85
- prev: float | None = None
86
- for i, v in enumerate(values):
87
- if v is None:
88
- out[i] = prev
89
- continue
90
- if prev is None:
91
- # seed with SMA of first `period` finite values if possible
92
- seed_vals = [x for x in values[: i + 1] if x is not None]
93
- if len(seed_vals) < period:
94
- continue
95
- prev = sum(seed_vals[-period:]) / period
96
- out[i] = prev
97
- else:
98
- prev = v * k + prev * (1 - k)
99
- out[i] = prev
100
- return out
101
-
102
-
103
- def _ema_tdx(values: list[float | None], period: int) -> list[float | None]:
104
- """Tongdaxin / Eastmoney EMA seed: Y[0] = first finite X, then recurse.
105
-
106
- k = 2 / (period + 1). Emits from the first finite input (no SMA warm-up).
107
- Used only by `series_macd` (DIF EMAs + DEA on DIF). RSI/ATR stay on their
108
- own Wilder-style paths and are intentionally not switched here.
109
- """
110
- out: list[float | None] = [None] * len(values)
111
- if period <= 0:
112
- return out
113
- k = 2.0 / (period + 1)
114
- prev: float | None = None
115
- for i, v in enumerate(values):
116
- if v is None:
117
- out[i] = prev
118
- continue
119
- if prev is None:
120
- prev = float(v) # Y[0] = X[0]
121
- out[i] = prev
122
- else:
123
- prev = float(v) * k + prev * (1.0 - k)
124
- out[i] = prev
125
- return out
126
-
127
-
128
54
  def _calendar_days(t0: int, t1: int) -> int:
129
55
  """Calendar days between two unix-second timestamps (inclusive-ish span)."""
130
56
  if t1 < t0:
@@ -163,31 +89,20 @@ def series_ma(
163
89
  ) -> dict[str, dict[int, float]]:
164
90
  """Return {f"ma{p}": {time_sec: value}} for each period."""
165
91
  periods = list(periods or DEFAULT_MA_PERIODS)
166
- closes = _closes(rows)
167
- times = _times(rows)
168
- out: dict[str, dict[int, float]] = {}
169
- for p in periods:
170
- sma = _sma([float(c) for c in closes], int(p))
171
- m: dict[int, float] = {}
172
- for t, v in zip(times, sma):
173
- if v is not None:
174
- m[int(t)] = round(float(v), 6)
175
- out[f"ma{int(p)}"] = m
176
- return out
92
+ if not rows:
93
+ return {f"ma{int(p)}": {} for p in periods}
94
+ close = _ta_arrays(rows)["close"]
95
+ return {f"ma{int(p)}": _ta_map(rows, talib.SMA(close, timeperiod=int(p))) for p in periods}
177
96
 
178
97
 
179
98
  def series_vol_ma(
180
99
  rows: list[dict[str, Any]],
181
100
  period: int = DEFAULT_VOLUME_MA,
182
101
  ) -> dict[int, float]:
183
- vols = _volumes(rows)
184
- times = _times(rows)
185
- sma = _sma(vols, int(period))
186
- m: dict[int, float] = {}
187
- for t, v in zip(times, sma):
188
- if v is not None:
189
- m[int(t)] = round(float(v), 4)
190
- return m
102
+ if not rows:
103
+ return {}
104
+ volume = _ta_arrays(rows)["volume"]
105
+ return _ta_map(rows, talib.SMA(volume, timeperiod=int(period)), digits=4)
191
106
 
192
107
 
193
108
  def series_macd(
@@ -196,39 +111,12 @@ def series_macd(
196
111
  slow: int = DEFAULT_MACD[1],
197
112
  signal: int = DEFAULT_MACD[2],
198
113
  ) -> dict[str, dict[int, float]]:
199
- """MACD series — full Tongdaxin / Eastmoney path.
200
-
201
- - EMA seed: Y[0]=X[0] recursive (`_ema_tdx`), not SMA-of-first-period
202
- - hist = 2*(DIF-DEA) (column height matches 东财 terminal habit)
203
- - Keys = unix **seconds**
204
- """
205
- closes = [float(c) for c in _closes(rows)]
206
- times = _times(rows)
207
- ema_fast = _ema_tdx(closes, int(fast))
208
- ema_slow = _ema_tdx(closes, int(slow))
209
- dif: list[float | None] = []
210
- for a, b in zip(ema_fast, ema_slow):
211
- if a is None or b is None:
212
- dif.append(None)
213
- else:
214
- dif.append(a - b)
215
- dea = _ema_tdx(dif, int(signal))
216
- hist: list[float | None] = []
217
- for d, e in zip(dif, dea):
218
- if d is None or e is None:
219
- hist.append(None)
220
- else:
221
- # 通达信 / 东财口径:MACD 柱 = 2*(DIF-DEA)。西方标准 MACD 柱是 DIF-DEA(不×2)。
222
- hist.append((d - e) * 2.0)
223
- out = {"dif": {}, "dea": {}, "hist": {}}
224
- for t, d, e, h in zip(times, dif, dea, hist):
225
- if d is not None:
226
- out["dif"][int(t)] = round(float(d), 6)
227
- if e is not None:
228
- out["dea"][int(t)] = round(float(e), 6)
229
- if h is not None:
230
- out["hist"][int(t)] = round(float(h), 6)
231
- return out # type: ignore[return-value]
114
+ """TA-Lib MACD; hist is DIF-DEA without the former x2 convention."""
115
+ if not rows:
116
+ return {"dif": {}, "dea": {}, "hist": {}}
117
+ close = _ta_arrays(rows)["close"]
118
+ dif, dea, hist = talib.MACD(close, fastperiod=int(fast), slowperiod=int(slow), signalperiod=int(signal))
119
+ return {"dif": _ta_map(rows, dif), "dea": _ta_map(rows, dea), "hist": _ta_map(rows, hist)}
232
120
 
233
121
 
234
122
  def series_kdj(
@@ -237,34 +125,13 @@ def series_kdj(
237
125
  m1: int = DEFAULT_KDJ[1],
238
126
  m2: int = DEFAULT_KDJ[2],
239
127
  ) -> dict[str, dict[int, float]]:
240
- highs = _highs(rows)
241
- lows = _lows(rows)
242
- closes = _closes(rows)
243
- times = _times(rows)
244
- k_map: dict[int, float] = {}
245
- d_map: dict[int, float] = {}
246
- j_map: dict[int, float] = {}
247
- k_prev, d_prev = 50.0, 50.0
248
- n = max(1, int(n))
249
- m1 = max(1, int(m1))
250
- m2 = max(1, int(m2))
251
- for i in range(len(rows)):
252
- start = max(0, i - n + 1)
253
- hh = max(highs[start : i + 1])
254
- ll = min(lows[start : i + 1])
255
- if hh == ll:
256
- rsv = 50.0
257
- else:
258
- rsv = (closes[i] - ll) / (hh - ll) * 100.0
259
- k = (m1 - 1) / m1 * k_prev + 1 / m1 * rsv
260
- d = (m2 - 1) / m2 * d_prev + 1 / m2 * k
261
- j = 3 * k - 2 * d
262
- k_prev, d_prev = k, d
263
- t = int(times[i])
264
- k_map[t] = round(k, 4)
265
- d_map[t] = round(d, 4)
266
- j_map[t] = round(j, 4)
267
- return {"k": k_map, "d": d_map, "j": j_map}
128
+ if not rows:
129
+ return {"k": {}, "d": {}, "j": {}}
130
+ values = _ta_arrays(rows)
131
+ k, d, j = talib.KDJ(values["high"], values["low"], values["close"],
132
+ fastk_period=int(n), slowk_period=int(m1), slowk_matype=13,
133
+ slowd_period=int(m2), slowd_matype=13)
134
+ return {"k": _ta_map(rows, k, 4), "d": _ta_map(rows, d, 4), "j": _ta_map(rows, j, 4)}
268
135
 
269
136
 
270
137
  def series_boll(
@@ -272,120 +139,40 @@ def series_boll(
272
139
  period: int = DEFAULT_BOLL_PERIOD,
273
140
  std_mult: float = DEFAULT_BOLL_STD,
274
141
  ) -> dict[str, dict[int, float]]:
275
- closes = _closes(rows)
276
- times = _times(rows)
277
- period = max(1, int(period))
278
- mid_map: dict[int, float] = {}
279
- up_map: dict[int, float] = {}
280
- low_map: dict[int, float] = {}
281
- for i in range(len(rows)):
282
- if i + 1 < period:
283
- continue
284
- window = closes[i + 1 - period : i + 1]
285
- mean = sum(window) / period
286
- var = sum((x - mean) ** 2 for x in window) / period
287
- sd = math.sqrt(var)
288
- t = int(times[i])
289
- mid_map[t] = round(mean, 6)
290
- up_map[t] = round(mean + std_mult * sd, 6)
291
- low_map[t] = round(mean - std_mult * sd, 6)
292
- return {"mid": mid_map, "upper": up_map, "lower": low_map}
142
+ if not rows:
143
+ return {"mid": {}, "upper": {}, "lower": {}}
144
+ close = _ta_arrays(rows)["close"]
145
+ upper, mid, lower = talib.BBANDS(close, timeperiod=int(period), nbdevup=float(std_mult),
146
+ nbdevdn=float(std_mult), matype=0)
147
+ return {"mid": _ta_map(rows, mid), "upper": _ta_map(rows, upper), "lower": _ta_map(rows, lower)}
293
148
 
294
149
 
295
150
  def series_rsi(
296
151
  rows: list[dict[str, Any]],
297
152
  period: int = DEFAULT_RSI_PERIOD,
298
153
  ) -> dict[int, float]:
299
- closes = _closes(rows)
300
- times = _times(rows)
301
- period = max(1, int(period))
302
- out: dict[int, float] = {}
303
- if len(closes) < period + 1:
304
- return out
305
- gains = 0.0
306
- losses = 0.0
307
- for i in range(1, period + 1):
308
- d = closes[i] - closes[i - 1]
309
- if d >= 0:
310
- gains += d
311
- else:
312
- losses -= d
313
- avg_gain = gains / period
314
- avg_loss = losses / period
315
- if avg_loss == 0:
316
- rsi = 50.0 if avg_gain == 0 else 100.0
317
- else:
318
- rs = avg_gain / avg_loss
319
- rsi = 100.0 - 100.0 / (1 + rs)
320
- out[int(times[period])] = round(rsi, 4)
321
- for i in range(period + 1, len(closes)):
322
- d = closes[i] - closes[i - 1]
323
- gain = max(d, 0.0)
324
- loss = max(-d, 0.0)
325
- avg_gain = (avg_gain * (period - 1) + gain) / period
326
- avg_loss = (avg_loss * (period - 1) + loss) / period
327
- if avg_loss == 0:
328
- rsi = 50.0 if avg_gain == 0 else 100.0
329
- else:
330
- rs = avg_gain / avg_loss
331
- rsi = 100.0 - 100.0 / (1 + rs)
332
- out[int(times[i])] = round(rsi, 4)
333
- return out
154
+ if not rows:
155
+ return {}
156
+ close = _ta_arrays(rows)["close"]
157
+ return _ta_map(rows, talib.RSI(close, timeperiod=int(period)), digits=4)
334
158
 
335
159
 
336
160
  def series_vwap(rows: list[dict[str, Any]]) -> dict[int, float]:
337
- """Return the session-window VWAP series keyed by unix seconds.
338
-
339
- The chart deliberately anchors VWAP at the first supplied context bar. The
340
- view fetches warm-up history independently from the visible range, so a
341
- range switch does not make the line jump or require another provider call.
342
- """
343
- total_price_volume = 0.0
344
- total_volume = 0.0
345
- out: dict[int, float] = {}
346
- for row in rows:
347
- high = float(row["high"])
348
- low = float(row["low"])
349
- close = float(row["close"])
350
- volume = max(0.0, float(row.get("volume") or 0.0))
351
- if volume <= 0:
352
- continue
353
- total_price_volume += ((high + low + close) / 3.0) * volume
354
- total_volume += volume
355
- if total_volume > 0:
356
- out[int(row["time"])] = round(total_price_volume / total_volume, 6)
357
- return out
161
+ """TA-Lib path-dependent VWAP anchored at the first supplied bar."""
162
+ if not rows:
163
+ return {}
164
+ values = _ta_arrays(rows)
165
+ return _ta_map(rows, talib.VWAP(values["high"], values["low"], values["close"], values["volume"]))
358
166
 
359
167
 
360
168
  def series_atr(
361
169
  rows: list[dict[str, Any]],
362
170
  period: int = DEFAULT_ATR_PERIOD,
363
171
  ) -> dict[int, float]:
364
- highs = _highs(rows)
365
- lows = _lows(rows)
366
- closes = _closes(rows)
367
- times = _times(rows)
368
- period = max(1, int(period))
369
- trs: list[float] = []
370
- for i in range(len(rows)):
371
- if i == 0:
372
- trs.append(highs[i] - lows[i])
373
- else:
374
- tr = max(
375
- highs[i] - lows[i],
376
- abs(highs[i] - closes[i - 1]),
377
- abs(lows[i] - closes[i - 1]),
378
- )
379
- trs.append(tr)
380
- out: dict[int, float] = {}
381
- if len(trs) < period:
382
- return out
383
- atr = sum(trs[:period]) / period
384
- out[int(times[period - 1])] = round(atr, 6)
385
- for i in range(period, len(trs)):
386
- atr = (atr * (period - 1) + trs[i]) / period
387
- out[int(times[i])] = round(atr, 6)
388
- return out
172
+ if not rows:
173
+ return {}
174
+ values = _ta_arrays(rows)
175
+ return _ta_map(rows, talib.ATR(values["high"], values["low"], values["close"], timeperiod=int(period)))
389
176
 
390
177
 
391
178
  # ---------------------------------------------------------------------------
@@ -492,17 +279,22 @@ def metric_support_resistance(
492
279
  prices = [p for _, p in cl]
493
280
  idxs = [i for i, _ in cl]
494
281
  level = sum(prices) / len(prices)
282
+ # A later bar crossing the level invalidates its original role.
283
+ # Keep historical pivots out of the current support/resistance set.
284
+ later = rows[max(idxs) + 1:]
285
+ if kind == "support" and any(float(r["low"]) < level for r in later):
286
+ continue
287
+ if kind == "resistance" and any(float(r["high"]) > level for r in later):
288
+ continue
495
289
  # touches: bars whose high/low within band
496
290
  band = level * (tolerance_pct / 100.0)
497
291
  touches = 0
498
292
  for r in window:
499
- if kind == "resistance":
500
- # Count only high-side near-touches within band.
501
- if abs(float(r["high"]) - level) <= band:
502
- touches += 1
503
- else:
504
- if abs(float(r["low"]) - level) <= band:
505
- touches += 1
293
+ if kind == "resistance":
294
+ if abs(float(r["high"]) - level) <= band:
295
+ touches += 1
296
+ elif abs(float(r["low"]) - level) <= band:
297
+ touches += 1
506
298
  out.append(
507
299
  {
508
300
  "price": round(level, 4),
@@ -513,18 +305,18 @@ def metric_support_resistance(
513
305
  "side": "above" if level >= last_close else "below",
514
306
  }
515
307
  )
516
- # keep levels on the correct side of last close preferentially, sort by touches
308
+ # Rank all candidates first. Side filtering happens before the limit so
309
+ # stale levels cannot consume the five available slots.
517
310
  out.sort(key=lambda x: (-x["touches"], abs(x["price"] - last_close)))
518
- return out[:max_levels]
311
+ return out
519
312
 
520
- supports = [
521
- x for x in cluster(swings_low, kind="support") if x["price"] <= float(rows[-1]["close"]) * 1.01
522
- ]
313
+ last_close = float(rows[-1]["close"])
314
+ supports = [x for x in cluster(swings_low, kind="support") if x["price"] <= last_close][:max_levels]
523
315
  resistances = [
524
316
  x
525
317
  for x in cluster(swings_high, kind="resistance")
526
- if x["price"] >= float(rows[-1]["close"]) * 0.99
527
- ]
318
+ if x["price"] >= last_close
319
+ ][:max_levels]
528
320
  return {
529
321
  "method": "fractal",
530
322
  "lookback": lookback,
@@ -779,6 +571,8 @@ def calc_metrics(
779
571
  ordered = [m for m in wanted if m in AVAILABLE_METRICS]
780
572
  unknown = [m for m in wanted if m not in AVAILABLE_METRICS]
781
573
  result: dict[str, Any] = {
574
+ "calculation_engine": {"name": "TA-Lib", "wrapper_version": ENGINE_VERSION,
575
+ "native_version": NATIVE_VERSION},
782
576
  "count": len(rows),
783
577
  "start_time": int(rows[0]["time"]) if rows else None,
784
578
  "end_time": int(rows[-1]["time"]) if rows else None,
@@ -57,7 +57,7 @@ def _to_time_sec(v: Any) -> int | None:
57
57
  a field named ``time``.
58
58
  """
59
59
  n = _to_float(v)
60
- if n is None or n <= 0:
60
+ if n is None or not math.isfinite(n) or n <= 0:
61
61
  return None
62
62
  if n > _MS_THRESHOLD:
63
63
  n = n / 1000.0
@@ -171,7 +171,7 @@ def normalize_rows(rows: Any) -> list[dict[str, Any]]:
171
171
  return [dedup[k] for k in sorted(dedup)]
172
172
 
173
173
 
174
- def validate_rows(rows: Any, *, min_len: int = 2) -> list[dict[str, Any]]:
174
+ def validate_rows(rows: Any, *, min_len: int = 2, strict_prices: bool = False) -> list[dict[str, Any]]:
175
175
  """Contract gate for calc_* / draw_*.
176
176
 
177
177
  P0 basics (hard fail):
@@ -180,7 +180,8 @@ def validate_rows(rows: Any, *, min_len: int = 2) -> list[dict[str, Any]]:
180
180
  if input is non-empty list but all bars lack OHLC → explicit message)
181
181
  3. timestamps sorted ascending (normalize always sorts)
182
182
 
183
- P1 (not here): high < low reject/repair, gap handling, etc.
183
+ Set strict_prices for public OHLCV input. Pivot/shape algorithms also use
184
+ synthetic high/low sequences, so their existing contract stays unchanged.
184
185
  """
185
186
  if rows is None:
186
187
  raise RowsValidationError("rows is required (got None)")
@@ -189,6 +190,13 @@ def validate_rows(rows: Any, *, min_len: int = 2) -> list[dict[str, Any]]:
189
190
  if len(rows) == 0:
190
191
  raise RowsValidationError("rows is empty")
191
192
 
193
+ for index, raw in enumerate(rows):
194
+ if not isinstance(raw, dict):
195
+ continue
196
+ raw_time = _to_float(_pick_raw_time(raw))
197
+ if raw_time is not None and not math.isfinite(raw_time):
198
+ raise RowsValidationError(f"bar {index}: timestamp must be finite")
199
+
192
200
  raw_count = len(rows)
193
201
  norm = normalize_rows(rows)
194
202
 
@@ -207,6 +215,10 @@ def validate_rows(rows: Any, *, min_len: int = 2) -> list[dict[str, Any]]:
207
215
  prev = None
208
216
  for r in norm:
209
217
  t = int(r["time"])
218
+ if strict_prices and r["high"] < r["low"]:
219
+ raise RowsValidationError(f"bar at {t}: high must be at least low")
220
+ if strict_prices and r["volume"] < 0:
221
+ raise RowsValidationError(f"bar at {t}: volume must be non-negative")
210
222
  if prev is not None and t < prev:
211
223
  raise RowsValidationError(
212
224
  f"timestamps not sorted after normalize (saw {t} after {prev})"
@@ -0,0 +1,99 @@
1
+ """Pinned TA-Lib engine shared by public analysis and built-in indicators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import talib
10
+ from talib import abstract
11
+
12
+
13
+ ENGINE_VERSION = "0.8.2"
14
+ FUNCTION_COUNT = 201
15
+ if talib.__version__ != ENGINE_VERSION or len(talib.get_functions()) != FUNCTION_COUNT:
16
+ raise RuntimeError("TA-Lib version/catalog mismatch; legacy formulas are not a fallback")
17
+
18
+ NATIVE_VERSION = getattr(talib, "__ta_version__", b"unknown")
19
+ if isinstance(NATIVE_VERSION, bytes):
20
+ NATIVE_VERSION = NATIVE_VERSION.decode("utf-8", errors="replace")
21
+
22
+
23
+ def arrays(rows: list[dict[str, Any]]) -> dict[str, np.ndarray]:
24
+ return {key: np.asarray([float(row[key]) for row in rows], dtype=np.float64)
25
+ for key in ("open", "high", "low", "close", "volume")}
26
+
27
+
28
+ def finite_map(rows: list[dict[str, Any]], values: Any, digits: int = 6) -> dict[int, float]:
29
+ result: dict[int, float] = {}
30
+ for row, value in zip(rows, values):
31
+ number = float(value)
32
+ if math.isfinite(number):
33
+ result[int(row["time"])] = round(number, digits)
34
+ return result
35
+
36
+
37
+ def catalog() -> list[dict[str, Any]]:
38
+ return [{"name": name, **abstract.Function(name).info} for name in talib.get_functions()]
39
+
40
+
41
+ def calculate(name: str, rows: list[dict[str, Any]], *, parameters: dict[str, int | float] | None = None,
42
+ price_sources: dict[str, str] | None = None, periods_constant: int = 14) -> tuple[dict[str, Any], dict[str, list[int | float | None]]]:
43
+ if name not in talib.get_functions():
44
+ raise ValueError("unknown TA-Lib function")
45
+ if not 1 <= len(rows) <= 4000:
46
+ raise ValueError("TA-Lib requires 1..4000 loaded candles")
47
+ function = abstract.Function(name)
48
+ info = function.info
49
+ defaults = info["parameters"]
50
+ selected = dict(parameters or {})
51
+ if set(selected) - set(defaults):
52
+ raise ValueError("unsupported TA-Lib parameter")
53
+ for key, value in selected.items():
54
+ default = defaults[key]
55
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
56
+ raise ValueError("TA-Lib parameters must be finite numbers")
57
+ if type(default) is int and (type(value) is not int or abs(value) > 4000):
58
+ raise ValueError("TA-Lib integer parameter out of bounds")
59
+ if type(default) is float:
60
+ if abs(value) > 1_000_000:
61
+ raise ValueError("TA-Lib numeric parameter out of bounds")
62
+ # JSON callers naturally send 2 for a deviation of 2.0. The
63
+ # TA-Lib abstract wrapper requires an actual Python float.
64
+ selected[key] = float(value)
65
+ function.parameters = selected
66
+ sources = dict(price_sources or {})
67
+ allowed_roles = set(info["input_names"]) & {"price", "price0", "price1"}
68
+ if set(sources) - allowed_roles:
69
+ raise ValueError(f"{name} price_sources keys must be {sorted(allowed_roles)}; "
70
+ "see list_ta_functions input_names, not low-level TA-Lib names")
71
+ if any(value not in {"open", "high", "low", "close"} for value in sources.values()):
72
+ raise ValueError("price_sources values must be open, high, low, or close")
73
+ if sources:
74
+ function.input_names = sources
75
+ data = arrays(rows)
76
+ if name == "MAVP":
77
+ if type(periods_constant) is not int or not 2 <= periods_constant <= 4000:
78
+ raise ValueError("MAVP periods_constant must be an integer from 2 to 4000")
79
+ minperiod = selected.get("minperiod", defaults["minperiod"])
80
+ maxperiod = selected.get("maxperiod", defaults["maxperiod"])
81
+ if not minperiod <= periods_constant <= maxperiod:
82
+ raise ValueError("MAVP periods_constant must be within minperiod and maxperiod")
83
+ data["periods"] = np.full(len(rows), float(periods_constant), dtype=np.float64)
84
+ elif periods_constant != 14:
85
+ raise ValueError("periods_constant applies only to MAVP")
86
+ function.set_input_arrays(data)
87
+ raw = function()
88
+ outputs = raw if isinstance(raw, (list, tuple)) else [raw]
89
+ names = list(info["output_names"])
90
+ if len(outputs) != len(names):
91
+ raise RuntimeError("TA-Lib output metadata mismatch")
92
+ values: dict[str, list[int | float | None]] = {}
93
+ for output_name, output in zip(names, outputs):
94
+ vector = np.asarray(output)
95
+ if len(vector) != len(rows):
96
+ raise RuntimeError("TA-Lib output length mismatch")
97
+ integer_output = np.issubdtype(vector.dtype, np.integer)
98
+ values[output_name] = [int(x) if integer_output else float(x) if math.isfinite(float(x)) else None for x in vector]
99
+ return info, values
@@ -0,0 +1,15 @@
1
+ /** Non-authorizing row identity for candle-index-aligned drawings. */
2
+ export function candleSequenceHash(rows) {
3
+ const bytes = new DataView(new ArrayBuffer(8));
4
+ let hash = 0xcbf29ce484222325n;
5
+ for (const row of rows)
6
+ for (const key of ['time', 'open', 'high', 'low', 'close', 'volume']) {
7
+ const value = row?.[key];
8
+ if (typeof value !== 'number' || !Number.isFinite(value))
9
+ throw Error('invalid_candle_sequence');
10
+ bytes.setFloat64(0, value, false);
11
+ for (let i = 0; i < 8; i++)
12
+ hash = BigInt.asUintN(64, (hash ^ BigInt(bytes.getUint8(i))) * 0x100000001b3n);
13
+ }
14
+ return hash.toString(16).padStart(16, '0');
15
+ }
@@ -0,0 +1,33 @@
1
+ /** Canonical AI-owned text, numeric and icon annotations anchored to exact chart bars. */
2
+ export const CHART_ANNOTATION_ICONS = ['arrow_up', 'arrow_down', 'diamond'];
3
+ export function sanitizeChartAnnotation(raw) {
4
+ if (raw?.type !== 'DRAW_AGENT_ANNOTATION' || !['text_annotation', 'number_annotation', 'icon_annotation'].includes(raw.kind)
5
+ || typeof raw.id !== 'string' || !raw.id || raw.id.length > 128
6
+ || !Number.isSafeInteger(raw.time) || raw.time <= 0 || typeof raw.price !== 'number' || !Number.isFinite(raw.price) || raw.price <= 0
7
+ || !['info', 'warning', 'success', 'danger'].includes(raw.color ?? 'info')
8
+ || typeof (raw.interval ?? 'day') !== 'string')
9
+ throw Error('invalid_chart_annotation');
10
+ const result = { type: raw.type, kind: raw.kind, id: raw.id, interval: raw.interval, label: raw.label ?? '', color: raw.color ?? 'info', time: raw.time, price: raw.price };
11
+ if (typeof result.label !== 'string' || result.label.length > 48 || /[\x00-\x1f]/.test(result.label))
12
+ throw Error('invalid_chart_annotation');
13
+ if (raw.kind === 'text_annotation') {
14
+ if (typeof raw.text !== 'string' || !raw.text.trim() || raw.text.trim().length > 120 || /[\x00-\x1f]/.test(raw.text))
15
+ throw Error('invalid_chart_annotation');
16
+ result.text = raw.text.trim();
17
+ }
18
+ else if (raw.kind === 'number_annotation') {
19
+ if (typeof raw.value !== 'number' || !Number.isFinite(raw.value))
20
+ throw Error('invalid_chart_annotation');
21
+ result.value = raw.value;
22
+ }
23
+ else {
24
+ if (!CHART_ANNOTATION_ICONS.includes(raw.icon))
25
+ throw Error('invalid_chart_annotation');
26
+ result.icon = raw.icon;
27
+ }
28
+ return result;
29
+ }
30
+ export function chartAnnotationText(command) {
31
+ const clean = sanitizeChartAnnotation(command);
32
+ return clean.kind === 'text_annotation' ? clean.text : clean.kind === 'number_annotation' ? String(clean.value) : clean.icon;
33
+ }
@@ -166,6 +166,6 @@ export class ChartApplications {
166
166
  await this.write(path, app); // Record delivery before sending it to a browser.
167
167
  return { candidate_chart_session: token, context_ref: view.ref, conversation_id: view.conversation, view_id: view.view,
168
168
  expected_revision: view.revision, lease_id: app.lease_id, expires_at_ms: app.expires_at_ms, base_state: app.base_state,
169
- payload: { symbol: payload.symbol, interval: payload.interval, chartCommands: payload.chartCommands.filter((c) => ['DRAW_HORIZONTAL_LINE', 'DRAW_AGENT_TREND_LINE', 'DRAW_AGENT_CHANNEL', 'DRAW_AGENT_RECTANGLE'].includes(c.type)) } };
169
+ payload: { symbol: payload.symbol, interval: payload.interval, chartCommands: payload.chartCommands.filter((c) => ['DRAW_HORIZONTAL_LINE', 'DRAW_AGENT_TREND_LINE', 'DRAW_AGENT_CHANNEL', 'DRAW_AGENT_RECTANGLE', 'DRAW_AGENT_FIBONACCI', 'DRAW_AGENT_POLYLINE', 'DRAW_AGENT_ANNOTATION', 'DRAW_AGENT_SERIES_LINE', 'DRAW_AGENT_PRICE_BAND', 'DRAW_AGENT_PRICE_STICKS'].includes(c.type)) } };
170
170
  }
171
171
  }