oakscriptjs 0.15.3 → 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.
- package/dist/cjs/check/format.d.ts.map +1 -1
- package/dist/cjs/check/format.js +5 -0
- package/dist/cjs/check/format.js.map +2 -2
- package/dist/cjs/check/harness.d.ts +24 -0
- package/dist/cjs/check/harness.d.ts.map +1 -1
- package/dist/cjs/check/harness.js +33 -0
- package/dist/cjs/check/harness.js.map +2 -2
- package/dist/cjs/check/index.d.ts +9 -0
- package/dist/cjs/check/index.d.ts.map +1 -1
- package/dist/cjs/check/index.js +7 -0
- package/dist/cjs/check/index.js.map +2 -2
- package/dist/cjs/color/index.d.ts.map +1 -1
- package/dist/cjs/color/index.js +19 -2
- package/dist/cjs/color/index.js.map +2 -2
- package/dist/cjs/color/parse.d.ts +8 -6
- package/dist/cjs/color/parse.d.ts.map +1 -1
- package/dist/cjs/color/parse.js +15 -2
- package/dist/cjs/color/parse.js.map +2 -2
- package/dist/cjs/drawing/registry.d.ts +29 -0
- package/dist/cjs/drawing/registry.d.ts.map +1 -1
- package/dist/cjs/drawing/registry.js +83 -2
- package/dist/cjs/drawing/registry.js.map +2 -2
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +3 -1
- package/dist/cjs/index.js.map +2 -2
- package/dist/cjs/runtime/series.d.ts +16 -0
- package/dist/cjs/runtime/series.d.ts.map +1 -1
- package/dist/cjs/runtime/series.js +19 -2
- package/dist/cjs/runtime/series.js.map +2 -2
- package/dist/cjs/script/closure-writes.d.ts +16 -0
- package/dist/cjs/script/closure-writes.d.ts.map +1 -0
- package/dist/cjs/script/closure-writes.js +435 -0
- package/dist/cjs/script/closure-writes.js.map +7 -0
- package/dist/cjs/script/globals.d.ts +2 -0
- package/dist/cjs/script/globals.d.ts.map +1 -1
- package/dist/cjs/script/globals.js.map +1 -1
- package/dist/cjs/script/incremental.d.ts +140 -0
- package/dist/cjs/script/incremental.d.ts.map +1 -0
- package/dist/cjs/script/incremental.js +142 -0
- package/dist/cjs/script/incremental.js.map +7 -0
- package/dist/cjs/script/index.d.ts +116 -31
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +471 -25
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/str/numberformat.d.ts.map +1 -1
- package/dist/cjs/str/numberformat.js +23 -0
- package/dist/cjs/str/numberformat.js.map +2 -2
- package/dist/cjs/strategy/index.d.ts +8 -0
- package/dist/cjs/strategy/index.d.ts.map +1 -1
- package/dist/cjs/strategy/index.js.map +1 -1
- package/dist/cjs/ta/running-sum.d.ts.map +1 -1
- package/dist/cjs/ta/running-sum.js +72 -3
- package/dist/cjs/ta/running-sum.js.map +2 -2
- package/dist/cjs/ta/step.d.ts +476 -0
- package/dist/cjs/ta/step.d.ts.map +1 -0
- package/dist/cjs/ta/step.js +1000 -0
- package/dist/cjs/ta/step.js.map +7 -0
- package/dist/cjs/ta-series.d.ts +1 -1
- package/dist/cjs/ta-series.js +3 -3
- package/dist/cjs/ta-series.js.map +1 -1
- package/dist/esm/check/format.d.ts.map +1 -1
- package/dist/esm/check/format.js +5 -0
- package/dist/esm/check/format.js.map +1 -1
- package/dist/esm/check/harness.d.ts +24 -0
- package/dist/esm/check/harness.d.ts.map +1 -1
- package/dist/esm/check/harness.js +40 -6
- package/dist/esm/check/harness.js.map +1 -1
- package/dist/esm/check/index.d.ts +9 -0
- package/dist/esm/check/index.d.ts.map +1 -1
- package/dist/esm/check/index.js +11 -1
- package/dist/esm/check/index.js.map +1 -1
- package/dist/esm/color/index.d.ts.map +1 -1
- package/dist/esm/color/index.js +23 -3
- package/dist/esm/color/index.js.map +1 -1
- package/dist/esm/color/parse.d.ts +8 -6
- package/dist/esm/color/parse.d.ts.map +1 -1
- package/dist/esm/color/parse.js +19 -2
- package/dist/esm/color/parse.js.map +1 -1
- package/dist/esm/drawing/registry.d.ts +29 -0
- package/dist/esm/drawing/registry.d.ts.map +1 -1
- package/dist/esm/drawing/registry.js +102 -3
- package/dist/esm/drawing/registry.js.map +1 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/runtime/series.d.ts +16 -0
- package/dist/esm/runtime/series.d.ts.map +1 -1
- package/dist/esm/runtime/series.js +21 -1
- package/dist/esm/runtime/series.js.map +1 -1
- package/dist/esm/script/closure-writes.d.ts +16 -0
- package/dist/esm/script/closure-writes.d.ts.map +1 -0
- package/dist/esm/script/closure-writes.js +323 -0
- package/dist/esm/script/closure-writes.js.map +1 -0
- package/dist/esm/script/globals.d.ts +2 -0
- package/dist/esm/script/globals.d.ts.map +1 -1
- package/dist/esm/script/globals.js.map +1 -1
- package/dist/esm/script/incremental.d.ts +140 -0
- package/dist/esm/script/incremental.d.ts.map +1 -0
- package/dist/esm/script/incremental.js +173 -0
- package/dist/esm/script/incremental.js.map +1 -0
- package/dist/esm/script/index.d.ts +116 -31
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +561 -24
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/str/numberformat.d.ts.map +1 -1
- package/dist/esm/str/numberformat.js +30 -0
- package/dist/esm/str/numberformat.js.map +1 -1
- package/dist/esm/strategy/index.d.ts +8 -0
- package/dist/esm/strategy/index.d.ts.map +1 -1
- package/dist/esm/ta/running-sum.d.ts.map +1 -1
- package/dist/esm/ta/running-sum.js +79 -4
- package/dist/esm/ta/running-sum.js.map +1 -1
- package/dist/esm/ta/step.d.ts +476 -0
- package/dist/esm/ta/step.d.ts.map +1 -0
- package/dist/esm/ta/step.js +1089 -0
- package/dist/esm/ta/step.js.map +1 -0
- package/dist/esm/ta-series.d.ts +1 -1
- package/dist/esm/ta-series.js +4 -4
- package/package.json +1 -1
- package/skills/oakscript/SKILL.md +2 -2
- package/skills/oakscript/reference/check.md +5 -0
- package/skills/oakscript/reference/errors.md +0 -1
- package/skills/oakscript/reference/pine-differences.md +1 -2
- package/skills/oakscript/reference/plotting.md +5 -7
- package/skills/oakscript/reference/script-structure.md +6 -0
- package/src/check/format.ts +7 -0
- package/src/check/harness.ts +57 -0
- package/src/check/index.ts +16 -0
- package/src/color/index.ts +22 -3
- package/src/color/parse.ts +28 -3
- package/src/drawing/registry.ts +115 -3
- package/src/index.ts +4 -1
- package/src/runtime/series.ts +33 -1
- package/src/script/closure-writes.ts +279 -0
- package/src/script/globals.ts +2 -0
- package/src/script/incremental.ts +246 -0
- package/src/script/index.ts +695 -26
- package/src/str/numberformat.ts +29 -0
- package/src/strategy/index.ts +8 -0
- package/src/ta/running-sum.ts +78 -3
- package/src/ta/step.ts +1145 -0
- package/src/ta-series.ts +4 -4
package/dist/esm/script/index.js
CHANGED
|
@@ -34,11 +34,14 @@
|
|
|
34
34
|
*/
|
|
35
35
|
import { BarData, Series, MAX_BARS_BACK, historyError } from '../runtime/series.js';
|
|
36
36
|
import * as taSeries from '../ta-series.js';
|
|
37
|
+
import { taStep } from '../ta/step.js';
|
|
38
|
+
import * as incremental from './incremental.js';
|
|
39
|
+
import { outerWrites } from './closure-writes.js';
|
|
37
40
|
import * as pineConstants from './constants.js';
|
|
38
41
|
import { drawingNamespace, isPlainObject, namedArguments, unknownArgument } from './drawing-args.js';
|
|
39
42
|
import * as colorCore from '../color/index.js';
|
|
40
43
|
import { inputColorDefault } from '../color/parse.js';
|
|
41
|
-
import { fixnan as fixnanValues, isNA, nz } from '../utils/index.js';
|
|
44
|
+
import { fixnan as fixnanValues, isNA, nz as nzValue } from '../utils/index.js';
|
|
42
45
|
import { externalSource } from '../utils/source-resolver.js';
|
|
43
46
|
import * as lineCore from '../line/index.js';
|
|
44
47
|
import * as labelCore from '../label/index.js';
|
|
@@ -49,8 +52,28 @@ import * as tableCore from '../table/index.js';
|
|
|
49
52
|
import * as chartPointCore from '../chartpoint/index.js';
|
|
50
53
|
import * as textCore from '../text/index.js';
|
|
51
54
|
import * as mathCore from '../math/index.js';
|
|
52
|
-
import { createdDrawingKinds, resetDrawings, restoreDrawingState, saveDrawingState, setDrawingBar, setDrawingLimits, } from '../drawing/registry.js';
|
|
53
|
-
export { holdDrawing, releaseDrawing
|
|
55
|
+
import { createdDrawingKinds, resetDrawings, restoreDrawingCheckpoint, restoreDrawingState, saveDrawingCheckpoint, saveDrawingState, setDrawingBar, setDrawingLimits, holdDrawing, releaseDrawing, } from '../drawing/registry.js';
|
|
56
|
+
export { holdDrawing, releaseDrawing } from '../drawing/registry.js';
|
|
57
|
+
/**
|
|
58
|
+
* A PineScript `var` variable of a drawing type (`var line l = na`): the object it refers to is not deleted by the
|
|
59
|
+
* maximum count; assigning another object (or `undefined` for `na`) releases the one before. Its value is a
|
|
60
|
+
* {@link persist} box: an incremental run puts it back with the drawings (#196). Declare it in the script body.
|
|
61
|
+
*/
|
|
62
|
+
export function varDrawing(initial) {
|
|
63
|
+
const box = persist(initial ? holdDrawing(initial) : undefined);
|
|
64
|
+
return {
|
|
65
|
+
get value() {
|
|
66
|
+
return box.value;
|
|
67
|
+
},
|
|
68
|
+
set value(next) {
|
|
69
|
+
const current = box.value;
|
|
70
|
+
if (next === current)
|
|
71
|
+
return;
|
|
72
|
+
releaseDrawing(current);
|
|
73
|
+
box.value = next ? holdDrawing(next) : undefined;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
54
77
|
import { drawingOutputs } from '../drawing/output.js';
|
|
55
78
|
import * as timeframeCore from '../timeframe/index.js';
|
|
56
79
|
import * as timeCore from '../time/index.js';
|
|
@@ -173,8 +196,14 @@ function restoreRunState(st) {
|
|
|
173
196
|
* panels, workers and tests call it; scripts never do.
|
|
174
197
|
*/
|
|
175
198
|
export function executeScript(body, barsInput, inputs = {}, chart = {}, options = {}) {
|
|
199
|
+
return runBody(body, barsInput, inputs, chart, options, null);
|
|
200
|
+
}
|
|
201
|
+
/** executeScript(), as part of an incremental run (`inc`, see createScriptRun) or alone (null). */
|
|
202
|
+
function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
176
203
|
// A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.
|
|
177
204
|
const outer = ctx ? saveRunState() : null;
|
|
205
|
+
// A plain run inside an incremental one is not part of it.
|
|
206
|
+
const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();
|
|
178
207
|
ctxBars.setAll(barsInput);
|
|
179
208
|
chartCtx = { ...chart };
|
|
180
209
|
runNow = chart.now ?? Date.now();
|
|
@@ -190,6 +219,9 @@ export function executeScript(body, barsInput, inputs = {}, chart = {}, options
|
|
|
190
219
|
body();
|
|
191
220
|
if (missingSymbols.length)
|
|
192
221
|
throw new MissingSymbolDataError(missingSymbols);
|
|
222
|
+
// the outputs read the drawings: not a drawing of the script
|
|
223
|
+
if (inc)
|
|
224
|
+
incremental.bodyDone();
|
|
193
225
|
const c = ctx;
|
|
194
226
|
return {
|
|
195
227
|
metadata: {
|
|
@@ -235,6 +267,7 @@ export function executeScript(body, barsInput, inputs = {}, chart = {}, options
|
|
|
235
267
|
ctx = null;
|
|
236
268
|
if (outer)
|
|
237
269
|
restoreRunState(outer);
|
|
270
|
+
incremental.endRun(outerInc);
|
|
238
271
|
}
|
|
239
272
|
}
|
|
240
273
|
/**
|
|
@@ -263,6 +296,176 @@ export function executeIntrabar(body, bars, inputs, chart, options) {
|
|
|
263
296
|
// History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
|
|
264
297
|
{ ...chart, lastBarConfirmed: true, realtime: false }, { strategyEngine: () => options.engine });
|
|
265
298
|
}
|
|
299
|
+
/** Chart context fields that only change the last bar (barstate of the forming bar). */
|
|
300
|
+
const LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);
|
|
301
|
+
function sameChart(a, b) {
|
|
302
|
+
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
303
|
+
for (const k of keys) {
|
|
304
|
+
if (LAST_BAR_FIELDS.has(k))
|
|
305
|
+
continue;
|
|
306
|
+
if (!Object.is(a[k], b[k]))
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
/** `b` in `copy` from bar `from` on (the bars before are already there); a new copy when `copy` is null. */
|
|
312
|
+
function copyBars(b, copy = null, from = 0) {
|
|
313
|
+
let values = copy?.values ?? new Float64Array(Math.max(16, b.length) * 6);
|
|
314
|
+
if (values.length < b.length * 6) {
|
|
315
|
+
const grown = new Float64Array(b.length * 12);
|
|
316
|
+
grown.set(values.subarray(0, from * 6));
|
|
317
|
+
values = grown;
|
|
318
|
+
}
|
|
319
|
+
for (let i = from; i < b.length; i++) {
|
|
320
|
+
const x = b[i];
|
|
321
|
+
const o = i * 6;
|
|
322
|
+
values[o] = x.time;
|
|
323
|
+
values[o + 1] = x.open;
|
|
324
|
+
values[o + 2] = x.high;
|
|
325
|
+
values[o + 3] = x.low;
|
|
326
|
+
values[o + 4] = x.close;
|
|
327
|
+
values[o + 5] = x.volume ?? NaN;
|
|
328
|
+
}
|
|
329
|
+
return { n: b.length, values };
|
|
330
|
+
}
|
|
331
|
+
/** a and b are the same number (NaN equal to NaN, -0 not 0) */
|
|
332
|
+
const sameNumber = (a, b) => a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;
|
|
333
|
+
/** The first `count` bars of `b` have the values of `copy`. */
|
|
334
|
+
function sameBars(copy, b, count) {
|
|
335
|
+
const v = copy.values;
|
|
336
|
+
for (let i = 0; i < count; i++) {
|
|
337
|
+
const x = b[i];
|
|
338
|
+
const o = i * 6;
|
|
339
|
+
if (!sameNumber(v[o], x.time) || !sameNumber(v[o + 1], x.open) || !sameNumber(v[o + 2], x.high) ||
|
|
340
|
+
!sameNumber(v[o + 3], x.low) || !sameNumber(v[o + 4], x.close) || !sameNumber(v[o + 5], x.volume ?? NaN)) {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
/** Two run results with the same values (numbers compared with Object.is: NaN equal, -0 not 0). */
|
|
347
|
+
function sameResult(a, b) {
|
|
348
|
+
if (Object.is(a, b))
|
|
349
|
+
return true;
|
|
350
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
|
|
351
|
+
return false;
|
|
352
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
353
|
+
return false;
|
|
354
|
+
const ka = Object.keys(a);
|
|
355
|
+
const kb = Object.keys(b);
|
|
356
|
+
if (ka.length !== kb.length)
|
|
357
|
+
return false;
|
|
358
|
+
for (const k of ka) {
|
|
359
|
+
if (!sameResult(a[k], b[k]))
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* A script that calculates only the newest bars on a live update (#196). The first update is a full run; it keeps,
|
|
366
|
+
* for the next one, what the script created (its Series, ta.* calls, eachBar() blocks, persist() boxes and plots) with
|
|
367
|
+
* their state at the end of the last confirmed bar. An update whose bars are the same up to the forming bar of the
|
|
368
|
+
* previous update (a new price of the forming bar, or new bars after it) runs the script again from that bar only;
|
|
369
|
+
* the result is the same as a full run on the same bars. Other changes (history loaded, inputs, symbol, timeframe or
|
|
370
|
+
* other chart fields) run it in full.
|
|
371
|
+
*
|
|
372
|
+
* The state the script keeps from one bar to the next has to be in `persist()` boxes (not in `let` variables outside the
|
|
373
|
+
* eachBar() callbacks, which a resumed run cannot put back). The first resumed updates are also calculated in full and
|
|
374
|
+
* compared (`verify`): a difference makes the next updates full runs. Not resumed yet, so calculated in full: drawings,
|
|
375
|
+
* request.security, strategies, varip, timenow, last_bar_index, BarContext.n, barstate.islastconfirmedhistory
|
|
376
|
+
* (`fullRunReason` names the first one met).
|
|
377
|
+
*/
|
|
378
|
+
export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
379
|
+
let memory = null;
|
|
380
|
+
let previous = null;
|
|
381
|
+
let previousChart = chart;
|
|
382
|
+
let reason = null;
|
|
383
|
+
let verifyLeft = options.verify ?? 2;
|
|
384
|
+
const newRun = (mode, b, from) => {
|
|
385
|
+
const next = incremental.emptyMemory(b.length);
|
|
386
|
+
// the block that draws stays the one of the previous run (the forming bar may not draw)
|
|
387
|
+
if (mode === 'resume' && memory)
|
|
388
|
+
next.drawingBlock = memory.drawingBlock;
|
|
389
|
+
return {
|
|
390
|
+
mode,
|
|
391
|
+
from,
|
|
392
|
+
bars: b,
|
|
393
|
+
prev: mode === 'resume' ? memory : null,
|
|
394
|
+
next,
|
|
395
|
+
seriesSlot: 0,
|
|
396
|
+
taSlot: 0,
|
|
397
|
+
blockSlot: 0,
|
|
398
|
+
plotSlot: 0,
|
|
399
|
+
boxSlot: 0,
|
|
400
|
+
drawSlot: 0,
|
|
401
|
+
block: -1,
|
|
402
|
+
boxes: [],
|
|
403
|
+
blocked: null,
|
|
404
|
+
};
|
|
405
|
+
};
|
|
406
|
+
const full = (b, c) => {
|
|
407
|
+
memory = null;
|
|
408
|
+
if (reason)
|
|
409
|
+
return { ...runBody(body, b, inputs, c, options, null), from: 0, incremental: false };
|
|
410
|
+
const inc = newRun('record', b, 0);
|
|
411
|
+
const result = runBody(body, b, inputs, c, options, inc);
|
|
412
|
+
if (inc.blocked)
|
|
413
|
+
reason = inc.blocked;
|
|
414
|
+
else
|
|
415
|
+
memory = inc.next;
|
|
416
|
+
return { ...result, from: 0, incremental: false };
|
|
417
|
+
};
|
|
418
|
+
return {
|
|
419
|
+
get fullRunReason() {
|
|
420
|
+
return reason;
|
|
421
|
+
},
|
|
422
|
+
update(b, c = previousChart) {
|
|
423
|
+
const last = previous;
|
|
424
|
+
const m = memory;
|
|
425
|
+
const resumable = !reason && m !== null && last !== null && last.n >= 1 && b.length >= last.n && sameChart(previousChart, c) &&
|
|
426
|
+
sameBars(last, b, last.n - 1);
|
|
427
|
+
previousChart = c;
|
|
428
|
+
let out;
|
|
429
|
+
if (!resumable) {
|
|
430
|
+
out = full(b, c);
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
const from = last.n - 1;
|
|
434
|
+
const inc = newRun('resume', b, from);
|
|
435
|
+
let result = null;
|
|
436
|
+
try {
|
|
437
|
+
result = runBody(body, b, inputs, c, options, inc);
|
|
438
|
+
}
|
|
439
|
+
catch (err) {
|
|
440
|
+
// the memory is changed in place by a resumed run: an error leaves it unusable
|
|
441
|
+
memory = null;
|
|
442
|
+
previous = null;
|
|
443
|
+
if (!(err instanceof incremental.ResumeAborted))
|
|
444
|
+
throw err;
|
|
445
|
+
reason = err.reason;
|
|
446
|
+
}
|
|
447
|
+
if (result && verifyLeft > 0) {
|
|
448
|
+
verifyLeft--;
|
|
449
|
+
const check = runBody(body, b, inputs, c, options, null);
|
|
450
|
+
if (!sameResult(result, check)) {
|
|
451
|
+
reason = 'a resumed update differs from a full run (state kept outside persist()?)';
|
|
452
|
+
result = check;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (result && !reason) {
|
|
456
|
+
memory = inc.next;
|
|
457
|
+
out = { ...result, from, incremental: true };
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
out = result && reason ? { ...result, from: 0, incremental: false } : full(b, c);
|
|
461
|
+
memory = null;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);
|
|
465
|
+
return out;
|
|
466
|
+
},
|
|
467
|
+
};
|
|
468
|
+
}
|
|
266
469
|
let varipRun = { slot: 0, recorder: null, mode: 'live', scratch: null };
|
|
267
470
|
/**
|
|
268
471
|
* PineScript `varip`: a variable that keeps the changes made in the intrabar runs of a strategy (PineScript
|
|
@@ -272,6 +475,7 @@ let varipRun = { slot: 0, recorder: null, mode: 'live', scratch: null };
|
|
|
272
475
|
*/
|
|
273
476
|
export function varip(initial) {
|
|
274
477
|
collector();
|
|
478
|
+
incremental.nonIncremental('varip');
|
|
275
479
|
const slot = varipRun.slot++;
|
|
276
480
|
const state = varipRun;
|
|
277
481
|
const rec = state.recorder;
|
|
@@ -298,6 +502,76 @@ export function varip(initial) {
|
|
|
298
502
|
},
|
|
299
503
|
};
|
|
300
504
|
}
|
|
505
|
+
/**
|
|
506
|
+
* PineScript `var` kept by the runtime (#196): a variable that keeps its value from one bar to the next. Declare it in
|
|
507
|
+
* the script body (outside the callbacks), in the same order on each run, and read and write it in one eachBar()
|
|
508
|
+
* callback. In a plain run it is a plain variable. In an incremental run (createScriptRun), the runtime keeps its value
|
|
509
|
+
* at the end of the last confirmed bar and puts it back before the forming bar is calculated again: use it instead of
|
|
510
|
+
* a `let` variable outside the callback, which a resumed run cannot put back.
|
|
511
|
+
*
|
|
512
|
+
* The run is calculated in full (not resumed) when the variable is read or written outside an eachBar() callback, by
|
|
513
|
+
* two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans, arrays, plain objects,
|
|
514
|
+
* Map, Set).
|
|
515
|
+
*
|
|
516
|
+
* ```typescript
|
|
517
|
+
* const dir = persist(0); // var dir = 0
|
|
518
|
+
* const trend = eachBar((c) => {
|
|
519
|
+
* if (c.close > c.get(close, 1)) dir.value = 1;
|
|
520
|
+
* else if (c.close < c.get(close, 1)) dir.value = -1;
|
|
521
|
+
* return dir.value;
|
|
522
|
+
* });
|
|
523
|
+
* ```
|
|
524
|
+
*/
|
|
525
|
+
export function persist(initial) {
|
|
526
|
+
collector();
|
|
527
|
+
if (currentBar >= 0) {
|
|
528
|
+
throw new Error('persist() is declared in the script body, outside the eachBar() callback (once per run).');
|
|
529
|
+
}
|
|
530
|
+
let current = initial;
|
|
531
|
+
const run = incremental.active;
|
|
532
|
+
if (!run) {
|
|
533
|
+
return {
|
|
534
|
+
get value() {
|
|
535
|
+
return current;
|
|
536
|
+
},
|
|
537
|
+
set value(v) {
|
|
538
|
+
current = v;
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
const slot = run.boxSlot++;
|
|
543
|
+
run.boxes[slot] = {
|
|
544
|
+
get: () => current,
|
|
545
|
+
set: (v) => {
|
|
546
|
+
current = v;
|
|
547
|
+
},
|
|
548
|
+
};
|
|
549
|
+
if (run.mode === 'resume')
|
|
550
|
+
run.next.boxOwner[slot] = run.prev?.boxOwner[slot];
|
|
551
|
+
const touch = () => {
|
|
552
|
+
if (incremental.active !== run)
|
|
553
|
+
return;
|
|
554
|
+
if (run.block < 0) {
|
|
555
|
+
incremental.nonIncremental('persist() used outside eachBar()');
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const owner = run.next.boxOwner[slot];
|
|
559
|
+
if (owner === undefined)
|
|
560
|
+
run.next.boxOwner[slot] = run.block;
|
|
561
|
+
else if (owner !== run.block)
|
|
562
|
+
incremental.nonIncremental('persist() used by two eachBar() blocks');
|
|
563
|
+
};
|
|
564
|
+
return {
|
|
565
|
+
get value() {
|
|
566
|
+
touch();
|
|
567
|
+
return current;
|
|
568
|
+
},
|
|
569
|
+
set value(v) {
|
|
570
|
+
touch();
|
|
571
|
+
current = v;
|
|
572
|
+
},
|
|
573
|
+
};
|
|
574
|
+
}
|
|
301
575
|
/** PineScript `indicator()` — declares the script's metadata. */
|
|
302
576
|
export function indicator(title, options = {}) {
|
|
303
577
|
const c = collector();
|
|
@@ -486,7 +760,11 @@ export const hlcc4 = new Series(ctxBars, (b) => (b.high + b.low + 2 * b.close) /
|
|
|
486
760
|
export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
487
761
|
bar_index.fullHistory = true;
|
|
488
762
|
/** PineScript `last_bar_index`: the index of the last bar, on every bar. In a bar loop, `c.n - 1`. */
|
|
489
|
-
export const last_bar_index = new Series(ctxBars, (_b, _i, data) =>
|
|
763
|
+
export const last_bar_index = new Series(ctxBars, (_b, _i, data) => {
|
|
764
|
+
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196)
|
|
765
|
+
incremental.nonIncremental('last_bar_index');
|
|
766
|
+
return data.length - 1;
|
|
767
|
+
});
|
|
490
768
|
last_bar_index.fullHistory = true;
|
|
491
769
|
// built-in price variables keep the whole history (no 5000-bar limit)
|
|
492
770
|
for (const s of [hl2, hlc3, ohlc4, hlcc4])
|
|
@@ -596,23 +874,120 @@ function outsideBarLoops(members) {
|
|
|
596
874
|
}
|
|
597
875
|
return out;
|
|
598
876
|
}
|
|
877
|
+
/**
|
|
878
|
+
* A ta.* call of the script that has a {@link taStep} machine (#196). Outside an incremental run, the array function
|
|
879
|
+
* (`full`). In an incremental run, the machine steps every bar of a recorded run, and only the bars from the forming bar
|
|
880
|
+
* of the previous run in a resumed one (the machine holds the state of the last confirmed bar): the same doubles
|
|
881
|
+
* (tests/ta/step.test.ts).
|
|
882
|
+
*/
|
|
883
|
+
function stepped(kind, make, sources, args, outs, full) {
|
|
884
|
+
const run = incremental.active;
|
|
885
|
+
if (!run)
|
|
886
|
+
return full();
|
|
887
|
+
const slot = run.taSlot++;
|
|
888
|
+
const b = sources[0] ? sources[0].bars : bars();
|
|
889
|
+
const n = b.length;
|
|
890
|
+
const values = sources.map((s) => s.toArray());
|
|
891
|
+
let mem;
|
|
892
|
+
let from = 0;
|
|
893
|
+
const prev = run.mode === 'resume' ? run.prev?.ta[slot] : undefined;
|
|
894
|
+
if (run.mode === 'resume') {
|
|
895
|
+
if (!prev || prev.kind !== kind)
|
|
896
|
+
incremental.nonIncremental(`a new ta.${kind}() call`);
|
|
897
|
+
from = run.from;
|
|
898
|
+
// the arrays of the previous run are the run's own: their first values are kept in place
|
|
899
|
+
mem = { kind, machine: prev.machine, outs: prev.outs };
|
|
900
|
+
}
|
|
901
|
+
else {
|
|
902
|
+
mem = { kind, machine: make(), outs: Array.from({ length: outs }, () => []) };
|
|
903
|
+
}
|
|
904
|
+
for (const o of mem.outs)
|
|
905
|
+
o.length = n;
|
|
906
|
+
for (let i = from; i < n; i++) {
|
|
907
|
+
const r = mem.machine.step(...args(values, i));
|
|
908
|
+
if (outs === 1)
|
|
909
|
+
mem.outs[0][i] = typeof r === 'boolean' ? (r ? 1 : 0) : r;
|
|
910
|
+
else
|
|
911
|
+
for (let k = 0; k < outs; k++)
|
|
912
|
+
mem.outs[k][i] = r[k];
|
|
913
|
+
// the forming bar is not committed: the next update steps it again from the confirmed bars
|
|
914
|
+
if (i < n - 1)
|
|
915
|
+
mem.machine.commit();
|
|
916
|
+
}
|
|
917
|
+
run.next.ta[slot] = mem;
|
|
918
|
+
const series = mem.outs.map((o) => Series.fromArray(b, o));
|
|
919
|
+
return (outs === 1 ? series[0] : series);
|
|
920
|
+
}
|
|
921
|
+
const at = (v, k, i) => v[k][i];
|
|
922
|
+
/** The ta.* calls computed bar by bar in an incremental run (a length given as a Series uses the array function). */
|
|
923
|
+
const steppedTa = {
|
|
924
|
+
sma: (source, length) => typeof length === 'number'
|
|
925
|
+
? stepped('sma', taStep.sma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.sma(source, length))
|
|
926
|
+
: taSeries.sma(source, length),
|
|
927
|
+
ema: (source, length) => stepped('ema', () => taStep.ema(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.ema(source, length)),
|
|
928
|
+
rma: (source, length) => stepped('rma', () => taStep.rma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rma(source, length)),
|
|
929
|
+
wma: (source, length) => typeof length === 'number'
|
|
930
|
+
? stepped('wma', taStep.wma, [source], (v, i) => [at(v, 0, i), length], 1, () => taSeries.wma(source, length))
|
|
931
|
+
: taSeries.wma(source, length),
|
|
932
|
+
rsi: (source, length) => typeof length === 'number'
|
|
933
|
+
? stepped('rsi', () => taStep.rsi(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.rsi(source, length))
|
|
934
|
+
: taSeries.rsi(source, length),
|
|
935
|
+
change: (source, length = 1) => stepped('change', () => taStep.change(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.change(source, length)),
|
|
936
|
+
mom: (source, length) => stepped('mom', () => taStep.mom(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.mom(source, length)),
|
|
937
|
+
roc: (source, length) => stepped('roc', () => taStep.roc(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.roc(source, length)),
|
|
938
|
+
cum: (source) => stepped('cum', taStep.cum, [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cum(source)),
|
|
939
|
+
stdev: (source, length, biased = true) => typeof length === 'number'
|
|
940
|
+
? stepped('stdev', taStep.stdev, [source], (v, i) => [at(v, 0, i), length, biased], 1, () => taSeries.stdev(source, length, biased))
|
|
941
|
+
: taSeries.stdev(source, length, biased),
|
|
942
|
+
variance: (source, length, biased = true) => typeof length === 'number'
|
|
943
|
+
? stepped('variance', taStep.variance, [source], (v, i) => [at(v, 0, i), length, biased], 1, () => taSeries.variance(source, length, biased))
|
|
944
|
+
: taSeries.variance(source, length, biased),
|
|
945
|
+
crossover: (a, b) => stepped('crossover', taStep.crossover, typeof b === 'number' ? [a] : [a, b], (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossover(a, b)),
|
|
946
|
+
crossunder: (a, b) => stepped('crossunder', taStep.crossunder, typeof b === 'number' ? [a] : [a, b], (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.crossunder(a, b)),
|
|
947
|
+
cross: (a, b) => stepped('cross', taStep.cross, typeof b === 'number' ? [a] : [a, b], (v, i) => [at(v, 0, i), typeof b === 'number' ? b : at(v, 1, i)], 1, () => taSeries.cross(a, b)),
|
|
948
|
+
barssince: (condition) => stepped('barssince', taStep.barssince, [condition], (v, i) => [at(v, 0, i) === 1], 1, () => taSeries.barssince(condition)),
|
|
949
|
+
valuewhen: (condition, source, occurrence) => stepped('valuewhen', () => taStep.valuewhen(occurrence), [condition, source], (v, i) => [at(v, 0, i) === 1, at(v, 1, i)], 1, () => taSeries.valuewhen(condition, source, occurrence)),
|
|
950
|
+
macd: (source, fastLength, slowLength, signalLength) => stepped('macd', () => taStep.macd(fastLength, slowLength, signalLength), [source], (v, i) => [at(v, 0, i)], 3, () => taSeries.macd(source, fastLength, slowLength, signalLength)),
|
|
951
|
+
bb: (source, length, mult) => stepped('bb', () => taStep.bb(length, mult), [source], (v, i) => [at(v, 0, i)], 3, () => taSeries.bb(source, length, mult)),
|
|
952
|
+
hma: (source, length) => stepped('hma', () => taStep.hma(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.hma(source, length)),
|
|
953
|
+
dev: (source, length) => stepped('dev', () => taStep.dev(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.dev(source, length)),
|
|
954
|
+
cci: (source, length) => stepped('cci', () => taStep.cci(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.cci(source, length)),
|
|
955
|
+
percentrank: (source, length) => stepped('percentrank', () => taStep.percentrank(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.percentrank(source, length)),
|
|
956
|
+
median: (source, length) => stepped('median', () => taStep.median(length), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.median(source, length)),
|
|
957
|
+
linreg: (source, length, offset = 0) => stepped('linreg', () => taStep.linreg(length, offset), [source], (v, i) => [at(v, 0, i)], 1, () => taSeries.linreg(source, length, offset)),
|
|
958
|
+
correlation: (a, b, length) => stepped('correlation', () => taStep.correlation(length), [a, b], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () => taSeries.correlation(a, b, length)),
|
|
959
|
+
stoch: (source, highSource, lowSource, length) => stepped('stoch', () => taStep.stoch(length), [source, highSource, lowSource], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.stoch(source, highSource, lowSource, length)),
|
|
960
|
+
};
|
|
599
961
|
/** ta.* with the chart-implicit (bars-first) functions bound to the context,
|
|
600
962
|
* so scripts call them like PineScript: `ta.tr(true)`, `ta.atr(14)`. */
|
|
601
963
|
export const ta = strictNamespace('ta', outsideBarLoops({
|
|
602
964
|
...taSeries,
|
|
603
|
-
|
|
604
|
-
|
|
965
|
+
...steppedTa,
|
|
966
|
+
tr: (handleNa = false) => stepped('tr', () => taStep.tr(handleNa), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.tr(bars(), handleNa)),
|
|
967
|
+
atr: (length) => stepped('atr', () => taStep.atr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.atr(bars(), length)),
|
|
605
968
|
sar: (start, inc, max) => taSeries.sar(bars(), start, inc, max),
|
|
606
|
-
wpr: (length) => taSeries.wpr(bars(), length),
|
|
607
|
-
supertrend: (factor, atrLength) => taSeries.supertrend(bars(), factor, atrLength),
|
|
608
|
-
dmi: (diLength, adxSmoothing) => taSeries.dmi(bars(), diLength, adxSmoothing),
|
|
969
|
+
wpr: (length = 14) => stepped('wpr', () => taStep.wpr(length), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 1, () => taSeries.wpr(bars(), length)),
|
|
970
|
+
supertrend: (factor, atrLength) => stepped('supertrend', () => taStep.supertrend(factor, atrLength), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 2, () => taSeries.supertrend(bars(), factor, atrLength)),
|
|
971
|
+
dmi: (diLength, adxSmoothing) => stepped('dmi', () => taStep.dmi(diLength, adxSmoothing), [high, low, close], (v, i) => [at(v, 0, i), at(v, 1, i), at(v, 2, i)], 3, () => taSeries.dmi(bars(), diLength, adxSmoothing)),
|
|
609
972
|
kc: (source, length, mult, useTrueRange) => taSeries.kc(bars(), source, length, mult, useTrueRange),
|
|
610
973
|
kcw: (source, length, mult, useTrueRange) => taSeries.kcw(bars(), source, length, mult, useTrueRange),
|
|
611
974
|
ichimoku: (conversionPeriods, basePeriods, laggingSpan2Periods, displacement) => taSeries.ichimoku(bars(), conversionPeriods, basePeriods, laggingSpan2Periods, displacement),
|
|
612
975
|
/** `ta.highest(source, length)` or `ta.highest(length)` (source = high). */
|
|
613
|
-
highest: (sourceOrLength, length) =>
|
|
976
|
+
highest: (sourceOrLength, length) => {
|
|
977
|
+
const source = typeof sourceOrLength === 'number' ? high : sourceOrLength;
|
|
978
|
+
const len = typeof sourceOrLength === 'number' ? sourceOrLength : length;
|
|
979
|
+
return typeof len === 'number'
|
|
980
|
+
? stepped('highest', taStep.highest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.highest(source, len))
|
|
981
|
+
: taSeries.highest(source, len);
|
|
982
|
+
},
|
|
614
983
|
/** `ta.lowest(source, length)` or `ta.lowest(length)` (source = low). */
|
|
615
|
-
lowest: (sourceOrLength, length) =>
|
|
984
|
+
lowest: (sourceOrLength, length) => {
|
|
985
|
+
const source = typeof sourceOrLength === 'number' ? low : sourceOrLength;
|
|
986
|
+
const len = typeof sourceOrLength === 'number' ? sourceOrLength : length;
|
|
987
|
+
return typeof len === 'number'
|
|
988
|
+
? stepped('lowest', taStep.lowest, [source], (v, i) => [at(v, 0, i), len], 1, () => taSeries.lowest(source, len))
|
|
989
|
+
: taSeries.lowest(source, len);
|
|
990
|
+
},
|
|
616
991
|
/** `ta.highestbars(source, length)` or `ta.highestbars(length)` (source = high); offsets are 0 or negative. */
|
|
617
992
|
highestbars: (sourceOrLength, length) => typeof sourceOrLength === 'number'
|
|
618
993
|
? taSeries.highestbars(high, sourceOrLength)
|
|
@@ -630,9 +1005,9 @@ export const ta = strictNamespace('ta', outsideBarLoops({
|
|
|
630
1005
|
return stdev_mult === undefined ? taSeries.vwap(source, volume, a) : taSeries.vwapBands(source, volume, a, stdev_mult);
|
|
631
1006
|
}),
|
|
632
1007
|
/** `ta.vwma(source, length)` with the chart volume, as PineScript; a third argument gives another volume. */
|
|
633
|
-
vwma: (source, length, vol) => taSeries.vwma(source, length, vol ?? volume),
|
|
1008
|
+
vwma: (source, length, vol) => stepped('vwma', () => taStep.vwma(length), [source, vol ?? volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () => taSeries.vwma(source, length, vol ?? volume)),
|
|
634
1009
|
/** `ta.mfi(source, length)` with the chart volume (PineScript takes 2 arguments). */
|
|
635
|
-
mfi: (source, length) => taSeries.mfi(source, length, volume),
|
|
1010
|
+
mfi: (source, length) => stepped('mfi', () => taStep.mfi(length), [source, volume], (v, i) => [at(v, 0, i), at(v, 1, i)], 1, () => taSeries.mfi(source, length, volume)),
|
|
636
1011
|
/** `ta.pivothigh(source, leftbars, rightbars)` or `ta.pivothigh(leftbars, rightbars)` (source = high).
|
|
637
1012
|
* The value appears `rightbars` bars after the pivot bar, as in PineScript. */
|
|
638
1013
|
pivothigh: (sourceOrLeft, leftOrRight, rightbars) => typeof sourceOrLeft === 'number'
|
|
@@ -658,6 +1033,20 @@ export function fixnan(source) {
|
|
|
658
1033
|
// the colours are the same set: the palette stays
|
|
659
1034
|
return withPalette(fixnanValues(source), colorPalettes.get(source));
|
|
660
1035
|
}
|
|
1036
|
+
export function na(x) {
|
|
1037
|
+
if (x instanceof Series)
|
|
1038
|
+
return Series.fromArray(ctxBars, x.toArray().map((v) => (isNA(v) ? 1 : 0)));
|
|
1039
|
+
return isNA(x);
|
|
1040
|
+
}
|
|
1041
|
+
export function nz(source, replacement = 0) {
|
|
1042
|
+
if (source instanceof Series) {
|
|
1043
|
+
const values = source.toArray();
|
|
1044
|
+
const rep = replacement instanceof Series ? replacement.toArray() : undefined;
|
|
1045
|
+
const r = rep ? 0 : Number(replacement);
|
|
1046
|
+
return Series.fromArray(ctxBars, values.map((v, i) => (isNA(v) ? (rep ? rep[i] : r) : v)));
|
|
1047
|
+
}
|
|
1048
|
+
return nzValue(source, replacement);
|
|
1049
|
+
}
|
|
661
1050
|
// ── Color helpers ────────────────────────────────────────────────────────────
|
|
662
1051
|
/**
|
|
663
1052
|
* The palette of a per-bar colour array: the constant colours it chooses from (PineScript compiles the colours of a
|
|
@@ -679,10 +1068,21 @@ function colorWhen(cond, colorTrue, colorFalse) {
|
|
|
679
1068
|
const palette = [colorTrue, ...(colorFalse !== undefined && colorFalse !== colorTrue ? [colorFalse] : [])];
|
|
680
1069
|
return withPalette(colors, palette);
|
|
681
1070
|
}
|
|
1071
|
+
function fromGradient(value, bottom_value, top_value, bottom_color, top_color) {
|
|
1072
|
+
const args = [value, bottom_value, top_value];
|
|
1073
|
+
if (!args.some((a) => a instanceof Series) && !Array.isArray(bottom_color) && !Array.isArray(top_color)) {
|
|
1074
|
+
return colorCore.from_gradient(value, bottom_value, top_value, bottom_color, top_color);
|
|
1075
|
+
}
|
|
1076
|
+
const [v, lo, hi] = args.map((a) => (a instanceof Series ? a.toArray() : undefined));
|
|
1077
|
+
const at = (arr, num, i) => (arr ? arr[i] : num);
|
|
1078
|
+
const colorAt = (c, i) => (Array.isArray(c) ? c[i] : c);
|
|
1079
|
+
return Array.from({ length: ctxBars.length }, (_, i) => colorCore.from_gradient(at(v, value, i), at(lo, bottom_value, i), at(hi, top_value, i), colorAt(bottom_color, i), colorAt(top_color, i)));
|
|
1080
|
+
}
|
|
682
1081
|
/** color.* plus `when` — per-bar conditional colors for plot()/fill()/bgcolor()/barcolor(). */
|
|
683
1082
|
export const color = strictNamespace('color', {
|
|
684
1083
|
...colorCore,
|
|
685
1084
|
new: colorCore.new_color,
|
|
1085
|
+
from_gradient: fromGradient,
|
|
686
1086
|
when: colorWhen,
|
|
687
1087
|
});
|
|
688
1088
|
/**
|
|
@@ -726,17 +1126,42 @@ function plotImpl(series, title = DEFAULT_OUTPUT_TITLES.plot, options = {}) {
|
|
|
726
1126
|
c.outputs.push({ kind: 'plot', id, title });
|
|
727
1127
|
const values = series.toArray();
|
|
728
1128
|
const b = bars();
|
|
729
|
-
|
|
1129
|
+
let data = [];
|
|
730
1130
|
// offset (PineScript plot(offset = k)): the value and colour of bar i are drawn on bar i + k; bars past the
|
|
731
1131
|
// chart's first or last bar are dropped
|
|
732
1132
|
const off = Math.trunc(options.offset ?? 0);
|
|
733
|
-
|
|
1133
|
+
let j0 = Math.max(0, off);
|
|
1134
|
+
// An incremental run (#196) keeps the points of the bars whose values did not change; pos[j]: points before bar j
|
|
1135
|
+
const run = incremental.active;
|
|
1136
|
+
const slot = run ? run.plotSlot++ : -1;
|
|
1137
|
+
let pos = [];
|
|
1138
|
+
const prev = run?.mode === 'resume' ? run.prev?.plots[slot] : undefined;
|
|
1139
|
+
const sig = `${off}|${perBar ? 'colors' : ''}`;
|
|
1140
|
+
if (prev && prev.sig === sig) {
|
|
1141
|
+
const from = Math.max(j0, run.from + Math.min(0, off));
|
|
1142
|
+
if (from < prev.pos.length) {
|
|
1143
|
+
// the points are given to the host: a copy of the kept ones (the positions are the run's own)
|
|
1144
|
+
data = prev.data.slice(0, prev.pos[from]);
|
|
1145
|
+
pos = prev.pos;
|
|
1146
|
+
pos.length = from;
|
|
1147
|
+
j0 = from;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
for (let j = 0; j < j0; j++)
|
|
1151
|
+
pos[j] ??= 0;
|
|
1152
|
+
let j = j0;
|
|
1153
|
+
for (; j < b.length && j - off < b.length; j++) {
|
|
1154
|
+
pos[j] = data.length;
|
|
734
1155
|
const i = j - off;
|
|
735
1156
|
const value = values[i];
|
|
736
1157
|
if (value === undefined || !Number.isFinite(value))
|
|
737
1158
|
continue; // PineScript plots +/-Infinity as na
|
|
738
1159
|
data.push(perBar ? { time: b[j].time, value, color: perBar[i] } : { time: b[j].time, value });
|
|
739
1160
|
}
|
|
1161
|
+
for (; j <= b.length; j++)
|
|
1162
|
+
pos[j] = data.length;
|
|
1163
|
+
if (run)
|
|
1164
|
+
run.next.plots[slot] = { data, pos, sig };
|
|
740
1165
|
c.plots[id] = data;
|
|
741
1166
|
return { id, kind: 'plot' };
|
|
742
1167
|
}
|
|
@@ -1204,21 +1629,107 @@ export function plotbar(open, high, low, close, title, options = {}) {
|
|
|
1204
1629
|
/** Initial history buffer of a script series and its growth factor (measured, issue #149). */
|
|
1205
1630
|
const HISTORY_START = 242;
|
|
1206
1631
|
const HISTORY_GROWTH = 1.618034;
|
|
1632
|
+
/** The outer variables an eachBar() callback changes, by callback source (the same callback on every run). */
|
|
1633
|
+
const outerWritesCache = new Map();
|
|
1634
|
+
function outerWritesOf(fn) {
|
|
1635
|
+
const src = fn.toString();
|
|
1636
|
+
let found = outerWritesCache.get(src);
|
|
1637
|
+
if (!found) {
|
|
1638
|
+
found = outerWrites(src);
|
|
1639
|
+
if (outerWritesCache.size > 500)
|
|
1640
|
+
outerWritesCache.clear();
|
|
1641
|
+
outerWritesCache.set(src, found);
|
|
1642
|
+
}
|
|
1643
|
+
return found;
|
|
1644
|
+
}
|
|
1207
1645
|
export function eachBar(fn) {
|
|
1646
|
+
return runBlock(fn);
|
|
1647
|
+
}
|
|
1648
|
+
function runBlock(fn, extra,
|
|
1649
|
+
/** The script's own callback, when fn wraps it (strategy.eachBar) */
|
|
1650
|
+
own = fn) {
|
|
1208
1651
|
collector(); // same lifecycle guard (and error message) as the declaration calls
|
|
1209
1652
|
const b = bars();
|
|
1210
1653
|
// An intrabar run ends on its bar: the chart's last bar stays the main run's.
|
|
1211
1654
|
const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;
|
|
1212
|
-
|
|
1655
|
+
let out = new Array(b.length).fill(NaN);
|
|
1213
1656
|
const cache = new Map();
|
|
1657
|
+
// history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series
|
|
1214
1658
|
const buffers = new Map();
|
|
1659
|
+
const bufferKey = (src) => incremental.slotOf(src) ?? src;
|
|
1215
1660
|
let pendingError = null;
|
|
1216
1661
|
let idx = 0;
|
|
1662
|
+
// An incremental run (#196): the block is matched by its order with the previous run; a resumed block starts on the
|
|
1663
|
+
// forming bar of the previous run, from its state at the end of the last confirmed bar.
|
|
1664
|
+
const run = incremental.active;
|
|
1665
|
+
const slot = run ? (run.block < 0 ? run.blockSlot++ : -1) : -1;
|
|
1666
|
+
if (run && slot < 0)
|
|
1667
|
+
incremental.nonIncremental('eachBar() inside eachBar()');
|
|
1668
|
+
if (run?.mode === 'record') {
|
|
1669
|
+
// a variable outside the callback that it changes is not put back by a resumed run: use persist()
|
|
1670
|
+
const written = outerWritesOf(own);
|
|
1671
|
+
if (written.length)
|
|
1672
|
+
incremental.nonIncremental(`eachBar() callback changes ${written.join(', ')} outside it (use persist())`);
|
|
1673
|
+
}
|
|
1674
|
+
let start = 0;
|
|
1675
|
+
let checkpoint = null;
|
|
1676
|
+
if (run?.mode === 'resume') {
|
|
1677
|
+
const prev = run.prev?.blocks[slot];
|
|
1678
|
+
if (!prev)
|
|
1679
|
+
incremental.nonIncremental('a new eachBar() block');
|
|
1680
|
+
start = run.from;
|
|
1681
|
+
// the block's own array of the previous run: its first values are kept in place
|
|
1682
|
+
out = prev.out;
|
|
1683
|
+
out.length = b.length;
|
|
1684
|
+
for (let i = start; i < b.length; i++)
|
|
1685
|
+
out[i] = NaN;
|
|
1686
|
+
checkpoint = prev.checkpoint;
|
|
1687
|
+
// the block that draws puts the registry back to the last confirmed bar
|
|
1688
|
+
if (run.prev.drawingBlock === slot && checkpoint.drawings)
|
|
1689
|
+
restoreDrawingCheckpoint(checkpoint.drawings);
|
|
1690
|
+
if (extra)
|
|
1691
|
+
extra.restore(checkpoint.extra);
|
|
1692
|
+
for (const [key, state] of checkpoint.buffers)
|
|
1693
|
+
buffers.set(key, { ...state });
|
|
1694
|
+
pendingError = checkpoint.pendingError ? { ...checkpoint.pendingError } : null;
|
|
1695
|
+
for (const [box, value] of checkpoint.boxes) {
|
|
1696
|
+
const ref = run.boxes[box];
|
|
1697
|
+
if (!ref)
|
|
1698
|
+
incremental.nonIncremental('a persist() box of the previous run is missing');
|
|
1699
|
+
ref.set(incremental.copyValue(value));
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
/** State at the end of the bar just run: the boxes this block owns, the history buffers */
|
|
1703
|
+
const takeCheckpoint = () => {
|
|
1704
|
+
const boxes = new Map();
|
|
1705
|
+
run.boxes.forEach((ref, box) => {
|
|
1706
|
+
if (run.next.boxOwner[box] === slot)
|
|
1707
|
+
boxes.set(box, incremental.copyValue(ref.get()));
|
|
1708
|
+
});
|
|
1709
|
+
const kept = new Map();
|
|
1710
|
+
for (const [key, state] of buffers)
|
|
1711
|
+
kept.set(key, { ...state });
|
|
1712
|
+
return {
|
|
1713
|
+
boxes,
|
|
1714
|
+
buffers: kept,
|
|
1715
|
+
pendingError: pendingError ? { ...pendingError } : null,
|
|
1716
|
+
drawings: saveDrawingCheckpoint(),
|
|
1717
|
+
extra: extra?.save(),
|
|
1718
|
+
};
|
|
1719
|
+
};
|
|
1720
|
+
// the last confirmed bar is before the first bar run (a new run of one bar): its state is the initial one
|
|
1721
|
+
if (run && b.length - 2 < start && !checkpoint)
|
|
1722
|
+
checkpoint = takeCheckpoint();
|
|
1217
1723
|
const ctx = {
|
|
1218
1724
|
get i() {
|
|
1219
1725
|
return idx;
|
|
1220
1726
|
},
|
|
1221
|
-
n
|
|
1727
|
+
get n() {
|
|
1728
|
+
// the bar count changes with each new bar: a value read from it is not kept by an incremental run
|
|
1729
|
+
if (run)
|
|
1730
|
+
incremental.nonIncremental('BarContext.n');
|
|
1731
|
+
return lastIndex + 1;
|
|
1732
|
+
},
|
|
1222
1733
|
get time() {
|
|
1223
1734
|
return b[idx].time;
|
|
1224
1735
|
},
|
|
@@ -1244,9 +1755,9 @@ export function eachBar(fn) {
|
|
|
1244
1755
|
const k = Math.floor(offset);
|
|
1245
1756
|
if (k > MAX_BARS_BACK)
|
|
1246
1757
|
throw new Error(historyError(idx, k));
|
|
1247
|
-
let buffer = buffers.get(src);
|
|
1758
|
+
let buffer = buffers.get(bufferKey(src));
|
|
1248
1759
|
if (!buffer)
|
|
1249
|
-
buffers.set(src, (buffer = { size: HISTORY_START, previous: 0, barMax: 0 }));
|
|
1760
|
+
buffers.set(bufferKey(src), (buffer = { size: HISTORY_START, previous: 0, barMax: 0 }));
|
|
1250
1761
|
if (k > buffer.barMax)
|
|
1251
1762
|
buffer.barMax = k;
|
|
1252
1763
|
}
|
|
@@ -1263,8 +1774,11 @@ export function eachBar(fn) {
|
|
|
1263
1774
|
return j >= 0 ? out[j] : NaN;
|
|
1264
1775
|
},
|
|
1265
1776
|
};
|
|
1777
|
+
const outerBlock = run ? run.block : -1;
|
|
1778
|
+
if (run)
|
|
1779
|
+
run.block = slot;
|
|
1266
1780
|
try {
|
|
1267
|
-
for (idx =
|
|
1781
|
+
for (idx = start; idx < b.length; idx++) {
|
|
1268
1782
|
if (pendingError && pendingError.bar === idx)
|
|
1269
1783
|
throw new Error(historyError(idx, pendingError.barsBack));
|
|
1270
1784
|
currentBar = idx;
|
|
@@ -1283,12 +1797,19 @@ export function eachBar(fn) {
|
|
|
1283
1797
|
buffer.previous = k;
|
|
1284
1798
|
buffer.barMax = 0;
|
|
1285
1799
|
}
|
|
1800
|
+
// the last confirmed bar (the forming bar is the last one): its state is where the next update starts
|
|
1801
|
+
if (run && idx === b.length - 2)
|
|
1802
|
+
checkpoint = takeCheckpoint();
|
|
1286
1803
|
}
|
|
1287
1804
|
}
|
|
1288
1805
|
finally {
|
|
1289
1806
|
currentBar = -1;
|
|
1290
1807
|
setDrawingBar(null);
|
|
1808
|
+
if (run)
|
|
1809
|
+
run.block = outerBlock;
|
|
1291
1810
|
}
|
|
1811
|
+
if (run)
|
|
1812
|
+
run.next.blocks[slot] = { out, checkpoint: checkpoint };
|
|
1292
1813
|
return Series.fromArray(ctxBars, out);
|
|
1293
1814
|
}
|
|
1294
1815
|
/** Bar index of the running eachBar() callback, -1 outside eachBar(). */
|
|
@@ -1422,7 +1943,15 @@ function strategyEachBar(fn) {
|
|
|
1422
1943
|
});
|
|
1423
1944
|
}
|
|
1424
1945
|
const recorder = scriptOptions.recorder;
|
|
1425
|
-
|
|
1946
|
+
// an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it
|
|
1947
|
+
if (incremental.active) {
|
|
1948
|
+
if (recorder)
|
|
1949
|
+
incremental.nonIncremental('a strategy with intrabar runs (recorder)');
|
|
1950
|
+
if (!engine.save || !engine.restore)
|
|
1951
|
+
incremental.nonIncremental('a strategy engine without save() / restore()');
|
|
1952
|
+
}
|
|
1953
|
+
const extra = engine.save && engine.restore ? { save: () => engine.save(), restore: (s) => engine.restore(s) } : undefined;
|
|
1954
|
+
return runBlock((c) => {
|
|
1426
1955
|
engine.processBar(c.i);
|
|
1427
1956
|
if (recorder) {
|
|
1428
1957
|
recorder.varipStarts[c.i] = [...recorder.varip];
|
|
@@ -1437,7 +1966,7 @@ function strategyEachBar(fn) {
|
|
|
1437
1966
|
run.engine = engine;
|
|
1438
1967
|
engine.processClose(c.i);
|
|
1439
1968
|
}
|
|
1440
|
-
});
|
|
1969
|
+
}, extra, fn);
|
|
1441
1970
|
}
|
|
1442
1971
|
/** The engine of a main run that records its answers (see {@link StrategyRecorder}). */
|
|
1443
1972
|
function recordingEngine(engine, log) {
|
|
@@ -1826,7 +2355,10 @@ function timeCloseFunction(tf, session, timezone) {
|
|
|
1826
2355
|
/** Current time of the run in ms, see `ChartContext.now`. */
|
|
1827
2356
|
let runNow = NaN;
|
|
1828
2357
|
/** PineScript `timenow`: the current time in ms, the same on every bar of a run (`ChartContext.now`). */
|
|
1829
|
-
export const timenow = new Series(ctxBars, () =>
|
|
2358
|
+
export const timenow = new Series(ctxBars, () => {
|
|
2359
|
+
incremental.nonIncremental('timenow');
|
|
2360
|
+
return runNow;
|
|
2361
|
+
});
|
|
1830
2362
|
export const time = callableSeries(new Series(ctxBars, (b) => barTime(b)), timeFunction);
|
|
1831
2363
|
/**
|
|
1832
2364
|
* PineScript `time_close`: the bar close time in ms (a Series), and `time_close(timeframe?, session?, timezone?)`.
|
|
@@ -1914,6 +2446,8 @@ export const barstate = {
|
|
|
1914
2446
|
get isnew() { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },
|
|
1915
2447
|
get islastconfirmedhistory() {
|
|
1916
2448
|
return namedFlag('islastconfirmedhistory', (i, n) => {
|
|
2449
|
+
// moves to the next bar with each new bar: not kept by an incremental run (#196)
|
|
2450
|
+
incremental.nonIncremental('barstate.islastconfirmedhistory');
|
|
1917
2451
|
const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;
|
|
1918
2452
|
const count = chartBarCount(n);
|
|
1919
2453
|
return i === (lastConfirmed ? count - 1 : count - 2);
|
|
@@ -1978,6 +2512,8 @@ function valuesOf(value, length) {
|
|
|
1978
2512
|
*/
|
|
1979
2513
|
function security(symbol, timeframe, expression, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = false) {
|
|
1980
2514
|
collector();
|
|
2515
|
+
// other bars merged on the chart bars: not resumed by an incremental run (#196)
|
|
2516
|
+
incremental.nonIncremental('request.security');
|
|
1981
2517
|
const heikin = symbol.startsWith(HEIKIN_ASHI);
|
|
1982
2518
|
const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;
|
|
1983
2519
|
const chart = chartTimeframe();
|
|
@@ -2125,6 +2661,7 @@ function externalSecurity(symbol, heikin, tf, expression, gaps, lookahead, ignor
|
|
|
2125
2661
|
*/
|
|
2126
2662
|
function security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol = false) {
|
|
2127
2663
|
collector();
|
|
2664
|
+
incremental.nonIncremental('request.security_lower_tf');
|
|
2128
2665
|
const heikin = symbol.startsWith(HEIKIN_ASHI);
|
|
2129
2666
|
const base = heikin ? symbol.slice(HEIKIN_ASHI.length) : symbol;
|
|
2130
2667
|
const chart = chartTimeframe();
|
|
@@ -2281,7 +2818,7 @@ export const alert = Object.assign(alertImpl, {
|
|
|
2281
2818
|
freq_once_per_bar_close: 'once_per_bar_close',
|
|
2282
2819
|
});
|
|
2283
2820
|
// ── Convenience re-exports ───────────────────────────────────────────────────
|
|
2284
|
-
export { Series, BarData
|
|
2821
|
+
export { Series, BarData };
|
|
2285
2822
|
export { STRATEGY_DEFAULTS } from '../strategy/index.js';
|
|
2286
2823
|
/** PineScript `math.*`; `math.round_to_mintick(x)` uses `syminfo.mintick` of the chart context. */
|
|
2287
2824
|
const { saveRandom: _saveRandom, restoreRandom: _restoreRandom, ...mathScript } = mathCore;
|