oakscriptjs 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/script/globals.d.ts +3 -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 +4 -0
- package/dist/cjs/script/incremental.d.ts.map +1 -1
- package/dist/cjs/script/incremental.js +32 -1
- package/dist/cjs/script/incremental.js.map +3 -3
- package/dist/cjs/script/index.d.ts +75 -10
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +218 -52
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/script/globals.d.ts +3 -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 +4 -0
- package/dist/esm/script/incremental.d.ts.map +1 -1
- package/dist/esm/script/incremental.js +40 -1
- package/dist/esm/script/incremental.js.map +1 -1
- package/dist/esm/script/index.d.ts +75 -10
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +281 -54
- package/dist/esm/script/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/oakscript/reference/plotting.md +16 -0
- package/src/index.ts +1 -1
- package/src/script/globals.ts +3 -0
- package/src/script/incremental.ts +35 -1
- package/src/script/index.ts +339 -60
package/dist/esm/script/index.js
CHANGED
|
@@ -126,6 +126,7 @@ function freshCollector(inputValues) {
|
|
|
126
126
|
alertConfig: [],
|
|
127
127
|
alerts: [],
|
|
128
128
|
alertCalls: [],
|
|
129
|
+
logs: [],
|
|
129
130
|
hasAlertFunction: false,
|
|
130
131
|
};
|
|
131
132
|
}
|
|
@@ -157,6 +158,13 @@ export class StrategyRecorder {
|
|
|
157
158
|
varipStarts = [];
|
|
158
159
|
/** Current `varip` values: kept through the intrabar runs (no rollback). */
|
|
159
160
|
varip = [];
|
|
161
|
+
/**
|
|
162
|
+
* Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,
|
|
163
|
+
* or a verification difference); null while they are resumed (see {@link executeIntrabar}).
|
|
164
|
+
*/
|
|
165
|
+
get intrabarFullRunReason() {
|
|
166
|
+
return intrabarChains.get(this)?.reason ?? null;
|
|
167
|
+
}
|
|
160
168
|
}
|
|
161
169
|
function saveRunState() {
|
|
162
170
|
return {
|
|
@@ -202,6 +210,9 @@ export function executeScript(body, barsInput, inputs = {}, chart = {}, options
|
|
|
202
210
|
function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
203
211
|
// A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.
|
|
204
212
|
const outer = ctx ? saveRunState() : null;
|
|
213
|
+
// A main run with a recorder starts a new backtest: its intrabar runs start again (#206).
|
|
214
|
+
if (options.recorder)
|
|
215
|
+
intrabarChains.delete(options.recorder);
|
|
205
216
|
// A plain run inside an incremental one is not part of it.
|
|
206
217
|
const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();
|
|
207
218
|
ctxBars.setAll(barsInput);
|
|
@@ -259,6 +270,8 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
259
270
|
...(intrabarRun ? {} : drawingOutputs(ctxBars.bars, chartCtx.timeUnit)),
|
|
260
271
|
alerts: c.alerts.length ? c.alerts : undefined,
|
|
261
272
|
alertCalls: c.alertCalls.length ? c.alertCalls : undefined,
|
|
273
|
+
// By bar, in call order on each bar (the top-level calls make theirs on every bar at once).
|
|
274
|
+
logs: c.logs.length ? [...c.logs].sort((x, y) => x.bar - y.bar).slice(-MAX_LOG_ENTRIES) : undefined,
|
|
262
275
|
},
|
|
263
276
|
hasAlertFunction: c.hasAlertFunction,
|
|
264
277
|
};
|
|
@@ -270,31 +283,180 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
|
|
|
270
283
|
incremental.endRun(outerInc);
|
|
271
284
|
}
|
|
272
285
|
}
|
|
286
|
+
const intrabarChains = new WeakMap();
|
|
287
|
+
/**
|
|
288
|
+
* The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when
|
|
289
|
+
* `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run
|
|
290
|
+
* stopped in the middle makes none).
|
|
291
|
+
*/
|
|
292
|
+
function intrabarEngine(engine, log, writes) {
|
|
293
|
+
const read = (name, args, value) => {
|
|
294
|
+
log?.push([name, ...args, value]);
|
|
295
|
+
return value;
|
|
296
|
+
};
|
|
297
|
+
const write = (name, args, call) => {
|
|
298
|
+
log?.push([name, ...args]);
|
|
299
|
+
if (writes)
|
|
300
|
+
writes.push(call);
|
|
301
|
+
else
|
|
302
|
+
call();
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
...forward(engine),
|
|
306
|
+
entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),
|
|
307
|
+
order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),
|
|
308
|
+
exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),
|
|
309
|
+
close: (id, options) => write('close', [id, options], () => engine.close(id, options)),
|
|
310
|
+
close_all: (options) => write('close_all', [options], () => engine.close_all(options)),
|
|
311
|
+
cancel: (id) => write('cancel', [id], () => engine.cancel(id)),
|
|
312
|
+
cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),
|
|
313
|
+
get: (name) => read('get', [name], engine.get(name)),
|
|
314
|
+
openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),
|
|
315
|
+
closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),
|
|
316
|
+
defaultEntryQty: engine.defaultEntryQty
|
|
317
|
+
? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty(price))
|
|
318
|
+
: undefined,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/** Puts the `varip` values back to a copy taken before a run. */
|
|
322
|
+
function setVarip(recorder, values) {
|
|
323
|
+
recorder.varip.length = 0;
|
|
324
|
+
recorder.varip.push(...values);
|
|
325
|
+
}
|
|
273
326
|
/**
|
|
274
327
|
* Runs a strategy once more on a bar, inside the bar (PineScript `calc_on_order_fills` and calculations on the
|
|
275
328
|
* ticks of history bars): `bars` holds the bars up to that bar, the last one as it stands at the tick (its close is
|
|
276
|
-
* the tick price, its high and low the extremes reached so far). The script's
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
*
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
329
|
+
* the tick price, its high and low the extremes reached so far). The script's variables come back to their state at
|
|
330
|
+
* the start of the bar (PineScript rollback), except `varip` ones. In strategy.eachBar(), the bars before replay the
|
|
331
|
+
* engine's answers that the main run recorded (their order calls are dropped), and the bar itself calls
|
|
332
|
+
* `options.engine` without processBar / processClose (the host is filling its orders). That bar is a confirmed
|
|
333
|
+
* history bar (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last
|
|
334
|
+
* bar. Strategy risk rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host
|
|
335
|
+
* calls it inside the bar loop of the main run.
|
|
336
|
+
*
|
|
337
|
+
* Resumed runs (#206): the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state
|
|
338
|
+
* of the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar
|
|
339
|
+
* run), not all the bars before it; the order calls and `strategy.*` reads are the same as in a full run. The bars
|
|
340
|
+
* before `options.bar` must be the main run's (the same on every call). A script that keeps state outside `persist()`
|
|
341
|
+
* boxes (a `let` variable outside the callbacks that a callback changes), or uses a feature that is not resumed, gets
|
|
342
|
+
* full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared (`verify`). A resumed
|
|
343
|
+
* run gives its order calls to the engine once it has ended.
|
|
283
344
|
*/
|
|
284
345
|
export function executeIntrabar(body, bars, inputs, chart, options) {
|
|
285
|
-
const
|
|
286
|
-
bar: options.bar,
|
|
287
|
-
lastBarIndex: options.lastBarIndex,
|
|
288
|
-
engine: options.engine,
|
|
289
|
-
recorder: options.recorder,
|
|
290
|
-
};
|
|
291
|
-
executeScript(() => {
|
|
292
|
-
intrabarRun = run;
|
|
293
|
-
varipRun = { slot: 0, recorder: options.recorder, mode: 'live', scratch: null };
|
|
294
|
-
body();
|
|
295
|
-
}, bars, inputs,
|
|
346
|
+
const recorder = options.recorder;
|
|
296
347
|
// History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
|
|
297
|
-
{ ...chart, lastBarConfirmed: true, realtime: false }
|
|
348
|
+
const runChart = { ...chart, lastBarConfirmed: true, realtime: false };
|
|
349
|
+
const execute = (engine, inc) => {
|
|
350
|
+
const run = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };
|
|
351
|
+
runBody(() => {
|
|
352
|
+
intrabarRun = run;
|
|
353
|
+
varipRun = { slot: 0, recorder, mode: 'live', scratch: null };
|
|
354
|
+
body();
|
|
355
|
+
}, bars, inputs, runChart, { strategyEngine: () => engine }, inc);
|
|
356
|
+
};
|
|
357
|
+
const fullRun = (reason) => {
|
|
358
|
+
execute(options.engine, null);
|
|
359
|
+
return { from: 0, incremental: false, fullRunReason: reason };
|
|
360
|
+
};
|
|
361
|
+
if (options.resume === false)
|
|
362
|
+
return fullRun('resume: false');
|
|
363
|
+
const n = bars.length;
|
|
364
|
+
if (options.bar !== n - 1)
|
|
365
|
+
return fullRun('the bar is not the last of the bars');
|
|
366
|
+
let chain = intrabarChains.get(recorder);
|
|
367
|
+
if (!chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||
|
|
368
|
+
!sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)) {
|
|
369
|
+
chain = {
|
|
370
|
+
body,
|
|
371
|
+
inputs,
|
|
372
|
+
chart: runChart,
|
|
373
|
+
engine: options.engine,
|
|
374
|
+
lastBarIndex: options.lastBarIndex,
|
|
375
|
+
memory: null,
|
|
376
|
+
n: 0,
|
|
377
|
+
reason: null,
|
|
378
|
+
verifyLeft: options.verify ?? 2,
|
|
379
|
+
};
|
|
380
|
+
intrabarChains.set(recorder, chain);
|
|
381
|
+
}
|
|
382
|
+
if (chain.reason)
|
|
383
|
+
return fullRun(chain.reason);
|
|
384
|
+
const memory = chain.memory;
|
|
385
|
+
// A resumed run changes the memory in place: it is usable again only when the run has ended.
|
|
386
|
+
chain.memory = null;
|
|
387
|
+
if (!memory || n < chain.n) {
|
|
388
|
+
const inc = newActiveRun('record', bars, 0, null);
|
|
389
|
+
execute(options.engine, inc);
|
|
390
|
+
if (inc.blocked)
|
|
391
|
+
chain.reason = inc.blocked;
|
|
392
|
+
else {
|
|
393
|
+
chain.memory = inc.next;
|
|
394
|
+
chain.n = n;
|
|
395
|
+
}
|
|
396
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
397
|
+
}
|
|
398
|
+
const from = chain.n - 1;
|
|
399
|
+
const start = incremental.plainCopy(recorder.varip);
|
|
400
|
+
if (start === incremental.NOT_COPIED) {
|
|
401
|
+
chain.reason = 'a varip value that is not plain data';
|
|
402
|
+
return fullRun(chain.reason);
|
|
403
|
+
}
|
|
404
|
+
const verifying = chain.verifyLeft > 0;
|
|
405
|
+
const log = verifying ? [] : null;
|
|
406
|
+
const writes = [];
|
|
407
|
+
const inc = newActiveRun('resume', bars, from, memory);
|
|
408
|
+
try {
|
|
409
|
+
execute(intrabarEngine(options.engine, log, writes), inc);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
// The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An
|
|
413
|
+
// error of the script is the full run's (it throws it again).
|
|
414
|
+
setVarip(recorder, start);
|
|
415
|
+
if (err instanceof incremental.ResumeAborted)
|
|
416
|
+
chain.reason = err.reason;
|
|
417
|
+
return fullRun(chain.reason);
|
|
418
|
+
}
|
|
419
|
+
if (verifying) {
|
|
420
|
+
chain.verifyLeft--;
|
|
421
|
+
const resumedVarip = incremental.plainCopy(recorder.varip);
|
|
422
|
+
setVarip(recorder, start);
|
|
423
|
+
const fullLog = [];
|
|
424
|
+
execute(intrabarEngine(options.engine, fullLog, null), null);
|
|
425
|
+
if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {
|
|
426
|
+
chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';
|
|
427
|
+
return { from: 0, incremental: false, fullRunReason: chain.reason };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
for (const call of writes)
|
|
432
|
+
call();
|
|
433
|
+
}
|
|
434
|
+
chain.memory = inc.next;
|
|
435
|
+
chain.n = n;
|
|
436
|
+
return { from, incremental: true, fullRunReason: null };
|
|
437
|
+
}
|
|
438
|
+
/** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */
|
|
439
|
+
function newActiveRun(mode, b, from, prev) {
|
|
440
|
+
const next = incremental.emptyMemory(b.length);
|
|
441
|
+
// the block that draws stays the one of the previous run (the forming bar may not draw)
|
|
442
|
+
if (mode === 'resume' && prev)
|
|
443
|
+
next.drawingBlock = prev.drawingBlock;
|
|
444
|
+
return {
|
|
445
|
+
mode,
|
|
446
|
+
from,
|
|
447
|
+
bars: b,
|
|
448
|
+
prev: mode === 'resume' ? prev : null,
|
|
449
|
+
next,
|
|
450
|
+
seriesSlot: 0,
|
|
451
|
+
taSlot: 0,
|
|
452
|
+
blockSlot: 0,
|
|
453
|
+
plotSlot: 0,
|
|
454
|
+
boxSlot: 0,
|
|
455
|
+
drawSlot: 0,
|
|
456
|
+
block: -1,
|
|
457
|
+
boxes: [],
|
|
458
|
+
blocked: null,
|
|
459
|
+
};
|
|
298
460
|
}
|
|
299
461
|
/** Chart context fields that only change the last bar (barstate of the forming bar). */
|
|
300
462
|
const LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);
|
|
@@ -381,28 +543,9 @@ export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
|
381
543
|
let previousChart = chart;
|
|
382
544
|
let reason = null;
|
|
383
545
|
let verifyLeft = options.verify ?? 2;
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
-
};
|
|
546
|
+
/** The log messages of the last update: a resumed update keeps those of the bars it does not calculate again. */
|
|
547
|
+
let lastLogs;
|
|
548
|
+
const newRun = (mode, b, from) => newActiveRun(mode, b, from, memory);
|
|
406
549
|
const full = (b, c) => {
|
|
407
550
|
memory = null;
|
|
408
551
|
if (reason)
|
|
@@ -435,6 +578,7 @@ export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
|
435
578
|
let result = null;
|
|
436
579
|
try {
|
|
437
580
|
result = runBody(body, b, inputs, c, options, inc);
|
|
581
|
+
result.result.logs = resumedLogs(lastLogs, result.result.logs, from);
|
|
438
582
|
}
|
|
439
583
|
catch (err) {
|
|
440
584
|
// the memory is changed in place by a resumed run: an error leaves it unusable
|
|
@@ -462,6 +606,7 @@ export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
|
|
|
462
606
|
}
|
|
463
607
|
}
|
|
464
608
|
previous = out.incremental && last ? copyBars(b, last, last.n - 1) : copyBars(b);
|
|
609
|
+
lastLogs = out.result.logs;
|
|
465
610
|
return out;
|
|
466
611
|
},
|
|
467
612
|
};
|
|
@@ -475,7 +620,9 @@ let varipRun = { slot: 0, recorder: null, mode: 'live', scratch: null };
|
|
|
475
620
|
*/
|
|
476
621
|
export function varip(initial) {
|
|
477
622
|
collector();
|
|
478
|
-
|
|
623
|
+
// the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)
|
|
624
|
+
if (!intrabarRun)
|
|
625
|
+
incremental.nonIncremental('varip');
|
|
479
626
|
const slot = varipRun.slot++;
|
|
480
627
|
const state = varipRun;
|
|
481
628
|
const rec = state.recorder;
|
|
@@ -492,7 +639,12 @@ export function varip(initial) {
|
|
|
492
639
|
}
|
|
493
640
|
if (rec.varip.length <= slot)
|
|
494
641
|
rec.varip[slot] = initial;
|
|
495
|
-
const store = () =>
|
|
642
|
+
const store = () => {
|
|
643
|
+
// elsewhere, a resumed run would keep values of the bars before calculated with older varip values
|
|
644
|
+
if (incremental.active && !ctx?.strategy?.inLoop)
|
|
645
|
+
incremental.nonIncremental('varip used outside strategy.eachBar()');
|
|
646
|
+
return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;
|
|
647
|
+
};
|
|
496
648
|
return {
|
|
497
649
|
get value() {
|
|
498
650
|
return store()[slot];
|
|
@@ -761,9 +913,11 @@ export const bar_index = new Series(ctxBars, (_b, i) => i);
|
|
|
761
913
|
bar_index.fullHistory = true;
|
|
762
914
|
/** PineScript `last_bar_index`: the index of the last bar, on every bar. In a bar loop, `c.n - 1`. */
|
|
763
915
|
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
|
-
|
|
766
|
-
|
|
916
|
+
// the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
|
|
917
|
+
// intrabar runs of a backtest (the chart's last bar, #206)
|
|
918
|
+
if (!intrabarRun)
|
|
919
|
+
incremental.nonIncremental('last_bar_index');
|
|
920
|
+
return chartBarCount(data.length) - 1;
|
|
767
921
|
});
|
|
768
922
|
last_bar_index.fullHistory = true;
|
|
769
923
|
// built-in price variables keep the whole history (no 5000-bar limit)
|
|
@@ -1652,7 +1806,7 @@ own = fn) {
|
|
|
1652
1806
|
const b = bars();
|
|
1653
1807
|
// An intrabar run ends on its bar: the chart's last bar stays the main run's.
|
|
1654
1808
|
const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;
|
|
1655
|
-
let out =
|
|
1809
|
+
let out = [];
|
|
1656
1810
|
const cache = new Map();
|
|
1657
1811
|
// history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series
|
|
1658
1812
|
const buffers = new Map();
|
|
@@ -1673,7 +1827,9 @@ own = fn) {
|
|
|
1673
1827
|
}
|
|
1674
1828
|
let start = 0;
|
|
1675
1829
|
let checkpoint = null;
|
|
1676
|
-
if (run?.mode
|
|
1830
|
+
if (run?.mode !== 'resume')
|
|
1831
|
+
out = new Array(b.length).fill(NaN);
|
|
1832
|
+
else {
|
|
1677
1833
|
const prev = run.prev?.blocks[slot];
|
|
1678
1834
|
if (!prev)
|
|
1679
1835
|
incremental.nonIncremental('a new eachBar() block');
|
|
@@ -1725,8 +1881,9 @@ own = fn) {
|
|
|
1725
1881
|
return idx;
|
|
1726
1882
|
},
|
|
1727
1883
|
get n() {
|
|
1728
|
-
// the bar count changes with each new bar: a value read from it is not kept by an incremental run
|
|
1729
|
-
|
|
1884
|
+
// the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's
|
|
1885
|
+
// last bar of the intrabar runs of a backtest does not change)
|
|
1886
|
+
if (run && !intrabarRun)
|
|
1730
1887
|
incremental.nonIncremental('BarContext.n');
|
|
1731
1888
|
return lastIndex + 1;
|
|
1732
1889
|
},
|
|
@@ -1920,7 +2077,7 @@ function strategyEachBar(fn) {
|
|
|
1920
2077
|
const varipState = varipRun;
|
|
1921
2078
|
const replayLog = { answers: [], next: 0 };
|
|
1922
2079
|
const replayed = replayEngine(replayLog);
|
|
1923
|
-
return
|
|
2080
|
+
return runBlock((c) => {
|
|
1924
2081
|
const replay = c.i < intrabar.bar;
|
|
1925
2082
|
if (replay) {
|
|
1926
2083
|
replayLog.answers = intrabar.recorder.answers[c.i] ?? [];
|
|
@@ -1940,7 +2097,7 @@ function strategyEachBar(fn) {
|
|
|
1940
2097
|
varipState.mode = 'live';
|
|
1941
2098
|
varipState.scratch = null;
|
|
1942
2099
|
}
|
|
1943
|
-
});
|
|
2100
|
+
}, undefined, fn);
|
|
1944
2101
|
}
|
|
1945
2102
|
const recorder = scriptOptions.recorder;
|
|
1946
2103
|
// an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it
|
|
@@ -2446,8 +2603,10 @@ export const barstate = {
|
|
|
2446
2603
|
get isnew() { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },
|
|
2447
2604
|
get islastconfirmedhistory() {
|
|
2448
2605
|
return namedFlag('islastconfirmedhistory', (i, n) => {
|
|
2449
|
-
// moves to the next bar with each new bar: not kept by an incremental run (#196)
|
|
2450
|
-
|
|
2606
|
+
// moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar
|
|
2607
|
+
// runs of a backtest (#206)
|
|
2608
|
+
if (!intrabarRun)
|
|
2609
|
+
incremental.nonIncremental('barstate.islastconfirmedhistory');
|
|
2451
2610
|
const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;
|
|
2452
2611
|
const count = chartBarCount(n);
|
|
2453
2612
|
return i === (lastConfirmed ? count - 1 : count - 2);
|
|
@@ -2833,6 +2992,69 @@ export const alert = Object.assign(alertImpl, {
|
|
|
2833
2992
|
freq_once_per_bar: 'once_per_bar',
|
|
2834
2993
|
freq_once_per_bar_close: 'once_per_bar_close',
|
|
2835
2994
|
});
|
|
2995
|
+
/** The most messages a run keeps: the newest ones. */
|
|
2996
|
+
export const MAX_LOG_ENTRIES = 10_000;
|
|
2997
|
+
let logLineResolver = null;
|
|
2998
|
+
/**
|
|
2999
|
+
* How the host finds the line of the script that called log.*(): `resolver` gets the stack of the call (an Error's
|
|
3000
|
+
* `stack`) and gives the line in the script's own source. Null (the default): messages have no line.
|
|
3001
|
+
*/
|
|
3002
|
+
export function setLogLineResolver(resolver) {
|
|
3003
|
+
logLineResolver = resolver;
|
|
3004
|
+
}
|
|
3005
|
+
function logImpl(level, message, args) {
|
|
3006
|
+
const c = collector();
|
|
3007
|
+
const b = ctxBars.bars;
|
|
3008
|
+
const line = logLineResolver ? logLineResolver(new Error().stack ?? '') : undefined;
|
|
3009
|
+
const add = (i) => {
|
|
3010
|
+
const text = typeof message === 'string' ? message : message[i];
|
|
3011
|
+
if (text === undefined || text === null)
|
|
3012
|
+
return;
|
|
3013
|
+
// A Series argument gives its value on the bar.
|
|
3014
|
+
const values = args.map((a) => (a instanceof Series ? a.get(i) : a));
|
|
3015
|
+
const entry = {
|
|
3016
|
+
bar: i,
|
|
3017
|
+
time: b[i].time,
|
|
3018
|
+
level,
|
|
3019
|
+
message: args.length ? formatMessage(String(text), values, exchangeTimezone) : String(text),
|
|
3020
|
+
};
|
|
3021
|
+
if (line !== undefined)
|
|
3022
|
+
entry.line = line;
|
|
3023
|
+
c.logs.push(entry);
|
|
3024
|
+
};
|
|
3025
|
+
if (currentBar >= 0)
|
|
3026
|
+
add(currentBar);
|
|
3027
|
+
else
|
|
3028
|
+
for (let i = 0; i < b.length; i++)
|
|
3029
|
+
add(i);
|
|
3030
|
+
if (c.logs.length > MAX_LOG_ENTRIES * 2)
|
|
3031
|
+
c.logs.splice(0, c.logs.length - MAX_LOG_ENTRIES);
|
|
3032
|
+
}
|
|
3033
|
+
/**
|
|
3034
|
+
* PineScript `log.info()`, `log.warning()` and `log.error()`: a message for the host's logs panel, made on the current
|
|
3035
|
+
* bar inside eachBar() / strategy.eachBar(), on every bar at the top level of the script (which PineScript runs on
|
|
3036
|
+
* every bar; `message` is then a text or one text per bar, a bar whose text is na makes no message). With arguments,
|
|
3037
|
+
* `message` is a str.format() pattern (`log.info('close {0}', close)`), a Series argument giving its value on the bar.
|
|
3038
|
+
* The messages of a run are in `result.logs`, by bar ({@link MAX_LOG_ENTRIES} newest kept).
|
|
3039
|
+
*/
|
|
3040
|
+
export const log = strictNamespace('log', {
|
|
3041
|
+
info(message, ...args) {
|
|
3042
|
+
logImpl('info', message, args);
|
|
3043
|
+
},
|
|
3044
|
+
warning(message, ...args) {
|
|
3045
|
+
logImpl('warning', message, args);
|
|
3046
|
+
},
|
|
3047
|
+
error(message, ...args) {
|
|
3048
|
+
logImpl('error', message, args);
|
|
3049
|
+
},
|
|
3050
|
+
});
|
|
3051
|
+
/** The messages of a resumed run calculated from bar `from`: those of the run before on the bars before `from`, then the
|
|
3052
|
+
* new ones on the bars from `from` (the top-level log calls of a resumed run make them again on every bar). */
|
|
3053
|
+
function resumedLogs(before, now, from) {
|
|
3054
|
+
const kept = (before ?? []).filter((e) => e.bar < from);
|
|
3055
|
+
const logs = kept.concat((now ?? []).filter((e) => e.bar >= from));
|
|
3056
|
+
return logs.length ? logs.slice(-MAX_LOG_ENTRIES) : undefined;
|
|
3057
|
+
}
|
|
2836
3058
|
// ── Convenience re-exports ───────────────────────────────────────────────────
|
|
2837
3059
|
export { Series, BarData };
|
|
2838
3060
|
export { STRATEGY_DEFAULTS } from '../strategy/index.js';
|
|
@@ -2842,6 +3064,11 @@ void _saveRandom;
|
|
|
2842
3064
|
void _restoreRandom;
|
|
2843
3065
|
export const math = strictNamespace('math', {
|
|
2844
3066
|
...mathScript,
|
|
3067
|
+
// the generators start again on each run: a resumed run would draw other numbers (#206)
|
|
3068
|
+
random: ((min, max, seed) => {
|
|
3069
|
+
incremental.nonIncremental('math.random');
|
|
3070
|
+
return mathCore.random(min, max, seed);
|
|
3071
|
+
}),
|
|
2845
3072
|
round_to_mintick: ((number, mintick) => {
|
|
2846
3073
|
const tick = mintick ?? syminfo.mintick;
|
|
2847
3074
|
return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);
|