hyperprop-charting-library 0.1.132 → 0.1.134

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.
@@ -23,9 +23,12 @@ __export(index_exports, {
23
23
  FIB_DEFAULT_PALETTE: () => FIB_DEFAULT_PALETTE,
24
24
  POSITION_DEFAULT_COLORS: () => POSITION_DEFAULT_COLORS,
25
25
  compileScriptIndicator: () => compileScriptIndicator,
26
- createChart: () => createChart
26
+ createChart: () => createChart,
27
+ validateScriptSource: () => validateScriptSource
27
28
  });
28
29
  module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/types.ts
29
32
  var POSITION_DEFAULT_COLORS = ["#26a69a", "#ef5350", "#ffffff"];
30
33
  var FIB_DEFAULT_PALETTE = [
31
34
  "#787b86",
@@ -37,387 +40,127 @@ var FIB_DEFAULT_PALETTE = [
37
40
  "#2962ff",
38
41
  "#9c27b0"
39
42
  ];
40
- var DEFAULT_GRID_OPTIONS = {
41
- color: "#2b2f38",
42
- opacity: 0.38,
43
- horizontalLines: true,
44
- verticalLines: true,
45
- xTickCount: 8,
46
- yTickCount: 6,
47
- horizontalTickCount: 6,
48
- sessionSeparators: false,
49
- sessionSeparatorColor: "#3b4150",
50
- sessionSeparatorOpacity: 0.55
43
+
44
+ // src/indicators.ts
45
+ var getIndicatorSourceValue = (point, source) => {
46
+ if (source === "open") return point.o;
47
+ if (source === "high") return point.h;
48
+ if (source === "low") return point.l;
49
+ if (source === "hl2") return (point.h + point.l) / 2;
50
+ return point.c;
51
51
  };
52
- var DEFAULT_AXIS_OPTIONS = {
53
- lineColor: "#3b3f47",
54
- textColor: "#a9adb6",
55
- fontSize: 12,
56
- lineWidth: 1
52
+ var clampIndicatorLength = (value, fallback) => {
53
+ return Math.max(1, Math.round(Number(value) || fallback));
57
54
  };
58
- var DEFAULT_CROSSHAIR_OPTIONS = {
59
- visible: true,
60
- color: "#94a3b8",
61
- width: 1,
62
- style: "dotted",
63
- mode: "cross",
64
- dotRadius: 3,
65
- showHorizontal: true,
66
- showVertical: true,
67
- showPriceLabel: true,
68
- showTimeLabel: true,
69
- timeLabelFormat: "auto",
70
- labelBackgroundColor: "#0b1220",
71
- labelTextColor: "#cbd5e1",
72
- labelBorderRadius: 3,
73
- labelBorderColor: "#94a3b8",
74
- labelBorderWidth: 1,
75
- labelBorderStyle: "solid",
76
- showPriceActionButton: false,
77
- priceActionButtonIcon: "plusThin",
78
- priceActionButtonText: "+",
79
- priceActionButtonSize: 16,
80
- priceActionButtonGap: 4,
81
- priceActionButtonRounded: true,
82
- priceActionButtonBorderRadius: 8,
83
- sideHintLeft: "",
84
- sideHintRight: "",
85
- sideHintLeftColor: "#26a69a",
86
- sideHintRightColor: "#ef5350"
55
+ var parseColorToRgb = (value) => {
56
+ if (!value) return null;
57
+ const normalized = value.trim().toLowerCase();
58
+ if (normalized === "white") return { r: 255, g: 255, b: 255 };
59
+ if (normalized === "black") return { r: 0, g: 0, b: 0 };
60
+ const hex3 = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(normalized);
61
+ if (hex3) {
62
+ return {
63
+ r: parseInt(hex3[1] + hex3[1], 16),
64
+ g: parseInt(hex3[2] + hex3[2], 16),
65
+ b: parseInt(hex3[3] + hex3[3], 16)
66
+ };
67
+ }
68
+ const hex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})(?:[0-9a-f]{2})?$/.exec(normalized);
69
+ if (hex) {
70
+ return {
71
+ r: parseInt(hex[1], 16),
72
+ g: parseInt(hex[2], 16),
73
+ b: parseInt(hex[3], 16)
74
+ };
75
+ }
76
+ const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)$/.exec(normalized);
77
+ if (rgb) {
78
+ return { r: Number(rgb[1]), g: Number(rgb[2]), b: Number(rgb[3]) };
79
+ }
80
+ return null;
87
81
  };
88
- var DEFAULT_WATERMARK_OPTIONS = {
89
- visible: false,
90
- text: "",
91
- color: "#81858d",
92
- opacity: 0.14,
93
- fontSize: 92,
94
- fontWeight: 700,
95
- thickness: 0,
96
- imageSrc: "",
97
- imageScale: 1,
98
- imageMaxWidthRatio: 0.42,
99
- imageMaxHeightRatio: 0.3,
100
- imageTintColor: "",
101
- imageTintOpacity: 1
82
+ var labelTextColorOn = (background, textColor) => {
83
+ const rgb = parseColorToRgb(background);
84
+ if (!rgb) return textColor;
85
+ const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
86
+ return luminance >= 0.62 ? "#000000" : textColor;
102
87
  };
103
- var DEFAULT_DASH_PATTERNS = {
104
- dotted: [2, 2],
105
- dashed: [8, 6],
106
- connectorDotted: [2, 3],
107
- connectorDashed: [6, 5],
108
- borderDotted: [2, 2],
109
- borderDashed: [6, 4]
88
+ var computeSmaSeries = (data, length, source) => {
89
+ const result = new Array(data.length).fill(null);
90
+ let sum = 0;
91
+ for (let i = 0; i < data.length; i += 1) {
92
+ const point = data[i];
93
+ if (!point) continue;
94
+ const value = getIndicatorSourceValue(point, source);
95
+ sum += value;
96
+ if (i >= length) {
97
+ const oldPoint = data[i - length];
98
+ if (oldPoint) {
99
+ sum -= getIndicatorSourceValue(oldPoint, source);
100
+ }
101
+ }
102
+ if (i >= length - 1) {
103
+ result[i] = sum / length;
104
+ }
105
+ }
106
+ return result;
110
107
  };
111
- var DEFAULT_LABELS_OPTIONS = {
112
- visible: true,
113
- symbolName: "",
114
- showSymbolName: false,
115
- showLastPrice: true,
116
- showPreviousClose: false,
117
- previousClosePrice: Number.NaN,
118
- showHighLow: false,
119
- showBidAsk: false,
120
- bidPrice: Number.NaN,
121
- askPrice: Number.NaN,
122
- showIndicatorNames: false,
123
- showIndicatorValues: false,
124
- showIndicatorValueLabels: true,
125
- indicatorLegendPosition: "top-left",
126
- indicatorLegendOffsetX: 10,
127
- indicatorLegendOffsetY: 10,
128
- showCountdownToBarClose: false,
129
- noOverlapping: true,
130
- backgroundColor: "#0b1220",
131
- textColor: "#cbd5e1",
132
- mutedTextColor: "#94a3b8",
133
- symbolNameBackgroundColor: "#1f2937",
134
- symbolNameTextColor: "#e5e7eb",
135
- previousCloseColor: "#94a3b8",
136
- highLowColor: "#a78bfa",
137
- bidColor: "#ef4444",
138
- askColor: "#22c55e",
139
- indicatorTextColor: "#cbd5e1",
140
- borderRadius: 3,
141
- labelHeight: 20,
142
- labelPaddingX: 8
108
+ var computeEmaSeries = (data, length, source) => {
109
+ const result = new Array(data.length).fill(null);
110
+ const alpha = 2 / (length + 1);
111
+ let prev = null;
112
+ for (let i = 0; i < data.length; i += 1) {
113
+ const point = data[i];
114
+ if (!point) continue;
115
+ const value = getIndicatorSourceValue(point, source);
116
+ prev = prev === null ? value : alpha * value + (1 - alpha) * prev;
117
+ if (i >= length - 1) {
118
+ result[i] = prev;
119
+ }
120
+ }
121
+ return result;
143
122
  };
144
- var DEFAULT_PRICE_LINE_OPTIONS = {
145
- visible: true,
146
- style: "solid",
147
- thickness: 1,
148
- color: "#38bdf8",
149
- labelBackgroundColor: "#0b1220",
150
- labelTextColor: "#60a5fa",
151
- labelBorderRadius: 3,
152
- showLabel: true,
153
- pinOutOfRange: false
123
+ var computeRmaSeries = (data, length, source) => {
124
+ const result = new Array(data.length).fill(null);
125
+ let prev = null;
126
+ let seedSum = 0;
127
+ for (let i = 0; i < data.length; i += 1) {
128
+ const point = data[i];
129
+ if (!point) continue;
130
+ const value = getIndicatorSourceValue(point, source);
131
+ if (i < length) {
132
+ seedSum += value;
133
+ if (i === length - 1) {
134
+ prev = seedSum / length;
135
+ result[i] = prev;
136
+ }
137
+ continue;
138
+ }
139
+ prev = prev === null ? value : (prev * (length - 1) + value) / length;
140
+ result[i] = prev;
141
+ }
142
+ return result;
154
143
  };
155
- var DEFAULT_ORDER_LINE_OPTIONS = {
156
- visible: true,
157
- behavior: "static",
158
- style: "solid",
159
- thickness: 1,
160
- color: "rgba(59,130,246,0.8)",
161
- labelBackgroundColor: "#0b1220",
162
- labelTextColor: "#60a5fa",
163
- labelBorderRadius: 3,
164
- showCloseButton: true,
165
- widgetPosition: "left",
166
- widgetPaddingRight: 10,
167
- draggable: false,
168
- actionButtonAction: "execute",
169
- actionButtonTextColor: "#dbeafe",
170
- actionButtonBackgroundColor: "#2563eb",
171
- actionButtonBorderRadius: 2,
172
- actionButtonMinWidth: 34,
173
- actionButtonPaddingX: 0,
174
- actionButtonFullHeight: true,
175
- actionButtonFontWeight: 500,
176
- actionButtonBorderColor: "#2563eb",
177
- actionButtonBorderStyle: "solid",
178
- actionButtonsInnerGap: 6,
179
- actionButtonsGroupGap: 8,
180
- actionButtons: [],
181
- connectorToPrice: Number.NaN,
182
- connectorColor: "#2563eb",
183
- connectorStyle: "dotted",
184
- connectorThickness: 1,
185
- connectorAnchorPaddingRight: 10,
186
- fillToPrice: Number.NaN,
187
- fillColor: "rgba(37,99,235,0.18)",
188
- pinOutOfRange: false
189
- };
190
- var DEFAULT_OPTIONS = {
191
- width: 720,
192
- height: 360,
193
- backgroundColor: "#101114",
194
- axisColor: "#7f8289",
195
- axis: DEFAULT_AXIS_OPTIONS,
196
- xAxis: DEFAULT_AXIS_OPTIONS,
197
- yAxis: DEFAULT_AXIS_OPTIONS,
198
- priceDecimals: 2,
199
- stabilizePriceLabels: true,
200
- priceLabelMinIntegerDigits: 3,
201
- priceLabelWidthTemplate: "",
202
- initialViewport: "latest",
203
- initialVisibleBars: 60,
204
- minVisibleBars: 5,
205
- maxVisibleBars: 2e4,
206
- maxPanBars: 1e6,
207
- rightEdgePaddingBars: 2,
208
- preserveViewportOnDataUpdate: true,
209
- upColor: "#2fb171",
210
- downColor: "#d35a5a",
211
- gridColor: "#252932",
212
- fontFamily: "Inter, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",
213
- candleBodyWidthRatio: 0.7,
214
- candleMinWidth: 0.5,
215
- candleWickWidth: 1,
216
- tickSize: 0,
217
- candleColorMode: "openClose",
218
- candleColorEpsilon: -1,
219
- chartType: "candles",
220
- lineColor: "#2962ff",
221
- lineWidth: 2,
222
- areaFillOpacity: 0.12,
223
- baselinePrice: null,
224
- // 0 = deterministic scale (lightweight-charts behavior): the y-range is a
225
- // pure function of the visible data, so it can never drift or "breathe".
226
- // Values > 0 re-enable eased contraction for hosts that prefer it.
227
- autoScaleSmoothing: 0,
228
- autoScaleIgnoreLatestCandle: true,
229
- kineticScroll: { touch: true, mouse: false },
230
- timeStepMs: 0,
231
- clockOffsetMs: 0,
232
- pinOutOfRangeLines: false,
233
- doubleClickEnabled: true,
234
- doubleClickAction: "reset",
235
- crosshair: DEFAULT_CROSSHAIR_OPTIONS,
236
- grid: DEFAULT_GRID_OPTIONS,
237
- watermark: DEFAULT_WATERMARK_OPTIONS,
238
- priceLines: [],
239
- orderLines: [],
240
- tickerLine: {
241
- visible: true,
242
- style: "dotted",
243
- thickness: 1,
244
- labelTextColor: "#0b1220",
245
- labelSubtext: "",
246
- labelSubtexts: [],
247
- labelSubtextColor: "#0b1220",
248
- labelSubtextFontSize: 0,
249
- showCountdownInLabel: false,
250
- labelBorderRadius: 3
251
- },
252
- labels: DEFAULT_LABELS_OPTIONS,
253
- dashPatterns: DEFAULT_DASH_PATTERNS,
254
- indicators: [],
255
- drawings: []
256
- };
257
- var mergeChartOptions = (baseOptions, options = {}) => ({
258
- ...baseOptions,
259
- ...options,
260
- axis: {
261
- ...baseOptions.axis,
262
- ...options.axis ?? {},
263
- ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {}
264
- },
265
- xAxis: {
266
- ...baseOptions.xAxis,
267
- ...options.axis ?? {},
268
- ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {},
269
- ...options.xAxis ?? {}
270
- },
271
- yAxis: {
272
- ...baseOptions.yAxis,
273
- ...options.axis ?? {},
274
- ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {},
275
- ...options.yAxis ?? {}
276
- },
277
- crosshair: {
278
- ...baseOptions.crosshair,
279
- ...options.crosshair ?? {}
280
- },
281
- grid: {
282
- ...baseOptions.grid,
283
- ...options.grid ?? {}
284
- },
285
- watermark: {
286
- ...baseOptions.watermark,
287
- ...options.watermark ?? {}
288
- },
289
- tickerLine: {
290
- ...baseOptions.tickerLine,
291
- ...options.tickerLine ?? {}
292
- },
293
- labels: {
294
- ...baseOptions.labels,
295
- ...options.labels ?? {}
296
- },
297
- dashPatterns: {
298
- ...baseOptions.dashPatterns,
299
- ...options.dashPatterns ?? {}
300
- }
301
- });
302
- var getIndicatorSourceValue = (point, source) => {
303
- if (source === "open") return point.o;
304
- if (source === "high") return point.h;
305
- if (source === "low") return point.l;
306
- if (source === "hl2") return (point.h + point.l) / 2;
307
- return point.c;
308
- };
309
- var clampIndicatorLength = (value, fallback) => {
310
- return Math.max(1, Math.round(Number(value) || fallback));
311
- };
312
- var parseColorToRgb = (value) => {
313
- if (!value) return null;
314
- const normalized = value.trim().toLowerCase();
315
- if (normalized === "white") return { r: 255, g: 255, b: 255 };
316
- if (normalized === "black") return { r: 0, g: 0, b: 0 };
317
- const hex3 = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(normalized);
318
- if (hex3) {
319
- return {
320
- r: parseInt(hex3[1] + hex3[1], 16),
321
- g: parseInt(hex3[2] + hex3[2], 16),
322
- b: parseInt(hex3[3] + hex3[3], 16)
323
- };
324
- }
325
- const hex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})(?:[0-9a-f]{2})?$/.exec(normalized);
326
- if (hex) {
327
- return {
328
- r: parseInt(hex[1], 16),
329
- g: parseInt(hex[2], 16),
330
- b: parseInt(hex[3], 16)
331
- };
332
- }
333
- const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)$/.exec(normalized);
334
- if (rgb) {
335
- return { r: Number(rgb[1]), g: Number(rgb[2]), b: Number(rgb[3]) };
336
- }
337
- return null;
338
- };
339
- var labelTextColorOn = (background, textColor) => {
340
- const rgb = parseColorToRgb(background);
341
- if (!rgb) return textColor;
342
- const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
343
- return luminance >= 0.62 ? "#000000" : textColor;
344
- };
345
- var computeSmaSeries = (data, length, source) => {
346
- const result = new Array(data.length).fill(null);
347
- let sum = 0;
348
- for (let i = 0; i < data.length; i += 1) {
349
- const point = data[i];
350
- if (!point) continue;
351
- const value = getIndicatorSourceValue(point, source);
352
- sum += value;
353
- if (i >= length) {
354
- const oldPoint = data[i - length];
355
- if (oldPoint) {
356
- sum -= getIndicatorSourceValue(oldPoint, source);
357
- }
358
- }
359
- if (i >= length - 1) {
360
- result[i] = sum / length;
361
- }
362
- }
363
- return result;
364
- };
365
- var computeEmaSeries = (data, length, source) => {
366
- const result = new Array(data.length).fill(null);
367
- const alpha = 2 / (length + 1);
368
- let prev = null;
369
- for (let i = 0; i < data.length; i += 1) {
370
- const point = data[i];
371
- if (!point) continue;
372
- const value = getIndicatorSourceValue(point, source);
373
- prev = prev === null ? value : alpha * value + (1 - alpha) * prev;
374
- if (i >= length - 1) {
375
- result[i] = prev;
376
- }
377
- }
378
- return result;
379
- };
380
- var computeRmaSeries = (data, length, source) => {
381
- const result = new Array(data.length).fill(null);
382
- let prev = null;
383
- let seedSum = 0;
384
- for (let i = 0; i < data.length; i += 1) {
385
- const point = data[i];
386
- if (!point) continue;
387
- const value = getIndicatorSourceValue(point, source);
388
- if (i < length) {
389
- seedSum += value;
390
- if (i === length - 1) {
391
- prev = seedSum / length;
392
- result[i] = prev;
393
- }
394
- continue;
395
- }
396
- prev = prev === null ? value : (prev * (length - 1) + value) / length;
397
- result[i] = prev;
398
- }
399
- return result;
400
- };
401
- var computeWmaSeriesFromValues = (values, length) => {
402
- const result = new Array(values.length).fill(null);
403
- const denominator = length * (length + 1) / 2;
404
- for (let i = 0; i < values.length; i += 1) {
405
- if (i < length - 1) continue;
406
- let weighted = 0;
407
- let valid = true;
408
- for (let j = 0; j < length; j += 1) {
409
- const value = values[i - length + 1 + j];
410
- if (value == null) {
411
- valid = false;
412
- break;
413
- }
414
- weighted += value * (j + 1);
415
- }
416
- if (valid) {
417
- result[i] = weighted / denominator;
418
- }
419
- }
420
- return result;
144
+ var computeWmaSeriesFromValues = (values, length) => {
145
+ const result = new Array(values.length).fill(null);
146
+ const denominator = length * (length + 1) / 2;
147
+ for (let i = 0; i < values.length; i += 1) {
148
+ if (i < length - 1) continue;
149
+ let weighted = 0;
150
+ let valid = true;
151
+ for (let j = 0; j < length; j += 1) {
152
+ const value = values[i - length + 1 + j];
153
+ if (value == null) {
154
+ valid = false;
155
+ break;
156
+ }
157
+ weighted += value * (j + 1);
158
+ }
159
+ if (valid) {
160
+ result[i] = weighted / denominator;
161
+ }
162
+ }
163
+ return result;
421
164
  };
422
165
  var computeWmaSeries = (data, length, source) => {
423
166
  const sourceValues = data.map((point) => getIndicatorSourceValue(point, source));
@@ -630,14 +373,23 @@ var withCachedSeries = (key, data, compute) => {
630
373
  return values;
631
374
  };
632
375
  var builtInComputationCache = /* @__PURE__ */ new Map();
376
+ var COMPUTATION_CACHE_MAX_ENTRIES = 128;
633
377
  var withCachedComputation = (key, data, compute) => {
634
378
  const fingerprint = getSeriesFingerprint(data);
635
379
  const existing = builtInComputationCache.get(key);
636
380
  if (existing && existing.fingerprint === fingerprint) {
381
+ builtInComputationCache.delete(key);
382
+ builtInComputationCache.set(key, existing);
637
383
  return existing.value;
638
384
  }
639
385
  const value = compute();
386
+ builtInComputationCache.delete(key);
640
387
  builtInComputationCache.set(key, { fingerprint, value });
388
+ while (builtInComputationCache.size > COMPUTATION_CACHE_MAX_ENTRIES) {
389
+ const oldest = builtInComputationCache.keys().next().value;
390
+ if (oldest === void 0) break;
391
+ builtInComputationCache.delete(oldest);
392
+ }
641
393
  return value;
642
394
  };
643
395
  var rollingExtremeSeries = (values, length, mode) => {
@@ -1495,208 +1247,19 @@ var drawSeparateMultiSeries = (ctx, renderContext, seriesList, options = {}) =>
1495
1247
  }
1496
1248
  return paneInfo;
1497
1249
  };
1498
- var scriptRollingExtreme = (values, length, mode) => {
1499
- const fallback = mode === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
1500
- const filled = new Array(values.length);
1501
- for (let i = 0; i < values.length; i += 1) {
1502
- const value = values[i];
1503
- filled[i] = value != null && Number.isFinite(value) ? value : fallback;
1504
- }
1505
- const raw = rollingExtremeSeries(filled, Math.max(1, Math.floor(length)), mode);
1506
- return raw.map((value) => value != null && Number.isFinite(value) ? value : null);
1507
- };
1508
- var scriptStdevSeries = (values, length) => {
1509
- const window2 = Math.max(1, Math.floor(length));
1510
- const result = new Array(values.length).fill(null);
1511
- let sum = 0;
1512
- let sumSq = 0;
1513
- let valid = 0;
1514
- for (let i = 0; i < values.length; i += 1) {
1515
- const value = values[i];
1516
- if (value == null || !Number.isFinite(value)) {
1517
- sum = 0;
1518
- sumSq = 0;
1519
- valid = 0;
1520
- continue;
1521
- }
1522
- sum += value;
1523
- sumSq += value * value;
1524
- valid += 1;
1525
- if (valid > window2) {
1526
- const old = values[i - window2];
1527
- sum -= old;
1528
- sumSq -= old * old;
1529
- valid -= 1;
1530
- }
1531
- if (valid === window2) {
1532
- const mean = sum / window2;
1533
- result[i] = Math.sqrt(Math.max(0, sumSq / window2 - mean * mean));
1534
- }
1535
- }
1536
- return result;
1537
- };
1538
- var scriptAtrSeries = (bars, length) => {
1539
- const tr = new Array(bars.length).fill(null);
1540
- for (let i = 0; i < bars.length; i += 1) {
1541
- const bar = bars[i];
1542
- if (i === 0) {
1543
- tr[i] = bar.h - bar.l;
1544
- continue;
1545
- }
1546
- const prevClose = bars[i - 1].c;
1547
- tr[i] = Math.max(bar.h - bar.l, Math.abs(bar.h - prevClose), Math.abs(bar.l - prevClose));
1548
- }
1549
- return rmaFromValues(tr, Math.max(1, Math.floor(length)));
1550
- };
1551
- var SCRIPT_HELPERS = Object.freeze({
1552
- sma: (values, length) => smaFromValues(values, Math.max(1, Math.floor(length))),
1553
- ema: (values, length) => emaFromValues(values, Math.max(1, Math.floor(length))),
1554
- rma: (values, length) => rmaFromValues(values, Math.max(1, Math.floor(length))),
1555
- highest: (values, length) => scriptRollingExtreme(values, length, "max"),
1556
- lowest: (values, length) => scriptRollingExtreme(values, length, "min"),
1557
- change: (values, length = 1) => values.map((value, index) => {
1558
- const prev = values[index - Math.max(1, Math.floor(length))];
1559
- return value != null && prev != null ? value - prev : null;
1560
- }),
1561
- stdev: scriptStdevSeries,
1562
- atr: scriptAtrSeries
1563
- });
1564
- var SCRIPT_PLOT_PALETTE = ["#2962ff", "#ff6d00", "#26a69a", "#ab47bc", "#ef5350", "#fdd835"];
1565
- var hashScriptSource = (source) => {
1566
- let hash = 5381;
1567
- for (let i = 0; i < source.length; i += 1) {
1568
- hash = (hash << 5) + hash + source.charCodeAt(i) | 0;
1569
- }
1570
- return (hash >>> 0).toString(36);
1571
- };
1572
- var compileScriptCompute = (source) => {
1573
- const factory = new Function(
1574
- `"use strict";
1575
- ${source}
1576
- ;if (typeof compute !== "function") { throw new Error("Script must define function compute(bars, inputs, hp)"); }
1577
- return compute;`
1578
- );
1579
- return factory();
1580
- };
1581
- var drawScriptError = (ctx, renderContext, name, message) => {
1582
- ctx.save();
1583
- ctx.font = "11px -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";
1584
- ctx.textAlign = "left";
1585
- ctx.textBaseline = "top";
1586
- ctx.fillStyle = "#ef5350";
1587
- const text = `${name}: ${message}`.slice(0, 160);
1588
- ctx.fillText(text, renderContext.chartLeft + 10, renderContext.chartTop + 24);
1589
- ctx.restore();
1590
- };
1591
- var compileScriptIndicator = (definition) => {
1592
- const pane = definition.pane ?? "separate";
1593
- const defaultInputs = { showValueLine: true };
1594
- for (const input of definition.inputs ?? []) {
1595
- defaultInputs[input.key] = input.default;
1596
- }
1597
- let compiled = null;
1598
- let compileError = null;
1599
- try {
1600
- compiled = compileScriptCompute(definition.source);
1601
- } catch (error) {
1602
- compileError = error instanceof Error ? error.message : String(error);
1603
- }
1604
- const sourceKey = hashScriptSource(definition.source);
1605
- const runCompute = (data, inputs) => {
1606
- if (!compiled) {
1607
- return { error: compileError ?? "Script failed to compile" };
1608
- }
1609
- try {
1610
- const result = compiled(data, inputs, SCRIPT_HELPERS);
1611
- if (!result || !Array.isArray(result.plots)) {
1612
- return { error: "compute() must return { plots: [...] }" };
1613
- }
1614
- for (const plot of result.plots) {
1615
- if (!plot || !Array.isArray(plot.values)) {
1616
- return { error: "Every plot needs a `values` array" };
1617
- }
1618
- }
1619
- return { result };
1620
- } catch (error) {
1621
- return { error: error instanceof Error ? error.message : String(error) };
1622
- }
1623
- };
1624
- const cachedCompute = (data, inputs) => withCachedComputation(
1625
- `script|${definition.id}|${sourceKey}|${JSON.stringify(inputs)}`,
1626
- data,
1627
- () => runCompute(data, inputs)
1628
- );
1629
- const plugin = {
1630
- id: definition.id,
1631
- name: definition.name,
1632
- pane,
1633
- defaultInputs,
1634
- draw: (ctx, renderContext, inputs) => {
1635
- const outcome = cachedCompute(renderContext.data, inputs);
1636
- if (!outcome.result) {
1637
- drawScriptError(ctx, renderContext, definition.name, outcome.error ?? "Unknown script error");
1638
- return pane === "separate" ? { title: `${definition.name} (script error)` } : void 0;
1639
- }
1640
- const { plots, range, guides, decimals } = outcome.result;
1641
- if (pane === "separate") {
1642
- const seriesList = plots.map((plot, index) => ({
1643
- values: plot.values,
1644
- color: plot.color ?? SCRIPT_PLOT_PALETTE[index % SCRIPT_PLOT_PALETTE.length],
1645
- ...plot.width !== void 0 ? { width: plot.width } : {},
1646
- ...plot.title ? { label: plot.title } : {},
1647
- ...plot.style === "histogram" ? { histogram: true } : {},
1648
- ...plot.negativeColor ? { negativeColor: plot.negativeColor } : {}
1649
- }));
1650
- return drawSeparateMultiSeries(ctx, renderContext, seriesList, {
1651
- title: definition.name,
1652
- ...range?.min !== void 0 ? { minOverride: range.min } : {},
1653
- ...range?.max !== void 0 ? { maxOverride: range.max } : {},
1654
- ...guides && guides.length > 0 ? { guideLines: guides } : {},
1655
- ...decimals !== void 0 ? { decimals } : {},
1656
- valueLines: inputs.showValueLine !== false
1657
- });
1658
- }
1659
- for (let index = 0; index < plots.length; index += 1) {
1660
- const plot = plots[index];
1661
- if (plot.style === "histogram") continue;
1662
- drawOverlaySeries(
1663
- ctx,
1664
- renderContext,
1665
- plot.values,
1666
- plot.color ?? SCRIPT_PLOT_PALETTE[index % SCRIPT_PLOT_PALETTE.length],
1667
- plot.width ?? 2
1668
- );
1669
- }
1670
- return void 0;
1671
- },
1672
- ...pane === "overlay" ? {
1673
- getAutoscaleRange: (data, startIndex, endIndex, inputs, skipIndex) => {
1674
- const outcome = cachedCompute(data, inputs);
1675
- if (!outcome.result) return null;
1676
- const lineSeries = outcome.result.plots.filter((plot) => plot.style !== "histogram").map((plot) => plot.values);
1677
- if (lineSeries.length === 0) return null;
1678
- return rangeOfSeries(lineSeries, startIndex, endIndex, skipIndex);
1679
- }
1680
- } : {}
1681
- };
1682
- if (definition.paneHeightRatio !== void 0) {
1683
- plugin.paneHeightRatio = definition.paneHeightRatio;
1684
- }
1685
- return plugin;
1686
- };
1687
- var computeMacd = (data, fast, slow, signalLength) => {
1688
- const fastEma = computeEmaSeries(data, fast, "close");
1689
- const slowEma = computeEmaSeries(data, slow, "close");
1690
- const macd = fastEma.map((value, idx) => {
1691
- const slowValue = slowEma[idx];
1692
- return value == null || slowValue == null ? null : value - slowValue;
1693
- });
1694
- const signal = emaFromValues(macd, signalLength);
1695
- const hist = macd.map((value, idx) => {
1696
- const signalValue = signal[idx];
1697
- return value == null || signalValue == null ? null : value - signalValue;
1698
- });
1699
- return { macd, signal, hist };
1250
+ var computeMacd = (data, fast, slow, signalLength) => {
1251
+ const fastEma = computeEmaSeries(data, fast, "close");
1252
+ const slowEma = computeEmaSeries(data, slow, "close");
1253
+ const macd = fastEma.map((value, idx) => {
1254
+ const slowValue = slowEma[idx];
1255
+ return value == null || slowValue == null ? null : value - slowValue;
1256
+ });
1257
+ const signal = emaFromValues(macd, signalLength);
1258
+ const hist = macd.map((value, idx) => {
1259
+ const signalValue = signal[idx];
1260
+ return value == null || signalValue == null ? null : value - signalValue;
1261
+ });
1262
+ return { macd, signal, hist };
1700
1263
  };
1701
1264
  var computeStochastic = (data, kLength, kSmoothing, dLength) => {
1702
1265
  const highestHigh = rollingExtremeSeries(data.map((point) => point.h), kLength, "max");
@@ -2512,6 +2075,763 @@ var BUILTIN_INDICATORS = [
2512
2075
  BUILTIN_KELTNER_INDICATOR,
2513
2076
  BUILTIN_DONCHIAN_INDICATOR
2514
2077
  ];
2078
+
2079
+ // src/scripts.ts
2080
+ var scriptRollingExtreme = (values, length, mode) => {
2081
+ const fallback = mode === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
2082
+ const filled = new Array(values.length);
2083
+ for (let i = 0; i < values.length; i += 1) {
2084
+ const value = values[i];
2085
+ filled[i] = value != null && Number.isFinite(value) ? value : fallback;
2086
+ }
2087
+ const raw = rollingExtremeSeries(filled, Math.max(1, Math.floor(length)), mode);
2088
+ return raw.map((value) => value != null && Number.isFinite(value) ? value : null);
2089
+ };
2090
+ var scriptStdevSeries = (values, length) => {
2091
+ const window2 = Math.max(1, Math.floor(length));
2092
+ const result = new Array(values.length).fill(null);
2093
+ let sum = 0;
2094
+ let sumSq = 0;
2095
+ let valid = 0;
2096
+ for (let i = 0; i < values.length; i += 1) {
2097
+ const value = values[i];
2098
+ if (value == null || !Number.isFinite(value)) {
2099
+ sum = 0;
2100
+ sumSq = 0;
2101
+ valid = 0;
2102
+ continue;
2103
+ }
2104
+ sum += value;
2105
+ sumSq += value * value;
2106
+ valid += 1;
2107
+ if (valid > window2) {
2108
+ const old = values[i - window2];
2109
+ sum -= old;
2110
+ sumSq -= old * old;
2111
+ valid -= 1;
2112
+ }
2113
+ if (valid === window2) {
2114
+ const mean = sum / window2;
2115
+ result[i] = Math.sqrt(Math.max(0, sumSq / window2 - mean * mean));
2116
+ }
2117
+ }
2118
+ return result;
2119
+ };
2120
+ var scriptAtrSeries = (bars, length) => {
2121
+ const tr = new Array(bars.length).fill(null);
2122
+ for (let i = 0; i < bars.length; i += 1) {
2123
+ const bar = bars[i];
2124
+ if (i === 0) {
2125
+ tr[i] = bar.h - bar.l;
2126
+ continue;
2127
+ }
2128
+ const prevClose = bars[i - 1].c;
2129
+ tr[i] = Math.max(bar.h - bar.l, Math.abs(bar.h - prevClose), Math.abs(bar.l - prevClose));
2130
+ }
2131
+ return rmaFromValues(tr, Math.max(1, Math.floor(length)));
2132
+ };
2133
+ var SCRIPT_HELPERS = Object.freeze({
2134
+ sma: (values, length) => smaFromValues(values, Math.max(1, Math.floor(length))),
2135
+ ema: (values, length) => emaFromValues(values, Math.max(1, Math.floor(length))),
2136
+ rma: (values, length) => rmaFromValues(values, Math.max(1, Math.floor(length))),
2137
+ highest: (values, length) => scriptRollingExtreme(values, length, "max"),
2138
+ lowest: (values, length) => scriptRollingExtreme(values, length, "min"),
2139
+ change: (values, length = 1) => values.map((value, index) => {
2140
+ const prev = values[index - Math.max(1, Math.floor(length))];
2141
+ return value != null && prev != null ? value - prev : null;
2142
+ }),
2143
+ stdev: scriptStdevSeries,
2144
+ atr: scriptAtrSeries
2145
+ });
2146
+ var SCRIPT_PLOT_PALETTE = ["#2962ff", "#ff6d00", "#26a69a", "#ab47bc", "#ef5350", "#fdd835"];
2147
+ var hashScriptSource = (source) => {
2148
+ let hash = 5381;
2149
+ for (let i = 0; i < source.length; i += 1) {
2150
+ hash = (hash << 5) + hash + source.charCodeAt(i) | 0;
2151
+ }
2152
+ return (hash >>> 0).toString(36);
2153
+ };
2154
+ var SCRIPT_GUARD_BUDGET_MS = 1e3;
2155
+ var ScriptBudgetError = class extends Error {
2156
+ constructor() {
2157
+ super(
2158
+ `Script exceeded the ${SCRIPT_GUARD_BUDGET_MS}ms execution budget (possible infinite loop) \u2014 edit the script to retry`
2159
+ );
2160
+ this.name = "ScriptBudgetError";
2161
+ }
2162
+ };
2163
+ var createScriptGuard = () => {
2164
+ let deadline = Date.now() + SCRIPT_GUARD_BUDGET_MS;
2165
+ let count = 0;
2166
+ const guard = (() => {
2167
+ count += 1;
2168
+ if ((count & 1023) === 0 && Date.now() > deadline) {
2169
+ throw new ScriptBudgetError();
2170
+ }
2171
+ return true;
2172
+ });
2173
+ guard.reset = () => {
2174
+ count = 0;
2175
+ deadline = Date.now() + SCRIPT_GUARD_BUDGET_MS;
2176
+ };
2177
+ return guard;
2178
+ };
2179
+ var injectLoopGuards = (source, guardName) => {
2180
+ const n = source.length;
2181
+ const isIdChar = (ch) => ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "_" || ch === "$";
2182
+ const scanString = (start) => {
2183
+ const quote = source[start];
2184
+ let j = start + 1;
2185
+ while (j < n) {
2186
+ const cj = source[j];
2187
+ if (cj === "\\") {
2188
+ j += 2;
2189
+ continue;
2190
+ }
2191
+ if (cj === quote) {
2192
+ return j + 1;
2193
+ }
2194
+ if (quote === "`" && cj === "$" && source[j + 1] === "{") {
2195
+ let depth = 1;
2196
+ j += 2;
2197
+ while (j < n && depth > 0) {
2198
+ const ce = source[j];
2199
+ if (ce === "\\") {
2200
+ j += 2;
2201
+ continue;
2202
+ }
2203
+ if (ce === '"' || ce === "'" || ce === "`") {
2204
+ j = scanString(j);
2205
+ continue;
2206
+ }
2207
+ if (ce === "{") depth += 1;
2208
+ else if (ce === "}") depth -= 1;
2209
+ j += 1;
2210
+ }
2211
+ continue;
2212
+ }
2213
+ j += 1;
2214
+ }
2215
+ return n;
2216
+ };
2217
+ const scanRegex = (start) => {
2218
+ let j = start + 1;
2219
+ let inClass = false;
2220
+ while (j < n) {
2221
+ const cj = source[j];
2222
+ if (cj === "\\") {
2223
+ j += 2;
2224
+ continue;
2225
+ }
2226
+ if (cj === "\n") return j;
2227
+ if (cj === "[") inClass = true;
2228
+ else if (cj === "]") inClass = false;
2229
+ else if (cj === "/" && !inClass) return j + 1;
2230
+ j += 1;
2231
+ }
2232
+ return n;
2233
+ };
2234
+ const skipWsAndComments = (k) => {
2235
+ let j = k;
2236
+ while (j < n) {
2237
+ const cj = source[j];
2238
+ if (cj === " " || cj === " " || cj === "\n" || cj === "\r") {
2239
+ j += 1;
2240
+ continue;
2241
+ }
2242
+ if (cj === "/" && source[j + 1] === "/") {
2243
+ const nl = source.indexOf("\n", j);
2244
+ j = nl === -1 ? n : nl + 1;
2245
+ continue;
2246
+ }
2247
+ if (cj === "/" && source[j + 1] === "*") {
2248
+ const end = source.indexOf("*/", j + 2);
2249
+ j = end === -1 ? n : end + 2;
2250
+ continue;
2251
+ }
2252
+ return j;
2253
+ }
2254
+ return n;
2255
+ };
2256
+ const matchParen = (openIdx) => {
2257
+ let depth = 0;
2258
+ let j = openIdx;
2259
+ while (j < n) {
2260
+ const cj = source[j];
2261
+ if (cj === '"' || cj === "'" || cj === "`") {
2262
+ j = scanString(j);
2263
+ continue;
2264
+ }
2265
+ if (cj === "/" && source[j + 1] === "/") {
2266
+ const nl = source.indexOf("\n", j);
2267
+ j = nl === -1 ? n : nl + 1;
2268
+ continue;
2269
+ }
2270
+ if (cj === "/" && source[j + 1] === "*") {
2271
+ const end = source.indexOf("*/", j + 2);
2272
+ j = end === -1 ? n : end + 2;
2273
+ continue;
2274
+ }
2275
+ if (cj === "(") depth += 1;
2276
+ else if (cj === ")") {
2277
+ depth -= 1;
2278
+ if (depth === 0) return j;
2279
+ }
2280
+ j += 1;
2281
+ }
2282
+ return -1;
2283
+ };
2284
+ const splitTopLevelSemicolons = (inner) => {
2285
+ const parts = [];
2286
+ let depth = 0;
2287
+ let j = 0;
2288
+ let last = 0;
2289
+ const m = inner.length;
2290
+ while (j < m) {
2291
+ const cj = inner[j];
2292
+ if (cj === '"' || cj === "'" || cj === "`") {
2293
+ const quote = cj;
2294
+ j += 1;
2295
+ while (j < m) {
2296
+ if (inner[j] === "\\") {
2297
+ j += 2;
2298
+ continue;
2299
+ }
2300
+ if (inner[j] === quote) {
2301
+ j += 1;
2302
+ break;
2303
+ }
2304
+ j += 1;
2305
+ }
2306
+ continue;
2307
+ }
2308
+ if (cj === "(" || cj === "[" || cj === "{") depth += 1;
2309
+ else if (cj === ")" || cj === "]" || cj === "}") depth -= 1;
2310
+ else if (cj === ";" && depth === 0) {
2311
+ parts.push(inner.slice(last, j));
2312
+ last = j + 1;
2313
+ }
2314
+ j += 1;
2315
+ }
2316
+ parts.push(inner.slice(last));
2317
+ return parts;
2318
+ };
2319
+ const REGEX_PRECEDING_WORDS = /* @__PURE__ */ new Set([
2320
+ "return",
2321
+ "typeof",
2322
+ "case",
2323
+ "do",
2324
+ "else",
2325
+ "in",
2326
+ "of",
2327
+ "new",
2328
+ "delete",
2329
+ "void",
2330
+ "instanceof",
2331
+ "yield",
2332
+ "await"
2333
+ ]);
2334
+ let out = "";
2335
+ let i = 0;
2336
+ let lastSig = "";
2337
+ let lastWord = "";
2338
+ while (i < n) {
2339
+ const ch = source[i];
2340
+ if (ch === "/" && source[i + 1] === "/") {
2341
+ const nl = source.indexOf("\n", i);
2342
+ const end = nl === -1 ? n : nl;
2343
+ out += source.slice(i, end);
2344
+ i = end;
2345
+ continue;
2346
+ }
2347
+ if (ch === "/" && source[i + 1] === "*") {
2348
+ const close = source.indexOf("*/", i + 2);
2349
+ const end = close === -1 ? n : close + 2;
2350
+ out += source.slice(i, end);
2351
+ i = end;
2352
+ continue;
2353
+ }
2354
+ if (ch === '"' || ch === "'" || ch === "`") {
2355
+ const end = scanString(i);
2356
+ out += source.slice(i, end);
2357
+ lastSig = ch;
2358
+ lastWord = "";
2359
+ i = end;
2360
+ continue;
2361
+ }
2362
+ if (ch === "/") {
2363
+ const regexLikely = lastSig === "" || "(,=:;!&|?{}[+-*%~^<>".includes(lastSig) || REGEX_PRECEDING_WORDS.has(lastWord);
2364
+ if (regexLikely) {
2365
+ const end = scanRegex(i);
2366
+ out += source.slice(i, end);
2367
+ lastSig = "/";
2368
+ lastWord = "";
2369
+ i = end;
2370
+ continue;
2371
+ }
2372
+ out += ch;
2373
+ lastSig = ch;
2374
+ lastWord = "";
2375
+ i += 1;
2376
+ continue;
2377
+ }
2378
+ if (isIdChar(ch)) {
2379
+ let j = i;
2380
+ while (j < n && isIdChar(source[j])) j += 1;
2381
+ const word = source.slice(i, j);
2382
+ if ((word === "while" || word === "for") && lastSig !== ".") {
2383
+ const k = skipWsAndComments(j);
2384
+ if (source[k] === "(") {
2385
+ const close = matchParen(k);
2386
+ if (close !== -1) {
2387
+ const inner = source.slice(k + 1, close);
2388
+ if (word === "while") {
2389
+ out += `while (${guardName}() && (${inner}))`;
2390
+ lastSig = ")";
2391
+ lastWord = "";
2392
+ i = close + 1;
2393
+ continue;
2394
+ }
2395
+ const parts = splitTopLevelSemicolons(inner);
2396
+ if (parts.length === 3) {
2397
+ const cond = parts[1].trim();
2398
+ const guardedCond = cond ? `${guardName}() && (${cond})` : `${guardName}()`;
2399
+ out += `for (${parts[0]}; ${guardedCond}; ${parts[2]})`;
2400
+ lastSig = ")";
2401
+ lastWord = "";
2402
+ i = close + 1;
2403
+ continue;
2404
+ }
2405
+ out += source.slice(i, close + 1);
2406
+ lastSig = ")";
2407
+ lastWord = "";
2408
+ i = close + 1;
2409
+ continue;
2410
+ }
2411
+ }
2412
+ }
2413
+ out += word;
2414
+ lastSig = word[word.length - 1];
2415
+ lastWord = word;
2416
+ i = j;
2417
+ continue;
2418
+ }
2419
+ out += ch;
2420
+ if (ch !== " " && ch !== " " && ch !== "\n" && ch !== "\r") {
2421
+ lastSig = ch;
2422
+ lastWord = "";
2423
+ }
2424
+ i += 1;
2425
+ }
2426
+ return out;
2427
+ };
2428
+ var compileScriptCompute = (source, guard) => {
2429
+ const makeFactory = (body) => new Function(
2430
+ "__hpGuard",
2431
+ `"use strict";
2432
+ ${body}
2433
+ ;if (typeof compute !== "function") { throw new Error("Script must define function compute(bars, inputs, hp)"); }
2434
+ return compute;`
2435
+ );
2436
+ let factory;
2437
+ try {
2438
+ factory = makeFactory(injectLoopGuards(source, "__hpGuard"));
2439
+ } catch {
2440
+ factory = makeFactory(source);
2441
+ }
2442
+ guard.reset();
2443
+ return factory(guard);
2444
+ };
2445
+ var validateScriptSource = (source) => {
2446
+ try {
2447
+ compileScriptCompute(source, createScriptGuard());
2448
+ return null;
2449
+ } catch (error) {
2450
+ return error instanceof Error ? error.message : String(error);
2451
+ }
2452
+ };
2453
+ var drawScriptError = (ctx, renderContext, name, message) => {
2454
+ ctx.save();
2455
+ ctx.font = "11px -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";
2456
+ ctx.textAlign = "left";
2457
+ ctx.textBaseline = "top";
2458
+ ctx.fillStyle = "#ef5350";
2459
+ const text = `${name}: ${message}`.slice(0, 160);
2460
+ ctx.fillText(text, renderContext.chartLeft + 10, renderContext.chartTop + 24);
2461
+ ctx.restore();
2462
+ };
2463
+ var compileScriptIndicator = (definition) => {
2464
+ const pane = definition.pane ?? "separate";
2465
+ const defaultInputs = { showValueLine: true };
2466
+ for (const input of definition.inputs ?? []) {
2467
+ defaultInputs[input.key] = input.default;
2468
+ }
2469
+ let compiled = null;
2470
+ let compileError = null;
2471
+ const guard = createScriptGuard();
2472
+ try {
2473
+ compiled = compileScriptCompute(definition.source, guard);
2474
+ } catch (error) {
2475
+ compileError = error instanceof Error ? error.message : String(error);
2476
+ }
2477
+ const sourceKey = hashScriptSource(definition.source);
2478
+ let trippedError = null;
2479
+ const runCompute = (data, inputs) => {
2480
+ if (!compiled) {
2481
+ return { error: compileError ?? "Script failed to compile" };
2482
+ }
2483
+ if (trippedError) {
2484
+ return { error: trippedError };
2485
+ }
2486
+ try {
2487
+ guard.reset();
2488
+ const result = compiled(data, inputs, SCRIPT_HELPERS);
2489
+ if (!result || !Array.isArray(result.plots)) {
2490
+ return { error: "compute() must return { plots: [...] }" };
2491
+ }
2492
+ for (const plot of result.plots) {
2493
+ if (!plot || !Array.isArray(plot.values)) {
2494
+ return { error: "Every plot needs a `values` array" };
2495
+ }
2496
+ }
2497
+ return { result };
2498
+ } catch (error) {
2499
+ const message = error instanceof Error ? error.message : String(error);
2500
+ if (error instanceof ScriptBudgetError) {
2501
+ trippedError = message;
2502
+ }
2503
+ return { error: message };
2504
+ }
2505
+ };
2506
+ const cachedCompute = (data, inputs) => withCachedComputation(
2507
+ `script|${definition.id}|${sourceKey}|${JSON.stringify(inputs)}`,
2508
+ data,
2509
+ () => runCompute(data, inputs)
2510
+ );
2511
+ const plugin = {
2512
+ id: definition.id,
2513
+ name: definition.name,
2514
+ pane,
2515
+ defaultInputs,
2516
+ draw: (ctx, renderContext, inputs) => {
2517
+ const outcome = cachedCompute(renderContext.data, inputs);
2518
+ if (!outcome.result) {
2519
+ drawScriptError(ctx, renderContext, definition.name, outcome.error ?? "Unknown script error");
2520
+ return pane === "separate" ? { title: `${definition.name} (script error)` } : void 0;
2521
+ }
2522
+ const { plots, range, guides, decimals } = outcome.result;
2523
+ if (pane === "separate") {
2524
+ const seriesList = plots.map((plot, index) => ({
2525
+ values: plot.values,
2526
+ color: plot.color ?? SCRIPT_PLOT_PALETTE[index % SCRIPT_PLOT_PALETTE.length],
2527
+ ...plot.width !== void 0 ? { width: plot.width } : {},
2528
+ ...plot.title ? { label: plot.title } : {},
2529
+ ...plot.style === "histogram" ? { histogram: true } : {},
2530
+ ...plot.negativeColor ? { negativeColor: plot.negativeColor } : {}
2531
+ }));
2532
+ return drawSeparateMultiSeries(ctx, renderContext, seriesList, {
2533
+ title: definition.name,
2534
+ ...range?.min !== void 0 ? { minOverride: range.min } : {},
2535
+ ...range?.max !== void 0 ? { maxOverride: range.max } : {},
2536
+ ...guides && guides.length > 0 ? { guideLines: guides } : {},
2537
+ ...decimals !== void 0 ? { decimals } : {},
2538
+ valueLines: inputs.showValueLine !== false
2539
+ });
2540
+ }
2541
+ for (let index = 0; index < plots.length; index += 1) {
2542
+ const plot = plots[index];
2543
+ if (plot.style === "histogram") continue;
2544
+ drawOverlaySeries(
2545
+ ctx,
2546
+ renderContext,
2547
+ plot.values,
2548
+ plot.color ?? SCRIPT_PLOT_PALETTE[index % SCRIPT_PLOT_PALETTE.length],
2549
+ plot.width ?? 2
2550
+ );
2551
+ }
2552
+ return void 0;
2553
+ },
2554
+ ...pane === "overlay" ? {
2555
+ getAutoscaleRange: (data, startIndex, endIndex, inputs, skipIndex) => {
2556
+ const outcome = cachedCompute(data, inputs);
2557
+ if (!outcome.result) return null;
2558
+ const lineSeries = outcome.result.plots.filter((plot) => plot.style !== "histogram").map((plot) => plot.values);
2559
+ if (lineSeries.length === 0) return null;
2560
+ return rangeOfSeries(lineSeries, startIndex, endIndex, skipIndex);
2561
+ }
2562
+ } : {}
2563
+ };
2564
+ if (definition.paneHeightRatio !== void 0) {
2565
+ plugin.paneHeightRatio = definition.paneHeightRatio;
2566
+ }
2567
+ return plugin;
2568
+ };
2569
+
2570
+ // src/options.ts
2571
+ var DEFAULT_GRID_OPTIONS = {
2572
+ color: "#2b2f38",
2573
+ opacity: 0.38,
2574
+ horizontalLines: true,
2575
+ verticalLines: true,
2576
+ xTickCount: 8,
2577
+ yTickCount: 6,
2578
+ horizontalTickCount: 6,
2579
+ sessionSeparators: false,
2580
+ sessionSeparatorColor: "#3b4150",
2581
+ sessionSeparatorOpacity: 0.55
2582
+ };
2583
+ var DEFAULT_AXIS_OPTIONS = {
2584
+ lineColor: "#3b3f47",
2585
+ textColor: "#a9adb6",
2586
+ fontSize: 12,
2587
+ lineWidth: 1
2588
+ };
2589
+ var DEFAULT_CROSSHAIR_OPTIONS = {
2590
+ visible: true,
2591
+ color: "#94a3b8",
2592
+ width: 1,
2593
+ style: "dotted",
2594
+ mode: "cross",
2595
+ dotRadius: 3,
2596
+ showHorizontal: true,
2597
+ showVertical: true,
2598
+ showPriceLabel: true,
2599
+ showTimeLabel: true,
2600
+ timeLabelFormat: "auto",
2601
+ labelBackgroundColor: "#0b1220",
2602
+ labelTextColor: "#cbd5e1",
2603
+ labelBorderRadius: 3,
2604
+ labelBorderColor: "#94a3b8",
2605
+ labelBorderWidth: 1,
2606
+ labelBorderStyle: "solid",
2607
+ showPriceActionButton: false,
2608
+ priceActionButtonIcon: "plusThin",
2609
+ priceActionButtonText: "+",
2610
+ priceActionButtonSize: 16,
2611
+ priceActionButtonGap: 4,
2612
+ priceActionButtonRounded: true,
2613
+ priceActionButtonBorderRadius: 8,
2614
+ sideHintLeft: "",
2615
+ sideHintRight: "",
2616
+ sideHintLeftColor: "#26a69a",
2617
+ sideHintRightColor: "#ef5350"
2618
+ };
2619
+ var DEFAULT_WATERMARK_OPTIONS = {
2620
+ visible: false,
2621
+ text: "",
2622
+ color: "#81858d",
2623
+ opacity: 0.14,
2624
+ fontSize: 92,
2625
+ fontWeight: 700,
2626
+ thickness: 0,
2627
+ imageSrc: "",
2628
+ imageScale: 1,
2629
+ imageMaxWidthRatio: 0.42,
2630
+ imageMaxHeightRatio: 0.3,
2631
+ imageTintColor: "",
2632
+ imageTintOpacity: 1
2633
+ };
2634
+ var DEFAULT_DASH_PATTERNS = {
2635
+ dotted: [2, 2],
2636
+ dashed: [8, 6],
2637
+ connectorDotted: [2, 3],
2638
+ connectorDashed: [6, 5],
2639
+ borderDotted: [2, 2],
2640
+ borderDashed: [6, 4]
2641
+ };
2642
+ var DEFAULT_LABELS_OPTIONS = {
2643
+ visible: true,
2644
+ symbolName: "",
2645
+ showSymbolName: false,
2646
+ showLastPrice: true,
2647
+ showPreviousClose: false,
2648
+ previousClosePrice: Number.NaN,
2649
+ showHighLow: false,
2650
+ showBidAsk: false,
2651
+ bidPrice: Number.NaN,
2652
+ askPrice: Number.NaN,
2653
+ showIndicatorNames: false,
2654
+ showIndicatorValues: false,
2655
+ showIndicatorValueLabels: true,
2656
+ indicatorLegendPosition: "top-left",
2657
+ indicatorLegendOffsetX: 10,
2658
+ indicatorLegendOffsetY: 10,
2659
+ showCountdownToBarClose: false,
2660
+ noOverlapping: true,
2661
+ backgroundColor: "#0b1220",
2662
+ textColor: "#cbd5e1",
2663
+ mutedTextColor: "#94a3b8",
2664
+ symbolNameBackgroundColor: "#1f2937",
2665
+ symbolNameTextColor: "#e5e7eb",
2666
+ previousCloseColor: "#94a3b8",
2667
+ highLowColor: "#a78bfa",
2668
+ bidColor: "#ef4444",
2669
+ askColor: "#22c55e",
2670
+ indicatorTextColor: "#cbd5e1",
2671
+ borderRadius: 3,
2672
+ labelHeight: 20,
2673
+ labelPaddingX: 8
2674
+ };
2675
+ var DEFAULT_PRICE_LINE_OPTIONS = {
2676
+ visible: true,
2677
+ style: "solid",
2678
+ thickness: 1,
2679
+ color: "#38bdf8",
2680
+ labelBackgroundColor: "#0b1220",
2681
+ labelTextColor: "#60a5fa",
2682
+ labelBorderRadius: 3,
2683
+ showLabel: true,
2684
+ pinOutOfRange: false
2685
+ };
2686
+ var DEFAULT_ORDER_LINE_OPTIONS = {
2687
+ visible: true,
2688
+ behavior: "static",
2689
+ style: "solid",
2690
+ thickness: 1,
2691
+ color: "rgba(59,130,246,0.8)",
2692
+ labelBackgroundColor: "#0b1220",
2693
+ labelTextColor: "#60a5fa",
2694
+ labelBorderRadius: 3,
2695
+ showCloseButton: true,
2696
+ widgetPosition: "left",
2697
+ widgetPaddingRight: 10,
2698
+ draggable: false,
2699
+ actionButtonAction: "execute",
2700
+ actionButtonTextColor: "#dbeafe",
2701
+ actionButtonBackgroundColor: "#2563eb",
2702
+ actionButtonBorderRadius: 2,
2703
+ actionButtonMinWidth: 34,
2704
+ actionButtonPaddingX: 0,
2705
+ actionButtonFullHeight: true,
2706
+ actionButtonFontWeight: 500,
2707
+ actionButtonBorderColor: "#2563eb",
2708
+ actionButtonBorderStyle: "solid",
2709
+ actionButtonsInnerGap: 6,
2710
+ actionButtonsGroupGap: 8,
2711
+ actionButtons: [],
2712
+ connectorToPrice: Number.NaN,
2713
+ connectorColor: "#2563eb",
2714
+ connectorStyle: "dotted",
2715
+ connectorThickness: 1,
2716
+ connectorAnchorPaddingRight: 10,
2717
+ fillToPrice: Number.NaN,
2718
+ fillColor: "rgba(37,99,235,0.18)",
2719
+ pinOutOfRange: false
2720
+ };
2721
+ var DEFAULT_OPTIONS = {
2722
+ width: 720,
2723
+ height: 360,
2724
+ backgroundColor: "#101114",
2725
+ axisColor: "#7f8289",
2726
+ axis: DEFAULT_AXIS_OPTIONS,
2727
+ xAxis: DEFAULT_AXIS_OPTIONS,
2728
+ yAxis: DEFAULT_AXIS_OPTIONS,
2729
+ priceDecimals: 2,
2730
+ stabilizePriceLabels: true,
2731
+ priceLabelMinIntegerDigits: 3,
2732
+ priceLabelWidthTemplate: "",
2733
+ initialViewport: "latest",
2734
+ initialVisibleBars: 60,
2735
+ minVisibleBars: 5,
2736
+ maxVisibleBars: 2e4,
2737
+ maxPanBars: 1e6,
2738
+ rightEdgePaddingBars: 2,
2739
+ preserveViewportOnDataUpdate: true,
2740
+ upColor: "#2fb171",
2741
+ downColor: "#d35a5a",
2742
+ gridColor: "#252932",
2743
+ fontFamily: "Inter, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",
2744
+ candleBodyWidthRatio: 0.7,
2745
+ candleMinWidth: 0.5,
2746
+ candleWickWidth: 1,
2747
+ tickSize: 0,
2748
+ candleColorMode: "openClose",
2749
+ candleColorEpsilon: -1,
2750
+ chartType: "candles",
2751
+ lineColor: "#2962ff",
2752
+ lineWidth: 2,
2753
+ areaFillOpacity: 0.12,
2754
+ baselinePrice: null,
2755
+ // 0 = deterministic scale (lightweight-charts behavior): the y-range is a
2756
+ // pure function of the visible data, so it can never drift or "breathe".
2757
+ // Values > 0 re-enable eased contraction for hosts that prefer it.
2758
+ autoScaleSmoothing: 0,
2759
+ autoScaleIgnoreLatestCandle: true,
2760
+ kineticScroll: { touch: true, mouse: false },
2761
+ timeStepMs: 0,
2762
+ clockOffsetMs: 0,
2763
+ pinOutOfRangeLines: false,
2764
+ doubleClickEnabled: true,
2765
+ doubleClickAction: "reset",
2766
+ crosshair: DEFAULT_CROSSHAIR_OPTIONS,
2767
+ grid: DEFAULT_GRID_OPTIONS,
2768
+ watermark: DEFAULT_WATERMARK_OPTIONS,
2769
+ priceLines: [],
2770
+ orderLines: [],
2771
+ tickerLine: {
2772
+ visible: true,
2773
+ style: "dotted",
2774
+ thickness: 1,
2775
+ labelTextColor: "#0b1220",
2776
+ labelSubtext: "",
2777
+ labelSubtexts: [],
2778
+ labelSubtextColor: "#0b1220",
2779
+ labelSubtextFontSize: 0,
2780
+ showCountdownInLabel: false,
2781
+ labelBorderRadius: 3
2782
+ },
2783
+ labels: DEFAULT_LABELS_OPTIONS,
2784
+ dashPatterns: DEFAULT_DASH_PATTERNS,
2785
+ indicators: [],
2786
+ drawings: []
2787
+ };
2788
+ var mergeChartOptions = (baseOptions, options = {}) => ({
2789
+ ...baseOptions,
2790
+ ...options,
2791
+ axis: {
2792
+ ...baseOptions.axis,
2793
+ ...options.axis ?? {},
2794
+ ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {}
2795
+ },
2796
+ xAxis: {
2797
+ ...baseOptions.xAxis,
2798
+ ...options.axis ?? {},
2799
+ ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {},
2800
+ ...options.xAxis ?? {}
2801
+ },
2802
+ yAxis: {
2803
+ ...baseOptions.yAxis,
2804
+ ...options.axis ?? {},
2805
+ ...options.axisColor ? { lineColor: options.axisColor, textColor: options.axisColor } : {},
2806
+ ...options.yAxis ?? {}
2807
+ },
2808
+ crosshair: {
2809
+ ...baseOptions.crosshair,
2810
+ ...options.crosshair ?? {}
2811
+ },
2812
+ grid: {
2813
+ ...baseOptions.grid,
2814
+ ...options.grid ?? {}
2815
+ },
2816
+ watermark: {
2817
+ ...baseOptions.watermark,
2818
+ ...options.watermark ?? {}
2819
+ },
2820
+ tickerLine: {
2821
+ ...baseOptions.tickerLine,
2822
+ ...options.tickerLine ?? {}
2823
+ },
2824
+ labels: {
2825
+ ...baseOptions.labels,
2826
+ ...options.labels ?? {}
2827
+ },
2828
+ dashPatterns: {
2829
+ ...baseOptions.dashPatterns,
2830
+ ...options.dashPatterns ?? {}
2831
+ }
2832
+ });
2833
+
2834
+ // src/chart.ts
2515
2835
  function createChart(element, options = {}) {
2516
2836
  let mergedOptions = mergeChartOptions(DEFAULT_OPTIONS, options);
2517
2837
  let resolvedAxis = { ...DEFAULT_AXIS_OPTIONS, ...mergedOptions.axis ?? {} };
@@ -8068,5 +8388,6 @@ function createChart(element, options = {}) {
8068
8388
  FIB_DEFAULT_PALETTE,
8069
8389
  POSITION_DEFAULT_COLORS,
8070
8390
  compileScriptIndicator,
8071
- createChart
8391
+ createChart,
8392
+ validateScriptSource
8072
8393
  });