@tradecanvas/script 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1522 +1,1726 @@
1
- import { timeframeToMs as _t, fadeBy as Wt } from "@tradecanvas/commons";
2
- import { periodKeyer as Kt, IndicatorBase as ft, IndicatorValueMap as pt } from "@tradecanvas/core";
3
- function zt(n) {
4
- if (typeof n.id != "string" || n.id.trim() === "") throw new Error("defineScript: a script needs an id");
5
- if (typeof n.setup != "function") throw new Error(`defineScript('${n.id}'): a script needs a setup function`);
6
- return Object.freeze({ ...n, kind: "script" });
7
- }
8
- function Dt(n, t) {
9
- const e = t.default;
10
- if (typeof e == "number") {
11
- const s = typeof n == "string" && n.trim() !== "" ? Number(n) : n;
12
- if (typeof s != "number" || !Number.isFinite(s)) return e;
13
- const r = t.kind === "int" ? Math.floor(s) : s;
14
- return Math.min(t.max ?? 1 / 0, Math.max(t.min ?? -1 / 0, r));
15
- }
16
- return typeof n != typeof e || t.options && !t.options.some((s) => (typeof s == "object" ? s.value : s) === n) ? e : n;
17
- }
18
- const Pt = 256;
19
- class Y {
20
- constructor(t, e) {
21
- this.make = t, this.empty = e, this.data = t(Pt), this.data.fill(e);
22
- }
23
- data;
24
- filled = 0;
25
- /** Set bar `index`, growing to it. */
26
- set(t, e) {
27
- this.reach(t + 1), this.data[t] = e;
28
- }
29
- get(t) {
30
- return t >= 0 && t < this.filled ? this.data[t] : this.empty;
31
- }
32
- /** Make room for `length` bars, the new ones empty. */
33
- reach(t) {
34
- if (t > this.data.length) {
35
- let e = this.data.length;
36
- for (; e < t; ) e *= 2;
37
- const s = this.make(e);
38
- s.fill(this.empty), s.set(this.data), this.data = s;
39
- }
40
- t > this.filled && (this.filled = t);
41
- }
42
- /** Its first `length` bars, without copying them: good until a bar is set past what it holds. */
43
- view(t) {
44
- return this.reach(t), this.data.subarray(0, t);
45
- }
46
- }
47
- const J = () => new Y((n) => new Float64Array(n), Number.NaN), B = () => new Y((n) => new Uint16Array(n), 0), rt = () => new Y((n) => new Uint8Array(n), 0), nt = 65535;
48
- class Ut {
49
- constructor(t) {
50
- this.scope = t, t.clearers.push((e) => {
51
- for (const s of this.plots)
52
- s.values.set(e, Number.NaN), s.colors.set(e, 0);
53
- for (const s of this.shapes) s.on.set(e, 0);
54
- for (const s of this.fills) s.colors.set(e, 0);
55
- for (const s of this.backgrounds) s.colors.set(e, 0);
56
- for (const s of this.conditions) s.on.set(e, 0);
57
- for (const s of this.barColorSlots) s.set(e, 0);
58
- });
59
- }
60
- plots = [];
61
- handles = /* @__PURE__ */ new Map();
62
- shapes = [];
63
- fills = [];
64
- backgrounds = [];
65
- conditions = [];
66
- barColorSlots = [];
67
- levels = [];
68
- drawingLists = [];
69
- palette = [];
70
- paletteIndex = /* @__PURE__ */ new Map();
71
- open = !0;
72
- /** No more plots, marks or levels: the setup is over. */
73
- close() {
74
- this.open = !1;
75
- }
76
- declaring(t) {
77
- if (!this.open) throw new Error(`${t} is declared in the script's setup, not on a bar`);
78
- }
79
- /** A colour's place in the palette plus one. */
80
- colorIndex(t) {
81
- let e = this.paletteIndex.get(t);
82
- if (e === void 0) {
83
- if (this.palette.length >= nt) throw new Error(`a script gives its bars at most ${nt} colours`);
84
- this.palette.push(t), e = this.palette.length, this.paletteIndex.set(t, e);
85
- }
86
- return e;
87
- }
88
- plot(t, e = {}) {
89
- this.declaring("plot");
90
- const s = {
91
- declaration: { title: t, kind: e.kind ?? "line", ...e.color ? { color: e.color } : {}, ...e.width ? { width: e.width } : {} },
92
- values: J(),
93
- colors: B()
94
- };
95
- this.plots.push(s);
96
- const r = {
97
- set: (i, o) => (s.values.set(this.scope.bar, Number.isFinite(i) ? i : Number.NaN), o !== void 0 && s.colors.set(this.scope.bar, this.colorIndex(o)), i)
98
- };
99
- return this.handles.set(r, this.plots.length - 1), r;
100
- }
101
- shape(t, e = {}) {
102
- this.declaring("shape");
103
- const s = {
104
- declaration: { title: t, shape: e.shape ?? "triangleUp", position: e.position ?? "belowBar", ...e.color ? { color: e.color } : {} },
105
- on: rt()
106
- };
107
- return this.shapes.push(s), {
108
- set: (r) => (s.on.set(this.scope.bar, r ? 1 : 0), r)
109
- };
110
- }
111
- fill(t, e, s = {}) {
112
- this.declaring("fill");
113
- const r = this.handles.get(t), i = this.handles.get(e);
114
- if (r === void 0 || i === void 0) throw new Error("fill is between two plots of the same script");
115
- const o = {
116
- declaration: { between: [r, i], ...s.color ? { color: s.color } : {} },
117
- colors: B()
118
- };
119
- return this.fills.push(o), {
120
- set: (u) => {
121
- o.colors.set(this.scope.bar, u === void 0 ? 0 : this.colorIndex(u));
122
- }
123
- };
124
- }
125
- bgcolor(t = {}) {
126
- this.declaring("bgcolor");
127
- const e = { declaration: { title: t.title ?? "Background" }, colors: B() };
128
- return this.backgrounds.push(e), {
129
- set: (s) => {
130
- e.colors.set(this.scope.bar, s === void 0 ? 0 : this.colorIndex(s));
131
- }
132
- };
133
- }
134
- /** Shapes the script draws, listed with its output. */
135
- addDrawings(t) {
136
- return this.drawingLists.push(t), t;
137
- }
138
- barcolor() {
139
- this.declaring("barcolor");
140
- const t = B();
141
- return this.barColorSlots.push(t), {
142
- set: (e) => {
143
- t.set(this.scope.bar, e === void 0 ? 0 : this.colorIndex(e));
144
- }
145
- };
146
- }
147
- alertCondition(t, e = {}) {
148
- this.declaring("alertCondition");
149
- const s = { declaration: { title: t, ...e.message ? { message: e.message } : {} }, on: rt() };
150
- return this.conditions.push(s), {
151
- set: (r) => (s.on.set(this.scope.bar, r ? 1 : 0), r)
152
- };
153
- }
154
- hline(t, e = {}) {
155
- this.declaring("hline"), this.levels.push({ price: t, ...e });
156
- }
157
- declarations(t) {
158
- return {
159
- overlay: t,
160
- plots: this.plots.map((e) => e.declaration),
161
- shapes: this.shapes.map((e) => e.declaration),
162
- levels: [...this.levels],
163
- fills: this.fills.map((e) => e.declaration),
164
- backgrounds: this.backgrounds.map((e) => e.declaration),
165
- barColors: this.barColorSlots.length,
166
- alertConditions: this.conditions.map((e) => e.declaration)
167
- };
168
- }
169
- output(t, e) {
170
- return {
171
- length: t,
172
- plots: this.plots.map((s) => ({ ...s.declaration, values: s.values.view(t), colors: s.colors.view(t) })),
173
- shapes: this.shapes.map((s) => ({ ...s.declaration, on: s.on.view(t) })),
174
- levels: [...this.levels],
175
- fills: this.fills.map((s) => ({ ...s.declaration, colors: s.colors.view(t) })),
176
- backgrounds: this.backgrounds.map((s) => ({ ...s.declaration, colors: s.colors.view(t) })),
177
- barColors: this.barColorSlots.map((s) => s.view(t)),
178
- alertConditions: this.conditions.map((s) => ({ ...s.declaration, on: s.on.view(t) })),
179
- palette: [...this.palette],
180
- drawings: this.drawingLists.flatMap((s) => s.list()),
181
- errors: [...e]
182
- };
183
- }
184
- }
185
- let F = null;
186
- function Zt(n, t) {
187
- const e = F;
188
- F = n;
189
- try {
190
- return t();
191
- } finally {
192
- F = e;
193
- }
194
- }
195
- function O(n = "ta and state") {
196
- if (!F) throw new Error(`${n} are made in a script's setup, not on a bar: each keeps the state of one script`);
197
- return F;
198
- }
199
- function b(n) {
200
- const t = { ...n }, e = { ...n };
201
- return O().units.push({
202
- commit: () => Object.assign(e, t),
203
- rollback: () => Object.assign(t, e)
204
- }), t;
205
- }
206
- const it = {
207
- loopSteps: 1e6,
208
- arraySize: 1e5,
209
- runMs: Number.POSITIVE_INFINITY
1
+ import { fadeBy as e, timeframeToMs as t } from "@tradecanvas/commons";
2
+ import { IndicatorBase as n, IndicatorValueMap as r, periodKeyer as i } from "@tradecanvas/core";
3
+ //#region src/defineScript.ts
4
+ function a(e) {
5
+ if (typeof e.id != "string" || e.id.trim() === "") throw Error("defineScript: a script needs an id");
6
+ if (typeof e.setup != "function") throw Error(`defineScript('${e.id}'): a script needs a setup function`);
7
+ return Object.freeze({
8
+ ...e,
9
+ kind: "script"
10
+ });
11
+ }
12
+ function o(e, t) {
13
+ let n = t.default;
14
+ if (typeof n == "number") {
15
+ let r = typeof e == "string" && e.trim() !== "" ? Number(e) : e;
16
+ if (typeof r != "number" || !Number.isFinite(r)) return n;
17
+ let i = t.kind === "int" ? Math.floor(r) : r;
18
+ return Math.min(t.max ?? Infinity, Math.max(t.min ?? -Infinity, i));
19
+ }
20
+ return typeof e != typeof n || t.options && !t.options.some((t) => (typeof t == "object" ? t.value : t) === e) ? n : e;
21
+ }
22
+ //#endregion
23
+ //#region src/Column.ts
24
+ var s = 256, c = class {
25
+ data;
26
+ filled = 0;
27
+ constructor(e, t) {
28
+ this.make = e, this.empty = t, this.data = e(s), this.data.fill(t);
29
+ }
30
+ set(e, t) {
31
+ this.reach(e + 1), this.data[e] = t;
32
+ }
33
+ get(e) {
34
+ return e >= 0 && e < this.filled ? this.data[e] : this.empty;
35
+ }
36
+ reach(e) {
37
+ if (e > this.data.length) {
38
+ let t = this.data.length;
39
+ for (; t < e;) t *= 2;
40
+ let n = this.make(t);
41
+ n.fill(this.empty), n.set(this.data), this.data = n;
42
+ }
43
+ e > this.filled && (this.filled = e);
44
+ }
45
+ view(e) {
46
+ return this.reach(e), this.data.subarray(0, e);
47
+ }
48
+ }, l = () => new c((e) => new Float64Array(e), NaN), u = () => new c((e) => new Uint16Array(e), 0), d = () => new c((e) => new Uint8Array(e), 0), f = 65535, p = class {
49
+ plots = [];
50
+ handles = /* @__PURE__ */ new Map();
51
+ shapes = [];
52
+ fills = [];
53
+ backgrounds = [];
54
+ conditions = [];
55
+ barColorSlots = [];
56
+ levels = [];
57
+ drawingLists = [];
58
+ palette = [];
59
+ paletteIndex = /* @__PURE__ */ new Map();
60
+ open = !0;
61
+ constructor(e) {
62
+ this.scope = e, e.clearers.push((e) => {
63
+ for (let t of this.plots) t.values.set(e, NaN), t.colors.set(e, 0);
64
+ for (let t of this.shapes) t.on.set(e, 0);
65
+ for (let t of this.fills) t.colors.set(e, 0);
66
+ for (let t of this.backgrounds) t.colors.set(e, 0);
67
+ for (let t of this.conditions) t.on.set(e, 0);
68
+ for (let t of this.barColorSlots) t.set(e, 0);
69
+ });
70
+ }
71
+ close() {
72
+ this.open = !1;
73
+ }
74
+ declaring(e) {
75
+ if (!this.open) throw Error(`${e} is declared in the script's setup, not on a bar`);
76
+ }
77
+ colorIndex(e) {
78
+ let t = this.paletteIndex.get(e);
79
+ if (t === void 0) {
80
+ if (this.palette.length >= f) throw Error(`a script gives its bars at most ${f} colours`);
81
+ this.palette.push(e), t = this.palette.length, this.paletteIndex.set(e, t);
82
+ }
83
+ return t;
84
+ }
85
+ plot(e, t = {}) {
86
+ this.declaring("plot");
87
+ let n = {
88
+ declaration: {
89
+ title: e,
90
+ kind: t.kind ?? "line",
91
+ ...t.color ? { color: t.color } : {},
92
+ ...t.width ? { width: t.width } : {}
93
+ },
94
+ values: l(),
95
+ colors: u()
96
+ };
97
+ this.plots.push(n);
98
+ let r = { set: (e, t) => (n.values.set(this.scope.bar, Number.isFinite(e) ? e : NaN), t !== void 0 && n.colors.set(this.scope.bar, this.colorIndex(t)), e) };
99
+ return this.handles.set(r, this.plots.length - 1), r;
100
+ }
101
+ shape(e, t = {}) {
102
+ this.declaring("shape");
103
+ let n = {
104
+ declaration: {
105
+ title: e,
106
+ shape: t.shape ?? "triangleUp",
107
+ position: t.position ?? "belowBar",
108
+ ...t.color ? { color: t.color } : {}
109
+ },
110
+ on: d()
111
+ };
112
+ return this.shapes.push(n), { set: (e) => (n.on.set(this.scope.bar, +!!e), e) };
113
+ }
114
+ fill(e, t, n = {}) {
115
+ this.declaring("fill");
116
+ let r = this.handles.get(e), i = this.handles.get(t);
117
+ if (r === void 0 || i === void 0) throw Error("fill is between two plots of the same script");
118
+ let a = {
119
+ declaration: {
120
+ between: [r, i],
121
+ ...n.color ? { color: n.color } : {}
122
+ },
123
+ colors: u()
124
+ };
125
+ return this.fills.push(a), { set: (e) => {
126
+ a.colors.set(this.scope.bar, e === void 0 ? 0 : this.colorIndex(e));
127
+ } };
128
+ }
129
+ bgcolor(e = {}) {
130
+ this.declaring("bgcolor");
131
+ let t = {
132
+ declaration: { title: e.title ?? "Background" },
133
+ colors: u()
134
+ };
135
+ return this.backgrounds.push(t), { set: (e) => {
136
+ t.colors.set(this.scope.bar, e === void 0 ? 0 : this.colorIndex(e));
137
+ } };
138
+ }
139
+ addDrawings(e) {
140
+ return this.drawingLists.push(e), e;
141
+ }
142
+ barcolor() {
143
+ this.declaring("barcolor");
144
+ let e = u();
145
+ return this.barColorSlots.push(e), { set: (t) => {
146
+ e.set(this.scope.bar, t === void 0 ? 0 : this.colorIndex(t));
147
+ } };
148
+ }
149
+ alertCondition(e, t = {}) {
150
+ this.declaring("alertCondition");
151
+ let n = {
152
+ declaration: {
153
+ title: e,
154
+ ...t.message ? { message: t.message } : {}
155
+ },
156
+ on: d()
157
+ };
158
+ return this.conditions.push(n), { set: (e) => (n.on.set(this.scope.bar, +!!e), e) };
159
+ }
160
+ hline(e, t = {}) {
161
+ this.declaring("hline"), this.levels.push({
162
+ price: e,
163
+ ...t
164
+ });
165
+ }
166
+ declarations(e) {
167
+ return {
168
+ overlay: e,
169
+ plots: this.plots.map((e) => e.declaration),
170
+ shapes: this.shapes.map((e) => e.declaration),
171
+ levels: [...this.levels],
172
+ fills: this.fills.map((e) => e.declaration),
173
+ backgrounds: this.backgrounds.map((e) => e.declaration),
174
+ barColors: this.barColorSlots.length,
175
+ alertConditions: this.conditions.map((e) => e.declaration)
176
+ };
177
+ }
178
+ output(e, t) {
179
+ return {
180
+ length: e,
181
+ plots: this.plots.map((t) => ({
182
+ ...t.declaration,
183
+ values: t.values.view(e),
184
+ colors: t.colors.view(e)
185
+ })),
186
+ shapes: this.shapes.map((t) => ({
187
+ ...t.declaration,
188
+ on: t.on.view(e)
189
+ })),
190
+ levels: [...this.levels],
191
+ fills: this.fills.map((t) => ({
192
+ ...t.declaration,
193
+ colors: t.colors.view(e)
194
+ })),
195
+ backgrounds: this.backgrounds.map((t) => ({
196
+ ...t.declaration,
197
+ colors: t.colors.view(e)
198
+ })),
199
+ barColors: this.barColorSlots.map((t) => t.view(e)),
200
+ alertConditions: this.conditions.map((t) => ({
201
+ ...t.declaration,
202
+ on: t.on.view(e)
203
+ })),
204
+ palette: [...this.palette],
205
+ drawings: this.drawingLists.flatMap((e) => e.list()),
206
+ errors: [...t]
207
+ };
208
+ }
209
+ }, m = null;
210
+ function h(e, t) {
211
+ let n = m;
212
+ m = e;
213
+ try {
214
+ return t();
215
+ } finally {
216
+ m = n;
217
+ }
218
+ }
219
+ function g(e = "ta and state") {
220
+ if (!m) throw Error(`${e} are made in a script's setup, not on a bar: each keeps the state of one script`);
221
+ return m;
222
+ }
223
+ function _(e) {
224
+ let t = { ...e }, n = { ...e };
225
+ return g().units.push({
226
+ commit: () => Object.assign(n, t),
227
+ rollback: () => Object.assign(t, n)
228
+ }), t;
229
+ }
230
+ //#endregion
231
+ //#region src/limits.ts
232
+ var v = {
233
+ loopSteps: 1e6,
234
+ arraySize: 1e5,
235
+ runMs: Infinity
236
+ }, y = class extends Error {
237
+ constructor(e, t) {
238
+ super(t), this.limit = e, this.name = "ScriptLimitError";
239
+ }
210
240
  };
211
- class W extends Error {
212
- constructor(t, e) {
213
- super(e), this.limit = t, this.name = "ScriptLimitError";
214
- }
215
- }
216
- function Q(n = {}) {
217
- const t = Object.fromEntries(Object.entries(n).filter(([, s]) => s !== void 0)), e = { ...it, ...t };
218
- for (const s of Object.keys(it)) {
219
- const r = e[s];
220
- if (typeof r != "number" || Number.isNaN(r) || r <= 0)
221
- throw new RangeError(`script limits: ${s} must be a positive number, not ${String(r)}`);
222
- }
223
- return e;
224
- }
225
- function Nt(n, t, e) {
226
- const s = new W(t, e);
227
- throw n.breach ??= s, s;
228
- }
229
- function Vt(n) {
230
- const t = O("state.var"), e = { value: n };
231
- let s = n;
232
- return t.units.push({
233
- commit: () => {
234
- s = e.value;
235
- },
236
- rollback: () => {
237
- e.value = s;
238
- }
239
- }), e;
240
- }
241
- function Xt() {
242
- const n = O("state.series"), t = J();
243
- return n.clearers.push((e) => t.set(e, Number.NaN)), {
244
- set: (e) => (t.set(n.bar, e), e),
245
- // Never a bar ahead: a bar reads only itself and the bars before it.
246
- at: (e = 0) => e >= 0 ? t.get(n.bar - Math.floor(e)) : Number.NaN
247
- };
248
- }
249
- class Gt {
250
- constructor(t) {
251
- this.scope = t, t.units.push({
252
- commit: () => {
253
- this.undo = [];
254
- },
255
- rollback: () => {
256
- for (let e = this.undo.length - 1; e >= 0; e--) this.undo[e]();
257
- this.undo = [];
258
- }
259
- });
260
- }
261
- items = [];
262
- undo = [];
263
- record(t) {
264
- this.scope.live && this.undo.push(t);
265
- }
266
- /** Room for one more number, or the bar stops. */
267
- grow() {
268
- const t = this.scope.limits.arraySize;
269
- this.items.length >= t && Nt(this.scope, "array", `a list holds at most ${t} numbers`);
270
- }
271
- size() {
272
- return this.items.length;
273
- }
274
- /** The value at `index` (negative: from the end); NaN outside the list. */
275
- get(t) {
276
- const e = t < 0 ? this.items.length + t : t;
277
- return e >= 0 && e < this.items.length ? this.items[e] : Number.NaN;
278
- }
279
- set(t, e) {
280
- if (t < 0 || t >= this.items.length) throw new RangeError(`array.set: index ${t} is outside a list of ${this.items.length}`);
281
- const s = this.items[t];
282
- this.items[t] = e, this.record(() => {
283
- this.items[t] = s;
284
- });
285
- }
286
- push(t) {
287
- this.grow(), this.items.push(t), this.record(() => {
288
- this.items.pop();
289
- });
290
- }
291
- pop() {
292
- if (this.items.length === 0) return Number.NaN;
293
- const t = this.items.pop();
294
- return this.record(() => {
295
- this.items.push(t);
296
- }), t;
297
- }
298
- shift() {
299
- if (this.items.length === 0) return Number.NaN;
300
- const t = this.items.shift();
301
- return this.record(() => {
302
- this.items.unshift(t);
303
- }), t;
304
- }
305
- unshift(t) {
306
- this.grow(), this.items.unshift(t), this.record(() => {
307
- this.items.shift();
308
- });
309
- }
310
- clear() {
311
- const t = this.items;
312
- this.items = [], this.record(() => {
313
- this.items = t;
314
- });
315
- }
316
- /** A copy of the values. */
317
- toArray() {
318
- return [...this.items];
319
- }
320
- sum() {
321
- let t = 0;
322
- for (const e of this.items) t += e;
323
- return t;
324
- }
325
- avg() {
326
- return this.items.length > 0 ? this.sum() / this.items.length : Number.NaN;
327
- }
328
- min() {
329
- return this.items.reduce((t, e) => e < t ? e : t, this.items.length > 0 ? 1 / 0 : Number.NaN);
330
- }
331
- max() {
332
- return this.items.reduce((t, e) => e > t ? e : t, this.items.length > 0 ? -1 / 0 : Number.NaN);
333
- }
334
- /** The middle value, or the mean of the two middle ones. */
335
- median() {
336
- const t = this.items.length;
337
- if (t === 0) return Number.NaN;
338
- const e = [...this.items].sort((r, i) => r - i), s = t >> 1;
339
- return t % 2 === 1 ? e[s] : (e[s - 1] + e[s]) / 2;
340
- }
341
- }
342
- function Ht() {
343
- return new Gt(O("state.array"));
344
- }
345
- const Yt = 50, Jt = 500, U = (n) => n === void 0 || Number.isNaN(n) ? Yt : Math.min(Jt, Math.max(1, Math.floor(n))), Qt = (n) => !!n && typeof n.bar == "number" && typeof n.value == "number", qt = { label: ["at"], line: ["from", "to"], box: ["from", "to"] };
346
- function ot(n) {
347
- for (const t of qt[n.kind])
348
- if (!Qt(n[t])) throw new Error(`a ${n.kind} needs ${t}: { bar, value }`);
349
- return n;
350
- }
351
- const te = (n) => ({ bar: n.bar, value: n.value });
352
- function ut(n) {
353
- const t = { ...n };
354
- for (const e of ["at", "from", "to"]) {
355
- const s = t[e];
356
- s && (t[e] = te(s));
357
- }
358
- return t;
359
- }
360
- class ee {
361
- constructor(t, e = {}) {
362
- this.scope = t, this.limits = { label: U(e.maxLabels), line: U(e.maxLines), box: U(e.maxBoxes) }, t.units.push({
363
- commit: () => {
364
- this.undo = [];
365
- },
366
- rollback: () => {
367
- for (let s = this.undo.length - 1; s >= 0; s--) this.undo[s]();
368
- this.undo = [];
369
- }
370
- });
371
- }
372
- /** By id: an id is the order made in. */
373
- items = /* @__PURE__ */ new Map();
374
- order = { label: [], line: [], box: [] };
375
- limits;
376
- nextId = 0;
377
- undo = [];
378
- label(t) {
379
- return this.add({ kind: "label", ...t });
380
- }
381
- line(t) {
382
- return this.add({ kind: "line", ...t });
383
- }
384
- box(t) {
385
- return this.add({ kind: "box", ...t });
386
- }
387
- /** The shapes kept, in the order made. */
388
- list() {
389
- return [...this.items.keys()].sort((t, e) => t - e).map((t) => this.items.get(t));
390
- }
391
- record(t) {
392
- this.scope.live && this.undo.push(t);
393
- }
394
- add(t) {
395
- ot(t);
396
- const e = this.nextId++;
397
- this.record(() => {
398
- this.nextId = e;
399
- }), this.items.set(e, ut(t)), this.record(() => {
400
- this.items.delete(e);
401
- });
402
- const s = this.order[t.kind];
403
- for (s.push(e), this.record(() => {
404
- s.pop();
405
- }); s.length > this.limits[t.kind]; ) {
406
- const r = s.shift(), i = this.items.get(r);
407
- this.items.delete(r), this.record(() => {
408
- this.items.set(r, i), s.unshift(r);
409
- });
410
- }
411
- return {
412
- set: (r) => this.change(e, r),
413
- remove: () => this.remove(e)
414
- };
415
- }
416
- change(t, e) {
417
- const s = this.items.get(t);
418
- s && (this.items.set(t, ut(ot({ ...s, ...e, kind: s.kind }))), this.record(() => {
419
- this.items.set(t, s);
420
- }));
421
- }
422
- remove(t) {
423
- const e = this.items.get(t);
424
- if (!e) return;
425
- this.items.delete(t);
426
- const s = this.order[e.kind], r = s.indexOf(t);
427
- r >= 0 && s.splice(r, 1), this.record(() => {
428
- this.items.set(t, e), r >= 0 && s.splice(r, 0, t);
429
- });
430
- }
431
- }
432
- const se = 1e11, Z = (n, t) => n ? { open: n.open, high: Math.max(n.high, t.high), low: Math.min(n.low, t.low), close: t.close, volume: n.volume + t.volume } : { open: t.open, high: t.high, low: t.low, close: t.close, volume: t.volume }, re = (n, t) => !!n && n.open === t.open && n.high === t.high && n.low === t.low && n.close === t.close && n.volume === t.volume;
433
- function ne(n) {
434
- let t = 1 / 0;
435
- for (let e = 1; e < n.length; e++) t = Math.min(t, n[e].time - n[e - 1].time);
436
- return !Number.isFinite(t) || t <= 0 ? Number.NaN : n[n.length - 1].time < se ? t * 1e3 : t;
437
- }
438
- function ie(n, t, e, s = {}) {
439
- const r = typeof t == "string" ? _t(t) : Number.NaN;
440
- if (!Number.isFinite(r))
441
- throw new Error(`request.security: '${String(t)}' is no interval it can read: a count and a unit, as '15m', '1h', '4h', '1d', '1w', '1M' (case matters)`);
442
- const i = [];
443
- let o = !1;
444
- const u = new D(zt({
445
- id: `security:${t}`,
446
- name: t,
447
- setup(d) {
448
- const y = e({ prices: d.prices, state: d.state });
449
- return (k) => {
450
- i[k.index] = y(k.live === o ? k : { ...k, live: o });
451
- };
452
- }
453
- }), {}, n.limits ? { limits: { loopSteps: n.limits.loopSteps, arraySize: n.limits.arraySize } } : {});
454
- let c = null, a = -1, l = Number.NaN, m = Number.NaN, v = null, N = null, x = 0;
455
- const S = (d, y, k) => {
456
- const I = { time: y, ...d };
457
- u.length === 0 ? u.load([I]) : k && u.length === x ? u.next(I) : u.tick(I);
458
- const w = u.errors[0];
459
- if (!w) return;
460
- const E = `request.security('${t}'), on its bar ${w.bar}: ${w.message}`;
461
- if (!w.limit) throw new Error(E);
462
- const T = new W(w.limit, E);
463
- throw n.onLimit?.(T), T;
464
- }, Rt = () => {
465
- if (c) return c;
466
- const d = n.timeline(), y = ne(d);
467
- if (Number.isFinite(y) && r < y)
468
- throw new Error(`request.security('${t}') reads a higher interval than the chart's bars: they are ${y / 6e4} minutes apart`);
469
- return c = Kt(d, t, n.exchangeTimeZone, n.sessionStart), c;
470
- };
471
- return (d) => {
472
- const y = Rt();
473
- if (o = d.live, d.index === a) {
474
- if (y(d.time) !== l) throw new Error(`request.security('${t}'): the live bar's time moved to another period; load the bars again`);
475
- const w = Z(v, d);
476
- S(w, m, !1), N = w;
477
- } else if (d.index === a + 1) {
478
- if (a >= 0) {
479
- const P = Z(v, n.barAt(a));
480
- o = !1, re(N, P) || S(P, m, !1), o = d.live, N = P;
481
- }
482
- const w = y(d.time), E = w !== l || N === null, T = E ? null : N, et = Z(T, d), st = E ? d.time : m;
483
- S(et, st, E), l = w, m = st, v = T, N = et, a = d.index, x = u.length;
484
- } else
485
- throw new Error(`request.security('${t}') is called on every bar: it was not on bar ${a + 1}`);
486
- const k = u.length - 1, I = s.live ? i[k] : i[k - 1];
487
- return I === void 0 ? Number.NaN : I;
488
- };
489
- }
490
- const at = ["time", "open", "high", "low", "close", "volume"];
491
- class D {
492
- constructor(t, e = {}, s = {}) {
493
- this.script = t, this.params = e, this.options = s, this.limits = Q(s.limits), this.start();
494
- }
495
- scope;
496
- outputs;
497
- onBar;
498
- prices;
499
- count = 0;
500
- failures = [];
501
- /** The bar the script threw on, after which no bar runs; -1: none. */
502
- haltedAt = -1;
503
- declared;
504
- /** Whether no bar has run since the setup: a load needs no setup of its own. */
505
- fresh = !1;
506
- /** What it draws, known from its setup. */
507
- get declarations() {
508
- return this.declared;
509
- }
510
- /** The bars loaded last: what a higher interval reads the bars' clock from. */
511
- loaded = [];
512
- limits;
513
- /** When the `load`, `tick` or `next` running began, by `performance.now()`. */
514
- began = 0;
515
- /** Where the script stopped, and why: none while it runs. */
516
- get errors() {
517
- return this.failures;
518
- }
519
- /** How many bars it has run. */
520
- get length() {
521
- return this.count;
522
- }
523
- get output() {
524
- return this.outputs.output(this.count, this.failures);
525
- }
526
- /** Run all of `bars` from the start; the last one stays live. */
527
- load(t) {
528
- this.loaded = t, this.fresh || this.start(), this.fresh = !1, this.clockIn();
529
- for (let e = 0; e < t.length; e++)
530
- e === t.length - 1 && this.goLive(), this.write(e, t[e]), this.count = e + 1, this.runBar(e);
531
- }
532
- /** The live bar as it now is: run it again from the state the bar before left. */
533
- tick(t) {
534
- if (this.count === 0) return this.load([t]);
535
- this.fresh = !1, this.clockIn();
536
- const e = this.count - 1;
537
- this.write(e, t);
538
- for (const s of this.scope.units) s.rollback();
539
- this.haltedAt === e && (this.haltedAt = -1, this.failures = this.failures.filter((s) => s.bar !== e)), this.runBar(e);
540
- }
541
- /**
542
- * Close the live bar as it last ran, and run `bar` as the new live one. A
543
- * script that threw on the live bar stays stopped once it closes, as on
544
- * any closed bar: load the bars again to run it anew.
545
- */
546
- next(t) {
547
- if (this.count === 0) return this.load([t]);
548
- this.fresh = !1, this.clockIn(), this.goLive();
549
- const e = this.count;
550
- this.write(e, t), this.count = e + 1, this.runBar(e);
551
- }
552
- /** A bar from a feed: a tick when it has the live bar's time, a new bar when later. An earlier one is not run: load the bars again. */
553
- update(t) {
554
- if (this.count === 0)
555
- return this.load([t]), "bar";
556
- const e = this.prices.time.get(this.count - 1);
557
- return t.time === e ? (this.tick(t), "tick") : t.time > e ? (this.next(t), "bar") : "reload";
558
- }
559
- /** Begin again from no bars: a new setup, new state. */
560
- start() {
561
- const t = { units: [], live: !1, bar: 0, clearers: [], limits: this.limits, steps: 0, breach: null };
562
- this.scope = t, this.prices = Object.fromEntries(at.map((r) => [r, J()])), this.outputs = new Ut(t), this.count = 0, this.failures = [], this.haltedAt = -1;
563
- const e = this.script.inputs ?? {}, s = Object.fromEntries(Object.keys(e).map((r) => [r, Dt(this.params[r], e[r])]));
564
- if (this.onBar = Zt(t, () => this.script.setup({
565
- inputs: s,
566
- prices: this.priceSeries(),
567
- plot: (r, i) => this.outputs.plot(r, i),
568
- loop: () => {
569
- ++t.steps > t.limits.loopSteps && Nt(t, "loop", `a bar takes at most ${t.limits.loopSteps} loop steps`);
570
- },
571
- shape: (r, i) => this.outputs.shape(r, i),
572
- fill: (r, i, o) => this.outputs.fill(r, i, o),
573
- bgcolor: (r) => this.outputs.bgcolor(r),
574
- barcolor: () => this.outputs.barcolor(),
575
- alertCondition: (r, i) => this.outputs.alertCondition(r, i),
576
- drawings: (r) => this.outputs.addDrawings(new ee(O("drawings"), r)),
577
- request: {
578
- security: (r, i, o) => {
579
- const u = O("request.security"), c = {
580
- timeline: () => this.loaded,
581
- barAt: (a) => this.barAt(a),
582
- ...this.options,
583
- limits: this.limits,
584
- onLimit: (a) => {
585
- u.breach ??= a;
586
- }
587
- };
588
- return ie(c, r, i, o);
589
- }
590
- },
591
- hline: (r, i) => this.outputs.hline(r, i),
592
- state: { var: Vt, array: Ht, series: Xt }
593
- })), this.outputs.close(), typeof this.onBar != "function") throw new Error(`script '${this.script.id}': setup must return what each bar runs`);
594
- this.declared = this.outputs.declarations(this.script.overlay === !0), this.fresh = !0;
595
- }
596
- /** From here on the bar run is the live one: keep the state the bars before left. */
597
- goLive() {
598
- for (const t of this.scope.units) t.commit();
599
- this.scope.live = !0;
600
- }
601
- priceSeries() {
602
- const t = (e) => ({
603
- // Never a bar ahead: a bar sees only itself and the bars before it.
604
- at: (s = 0) => s >= 0 ? this.prices[e].get(this.scope.bar - Math.floor(s)) : Number.NaN
605
- });
606
- return Object.fromEntries(at.map((e) => [e, t(e)]));
607
- }
608
- write(t, e) {
609
- const s = this.prices;
610
- s.time.set(t, e.time), s.open.set(t, e.open), s.high.set(t, e.high), s.low.set(t, e.low), s.close.set(t, e.close), s.volume.set(t, e.volume ?? 0);
611
- }
612
- /** Bar `i` as its prices now stand. */
613
- barAt(t) {
614
- const e = this.prices;
615
- return {
616
- index: t,
617
- time: e.time.get(t),
618
- open: e.open.get(t),
619
- high: e.high.get(t),
620
- low: e.low.get(t),
621
- close: e.close.get(t),
622
- volume: e.volume.get(t),
623
- live: this.scope.live && t === this.count - 1
624
- };
625
- }
626
- runBar(t) {
627
- const e = this.scope;
628
- e.bar = t;
629
- for (const o of e.clearers) o(t);
630
- if (this.haltedAt >= 0) return;
631
- const s = this.barAt(t);
632
- e.steps = 0, e.breach = null;
633
- let r = null;
634
- try {
635
- this.onBar(s);
636
- } catch (o) {
637
- r = o;
638
- }
639
- if (r = e.breach ?? r ?? this.overTime(), r === null) return;
640
- this.haltedAt = t;
641
- const i = r instanceof W ? { limit: r.limit } : {};
642
- this.failures.push({ bar: t, message: r instanceof Error ? r.message : String(r), ...i });
643
- }
644
- /** Start the clock of a `load`, `tick` or `next`, when the run has a time. */
645
- clockIn() {
646
- Number.isFinite(this.limits.runMs) && (this.began = performance.now());
647
- }
648
- /** The time gone past, once a bar is done; null while within it. */
649
- overTime() {
650
- const t = this.limits.runMs;
651
- return !Number.isFinite(t) || performance.now() - this.began <= t ? null : new W("time", `a run takes at most ${t} ms; it was past that at this bar`);
652
- }
653
- }
654
- class p {
655
- constructor(t) {
656
- this.size = t;
657
- const e = O();
658
- this.slots = new Float64Array(t + 1).fill(Number.NaN), e.units.push({
659
- commit: () => {
660
- this.kept = { count: this.count, run: this.run }, this.overwritten = [];
661
- },
662
- rollback: () => {
663
- for (let s = this.overwritten.length - 2; s >= 0; s -= 2) this.slots[this.overwritten[s]] = this.overwritten[s + 1];
664
- this.overwritten = [], this.count = this.kept.count, this.run = this.kept.run;
665
- }
666
- }), this.live = () => e.live;
667
- }
668
- slots;
669
- count = 0;
670
- run = 0;
671
- kept = { count: 0, run: 0 };
672
- /** The slots written over on the live bar, as [slot, value before], oldest first. */
673
- overwritten = [];
674
- live;
675
- /** Take the next value. */
676
- push(t) {
677
- const e = this.count % this.slots.length;
678
- this.live() && this.overwritten.push(e, this.slots[e]), this.slots[e] = t, this.count++, this.run = Number.isNaN(t) ? 0 : this.run + 1;
679
- }
680
- /** The value `back` values before the last one given (0: the last); NaN before the first. */
681
- at(t) {
682
- const e = this.count - 1 - t;
683
- return t < 0 || t > this.size || e < 0 ? Number.NaN : this.slots[e % this.slots.length];
684
- }
685
- /** How many values were given. */
686
- get given() {
687
- return this.count;
688
- }
689
- /** How many values in a row, up to the last, were numbers. */
690
- get numbersInRow() {
691
- return this.run;
692
- }
693
- }
694
- function h(n) {
695
- return Number.isFinite(n) ? n : Number.NaN;
696
- }
697
- function f(n) {
698
- return Number.isFinite(n) ? Math.max(1, Math.floor(n)) : 1;
699
- }
700
- function L(n, t) {
701
- const e = b({ last: Number.NaN });
702
- return (s) => {
703
- const r = h(s);
704
- return Number.isNaN(r) ? (Number.isNaN(e.last) || n(e.last), t) : (e.last = r, n(r));
705
- };
706
- }
707
- function q() {
708
- const n = b({ close: Number.NaN });
709
- return (t) => {
710
- const e = Number.isFinite(t.close) ? t.close : n.close;
711
- n.close = e;
712
- const s = (r) => Number.isFinite(r) ? r : e;
713
- return { high: s(t.high), low: s(t.low), close: e };
714
- };
715
- }
716
- function dt(n) {
717
- const t = f(n), e = new p(t), s = b({ sum: 0 });
718
- return (r) => {
719
- const i = h(r);
720
- return e.push(i), Number.isNaN(i) ? (s.sum = 0, Number.NaN) : (s.sum += i, e.numbersInRow > t && (s.sum -= e.at(t)), e.numbersInRow >= t ? s.sum / t : Number.NaN);
721
- };
722
- }
723
- function bt(n, t) {
724
- const e = f(n), s = t(e), r = b({ seed: 0, count: 0, value: Number.NaN });
725
- return (i) => {
726
- const o = h(i);
727
- return Number.isNaN(o) ? Number.NaN : Number.isNaN(r.value) ? (r.seed += o, r.count++, r.count === e && (r.value = r.seed / e), r.value) : (r.value += s * (o - r.value), r.value);
728
- };
729
- }
730
- function R(n) {
731
- return bt(n, (t) => 2 / (t + 1));
732
- }
733
- function oe(n) {
734
- return bt(n, (t) => 1 / t);
735
- }
736
- function g(n, t) {
737
- if (n.given < t) return null;
738
- const e = new Array(t);
739
- for (let s = 0; s < t; s++) {
740
- const r = n.at(t - 1 - s);
741
- if (Number.isNaN(r)) return null;
742
- e[s] = r;
743
- }
744
- return e;
745
- }
746
- function _(n) {
747
- const t = f(n), e = new p(t), s = t * (t + 1) / 2;
748
- return (r) => {
749
- e.push(h(r));
750
- const i = g(e, t);
751
- if (!i) return Number.NaN;
752
- let o = 0;
753
- for (let u = 0; u < t; u++) o += i[u] * (u + 1);
754
- return o / s;
755
- };
756
- }
757
- function gt(n) {
758
- const t = f(n), e = new p(t);
759
- return (s) => {
760
- e.push(h(s));
761
- const r = g(e, t);
762
- if (!r) return Number.NaN;
763
- let i = 0, o = 0;
764
- for (const c of r)
765
- i += c, o += c * c;
766
- const u = i / t;
767
- return Math.sqrt(Math.max(0, o / t - u * u));
768
- };
769
- }
770
- function ue(n) {
771
- return L(ae(n), Number.NaN);
772
- }
773
- function ae(n) {
774
- const t = Math.max(2, f(n)), e = _(Math.max(2, Math.floor(t / 2))), s = _(t), r = _(Math.max(2, Math.floor(Math.sqrt(t))));
775
- return (i) => {
776
- const o = e(i), u = s(i);
777
- return r(Number.isNaN(o) || Number.isNaN(u) ? Number.NaN : 2 * o - u);
778
- };
779
- }
780
- function ce(n) {
781
- const t = f(n), e = new p(t), s = new p(t), r = b({ pv: 0, volume: 0, last: Number.NaN });
782
- return (i, o) => {
783
- const u = h(i);
784
- Number.isNaN(u) || (r.last = u);
785
- const c = r.last;
786
- if (Number.isNaN(c)) return Number.NaN;
787
- const a = Number.isFinite(o) ? o : 0;
788
- return e.push(c), s.push(a), r.pv += c * a, r.volume += a, e.given > t && (r.pv -= e.at(t) * s.at(t), r.volume -= s.at(t)), Number.isNaN(u) ? Number.NaN : e.given >= t && r.volume > 0 ? r.pv / r.volume : Number.NaN;
789
- };
790
- }
791
- function wt(n) {
792
- const t = b({ a: Number.NaN, b: Number.NaN });
793
- return (e, s) => {
794
- const r = h(e), i = h(s), o = t.a, u = t.b;
795
- return t.a = r, t.b = i, [r, i, o, u].some(Number.isNaN) ? !1 : n ? o <= u && r > i : o >= u && r < i;
796
- };
797
- }
798
- function vt() {
799
- return wt(!0);
800
- }
801
- function yt() {
802
- return wt(!1);
803
- }
804
- function le() {
805
- const n = vt(), t = yt();
806
- return (e, s) => {
807
- const r = n(e, s), i = t(e, s);
808
- return r || i;
809
- };
810
- }
811
- function kt(n, t, e) {
812
- const s = f(n), r = f(t), i = new p(s + r);
813
- return (o) => {
814
- if (i.push(h(o)), i.given < s + r + 1) return Number.NaN;
815
- const u = i.at(r);
816
- if (Number.isNaN(u)) return Number.NaN;
817
- for (let c = 0; c <= s + r; c++) {
818
- if (c === r) continue;
819
- const a = i.at(c);
820
- if (Number.isNaN(a) || !e(u, a)) return Number.NaN;
821
- }
822
- return u;
823
- };
824
- }
825
- function he(n, t) {
826
- return kt(n, t, (e, s) => e > s);
827
- }
828
- function me(n, t) {
829
- return kt(n, t, (e, s) => e < s);
830
- }
831
- function fe() {
832
- const n = b({ since: Number.NaN });
833
- return (t) => (n.since = t ? 0 : n.since + 1, n.since);
834
- }
835
- function pe(n = 0) {
836
- const t = Math.max(0, Math.floor(n)), e = new p(t);
837
- return (s, r) => (s && e.push(h(r)), e.at(t));
838
- }
839
- function Ne(n = 14) {
840
- return L(de(n), Number.NaN);
841
- }
842
- function de(n) {
843
- const t = f(n), e = b({ prev: Number.NaN, count: 0, gain: 0, loss: 0 }), s = () => e.loss === 0 ? 100 : 100 - 100 / (1 + e.gain / e.loss);
844
- return (r) => {
845
- const i = h(r);
846
- if (Number.isNaN(i)) return Number.NaN;
847
- if (Number.isNaN(e.prev))
848
- return e.prev = i, Number.NaN;
849
- const o = i - e.prev;
850
- e.prev = i;
851
- const u = o > 0 ? o : 0, c = o < 0 ? -o : 0;
852
- return e.count < t ? (e.gain += u, e.loss += c, e.count++, e.count < t ? Number.NaN : (e.gain /= t, e.loss /= t, s())) : (e.gain = (e.gain * (t - 1) + u) / t, e.loss = (e.loss * (t - 1) + c) / t, s());
853
- };
854
- }
855
- function be(n = 12, t = 26, e = 9) {
856
- return L(ge(n, t, e), { macd: Number.NaN, signal: Number.NaN, histogram: Number.NaN });
857
- }
858
- function ge(n, t, e) {
859
- const s = R(n), r = R(t), i = R(e);
860
- return (o) => {
861
- const u = s(o), c = r(o), a = Number.isNaN(u) || Number.isNaN(c) ? Number.NaN : u - c, l = i(a);
862
- return { macd: a, signal: l, histogram: a - l };
863
- };
864
- }
865
- function we(n = 20, t = 2) {
866
- return L(ve(n, t), { basis: Number.NaN, upper: Number.NaN, lower: Number.NaN });
867
- }
868
- function ve(n, t) {
869
- const e = dt(n), s = gt(n);
870
- return (r) => {
871
- const i = e(r), o = t * s(r);
872
- return { basis: i, upper: i + o, lower: i - o };
873
- };
874
- }
875
- function Mt(n = 1) {
876
- const t = f(n), e = new p(t);
877
- return (s) => (e.push(h(s)), e.at(0) - e.at(t));
878
- }
879
- function ye(n = 10) {
880
- return L(Mt(n), Number.NaN);
881
- }
882
- function ke(n = 12) {
883
- return L(Me(n), Number.NaN);
884
- }
885
- function Me(n) {
886
- const t = f(n), e = new p(t);
887
- return (s) => {
888
- e.push(h(s));
889
- const r = e.at(0), i = e.at(t);
890
- return Number.isNaN(r) || Number.isNaN(i) ? Number.NaN : i === 0 ? 0 : (r - i) / i * 100;
891
- };
892
- }
893
- function xt() {
894
- const n = q(), t = b({ prevClose: Number.NaN });
895
- return (e) => {
896
- const s = n(e);
897
- if (Number.isNaN(s.close)) return Number.NaN;
898
- const r = s.high - s.low, i = t.prevClose;
899
- return t.prevClose = s.close, Number.isNaN(i) ? r : Math.max(r, Math.abs(s.high - i), Math.abs(s.low - i));
900
- };
901
- }
902
- function St(n = 14) {
903
- const t = f(n), e = xt(), s = b({ count: 0, value: 0 });
904
- return (r) => {
905
- const i = e(r);
906
- return Number.isNaN(i) ? Number.NaN : s.count < t ? (s.value += i, s.count++, s.count < t ? Number.NaN : (s.value /= t, s.value)) : (s.value = (s.value * (t - 1) + i) / t, s.value);
907
- };
908
- }
909
- function xe(n = 3, t = 10) {
910
- const e = f(t), s = St(e), r = b({ prevClose: Number.NaN, upper: 0, lower: 0, line: 0 }), i = q();
911
- return (o) => {
912
- const u = s(o), c = i(o), a = Number.isNaN(r.prevClose) ? c.close : r.prevClose;
913
- if (r.prevClose = c.close, Number.isNaN(u)) return { value: Number.NaN, trend: Number.NaN };
914
- const l = (c.high + c.low) / 2, m = l + n * u, v = l - n * u, N = m < r.upper || a > r.upper ? m : r.upper, x = v > r.lower || a < r.lower ? v : r.lower, S = r.line === r.upper ? c.close <= N ? N : x : c.close >= x ? x : N;
915
- return r.upper = N, r.lower = x, r.line = S, { value: S, trend: S === x ? 1 : -1 };
916
- };
917
- }
918
- function Ot(n, t) {
919
- const e = f(n), s = new p(e);
920
- return (r) => {
921
- if (s.push(h(r)), s.given < e) return Number.NaN;
922
- let i = s.at(0);
923
- for (let o = 0; o < e; o++) {
924
- const u = s.at(o);
925
- if (Number.isNaN(u)) return Number.NaN;
926
- t(u, i) && (i = u);
927
- }
928
- return i;
929
- };
930
- }
931
- function Se(n) {
932
- return Ot(n, (t, e) => t > e);
933
- }
934
- function Oe(n) {
935
- return Ot(n, (t, e) => t < e);
936
- }
937
- function Ie(n) {
938
- const t = f(n), e = new p(t), s = new p(t);
939
- return (r, i, o) => {
940
- e.push(h(i)), s.push(h(o));
941
- const u = g(e, t), c = g(s, t), a = h(r);
942
- if (!u || !c || Number.isNaN(a)) return Number.NaN;
943
- const l = Math.max(...u), m = Math.min(...c);
944
- return l === m ? 50 : (a - m) / (l - m) * 100;
945
- };
946
- }
947
- function Ee(n) {
948
- const t = f(n), e = new p(t + 1), s = new p(t + 1);
949
- return (r, i) => {
950
- e.push(h(r)), s.push(h(i));
951
- const o = g(e, t + 1), u = g(s, t + 1);
952
- if (!o || !u) return Number.NaN;
953
- let c = 0, a = 0;
954
- for (let l = 1; l <= t; l++)
955
- o[l] > o[l - 1] ? c += o[l] * u[l] : o[l] < o[l - 1] && (a += o[l] * u[l]);
956
- return a === 0 ? 100 : 100 - 100 / (1 + c / a);
957
- };
241
+ function b(e = {}) {
242
+ let t = Object.fromEntries(Object.entries(e).filter(([, e]) => e !== void 0)), n = {
243
+ ...v,
244
+ ...t
245
+ };
246
+ for (let e of Object.keys(v)) {
247
+ let t = n[e];
248
+ if (typeof t != "number" || Number.isNaN(t) || t <= 0) throw RangeError(`script limits: ${e} must be a positive number, not ${String(t)}`);
249
+ }
250
+ return n;
251
+ }
252
+ function x(e, t, n) {
253
+ let r = new y(t, n);
254
+ throw e.breach ??= r, r;
255
+ }
256
+ //#endregion
257
+ //#region src/state.ts
258
+ function ee(e) {
259
+ let t = g("state.var"), n = { value: e }, r = e;
260
+ return t.units.push({
261
+ commit: () => {
262
+ r = n.value;
263
+ },
264
+ rollback: () => {
265
+ n.value = r;
266
+ }
267
+ }), n;
268
+ }
269
+ function te() {
270
+ let e = g("state.series"), t = l();
271
+ return e.clearers.push((e) => t.set(e, NaN)), {
272
+ set: (n) => (t.set(e.bar, n), n),
273
+ at: (n = 0) => n >= 0 ? t.get(e.bar - Math.floor(n)) : NaN
274
+ };
275
+ }
276
+ var ne = class {
277
+ items = [];
278
+ undo = [];
279
+ constructor(e) {
280
+ this.scope = e, e.units.push({
281
+ commit: () => {
282
+ this.undo = [];
283
+ },
284
+ rollback: () => {
285
+ for (let e = this.undo.length - 1; e >= 0; e--) this.undo[e]();
286
+ this.undo = [];
287
+ }
288
+ });
289
+ }
290
+ record(e) {
291
+ this.scope.live && this.undo.push(e);
292
+ }
293
+ grow() {
294
+ let e = this.scope.limits.arraySize;
295
+ this.items.length >= e && x(this.scope, "array", `a list holds at most ${e} numbers`);
296
+ }
297
+ size() {
298
+ return this.items.length;
299
+ }
300
+ get(e) {
301
+ let t = e < 0 ? this.items.length + e : e;
302
+ return t >= 0 && t < this.items.length ? this.items[t] : NaN;
303
+ }
304
+ set(e, t) {
305
+ if (e < 0 || e >= this.items.length) throw RangeError(`array.set: index ${e} is outside a list of ${this.items.length}`);
306
+ let n = this.items[e];
307
+ this.items[e] = t, this.record(() => {
308
+ this.items[e] = n;
309
+ });
310
+ }
311
+ push(e) {
312
+ this.grow(), this.items.push(e), this.record(() => {
313
+ this.items.pop();
314
+ });
315
+ }
316
+ pop() {
317
+ if (this.items.length === 0) return NaN;
318
+ let e = this.items.pop();
319
+ return this.record(() => {
320
+ this.items.push(e);
321
+ }), e;
322
+ }
323
+ shift() {
324
+ if (this.items.length === 0) return NaN;
325
+ let e = this.items.shift();
326
+ return this.record(() => {
327
+ this.items.unshift(e);
328
+ }), e;
329
+ }
330
+ unshift(e) {
331
+ this.grow(), this.items.unshift(e), this.record(() => {
332
+ this.items.shift();
333
+ });
334
+ }
335
+ clear() {
336
+ let e = this.items;
337
+ this.items = [], this.record(() => {
338
+ this.items = e;
339
+ });
340
+ }
341
+ toArray() {
342
+ return [...this.items];
343
+ }
344
+ sum() {
345
+ let e = 0;
346
+ for (let t of this.items) e += t;
347
+ return e;
348
+ }
349
+ avg() {
350
+ return this.items.length > 0 ? this.sum() / this.items.length : NaN;
351
+ }
352
+ min() {
353
+ return this.items.reduce((e, t) => t < e ? t : e, this.items.length > 0 ? Infinity : NaN);
354
+ }
355
+ max() {
356
+ return this.items.reduce((e, t) => t > e ? t : e, this.items.length > 0 ? -Infinity : NaN);
357
+ }
358
+ median() {
359
+ let e = this.items.length;
360
+ if (e === 0) return NaN;
361
+ let t = [...this.items].sort((e, t) => e - t), n = e >> 1;
362
+ return e % 2 == 1 ? t[n] : (t[n - 1] + t[n]) / 2;
363
+ }
364
+ };
365
+ function re() {
366
+ return new ne(g("state.array"));
367
+ }
368
+ //#endregion
369
+ //#region src/drawings.ts
370
+ var ie = 50, ae = 500, S = (e) => e === void 0 || Number.isNaN(e) ? ie : Math.min(ae, Math.max(1, Math.floor(e))), oe = (e) => !!e && typeof e.bar == "number" && typeof e.value == "number", se = {
371
+ label: ["at"],
372
+ line: ["from", "to"],
373
+ box: ["from", "to"]
374
+ };
375
+ function ce(e) {
376
+ for (let t of se[e.kind]) if (!oe(e[t])) throw Error(`a ${e.kind} needs ${t}: { bar, value }`);
377
+ return e;
378
+ }
379
+ var le = (e) => ({
380
+ bar: e.bar,
381
+ value: e.value
382
+ });
383
+ function C(e) {
384
+ let t = { ...e };
385
+ for (let e of [
386
+ "at",
387
+ "from",
388
+ "to"
389
+ ]) {
390
+ let n = t[e];
391
+ n && (t[e] = le(n));
392
+ }
393
+ return t;
394
+ }
395
+ var ue = class {
396
+ items = /* @__PURE__ */ new Map();
397
+ order = {
398
+ label: [],
399
+ line: [],
400
+ box: []
401
+ };
402
+ limits;
403
+ nextId = 0;
404
+ undo = [];
405
+ constructor(e, t = {}) {
406
+ this.scope = e, this.limits = {
407
+ label: S(t.maxLabels),
408
+ line: S(t.maxLines),
409
+ box: S(t.maxBoxes)
410
+ }, e.units.push({
411
+ commit: () => {
412
+ this.undo = [];
413
+ },
414
+ rollback: () => {
415
+ for (let e = this.undo.length - 1; e >= 0; e--) this.undo[e]();
416
+ this.undo = [];
417
+ }
418
+ });
419
+ }
420
+ label(e) {
421
+ return this.add({
422
+ kind: "label",
423
+ ...e
424
+ });
425
+ }
426
+ line(e) {
427
+ return this.add({
428
+ kind: "line",
429
+ ...e
430
+ });
431
+ }
432
+ box(e) {
433
+ return this.add({
434
+ kind: "box",
435
+ ...e
436
+ });
437
+ }
438
+ list() {
439
+ return [...this.items.keys()].sort((e, t) => e - t).map((e) => this.items.get(e));
440
+ }
441
+ record(e) {
442
+ this.scope.live && this.undo.push(e);
443
+ }
444
+ add(e) {
445
+ ce(e);
446
+ let t = this.nextId++;
447
+ this.record(() => {
448
+ this.nextId = t;
449
+ }), this.items.set(t, C(e)), this.record(() => {
450
+ this.items.delete(t);
451
+ });
452
+ let n = this.order[e.kind];
453
+ for (n.push(t), this.record(() => {
454
+ n.pop();
455
+ }); n.length > this.limits[e.kind];) {
456
+ let e = n.shift(), t = this.items.get(e);
457
+ this.items.delete(e), this.record(() => {
458
+ this.items.set(e, t), n.unshift(e);
459
+ });
460
+ }
461
+ return {
462
+ set: (e) => this.change(t, e),
463
+ remove: () => this.remove(t)
464
+ };
465
+ }
466
+ change(e, t) {
467
+ let n = this.items.get(e);
468
+ n && (this.items.set(e, C(ce({
469
+ ...n,
470
+ ...t,
471
+ kind: n.kind
472
+ }))), this.record(() => {
473
+ this.items.set(e, n);
474
+ }));
475
+ }
476
+ remove(e) {
477
+ let t = this.items.get(e);
478
+ if (!t) return;
479
+ this.items.delete(e);
480
+ let n = this.order[t.kind], r = n.indexOf(e);
481
+ r >= 0 && n.splice(r, 1), this.record(() => {
482
+ this.items.set(e, t), r >= 0 && n.splice(r, 0, e);
483
+ });
484
+ }
485
+ }, de = 1e11, w = (e, t) => e ? {
486
+ open: e.open,
487
+ high: Math.max(e.high, t.high),
488
+ low: Math.min(e.low, t.low),
489
+ close: t.close,
490
+ volume: e.volume + t.volume
491
+ } : {
492
+ open: t.open,
493
+ high: t.high,
494
+ low: t.low,
495
+ close: t.close,
496
+ volume: t.volume
497
+ }, fe = (e, t) => !!e && e.open === t.open && e.high === t.high && e.low === t.low && e.close === t.close && e.volume === t.volume;
498
+ function pe(e) {
499
+ let t = Infinity;
500
+ for (let n = 1; n < e.length; n++) t = Math.min(t, e[n].time - e[n - 1].time);
501
+ return !Number.isFinite(t) || t <= 0 ? NaN : e[e.length - 1].time < de ? t * 1e3 : t;
502
+ }
503
+ function me(e, n, r, o = {}) {
504
+ let s = typeof n == "string" ? t(n) : NaN;
505
+ if (!Number.isFinite(s)) throw Error(`request.security: '${String(n)}' is no interval it can read: a count and a unit, as '15m', '1h', '4h', '1d', '1w', '1M' (case matters)`);
506
+ let c = [], l = !1, u = new T(a({
507
+ id: `security:${n}`,
508
+ name: n,
509
+ setup(e) {
510
+ let t = r({
511
+ prices: e.prices,
512
+ state: e.state
513
+ });
514
+ return (e) => {
515
+ c[e.index] = t(e.live && !l ? {
516
+ ...e,
517
+ live: !1
518
+ } : e);
519
+ };
520
+ }
521
+ }), {}, e.limits ? { limits: {
522
+ loopSteps: e.limits.loopSteps,
523
+ arraySize: e.limits.arraySize
524
+ } } : {}), d = null, f = -1, p = NaN, m = NaN, h = null, g = null, _ = 0, v = (t, r, i) => {
525
+ let a = {
526
+ time: r,
527
+ ...t
528
+ };
529
+ u.length === 0 ? u.load([a]) : i && u.length === _ ? u.next(a) : u.tick(a);
530
+ let o = u.errors[0];
531
+ if (!o) return;
532
+ let s = `request.security('${n}'), on its bar ${o.bar}: ${o.message}`;
533
+ if (!o.limit) throw Error(s);
534
+ let c = new y(o.limit, s);
535
+ throw e.onLimit?.(c), c;
536
+ }, b = () => {
537
+ if (d) return d;
538
+ let t = e.timeline(), r = pe(t);
539
+ if (Number.isFinite(r) && s < r) throw Error(`request.security('${n}') reads a higher interval than the chart's bars: they are ${r / 6e4} minutes apart`);
540
+ return d = i(t, n, e.exchangeTimeZone, e.sessionStart), d;
541
+ };
542
+ return (t) => {
543
+ let r = b();
544
+ if (l = t.live, t.index === f) {
545
+ if (r(t.time) !== p) throw Error(`request.security('${n}'): the live bar's time moved to another period; load the bars again`);
546
+ let e = w(h, t);
547
+ v(e, m, !1), g = e;
548
+ } else if (t.index === f + 1) {
549
+ if (f >= 0) {
550
+ let n = w(h, e.barAt(f));
551
+ l = !1, fe(g, n) || v(n, m, !1), l = t.live, g = n;
552
+ }
553
+ let n = r(t.time), i = n !== p || g === null, a = i ? null : g, o = w(a, t), s = i ? t.time : m;
554
+ v(o, s, i), p = n, m = s, h = a, g = o, f = t.index, _ = u.length;
555
+ } else throw Error(`request.security('${n}') is called on every bar: it was not on bar ${f + 1}`);
556
+ let i = u.length - 1, a = o.live ? c[i] : c[i - 1];
557
+ return a === void 0 ? NaN : a;
558
+ };
559
+ }
560
+ //#endregion
561
+ //#region src/ScriptRun.ts
562
+ var he = [
563
+ "time",
564
+ "open",
565
+ "high",
566
+ "low",
567
+ "close",
568
+ "volume"
569
+ ], T = class {
570
+ scope;
571
+ outputs;
572
+ onBar;
573
+ prices;
574
+ count = 0;
575
+ failures = [];
576
+ haltedAt = -1;
577
+ declared;
578
+ fresh = !1;
579
+ get declarations() {
580
+ return this.declared;
581
+ }
582
+ loaded = [];
583
+ limits;
584
+ began = 0;
585
+ intervalRead = !1;
586
+ constructor(e, t = {}, n = {}) {
587
+ this.script = e, this.params = t, this.options = n, this.limits = b(n.limits), this.start();
588
+ }
589
+ get errors() {
590
+ return this.failures;
591
+ }
592
+ get length() {
593
+ return this.count;
594
+ }
595
+ get output() {
596
+ return this.outputs.output(this.count, this.failures);
597
+ }
598
+ load(e) {
599
+ this.loaded = e, this.fresh || this.start(), this.fresh = !1, this.clockIn();
600
+ for (let t = 0; t < e.length; t++) t === e.length - 1 && this.goLive(), this.write(t, e[t]), this.count = t + 1, this.runBar(t);
601
+ }
602
+ tick(e) {
603
+ if (this.count === 0) return this.load([e]);
604
+ this.fresh = !1, this.clockIn();
605
+ let t = this.count - 1;
606
+ this.write(t, e);
607
+ for (let e of this.scope.units) e.rollback();
608
+ this.haltedAt === t && (this.haltedAt = -1, this.failures = this.failures.filter((e) => e.bar !== t)), this.runBar(t);
609
+ }
610
+ next(e) {
611
+ if (this.count === 0) return this.load([e]);
612
+ this.fresh = !1, this.clockIn(), this.closeLive(), this.goLive();
613
+ let t = this.count;
614
+ this.write(t, e), this.count = t + 1, this.runBar(t);
615
+ }
616
+ update(e) {
617
+ if (this.count === 0) return this.load([e]), "bar";
618
+ let t = this.prices.time.get(this.count - 1);
619
+ return e.time === t ? (this.tick(e), "tick") : e.time > t ? (this.next(e), "bar") : "reload";
620
+ }
621
+ start() {
622
+ let e = {
623
+ units: [],
624
+ live: !1,
625
+ bar: 0,
626
+ clearers: [],
627
+ limits: this.limits,
628
+ steps: 0,
629
+ breach: null
630
+ };
631
+ this.scope = e, this.prices = Object.fromEntries(he.map((e) => [e, l()])), this.outputs = new p(e), this.count = 0, this.failures = [], this.haltedAt = -1;
632
+ let t = this.script.inputs ?? {}, n = Object.fromEntries(Object.keys(t).map((e) => [e, o(this.params[e], t[e])]));
633
+ if (this.onBar = h(e, () => this.script.setup({
634
+ inputs: n,
635
+ chart: this.chart(),
636
+ prices: this.priceSeries(),
637
+ plot: (e, t) => this.outputs.plot(e, t),
638
+ loop: () => {
639
+ ++e.steps > e.limits.loopSteps && x(e, "loop", `a bar takes at most ${e.limits.loopSteps} loop steps`);
640
+ },
641
+ shape: (e, t) => this.outputs.shape(e, t),
642
+ fill: (e, t, n) => this.outputs.fill(e, t, n),
643
+ bgcolor: (e) => this.outputs.bgcolor(e),
644
+ barcolor: () => this.outputs.barcolor(),
645
+ alertCondition: (e, t) => this.outputs.alertCondition(e, t),
646
+ drawings: (e) => this.outputs.addDrawings(new ue(g("drawings"), e)),
647
+ request: { security: (e, t, n) => {
648
+ let r = g("request.security");
649
+ return me({
650
+ timeline: () => this.loaded,
651
+ barAt: (e) => this.barAt(e),
652
+ ...this.options,
653
+ limits: this.limits,
654
+ onLimit: (e) => {
655
+ r.breach ??= e;
656
+ }
657
+ }, e, t, n);
658
+ } },
659
+ hline: (e, t) => this.outputs.hline(e, t),
660
+ state: {
661
+ var: ee,
662
+ array: re,
663
+ series: te
664
+ }
665
+ })), this.outputs.close(), typeof this.onBar != "function") throw Error(`script '${this.script.id}': setup must return what each bar runs`);
666
+ this.declared = this.outputs.declarations(this.script.overlay === !0), this.fresh = !0;
667
+ }
668
+ chart() {
669
+ let { exchangeTimeZone: e = "UTC", interval: t = null } = this.options, n = () => (this.intervalRead = !0, t);
670
+ return Object.freeze({
671
+ timeZone: e,
672
+ get interval() {
673
+ return n();
674
+ }
675
+ });
676
+ }
677
+ get readsInterval() {
678
+ return this.intervalRead;
679
+ }
680
+ goLive() {
681
+ for (let e of this.scope.units) e.commit();
682
+ this.scope.live = !0;
683
+ }
684
+ closeLive() {
685
+ if (!(this.haltedAt >= 0)) {
686
+ for (let e of this.scope.units) e.rollback();
687
+ this.scope.live = !1, this.runBar(this.count - 1);
688
+ }
689
+ }
690
+ priceSeries() {
691
+ let e = (e) => ({ at: (t = 0) => t >= 0 ? this.prices[e].get(this.scope.bar - Math.floor(t)) : NaN });
692
+ return Object.fromEntries(he.map((t) => [t, e(t)]));
693
+ }
694
+ write(e, t) {
695
+ let n = this.prices;
696
+ n.time.set(e, t.time), n.open.set(e, t.open), n.high.set(e, t.high), n.low.set(e, t.low), n.close.set(e, t.close), n.volume.set(e, t.volume ?? 0);
697
+ }
698
+ barAt(e) {
699
+ let t = this.prices;
700
+ return {
701
+ index: e,
702
+ time: t.time.get(e),
703
+ open: t.open.get(e),
704
+ high: t.high.get(e),
705
+ low: t.low.get(e),
706
+ close: t.close.get(e),
707
+ volume: t.volume.get(e),
708
+ live: this.scope.live && e === this.count - 1
709
+ };
710
+ }
711
+ runBar(e) {
712
+ let t = this.scope;
713
+ t.bar = e;
714
+ for (let n of t.clearers) n(e);
715
+ if (this.haltedAt >= 0) return;
716
+ let n = this.barAt(e);
717
+ t.steps = 0, t.breach = null;
718
+ let r = null;
719
+ try {
720
+ this.onBar(n);
721
+ } catch (e) {
722
+ r = e;
723
+ }
724
+ if (r = t.breach ?? r ?? this.overTime(), r === null) return;
725
+ this.haltedAt = e;
726
+ let i = r instanceof y ? { limit: r.limit } : {};
727
+ this.failures.push({
728
+ bar: e,
729
+ message: r instanceof Error ? r.message : String(r),
730
+ ...i
731
+ });
732
+ }
733
+ clockIn() {
734
+ Number.isFinite(this.limits.runMs) && (this.began = performance.now());
735
+ }
736
+ overTime() {
737
+ let e = this.limits.runMs;
738
+ return !Number.isFinite(e) || performance.now() - this.began <= e ? null : new y("time", `a run takes at most ${e} ms; it was past that at this bar`);
739
+ }
740
+ }, E = class {
741
+ slots;
742
+ count = 0;
743
+ run = 0;
744
+ kept = {
745
+ count: 0,
746
+ run: 0
747
+ };
748
+ overwritten = [];
749
+ constructor(e) {
750
+ this.size = e;
751
+ let t = g();
752
+ this.slots = new Float64Array(e + 1).fill(NaN), t.units.push({
753
+ commit: () => {
754
+ this.kept = {
755
+ count: this.count,
756
+ run: this.run
757
+ }, this.overwritten = [];
758
+ },
759
+ rollback: () => {
760
+ for (let e = this.overwritten.length - 2; e >= 0; e -= 2) this.slots[this.overwritten[e]] = this.overwritten[e + 1];
761
+ this.overwritten = [], this.count = this.kept.count, this.run = this.kept.run;
762
+ }
763
+ }), this.live = () => t.live;
764
+ }
765
+ live;
766
+ push(e) {
767
+ let t = this.count % this.slots.length;
768
+ this.live() && this.overwritten.push(t, this.slots[t]), this.slots[t] = e, this.count++, this.run = Number.isNaN(e) ? 0 : this.run + 1;
769
+ }
770
+ at(e) {
771
+ let t = this.count - 1 - e;
772
+ return e < 0 || e > this.size || t < 0 ? NaN : this.slots[t % this.slots.length];
773
+ }
774
+ get given() {
775
+ return this.count;
776
+ }
777
+ get numbersInRow() {
778
+ return this.run;
779
+ }
780
+ };
781
+ //#endregion
782
+ //#region src/ta/common.ts
783
+ function D(e) {
784
+ return Number.isFinite(e) ? e : NaN;
785
+ }
786
+ function O(e) {
787
+ return Number.isFinite(e) ? Math.max(1, Math.floor(e)) : 1;
788
+ }
789
+ function k(e, t) {
790
+ let n = _({ last: NaN });
791
+ return (r) => {
792
+ let i = D(r);
793
+ return Number.isNaN(i) ? (Number.isNaN(n.last) || e(n.last), t) : (n.last = i, e(i));
794
+ };
795
+ }
796
+ function A() {
797
+ let e = _({ close: NaN });
798
+ return (t) => {
799
+ let n = Number.isFinite(t.close) ? t.close : e.close;
800
+ e.close = n;
801
+ let r = (e) => Number.isFinite(e) ? e : n;
802
+ return {
803
+ high: r(t.high),
804
+ low: r(t.low),
805
+ close: n
806
+ };
807
+ };
808
+ }
809
+ //#endregion
810
+ //#region src/ta/averages.ts
811
+ function j(e) {
812
+ let t = O(e), n = new E(t), r = _({ sum: 0 });
813
+ return (e) => {
814
+ let i = D(e);
815
+ return n.push(i), Number.isNaN(i) ? (r.sum = 0, NaN) : (r.sum += i, n.numbersInRow > t && (r.sum -= n.at(t)), n.numbersInRow >= t ? r.sum / t : NaN);
816
+ };
817
+ }
818
+ function M(e, t) {
819
+ let n = O(e), r = t(n), i = _({
820
+ seed: 0,
821
+ count: 0,
822
+ value: NaN
823
+ });
824
+ return (e) => {
825
+ let t = D(e);
826
+ return Number.isNaN(t) ? NaN : Number.isNaN(i.value) ? (i.seed += t, i.count++, i.count === n && (i.value = i.seed / n), i.value) : (i.value += r * (t - i.value), i.value);
827
+ };
828
+ }
829
+ function N(e) {
830
+ return M(e, (e) => 2 / (e + 1));
831
+ }
832
+ function ge(e) {
833
+ return M(e, (e) => 1 / e);
834
+ }
835
+ function P(e, t) {
836
+ if (e.given < t) return null;
837
+ let n = Array(t);
838
+ for (let r = 0; r < t; r++) {
839
+ let i = e.at(t - 1 - r);
840
+ if (Number.isNaN(i)) return null;
841
+ n[r] = i;
842
+ }
843
+ return n;
844
+ }
845
+ function F(e) {
846
+ let t = O(e), n = new E(t), r = t * (t + 1) / 2;
847
+ return (e) => {
848
+ n.push(D(e));
849
+ let i = P(n, t);
850
+ if (!i) return NaN;
851
+ let a = 0;
852
+ for (let e = 0; e < t; e++) a += i[e] * (e + 1);
853
+ return a / r;
854
+ };
855
+ }
856
+ function _e(e) {
857
+ let t = O(e), n = new E(t);
858
+ return (e) => {
859
+ n.push(D(e));
860
+ let r = P(n, t);
861
+ if (!r) return NaN;
862
+ let i = 0, a = 0;
863
+ for (let e of r) i += e, a += e * e;
864
+ let o = i / t;
865
+ return Math.sqrt(Math.max(0, a / t - o * o));
866
+ };
867
+ }
868
+ function ve(e) {
869
+ return k(ye(e), NaN);
870
+ }
871
+ function ye(e) {
872
+ let t = Math.max(2, O(e)), n = F(Math.max(2, Math.floor(t / 2))), r = F(t), i = F(Math.max(2, Math.floor(Math.sqrt(t))));
873
+ return (e) => {
874
+ let t = n(e), a = r(e);
875
+ return i(Number.isNaN(t) || Number.isNaN(a) ? NaN : 2 * t - a);
876
+ };
877
+ }
878
+ function be(e) {
879
+ let t = O(e), n = new E(t), r = new E(t), i = _({
880
+ pv: 0,
881
+ volume: 0,
882
+ last: NaN
883
+ });
884
+ return (e, a) => {
885
+ let o = D(e);
886
+ Number.isNaN(o) || (i.last = o);
887
+ let s = i.last;
888
+ if (Number.isNaN(s)) return NaN;
889
+ let c = Number.isFinite(a) ? a : 0;
890
+ return n.push(s), r.push(c), i.pv += s * c, i.volume += c, n.given > t && (i.pv -= n.at(t) * r.at(t), i.volume -= r.at(t)), Number.isNaN(o) ? NaN : n.given >= t && i.volume > 0 ? i.pv / i.volume : NaN;
891
+ };
892
+ }
893
+ //#endregion
894
+ //#region src/ta/events.ts
895
+ function xe(e) {
896
+ let t = _({
897
+ a: NaN,
898
+ b: NaN
899
+ });
900
+ return (n, r) => {
901
+ let i = D(n), a = D(r), o = t.a, s = t.b;
902
+ return t.a = i, t.b = a, [
903
+ i,
904
+ a,
905
+ o,
906
+ s
907
+ ].some(Number.isNaN) ? !1 : e ? o <= s && i > a : o >= s && i < a;
908
+ };
909
+ }
910
+ function Se() {
911
+ return xe(!0);
912
+ }
913
+ function Ce() {
914
+ return xe(!1);
915
+ }
916
+ function we() {
917
+ let e = Se(), t = Ce();
918
+ return (n, r) => {
919
+ let i = e(n, r), a = t(n, r);
920
+ return i || a;
921
+ };
922
+ }
923
+ function Te(e, t, n) {
924
+ let r = O(e), i = O(t), a = new E(r + i);
925
+ return (e) => {
926
+ if (a.push(D(e)), a.given < r + i + 1) return NaN;
927
+ let t = a.at(i);
928
+ if (Number.isNaN(t)) return NaN;
929
+ for (let e = 0; e <= r + i; e++) {
930
+ if (e === i) continue;
931
+ let r = a.at(e);
932
+ if (Number.isNaN(r) || !n(t, r)) return NaN;
933
+ }
934
+ return t;
935
+ };
936
+ }
937
+ function Ee(e, t) {
938
+ return Te(e, t, (e, t) => e > t);
939
+ }
940
+ function De(e, t) {
941
+ return Te(e, t, (e, t) => e < t);
942
+ }
943
+ function Oe() {
944
+ let e = _({ since: NaN });
945
+ return (t) => (e.since = t ? 0 : e.since + 1, e.since);
946
+ }
947
+ function ke(e = 0) {
948
+ let t = Math.max(0, Math.floor(e)), n = new E(t);
949
+ return (e, r) => (e && n.push(D(r)), n.at(t));
950
+ }
951
+ //#endregion
952
+ //#region src/ta/oscillators.ts
953
+ function Ae(e = 14) {
954
+ return k(je(e), NaN);
955
+ }
956
+ function je(e) {
957
+ let t = O(e), n = _({
958
+ prev: NaN,
959
+ count: 0,
960
+ gain: 0,
961
+ loss: 0
962
+ }), r = () => n.loss === 0 ? 100 : 100 - 100 / (1 + n.gain / n.loss);
963
+ return (e) => {
964
+ let i = D(e);
965
+ if (Number.isNaN(i)) return NaN;
966
+ if (Number.isNaN(n.prev)) return n.prev = i, NaN;
967
+ let a = i - n.prev;
968
+ n.prev = i;
969
+ let o = a > 0 ? a : 0, s = a < 0 ? -a : 0;
970
+ return n.count < t ? (n.gain += o, n.loss += s, n.count++, n.count < t ? NaN : (n.gain /= t, n.loss /= t, r())) : (n.gain = (n.gain * (t - 1) + o) / t, n.loss = (n.loss * (t - 1) + s) / t, r());
971
+ };
972
+ }
973
+ function Me(e = 12, t = 26, n = 9) {
974
+ return k(Ne(e, t, n), {
975
+ macd: NaN,
976
+ signal: NaN,
977
+ histogram: NaN
978
+ });
979
+ }
980
+ function Ne(e, t, n) {
981
+ let r = N(e), i = N(t), a = N(n);
982
+ return (e) => {
983
+ let t = r(e), n = i(e), o = Number.isNaN(t) || Number.isNaN(n) ? NaN : t - n, s = a(o);
984
+ return {
985
+ macd: o,
986
+ signal: s,
987
+ histogram: o - s
988
+ };
989
+ };
990
+ }
991
+ function Pe(e = 20, t = 2) {
992
+ return k(Fe(e, t), {
993
+ basis: NaN,
994
+ upper: NaN,
995
+ lower: NaN
996
+ });
997
+ }
998
+ function Fe(e, t) {
999
+ let n = j(e), r = _e(e);
1000
+ return (e) => {
1001
+ let i = n(e), a = t * r(e);
1002
+ return {
1003
+ basis: i,
1004
+ upper: i + a,
1005
+ lower: i - a
1006
+ };
1007
+ };
1008
+ }
1009
+ function Ie(e = 1) {
1010
+ let t = O(e), n = new E(t);
1011
+ return (e) => (n.push(D(e)), n.at(0) - n.at(t));
1012
+ }
1013
+ function Le(e = 10) {
1014
+ return k(Ie(e), NaN);
1015
+ }
1016
+ function Re(e = 12) {
1017
+ return k(ze(e), NaN);
1018
+ }
1019
+ function ze(e) {
1020
+ let t = O(e), n = new E(t);
1021
+ return (e) => {
1022
+ n.push(D(e));
1023
+ let r = n.at(0), i = n.at(t);
1024
+ return Number.isNaN(r) || Number.isNaN(i) ? NaN : i === 0 ? 0 : (r - i) / i * 100;
1025
+ };
1026
+ }
1027
+ //#endregion
1028
+ //#region src/ta/ranges.ts
1029
+ function Be() {
1030
+ let e = A(), t = _({ prevClose: NaN });
1031
+ return (n) => {
1032
+ let r = e(n);
1033
+ if (Number.isNaN(r.close)) return NaN;
1034
+ let i = r.high - r.low, a = t.prevClose;
1035
+ return t.prevClose = r.close, Number.isNaN(a) ? i : Math.max(i, Math.abs(r.high - a), Math.abs(r.low - a));
1036
+ };
1037
+ }
1038
+ function I(e = 14) {
1039
+ let t = O(e), n = Be(), r = _({
1040
+ count: 0,
1041
+ value: 0
1042
+ });
1043
+ return (e) => {
1044
+ let i = n(e);
1045
+ return Number.isNaN(i) ? NaN : r.count < t ? (r.value += i, r.count++, r.count < t ? NaN : (r.value /= t, r.value)) : (r.value = (r.value * (t - 1) + i) / t, r.value);
1046
+ };
1047
+ }
1048
+ function Ve(e = 3, t = 10) {
1049
+ let n = I(O(t)), r = _({
1050
+ prevClose: NaN,
1051
+ upper: 0,
1052
+ lower: 0,
1053
+ line: 0
1054
+ }), i = A();
1055
+ return (t) => {
1056
+ let a = n(t), o = i(t), s = Number.isNaN(r.prevClose) ? o.close : r.prevClose;
1057
+ if (r.prevClose = o.close, Number.isNaN(a)) return {
1058
+ value: NaN,
1059
+ trend: NaN
1060
+ };
1061
+ let c = (o.high + o.low) / 2, l = c + e * a, u = c - e * a, d = l < r.upper || s > r.upper ? l : r.upper, f = u > r.lower || s < r.lower ? u : r.lower, p = r.line === r.upper ? o.close <= d ? d : f : o.close >= f ? f : d;
1062
+ return r.upper = d, r.lower = f, r.line = p, {
1063
+ value: p,
1064
+ trend: p === f ? 1 : -1
1065
+ };
1066
+ };
1067
+ }
1068
+ function L(e, t) {
1069
+ let n = O(e), r = new E(n);
1070
+ return (e) => {
1071
+ if (r.push(D(e)), r.given < n) return NaN;
1072
+ let i = r.at(0);
1073
+ for (let e = 0; e < n; e++) {
1074
+ let n = r.at(e);
1075
+ if (Number.isNaN(n)) return NaN;
1076
+ t(n, i) && (i = n);
1077
+ }
1078
+ return i;
1079
+ };
1080
+ }
1081
+ function He(e) {
1082
+ return L(e, (e, t) => e > t);
1083
+ }
1084
+ function Ue(e) {
1085
+ return L(e, (e, t) => e < t);
1086
+ }
1087
+ //#endregion
1088
+ //#region src/ta/moves.ts
1089
+ function We(e) {
1090
+ let t = O(e), n = new E(t), r = new E(t);
1091
+ return (e, i, a) => {
1092
+ n.push(D(i)), r.push(D(a));
1093
+ let o = P(n, t), s = P(r, t), c = D(e);
1094
+ if (!o || !s || Number.isNaN(c)) return NaN;
1095
+ let l = Math.max(...o), u = Math.min(...s);
1096
+ return l === u ? 50 : (c - u) / (l - u) * 100;
1097
+ };
1098
+ }
1099
+ function Ge(e) {
1100
+ let t = O(e), n = new E(t + 1), r = new E(t + 1);
1101
+ return (e, i) => {
1102
+ n.push(D(e)), r.push(D(i));
1103
+ let a = P(n, t + 1), o = P(r, t + 1);
1104
+ if (!a || !o) return NaN;
1105
+ let s = 0, c = 0;
1106
+ for (let e = 1; e <= t; e++) a[e] > a[e - 1] ? s += a[e] * o[e] : a[e] < a[e - 1] && (c += a[e] * o[e]);
1107
+ return c === 0 ? 100 : 100 - 100 / (1 + s / c);
1108
+ };
1109
+ }
1110
+ function Ke() {
1111
+ let e = _({
1112
+ value: 0,
1113
+ prev: NaN
1114
+ });
1115
+ return (t, n) => {
1116
+ let r = D(t);
1117
+ if (Number.isNaN(r)) return NaN;
1118
+ let i = e.prev;
1119
+ if (e.prev = r, Number.isNaN(i)) return e.value;
1120
+ let a = Number.isFinite(n) ? n : 0;
1121
+ return r > i ? e.value += a : r < i && (e.value -= a), e.value;
1122
+ };
1123
+ }
1124
+ function qe(e = .02, t = .02, n = .2) {
1125
+ let r = A(), i = _({
1126
+ bars: 0,
1127
+ up: 0,
1128
+ af: 0,
1129
+ ep: 0,
1130
+ sar: 0,
1131
+ high1: 0,
1132
+ low1: 0,
1133
+ high2: 0,
1134
+ low2: 0,
1135
+ close1: 0
1136
+ });
1137
+ return (a) => {
1138
+ let o = r(a);
1139
+ return Number.isNaN(o.close) ? NaN : (i.bars++, i.bars === 1 ? (i.high1 = o.high, i.low1 = o.low, i.close1 = o.close, NaN) : (i.bars === 2 && (i.up = +(o.close > i.close1), i.af = e, i.ep = i.up ? i.high1 : i.low1, i.sar = i.up ? i.low1 : i.high1), i.sar += i.af * (i.ep - i.sar), i.up ? (i.sar = Math.min(i.sar, i.low1), i.bars > 2 && (i.sar = Math.min(i.sar, i.low2)), o.low < i.sar ? (i.up = 0, i.sar = i.ep, i.ep = o.low, i.af = e) : o.high > i.ep && (i.ep = o.high, i.af = Math.min(i.af + t, n))) : (i.sar = Math.max(i.sar, i.high1), i.bars > 2 && (i.sar = Math.max(i.sar, i.high2)), o.high > i.sar ? (i.up = 1, i.sar = i.ep, i.ep = o.high, i.af = e) : o.low < i.ep && (i.ep = o.low, i.af = Math.min(i.af + t, n))), i.high2 = i.high1, i.low2 = i.low1, i.high1 = o.high, i.low1 = o.low, i.sar));
1140
+ };
1141
+ }
1142
+ function R(e, t) {
1143
+ let n = O(e), r = new E(n);
1144
+ return (e) => {
1145
+ r.push(D(e));
1146
+ let i = P(r, n);
1147
+ if (!i) return NaN;
1148
+ let a = n - 1;
1149
+ for (let e = n - 2; e >= 0; e--) t(i[e], i[a]) && (a = e);
1150
+ return a - (n - 1);
1151
+ };
1152
+ }
1153
+ function Je(e) {
1154
+ return R(e, (e, t) => e > t);
1155
+ }
1156
+ function Ye(e) {
1157
+ return R(e, (e, t) => e < t);
1158
+ }
1159
+ function z(e, t) {
1160
+ let n = O(e), r = new E(n + 1);
1161
+ return (e) => {
1162
+ r.push(D(e));
1163
+ let i = P(r, n + 1);
1164
+ if (!i) return !1;
1165
+ for (let e = 0; e < n; e++) if (!t(i[n], i[e])) return !1;
1166
+ return !0;
1167
+ };
1168
+ }
1169
+ function Xe(e) {
1170
+ return z(e, (e, t) => e > t);
1171
+ }
1172
+ function Ze(e) {
1173
+ return z(e, (e, t) => e < t);
1174
+ }
1175
+ //#endregion
1176
+ //#region src/ta/statistics.ts
1177
+ function B(e, t) {
1178
+ let n = O(e), r = new E(n);
1179
+ return (e) => {
1180
+ r.push(D(e));
1181
+ let i = P(r, n);
1182
+ return i ? t(i, n) : NaN;
1183
+ };
1184
+ }
1185
+ var V = 5e3, H = (e) => e.reduce((e, t) => e + t, 0), U = (e) => [...e].sort((e, t) => e - t);
1186
+ function Qe(e) {
1187
+ return B(e, H);
958
1188
  }
959
1189
  function $e() {
960
- const n = b({ value: 0, prev: Number.NaN });
961
- return (t, e) => {
962
- const s = h(t);
963
- if (Number.isNaN(s)) return Number.NaN;
964
- const r = n.prev;
965
- if (n.prev = s, Number.isNaN(r)) return n.value;
966
- const i = Number.isFinite(e) ? e : 0;
967
- return s > r ? n.value += i : s < r && (n.value -= i), n.value;
968
- };
969
- }
970
- function Ce(n = 0.02, t = 0.02, e = 0.2) {
971
- const s = q(), r = b({ bars: 0, up: 0, af: 0, ep: 0, sar: 0, high1: 0, low1: 0, high2: 0, low2: 0, close1: 0 });
972
- return (i) => {
973
- const o = s(i);
974
- return Number.isNaN(o.close) ? Number.NaN : (r.bars++, r.bars === 1 ? (r.high1 = o.high, r.low1 = o.low, r.close1 = o.close, Number.NaN) : (r.bars === 2 && (r.up = o.close > r.close1 ? 1 : 0, r.af = n, r.ep = r.up ? r.high1 : r.low1, r.sar = r.up ? r.low1 : r.high1), r.sar += r.af * (r.ep - r.sar), r.up ? (r.sar = Math.min(r.sar, r.low1), r.bars > 2 && (r.sar = Math.min(r.sar, r.low2)), o.low < r.sar ? (r.up = 0, r.sar = r.ep, r.ep = o.low, r.af = n) : o.high > r.ep && (r.ep = o.high, r.af = Math.min(r.af + t, e))) : (r.sar = Math.max(r.sar, r.high1), r.bars > 2 && (r.sar = Math.max(r.sar, r.high2)), o.high > r.sar ? (r.up = 1, r.sar = r.ep, r.ep = o.high, r.af = n) : o.low < r.ep && (r.ep = o.low, r.af = Math.min(r.af + t, e))), r.high2 = r.high1, r.low2 = r.low1, r.high1 = o.high, r.low1 = o.low, r.sar));
975
- };
976
- }
977
- function It(n, t) {
978
- const e = f(n), s = new p(e);
979
- return (r) => {
980
- s.push(h(r));
981
- const i = g(s, e);
982
- if (!i) return Number.NaN;
983
- let o = e - 1;
984
- for (let u = e - 2; u >= 0; u--) t(i[u], i[o]) && (o = u);
985
- return o - (e - 1);
986
- };
987
- }
988
- function Ae(n) {
989
- return It(n, (t, e) => t > e);
990
- }
991
- function Le(n) {
992
- return It(n, (t, e) => t < e);
993
- }
994
- function Et(n, t) {
995
- const e = f(n), s = new p(e + 1);
996
- return (r) => {
997
- s.push(h(r));
998
- const i = g(s, e + 1);
999
- if (!i) return !1;
1000
- for (let o = 0; o < e; o++) if (!t(i[e], i[o])) return !1;
1001
- return !0;
1002
- };
1003
- }
1004
- function Te(n) {
1005
- return Et(n, (t, e) => t > e);
1006
- }
1007
- function Fe(n) {
1008
- return Et(n, (t, e) => t < e);
1009
- }
1010
- function M(n, t) {
1011
- const e = f(n), s = new p(e);
1012
- return (r) => {
1013
- s.push(h(r));
1014
- const i = g(s, e);
1015
- return i ? t(i, e) : Number.NaN;
1016
- };
1017
- }
1018
- const $t = 5e3, A = (n) => n.reduce((t, e) => t + e, 0), tt = (n) => [...n].sort((t, e) => t - e);
1019
- function Be(n) {
1020
- return M(n, A);
1021
- }
1022
- function je() {
1023
- const n = b({ total: 0, seen: 0 });
1024
- return (t) => {
1025
- const e = h(t);
1026
- return Number.isNaN(e) || (n.total += e, n.seen = 1), n.seen ? n.total : Number.NaN;
1027
- };
1028
- }
1029
- function Re(n) {
1030
- return M(n, (t, e) => {
1031
- const s = tt(t), r = Math.floor(e / 2);
1032
- return e % 2 === 1 ? s[r] : (s[r - 1] + s[r]) / 2;
1033
- });
1034
- }
1035
- function Ct(n) {
1036
- return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : Number.NaN;
1037
- }
1038
- function _e(n, t) {
1039
- const e = Ct(t);
1040
- return M(n, (s, r) => {
1041
- if (Number.isNaN(e)) return Number.NaN;
1042
- const i = Math.max(1, Math.ceil(Math.round(e * r * 1e6) / 1e8));
1043
- return tt(s)[i - 1];
1044
- });
1045
- }
1046
- function We(n, t) {
1047
- const e = Ct(t);
1048
- return M(n, (s, r) => {
1049
- if (Number.isNaN(e)) return Number.NaN;
1050
- const i = tt(s), o = e * (r - 1) / 100, u = Math.floor(o);
1051
- return i[u] + (i[Math.ceil(o)] - i[u]) * (o - u);
1052
- });
1053
- }
1054
- function Ke(n) {
1055
- const t = f(n), e = new p(t + 1);
1056
- return (s) => {
1057
- e.push(h(s));
1058
- const r = g(e, t + 1);
1059
- if (!r) return Number.NaN;
1060
- const i = r[t];
1061
- let o = 0;
1062
- for (let u = 0; u < t; u++) r[u] <= i && o++;
1063
- return o / t * 100;
1064
- };
1065
- }
1066
- function ze(n) {
1067
- return M(n, (t, e) => {
1068
- const s = A(t) / e;
1069
- return A(t.map((r) => Math.abs(r - s))) / e;
1070
- });
1071
- }
1072
- function De(n) {
1073
- return M(n, (t, e) => {
1074
- let s = 0, r = 0;
1075
- for (const o of t)
1076
- s += o, r += o * o;
1077
- const i = s / e;
1078
- return Math.max(0, r / e - i * i);
1079
- });
1080
- }
1081
- function Pe(n) {
1082
- const t = f(n), e = new p(t), s = new p(t);
1083
- return (r, i) => {
1084
- e.push(h(r)), s.push(h(i));
1085
- const o = g(e, t), u = g(s, t);
1086
- if (!o || !u) return Number.NaN;
1087
- const c = A(o) / t, a = A(u) / t;
1088
- let l = 0, m = 0, v = 0;
1089
- for (let N = 0; N < t; N++)
1090
- l += (o[N] - c) * (u[N] - a), m += (o[N] - c) ** 2, v += (u[N] - a) ** 2;
1091
- return m > 0 && v > 0 ? l / Math.sqrt(m * v) : Number.NaN;
1092
- };
1093
- }
1094
- function Ue(n, t = 0) {
1095
- const e = Math.max(-1e3, Math.round(Number.isFinite(t) ? t : 0));
1096
- return M(Math.min($t, Math.max(2, f(n))), (s, r) => {
1097
- const i = r * (r - 1) / 2, o = (r - 1) * r * (2 * r - 1) / 6, u = r * o - i * i;
1098
- let c = 0, a = 0;
1099
- for (let m = 0; m < r; m++)
1100
- c += s[m], a += m * s[m];
1101
- const l = (r * a - i * c) / u;
1102
- return (c - l * i) / r + l * (r - 1 - e);
1103
- });
1104
- }
1105
- function Ze(n, t = 0.85, e = 6) {
1106
- const s = Math.min($t, f(n)), r = Math.min(1, Math.max(0, Number.isFinite(t) ? t : 0.85)) * (s - 1), i = s / Math.max(0.5, Number.isFinite(e) ? e : 6), o = Array.from({ length: s }, (c, a) => Math.exp(-((a - r) ** 2) / (2 * i * i))), u = A(o);
1107
- return M(s, (c) => {
1108
- let a = 0;
1109
- for (let l = 0; l < s; l++) a += o[l] * c[l];
1110
- return a / u;
1111
- });
1112
- }
1113
- function Ve() {
1114
- return M(4, (n) => (n[0] + 2 * n[1] + 2 * n[2] + n[3]) / 6);
1115
- }
1116
- const ns = {
1117
- sma: dt,
1118
- ema: R,
1119
- rma: oe,
1120
- wma: _,
1121
- vwma: ce,
1122
- hma: ue,
1123
- stdev: gt,
1124
- bb: we,
1125
- rsi: Ne,
1126
- macd: be,
1127
- change: Mt,
1128
- mom: ye,
1129
- roc: ke,
1130
- tr: xt,
1131
- atr: St,
1132
- supertrend: xe,
1133
- highest: Se,
1134
- lowest: Oe,
1135
- crossover: vt,
1136
- crossunder: yt,
1137
- cross: le,
1138
- pivothigh: he,
1139
- pivotlow: me,
1140
- barssince: fe,
1141
- valuewhen: pe,
1142
- sum: Be,
1143
- cum: je,
1144
- median: Re,
1145
- percentileNearestRank: _e,
1146
- percentileLinearInterpolation: We,
1147
- percentrank: Ke,
1148
- dev: ze,
1149
- variance: De,
1150
- correlation: Pe,
1151
- linreg: Ue,
1152
- alma: Ze,
1153
- swma: Ve,
1154
- stoch: Ie,
1155
- mfi: Ee,
1156
- obv: $e,
1157
- sar: Ce,
1158
- highestbars: Ae,
1159
- lowestbars: Le,
1160
- rising: Te,
1161
- falling: Fe
1162
- }, V = 1, $ = (n) => `p${n}`, At = (n) => `s${n}`, K = (n) => `bg${n}`, z = (n) => `bc${n}`, C = (n) => `${n}c`, Lt = (n) => `f${n}c`, Tt = (n) => `a${n}`;
1163
- function j(n, t, e, s) {
1164
- const r = e[s];
1165
- r > 0 && (n[t] = r - 1);
1166
- }
1167
- function Ft(n, t) {
1168
- const e = {};
1169
- n.plots.forEach((s, r) => {
1170
- const i = s.values[t];
1171
- Number.isFinite(i) && (e[$(r)] = i, j(e, C($(r)), s.colors, t));
1172
- }), n.shapes.forEach((s, r) => {
1173
- s.on[t] === 1 && (e[At(r)] = V);
1174
- }), n.backgrounds.forEach((s, r) => {
1175
- s.colors[t] !== 0 && (e[K(r)] = V, j(e, C(K(r)), s.colors, t));
1176
- }), n.fills.forEach((s, r) => j(e, Lt(r), s.colors, t)), n.barColors.forEach((s, r) => {
1177
- s[t] !== 0 && (e[z(r)] = V, j(e, C(z(r)), s, t));
1178
- }), n.alertConditions.forEach((s, r) => {
1179
- e[Tt(r)] = s.on[t] === 1 ? 1 : 0;
1180
- });
1181
- for (const s in e) return e;
1182
- return null;
1183
- }
1184
- const ct = ["#2962ff", "#ff6d00", "#00bfa5", "#d500f9", "#ffd600", "#ef5350", "#26a69a", "#8d6e63"], Xe = 0.15;
1185
- function Ge(n, t) {
1186
- return t || n === "top" || n === "bottom" ? n : n === "aboveBar" ? "top" : "bottom";
1187
- }
1188
- function Bt(n, t) {
1189
- return {
1190
- ...t ? { limits: t } : {},
1191
- ...n.exchangeTimeZone ? { exchangeTimeZone: n.exchangeTimeZone } : {},
1192
- ...n.sessionStart !== void 0 ? { sessionStart: n.sessionStart } : {}
1193
- };
1194
- }
1195
- function H(n) {
1196
- return JSON.stringify(Object.keys(n).sort().map((t) => [t, n[t]]));
1197
- }
1198
- function He(n) {
1199
- const t = [];
1200
- let e = 0;
1201
- const s = (a) => (t.push(a ?? ct[e++ % ct.length]), t.length - 1), r = n.plots.map((a, l) => ({
1202
- key: $(l),
1203
- title: a.title,
1204
- color: s(a.color),
1205
- paletteBy: C($(l)),
1206
- ...a.kind !== "line" ? { kind: a.kind } : {},
1207
- ...a.width !== void 0 ? { width: a.width } : {}
1208
- })), i = n.shapes.map((a, l) => ({
1209
- key: At(l),
1210
- title: a.title,
1211
- color: s(a.color),
1212
- kind: "markers",
1213
- shape: a.shape,
1214
- position: Ge(a.position, n.overlay)
1215
- })), o = n.backgrounds.map((a, l) => ({
1216
- key: K(l),
1217
- title: a.title,
1218
- color: s(void 0),
1219
- kind: "background",
1220
- paletteBy: C(K(l)),
1221
- // Its colours carry their own strength, as a script gives them.
1222
- opacity: 1
1223
- })), u = n.fills.map((a, l) => {
1224
- const m = t[r[a.between[0]].color];
1225
- return {
1226
- between: [$(a.between[0]), $(a.between[1])],
1227
- color: s(a.color ?? Wt(m, Xe)),
1228
- paletteBy: Lt(l),
1229
- // Its colours carry their own strength.
1230
- opacity: 1
1231
- };
1232
- }), c = Array.from({ length: n.barColors }, (a, l) => ({
1233
- key: z(l),
1234
- title: "Bars",
1235
- color: s(void 0),
1236
- kind: "barColor",
1237
- paletteBy: C(z(l))
1238
- }));
1239
- return { plots: [...r, ...i, ...o, ...c], fills: u, colors: t };
1240
- }
1241
- function jt(n) {
1242
- const t = new D(n).declarations, { plots: e, fills: s, colors: r } = He(t), i = n.inputs ?? {}, o = Object.keys(i);
1243
- return {
1244
- id: n.id,
1245
- name: n.name,
1246
- placement: t.overlay ? "overlay" : "panel",
1247
- defaultConfig: Object.fromEntries(o.map((u) => [u, i[u].default])),
1248
- plots: e,
1249
- ...s && s.length > 0 ? { fills: s } : {},
1250
- ...n.shortName !== void 0 ? { shortName: n.shortName } : {},
1251
- ...t.levels.length > 0 ? { levels: t.levels.map((u) => u.price) } : {},
1252
- ...Je(t.levels),
1253
- ...o.length > 0 ? { inputs: Object.fromEntries(o.map((u) => {
1254
- const { default: c, ...a } = i[u];
1255
- return [u, a];
1256
- })) } : {},
1257
- ...r.length > 0 ? { defaultStyle: { colors: r } } : {},
1258
- ...t.alertConditions.length > 0 ? { alertConditions: t.alertConditions.map((u, c) => ({ key: Tt(c), ...u })) } : {},
1259
- // A higher interval of days is cut on the exchange's clock: a new zone or day start runs it again.
1260
- readsExchangeTimeZone: !0
1261
- };
1262
- }
1263
- class Ye extends ft {
1264
- constructor(t, e = {}) {
1265
- super(), this.script = t, this.options = e, this.descriptor = jt(t);
1266
- }
1267
- descriptor;
1268
- runs = /* @__PURE__ */ new WeakMap();
1269
- calculate(t, e) {
1270
- const s = new D(this.script, e.params, Bt(e, this.options.limits));
1271
- s.load(t);
1272
- const r = { values: new pt(), series: new Array(t.length).fill(null), meta: {} };
1273
- return this.writeFrom(r, t, s, 0), this.runs.set(r, { run: s, params: H(e.params) }), r;
1274
- }
1275
- /** Runs the live bar again on a tick, and new bars as they come; older bars changed, or other inputs, ask for a full calculate. */
1276
- update(t, e, s, r) {
1277
- const i = this.runs.get(s);
1278
- if (!i || i.params !== H(e.params) || !this.canResume(t, s, r)) return null;
1279
- const { run: o } = i;
1280
- if (r < o.length - 1 || t.length < o.length) return null;
1281
- for (let u = r; u < t.length; u++)
1282
- u === o.length - 1 ? o.tick(t[u]) : o.next(t[u]);
1283
- return s.series.length = t.length, this.writeFrom(s, t, o, r), s;
1284
- }
1285
- writeFrom(t, e, s, r) {
1286
- const i = s.output;
1287
- t.palette = i.palette, t.drawings = i.drawings, t.meta = { ...t.meta, errors: i.errors };
1288
- for (let o = r; o < e.length; o++) this.writePoint(t, e, o, Ft(i, o));
1289
- }
1290
- }
1291
- function Je(n) {
1292
- const t = n.filter((e) => e.color !== void 0 || e.lineStyle !== void 0 || e.title !== void 0).map(({ price: e, color: s, lineStyle: r, title: i }) => ({
1293
- price: e,
1294
- ...s !== void 0 ? { color: s } : {},
1295
- ...r !== void 0 ? { lineStyle: r } : {},
1296
- ...i !== void 0 ? { title: i } : {}
1297
- }));
1298
- return t.length > 0 ? { levelLooks: t } : {};
1299
- }
1300
- function is(n, t = {}) {
1301
- return t.limits && Q(t.limits), new Ye(n, t);
1302
- }
1303
- const Qe = 5e3;
1304
- function X(n) {
1305
- const t = n[n.length - 1];
1306
- return t ? `${n.length}|${t.time}|${t.open}|${t.high}|${t.low}|${t.close}|${t.volume ?? 0}` : "0";
1307
- }
1308
- function G(n) {
1309
- return `${H(n.params)}|${n.exchangeTimeZone ?? ""}|${n.sessionStart ?? ""}`;
1310
- }
1311
- function qe(n) {
1312
- return { values: new pt(), series: new Array(n).fill(null), meta: { errors: [] } };
1313
- }
1314
- function lt(n, t) {
1315
- const e = n.series;
1316
- for (e.length > t && (e.length = t); e.length < t; ) e.push(null);
1317
- return n;
1318
- }
1319
- class ts extends ft {
1320
- constructor(t, e) {
1321
- super(), this.script = t, this.options = e, this.descriptor = jt(t), this.timeoutMs = e.timeoutMs ?? Qe;
1322
- }
1323
- descriptor;
1324
- worker = null;
1325
- hosts = /* @__PURE__ */ new Set();
1326
- /** Each instance's run, by its config: a config is one instance on one chart. */
1327
- entries = /* @__PURE__ */ new WeakMap();
1328
- /** The runs in the worker, by number. */
1329
- runs = /* @__PURE__ */ new Map();
1330
- /** The run of each request not yet answered, in the order sent: the worker answers in that order. */
1331
- pending = [];
1332
- /** The instances whose answers came this task: the chart is asked once for each. */
1333
- due = /* @__PURE__ */ new Set();
1334
- nextRun = 1;
1335
- nextSeq = 1;
1336
- timer = null;
1337
- timeoutMs;
1338
- connect(t) {
1339
- return this.hosts.add(t), () => {
1340
- this.hosts.delete(t);
1341
- };
1342
- }
1343
- /** The instance is gone: its run goes, and the worker once it runs nothing. */
1344
- release(t) {
1345
- const e = this.entries.get(t);
1346
- e && (this.entries.delete(t), this.drop(e), this.runs.size === 0 && this.stopWorker());
1347
- }
1348
- /**
1349
- * The worker's output for these bars when it has come, or is coming (a
1350
- * tick sent meanwhile); otherwise the bars are sent to be run, and what
1351
- * was drawn stays till the worker answers.
1352
- */
1353
- calculate(t, e) {
1354
- const s = this.entries.get(e);
1355
- return s && s.key === G(e) && s.bars === t && (s.stopped || s.sent !== "" && s.sent === X(t)) ? s.output : this.load(t, e, s).output;
1356
- }
1357
- /** A tick, or new bars, sent to the worker one bar each; the output stays as it is till the answer comes. */
1358
- update(t, e, s, r) {
1359
- const i = this.entries.get(e);
1360
- if (!i || i.output !== s || i.stopped || i.key !== G(e) || i.bars !== t || i.sent === "") return null;
1361
- if (r < i.length - 1 || r > i.length || t.length < i.length)
1362
- return i.sent = "", null;
1363
- for (let o = r; o < t.length; o++) {
1364
- const u = o === i.length - 1 ? "tick" : "next";
1365
- this.send(i, { type: u, run: i.run, seq: this.nextSeq++, bar: t[o] }), u === "next" && (i.length = o + 1);
1366
- }
1367
- return lt(s, t.length), i.sent = X(t), s;
1368
- }
1369
- load(t, e, s) {
1370
- s && this.drop(s);
1371
- const r = {
1372
- run: this.nextRun++,
1373
- config: e,
1374
- key: G(e),
1375
- bars: t,
1376
- output: s ? lt(s.output, t.length) : qe(t.length),
1377
- length: t.length,
1378
- sent: X(t),
1379
- stopped: !1
1380
- };
1381
- return this.entries.set(e, r), this.runs.set(r.run, r), this.send(r, {
1382
- type: "load",
1383
- run: r.run,
1384
- seq: this.nextSeq++,
1385
- script: this.script.id,
1386
- params: { ...e.params },
1387
- options: Bt(e, this.options.limits),
1388
- bars: t.map((i) => ({ ...i }))
1389
- }), r;
1390
- }
1391
- /** Forget a run here and in the worker. */
1392
- drop(t) {
1393
- this.runs.delete(t.run) && this.worker?.postMessage({ type: "drop", run: t.run });
1394
- }
1395
- send(t, e) {
1396
- this.pending.push(t.run), this.ensureWorker().postMessage(e), this.pending.length === 1 && this.armTimer();
1397
- }
1398
- ensureWorker() {
1399
- if (this.worker) return this.worker;
1400
- const t = this.options.spawn();
1401
- return t.addEventListener("message", (e) => {
1402
- this.worker === t && this.receive(e.data);
1403
- }), this.worker = t, t;
1404
- }
1405
- stopWorker() {
1406
- this.timer && clearTimeout(this.timer), this.timer = null, this.pending = [], this.worker?.terminate(), this.worker = null;
1407
- }
1408
- /** The oldest request has `timeoutMs` from now to be answered. */
1409
- armTimer() {
1410
- this.timer && clearTimeout(this.timer), this.timer = setTimeout(() => this.timedOut(), this.timeoutMs);
1411
- }
1412
- receive(t) {
1413
- this.pending.shift(), this.timer && clearTimeout(this.timer), this.timer = null, this.pending.length > 0 && this.armTimer();
1414
- const e = this.runs.get(t.run);
1415
- e && (t.type === "patch" ? this.apply(e, t.from, t.points, t.palette, t.drawings, t.errors) : this.stop(e, { bar: Math.max(0, e.length - 1), message: t.message }), this.recompute(e));
1416
- }
1417
- apply(t, e, s, r, i, o) {
1418
- const u = t.output, c = u.series;
1419
- e === 0 && (u.values.clear(), c.fill(null));
1420
- for (let a = 0; a < s.length; a++) {
1421
- const l = e + a;
1422
- if (l >= t.bars.length) break;
1423
- for (; c.length <= l; ) c.push(null);
1424
- this.writePoint(u, t.bars, l, s[a]);
1425
- }
1426
- u.palette = r, u.drawings = i ?? [], u.meta = { ...u.meta, errors: o };
1427
- }
1428
- /**
1429
- * The worker did not answer in time. It answers in order, so it hung on
1430
- * the oldest request: that run is stopped, the worker with it, and the
1431
- * other runs load again in a new one.
1432
- */
1433
- timedOut() {
1434
- this.timer = null;
1435
- const t = this.pending[0];
1436
- this.stopWorker();
1437
- const e = [...this.runs.values()];
1438
- this.runs.clear();
1439
- for (const s of e)
1440
- s.run === t ? this.stop(s, { bar: Math.max(0, s.length - 1), message: `the script did not answer within ${this.timeoutMs} ms, and was stopped`, limit: "time" }) : s.sent = "", this.recompute(s);
1441
- }
1442
- stop(t, e) {
1443
- t.stopped = !0, this.runs.delete(t.run), t.output.meta = { ...t.output.meta, errors: [e] };
1444
- }
1445
- /** Ask the chart to compute the instance again, once for all the answers that came this task. */
1446
- recompute(t) {
1447
- this.due.size === 0 && queueMicrotask(() => this.flush()), this.due.add(t);
1448
- }
1449
- flush() {
1450
- const t = [...this.due];
1451
- this.due.clear();
1452
- for (const e of t)
1453
- if (this.entries.get(e.config) === e)
1454
- for (const s of this.hosts) s.recompute(e.config);
1455
- }
1456
- }
1457
- function os(n, t) {
1458
- if (t.limits && Q(t.limits), t.timeoutMs !== void 0 && !(t.timeoutMs > 0)) throw new RangeError(`scriptWorkerIndicator: timeoutMs must be a positive number, not ${t.timeoutMs}`);
1459
- return new ts(n, t);
1460
- }
1461
- function ht(n) {
1462
- return n instanceof Error ? n.message : String(n);
1463
- }
1464
- function mt(n, t, e, s) {
1465
- const r = e.output, i = [];
1466
- for (let o = s; o < r.length; o++) i.push(Ft(r, o));
1467
- return {
1468
- type: "patch",
1469
- run: n,
1470
- seq: t,
1471
- from: s,
1472
- points: i,
1473
- palette: [...r.palette],
1474
- drawings: [...r.drawings],
1475
- errors: [...r.errors]
1476
- };
1477
- }
1478
- function es(n, t) {
1479
- const e = new Map(n.map((i) => [i.id, i])), s = /* @__PURE__ */ new Map(), r = (i, o, u) => t({ type: "failed", run: i, seq: o, message: u });
1480
- return (i) => {
1481
- if (i.type === "drop") {
1482
- s.delete(i.run);
1483
- return;
1484
- }
1485
- if (i.type === "load") {
1486
- s.delete(i.run);
1487
- const c = e.get(i.script);
1488
- if (!c) return r(i.run, i.seq, `no script '${i.script}' in this worker: give it to serveScripts`);
1489
- try {
1490
- const a = new D(c, i.params, i.options);
1491
- a.load(i.bars), s.set(i.run, a), t(mt(i.run, i.seq, a, 0));
1492
- } catch (a) {
1493
- r(i.run, i.seq, ht(a));
1494
- }
1495
- return;
1496
- }
1497
- const o = s.get(i.run);
1498
- if (!o) return r(i.run, i.seq, `no run ${i.run} here: load it first`);
1499
- const u = i.type === "tick" ? o.length - 1 : o.length;
1500
- try {
1501
- i.type === "tick" ? o.tick(i.bar) : o.next(i.bar), t(mt(i.run, i.seq, o, Math.max(0, u)));
1502
- } catch (c) {
1503
- s.delete(i.run), r(i.run, i.seq, ht(c));
1504
- }
1505
- };
1506
- }
1507
- function us(n, t = self) {
1508
- const e = es(n, (s) => t.postMessage(s));
1509
- t.addEventListener("message", (s) => e(s.data));
1510
- }
1511
- export {
1512
- it as DEFAULT_LIMITS,
1513
- W as ScriptLimitError,
1514
- D as ScriptRun,
1515
- es as createScriptHandler,
1516
- zt as defineScript,
1517
- is as scriptIndicator,
1518
- os as scriptWorkerIndicator,
1519
- us as serveScripts,
1520
- ns as ta
1190
+ let e = _({
1191
+ total: 0,
1192
+ seen: 0
1193
+ });
1194
+ return (t) => {
1195
+ let n = D(t);
1196
+ return Number.isNaN(n) || (e.total += n, e.seen = 1), e.seen ? e.total : NaN;
1197
+ };
1198
+ }
1199
+ function et(e) {
1200
+ return B(e, (e, t) => {
1201
+ let n = U(e), r = Math.floor(t / 2);
1202
+ return t % 2 == 1 ? n[r] : (n[r - 1] + n[r]) / 2;
1203
+ });
1204
+ }
1205
+ function W(e) {
1206
+ return Number.isFinite(e) ? Math.min(100, Math.max(0, e)) : NaN;
1207
+ }
1208
+ function tt(e, t) {
1209
+ let n = W(t);
1210
+ return B(e, (e, t) => {
1211
+ if (Number.isNaN(n)) return NaN;
1212
+ let r = Math.max(1, Math.ceil(Math.round(n * t * 1e6) / 1e8));
1213
+ return U(e)[r - 1];
1214
+ });
1215
+ }
1216
+ function nt(e, t) {
1217
+ let n = W(t);
1218
+ return B(e, (e, t) => {
1219
+ if (Number.isNaN(n)) return NaN;
1220
+ let r = U(e), i = n * (t - 1) / 100, a = Math.floor(i);
1221
+ return r[a] + (r[Math.ceil(i)] - r[a]) * (i - a);
1222
+ });
1223
+ }
1224
+ function rt(e) {
1225
+ let t = O(e), n = new E(t + 1);
1226
+ return (e) => {
1227
+ n.push(D(e));
1228
+ let r = P(n, t + 1);
1229
+ if (!r) return NaN;
1230
+ let i = r[t], a = 0;
1231
+ for (let e = 0; e < t; e++) r[e] <= i && a++;
1232
+ return a / t * 100;
1233
+ };
1234
+ }
1235
+ function it(e) {
1236
+ return B(e, (e, t) => {
1237
+ let n = H(e) / t;
1238
+ return H(e.map((e) => Math.abs(e - n))) / t;
1239
+ });
1240
+ }
1241
+ function at(e) {
1242
+ return B(e, (e, t) => {
1243
+ let n = 0, r = 0;
1244
+ for (let t of e) n += t, r += t * t;
1245
+ let i = n / t;
1246
+ return Math.max(0, r / t - i * i);
1247
+ });
1248
+ }
1249
+ function ot(e) {
1250
+ let t = O(e), n = new E(t), r = new E(t);
1251
+ return (e, i) => {
1252
+ n.push(D(e)), r.push(D(i));
1253
+ let a = P(n, t), o = P(r, t);
1254
+ if (!a || !o) return NaN;
1255
+ let s = H(a) / t, c = H(o) / t, l = 0, u = 0, d = 0;
1256
+ for (let e = 0; e < t; e++) l += (a[e] - s) * (o[e] - c), u += (a[e] - s) ** 2, d += (o[e] - c) ** 2;
1257
+ return u > 0 && d > 0 ? l / Math.sqrt(u * d) : NaN;
1258
+ };
1259
+ }
1260
+ function st(e, t = 0) {
1261
+ let n = Math.max(-1e3, Math.round(Number.isFinite(t) ? t : 0));
1262
+ return B(Math.min(V, Math.max(2, O(e))), (e, t) => {
1263
+ let r = t * (t - 1) / 2, i = t * ((t - 1) * t * (2 * t - 1) / 6) - r * r, a = 0, o = 0;
1264
+ for (let n = 0; n < t; n++) a += e[n], o += n * e[n];
1265
+ let s = (t * o - r * a) / i;
1266
+ return (a - s * r) / t + s * (t - 1 - n);
1267
+ });
1268
+ }
1269
+ function ct(e, t = .85, n = 6) {
1270
+ let r = Math.min(V, O(e)), i = Math.min(1, Math.max(0, Number.isFinite(t) ? t : .85)) * (r - 1), a = r / Math.max(.5, Number.isFinite(n) ? n : 6), o = Array.from({ length: r }, (e, t) => Math.exp(-((t - i) ** 2) / (2 * a * a))), s = H(o);
1271
+ return B(r, (e) => {
1272
+ let t = 0;
1273
+ for (let n = 0; n < r; n++) t += o[n] * e[n];
1274
+ return t / s;
1275
+ });
1276
+ }
1277
+ function lt() {
1278
+ return B(4, (e) => (e[0] + 2 * e[1] + 2 * e[2] + e[3]) / 6);
1279
+ }
1280
+ //#endregion
1281
+ //#region src/ta/index.ts
1282
+ var ut = {
1283
+ sma: j,
1284
+ ema: N,
1285
+ rma: ge,
1286
+ wma: F,
1287
+ vwma: be,
1288
+ hma: ve,
1289
+ stdev: _e,
1290
+ bb: Pe,
1291
+ rsi: Ae,
1292
+ macd: Me,
1293
+ change: Ie,
1294
+ mom: Le,
1295
+ roc: Re,
1296
+ tr: Be,
1297
+ atr: I,
1298
+ supertrend: Ve,
1299
+ highest: He,
1300
+ lowest: Ue,
1301
+ crossover: Se,
1302
+ crossunder: Ce,
1303
+ cross: we,
1304
+ pivothigh: Ee,
1305
+ pivotlow: De,
1306
+ barssince: Oe,
1307
+ valuewhen: ke,
1308
+ sum: Qe,
1309
+ cum: $e,
1310
+ median: et,
1311
+ percentileNearestRank: tt,
1312
+ percentileLinearInterpolation: nt,
1313
+ percentrank: rt,
1314
+ dev: it,
1315
+ variance: at,
1316
+ correlation: ot,
1317
+ linreg: st,
1318
+ alma: ct,
1319
+ swma: lt,
1320
+ stoch: We,
1321
+ mfi: Ge,
1322
+ obv: Ke,
1323
+ sar: qe,
1324
+ highestbars: Je,
1325
+ lowestbars: Ye,
1326
+ rising: Xe,
1327
+ falling: Ze
1328
+ }, G = 1, K = (e) => `p${e}`, dt = (e) => `s${e}`, q = (e) => `bg${e}`, J = (e) => `bc${e}`, Y = (e) => `${e}c`, ft = (e) => `f${e}c`, pt = (e) => `a${e}`;
1329
+ function X(e, t, n, r) {
1330
+ let i = n[r];
1331
+ i > 0 && (e[t] = i - 1);
1332
+ }
1333
+ function mt(e, t) {
1334
+ let n = {};
1335
+ e.plots.forEach((e, r) => {
1336
+ let i = e.values[t];
1337
+ Number.isFinite(i) && (n[K(r)] = i, X(n, Y(K(r)), e.colors, t));
1338
+ }), e.shapes.forEach((e, r) => {
1339
+ e.on[t] === 1 && (n[dt(r)] = G);
1340
+ }), e.backgrounds.forEach((e, r) => {
1341
+ e.colors[t] !== 0 && (n[q(r)] = G, X(n, Y(q(r)), e.colors, t));
1342
+ }), e.fills.forEach((e, r) => X(n, ft(r), e.colors, t)), e.barColors.forEach((e, r) => {
1343
+ e[t] !== 0 && (n[J(r)] = G, X(n, Y(J(r)), e, t));
1344
+ }), e.alertConditions.forEach((e, r) => {
1345
+ n[pt(r)] = +(e.on[t] === 1);
1346
+ });
1347
+ for (let e in n) return n;
1348
+ return null;
1349
+ }
1350
+ //#endregion
1351
+ //#region src/scriptIndicator.ts
1352
+ var ht = [
1353
+ "#2962ff",
1354
+ "#ff6d00",
1355
+ "#00bfa5",
1356
+ "#d500f9",
1357
+ "#ffd600",
1358
+ "#ef5350",
1359
+ "#26a69a",
1360
+ "#8d6e63"
1361
+ ], gt = .15;
1362
+ function _t(e, t) {
1363
+ return t || e === "top" || e === "bottom" ? e : e === "aboveBar" ? "top" : "bottom";
1364
+ }
1365
+ function vt(e, t) {
1366
+ return {
1367
+ ...t ? { limits: t } : {},
1368
+ ...e.exchangeTimeZone ? { exchangeTimeZone: e.exchangeTimeZone } : {},
1369
+ ...e.sessionStart === void 0 ? {} : { sessionStart: e.sessionStart },
1370
+ ...e.interval === void 0 ? {} : { interval: e.interval }
1371
+ };
1372
+ }
1373
+ function Z(e) {
1374
+ return JSON.stringify(Object.keys(e).sort().map((t) => [t, e[t]]));
1375
+ }
1376
+ function yt(t) {
1377
+ let n = [], r = 0, i = (e) => (n.push(e ?? ht[r++ % ht.length]), n.length - 1), a = t.plots.map((e, t) => ({
1378
+ key: K(t),
1379
+ title: e.title,
1380
+ color: i(e.color),
1381
+ paletteBy: Y(K(t)),
1382
+ ...e.kind === "line" ? {} : { kind: e.kind },
1383
+ ...e.width === void 0 ? {} : { width: e.width }
1384
+ })), o = t.shapes.map((e, n) => ({
1385
+ key: dt(n),
1386
+ title: e.title,
1387
+ color: i(e.color),
1388
+ kind: "markers",
1389
+ shape: e.shape,
1390
+ position: _t(e.position, t.overlay)
1391
+ })), s = t.backgrounds.map((e, t) => ({
1392
+ key: q(t),
1393
+ title: e.title,
1394
+ color: i(void 0),
1395
+ kind: "background",
1396
+ paletteBy: Y(q(t)),
1397
+ opacity: 1
1398
+ })), c = t.fills.map((t, r) => {
1399
+ let o = n[a[t.between[0]].color];
1400
+ return {
1401
+ between: [K(t.between[0]), K(t.between[1])],
1402
+ color: i(t.color ?? e(o, gt)),
1403
+ paletteBy: ft(r),
1404
+ opacity: 1
1405
+ };
1406
+ }), l = Array.from({ length: t.barColors }, (e, t) => ({
1407
+ key: J(t),
1408
+ title: "Bars",
1409
+ color: i(void 0),
1410
+ kind: "barColor",
1411
+ paletteBy: Y(J(t))
1412
+ }));
1413
+ return {
1414
+ plots: [
1415
+ ...a,
1416
+ ...o,
1417
+ ...s,
1418
+ ...l
1419
+ ],
1420
+ fills: c,
1421
+ colors: n
1422
+ };
1423
+ }
1424
+ function bt(e) {
1425
+ let t = new T(e), n = t.declarations, { plots: r, fills: i, colors: a } = yt(n), o = e.inputs ?? {}, s = Object.keys(o);
1426
+ return {
1427
+ id: e.id,
1428
+ name: e.name,
1429
+ placement: n.overlay ? "overlay" : "panel",
1430
+ defaultConfig: Object.fromEntries(s.map((e) => [e, o[e].default])),
1431
+ plots: r,
1432
+ ...i && i.length > 0 ? { fills: i } : {},
1433
+ ...e.shortName === void 0 ? {} : { shortName: e.shortName },
1434
+ ...n.levels.length > 0 ? { levels: n.levels.map((e) => e.price) } : {},
1435
+ ...St(n.levels),
1436
+ ...s.length > 0 ? { inputs: Object.fromEntries(s.map((e) => {
1437
+ let { default: t, ...n } = o[e];
1438
+ return [e, n];
1439
+ })) } : {},
1440
+ ...a.length > 0 ? { defaultStyle: { colors: a } } : {},
1441
+ ...n.alertConditions.length > 0 ? { alertConditions: n.alertConditions.map((e, t) => ({
1442
+ key: pt(t),
1443
+ ...e
1444
+ })) } : {},
1445
+ readsExchangeTimeZone: !0,
1446
+ ...t.readsInterval ? { readsInterval: !0 } : {}
1447
+ };
1448
+ }
1449
+ var xt = class extends n {
1450
+ descriptor;
1451
+ runs = /* @__PURE__ */ new WeakMap();
1452
+ constructor(e, t = {}) {
1453
+ super(), this.script = e, this.options = t, this.descriptor = bt(e);
1454
+ }
1455
+ calculate(e, t) {
1456
+ let n = new T(this.script, t.params, vt(t, this.options.limits));
1457
+ n.load(e);
1458
+ let i = {
1459
+ values: new r(),
1460
+ series: Array(e.length).fill(null),
1461
+ meta: {}
1462
+ };
1463
+ return this.writeFrom(i, e, n, 0), this.runs.set(i, {
1464
+ run: n,
1465
+ params: Z(t.params),
1466
+ interval: t.interval
1467
+ }), i;
1468
+ }
1469
+ update(e, t, n, r) {
1470
+ let i = this.runs.get(n), a = this.descriptor.readsInterval === !0 && i?.interval !== t.interval;
1471
+ if (!i || a || i.params !== Z(t.params) || !this.canResume(e, n, r)) return null;
1472
+ let { run: o } = i;
1473
+ if (r < o.length - 1 || e.length < o.length) return null;
1474
+ for (let t = r; t < e.length; t++) t === o.length - 1 ? o.tick(e[t]) : o.next(e[t]);
1475
+ return n.series.length = e.length, this.writeFrom(n, e, o, Math.max(0, r - 1)), n;
1476
+ }
1477
+ revisesBefore() {
1478
+ return 1;
1479
+ }
1480
+ writeFrom(e, t, n, r) {
1481
+ let i = n.output;
1482
+ e.palette = i.palette, e.drawings = i.drawings, e.meta = {
1483
+ ...e.meta,
1484
+ errors: i.errors
1485
+ };
1486
+ for (let n = r; n < t.length; n++) this.writePoint(e, t, n, mt(i, n));
1487
+ }
1488
+ };
1489
+ function St(e) {
1490
+ let t = e.filter((e) => e.color !== void 0 || e.lineStyle !== void 0 || e.title !== void 0).map(({ price: e, color: t, lineStyle: n, title: r }) => ({
1491
+ price: e,
1492
+ ...t === void 0 ? {} : { color: t },
1493
+ ...n === void 0 ? {} : { lineStyle: n },
1494
+ ...r === void 0 ? {} : { title: r }
1495
+ }));
1496
+ return t.length > 0 ? { levelLooks: t } : {};
1497
+ }
1498
+ function Ct(e, t = {}) {
1499
+ return t.limits && b(t.limits), new xt(e, t);
1500
+ }
1501
+ //#endregion
1502
+ //#region src/worker/scriptWorkerIndicator.ts
1503
+ var wt = 5e3;
1504
+ function Q(e) {
1505
+ let t = e[e.length - 1];
1506
+ return t ? `${e.length}|${t.time}|${t.open}|${t.high}|${t.low}|${t.close}|${t.volume ?? 0}` : "0";
1507
+ }
1508
+ function Tt(e, t) {
1509
+ return `${Z(e.params)}|${e.exchangeTimeZone ?? ""}|${e.sessionStart ?? ""}|${t ? e.interval ?? "" : ""}`;
1510
+ }
1511
+ function Et(e) {
1512
+ return {
1513
+ values: new r(),
1514
+ series: Array(e).fill(null),
1515
+ meta: { errors: [] }
1516
+ };
1517
+ }
1518
+ function Dt(e, t) {
1519
+ let n = e.series;
1520
+ for (n.length > t && (n.length = t); n.length < t;) n.push(null);
1521
+ return e;
1522
+ }
1523
+ var Ot = class extends n {
1524
+ descriptor;
1525
+ worker = null;
1526
+ hosts = /* @__PURE__ */ new Set();
1527
+ entries = /* @__PURE__ */ new WeakMap();
1528
+ runs = /* @__PURE__ */ new Map();
1529
+ pending = [];
1530
+ due = /* @__PURE__ */ new Set();
1531
+ nextRun = 1;
1532
+ nextSeq = 1;
1533
+ timer = null;
1534
+ timeoutMs;
1535
+ constructor(e, t) {
1536
+ super(), this.script = e, this.options = t, this.descriptor = bt(e), this.timeoutMs = t.timeoutMs ?? wt;
1537
+ }
1538
+ connect(e) {
1539
+ return this.hosts.add(e), () => {
1540
+ this.hosts.delete(e);
1541
+ };
1542
+ }
1543
+ release(e) {
1544
+ let t = this.entries.get(e);
1545
+ t && (this.entries.delete(e), this.drop(t), this.runs.size === 0 && this.stopWorker());
1546
+ }
1547
+ calculate(e, t) {
1548
+ let n = this.entries.get(t);
1549
+ return n && n.key === this.keyOf(t) && n.bars === e && (n.stopped || n.sent !== "" && n.sent === Q(e)) ? n.output : this.load(e, t, n).output;
1550
+ }
1551
+ update(e, t, n, r) {
1552
+ let i = this.entries.get(t);
1553
+ if (!i || i.output !== n || i.stopped || i.key !== this.keyOf(t) || i.bars !== e || i.sent === "") return null;
1554
+ if (r < i.length - 1 || r > i.length || e.length < i.length) return i.sent = "", null;
1555
+ for (let t = r; t < e.length; t++) {
1556
+ let n = t === i.length - 1 ? "tick" : "next";
1557
+ this.send(i, {
1558
+ type: n,
1559
+ run: i.run,
1560
+ seq: this.nextSeq++,
1561
+ bar: e[t]
1562
+ }), n === "next" && (i.length = t + 1);
1563
+ }
1564
+ return Dt(n, e.length), i.sent = Q(e), n;
1565
+ }
1566
+ keyOf(e) {
1567
+ return Tt(e, this.descriptor.readsInterval === !0);
1568
+ }
1569
+ load(e, t, n) {
1570
+ n && this.drop(n);
1571
+ let r = {
1572
+ run: this.nextRun++,
1573
+ config: t,
1574
+ key: this.keyOf(t),
1575
+ bars: e,
1576
+ output: n ? Dt(n.output, e.length) : Et(e.length),
1577
+ length: e.length,
1578
+ sent: Q(e),
1579
+ stopped: !1
1580
+ };
1581
+ return this.entries.set(t, r), this.runs.set(r.run, r), this.send(r, {
1582
+ type: "load",
1583
+ run: r.run,
1584
+ seq: this.nextSeq++,
1585
+ script: this.script.id,
1586
+ params: { ...t.params },
1587
+ options: vt(t, this.options.limits),
1588
+ bars: e.map((e) => ({ ...e }))
1589
+ }), r;
1590
+ }
1591
+ drop(e) {
1592
+ this.runs.delete(e.run) && this.worker?.postMessage({
1593
+ type: "drop",
1594
+ run: e.run
1595
+ });
1596
+ }
1597
+ send(e, t) {
1598
+ this.pending.push(e.run), this.ensureWorker().postMessage(t), this.pending.length === 1 && this.armTimer();
1599
+ }
1600
+ ensureWorker() {
1601
+ if (this.worker) return this.worker;
1602
+ let e = this.options.spawn();
1603
+ return e.addEventListener("message", (t) => {
1604
+ this.worker === e && this.receive(t.data);
1605
+ }), this.worker = e, e;
1606
+ }
1607
+ stopWorker() {
1608
+ this.timer && clearTimeout(this.timer), this.timer = null, this.pending = [], this.worker?.terminate(), this.worker = null;
1609
+ }
1610
+ armTimer() {
1611
+ this.timer && clearTimeout(this.timer), this.timer = setTimeout(() => this.timedOut(), this.timeoutMs);
1612
+ }
1613
+ receive(e) {
1614
+ this.pending.shift(), this.timer && clearTimeout(this.timer), this.timer = null, this.pending.length > 0 && this.armTimer();
1615
+ let t = this.runs.get(e.run);
1616
+ t && (e.type === "patch" ? this.apply(t, e.from, e.points, e.palette, e.drawings, e.errors) : this.stop(t, {
1617
+ bar: Math.max(0, t.length - 1),
1618
+ message: e.message
1619
+ }), this.recompute(t));
1620
+ }
1621
+ apply(e, t, n, r, i, a) {
1622
+ let o = e.output, s = o.series;
1623
+ t === 0 && (o.values.clear(), s.fill(null));
1624
+ for (let r = 0; r < n.length; r++) {
1625
+ let i = t + r;
1626
+ if (i >= e.bars.length) break;
1627
+ for (; s.length <= i;) s.push(null);
1628
+ this.writePoint(o, e.bars, i, n[r]);
1629
+ }
1630
+ o.palette = r, o.drawings = i ?? [], o.meta = {
1631
+ ...o.meta,
1632
+ errors: a
1633
+ };
1634
+ }
1635
+ timedOut() {
1636
+ this.timer = null;
1637
+ let e = this.pending[0];
1638
+ this.stopWorker();
1639
+ let t = [...this.runs.values()];
1640
+ this.runs.clear();
1641
+ for (let n of t) n.run === e ? this.stop(n, {
1642
+ bar: Math.max(0, n.length - 1),
1643
+ message: `the script did not answer within ${this.timeoutMs} ms, and was stopped`,
1644
+ limit: "time"
1645
+ }) : n.sent = "", this.recompute(n);
1646
+ }
1647
+ stop(e, t) {
1648
+ e.stopped = !0, this.runs.delete(e.run), e.output.meta = {
1649
+ ...e.output.meta,
1650
+ errors: [t]
1651
+ };
1652
+ }
1653
+ recompute(e) {
1654
+ this.due.size === 0 && queueMicrotask(() => this.flush()), this.due.add(e);
1655
+ }
1656
+ flush() {
1657
+ let e = [...this.due];
1658
+ this.due.clear();
1659
+ for (let t of e) if (this.entries.get(t.config) === t) for (let e of this.hosts) e.recompute(t.config);
1660
+ }
1521
1661
  };
1522
- //# sourceMappingURL=index.js.map
1662
+ function kt(e, t) {
1663
+ if (t.limits && b(t.limits), t.timeoutMs !== void 0 && !(t.timeoutMs > 0)) throw RangeError(`scriptWorkerIndicator: timeoutMs must be a positive number, not ${t.timeoutMs}`);
1664
+ return new Ot(e, t);
1665
+ }
1666
+ //#endregion
1667
+ //#region src/worker/serveScripts.ts
1668
+ function $(e) {
1669
+ return e instanceof Error ? e.message : String(e);
1670
+ }
1671
+ function At(e, t, n, r) {
1672
+ let i = n.output, a = [];
1673
+ for (let e = r; e < i.length; e++) a.push(mt(i, e));
1674
+ return {
1675
+ type: "patch",
1676
+ run: e,
1677
+ seq: t,
1678
+ from: r,
1679
+ points: a,
1680
+ palette: [...i.palette],
1681
+ drawings: [...i.drawings],
1682
+ errors: [...i.errors]
1683
+ };
1684
+ }
1685
+ function jt(e, t) {
1686
+ let n = new Map(e.map((e) => [e.id, e])), r = /* @__PURE__ */ new Map(), i = (e, n, r) => t({
1687
+ type: "failed",
1688
+ run: e,
1689
+ seq: n,
1690
+ message: r
1691
+ });
1692
+ return (e) => {
1693
+ if (e.type === "drop") {
1694
+ r.delete(e.run);
1695
+ return;
1696
+ }
1697
+ if (e.type === "load") {
1698
+ r.delete(e.run);
1699
+ let a = n.get(e.script);
1700
+ if (!a) return i(e.run, e.seq, `no script '${e.script}' in this worker: give it to serveScripts`);
1701
+ try {
1702
+ let n = new T(a, e.params, e.options);
1703
+ n.load(e.bars), r.set(e.run, n), t(At(e.run, e.seq, n, 0));
1704
+ } catch (t) {
1705
+ i(e.run, e.seq, $(t));
1706
+ }
1707
+ return;
1708
+ }
1709
+ let a = r.get(e.run);
1710
+ if (!a) return i(e.run, e.seq, `no run ${e.run} here: load it first`);
1711
+ let o = a.length - 1;
1712
+ try {
1713
+ e.type === "tick" ? a.tick(e.bar) : a.next(e.bar), t(At(e.run, e.seq, a, Math.max(0, o)));
1714
+ } catch (t) {
1715
+ r.delete(e.run), i(e.run, e.seq, $(t));
1716
+ }
1717
+ };
1718
+ }
1719
+ function Mt(e, t = self) {
1720
+ let n = jt(e, (e) => t.postMessage(e));
1721
+ t.addEventListener("message", (e) => n(e.data));
1722
+ }
1723
+ //#endregion
1724
+ export { v as DEFAULT_LIMITS, y as ScriptLimitError, T as ScriptRun, jt as createScriptHandler, a as defineScript, Ct as scriptIndicator, kt as scriptWorkerIndicator, Mt as serveScripts, ut as ta };
1725
+
1726
+ //# sourceMappingURL=index.js.map