oakscriptjs 0.15.2 → 0.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/cjs/check/format.d.ts.map +1 -1
  2. package/dist/cjs/check/format.js +5 -0
  3. package/dist/cjs/check/format.js.map +2 -2
  4. package/dist/cjs/check/harness.d.ts +24 -0
  5. package/dist/cjs/check/harness.d.ts.map +1 -1
  6. package/dist/cjs/check/harness.js +33 -0
  7. package/dist/cjs/check/harness.js.map +2 -2
  8. package/dist/cjs/check/index.d.ts +9 -0
  9. package/dist/cjs/check/index.d.ts.map +1 -1
  10. package/dist/cjs/check/index.js +7 -0
  11. package/dist/cjs/check/index.js.map +2 -2
  12. package/dist/cjs/color/index.d.ts.map +1 -1
  13. package/dist/cjs/color/index.js +19 -2
  14. package/dist/cjs/color/index.js.map +2 -2
  15. package/dist/cjs/color/parse.d.ts +8 -6
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +15 -2
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/drawing/registry.d.ts +32 -0
  20. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  21. package/dist/cjs/drawing/registry.js +179 -45
  22. package/dist/cjs/drawing/registry.js.map +2 -2
  23. package/dist/cjs/index.d.ts +2 -1
  24. package/dist/cjs/index.d.ts.map +1 -1
  25. package/dist/cjs/index.js +3 -1
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/runtime/series.d.ts +16 -0
  28. package/dist/cjs/runtime/series.d.ts.map +1 -1
  29. package/dist/cjs/runtime/series.js +19 -2
  30. package/dist/cjs/runtime/series.js.map +2 -2
  31. package/dist/cjs/script/closure-writes.d.ts +16 -0
  32. package/dist/cjs/script/closure-writes.d.ts.map +1 -0
  33. package/dist/cjs/script/closure-writes.js +435 -0
  34. package/dist/cjs/script/closure-writes.js.map +7 -0
  35. package/dist/cjs/script/globals.d.ts +2 -0
  36. package/dist/cjs/script/globals.d.ts.map +1 -1
  37. package/dist/cjs/script/globals.js.map +1 -1
  38. package/dist/cjs/script/incremental.d.ts +140 -0
  39. package/dist/cjs/script/incremental.d.ts.map +1 -0
  40. package/dist/cjs/script/incremental.js +142 -0
  41. package/dist/cjs/script/incremental.js.map +7 -0
  42. package/dist/cjs/script/index.d.ts +116 -31
  43. package/dist/cjs/script/index.d.ts.map +1 -1
  44. package/dist/cjs/script/index.js +471 -25
  45. package/dist/cjs/script/index.js.map +3 -3
  46. package/dist/cjs/session/bars.d.ts +3 -0
  47. package/dist/cjs/session/bars.d.ts.map +1 -1
  48. package/dist/cjs/session/bars.js +10 -3
  49. package/dist/cjs/session/bars.js.map +2 -2
  50. package/dist/cjs/session/calendar.d.ts +19 -6
  51. package/dist/cjs/session/calendar.d.ts.map +1 -1
  52. package/dist/cjs/session/calendar.js +57 -18
  53. package/dist/cjs/session/calendar.js.map +2 -2
  54. package/dist/cjs/session/context.d.ts.map +1 -1
  55. package/dist/cjs/session/context.js +25 -8
  56. package/dist/cjs/session/context.js.map +2 -2
  57. package/dist/cjs/str/numberformat.d.ts.map +1 -1
  58. package/dist/cjs/str/numberformat.js +23 -0
  59. package/dist/cjs/str/numberformat.js.map +2 -2
  60. package/dist/cjs/strategy/index.d.ts +8 -0
  61. package/dist/cjs/strategy/index.d.ts.map +1 -1
  62. package/dist/cjs/strategy/index.js.map +1 -1
  63. package/dist/cjs/ta/running-sum.d.ts.map +1 -1
  64. package/dist/cjs/ta/running-sum.js +72 -3
  65. package/dist/cjs/ta/running-sum.js.map +2 -2
  66. package/dist/cjs/ta/step.d.ts +476 -0
  67. package/dist/cjs/ta/step.d.ts.map +1 -0
  68. package/dist/cjs/ta/step.js +1000 -0
  69. package/dist/cjs/ta/step.js.map +7 -0
  70. package/dist/cjs/ta-series.d.ts +1 -1
  71. package/dist/cjs/ta-series.js +3 -3
  72. package/dist/cjs/ta-series.js.map +1 -1
  73. package/dist/cjs/time/timezone.d.ts +13 -1
  74. package/dist/cjs/time/timezone.d.ts.map +1 -1
  75. package/dist/cjs/time/timezone.js +52 -13
  76. package/dist/cjs/time/timezone.js.map +2 -2
  77. package/dist/esm/check/format.d.ts.map +1 -1
  78. package/dist/esm/check/format.js +5 -0
  79. package/dist/esm/check/format.js.map +1 -1
  80. package/dist/esm/check/harness.d.ts +24 -0
  81. package/dist/esm/check/harness.d.ts.map +1 -1
  82. package/dist/esm/check/harness.js +40 -6
  83. package/dist/esm/check/harness.js.map +1 -1
  84. package/dist/esm/check/index.d.ts +9 -0
  85. package/dist/esm/check/index.d.ts.map +1 -1
  86. package/dist/esm/check/index.js +11 -1
  87. package/dist/esm/check/index.js.map +1 -1
  88. package/dist/esm/color/index.d.ts.map +1 -1
  89. package/dist/esm/color/index.js +23 -3
  90. package/dist/esm/color/index.js.map +1 -1
  91. package/dist/esm/color/parse.d.ts +8 -6
  92. package/dist/esm/color/parse.d.ts.map +1 -1
  93. package/dist/esm/color/parse.js +19 -2
  94. package/dist/esm/color/parse.js.map +1 -1
  95. package/dist/esm/drawing/registry.d.ts +32 -0
  96. package/dist/esm/drawing/registry.d.ts.map +1 -1
  97. package/dist/esm/drawing/registry.js +214 -51
  98. package/dist/esm/drawing/registry.js.map +1 -1
  99. package/dist/esm/index.d.ts +2 -1
  100. package/dist/esm/index.d.ts.map +1 -1
  101. package/dist/esm/index.js +3 -1
  102. package/dist/esm/index.js.map +1 -1
  103. package/dist/esm/runtime/series.d.ts +16 -0
  104. package/dist/esm/runtime/series.d.ts.map +1 -1
  105. package/dist/esm/runtime/series.js +21 -1
  106. package/dist/esm/runtime/series.js.map +1 -1
  107. package/dist/esm/script/closure-writes.d.ts +16 -0
  108. package/dist/esm/script/closure-writes.d.ts.map +1 -0
  109. package/dist/esm/script/closure-writes.js +323 -0
  110. package/dist/esm/script/closure-writes.js.map +1 -0
  111. package/dist/esm/script/globals.d.ts +2 -0
  112. package/dist/esm/script/globals.d.ts.map +1 -1
  113. package/dist/esm/script/globals.js.map +1 -1
  114. package/dist/esm/script/incremental.d.ts +140 -0
  115. package/dist/esm/script/incremental.d.ts.map +1 -0
  116. package/dist/esm/script/incremental.js +173 -0
  117. package/dist/esm/script/incremental.js.map +1 -0
  118. package/dist/esm/script/index.d.ts +116 -31
  119. package/dist/esm/script/index.d.ts.map +1 -1
  120. package/dist/esm/script/index.js +561 -24
  121. package/dist/esm/script/index.js.map +1 -1
  122. package/dist/esm/session/bars.d.ts +3 -0
  123. package/dist/esm/session/bars.d.ts.map +1 -1
  124. package/dist/esm/session/bars.js +11 -3
  125. package/dist/esm/session/bars.js.map +1 -1
  126. package/dist/esm/session/calendar.d.ts +19 -6
  127. package/dist/esm/session/calendar.d.ts.map +1 -1
  128. package/dist/esm/session/calendar.js +74 -21
  129. package/dist/esm/session/calendar.js.map +1 -1
  130. package/dist/esm/session/context.d.ts.map +1 -1
  131. package/dist/esm/session/context.js +34 -9
  132. package/dist/esm/session/context.js.map +1 -1
  133. package/dist/esm/str/numberformat.d.ts.map +1 -1
  134. package/dist/esm/str/numberformat.js +30 -0
  135. package/dist/esm/str/numberformat.js.map +1 -1
  136. package/dist/esm/strategy/index.d.ts +8 -0
  137. package/dist/esm/strategy/index.d.ts.map +1 -1
  138. package/dist/esm/ta/running-sum.d.ts.map +1 -1
  139. package/dist/esm/ta/running-sum.js +79 -4
  140. package/dist/esm/ta/running-sum.js.map +1 -1
  141. package/dist/esm/ta/step.d.ts +476 -0
  142. package/dist/esm/ta/step.d.ts.map +1 -0
  143. package/dist/esm/ta/step.js +1089 -0
  144. package/dist/esm/ta/step.js.map +1 -0
  145. package/dist/esm/ta-series.d.ts +1 -1
  146. package/dist/esm/ta-series.js +4 -4
  147. package/dist/esm/time/timezone.d.ts +13 -1
  148. package/dist/esm/time/timezone.d.ts.map +1 -1
  149. package/dist/esm/time/timezone.js +78 -17
  150. package/dist/esm/time/timezone.js.map +1 -1
  151. package/package.json +1 -1
  152. package/skills/oakscript/SKILL.md +2 -2
  153. package/skills/oakscript/reference/check.md +5 -0
  154. package/skills/oakscript/reference/errors.md +0 -1
  155. package/skills/oakscript/reference/pine-differences.md +1 -2
  156. package/skills/oakscript/reference/plotting.md +5 -7
  157. package/skills/oakscript/reference/script-structure.md +6 -0
  158. package/src/check/format.ts +7 -0
  159. package/src/check/harness.ts +57 -0
  160. package/src/check/index.ts +16 -0
  161. package/src/color/index.ts +22 -3
  162. package/src/color/parse.ts +28 -3
  163. package/src/drawing/registry.ts +233 -50
  164. package/src/index.ts +4 -1
  165. package/src/runtime/series.ts +33 -1
  166. package/src/script/closure-writes.ts +279 -0
  167. package/src/script/globals.ts +2 -0
  168. package/src/script/incremental.ts +246 -0
  169. package/src/script/index.ts +695 -26
  170. package/src/session/bars.ts +11 -3
  171. package/src/session/calendar.ts +84 -21
  172. package/src/session/context.ts +36 -9
  173. package/src/str/numberformat.ts +29 -0
  174. package/src/strategy/index.ts +8 -0
  175. package/src/ta/running-sum.ts +78 -3
  176. package/src/ta/step.ts +1145 -0
  177. package/src/ta-series.ts +4 -4
  178. package/src/time/timezone.ts +76 -15
@@ -4,12 +4,37 @@
4
4
 
5
5
  import type { color, int, float } from '../types/index.js';
6
6
 
7
+ export interface ParsedColor {
8
+ readonly r: int;
9
+ readonly g: int;
10
+ readonly b: int;
11
+ readonly a: float;
12
+ }
13
+
14
+ const BLACK: ParsedColor = { r: 0, g: 0, b: 0, a: 1 };
15
+
16
+ /** Parsed colours by text: a script reads the same few colours on every bar, and again on each run. */
17
+ const parsed = new Map<string, ParsedColor>();
18
+ const PARSED_KEPT = 4096;
19
+
7
20
  /**
8
21
  * Parses a colour string to its channels (0-255) and alpha (0-1).
9
22
  * Hex: #RRGGBB, #RRGGBBAA (PineScript literals), #RGB, #RGBA; rgb() / rgba(). Anything else is opaque black.
23
+ * The result is shared between calls: do not change it.
10
24
  */
11
- export function parseColor(clr: color): { r: int; g: int; b: int; a: float } {
12
- if (typeof clr === 'string') {
25
+ export function parseColor(clr: color): ParsedColor {
26
+ if (typeof clr !== 'string') return BLACK;
27
+ let p = parsed.get(clr);
28
+ if (p === undefined) {
29
+ p = parseText(clr);
30
+ if (parsed.size >= PARSED_KEPT) parsed.clear();
31
+ parsed.set(clr, p);
32
+ }
33
+ return p;
34
+ }
35
+
36
+ function parseText(clr: string): ParsedColor {
37
+ {
13
38
  const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(clr.trim());
14
39
  if (hex) {
15
40
  let digits = hex[1]!;
@@ -27,7 +52,7 @@ export function parseColor(clr: color): { r: int; g: int; b: int; a: float } {
27
52
  };
28
53
  }
29
54
  }
30
- return { r: 0, g: 0, b: 0, a: 1 };
55
+ return BLACK;
31
56
  }
32
57
 
33
58
  /** Alpha byte (0-255) of an alpha (0-1), as PineScript stores it. */
@@ -71,13 +71,87 @@ const SLACK = 5;
71
71
 
72
72
  export type DrawingLimits = Partial<Record<Exclude<DrawingKind, 'linefill' | 'table'>, number>>;
73
73
 
74
- const live: { [K in DrawingKind]: Array<DrawingTypes[K]> } = {
75
- line: [],
76
- label: [],
77
- box: [],
78
- polyline: [],
79
- linefill: [],
80
- table: [],
74
+ /**
75
+ * The live objects of a kind, in creation order. The maximum count deletes the oldest ones: they leave by moving the
76
+ * head, and the array drops its dead front once it is as long as the live part, so a creation at the maximum costs
77
+ * O(1) amortised instead of a move of the whole list on every cut.
78
+ */
79
+ class LiveList<T> {
80
+ private items: T[] = [];
81
+ private head = 0;
82
+
83
+ get length(): number {
84
+ return this.items.length - this.head;
85
+ }
86
+
87
+ /** The `k`-th live object (0: the oldest) */
88
+ at(k: number): T {
89
+ return this.items[this.head + k]!;
90
+ }
91
+
92
+ push(obj: T): void {
93
+ this.items.push(obj);
94
+ }
95
+
96
+ /** Position of `obj` among the live objects, -1 when it is not one */
97
+ lastIndexOf(obj: T): number {
98
+ const index = this.items.lastIndexOf(obj);
99
+ return index >= this.head ? index - this.head : -1;
100
+ }
101
+
102
+ removeAt(k: number): void {
103
+ if (k === 0) this.dropFront(1);
104
+ else this.items.splice(this.head + k, 1);
105
+ }
106
+
107
+ /** Removes the live objects at positions `gone` (increasing); the others keep their order */
108
+ removeAll(gone: readonly number[]): void {
109
+ if (gone.length === 0) return;
110
+ if (gone[0] === 0 && gone[gone.length - 1] === gone.length - 1) {
111
+ this.dropFront(gone.length);
112
+ return;
113
+ }
114
+ const items = this.items;
115
+ let to = this.head + gone[0]!;
116
+ for (let from = to, g = 0; from < items.length; from++) {
117
+ if (from - this.head === gone[g]) g++;
118
+ else items[to++] = items[from]!;
119
+ }
120
+ items.length = to;
121
+ }
122
+
123
+ /** Removes the `n` oldest objects and returns them */
124
+ takeFront(n: number): T[] {
125
+ const out = this.items.slice(this.head, this.head + n);
126
+ this.dropFront(n);
127
+ return out;
128
+ }
129
+
130
+ private dropFront(n: number): void {
131
+ this.head += n;
132
+ if (this.head >= this.length) {
133
+ this.items = this.items.slice(this.head);
134
+ this.head = 0;
135
+ }
136
+ }
137
+
138
+ toArray(): T[] {
139
+ return this.items.slice(this.head);
140
+ }
141
+
142
+ replace(objs: readonly T[]): void {
143
+ this.items = [...objs];
144
+ this.head = 0;
145
+ }
146
+ }
147
+
148
+ const live: { [K in DrawingKind]: LiveList<DrawingTypes[K]> } = {
149
+ line: new LiveList(),
150
+ label: new LiveList(),
151
+ box: new LiveList(),
152
+ polyline: new LiveList(),
153
+ linefill: new LiveList(),
154
+ table: new LiveList(),
81
155
  };
82
156
  let limits: Required<DrawingLimits> = {
83
157
  line: DEFAULT_MAX_COUNT,
@@ -97,21 +171,51 @@ export class Stamped {
97
171
  }
98
172
  }
99
173
 
100
- /** The deleted objects. */
174
+ /** The deleted objects (an incremental run can bring one back when it puts the registry back, #196). */
101
175
  class Deleted extends Stamped {
102
176
  #deleted = true;
103
177
  static mark(obj: object): void {
104
- if (!Deleted.has(obj)) new Deleted(obj);
178
+ if (#deleted in obj) (obj as Deleted).#deleted = true;
179
+ else new Deleted(obj);
180
+ }
181
+ static unmark(obj: object): void {
182
+ if (#deleted in obj) (obj as Deleted).#deleted = false;
105
183
  }
106
184
  static has(obj: object): boolean {
107
- return #deleted in obj;
185
+ return #deleted in obj && (obj as Deleted).#deleted;
108
186
  }
109
187
  }
110
188
 
189
+ /** The objects the registry recorded (drawing objects, kept as references by the copies of an incremental run). */
190
+ const registered = new WeakSet<object>();
191
+
192
+ /** True for a drawing object of the registry (a line, a label, a box, a polyline, a linefill or a table). */
193
+ export function isDrawingObject(value: unknown): boolean {
194
+ return typeof value === 'object' && value !== null && registered.has(value);
195
+ }
196
+
197
+ /** Hooks of an incremental script run (#196, set by the script runtime during a run only). @internal */
198
+ export interface DrawingRunHooks {
199
+ /** A drawing function read or changed the registry or an object */
200
+ access(): void;
201
+ /** A creation: the object of the previous run to use instead of `obj` (its fields are set to those of `obj`) */
202
+ reuse(kind: DrawingKind, obj: object): object | null;
203
+ }
204
+
205
+ let runHooks: DrawingRunHooks | null = null;
206
+
207
+ /** @internal */
208
+ export function setDrawingRunHooks(hooks: DrawingRunHooks | null): void {
209
+ runHooks = hooks;
210
+ }
211
+
111
212
  /** The `var` records of a run: a reset starts new ones, a nested run saves and puts back those of its run. */
112
213
  interface Holds {
113
214
  /** The records of the objects whose private record belongs to another run */
114
215
  readonly others: WeakMap<object, HoldRecord>;
216
+ /** Records made in the run. None: no object has one, nothing to look up for each object the maximum count may
217
+ * delete */
218
+ records: number;
115
219
  }
116
220
 
117
221
  /** What the `var` variables of a run did with an object. */
@@ -125,7 +229,7 @@ interface HoldRecord {
125
229
  /** Bar on which the last `var` variable released the object (linefill rule) */
126
230
  releasedAt: number | undefined;
127
231
  }
128
- let holds: Holds = { others: new WeakMap() };
232
+ let holds: Holds = { others: new WeakMap(), records: 0 };
129
233
 
130
234
  /**
131
235
  * The record of the first run that holds an object, on the object itself (a study holding a new object on every bar
@@ -139,12 +243,14 @@ class Held extends Stamped {
139
243
  }
140
244
  /** The record of `obj` in the current run, if any. */
141
245
  static get(obj: object): HoldRecord | undefined {
246
+ if (holds.records === 0) return undefined;
142
247
  const own = #record in obj ? (obj as Held).#record : undefined;
143
248
  return own?.run === holds ? own : holds.others.get(obj);
144
249
  }
145
250
  /** A new record of `obj` in the current run (it has none). */
146
251
  static create(obj: object): HoldRecord {
147
252
  const record: HoldRecord = { run: holds, count: 0, heldAt: undefined, releasedAt: undefined };
253
+ holds.records++;
148
254
  if (#record in obj) holds.others.set(obj, record);
149
255
  else new Held(obj, record);
150
256
  return record;
@@ -286,7 +392,7 @@ export function setDrawingBar(barIndex: number | null, last: boolean = false, la
286
392
  const start = (kind: AllowanceKind): number => (pending[kind] >= PENDING_RESET[kind] ? 0 : pending[kind]);
287
393
  lastBar = {
288
394
  bar: barIndex,
289
- old: new Set<object>([...live.line, ...live.label, ...live.box, ...live.polyline]),
395
+ old: new Set<object>([...live.line.toArray(), ...live.label.toArray(), ...live.box.toArray(), ...live.polyline.toArray()]),
290
396
  allowance: { line: start('line'), label: start('label'), box: start('box') },
291
397
  carried: pending.polyline,
292
398
  polyline: false,
@@ -379,7 +485,7 @@ function allowance(kind: DrawingKind): number {
379
485
  */
380
486
  function cutOldest<K extends DrawingKind>(
381
487
  kind: K,
382
- list: Array<DrawingTypes[K]>,
488
+ list: LiveList<DrawingTypes[K]>,
383
489
  obj: DrawingTypes[K],
384
490
  only?: (old: object) => boolean
385
491
  ): Array<DrawingTypes[K]> {
@@ -387,35 +493,26 @@ function cutOldest<K extends DrawingKind>(
387
493
  const max = limits[kind === 'linefill' ? 'line' : (kind as keyof DrawingLimits)] + allowance(kind);
388
494
  if (list.length <= max + SLACK) return [];
389
495
  let excess = list.length - max;
390
- const candidate = (old: DrawingTypes[K]): boolean =>
391
- old !== obj && (!only || only(old)) && !(kind === 'linefill' ? fillProtected(old) : heldBefore(old));
496
+ const fill = kind === 'linefill';
392
497
  // positions of the objects to delete. The oldest first; the objects a `var` variable got (or released) on this bar
393
498
  // only when the others are not enough (the two passes pick different objects)
394
499
  const gone: number[] = [];
395
- for (const weak of kind === 'linefill' ? [false] : [false, true]) {
500
+ for (let pass = 0; pass < (fill ? 1 : 2); pass++) {
396
501
  const before = gone.length;
397
502
  for (let k = 0; k < list.length && excess > 0; k++) {
398
- const old = list[k]!;
399
- if (candidate(old) && (kind === 'linefill' || heldOnThisBar(old) === weak)) {
400
- excess--;
401
- gone.push(k);
402
- }
503
+ const old = list.at(k);
504
+ if (old === obj || (only && !only(old))) continue;
505
+ if (fill ? fillProtected(old) : heldBefore(old) || heldOnThisBar(old) !== (pass === 1)) continue;
506
+ excess--;
507
+ gone.push(k);
403
508
  }
404
509
  if (before > 0 && gone.length > before) gone.sort((a, b) => a - b);
405
510
  }
406
- const cut = gone.map((k) => list[k]!);
407
- // the others keep their order; usually the cut is the oldest run of objects, removed at once
408
- if (gone.length > 0 && gone[gone.length - 1]! - gone[0]! === gone.length - 1) list.splice(gone[0]!, gone.length);
409
- else if (gone.length > 0) {
410
- let to = gone[0]!;
411
- for (let from = to, g = 0; from < list.length; from++) {
412
- if (from === gone[g]) g++;
413
- else list[to++] = list[from]!;
414
- }
415
- list.length = to;
416
- }
511
+ const cut = gone.map((k) => list.at(k));
512
+ // the others keep their order; usually the cut is the oldest run of objects, which leaves by moving the head
513
+ list.removeAll(gone);
417
514
  // linefills: still above the maximum + 5, the oldest go, the held ones too
418
- if (kind === 'linefill' && list.length > max + SLACK) cut.push(...list.splice(0, list.length - max));
515
+ if (fill && list.length > max + SLACK) cut.push(...list.takeFront(list.length - max));
419
516
  return cut;
420
517
  }
421
518
 
@@ -429,6 +526,18 @@ export function createdDrawingKinds(): DrawingKind[] {
429
526
 
430
527
  /** Records a new object and deletes the oldest objects of its kind when the count is too high. */
431
528
  export function register<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): DrawingTypes[K] {
529
+ if (runHooks) {
530
+ runHooks.access();
531
+ const old = runHooks.reuse(kind, obj);
532
+ if (old && old !== obj) {
533
+ // the same object as in the previous run, with the fields of the new one
534
+ for (const key of Object.keys(old)) if (!(key in obj)) delete (old as Record<string, unknown>)[key];
535
+ Object.assign(old, obj);
536
+ Deleted.unmark(old);
537
+ obj = old as DrawingTypes[K];
538
+ }
539
+ }
540
+ registered.add(obj);
432
541
  const list = live[kind];
433
542
  created.add(kind);
434
543
  if (lastBar && isCounted(kind)) return registerLast(lastBar, kind, obj);
@@ -454,7 +563,12 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
454
563
  const list = live[kind];
455
564
  list.push(obj);
456
565
  const isOld = (old: object): boolean => bar.old.has(old);
457
- if (list.some((old) => old !== obj && isOld(old) && !heldBefore(old) && !heldOnThisBar(old))) {
566
+ let oldCandidate = false;
567
+ for (let k = 0; k < list.length && !oldCandidate; k++) {
568
+ const old = list.at(k);
569
+ oldCandidate = old !== obj && isOld(old) && !heldBefore(old) && !heldOnThisBar(old);
570
+ }
571
+ if (oldCandidate) {
458
572
  // the objects of the bars before only; a line takes its linefills with it
459
573
  const cut = cutOldest(kind, list, obj, isOld);
460
574
  if (kind === 'polyline') {
@@ -474,11 +588,12 @@ function registerLast<K extends DrawingKind>(bar: LastBar, kind: K, obj: Drawing
474
588
 
475
589
  /** Deletes an object (no effect when it is already deleted). */
476
590
  export function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): void {
591
+ runHooks?.access();
477
592
  const list = live[kind];
478
593
  // from the end: an object is in the list once, and scripts mostly delete their newest objects
479
594
  const index = list.lastIndexOf(obj);
480
595
  if (index !== -1) {
481
- list.splice(index, 1);
596
+ list.removeAt(index);
482
597
  if (kind === 'linefill') untrackFill(obj as Linefill);
483
598
  if (isCounted(kind)) pending[kind]++;
484
599
  if (kind === 'polyline' && lastBar?.old.has(obj)) lastBar.oldPolylinesGone++;
@@ -488,20 +603,23 @@ export function remove<K extends DrawingKind>(kind: K, obj: DrawingTypes[K]): vo
488
603
 
489
604
  /** True when the object was deleted (by `delete` or by the maximum count). */
490
605
  export function isDeleted(obj: unknown): boolean {
606
+ // the setters and getters of the drawing objects start here
607
+ runHooks?.access();
491
608
  return typeof obj === 'object' && obj !== null && Deleted.has(obj);
492
609
  }
493
610
 
494
611
  /** The live objects of a kind, in creation order (a new array). */
495
612
  export function all<K extends DrawingKind>(kind: K): Array<DrawingTypes[K]> {
496
- return [...live[kind]] as Array<DrawingTypes[K]>;
613
+ runHooks?.access();
614
+ return live[kind].toArray() as Array<DrawingTypes[K]>;
497
615
  }
498
616
 
499
617
  /** Forgets all objects (without deleting them) and sets the maximum counts (default 50). */
500
618
  export function resetDrawings(newLimits: DrawingLimits = {}): void {
501
- for (const kind of Object.keys(live) as DrawingKind[]) live[kind].length = 0;
619
+ for (const kind of Object.keys(live) as DrawingKind[]) live[kind].replace([]);
502
620
  fillsOfLine = new Map();
503
621
  created.clear();
504
- holds = { others: new WeakMap() };
622
+ holds = { others: new WeakMap(), records: 0 };
505
623
  pending = { line: 0, label: 0, box: 0, polyline: 0 };
506
624
  currentBar = null;
507
625
  lastBarIndex = null;
@@ -535,12 +653,12 @@ export interface DrawingState {
535
653
  export function saveDrawingState(): DrawingState {
536
654
  return {
537
655
  live: {
538
- line: [...live.line],
539
- label: [...live.label],
540
- box: [...live.box],
541
- polyline: [...live.polyline],
542
- linefill: [...live.linefill],
543
- table: [...live.table],
656
+ line: live.line.toArray(),
657
+ label: live.label.toArray(),
658
+ box: live.box.toArray(),
659
+ polyline: live.polyline.toArray(),
660
+ linefill: live.linefill.toArray(),
661
+ table: live.table.toArray(),
544
662
  },
545
663
  created: [...created],
546
664
  holds,
@@ -552,15 +670,80 @@ export function saveDrawingState(): DrawingState {
552
670
  };
553
671
  }
554
672
 
673
+ /**
674
+ * The registry and the state of its objects at the end of a bar, for an incremental run (#196): the live objects, the
675
+ * fields of each one (arrays, maps and plain objects copied; other drawing objects kept as references), their `var`
676
+ * records, and the counters. {@link restoreDrawingCheckpoint} puts it back on the same objects.
677
+ */
678
+ export interface DrawingCheckpoint {
679
+ state: DrawingState;
680
+ fields: Map<object, Record<string, unknown>>;
681
+ records: Map<object, { count: number; heldAt: number | undefined; releasedAt: number | undefined } | null>;
682
+ }
683
+
684
+ /** A copy of a field value of a drawing object: plain data copied, drawing objects (and other instances) shared. */
685
+ function copyField(v: unknown): unknown {
686
+ if (v === null || typeof v !== 'object' || registered.has(v)) return v;
687
+ if (Array.isArray(v)) return v.map(copyField);
688
+ if (v instanceof Map) return new Map([...v].map(([k, x]) => [k, copyField(x)]));
689
+ if (v instanceof Set) return new Set([...v].map(copyField));
690
+ const proto = Object.getPrototypeOf(v);
691
+ if (proto !== Object.prototype && proto !== null) return v;
692
+ const out: Record<string, unknown> = {};
693
+ for (const [k, x] of Object.entries(v)) out[k] = copyField(x);
694
+ return out;
695
+ }
696
+
697
+ function copyFields(obj: object): Record<string, unknown> {
698
+ const out: Record<string, unknown> = {};
699
+ for (const [k, v] of Object.entries(obj)) out[k] = copyField(v);
700
+ return out;
701
+ }
702
+
703
+ /** @internal */
704
+ export function saveDrawingCheckpoint(): DrawingCheckpoint {
705
+ const state = saveDrawingState();
706
+ const fields = new Map<object, Record<string, unknown>>();
707
+ const records: DrawingCheckpoint['records'] = new Map();
708
+ for (const kind of Object.keys(state.live) as DrawingKind[]) {
709
+ for (const obj of state.live[kind] as object[]) {
710
+ fields.set(obj, copyFields(obj));
711
+ const r = Held.get(obj);
712
+ records.set(obj, r ? { count: r.count, heldAt: r.heldAt, releasedAt: r.releasedAt } : null);
713
+ }
714
+ }
715
+ return { state, fields, records };
716
+ }
717
+
718
+ /** @internal Puts back a {@link saveDrawingCheckpoint}; it can be put back again later. */
719
+ export function restoreDrawingCheckpoint(cp: DrawingCheckpoint): void {
720
+ restoreDrawingState(cp.state);
721
+ pending = { ...cp.state.pending };
722
+ for (const [obj, saved] of cp.fields) {
723
+ for (const key of Object.keys(obj)) if (!(key in saved)) delete (obj as Record<string, unknown>)[key];
724
+ Object.assign(obj, copyFields(saved));
725
+ Deleted.unmark(obj);
726
+ }
727
+ for (const [obj, saved] of cp.records) {
728
+ const r = Held.get(obj);
729
+ if (saved) {
730
+ const record = r ?? Held.create(obj);
731
+ record.count = saved.count;
732
+ record.heldAt = saved.heldAt;
733
+ record.releasedAt = saved.releasedAt;
734
+ } else if (r) {
735
+ r.count = 0;
736
+ r.heldAt = undefined;
737
+ r.releasedAt = undefined;
738
+ }
739
+ }
740
+ }
741
+
555
742
  /** Puts back the registry saved by {@link saveDrawingState} after the nested run. */
556
743
  export function restoreDrawingState(s: DrawingState): void {
557
- for (const kind of Object.keys(live) as DrawingKind[]) {
558
- const list = live[kind] as object[];
559
- list.length = 0;
560
- list.push(...(s.live[kind] as object[]));
561
- }
744
+ for (const kind of Object.keys(live) as DrawingKind[]) (live[kind] as LiveList<object>).replace(s.live[kind]);
562
745
  fillsOfLine = new Map();
563
- for (const fill of live.linefill) trackFill(fill);
746
+ for (const fill of s.live.linefill) trackFill(fill);
564
747
  created.clear();
565
748
  for (const kind of s.created) created.add(kind);
566
749
  holds = s.holds;
package/src/index.ts CHANGED
@@ -39,6 +39,9 @@ import * as callsite from './callsite/index.js';
39
39
 
40
40
  export { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };
41
41
 
42
+ // ta.* one bar at a time (step / commit), for incremental calculations (#196)
43
+ export { taStep, type BarStep } from './ta/step.js';
44
+
42
45
  // Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times
43
46
  export { drawingOutputs, type DrawingOutputs } from './drawing/output.js';
44
47
  export { barInterval, barTime } from './drawing/bar-time.js';
@@ -225,7 +228,7 @@ export type { LightweightSeriesDefinitions } from './runtime/adapters/Lightweigh
225
228
  export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
226
229
 
227
230
  // Version
228
- export const VERSION = '0.15.2';
231
+ export const VERSION = '0.15.4';
229
232
 
230
233
  /**
231
234
  * Library information
@@ -185,6 +185,25 @@ export function historyError(bar: number, barsBack: number): string {
185
185
  );
186
186
  }
187
187
 
188
+ /**
189
+ * Hooks of an incremental script run (#196, set by the script runtime during a run only): a Series created by the
190
+ * script gets a slot, and toArray() reuses the values of the previous run up to the first bar that changed.
191
+ * @internal
192
+ */
193
+ export interface SeriesRunHooks {
194
+ created(series: Series): void;
195
+ /** The values of the previous run (indexes below `from` are kept; the array is reused), or null to compute every bar */
196
+ prefix(series: Series, bars: readonly Bar[]): { values: number[]; from: number } | null;
197
+ computed(series: Series, values: number[]): void;
198
+ }
199
+
200
+ let runHooks: SeriesRunHooks | null = null;
201
+
202
+ /** @internal */
203
+ export function setSeriesRunHooks(hooks: SeriesRunHooks | null): void {
204
+ runHooks = hooks;
205
+ }
206
+
188
207
  export class Series {
189
208
  private extractor: SeriesExtractor;
190
209
  private dataSource: BarData;
@@ -207,6 +226,7 @@ export class Series {
207
226
  // Support both Bar[] and BarData for backward compatibility
208
227
  this.dataSource = data instanceof BarData ? data : new BarData(data);
209
228
  this.extractor = extractor;
229
+ runHooks?.created(this);
210
230
  }
211
231
 
212
232
  /**
@@ -568,8 +588,20 @@ export class Series {
568
588
 
569
589
  // Recompute and update cache
570
590
  const bars = this.dataSource.bars;
571
- this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
591
+ const prefix = runHooks?.prefix(this, bars) ?? null;
592
+ if (prefix) {
593
+ // the run's own array of the previous run: its first values are kept, the newest computed in place
594
+ const n = bars.length;
595
+ const values = prefix.values;
596
+ const from = Math.min(prefix.from, n);
597
+ values.length = n;
598
+ for (let i = from; i < n; i++) values[i] = this.extractor(bars[i]!, i, bars);
599
+ this.cached = values;
600
+ } else {
601
+ this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
602
+ }
572
603
  this.cachedVersion = this.dataSource.version;
604
+ runHooks?.computed(this, this.cached);
573
605
  return this.cached;
574
606
  }
575
607