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
@@ -51,6 +51,8 @@ export class SessionBars {
51
51
  readonly chart: TimeframeInfo;
52
52
 
53
53
  private readonly yearDays = new Map<number, DateNum[]>();
54
+ /** Parsed timeframes: `timeOf` / `closeOf` run on every bar */
55
+ private readonly timeframes = new Map<string, TimeframeInfo>();
54
56
 
55
57
  constructor(
56
58
  readonly calendar: TradingCalendar,
@@ -102,6 +104,12 @@ export class SessionBars {
102
104
  return [monthStart(year * 10000 + firstMonth * 100 + 1), monthEnd(year * 10000 + lastMonth * 100 + 1)];
103
105
  }
104
106
 
107
+ private timeframe(timeframe: string): TimeframeInfo {
108
+ let tf = this.timeframes.get(timeframe);
109
+ if (!tf) this.timeframes.set(timeframe, (tf = info(timeframe)));
110
+ return tf;
111
+ }
112
+
105
113
  private dayStart(date: DateNum): number {
106
114
  return this.calendar.periods(date)[0]![0];
107
115
  }
@@ -117,7 +125,7 @@ export class SessionBars {
117
125
  * NaN on it (measured; `time("W")` keeps its value).
118
126
  */
119
127
  timeOf(time: number, timeframe: string): number {
120
- const tf = info(timeframe);
128
+ const tf = this.timeframe(timeframe);
121
129
  const at = this.calendar.locate(time);
122
130
  if (!at) return NaN;
123
131
  if (tf.isintraday) {
@@ -137,7 +145,7 @@ export class SessionBars {
137
145
 
138
146
  /** PineScript `time_close(tf)` for a bar that opens at `time`. */
139
147
  closeOf(time: number, timeframe: string): number {
140
- const tf = info(timeframe);
148
+ const tf = this.timeframe(timeframe);
141
149
  const at = this.calendar.locate(time);
142
150
  if (!at) return NaN;
143
151
  if (tf.isintraday) {
@@ -178,7 +186,7 @@ export class SessionBars {
178
186
  * bar completes a higher-timeframe period (request.security).
179
187
  */
180
188
  periodEnd(time: number, timeframe: string): number {
181
- const tf = info(timeframe);
189
+ const tf = this.timeframe(timeframe);
182
190
  const at = this.calendar.locate(time);
183
191
  if (!at) return NaN;
184
192
  if (tf.isintraday) {
@@ -18,7 +18,7 @@
18
18
  * dates (early closes, days off); holidays ("session_holidays") are dates without session
19
19
  */
20
20
 
21
- import { zonedFields, zonedToUnix } from '../time/timezone.js';
21
+ import { civilFromDays, zoneOffset, zonedToUnix } from '../time/timezone.js';
22
22
  import { parsePineSession } from '../time/session.js';
23
23
 
24
24
  /** Session information of a symbol (hours, corrections, holidays). */
@@ -54,13 +54,40 @@ interface Version {
54
54
 
55
55
  export const toDateNum = (y: number, m: number, d: number): DateNum => y * 10000 + m * 100 + d;
56
56
  const utcOf = (date: DateNum): number => Date.UTC(Math.floor(date / 10000), Math.floor(date / 100) % 100 - 1, date % 100);
57
- const fromUtc = (ms: number): DateNum => {
58
- const d = new Date(ms);
59
- return toDateNum(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
60
- };
61
- export const addDays = (date: DateNum, n: number): DateNum => fromUtc(utcOf(date) + n * 86_400_000);
62
- /** 1 = Sunday ... 7 = Saturday */
63
- export const weekdayOf = (date: DateNum): number => new Date(utcOf(date)).getUTCDay() + 1;
57
+
58
+ const MS_PER_DAY = 86_400_000;
59
+ /** Days of a valid `Date` on each side of 01/01/1970 (8.64e15 ms) */
60
+ const MAX_DAY = 100_000_000;
61
+
62
+ /**
63
+ * Days since 01/01/1970 of a date, as `utcOf(date) / 1 day` but without a `Date`: the calendar functions step
64
+ * through days on every bar. Years before 100 and months outside 1-12 keep the `Date.UTC` reading (years 0-99 are
65
+ * 1900-1999 there). NaN outside the `Date` range.
66
+ */
67
+ function dayOf(date: DateNum): number {
68
+ let y = Math.floor(date / 10000);
69
+ const m = Math.floor(date / 100) % 100;
70
+ if (!(y >= 100 && m >= 1 && m <= 12)) return utcOf(date) / MS_PER_DAY;
71
+ // proleptic Gregorian day count, years starting in March (the leap day last)
72
+ if (m <= 2) y--;
73
+ const era = Math.floor(y / 400);
74
+ const yearOfEra = y - era * 400;
75
+ const dayOfYear = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + (date % 100) - 1;
76
+ const day = era * 146_097 + yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear - 719_468;
77
+ return Math.abs(day) <= MAX_DAY ? day : NaN;
78
+ }
79
+
80
+ /** Date of a day since 01/01/1970 (the inverse of `dayOf`); NaN outside the `Date` range. */
81
+ function dateOf(day: number): DateNum {
82
+ if (!(Math.abs(day) <= MAX_DAY)) return NaN;
83
+ const { year, month, day: d } = civilFromDays(day);
84
+ return toDateNum(year, month, d);
85
+ }
86
+
87
+ /** The date `n` (whole) days after `date`. */
88
+ export const addDays = (date: DateNum, n: number): DateNum => dateOf(dayOf(date) + n);
89
+ /** 1 = Sunday ... 7 = Saturday (01/01/1970 is a Thursday) */
90
+ export const weekdayOf = (date: DateNum): number => ((((dayOf(date) + 4) % 7) + 7) % 7) + 1;
64
91
  /** 00:00 UTC of the date, in ms (PineScript `time_tradingday`). */
65
92
  export const dateUtcMs = utcOf;
66
93
 
@@ -132,13 +159,25 @@ function parseVersion(text: string, from: DateNum, spec: string, rule: 'symbol'
132
159
  return { from, periods, days };
133
160
  }
134
161
 
162
+ /** Trading day and period of a time (see `TradingCalendar.locate`). */
163
+ interface Located {
164
+ date: DateNum;
165
+ index: number;
166
+ inside: boolean;
167
+ }
168
+
135
169
  /** Session periods of every trading day of a symbol, as UNIX times (ms). */
136
170
  export class TradingCalendar {
137
171
  private readonly versions: Version[];
138
172
  private readonly corrections = new Map<DateNum, Period[] | null>();
139
173
  private readonly holidays: Set<DateNum>;
140
174
  private readonly cache = new Map<DateNum, Array<[number, number]>>();
175
+ /** The date and periods of each day since 01/01/1970 that `search` looked at */
176
+ private readonly days = new Map<number, { date: DateNum; periods: Array<[number, number]> }>();
141
177
  private readonly pine: boolean;
178
+ /** The last time located and its result: the functions of one bar locate the same time several times */
179
+ private lastTime = NaN;
180
+ private lastAt: Located | null = null;
142
181
 
143
182
  /**
144
183
  * @param timezone - Time zone of the session hours (the exchange time zone)
@@ -180,7 +219,7 @@ export class TradingCalendar {
180
219
  if (correction !== undefined) {
181
220
  periods = correction ?? [];
182
221
  } else if (!this.holidays.has(date)) {
183
- const version = [...this.versions].reverse().find((v) => v.from <= date)!;
222
+ const version = this.versionOf(date);
184
223
  if (version.byDay) periods = version.byDay[weekdayOf(date)]!;
185
224
  else if (version.days[weekdayOf(date)]) periods = version.periods;
186
225
  }
@@ -204,6 +243,13 @@ export class TradingCalendar {
204
243
  return out;
205
244
  }
206
245
 
246
+ /** The session version in force on `date` (the last one that starts on or before it). */
247
+ private versionOf(date: DateNum): Version {
248
+ let k = this.versions.length - 1;
249
+ while (k >= 0 && !(this.versions[k]!.from <= date)) k--;
250
+ return this.versions[k]!;
251
+ }
252
+
207
253
  isTradingDay(date: DateNum): boolean {
208
254
  return this.periods(date).length > 0;
209
255
  }
@@ -215,7 +261,7 @@ export class TradingCalendar {
215
261
  afterEarlyClose(time: number): boolean {
216
262
  const at = this.locate(time);
217
263
  if (!at || at.inside || !this.corrections.get(at.date)) return false;
218
- const version = [...this.versions].reverse().find((v) => v.from <= at.date)!;
264
+ const version = this.versionOf(at.date);
219
265
  const usual = version.byDay ? version.byDay[weekdayOf(at.date)]! : version.days[weekdayOf(at.date)] ? version.periods : [];
220
266
  const y = Math.floor(at.date / 10000);
221
267
  const m = Math.floor(at.date / 100) % 100;
@@ -231,26 +277,43 @@ export class TradingCalendar {
231
277
  * Trading day and period of a time: the period that contains it, else the last period that started
232
278
  * before it. Null when no trading day is found near the time.
233
279
  */
234
- locate(time: number): { date: DateNum; index: number; inside: boolean } | null {
235
- const f = zonedFields(time, this.timezone);
236
- const local = toDateNum(f.year, f.month, f.day);
280
+ locate(time: number): Located | null {
281
+ if (time !== this.lastTime) {
282
+ this.lastAt = this.search(time);
283
+ this.lastTime = time;
284
+ }
285
+ const at = this.lastAt;
286
+ return at && { date: at.date, index: at.index, inside: at.inside };
287
+ }
288
+
289
+ private search(time: number): Located | null {
290
+ // the local date of the time, as `Date` reads the wall clock (whole ms, NaN outside its range)
291
+ const wall = time + zoneOffset(time, this.timezone);
292
+ const local = dayOf(dateOf(Math.abs(wall) <= MAX_DAY * MS_PER_DAY ? Math.floor(Math.trunc(wall) / MS_PER_DAY) : NaN));
237
293
  for (let k = 0; k <= 5; k++) {
238
- const date = addDays(local, k);
239
- const index = this.periods(date).findIndex(([s, e]) => s <= time && time < e);
294
+ const { date, periods } = this.dayAt(local + k);
295
+ const index = periods.findIndex(([s, e]) => s <= time && time < e);
240
296
  if (index !== -1) return { date, index, inside: true };
241
297
  }
242
298
  for (let k = 5; k >= -7; k--) {
243
- const date = addDays(local, k);
244
- const periods = this.periods(date);
245
- let index = -1;
246
- periods.forEach(([s], i) => {
247
- if (s <= time) index = i;
248
- });
299
+ const { date, periods } = this.dayAt(local + k);
300
+ let index = periods.length - 1;
301
+ while (index >= 0 && !(periods[index]![0] <= time)) index--;
249
302
  if (index !== -1) return { date, index, inside: false };
250
303
  }
251
304
  return null;
252
305
  }
253
306
 
307
+ private dayAt(day: number): { date: DateNum; periods: Array<[number, number]> } {
308
+ let at = this.days.get(day);
309
+ if (!at) {
310
+ const date = dateOf(day);
311
+ at = { date, periods: this.periods(date) };
312
+ this.days.set(day, at);
313
+ }
314
+ return at;
315
+ }
316
+
254
317
  /** First trading day in [from, to] (dates), or null. */
255
318
  firstTradingDay(from: DateNum, to: DateNum): DateNum | null {
256
319
  for (let date = from; date <= to; date = addDays(date, 1)) if (this.isTradingDay(date)) return date;
@@ -68,6 +68,26 @@ export interface SessionPeriods {
68
68
  close: (time: number) => number;
69
69
  }
70
70
 
71
+ /** Calendars of the `session` / `timezone` arguments before the cache restarts */
72
+ const MAX_ARGUMENT_CALENDARS = 64;
73
+ const argumentCalendars = new Map<string, TradingCalendar>();
74
+
75
+ /**
76
+ * Calendar of a session string read in a time zone, without corrections and holidays: it depends on these only, so
77
+ * the calls with other timeframes or other chart contexts share it and its periods (a script often reads
78
+ * `time(timeframe.period, s)` and `time("D", s)` on every bar).
79
+ */
80
+ function argumentCalendar(timezone: string, session: string, rule: 'symbol' | 'pine', dayPlacement: boolean): TradingCalendar {
81
+ const key = `${rule}|${dayPlacement}|${timezone}|${session}`;
82
+ let calendar = argumentCalendars.get(key);
83
+ if (!calendar) {
84
+ calendar = new TradingCalendar(timezone, { session }, rule, dayPlacement);
85
+ if (argumentCalendars.size >= MAX_ARGUMENT_CALENDARS) argumentCalendars.clear();
86
+ argumentCalendars.set(key, calendar);
87
+ }
88
+ return calendar;
89
+ }
90
+
71
91
  /**
72
92
  * Calendar for the `session` / `timezone` arguments of `time(tf, session, timezone)`. Without both: the loaded
73
93
  * session. As in PineScript, an explicit time zone reads the symbol session hours in that zone without corrections
@@ -87,11 +107,13 @@ function calendarFor(
87
107
  if (session !== undefined && parsePineSession(session) === null) {
88
108
  const name = session.trim();
89
109
  const symbol = name === 'regular' && chart.regularSession ? chart.regularSession : chart.session!;
90
- return { bars: new SessionBars(new TradingCalendar(tz, { session: toSpec(symbol).session }, 'symbol'), bars.chart.period), test: true };
110
+ return { bars: new SessionBars(argumentCalendar(tz, toSpec(symbol).session, 'symbol', false), bars.chart.period), test: true };
91
111
  }
92
- const spec = session ? { session } : { session: toSpec(chart.session!).session };
93
112
  return {
94
- bars: new SessionBars(new TradingCalendar(tz, spec, session ? 'pine' : 'symbol', dayPlacement), bars.chart.period),
113
+ bars: new SessionBars(
114
+ argumentCalendar(tz, session || toSpec(chart.session!).session, session ? 'pine' : 'symbol', dayPlacement),
115
+ bars.chart.period
116
+ ),
95
117
  test: true,
96
118
  // a PineScript session string: the rules of time.inSession (runs ending at 0000, days around a clock change)
97
119
  inside: session ? (time) => sessionRun(time, session, tz, in_seconds(bars.chart.period) * 1000) !== null : undefined,
@@ -138,15 +160,20 @@ export function sessionPeriods(
138
160
  return { open, close };
139
161
  }
140
162
 
141
- const periodCache = new WeakMap<object, Map<string, SessionPeriods>>();
163
+ /** Periods per chart, timeframe, session and time zone (no session / time zone is ""): maps of the given strings, no
164
+ * key to build on every bar */
165
+ const periodCache = new WeakMap<object, Map<string, Map<string, Map<string, SessionPeriods>>>>();
142
166
 
143
167
  function periodsOfChart(chart: SessionContext, timeframe: string, session?: string, timezone?: string): { s: ChartSessions; p: SessionPeriods } {
144
168
  const s = chartSessions(chart);
145
- let byKey = periodCache.get(chart);
146
- if (!byKey) periodCache.set(chart, (byKey = new Map()));
147
- const key = `${timeframe}|${session ?? ''}|${timezone ?? ''}`;
148
- let p = byKey.get(key);
149
- if (!p) byKey.set(key, (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));
169
+ let byTimeframe = periodCache.get(chart);
170
+ if (!byTimeframe) periodCache.set(chart, (byTimeframe = new Map()));
171
+ let bySession = byTimeframe.get(timeframe);
172
+ if (!bySession) byTimeframe.set(timeframe, (bySession = new Map()));
173
+ let byZone = bySession.get(session ?? '');
174
+ if (!byZone) bySession.set(session ?? '', (byZone = new Map()));
175
+ let p = byZone.get(timezone ?? '');
176
+ if (!p) byZone.set(timezone ?? '', (p = sessionPeriods(s.bars, chart, timeframe, session, timezone)));
150
177
  return { s, p };
151
178
  }
152
179
 
@@ -194,8 +194,37 @@ function layout(d: Digits, p: Pattern): string {
194
194
  return group(int, p.grouping) + (frac ? '.' + frac : '');
195
195
  }
196
196
 
197
+ /**
198
+ * Texts already formatted, by rounding mode, pattern and value: a script formats the same values on each run (the
199
+ * whole history again on every update of the last bar). -0 is not kept (a Map does not tell it from 0).
200
+ */
201
+ const formatted = new Map<Rounding, Map<string, Map<number, string>>>();
202
+ let formattedCount = 0;
203
+ const FORMATTED_KEPT = 100_000;
204
+
197
205
  /** Formats a number with a DecimalFormat pattern. */
198
206
  export function formatNumber(value: number, pattern: string, mode: Rounding): string {
207
+ if (Number.isNaN(value) || Object.is(value, -0)) return format(value, pattern, mode);
208
+ let byPattern = formatted.get(mode);
209
+ if (byPattern === undefined) formatted.set(mode, (byPattern = new Map()));
210
+ let byValue = byPattern.get(pattern);
211
+ if (byValue === undefined) byPattern.set(pattern, (byValue = new Map()));
212
+ let text = byValue.get(value);
213
+ if (text === undefined) {
214
+ text = format(value, pattern, mode);
215
+ if (formattedCount >= FORMATTED_KEPT) {
216
+ formatted.clear();
217
+ formattedCount = 0;
218
+ formatted.set(mode, (byPattern = new Map()));
219
+ byPattern.set(pattern, (byValue = new Map()));
220
+ }
221
+ byValue.set(value, text);
222
+ formattedCount++;
223
+ }
224
+ return text;
225
+ }
226
+
227
+ function format(value: number, pattern: string, mode: Rounding): string {
199
228
  if (Number.isNaN(value)) return 'NaN';
200
229
  const p = parsePattern(pattern);
201
230
  if (!Number.isFinite(value)) return affixes(p, value < 0, '∞');
@@ -282,4 +282,12 @@ export interface StrategyEngine {
282
282
  risk?(rule: StrategyRiskRule): void;
283
283
  /** `strategy.default_entry_qty(fill_price)`; optional. */
284
284
  defaultEntryQty?(fillPrice: number): number;
285
+ /**
286
+ * The engine state at the end of a bar (orders, positions, trades, equity), for an incremental script run
287
+ * (createScriptRun, #196); optional. With {@link restore}, a live update of a strategy calculates the newest bars
288
+ * only: the engine of the next run gets the state of the last confirmed bar. Without them, every update is a full run.
289
+ */
290
+ save?(): unknown;
291
+ /** Puts back a state given by {@link save} (on a new engine of the same script and bars). */
292
+ restore?(state: unknown): void;
285
293
  }
@@ -25,7 +25,11 @@ function addExact(p: number[], x: number): void {
25
25
  let i = 0;
26
26
  for (let j = 0; j < p.length; j++) {
27
27
  let y = p[j]!;
28
- if (Math.abs(x) < Math.abs(y)) [x, y] = [y, x];
28
+ if (Math.abs(x) < Math.abs(y)) {
29
+ const t = x;
30
+ x = y;
31
+ y = t;
32
+ }
29
33
  const hi = x + y;
30
34
  const lo = y - (hi - x);
31
35
  if (lo !== 0) p[i++] = lo;
@@ -161,8 +165,79 @@ function sumWindows(source: ArrayLike<number | null | undefined>, lengthAt: (i:
161
165
  */
162
166
  export function runningSum(source: ArrayLike<number | null | undefined>, length: number): number[] {
163
167
  const len = Math.floor(length);
164
- if (!(len >= 1)) return new Array<number>(source.length).fill(NaN);
165
- return sumWindows(source, () => len);
168
+ const n = source.length;
169
+ const out = new Array<number>(n);
170
+ if (!(len >= 1)) return out.fill(NaN);
171
+ // A constant length: the partials of the window are changed in place, with the steps of RunningSum in the same
172
+ // order (the value that leaves, then the one that enters), so the sums are the same doubles without a copy per bar.
173
+ const values: number[] = [];
174
+ const p = new FixedPartials();
175
+ let last = NaN;
176
+ for (let i = 0; i < n; i++) {
177
+ const v = source[i];
178
+ if (!isNa(v)) {
179
+ const count = values.length;
180
+ if (count >= len) p.add(-values[count - len]!);
181
+ p.add(v as number);
182
+ values.push(v as number);
183
+ last = count + 1 >= len ? p.round() : NaN;
184
+ }
185
+ out[i] = last;
186
+ }
187
+ return out;
188
+ }
189
+
190
+ /** The partials of {@link addExact} / {@link roundExact} in a typed array with a count (same operations). */
191
+ class FixedPartials {
192
+ private p = new Float64Array(64);
193
+ private n = 0;
194
+
195
+ add(x: number): void {
196
+ const p = this.p;
197
+ const n = this.n;
198
+ let i = 0;
199
+ for (let j = 0; j < n; j++) {
200
+ let y = p[j]!;
201
+ if (Math.abs(x) < Math.abs(y)) {
202
+ const t = x;
203
+ x = y;
204
+ y = t;
205
+ }
206
+ const hi = x + y;
207
+ const lo = y - (hi - x);
208
+ if (lo !== 0) p[i++] = lo;
209
+ x = hi;
210
+ }
211
+ if (i === p.length) {
212
+ const grown = new Float64Array(p.length * 2);
213
+ grown.set(p);
214
+ this.p = grown;
215
+ }
216
+ this.p[i] = x;
217
+ this.n = i + 1;
218
+ }
219
+
220
+ round(): number {
221
+ const p = this.p;
222
+ let n = this.n;
223
+ if (n === 0) return 0;
224
+ let hi = p[--n]!;
225
+ while (n > 0) {
226
+ const x = hi;
227
+ const y = p[--n]!;
228
+ hi = x + y;
229
+ const lo = y - (hi - x);
230
+ if (lo !== 0) {
231
+ if (n > 0 && ((lo < 0 && p[n - 1]! < 0) || (lo > 0 && p[n - 1]! > 0))) {
232
+ const y2 = lo * 2;
233
+ const x2 = hi + y2;
234
+ if (y2 === x2 - hi) hi = x2;
235
+ }
236
+ break;
237
+ }
238
+ }
239
+ return hi;
240
+ }
166
241
  }
167
242
 
168
243
  /** The values of a series length, floored, checked to be at least 1 on every bar. */