oakscriptjs 0.15.2 → 0.15.3
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/cjs/drawing/registry.d.ts +3 -0
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +96 -43
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/session/bars.d.ts +3 -0
- package/dist/cjs/session/bars.d.ts.map +1 -1
- package/dist/cjs/session/bars.js +10 -3
- package/dist/cjs/session/bars.js.map +2 -2
- package/dist/cjs/session/calendar.d.ts +19 -6
- package/dist/cjs/session/calendar.d.ts.map +1 -1
- package/dist/cjs/session/calendar.js +57 -18
- package/dist/cjs/session/calendar.js.map +2 -2
- package/dist/cjs/session/context.d.ts.map +1 -1
- package/dist/cjs/session/context.js +25 -8
- package/dist/cjs/session/context.js.map +2 -2
- package/dist/cjs/time/timezone.d.ts +13 -1
- package/dist/cjs/time/timezone.d.ts.map +1 -1
- package/dist/cjs/time/timezone.js +52 -13
- package/dist/cjs/time/timezone.js.map +2 -2
- package/dist/esm/drawing/registry.d.ts +3 -0
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +112 -48
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/session/bars.d.ts +3 -0
- package/dist/esm/session/bars.d.ts.map +1 -1
- package/dist/esm/session/bars.js +11 -3
- package/dist/esm/session/bars.js.map +1 -1
- package/dist/esm/session/calendar.d.ts +19 -6
- package/dist/esm/session/calendar.d.ts.map +1 -1
- package/dist/esm/session/calendar.js +74 -21
- package/dist/esm/session/calendar.js.map +1 -1
- package/dist/esm/session/context.d.ts.map +1 -1
- package/dist/esm/session/context.js +34 -9
- package/dist/esm/session/context.js.map +1 -1
- package/dist/esm/time/timezone.d.ts +13 -1
- package/dist/esm/time/timezone.d.ts.map +1 -1
- package/dist/esm/time/timezone.js +78 -17
- package/dist/esm/time/timezone.js.map +1 -1
- package/package.json +1 -1
- package/src/drawing/registry.ts +118 -47
- package/src/index.ts +1 -1
- package/src/session/bars.ts +11 -3
- package/src/session/calendar.ts +84 -21
- package/src/session/context.ts +36 -9
- package/src/time/timezone.ts +76 -15
|
@@ -76,6 +76,9 @@ export declare class Stamped {
|
|
|
76
76
|
interface Holds {
|
|
77
77
|
/** The records of the objects whose private record belongs to another run */
|
|
78
78
|
readonly others: WeakMap<object, HoldRecord>;
|
|
79
|
+
/** Records made in the run. None: no object has one, nothing to look up for each object the maximum count may
|
|
80
|
+
* delete */
|
|
81
|
+
records: number;
|
|
79
82
|
}
|
|
80
83
|
/** What the `var` variables of a run did with an object. */
|
|
81
84
|
interface HoldRecord {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/drawing/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAErF,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,CAAC;AAEvF,UAAU,YAAY;IACpB,IAAI,EAAE,IAAI,CAAC;IACX,KAAK,EAAE,KAAK,CAAC;IACb,GAAG,EAAE,GAAG,CAAC;IACT,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,QAAQ,CAAC;IACnB,KAAK,EAAE,KAAK,CAAC;CACd;AAED,+FAA+F;AAC/F,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAIpC,MAAM,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KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;KAAE,CAAC;IACrD,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,KAAK,EAAE,KAAK,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACrC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAC;CACjC;AAED,iGAAiG;AACjG,wBAAgB,gBAAgB,IAAI,YAAY,CAkB/C;AAED,qFAAqF;AACrF,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,YAAY,GAAG,IAAI,CAYzD"}
|
|
@@ -41,13 +41,71 @@ __export(registry_exports, {
|
|
|
41
41
|
module.exports = __toCommonJS(registry_exports);
|
|
42
42
|
const DEFAULT_MAX_COUNT = 50;
|
|
43
43
|
const SLACK = 5;
|
|
44
|
+
class LiveList {
|
|
45
|
+
items = [];
|
|
46
|
+
head = 0;
|
|
47
|
+
get length() {
|
|
48
|
+
return this.items.length - this.head;
|
|
49
|
+
}
|
|
50
|
+
/** The `k`-th live object (0: the oldest) */
|
|
51
|
+
at(k) {
|
|
52
|
+
return this.items[this.head + k];
|
|
53
|
+
}
|
|
54
|
+
push(obj) {
|
|
55
|
+
this.items.push(obj);
|
|
56
|
+
}
|
|
57
|
+
/** Position of `obj` among the live objects, -1 when it is not one */
|
|
58
|
+
lastIndexOf(obj) {
|
|
59
|
+
const index = this.items.lastIndexOf(obj);
|
|
60
|
+
return index >= this.head ? index - this.head : -1;
|
|
61
|
+
}
|
|
62
|
+
removeAt(k) {
|
|
63
|
+
if (k === 0) this.dropFront(1);
|
|
64
|
+
else this.items.splice(this.head + k, 1);
|
|
65
|
+
}
|
|
66
|
+
/** Removes the live objects at positions `gone` (increasing); the others keep their order */
|
|
67
|
+
removeAll(gone) {
|
|
68
|
+
if (gone.length === 0) return;
|
|
69
|
+
if (gone[0] === 0 && gone[gone.length - 1] === gone.length - 1) {
|
|
70
|
+
this.dropFront(gone.length);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const items = this.items;
|
|
74
|
+
let to = this.head + gone[0];
|
|
75
|
+
for (let from = to, g = 0; from < items.length; from++) {
|
|
76
|
+
if (from - this.head === gone[g]) g++;
|
|
77
|
+
else items[to++] = items[from];
|
|
78
|
+
}
|
|
79
|
+
items.length = to;
|
|
80
|
+
}
|
|
81
|
+
/** Removes the `n` oldest objects and returns them */
|
|
82
|
+
takeFront(n) {
|
|
83
|
+
const out = this.items.slice(this.head, this.head + n);
|
|
84
|
+
this.dropFront(n);
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
dropFront(n) {
|
|
88
|
+
this.head += n;
|
|
89
|
+
if (this.head >= this.length) {
|
|
90
|
+
this.items = this.items.slice(this.head);
|
|
91
|
+
this.head = 0;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
toArray() {
|
|
95
|
+
return this.items.slice(this.head);
|
|
96
|
+
}
|
|
97
|
+
replace(objs) {
|
|
98
|
+
this.items = [...objs];
|
|
99
|
+
this.head = 0;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
44
102
|
const live = {
|
|
45
|
-
line:
|
|
46
|
-
label:
|
|
47
|
-
box:
|
|
48
|
-
polyline:
|
|
49
|
-
linefill:
|
|
50
|
-
table:
|
|
103
|
+
line: new LiveList(),
|
|
104
|
+
label: new LiveList(),
|
|
105
|
+
box: new LiveList(),
|
|
106
|
+
polyline: new LiveList(),
|
|
107
|
+
linefill: new LiveList(),
|
|
108
|
+
table: new LiveList()
|
|
51
109
|
};
|
|
52
110
|
let limits = {
|
|
53
111
|
line: DEFAULT_MAX_COUNT,
|
|
@@ -69,7 +127,7 @@ class Deleted extends Stamped {
|
|
|
69
127
|
return #deleted in obj;
|
|
70
128
|
}
|
|
71
129
|
}
|
|
72
|
-
let holds = { others: /* @__PURE__ */ new WeakMap() };
|
|
130
|
+
let holds = { others: /* @__PURE__ */ new WeakMap(), records: 0 };
|
|
73
131
|
class Held extends Stamped {
|
|
74
132
|
#record;
|
|
75
133
|
constructor(obj, record) {
|
|
@@ -78,12 +136,14 @@ class Held extends Stamped {
|
|
|
78
136
|
}
|
|
79
137
|
/** The record of `obj` in the current run, if any. */
|
|
80
138
|
static get(obj) {
|
|
139
|
+
if (holds.records === 0) return void 0;
|
|
81
140
|
const own = #record in obj ? obj.#record : void 0;
|
|
82
141
|
return own?.run === holds ? own : holds.others.get(obj);
|
|
83
142
|
}
|
|
84
143
|
/** A new record of `obj` in the current run (it has none). */
|
|
85
144
|
static create(obj) {
|
|
86
145
|
const record = { run: holds, count: 0, heldAt: void 0, releasedAt: void 0 };
|
|
146
|
+
holds.records++;
|
|
87
147
|
if (#record in obj) holds.others.set(obj, record);
|
|
88
148
|
else new Held(obj, record);
|
|
89
149
|
return record;
|
|
@@ -153,7 +213,7 @@ function setDrawingBar(barIndex, last = false, lastIndex) {
|
|
|
153
213
|
const start = (kind) => pending[kind] >= PENDING_RESET[kind] ? 0 : pending[kind];
|
|
154
214
|
lastBar = {
|
|
155
215
|
bar: barIndex,
|
|
156
|
-
old: /* @__PURE__ */ new Set([...live.line, ...live.label, ...live.box, ...live.polyline]),
|
|
216
|
+
old: /* @__PURE__ */ new Set([...live.line.toArray(), ...live.label.toArray(), ...live.box.toArray(), ...live.polyline.toArray()]),
|
|
157
217
|
allowance: { line: start("line"), label: start("label"), box: start("box") },
|
|
158
218
|
carried: pending.polyline,
|
|
159
219
|
polyline: false,
|
|
@@ -222,30 +282,22 @@ function cutOldest(kind, list, obj, only) {
|
|
|
222
282
|
const max = limits[kind === "linefill" ? "line" : kind] + allowance(kind);
|
|
223
283
|
if (list.length <= max + SLACK) return [];
|
|
224
284
|
let excess = list.length - max;
|
|
225
|
-
const
|
|
285
|
+
const fill = kind === "linefill";
|
|
226
286
|
const gone = [];
|
|
227
|
-
for (
|
|
287
|
+
for (let pass = 0; pass < (fill ? 1 : 2); pass++) {
|
|
228
288
|
const before = gone.length;
|
|
229
289
|
for (let k = 0; k < list.length && excess > 0; k++) {
|
|
230
|
-
const old = list
|
|
231
|
-
if (
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
290
|
+
const old = list.at(k);
|
|
291
|
+
if (old === obj || only && !only(old)) continue;
|
|
292
|
+
if (fill ? fillProtected(old) : heldBefore(old) || heldOnThisBar(old) !== (pass === 1)) continue;
|
|
293
|
+
excess--;
|
|
294
|
+
gone.push(k);
|
|
235
295
|
}
|
|
236
296
|
if (before > 0 && gone.length > before) gone.sort((a, b) => a - b);
|
|
237
297
|
}
|
|
238
|
-
const cut = gone.map((k) => list
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
let to = gone[0];
|
|
242
|
-
for (let from = to, g = 0; from < list.length; from++) {
|
|
243
|
-
if (from === gone[g]) g++;
|
|
244
|
-
else list[to++] = list[from];
|
|
245
|
-
}
|
|
246
|
-
list.length = to;
|
|
247
|
-
}
|
|
248
|
-
if (kind === "linefill" && list.length > max + SLACK) cut.push(...list.splice(0, list.length - max));
|
|
298
|
+
const cut = gone.map((k) => list.at(k));
|
|
299
|
+
list.removeAll(gone);
|
|
300
|
+
if (fill && list.length > max + SLACK) cut.push(...list.takeFront(list.length - max));
|
|
249
301
|
return cut;
|
|
250
302
|
}
|
|
251
303
|
const created = /* @__PURE__ */ new Set();
|
|
@@ -276,7 +328,12 @@ function registerLast(bar, kind, obj) {
|
|
|
276
328
|
const list = live[kind];
|
|
277
329
|
list.push(obj);
|
|
278
330
|
const isOld = (old) => bar.old.has(old);
|
|
279
|
-
|
|
331
|
+
let oldCandidate = false;
|
|
332
|
+
for (let k = 0; k < list.length && !oldCandidate; k++) {
|
|
333
|
+
const old = list.at(k);
|
|
334
|
+
oldCandidate = old !== obj && isOld(old) && !heldBefore(old) && !heldOnThisBar(old);
|
|
335
|
+
}
|
|
336
|
+
if (oldCandidate) {
|
|
280
337
|
const cut = cutOldest(kind, list, obj, isOld);
|
|
281
338
|
if (kind === "polyline") {
|
|
282
339
|
pending.polyline += cut.length;
|
|
@@ -295,7 +352,7 @@ function remove(kind, obj) {
|
|
|
295
352
|
const list = live[kind];
|
|
296
353
|
const index = list.lastIndexOf(obj);
|
|
297
354
|
if (index !== -1) {
|
|
298
|
-
list.
|
|
355
|
+
list.removeAt(index);
|
|
299
356
|
if (kind === "linefill") untrackFill(obj);
|
|
300
357
|
if (isCounted(kind)) pending[kind]++;
|
|
301
358
|
if (kind === "polyline" && lastBar?.old.has(obj)) lastBar.oldPolylinesGone++;
|
|
@@ -306,13 +363,13 @@ function isDeleted(obj) {
|
|
|
306
363
|
return typeof obj === "object" && obj !== null && Deleted.has(obj);
|
|
307
364
|
}
|
|
308
365
|
function all(kind) {
|
|
309
|
-
return
|
|
366
|
+
return live[kind].toArray();
|
|
310
367
|
}
|
|
311
368
|
function resetDrawings(newLimits = {}) {
|
|
312
|
-
for (const kind of Object.keys(live)) live[kind].
|
|
369
|
+
for (const kind of Object.keys(live)) live[kind].replace([]);
|
|
313
370
|
fillsOfLine = /* @__PURE__ */ new Map();
|
|
314
371
|
created.clear();
|
|
315
|
-
holds = { others: /* @__PURE__ */ new WeakMap() };
|
|
372
|
+
holds = { others: /* @__PURE__ */ new WeakMap(), records: 0 };
|
|
316
373
|
pending = { line: 0, label: 0, box: 0, polyline: 0 };
|
|
317
374
|
currentBar = null;
|
|
318
375
|
lastBarIndex = null;
|
|
@@ -330,12 +387,12 @@ function setDrawingLimits(newLimits) {
|
|
|
330
387
|
function saveDrawingState() {
|
|
331
388
|
return {
|
|
332
389
|
live: {
|
|
333
|
-
line:
|
|
334
|
-
label:
|
|
335
|
-
box:
|
|
336
|
-
polyline:
|
|
337
|
-
linefill:
|
|
338
|
-
table:
|
|
390
|
+
line: live.line.toArray(),
|
|
391
|
+
label: live.label.toArray(),
|
|
392
|
+
box: live.box.toArray(),
|
|
393
|
+
polyline: live.polyline.toArray(),
|
|
394
|
+
linefill: live.linefill.toArray(),
|
|
395
|
+
table: live.table.toArray()
|
|
339
396
|
},
|
|
340
397
|
created: [...created],
|
|
341
398
|
holds,
|
|
@@ -347,13 +404,9 @@ function saveDrawingState() {
|
|
|
347
404
|
};
|
|
348
405
|
}
|
|
349
406
|
function restoreDrawingState(s) {
|
|
350
|
-
for (const kind of Object.keys(live))
|
|
351
|
-
const list = live[kind];
|
|
352
|
-
list.length = 0;
|
|
353
|
-
list.push(...s.live[kind]);
|
|
354
|
-
}
|
|
407
|
+
for (const kind of Object.keys(live)) live[kind].replace(s.live[kind]);
|
|
355
408
|
fillsOfLine = /* @__PURE__ */ new Map();
|
|
356
|
-
for (const fill of live.linefill) trackFill(fill);
|
|
409
|
+
for (const fill of s.live.linefill) trackFill(fill);
|
|
357
410
|
created.clear();
|
|
358
411
|
for (const kind of s.created) created.add(kind);
|
|
359
412
|
holds = s.holds;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/drawing/registry.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Registry of the live drawing objects (lines, labels, boxes, polylines, linefills, tables), as PineScript\n * keeps them. PineScript rules:\n *\n * - `line.all`, `label.all`, ... list the live objects in creation order (a copy of the list)\n * - `delete` removes an object; the object becomes `na`: its getters return NaN and its setters\n * do nothing. Deleting a line with `line.delete` also deletes the linefills that use it\n * - when a creation brings the count above `max_*_count + 5`, the oldest objects are deleted until\n * `max_*_count` remain (default 50). Copies count as creations. Linefills follow the same rule with\n * `max_lines_count`; lines deleted by this rule do not delete their linefills\n * - the object that was just created is never deleted by this rule\n * - an object that a `var` variable of the drawing type refers to is never deleted by this rule, and it still counts\n * (measured for lines, labels and boxes: with 9 held boxes and a maximum of 50, 9 held + 46 others stay; with 8\n * held lines and a maximum of 5, the 8 and the newest line stay). The protection starts on the bar after the\n * assignment: 12 `var` lines created on the first bar with a maximum of 5 lose the first 6. Only\n * the variable itself protects: an object in a `var` array, in a field of a user type or in a variable that got\n * another object or `na` later is deleted like any other. JavaScript has no `var` declaration to observe, so the\n * script says it: {@link varDrawing} (a variable), or {@link holdDrawing} / {@link releaseDrawing}\n * - linefills have the limit of `max_lines_count` with another rule for the held ones (measured on one script, two\n * long runs): a fill is skipped when a `var` variable holds it or released it less than 5,000 bars ago (the bar\n * of {@link setDrawingBar}); when the count is still above the maximum + 5 after that, the oldest fills are\n * deleted until the maximum remain, the held ones too\n * - the script deletes count (`line.delete`, `label.delete`, ...): each kind has a number `P` of deleted objects. A\n * delete adds 1; a creation first sets `P` to 0 when it is 5 or more (3 or more for polylines)\n * - polylines use `P` on every bar: a creation cuts when the count is above `max_polylines_count + 5 + P`, down to\n * the maximum + `P`, and the polylines of the cut are added to `P`. A script that deletes and creates one polyline\n * per bar therefore sees the cut 0, 1 or 2 bars late\n * - lines, labels and boxes use `P` on the last bar only, with its value at the start of that bar: there the cut is\n * above the maximum + 5 + `P`, down to the maximum + `P` (up to 4 more objects)\n * - the last bar has rules of its own (measured from the count after each creation, on a closed and on an open last\n * bar): a cut deletes the objects of the bars before first, at most those (a line takes its linefills with it);\n * once none is left, a cut deletes objects of the last bar as on any bar. With 10 lines and a maximum of 10, 13\n * lines on the last bar leave these 13: the cut at the 16th line deletes the 10 old ones only. Lines, labels and\n * boxes: equal to PineScript, count after every operation and objects alive at the end, on 72 of 72 runs checked\n * after the rule was written (and 218 of 218 end states before)\n * - polylines on the last bar: the `P` carried from the bar before is counted twice (the first creation adds it once\n * more, unless it sets `P` to 0), later creations do not set `P` to 0, and the polylines of the bars before that a\n * cut deletes are added to `P`. Once none is\n * left, `P` is at least the number of polylines of the bars before deleted on the last bar (by the count or by\n * the script) and a cut deletes polylines of the last bar: a script that deletes its 100 polylines and creates 200\n * on the last bar keeps them all (#176). Equal to PineScript for the polylines alive at the end on 271 of\n * 281 probe runs; the count inside the bar can differ when the script deletes polylines of the last bar\n *\n * - a bar index (`xloc.bar_index`) more than 10,000 bars before the current bar stops the script (runtime error\n * RE10026) in `line.new`, `box.new`, `label.new`, `polyline.new` and the setters of x. The current bar is the one\n * of `eachBar` in a script run; a port with its own bar loop gives it with {@link setDrawingBar}\n *\n * The script API (`executeScript`) resets the registry at the start of every run and applies the\n * `max_*_count` values of `indicator()`. Outside a script run the registry is global to the module.\n *\n * @module drawing/registry\n */\n\nimport type { Box, Label, Line, Linefill, Polyline, Table } from '../types/index.js';\n\nexport type DrawingKind = 'line' | 'label' | 'box' | 'polyline' | 'linefill' | 'table';\n\ninterface DrawingTypes {\n line: Line;\n label: Label;\n box: Box;\n polyline: Polyline;\n linefill: Linefill;\n table: Table;\n}\n\n/** Default `max_lines_count`, `max_labels_count`, `max_boxes_count`, `max_polylines_count`. */\nexport const DEFAULT_MAX_COUNT = 50;\n/** Objects above the maximum that PineScript keeps before it deletes the oldest ones. */\nconst SLACK = 5;\n\nexport type DrawingLimits = Partial<Record<Exclude<DrawingKind, 'linefill' | 'table'>, number>>;\n\nconst live: { [K in DrawingKind]: Array<DrawingTypes[K]> } = {\n line: [],\n label: [],\n box: [],\n polyline: [],\n linefill: [],\n table: [],\n};\nlet limits: Required<DrawingLimits> = {\n line: DEFAULT_MAX_COUNT,\n label: DEFAULT_MAX_COUNT,\n box: DEFAULT_MAX_COUNT,\n polyline: DEFAULT_MAX_COUNT,\n};\n/**\n * Base of the classes that add a private field to an existing object (their constructor returns the object they are\n * given). Such a field replaces a WeakMap entry: a study that creates hundreds of thousands of objects spends most of\n * its drawing time adding WeakMap keys. The field is invisible (not a key, not copied by a spread) and stays for the\n * life of the object, as the entry did.\n */\nexport class Stamped {\n constructor(obj: object) {\n return obj;\n }\n}\n\n/** The deleted objects. */\nclass Deleted extends Stamped {\n #deleted = true;\n static mark(obj: object): void {\n if (!Deleted.has(obj)) new Deleted(obj);\n }\n static has(obj: object): boolean {\n return #deleted in obj;\n }\n}\n\n/** The `var` records of a run: a reset starts new ones, a nested run saves and puts back those of its run. */\ninterface Holds {\n /** The records of the objects whose private record belongs to another run */\n readonly others: WeakMap<object, HoldRecord>;\n}\n\n/** What the `var` variables of a run did with an object. */\ninterface HoldRecord {\n readonly run: Holds;\n /** Number of `var` variables that hold the object (0: not held) */\n count: number;\n /** Bar on which a `var` variable got the object: on that bar the maximum count deletes it only when no other object\n * can go; from the next bar on, never. Undefined outside a bar loop */\n heldAt: number | undefined;\n /** Bar on which the last `var` variable released the object (linefill rule) */\n releasedAt: number | undefined;\n}\nlet holds: Holds = { others: new WeakMap() };\n\n/**\n * The record of the first run that holds an object, on the object itself (a study holding a new object on every bar\n * would otherwise add a WeakMap key per bar); the records of other runs go to their {@link Holds.others}.\n */\nclass Held extends Stamped {\n #record: HoldRecord;\n private constructor(obj: object, record: HoldRecord) {\n super(obj);\n this.#record = record;\n }\n /** The record of `obj` in the current run, if any. */\n static get(obj: object): HoldRecord | undefined {\n const own = #record in obj ? (obj as Held).#record : undefined;\n return own?.run === holds ? own : holds.others.get(obj);\n }\n /** A new record of `obj` in the current run (it has none). */\n static create(obj: object): HoldRecord {\n const record: HoldRecord = { run: holds, count: 0, heldAt: undefined, releasedAt: undefined };\n if (#record in obj) holds.others.set(obj, record);\n else new Held(obj, record);\n return record;\n }\n}\n/** Bars during which a released linefill is still skipped by the maximum count. */\nconst LINEFILL_RELEASE_BARS = 5000;\n/** Kinds with a maximum count of their own. */\ntype CountedKind = 'line' | 'label' | 'box' | 'polyline';\nconst COUNTED_KINDS: readonly CountedKind[] = ['line', 'label', 'box', 'polyline'];\nconst isCounted = (kind: DrawingKind): kind is CountedKind => (COUNTED_KINDS as readonly DrawingKind[]).includes(kind);\n/** `P` of the module notes: objects deleted by the script (for polylines also by the maximum count). */\nlet pending: Record<CountedKind, number> = { line: 0, label: 0, box: 0, polyline: 0 };\n/** A creation sets `P` to 0 from this value on. */\nconst PENDING_RESET: Record<CountedKind, number> = { line: 5, label: 5, box: 5, polyline: 3 };\n\n/**\n * Marks an object as held by a `var` variable (PineScript `var line l = ...` or `l := line.new(...)` on a `var`\n * variable): the maximum count never deletes it, and it still counts. Returns the object.\n */\nexport function holdDrawing<T extends object>(obj: T): T {\n const record = Held.get(obj) ?? Held.create(obj);\n if (record.count === 0) record.heldAt = currentBar ?? undefined;\n record.count++;\n return obj;\n}\n\n/** The `var` variable no longer refers to the object (it got another object or `na`). */\nexport function releaseDrawing(obj: object | null | undefined): void {\n if (!obj) return;\n const record = Held.get(obj);\n if (!record || record.count === 0) return;\n record.count--;\n if (record.count === 0 && currentBar !== null) record.releasedAt = currentBar;\n}\n\n/** Held by a `var` variable since a bar before the current one (or outside a bar loop). */\nfunction heldBefore(obj: object): boolean {\n const record = Held.get(obj);\n if (!record || record.count === 0) return false;\n const bar = record.heldAt;\n return bar === undefined || currentBar === null || bar < currentBar;\n}\n\n/**\n * Held by a `var` variable since the current bar, or released by its last variable on the current bar: the maximum\n * count deletes such an object only when the objects it may delete are not enough (#193; 12 `var` lines made on the\n * first bar with a maximum of 5 lose the first 6, #158).\n */\nfunction heldOnThisBar(obj: object): boolean {\n if (currentBar === null) return false;\n const record = Held.get(obj);\n if (!record) return false;\n return record.count > 0 ? record.heldAt === currentBar : record.releasedAt === currentBar;\n}\n\n/** Linefill rule: held, or released less than 5,000 bars ago. */\nfunction fillProtected(obj: object): boolean {\n const record = Held.get(obj);\n if (!record) return false;\n if (record.count > 0) return true;\n const bar = record.releasedAt;\n return bar !== undefined && currentBar !== null && currentBar - bar < LINEFILL_RELEASE_BARS;\n}\n\n/** A `var` variable of a drawing type: see {@link varDrawing}. */\nexport interface DrawingVariable<T extends object> {\n /** The object of the variable; setting it holds the new object and releases the one before */\n value: T | undefined;\n}\n\n/**\n * A PineScript `var` variable of a drawing type (`var line l = na`). The object it refers to is not deleted by the\n * maximum count; assigning another object (or `undefined` for `na`) releases the one before.\n *\n * @example\n * ```typescript\n * // Pine: var line level = na\n * // level := line.new(bar_index, close, bar_index + 1, close)\n * const level = varDrawing<Line>();\n * level.value = line.new(i, close, i + 1, close);\n * ```\n */\nexport function varDrawing<T extends object>(initial?: T): DrawingVariable<T> {\n let current: T | undefined = initial ? holdDrawing(initial) : undefined;\n return {\n get value() {\n return current;\n },\n set value(next: T | undefined) {\n if (next === current) return;\n releaseDrawing(current);\n current = next ? holdDrawing(next) : undefined;\n },\n };\n}\n\n/** Largest distance, in bars, of a bar index before the current bar (PineScript runtime error RE10026 above it). */\nexport const MAX_DRAWING_BARS_BACK = 10000;\n/** Largest distance, in bars, of a bar index after the last bar of the data (PineScript runtime error RE10020 above it). */\nexport const MAX_DRAWING_BARS_FORWARD = 500;\nlet currentBar: number | null = null;\nlet lastBarIndex: number | null = null;\n\n/** Kinds whose allowance on the last bar is the `P` they had when the bar started. */\ntype AllowanceKind = 'line' | 'label' | 'box';\nconst isAllowanceKind = (kind: DrawingKind): kind is AllowanceKind => kind === 'line' || kind === 'label' || kind === 'box';\n\n/** State of the last bar (see the module notes). */\ninterface LastBar {\n bar: number;\n /** The objects alive when the bar started (the objects of the bars before) */\n old: Set<object>;\n /** `P` of lines, labels and boxes when the bar started: their allowance for the whole bar */\n allowance: Record<AllowanceKind, number>;\n /** `P` of polylines when the bar started */\n carried: number;\n /** A polyline was created on this bar */\n polyline: boolean;\n /** Polylines of the bars before deleted on this bar (by the count or by the script) */\n oldPolylinesGone: number;\n}\nlet lastBar: LastBar | null = null;\n\n/**\n * Tells the drawing functions which bar is being calculated (`bar_index`), so that a bar index more than 10,000\n * bars back throws as in PineScript; `null` turns the check off. `eachBar` of the script API calls it.\n *\n * The bar also dates the objects held by a `var` variable (on that bar deleted only when no other object can go,\n * never after). `last` says that it is the last bar of the data, which has rules of its own for the maximum count. `lastIndex` is the bar index of the\n * last bar of the data (PineScript `last_bar_index`): with it, a bar index more than 500 bars after it throws, also\n * on the bars before the last one (RE10020).\n */\nexport function setDrawingBar(barIndex: number | null, last: boolean = false, lastIndex?: number): void {\n if (lastBar && !(last && barIndex === lastBar.bar)) lastBar = null;\n currentBar = barIndex;\n lastBarIndex = barIndex === null ? null : (lastIndex ?? (last ? barIndex : null));\n if (barIndex !== null && last && !lastBar) {\n const start = (kind: AllowanceKind): number => (pending[kind] >= PENDING_RESET[kind] ? 0 : pending[kind]);\n lastBar = {\n bar: barIndex,\n old: new Set<object>([...live.line, ...live.label, ...live.box, ...live.polyline]),\n allowance: { line: start('line'), label: start('label'), box: start('box') },\n carried: pending.polyline,\n polyline: false,\n oldPolylinesGone: 0,\n };\n }\n}\n\n/**\n * Throws the PineScript runtime error RE10026 when `x` is a bar index more than 10,000 bars before the current bar,\n * and RE10020 when it is more than 500 bars after the last bar of the data (when {@link setDrawingBar} knows it).\n * `method` and `variable` are the names of the PineScript message (\"line.new\", \"x1\").\n *\n * Returns `x`, truncated when it is a bar index: PineScript's x is an int (a box from 5537.94 starts on bar 5537,\n * #176).\n */\nexport function checkBarIndex(method: string, variable: string, x: number, xloc: string | undefined): number {\n if ((xloc ?? 'bar_index') !== 'bar_index') return x;\n x = Math.trunc(x);\n if (currentBar === null) return x;\n if (lastBarIndex !== null && x - lastBarIndex > MAX_DRAWING_BARS_FORWARD) {\n throw new Error(\n `Error on bar ${currentBar}: Objects positioned using xloc.bar_index cannot be drawn further than ` +\n `${MAX_DRAWING_BARS_FORWARD} bars into the future.`\n );\n }\n if (currentBar - x > MAX_DRAWING_BARS_BACK) {\n throw new Error(\n `Error on bar ${currentBar}: Bar index value of the \\`${variable}\\` argument (${x}) in \\`${method}()\\` is too far ` +\n 'from the current bar index. Try using `time` instead.'\n );\n }\n return x;\n}\n\n/** Numeric fields that become NaN when an object is deleted, so that its getters return `na`. */\nconst COORDINATES: { [K in DrawingKind]: Array<keyof DrawingTypes[K]> } = {\n line: ['x1', 'y1', 'x2', 'y2'],\n label: ['x', 'y'],\n box: ['left', 'top', 'right', 'bottom'],\n polyline: [],\n linefill: [],\n table: [],\n};\n\n/** The live linefills of each line, in creation order: deleting a line or making a fill does not scan all the fills. */\nlet fillsOfLine = new Map<Line, Linefill[]>();\n\nfunction trackFill(fill: Linefill): void {\n for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {\n const fills = fillsOfLine.get(l);\n if (fills) fills.push(fill);\n else fillsOfLine.set(l, [fill]);\n }\n}\n\nfunction untrackFill(fill: Linefill): void {\n for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {\n const fills = fillsOfLine.get(l);\n if (!fills) continue;\n const k = fills.indexOf(fill);\n if (k !== -1) fills.splice(k, 1);\n if (fills.length === 0) fillsOfLine.delete(l);\n }\n}\n\n/** The live linefills that use `line`, in creation order (do not modify). */\nexport function liveFillsOf(line: Line): readonly Linefill[] {\n return fillsOfLine.get(line) ?? [];\n}\n\nfunction markDeleted<K extends DrawingKind>(kind: K, obj: DrawingTypes[K], explicit: boolean): void {\n Deleted.mark(obj);\n for (const field of COORDINATES[kind]) (obj as unknown as Record<string, unknown>)[field as string] = NaN;\n if (kind === 'line' && explicit) {\n const fills = fillsOfLine.get(obj as Line);\n if (fills) for (const fill of [...fills]) remove('linefill', fill);\n }\n}\n\n/** Objects above the maximum that the rule allows for, besides the 5: `P` of the module notes. */\nfunction allowance(kind: DrawingKind): number {\n if (kind === 'polyline') return pending.polyline;\n return lastBar && isAllowanceKind(kind) ? lastBar.allowance[kind] : 0;\n}\n\n/**\n * The maximum count after the creation of `obj`: removes the objects to delete from `list` (the oldest first; the new\n * object and an object held by a `var` variable are skipped and still count) and returns them.\n */\nfunction cutOldest<K extends DrawingKind>(\n kind: K,\n list: Array<DrawingTypes[K]>,\n obj: DrawingTypes[K],\n only?: (old: object) => boolean\n): Array<DrawingTypes[K]> {\n if (kind === 'table') return []; // tables have no maximum count\n const max = limits[kind === 'linefill' ? 'line' : (kind as keyof DrawingLimits)] + allowance(kind);\n if (list.length <= max + SLACK) return [];\n let excess = list.length - max;\n const candidate = (old: DrawingTypes[K]): boolean =>\n old !== obj && (!only || only(old)) && !(kind === 'linefill' ? fillProtected(old) : heldBefore(old));\n // positions of the objects to delete. The oldest first; the objects a `var` variable got (or released) on this bar\n // only when the others are not enough (the two passes pick different objects)\n const gone: number[] = [];\n for (const weak of kind === 'linefill' ? [false] : [false, true]) {\n const before = gone.length;\n for (let k = 0; k < list.length && excess > 0; k++) {\n const old = list[k]!;\n if (candidate(old) && (kind === 'linefill' || heldOnThisBar(old) === weak)) {\n excess--;\n gone.push(k);\n }\n }\n if (before > 0 && gone.length > before) gone.sort((a, b) => a - b);\n }\n const cut = gone.map((k) => list[k]!);\n // the others keep their order; usually the cut is the oldest run of objects, removed at once\n if (gone.length > 0 && gone[gone.length - 1]! - gone[0]! === gone.length - 1) list.splice(gone[0]!, gone.length);\n else if (gone.length > 0) {\n let to = gone[0]!;\n for (let from = to, g = 0; from < list.length; from++) {\n if (from === gone[g]) g++;\n else list[to++] = list[from]!;\n }\n list.length = to;\n }\n // linefills: still above the maximum + 5, the oldest go, the held ones too\n if (kind === 'linefill' && list.length > max + SLACK) cut.push(...list.splice(0, list.length - max));\n return cut;\n}\n\n/** Kinds of the objects created since the last reset (a table counts too), in no order. */\nconst created = new Set<DrawingKind>();\n\n/** The kinds of drawing objects created since the last {@link resetDrawings}, even when none is alive any more. */\nexport function createdDrawingKinds(): DrawingKind[] {\n return [...created];\n}\n\n/** Records a new object and deletes the oldest objects of its kind when the count is too high. */\nexport function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {\n const list = live[kind];\n created.add(kind);\n if (lastBar && isCounted(kind)) return registerLast(lastBar, kind, obj);\n if (isCounted(kind) && pending[kind] >= PENDING_RESET[kind]) pending[kind] = 0;\n list.push(obj);\n if (kind === 'linefill') trackFill(obj as Linefill);\n const cut = cutOldest(kind, list, obj);\n if (kind === 'polyline') pending.polyline += cut.length;\n for (const old of cut) {\n if (kind === 'linefill') untrackFill(old as Linefill);\n markDeleted(kind, old, false);\n }\n return obj;\n}\n\n/** An object created on the last bar (see the module notes). */\nfunction registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {\n if (kind === 'polyline' && !bar.polyline) {\n bar.polyline = true;\n if (pending.polyline >= PENDING_RESET.polyline) pending.polyline = 0;\n else pending.polyline += bar.carried; // counted twice\n }\n const list = live[kind];\n list.push(obj);\n const isOld = (old: object): boolean => bar.old.has(old);\n if (list.some((old) => old !== obj && isOld(old) && !heldBefore(old) && !heldOnThisBar(old))) {\n // the objects of the bars before only; a line takes its linefills with it\n const cut = cutOldest(kind, list, obj, isOld);\n if (kind === 'polyline') {\n pending.polyline += cut.length;\n bar.oldPolylinesGone += cut.length;\n }\n for (const old of cut) markDeleted(kind, old, true);\n } else {\n // the polylines of the bars before deleted on this bar count before the cut (#176)\n if (kind === 'polyline' && pending.polyline < bar.oldPolylinesGone) pending.polyline = bar.oldPolylinesGone;\n const cut = cutOldest(kind, list, obj);\n if (kind === 'polyline' && cut.length > 0) pending.polyline = bar.oldPolylinesGone;\n for (const old of cut) markDeleted(kind, old, false);\n }\n return obj;\n}\n\n/** Deletes an object (no effect when it is already deleted). */\nexport function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): void {\n const list = live[kind];\n // from the end: an object is in the list once, and scripts mostly delete their newest objects\n const index = list.lastIndexOf(obj);\n if (index !== -1) {\n list.splice(index, 1);\n if (kind === 'linefill') untrackFill(obj as Linefill);\n if (isCounted(kind)) pending[kind]++;\n if (kind === 'polyline' && lastBar?.old.has(obj)) lastBar.oldPolylinesGone++;\n }\n if (!Deleted.has(obj)) markDeleted(kind, obj, true);\n}\n\n/** True when the object was deleted (by `delete` or by the maximum count). */\nexport function isDeleted(obj: unknown): boolean {\n return typeof obj === 'object' && obj !== null && Deleted.has(obj);\n}\n\n/** The live objects of a kind, in creation order (a new array). */\nexport function all<K extends DrawingKind>(kind: K): Array<DrawingTypes[K]> {\n return [...live[kind]] as Array<DrawingTypes[K]>;\n}\n\n/** Forgets all objects (without deleting them) and sets the maximum counts (default 50). */\nexport function resetDrawings(newLimits: DrawingLimits = {}): void {\n for (const kind of Object.keys(live) as DrawingKind[]) live[kind].length = 0;\n fillsOfLine = new Map();\n created.clear();\n holds = { others: new WeakMap() };\n pending = { line: 0, label: 0, box: 0, polyline: 0 };\n currentBar = null;\n lastBarIndex = null;\n lastBar = null;\n limits = {\n line: newLimits.line ?? DEFAULT_MAX_COUNT,\n label: newLimits.label ?? DEFAULT_MAX_COUNT,\n box: newLimits.box ?? DEFAULT_MAX_COUNT,\n polyline: newLimits.polyline ?? DEFAULT_MAX_COUNT,\n };\n}\n\n/** Changes the maximum counts without forgetting the objects (PineScript `indicator(max_*_count)`). */\nexport function setDrawingLimits(newLimits: DrawingLimits): void {\n limits = { ...limits, ...Object.fromEntries(Object.entries(newLimits).filter(([, v]) => v !== undefined)) };\n}\n\n/** The registry state of a run, saved around a nested run (see {@link restoreDrawingState}). */\nexport interface DrawingState {\n live: { [K in DrawingKind]: Array<DrawingTypes[K]> };\n created: DrawingKind[];\n holds: Holds;\n pending: Record<CountedKind, number>;\n currentBar: number | null;\n lastBarIndex: number | null;\n lastBar: LastBar | null;\n limits: Required<DrawingLimits>;\n}\n\n/** Saves the registry of the current run before a nested run (an intrabar run of a strategy). */\nexport function saveDrawingState(): DrawingState {\n return {\n live: {\n line: [...live.line],\n label: [...live.label],\n box: [...live.box],\n polyline: [...live.polyline],\n linefill: [...live.linefill],\n table: [...live.table],\n },\n created: [...created],\n holds,\n pending: { ...pending },\n currentBar,\n lastBarIndex,\n lastBar,\n limits: { ...limits },\n };\n}\n\n/** Puts back the registry saved by {@link saveDrawingState} after the nested run. */\nexport function restoreDrawingState(s: DrawingState): void {\n for (const kind of Object.keys(live) as DrawingKind[]) {\n const list = live[kind] as object[];\n list.length = 0;\n list.push(...(s.live[kind] as object[]));\n }\n fillsOfLine = new Map();\n for (const fill of live.linefill) trackFill(fill);\n created.clear();\n for (const kind of s.created) created.add(kind);\n holds = s.holds;\n pending = { ...s.pending };\n currentBar = s.currentBar;\n lastBarIndex = s.lastBarIndex;\n lastBar = s.lastBar;\n limits = { ...s.limits };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmEO,MAAM,oBAAoB;AAEjC,MAAM,QAAQ;
|
|
4
|
+
"sourcesContent": ["/**\n * Registry of the live drawing objects (lines, labels, boxes, polylines, linefills, tables), as PineScript\n * keeps them. PineScript rules:\n *\n * - `line.all`, `label.all`, ... list the live objects in creation order (a copy of the list)\n * - `delete` removes an object; the object becomes `na`: its getters return NaN and its setters\n * do nothing. Deleting a line with `line.delete` also deletes the linefills that use it\n * - when a creation brings the count above `max_*_count + 5`, the oldest objects are deleted until\n * `max_*_count` remain (default 50). Copies count as creations. Linefills follow the same rule with\n * `max_lines_count`; lines deleted by this rule do not delete their linefills\n * - the object that was just created is never deleted by this rule\n * - an object that a `var` variable of the drawing type refers to is never deleted by this rule, and it still counts\n * (measured for lines, labels and boxes: with 9 held boxes and a maximum of 50, 9 held + 46 others stay; with 8\n * held lines and a maximum of 5, the 8 and the newest line stay). The protection starts on the bar after the\n * assignment: 12 `var` lines created on the first bar with a maximum of 5 lose the first 6. Only\n * the variable itself protects: an object in a `var` array, in a field of a user type or in a variable that got\n * another object or `na` later is deleted like any other. JavaScript has no `var` declaration to observe, so the\n * script says it: {@link varDrawing} (a variable), or {@link holdDrawing} / {@link releaseDrawing}\n * - linefills have the limit of `max_lines_count` with another rule for the held ones (measured on one script, two\n * long runs): a fill is skipped when a `var` variable holds it or released it less than 5,000 bars ago (the bar\n * of {@link setDrawingBar}); when the count is still above the maximum + 5 after that, the oldest fills are\n * deleted until the maximum remain, the held ones too\n * - the script deletes count (`line.delete`, `label.delete`, ...): each kind has a number `P` of deleted objects. A\n * delete adds 1; a creation first sets `P` to 0 when it is 5 or more (3 or more for polylines)\n * - polylines use `P` on every bar: a creation cuts when the count is above `max_polylines_count + 5 + P`, down to\n * the maximum + `P`, and the polylines of the cut are added to `P`. A script that deletes and creates one polyline\n * per bar therefore sees the cut 0, 1 or 2 bars late\n * - lines, labels and boxes use `P` on the last bar only, with its value at the start of that bar: there the cut is\n * above the maximum + 5 + `P`, down to the maximum + `P` (up to 4 more objects)\n * - the last bar has rules of its own (measured from the count after each creation, on a closed and on an open last\n * bar): a cut deletes the objects of the bars before first, at most those (a line takes its linefills with it);\n * once none is left, a cut deletes objects of the last bar as on any bar. With 10 lines and a maximum of 10, 13\n * lines on the last bar leave these 13: the cut at the 16th line deletes the 10 old ones only. Lines, labels and\n * boxes: equal to PineScript, count after every operation and objects alive at the end, on 72 of 72 runs checked\n * after the rule was written (and 218 of 218 end states before)\n * - polylines on the last bar: the `P` carried from the bar before is counted twice (the first creation adds it once\n * more, unless it sets `P` to 0), later creations do not set `P` to 0, and the polylines of the bars before that a\n * cut deletes are added to `P`. Once none is\n * left, `P` is at least the number of polylines of the bars before deleted on the last bar (by the count or by\n * the script) and a cut deletes polylines of the last bar: a script that deletes its 100 polylines and creates 200\n * on the last bar keeps them all (#176). Equal to PineScript for the polylines alive at the end on 271 of\n * 281 probe runs; the count inside the bar can differ when the script deletes polylines of the last bar\n *\n * - a bar index (`xloc.bar_index`) more than 10,000 bars before the current bar stops the script (runtime error\n * RE10026) in `line.new`, `box.new`, `label.new`, `polyline.new` and the setters of x. The current bar is the one\n * of `eachBar` in a script run; a port with its own bar loop gives it with {@link setDrawingBar}\n *\n * The script API (`executeScript`) resets the registry at the start of every run and applies the\n * `max_*_count` values of `indicator()`. Outside a script run the registry is global to the module.\n *\n * @module drawing/registry\n */\n\nimport type { Box, Label, Line, Linefill, Polyline, Table } from '../types/index.js';\n\nexport type DrawingKind = 'line' | 'label' | 'box' | 'polyline' | 'linefill' | 'table';\n\ninterface DrawingTypes {\n line: Line;\n label: Label;\n box: Box;\n polyline: Polyline;\n linefill: Linefill;\n table: Table;\n}\n\n/** Default `max_lines_count`, `max_labels_count`, `max_boxes_count`, `max_polylines_count`. */\nexport const DEFAULT_MAX_COUNT = 50;\n/** Objects above the maximum that PineScript keeps before it deletes the oldest ones. */\nconst SLACK = 5;\n\nexport type DrawingLimits = Partial<Record<Exclude<DrawingKind, 'linefill' | 'table'>, number>>;\n\n/**\n * The live objects of a kind, in creation order. The maximum count deletes the oldest ones: they leave by moving the\n * head, and the array drops its dead front once it is as long as the live part, so a creation at the maximum costs\n * O(1) amortised instead of a move of the whole list on every cut.\n */\nclass LiveList<T> {\n private items: T[] = [];\n private head = 0;\n\n get length(): number {\n return this.items.length - this.head;\n }\n\n /** The `k`-th live object (0: the oldest) */\n at(k: number): T {\n return this.items[this.head + k]!;\n }\n\n push(obj: T): void {\n this.items.push(obj);\n }\n\n /** Position of `obj` among the live objects, -1 when it is not one */\n lastIndexOf(obj: T): number {\n const index = this.items.lastIndexOf(obj);\n return index >= this.head ? index - this.head : -1;\n }\n\n removeAt(k: number): void {\n if (k === 0) this.dropFront(1);\n else this.items.splice(this.head + k, 1);\n }\n\n /** Removes the live objects at positions `gone` (increasing); the others keep their order */\n removeAll(gone: readonly number[]): void {\n if (gone.length === 0) return;\n if (gone[0] === 0 && gone[gone.length - 1] === gone.length - 1) {\n this.dropFront(gone.length);\n return;\n }\n const items = this.items;\n let to = this.head + gone[0]!;\n for (let from = to, g = 0; from < items.length; from++) {\n if (from - this.head === gone[g]) g++;\n else items[to++] = items[from]!;\n }\n items.length = to;\n }\n\n /** Removes the `n` oldest objects and returns them */\n takeFront(n: number): T[] {\n const out = this.items.slice(this.head, this.head + n);\n this.dropFront(n);\n return out;\n }\n\n private dropFront(n: number): void {\n this.head += n;\n if (this.head >= this.length) {\n this.items = this.items.slice(this.head);\n this.head = 0;\n }\n }\n\n toArray(): T[] {\n return this.items.slice(this.head);\n }\n\n replace(objs: readonly T[]): void {\n this.items = [...objs];\n this.head = 0;\n }\n}\n\nconst live: { [K in DrawingKind]: LiveList<DrawingTypes[K]> } = {\n line: new LiveList(),\n label: new LiveList(),\n box: new LiveList(),\n polyline: new LiveList(),\n linefill: new LiveList(),\n table: new LiveList(),\n};\nlet limits: Required<DrawingLimits> = {\n line: DEFAULT_MAX_COUNT,\n label: DEFAULT_MAX_COUNT,\n box: DEFAULT_MAX_COUNT,\n polyline: DEFAULT_MAX_COUNT,\n};\n/**\n * Base of the classes that add a private field to an existing object (their constructor returns the object they are\n * given). Such a field replaces a WeakMap entry: a study that creates hundreds of thousands of objects spends most of\n * its drawing time adding WeakMap keys. The field is invisible (not a key, not copied by a spread) and stays for the\n * life of the object, as the entry did.\n */\nexport class Stamped {\n constructor(obj: object) {\n return obj;\n }\n}\n\n/** The deleted objects. */\nclass Deleted extends Stamped {\n #deleted = true;\n static mark(obj: object): void {\n if (!Deleted.has(obj)) new Deleted(obj);\n }\n static has(obj: object): boolean {\n return #deleted in obj;\n }\n}\n\n/** The `var` records of a run: a reset starts new ones, a nested run saves and puts back those of its run. */\ninterface Holds {\n /** The records of the objects whose private record belongs to another run */\n readonly others: WeakMap<object, HoldRecord>;\n /** Records made in the run. None: no object has one, nothing to look up for each object the maximum count may\n * delete */\n records: number;\n}\n\n/** What the `var` variables of a run did with an object. */\ninterface HoldRecord {\n readonly run: Holds;\n /** Number of `var` variables that hold the object (0: not held) */\n count: number;\n /** Bar on which a `var` variable got the object: on that bar the maximum count deletes it only when no other object\n * can go; from the next bar on, never. Undefined outside a bar loop */\n heldAt: number | undefined;\n /** Bar on which the last `var` variable released the object (linefill rule) */\n releasedAt: number | undefined;\n}\nlet holds: Holds = { others: new WeakMap(), records: 0 };\n\n/**\n * The record of the first run that holds an object, on the object itself (a study holding a new object on every bar\n * would otherwise add a WeakMap key per bar); the records of other runs go to their {@link Holds.others}.\n */\nclass Held extends Stamped {\n #record: HoldRecord;\n private constructor(obj: object, record: HoldRecord) {\n super(obj);\n this.#record = record;\n }\n /** The record of `obj` in the current run, if any. */\n static get(obj: object): HoldRecord | undefined {\n if (holds.records === 0) return undefined;\n const own = #record in obj ? (obj as Held).#record : undefined;\n return own?.run === holds ? own : holds.others.get(obj);\n }\n /** A new record of `obj` in the current run (it has none). */\n static create(obj: object): HoldRecord {\n const record: HoldRecord = { run: holds, count: 0, heldAt: undefined, releasedAt: undefined };\n holds.records++;\n if (#record in obj) holds.others.set(obj, record);\n else new Held(obj, record);\n return record;\n }\n}\n/** Bars during which a released linefill is still skipped by the maximum count. */\nconst LINEFILL_RELEASE_BARS = 5000;\n/** Kinds with a maximum count of their own. */\ntype CountedKind = 'line' | 'label' | 'box' | 'polyline';\nconst COUNTED_KINDS: readonly CountedKind[] = ['line', 'label', 'box', 'polyline'];\nconst isCounted = (kind: DrawingKind): kind is CountedKind => (COUNTED_KINDS as readonly DrawingKind[]).includes(kind);\n/** `P` of the module notes: objects deleted by the script (for polylines also by the maximum count). */\nlet pending: Record<CountedKind, number> = { line: 0, label: 0, box: 0, polyline: 0 };\n/** A creation sets `P` to 0 from this value on. */\nconst PENDING_RESET: Record<CountedKind, number> = { line: 5, label: 5, box: 5, polyline: 3 };\n\n/**\n * Marks an object as held by a `var` variable (PineScript `var line l = ...` or `l := line.new(...)` on a `var`\n * variable): the maximum count never deletes it, and it still counts. Returns the object.\n */\nexport function holdDrawing<T extends object>(obj: T): T {\n const record = Held.get(obj) ?? Held.create(obj);\n if (record.count === 0) record.heldAt = currentBar ?? undefined;\n record.count++;\n return obj;\n}\n\n/** The `var` variable no longer refers to the object (it got another object or `na`). */\nexport function releaseDrawing(obj: object | null | undefined): void {\n if (!obj) return;\n const record = Held.get(obj);\n if (!record || record.count === 0) return;\n record.count--;\n if (record.count === 0 && currentBar !== null) record.releasedAt = currentBar;\n}\n\n/** Held by a `var` variable since a bar before the current one (or outside a bar loop). */\nfunction heldBefore(obj: object): boolean {\n const record = Held.get(obj);\n if (!record || record.count === 0) return false;\n const bar = record.heldAt;\n return bar === undefined || currentBar === null || bar < currentBar;\n}\n\n/**\n * Held by a `var` variable since the current bar, or released by its last variable on the current bar: the maximum\n * count deletes such an object only when the objects it may delete are not enough (#193; 12 `var` lines made on the\n * first bar with a maximum of 5 lose the first 6, #158).\n */\nfunction heldOnThisBar(obj: object): boolean {\n if (currentBar === null) return false;\n const record = Held.get(obj);\n if (!record) return false;\n return record.count > 0 ? record.heldAt === currentBar : record.releasedAt === currentBar;\n}\n\n/** Linefill rule: held, or released less than 5,000 bars ago. */\nfunction fillProtected(obj: object): boolean {\n const record = Held.get(obj);\n if (!record) return false;\n if (record.count > 0) return true;\n const bar = record.releasedAt;\n return bar !== undefined && currentBar !== null && currentBar - bar < LINEFILL_RELEASE_BARS;\n}\n\n/** A `var` variable of a drawing type: see {@link varDrawing}. */\nexport interface DrawingVariable<T extends object> {\n /** The object of the variable; setting it holds the new object and releases the one before */\n value: T | undefined;\n}\n\n/**\n * A PineScript `var` variable of a drawing type (`var line l = na`). The object it refers to is not deleted by the\n * maximum count; assigning another object (or `undefined` for `na`) releases the one before.\n *\n * @example\n * ```typescript\n * // Pine: var line level = na\n * // level := line.new(bar_index, close, bar_index + 1, close)\n * const level = varDrawing<Line>();\n * level.value = line.new(i, close, i + 1, close);\n * ```\n */\nexport function varDrawing<T extends object>(initial?: T): DrawingVariable<T> {\n let current: T | undefined = initial ? holdDrawing(initial) : undefined;\n return {\n get value() {\n return current;\n },\n set value(next: T | undefined) {\n if (next === current) return;\n releaseDrawing(current);\n current = next ? holdDrawing(next) : undefined;\n },\n };\n}\n\n/** Largest distance, in bars, of a bar index before the current bar (PineScript runtime error RE10026 above it). */\nexport const MAX_DRAWING_BARS_BACK = 10000;\n/** Largest distance, in bars, of a bar index after the last bar of the data (PineScript runtime error RE10020 above it). */\nexport const MAX_DRAWING_BARS_FORWARD = 500;\nlet currentBar: number | null = null;\nlet lastBarIndex: number | null = null;\n\n/** Kinds whose allowance on the last bar is the `P` they had when the bar started. */\ntype AllowanceKind = 'line' | 'label' | 'box';\nconst isAllowanceKind = (kind: DrawingKind): kind is AllowanceKind => kind === 'line' || kind === 'label' || kind === 'box';\n\n/** State of the last bar (see the module notes). */\ninterface LastBar {\n bar: number;\n /** The objects alive when the bar started (the objects of the bars before) */\n old: Set<object>;\n /** `P` of lines, labels and boxes when the bar started: their allowance for the whole bar */\n allowance: Record<AllowanceKind, number>;\n /** `P` of polylines when the bar started */\n carried: number;\n /** A polyline was created on this bar */\n polyline: boolean;\n /** Polylines of the bars before deleted on this bar (by the count or by the script) */\n oldPolylinesGone: number;\n}\nlet lastBar: LastBar | null = null;\n\n/**\n * Tells the drawing functions which bar is being calculated (`bar_index`), so that a bar index more than 10,000\n * bars back throws as in PineScript; `null` turns the check off. `eachBar` of the script API calls it.\n *\n * The bar also dates the objects held by a `var` variable (on that bar deleted only when no other object can go,\n * never after). `last` says that it is the last bar of the data, which has rules of its own for the maximum count. `lastIndex` is the bar index of the\n * last bar of the data (PineScript `last_bar_index`): with it, a bar index more than 500 bars after it throws, also\n * on the bars before the last one (RE10020).\n */\nexport function setDrawingBar(barIndex: number | null, last: boolean = false, lastIndex?: number): void {\n if (lastBar && !(last && barIndex === lastBar.bar)) lastBar = null;\n currentBar = barIndex;\n lastBarIndex = barIndex === null ? null : (lastIndex ?? (last ? barIndex : null));\n if (barIndex !== null && last && !lastBar) {\n const start = (kind: AllowanceKind): number => (pending[kind] >= PENDING_RESET[kind] ? 0 : pending[kind]);\n lastBar = {\n bar: barIndex,\n old: new Set<object>([...live.line.toArray(), ...live.label.toArray(), ...live.box.toArray(), ...live.polyline.toArray()]),\n allowance: { line: start('line'), label: start('label'), box: start('box') },\n carried: pending.polyline,\n polyline: false,\n oldPolylinesGone: 0,\n };\n }\n}\n\n/**\n * Throws the PineScript runtime error RE10026 when `x` is a bar index more than 10,000 bars before the current bar,\n * and RE10020 when it is more than 500 bars after the last bar of the data (when {@link setDrawingBar} knows it).\n * `method` and `variable` are the names of the PineScript message (\"line.new\", \"x1\").\n *\n * Returns `x`, truncated when it is a bar index: PineScript's x is an int (a box from 5537.94 starts on bar 5537,\n * #176).\n */\nexport function checkBarIndex(method: string, variable: string, x: number, xloc: string | undefined): number {\n if ((xloc ?? 'bar_index') !== 'bar_index') return x;\n x = Math.trunc(x);\n if (currentBar === null) return x;\n if (lastBarIndex !== null && x - lastBarIndex > MAX_DRAWING_BARS_FORWARD) {\n throw new Error(\n `Error on bar ${currentBar}: Objects positioned using xloc.bar_index cannot be drawn further than ` +\n `${MAX_DRAWING_BARS_FORWARD} bars into the future.`\n );\n }\n if (currentBar - x > MAX_DRAWING_BARS_BACK) {\n throw new Error(\n `Error on bar ${currentBar}: Bar index value of the \\`${variable}\\` argument (${x}) in \\`${method}()\\` is too far ` +\n 'from the current bar index. Try using `time` instead.'\n );\n }\n return x;\n}\n\n/** Numeric fields that become NaN when an object is deleted, so that its getters return `na`. */\nconst COORDINATES: { [K in DrawingKind]: Array<keyof DrawingTypes[K]> } = {\n line: ['x1', 'y1', 'x2', 'y2'],\n label: ['x', 'y'],\n box: ['left', 'top', 'right', 'bottom'],\n polyline: [],\n linefill: [],\n table: [],\n};\n\n/** The live linefills of each line, in creation order: deleting a line or making a fill does not scan all the fills. */\nlet fillsOfLine = new Map<Line, Linefill[]>();\n\nfunction trackFill(fill: Linefill): void {\n for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {\n const fills = fillsOfLine.get(l);\n if (fills) fills.push(fill);\n else fillsOfLine.set(l, [fill]);\n }\n}\n\nfunction untrackFill(fill: Linefill): void {\n for (const l of fill.line1 === fill.line2 ? [fill.line1] : [fill.line1, fill.line2]) {\n const fills = fillsOfLine.get(l);\n if (!fills) continue;\n const k = fills.indexOf(fill);\n if (k !== -1) fills.splice(k, 1);\n if (fills.length === 0) fillsOfLine.delete(l);\n }\n}\n\n/** The live linefills that use `line`, in creation order (do not modify). */\nexport function liveFillsOf(line: Line): readonly Linefill[] {\n return fillsOfLine.get(line) ?? [];\n}\n\nfunction markDeleted<K extends DrawingKind>(kind: K, obj: DrawingTypes[K], explicit: boolean): void {\n Deleted.mark(obj);\n for (const field of COORDINATES[kind]) (obj as unknown as Record<string, unknown>)[field as string] = NaN;\n if (kind === 'line' && explicit) {\n const fills = fillsOfLine.get(obj as Line);\n if (fills) for (const fill of [...fills]) remove('linefill', fill);\n }\n}\n\n/** Objects above the maximum that the rule allows for, besides the 5: `P` of the module notes. */\nfunction allowance(kind: DrawingKind): number {\n if (kind === 'polyline') return pending.polyline;\n return lastBar && isAllowanceKind(kind) ? lastBar.allowance[kind] : 0;\n}\n\n/**\n * The maximum count after the creation of `obj`: removes the objects to delete from `list` (the oldest first; the new\n * object and an object held by a `var` variable are skipped and still count) and returns them.\n */\nfunction cutOldest<K extends DrawingKind>(\n kind: K,\n list: LiveList<DrawingTypes[K]>,\n obj: DrawingTypes[K],\n only?: (old: object) => boolean\n): Array<DrawingTypes[K]> {\n if (kind === 'table') return []; // tables have no maximum count\n const max = limits[kind === 'linefill' ? 'line' : (kind as keyof DrawingLimits)] + allowance(kind);\n if (list.length <= max + SLACK) return [];\n let excess = list.length - max;\n const fill = kind === 'linefill';\n // positions of the objects to delete. The oldest first; the objects a `var` variable got (or released) on this bar\n // only when the others are not enough (the two passes pick different objects)\n const gone: number[] = [];\n for (let pass = 0; pass < (fill ? 1 : 2); pass++) {\n const before = gone.length;\n for (let k = 0; k < list.length && excess > 0; k++) {\n const old = list.at(k);\n if (old === obj || (only && !only(old))) continue;\n if (fill ? fillProtected(old) : heldBefore(old) || heldOnThisBar(old) !== (pass === 1)) continue;\n excess--;\n gone.push(k);\n }\n if (before > 0 && gone.length > before) gone.sort((a, b) => a - b);\n }\n const cut = gone.map((k) => list.at(k));\n // the others keep their order; usually the cut is the oldest run of objects, which leaves by moving the head\n list.removeAll(gone);\n // linefills: still above the maximum + 5, the oldest go, the held ones too\n if (fill && list.length > max + SLACK) cut.push(...list.takeFront(list.length - max));\n return cut;\n}\n\n/** Kinds of the objects created since the last reset (a table counts too), in no order. */\nconst created = new Set<DrawingKind>();\n\n/** The kinds of drawing objects created since the last {@link resetDrawings}, even when none is alive any more. */\nexport function createdDrawingKinds(): DrawingKind[] {\n return [...created];\n}\n\n/** Records a new object and deletes the oldest objects of its kind when the count is too high. */\nexport function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {\n const list = live[kind];\n created.add(kind);\n if (lastBar && isCounted(kind)) return registerLast(lastBar, kind, obj);\n if (isCounted(kind) && pending[kind] >= PENDING_RESET[kind]) pending[kind] = 0;\n list.push(obj);\n if (kind === 'linefill') trackFill(obj as Linefill);\n const cut = cutOldest(kind, list, obj);\n if (kind === 'polyline') pending.polyline += cut.length;\n for (const old of cut) {\n if (kind === 'linefill') untrackFill(old as Linefill);\n markDeleted(kind, old, false);\n }\n return obj;\n}\n\n/** An object created on the last bar (see the module notes). */\nfunction registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {\n if (kind === 'polyline' && !bar.polyline) {\n bar.polyline = true;\n if (pending.polyline >= PENDING_RESET.polyline) pending.polyline = 0;\n else pending.polyline += bar.carried; // counted twice\n }\n const list = live[kind];\n list.push(obj);\n const isOld = (old: object): boolean => bar.old.has(old);\n let oldCandidate = false;\n for (let k = 0; k < list.length && !oldCandidate; k++) {\n const old = list.at(k);\n oldCandidate = old !== obj && isOld(old) && !heldBefore(old) && !heldOnThisBar(old);\n }\n if (oldCandidate) {\n // the objects of the bars before only; a line takes its linefills with it\n const cut = cutOldest(kind, list, obj, isOld);\n if (kind === 'polyline') {\n pending.polyline += cut.length;\n bar.oldPolylinesGone += cut.length;\n }\n for (const old of cut) markDeleted(kind, old, true);\n } else {\n // the polylines of the bars before deleted on this bar count before the cut (#176)\n if (kind === 'polyline' && pending.polyline < bar.oldPolylinesGone) pending.polyline = bar.oldPolylinesGone;\n const cut = cutOldest(kind, list, obj);\n if (kind === 'polyline' && cut.length > 0) pending.polyline = bar.oldPolylinesGone;\n for (const old of cut) markDeleted(kind, old, false);\n }\n return obj;\n}\n\n/** Deletes an object (no effect when it is already deleted). */\nexport function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): void {\n const list = live[kind];\n // from the end: an object is in the list once, and scripts mostly delete their newest objects\n const index = list.lastIndexOf(obj);\n if (index !== -1) {\n list.removeAt(index);\n if (kind === 'linefill') untrackFill(obj as Linefill);\n if (isCounted(kind)) pending[kind]++;\n if (kind === 'polyline' && lastBar?.old.has(obj)) lastBar.oldPolylinesGone++;\n }\n if (!Deleted.has(obj)) markDeleted(kind, obj, true);\n}\n\n/** True when the object was deleted (by `delete` or by the maximum count). */\nexport function isDeleted(obj: unknown): boolean {\n return typeof obj === 'object' && obj !== null && Deleted.has(obj);\n}\n\n/** The live objects of a kind, in creation order (a new array). */\nexport function all<K extends DrawingKind>(kind: K): Array<DrawingTypes[K]> {\n return live[kind].toArray() as Array<DrawingTypes[K]>;\n}\n\n/** Forgets all objects (without deleting them) and sets the maximum counts (default 50). */\nexport function resetDrawings(newLimits: DrawingLimits = {}): void {\n for (const kind of Object.keys(live) as DrawingKind[]) live[kind].replace([]);\n fillsOfLine = new Map();\n created.clear();\n holds = { others: new WeakMap(), records: 0 };\n pending = { line: 0, label: 0, box: 0, polyline: 0 };\n currentBar = null;\n lastBarIndex = null;\n lastBar = null;\n limits = {\n line: newLimits.line ?? DEFAULT_MAX_COUNT,\n label: newLimits.label ?? DEFAULT_MAX_COUNT,\n box: newLimits.box ?? DEFAULT_MAX_COUNT,\n polyline: newLimits.polyline ?? DEFAULT_MAX_COUNT,\n };\n}\n\n/** Changes the maximum counts without forgetting the objects (PineScript `indicator(max_*_count)`). */\nexport function setDrawingLimits(newLimits: DrawingLimits): void {\n limits = { ...limits, ...Object.fromEntries(Object.entries(newLimits).filter(([, v]) => v !== undefined)) };\n}\n\n/** The registry state of a run, saved around a nested run (see {@link restoreDrawingState}). */\nexport interface DrawingState {\n live: { [K in DrawingKind]: Array<DrawingTypes[K]> };\n created: DrawingKind[];\n holds: Holds;\n pending: Record<CountedKind, number>;\n currentBar: number | null;\n lastBarIndex: number | null;\n lastBar: LastBar | null;\n limits: Required<DrawingLimits>;\n}\n\n/** Saves the registry of the current run before a nested run (an intrabar run of a strategy). */\nexport function saveDrawingState(): DrawingState {\n return {\n live: {\n line: live.line.toArray(),\n label: live.label.toArray(),\n box: live.box.toArray(),\n polyline: live.polyline.toArray(),\n linefill: live.linefill.toArray(),\n table: live.table.toArray(),\n },\n created: [...created],\n holds,\n pending: { ...pending },\n currentBar,\n lastBarIndex,\n lastBar,\n limits: { ...limits },\n };\n}\n\n/** Puts back the registry saved by {@link saveDrawingState} after the nested run. */\nexport function restoreDrawingState(s: DrawingState): void {\n for (const kind of Object.keys(live) as DrawingKind[]) (live[kind] as LiveList<object>).replace(s.live[kind]);\n fillsOfLine = new Map();\n for (const fill of s.live.linefill) trackFill(fill);\n created.clear();\n for (const kind of s.created) created.add(kind);\n holds = s.holds;\n pending = { ...s.pending };\n currentBar = s.currentBar;\n lastBarIndex = s.lastBarIndex;\n lastBar = s.lastBar;\n limits = { ...s.limits };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmEO,MAAM,oBAAoB;AAEjC,MAAM,QAAQ;AASd,MAAM,SAAY;AAAA,EACR,QAAa,CAAC;AAAA,EACd,OAAO;AAAA,EAEf,IAAI,SAAiB;AACnB,WAAO,KAAK,MAAM,SAAS,KAAK;AAAA,EAClC;AAAA;AAAA,EAGA,GAAG,GAAc;AACf,WAAO,KAAK,MAAM,KAAK,OAAO,CAAC;AAAA,EACjC;AAAA,EAEA,KAAK,KAAc;AACjB,SAAK,MAAM,KAAK,GAAG;AAAA,EACrB;AAAA;AAAA,EAGA,YAAY,KAAgB;AAC1B,UAAM,QAAQ,KAAK,MAAM,YAAY,GA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,OAAO;AACzB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -65,7 +65,7 @@ export type * from './strategy/index.js';
|
|
|
65
65
|
export { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';
|
|
66
66
|
export type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';
|
|
67
67
|
export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
|
|
68
|
-
export declare const VERSION = "0.15.
|
|
68
|
+
export declare const VERSION = "0.15.3";
|
|
69
69
|
/**
|
|
70
70
|
* Library information
|
|
71
71
|
*/
|
package/dist/cjs/index.js
CHANGED
|
@@ -209,7 +209,7 @@ var import_input_active = require("./runtime/input-active.js");
|
|
|
209
209
|
var import_strategy = require("./strategy/index.js");
|
|
210
210
|
var import_LightweightChartsAdapter = require("./runtime/adapters/LightweightChartsAdapter.js");
|
|
211
211
|
var import_SimpleInputAdapter = require("./runtime/adapters/SimpleInputAdapter.js");
|
|
212
|
-
const VERSION = "0.15.
|
|
212
|
+
const VERSION = "0.15.3";
|
|
213
213
|
const info = {
|
|
214
214
|
name: "OakScriptJS",
|
|
215
215
|
version: VERSION,
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * OakScriptJS - Simplified PineScript-like library for JavaScript\n *\n * This library provides Series-based lazy evaluation and technical analysis functions\n * for building trading indicators. The PineScript-style script API is in `oakscriptjs/script`.\n *\n * Key features:\n * - Series class for lazy evaluation and method chaining\n * - Core TA functions (array-based)\n * - TA-Series wrappers (Series-based)\n *\n * @packageDocumentation\n */\n\n// Export all types\nexport * from './types/index.js';\nexport * from './types/metadata.js';\n\n// Export core namespaces (array-based functions)\nimport * as taCore from './ta/index.js';\nimport * as math from './math/index.js';\nimport * as array from './array/index.js';\nimport * as map from './map/index.js';\nimport * as str from './str/index.js';\nimport * as color from './color/index.js';\nimport * as time from './time/index.js';\nimport * as timeframe from './timeframe/index.js';\nimport * as matrix from './matrix/index.js';\nimport * as line from './line/index.js';\nimport * as box from './box/index.js';\nimport * as label from './label/index.js';\nimport * as linefill from './linefill/index.js';\nimport * as chartPoint from './chartpoint/index.js';\nimport * as polyline from './polyline/index.js';\nimport * as table from './table/index.js';\nimport * as text from './text/index.js';\nimport * as compare from './compare/index.js';\nimport * as callsite from './callsite/index.js';\n\nexport { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };\n\n// Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times\nexport { drawingOutputs, type DrawingOutputs } from './drawing/output.js';\nexport { barInterval, barTime } from './drawing/bar-time.js';\n\n// Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count))\nexport {\n resetDrawings,\n setDrawingLimits,\n setDrawingBar,\n holdDrawing,\n releaseDrawing,\n varDrawing,\n createdDrawingKinds,\n type DrawingKind,\n type DrawingLimits,\n type DrawingVariable,\n} from './drawing/registry.js';\n\n// The session of a chart context without a script run: time(tf, session, timezone), time_close(...), time_tradingday,\n// session.* flags, request.security periods with the session and holidays, and bars after the last bar on the trading\n// calendar\nexport {\n chartSessions,\n sessionPeriods,\n periodTime,\n periodClose,\n tradingDayTime,\n chartSessionFlags,\n resampleSession,\n barTimeAfter,\n barsUntil,\n type SessionContext,\n type ChartSessions,\n type SessionPeriods,\n type SessionResample,\n} from './session/context.js';\nexport { TradingCalendar, type SessionSpec } from './session/calendar.js';\nexport { SessionBars, sessionFlags, type SessionFlags } from './session/bars.js';\n\n// Same-symbol request.security on a higher timeframe (completion and lookahead rules) and ticker.heikinashi\nexport { resample, periodsOf, afterCompletion, mapToChart, heikinAshi, type Resampled } from './security/resample.js';\n// request.security of another symbol: which bar of the other symbol each chart bar shows (#179)\nexport {\n securityOther,\n securityOtherValues,\n securityLowerTf,\n MAX_INTRABARS,\n type OtherSymbolChart,\n type OtherSymbolOptions,\n type SymbolCalendar,\n} from './security/other.js';\n\n// Export Series class (self-contained, no context)\nexport { Series, BarData } from './runtime/series.js';\nexport type { SeriesExtractor } from './runtime/series.js';\n\n// Export TA-Series namespace (Series-based wrappers)\nimport * as ta from './ta-series.js';\nexport { ta };\n\n// Export metadata types for indicator return values\nexport type {\n PlotOptions,\n HLineOptions,\n FillOptions,\n InputMetadata,\n PlotMetadata,\n IndicatorMetadata,\n TimeValue,\n PlotData,\n HLineData,\n FillData,\n FillGradient,\n IndicatorResult,\n IndicatorFactory,\n PlotStyle,\n LineStyle,\n PlotDisplay,\n InputType\n} from './types/metadata.js';\n\n// Re-export commonly used functions for convenience\nexport { sma, ema, rsi, macd, bb, stdev, crossover, crossunder, change, tr, atr, cum, vwap } from './ta-series.js';\nexport { abs, ceil, floor, round, max, min, avg, sum, sqrt, pow, exp, log, sin, cos, tan } from './math/index.js';\nexport { rgb, from_hex as color_from_hex, new_color } from './color/index.js';\n\n// Export chart data utilities\nexport { ohlcFromBars, getClose, getHigh, getLow, getOpen, getSource, getSourceSeries, at, div } from './utils/index.js';\nexport { setSourceResolver, externalSource, BUILTIN_SOURCES, type SourceResolver } from './utils/source-resolver.js';\n\n// Export libraries (ZigZag, etc.)\nexport * from './lib/index.js';\n\n// Export helper functions for generated indicators (PineScript compatibility)\nexport {isNA as na, nz, fixnan} from './utils/index.js';\n\n// Export indicator infrastructure\nexport {\n indicator,\n type IndicatorMetadataConfig,\n type InputDefinition,\n type IndicatorContext,\n type IndicatorInstance,\n type IndicatorConstructor,\n} from './indicator.js';\n\nexport {\n input,\n type InputValue,\n type IntInputOptions,\n type FloatInputOptions,\n type SourceInputOptions,\n type BoolInputOptions,\n type StringInputOptions,\n type TimeInputOptions,\n type SourceType,\n} from './input.js';\n\nexport {\n plot as plotHelper,\n createPlot,\n type Time,\n type TimeValuePair,\n type PlotOptions as PlotHelperOptions,\n type PlotResult,\n} from './plot.js';\n\n// Runtime exports - global context runtime (setContext, plot, hline) drawing through a ChartAdapter\nexport {\n setContext,\n clearContext,\n getContext,\n registerCalculate,\n recalculate,\n plot,\n hline,\n clearPlots,\n} from './runtime/runtime.js';\n\nexport {\n input_int,\n input_float,\n input_bool,\n input_string,\n input_text_area,\n input_source,\n input_timeframe,\n input_session,\n input_symbol,\n input_time,\n} from './runtime/inputs.js';\nexport { isInputActive } from './runtime/input-active.js';\n\nexport type {\n OakScriptContext,\n ChartAdapter,\n InputAdapter,\n SeriesHandle,\n SeriesOptions,\n InputConfig,\n InputCondition,\n InputOptions,\n OhlcvData,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ArrowConfig,\n CandleConfig,\n ShapeConfig,\n BarColorConfig,\n} from './runtime/types.js';\n\n// Strategy types and constants (the script API forwards strategy.* calls to a host engine)\nexport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n} from './strategy/index.js';\nexport type * from './strategy/index.js';\n\nexport { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';\nexport type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';\nexport { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';\n\n// Version\nexport const VERSION = '0.15.
|
|
4
|
+
"sourcesContent": ["/**\n * OakScriptJS - Simplified PineScript-like library for JavaScript\n *\n * This library provides Series-based lazy evaluation and technical analysis functions\n * for building trading indicators. The PineScript-style script API is in `oakscriptjs/script`.\n *\n * Key features:\n * - Series class for lazy evaluation and method chaining\n * - Core TA functions (array-based)\n * - TA-Series wrappers (Series-based)\n *\n * @packageDocumentation\n */\n\n// Export all types\nexport * from './types/index.js';\nexport * from './types/metadata.js';\n\n// Export core namespaces (array-based functions)\nimport * as taCore from './ta/index.js';\nimport * as math from './math/index.js';\nimport * as array from './array/index.js';\nimport * as map from './map/index.js';\nimport * as str from './str/index.js';\nimport * as color from './color/index.js';\nimport * as time from './time/index.js';\nimport * as timeframe from './timeframe/index.js';\nimport * as matrix from './matrix/index.js';\nimport * as line from './line/index.js';\nimport * as box from './box/index.js';\nimport * as label from './label/index.js';\nimport * as linefill from './linefill/index.js';\nimport * as chartPoint from './chartpoint/index.js';\nimport * as polyline from './polyline/index.js';\nimport * as table from './table/index.js';\nimport * as text from './text/index.js';\nimport * as compare from './compare/index.js';\nimport * as callsite from './callsite/index.js';\n\nexport { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };\n\n// Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times\nexport { drawingOutputs, type DrawingOutputs } from './drawing/output.js';\nexport { barInterval, barTime } from './drawing/bar-time.js';\n\n// Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count))\nexport {\n resetDrawings,\n setDrawingLimits,\n setDrawingBar,\n holdDrawing,\n releaseDrawing,\n varDrawing,\n createdDrawingKinds,\n type DrawingKind,\n type DrawingLimits,\n type DrawingVariable,\n} from './drawing/registry.js';\n\n// The session of a chart context without a script run: time(tf, session, timezone), time_close(...), time_tradingday,\n// session.* flags, request.security periods with the session and holidays, and bars after the last bar on the trading\n// calendar\nexport {\n chartSessions,\n sessionPeriods,\n periodTime,\n periodClose,\n tradingDayTime,\n chartSessionFlags,\n resampleSession,\n barTimeAfter,\n barsUntil,\n type SessionContext,\n type ChartSessions,\n type SessionPeriods,\n type SessionResample,\n} from './session/context.js';\nexport { TradingCalendar, type SessionSpec } from './session/calendar.js';\nexport { SessionBars, sessionFlags, type SessionFlags } from './session/bars.js';\n\n// Same-symbol request.security on a higher timeframe (completion and lookahead rules) and ticker.heikinashi\nexport { resample, periodsOf, afterCompletion, mapToChart, heikinAshi, type Resampled } from './security/resample.js';\n// request.security of another symbol: which bar of the other symbol each chart bar shows (#179)\nexport {\n securityOther,\n securityOtherValues,\n securityLowerTf,\n MAX_INTRABARS,\n type OtherSymbolChart,\n type OtherSymbolOptions,\n type SymbolCalendar,\n} from './security/other.js';\n\n// Export Series class (self-contained, no context)\nexport { Series, BarData } from './runtime/series.js';\nexport type { SeriesExtractor } from './runtime/series.js';\n\n// Export TA-Series namespace (Series-based wrappers)\nimport * as ta from './ta-series.js';\nexport { ta };\n\n// Export metadata types for indicator return values\nexport type {\n PlotOptions,\n HLineOptions,\n FillOptions,\n InputMetadata,\n PlotMetadata,\n IndicatorMetadata,\n TimeValue,\n PlotData,\n HLineData,\n FillData,\n FillGradient,\n IndicatorResult,\n IndicatorFactory,\n PlotStyle,\n LineStyle,\n PlotDisplay,\n InputType\n} from './types/metadata.js';\n\n// Re-export commonly used functions for convenience\nexport { sma, ema, rsi, macd, bb, stdev, crossover, crossunder, change, tr, atr, cum, vwap } from './ta-series.js';\nexport { abs, ceil, floor, round, max, min, avg, sum, sqrt, pow, exp, log, sin, cos, tan } from './math/index.js';\nexport { rgb, from_hex as color_from_hex, new_color } from './color/index.js';\n\n// Export chart data utilities\nexport { ohlcFromBars, getClose, getHigh, getLow, getOpen, getSource, getSourceSeries, at, div } from './utils/index.js';\nexport { setSourceResolver, externalSource, BUILTIN_SOURCES, type SourceResolver } from './utils/source-resolver.js';\n\n// Export libraries (ZigZag, etc.)\nexport * from './lib/index.js';\n\n// Export helper functions for generated indicators (PineScript compatibility)\nexport {isNA as na, nz, fixnan} from './utils/index.js';\n\n// Export indicator infrastructure\nexport {\n indicator,\n type IndicatorMetadataConfig,\n type InputDefinition,\n type IndicatorContext,\n type IndicatorInstance,\n type IndicatorConstructor,\n} from './indicator.js';\n\nexport {\n input,\n type InputValue,\n type IntInputOptions,\n type FloatInputOptions,\n type SourceInputOptions,\n type BoolInputOptions,\n type StringInputOptions,\n type TimeInputOptions,\n type SourceType,\n} from './input.js';\n\nexport {\n plot as plotHelper,\n createPlot,\n type Time,\n type TimeValuePair,\n type PlotOptions as PlotHelperOptions,\n type PlotResult,\n} from './plot.js';\n\n// Runtime exports - global context runtime (setContext, plot, hline) drawing through a ChartAdapter\nexport {\n setContext,\n clearContext,\n getContext,\n registerCalculate,\n recalculate,\n plot,\n hline,\n clearPlots,\n} from './runtime/runtime.js';\n\nexport {\n input_int,\n input_float,\n input_bool,\n input_string,\n input_text_area,\n input_source,\n input_timeframe,\n input_session,\n input_symbol,\n input_time,\n} from './runtime/inputs.js';\nexport { isInputActive } from './runtime/input-active.js';\n\nexport type {\n OakScriptContext,\n ChartAdapter,\n InputAdapter,\n SeriesHandle,\n SeriesOptions,\n InputConfig,\n InputCondition,\n InputOptions,\n OhlcvData,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ArrowConfig,\n CandleConfig,\n ShapeConfig,\n BarColorConfig,\n} from './runtime/types.js';\n\n// Strategy types and constants (the script API forwards strategy.* calls to a host engine)\nexport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n} from './strategy/index.js';\nexport type * from './strategy/index.js';\n\nexport { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';\nexport type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';\nexport { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';\n\n// Version\nexport const VERSION = '0.15.3';\n\n/**\n * Library information\n */\nexport const info = {\n name: 'OakScriptJS',\n version: VERSION,\n description: 'Simplified PineScript-like library - Series + TA functions',\n features: {\n series: 'Lazy evaluation with Series class',\n ta: 'Technical analysis functions (Series and array-based)',\n script: 'PineScript-style script API (oakscriptjs/script): indicator, strategy, inputs, plots, request.security',\n runtime: 'Global context runtime drawing through a ChartAdapter',\n indicator: 'Indicator function with automatic pane management'\n },\n namespaces: {\n core: ['ta', 'math', 'array', 'map', 'str', 'color', 'time', 'timeframe', 'matrix'],\n drawing: ['line', 'box', 'label', 'linefill', 'chartPoint', 'polyline', 'table', 'text'],\n runtime: ['setContext', 'plot', 'hline', 'input_*'],\n indicator: ['indicator', 'input', 'plotHelper', 'createPlot']\n }\n};\n\n// PineScript compatibility stubs - functions that have no runtime effect\n// These are no-ops so that PineScript-style code runs without modification\n\n/**\n * alertcondition() - Stub for PineScript alert configuration\n * In PineScript, this registers an alert condition. In oakscriptjs, it's a no-op\n * since alert configuration is handled by the host application.\n */\nexport function alertcondition(_condition: unknown, _title?: string, _message?: string): void {\n // No-op: Alert conditions are handled by the host application\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,0BAAc,6BAfd;AAgBA,0BAAc,gCAhBd;AAmBA,a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26,6 +26,8 @@ export declare class SessionBars {
|
|
|
26
26
|
readonly calendar: TradingCalendar;
|
|
27
27
|
readonly chart: TimeframeInfo;
|
|
28
28
|
private readonly yearDays;
|
|
29
|
+
/** Parsed timeframes: `timeOf` / `closeOf` run on every bar */
|
|
30
|
+
private readonly timeframes;
|
|
29
31
|
constructor(calendar: TradingCalendar, chartTimeframe: string);
|
|
30
32
|
/** Trading days of a calendar year, in order. */
|
|
31
33
|
private tradingDaysOf;
|
|
@@ -34,6 +36,7 @@ export declare class SessionBars {
|
|
|
34
36
|
* Periods restart each calendar year.
|
|
35
37
|
*/
|
|
36
38
|
private periodRange;
|
|
39
|
+
private timeframe;
|
|
37
40
|
private dayStart;
|
|
38
41
|
private dayEnd;
|
|
39
42
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bars.d.ts","sourceRoot":"","sources":["../../../src/session/bars.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAoB,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EACL,eAAe,EAMf,KAAK,OAAO,EACb,MAAM,eAAe,CAAC;AAiBvB,+DAA+D;AAC/D,qBAAa,WAAW;
|
|
1
|
+
{"version":3,"file":"bars.d.ts","sourceRoot":"","sources":["../../../src/session/bars.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAoB,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EACL,eAAe,EAMf,KAAK,OAAO,EACb,MAAM,eAAe,CAAC;AAiBvB,+DAA+D;AAC/D,qBAAa,WAAW;IAQpB,QAAQ,CAAC,QAAQ,EAAE,eAAe;IAPpC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAE9B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgC;IACzD,+DAA+D;IAC/D,OAAO,CAAC,QAAQ,CAAC,UAAU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C3B,UAAU,EAAE,OAAO,EAAE,CAAC;IACtB,SAAS,EAAE,OAAO,EAAE,CAAC;IACrB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,WAAW,EAAE,OAAO,EAAE,CAAC;IACvB,YAAY,EAAE,OAAO,EAAE,CAAC;IACxB,kBAAkB,EAAE,OAAO,EAAE,CAAC;IAC9B,iBAAiB,EAAE,OAAO,EAAE,CAAC;CAC9B;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,GAAG,YAAY,CA6CnG"}
|
package/dist/cjs/session/bars.js
CHANGED
|
@@ -42,6 +42,8 @@ class SessionBars {
|
|
|
42
42
|
calendar;
|
|
43
43
|
chart;
|
|
44
44
|
yearDays = /* @__PURE__ */ new Map();
|
|
45
|
+
/** Parsed timeframes: `timeOf` / `closeOf` run on every bar */
|
|
46
|
+
timeframes = /* @__PURE__ */ new Map();
|
|
45
47
|
/** Trading days of a calendar year, in order. */
|
|
46
48
|
tradingDaysOf(year) {
|
|
47
49
|
let days = this.yearDays.get(year);
|
|
@@ -83,6 +85,11 @@ class SessionBars {
|
|
|
83
85
|
const lastMonth = Math.min(firstMonth + n - 1, 12);
|
|
84
86
|
return [(0, import_calendar.monthStart)(year * 1e4 + firstMonth * 100 + 1), (0, import_calendar.monthEnd)(year * 1e4 + lastMonth * 100 + 1)];
|
|
85
87
|
}
|
|
88
|
+
timeframe(timeframe) {
|
|
89
|
+
let tf = this.timeframes.get(timeframe);
|
|
90
|
+
if (!tf) this.timeframes.set(timeframe, tf = (0, import_timeframe.info)(timeframe));
|
|
91
|
+
return tf;
|
|
92
|
+
}
|
|
86
93
|
dayStart(date) {
|
|
87
94
|
return this.calendar.periods(date)[0][0];
|
|
88
95
|
}
|
|
@@ -96,7 +103,7 @@ class SessionBars {
|
|
|
96
103
|
* NaN on it (measured; `time("W")` keeps its value).
|
|
97
104
|
*/
|
|
98
105
|
timeOf(time, timeframe) {
|
|
99
|
-
const tf =
|
|
106
|
+
const tf = this.timeframe(timeframe);
|
|
100
107
|
const at = this.calendar.locate(time);
|
|
101
108
|
if (!at) return NaN;
|
|
102
109
|
if (tf.isintraday) {
|
|
@@ -114,7 +121,7 @@ class SessionBars {
|
|
|
114
121
|
}
|
|
115
122
|
/** PineScript `time_close(tf)` for a bar that opens at `time`. */
|
|
116
123
|
closeOf(time, timeframe) {
|
|
117
|
-
const tf =
|
|
124
|
+
const tf = this.timeframe(timeframe);
|
|
118
125
|
const at = this.calendar.locate(time);
|
|
119
126
|
if (!at) return NaN;
|
|
120
127
|
if (tf.isintraday) {
|
|
@@ -151,7 +158,7 @@ class SessionBars {
|
|
|
151
158
|
* bar completes a higher-timeframe period (request.security).
|
|
152
159
|
*/
|
|
153
160
|
periodEnd(time, timeframe) {
|
|
154
|
-
const tf =
|
|
161
|
+
const tf = this.timeframe(timeframe);
|
|
155
162
|
const at = this.calendar.locate(time);
|
|
156
163
|
if (!at) return NaN;
|
|
157
164
|
if (tf.isintraday) {
|