oakscriptjs 0.16.0 → 0.17.1

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.
@@ -157,6 +157,13 @@ export class StrategyRecorder {
157
157
  varipStarts = [];
158
158
  /** Current `varip` values: kept through the intrabar runs (no rollback). */
159
159
  varip = [];
160
+ /**
161
+ * Why the intrabar runs of this recorder calculate all the bars before their bar (a feature that is not resumed,
162
+ * or a verification difference); null while they are resumed (see {@link executeIntrabar}).
163
+ */
164
+ get intrabarFullRunReason() {
165
+ return intrabarChains.get(this)?.reason ?? null;
166
+ }
160
167
  }
161
168
  function saveRunState() {
162
169
  return {
@@ -202,6 +209,9 @@ export function executeScript(body, barsInput, inputs = {}, chart = {}, options
202
209
  function runBody(body, barsInput, inputs, chart, options, inc) {
203
210
  // A run inside another one (an intrabar run of a strategy) puts the outer run back when it ends.
204
211
  const outer = ctx ? saveRunState() : null;
212
+ // A main run with a recorder starts a new backtest: its intrabar runs start again (#206).
213
+ if (options.recorder)
214
+ intrabarChains.delete(options.recorder);
205
215
  // A plain run inside an incremental one is not part of it.
206
216
  const outerInc = inc ? incremental.beginRun(inc) : incremental.suspendRun();
207
217
  ctxBars.setAll(barsInput);
@@ -270,31 +280,180 @@ function runBody(body, barsInput, inputs, chart, options, inc) {
270
280
  incremental.endRun(outerInc);
271
281
  }
272
282
  }
283
+ const intrabarChains = new WeakMap();
284
+ /**
285
+ * The live engine of an intrabar run with its calls logged (`log`, to compare two runs) and its order calls, when
286
+ * `writes` is given, kept there instead of made (a resumed run gives them to the engine once it has ended: a run
287
+ * stopped in the middle makes none).
288
+ */
289
+ function intrabarEngine(engine, log, writes) {
290
+ const read = (name, args, value) => {
291
+ log?.push([name, ...args, value]);
292
+ return value;
293
+ };
294
+ const write = (name, args, call) => {
295
+ log?.push([name, ...args]);
296
+ if (writes)
297
+ writes.push(call);
298
+ else
299
+ call();
300
+ };
301
+ return {
302
+ ...forward(engine),
303
+ entry: (id, direction, options) => write('entry', [id, direction, options], () => engine.entry(id, direction, options)),
304
+ order: (id, direction, options) => write('order', [id, direction, options], () => engine.order(id, direction, options)),
305
+ exit: (id, options) => write('exit', [id, options], () => engine.exit(id, options)),
306
+ close: (id, options) => write('close', [id, options], () => engine.close(id, options)),
307
+ close_all: (options) => write('close_all', [options], () => engine.close_all(options)),
308
+ cancel: (id) => write('cancel', [id], () => engine.cancel(id)),
309
+ cancel_all: () => write('cancel_all', [], () => engine.cancel_all()),
310
+ get: (name) => read('get', [name], engine.get(name)),
311
+ openTrade: (index) => read('openTrade', [index], engine.openTrade(index)),
312
+ closedTrade: (index) => read('closedTrade', [index], engine.closedTrade(index)),
313
+ defaultEntryQty: engine.defaultEntryQty
314
+ ? (price) => read('defaultEntryQty', [price], engine.defaultEntryQty(price))
315
+ : undefined,
316
+ };
317
+ }
318
+ /** Puts the `varip` values back to a copy taken before a run. */
319
+ function setVarip(recorder, values) {
320
+ recorder.varip.length = 0;
321
+ recorder.varip.push(...values);
322
+ }
273
323
  /**
274
324
  * Runs a strategy once more on a bar, inside the bar (PineScript `calc_on_order_fills` and calculations on the
275
325
  * 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 values are calculated again on these
277
- * bars, so its variables come back to their state at the start of the bar (PineScript rollback), except `varip`
278
- * ones. In strategy.eachBar(), the bars before replay the engine's answers that the main run recorded (their
279
- * order calls are dropped), and the bar itself calls `options.engine` without processBar / processClose (the host
280
- * is filling its orders). That bar is a confirmed history bar (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and
281
- * `BarContext.n` keep the chart's last bar. Strategy risk rules are not declared again, and the outputs (plots,
282
- * drawings) are dropped. Re-entrant: the host calls it inside the bar loop of the main run.
326
+ * the tick price, its high and low the extremes reached so far). The script's variables come back to their state at
327
+ * the start of the bar (PineScript rollback), except `varip` ones. In strategy.eachBar(), the bars before replay the
328
+ * engine's answers that the main run recorded (their order calls are dropped), and the bar itself calls
329
+ * `options.engine` without processBar / processClose (the host is filling its orders). That bar is a confirmed
330
+ * history bar (`barstate.isconfirmed`); `barstate.islast`, `last_bar_index` and `BarContext.n` keep the chart's last
331
+ * bar. Strategy risk rules are not declared again, and the outputs (plots, drawings) are dropped. Re-entrant: the host
332
+ * calls it inside the bar loop of the main run.
333
+ *
334
+ * Resumed runs (#206): the intrabar runs of a backtest (same recorder, script, inputs, chart and engine) keep the state
335
+ * of the script as createScriptRun does, so a run calculates its bar only (and the bars since the previous intrabar
336
+ * run), not all the bars before it; the order calls and `strategy.*` reads are the same as in a full run. The bars
337
+ * before `options.bar` must be the main run's (the same on every call). A script that keeps state outside `persist()`
338
+ * boxes (a `let` variable outside the callbacks that a callback changes), or uses a feature that is not resumed, gets
339
+ * full runs (`fullRunReason`); the first resumed runs are also calculated in full and compared (`verify`). A resumed
340
+ * run gives its order calls to the engine once it has ended.
283
341
  */
284
342
  export function executeIntrabar(body, bars, inputs, chart, options) {
285
- const run = {
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,
343
+ const recorder = options.recorder;
296
344
  // History bars are confirmed, also on their ticks (the reference app: a barstate.isconfirmed entry fills on them).
297
- { ...chart, lastBarConfirmed: true, realtime: false }, { strategyEngine: () => options.engine });
345
+ const runChart = { ...chart, lastBarConfirmed: true, realtime: false };
346
+ const execute = (engine, inc) => {
347
+ const run = { bar: options.bar, lastBarIndex: options.lastBarIndex, engine, recorder };
348
+ runBody(() => {
349
+ intrabarRun = run;
350
+ varipRun = { slot: 0, recorder, mode: 'live', scratch: null };
351
+ body();
352
+ }, bars, inputs, runChart, { strategyEngine: () => engine }, inc);
353
+ };
354
+ const fullRun = (reason) => {
355
+ execute(options.engine, null);
356
+ return { from: 0, incremental: false, fullRunReason: reason };
357
+ };
358
+ if (options.resume === false)
359
+ return fullRun('resume: false');
360
+ const n = bars.length;
361
+ if (options.bar !== n - 1)
362
+ return fullRun('the bar is not the last of the bars');
363
+ let chain = intrabarChains.get(recorder);
364
+ if (!chain || chain.body !== body || chain.engine !== options.engine || chain.lastBarIndex !== options.lastBarIndex ||
365
+ !sameResult(chain.inputs, inputs) || !sameChart(chain.chart, runChart)) {
366
+ chain = {
367
+ body,
368
+ inputs,
369
+ chart: runChart,
370
+ engine: options.engine,
371
+ lastBarIndex: options.lastBarIndex,
372
+ memory: null,
373
+ n: 0,
374
+ reason: null,
375
+ verifyLeft: options.verify ?? 2,
376
+ };
377
+ intrabarChains.set(recorder, chain);
378
+ }
379
+ if (chain.reason)
380
+ return fullRun(chain.reason);
381
+ const memory = chain.memory;
382
+ // A resumed run changes the memory in place: it is usable again only when the run has ended.
383
+ chain.memory = null;
384
+ if (!memory || n < chain.n) {
385
+ const inc = newActiveRun('record', bars, 0, null);
386
+ execute(options.engine, inc);
387
+ if (inc.blocked)
388
+ chain.reason = inc.blocked;
389
+ else {
390
+ chain.memory = inc.next;
391
+ chain.n = n;
392
+ }
393
+ return { from: 0, incremental: false, fullRunReason: chain.reason };
394
+ }
395
+ const from = chain.n - 1;
396
+ const start = incremental.plainCopy(recorder.varip);
397
+ if (start === incremental.NOT_COPIED) {
398
+ chain.reason = 'a varip value that is not plain data';
399
+ return fullRun(chain.reason);
400
+ }
401
+ const verifying = chain.verifyLeft > 0;
402
+ const log = verifying ? [] : null;
403
+ const writes = [];
404
+ const inc = newActiveRun('resume', bars, from, memory);
405
+ try {
406
+ execute(intrabarEngine(options.engine, log, writes), inc);
407
+ }
408
+ catch (err) {
409
+ // The run is calculated in full instead: the varip values back to the start, the kept order calls dropped. An
410
+ // error of the script is the full run's (it throws it again).
411
+ setVarip(recorder, start);
412
+ if (err instanceof incremental.ResumeAborted)
413
+ chain.reason = err.reason;
414
+ return fullRun(chain.reason);
415
+ }
416
+ if (verifying) {
417
+ chain.verifyLeft--;
418
+ const resumedVarip = incremental.plainCopy(recorder.varip);
419
+ setVarip(recorder, start);
420
+ const fullLog = [];
421
+ execute(intrabarEngine(options.engine, fullLog, null), null);
422
+ if (resumedVarip === incremental.NOT_COPIED || !sameResult(log, fullLog) || !sameResult(resumedVarip, recorder.varip)) {
423
+ chain.reason = 'a resumed intrabar run differs from a full run (state kept outside persist()?)';
424
+ return { from: 0, incremental: false, fullRunReason: chain.reason };
425
+ }
426
+ }
427
+ else {
428
+ for (const call of writes)
429
+ call();
430
+ }
431
+ chain.memory = inc.next;
432
+ chain.n = n;
433
+ return { from, incremental: true, fullRunReason: null };
434
+ }
435
+ /** The state of an incremental run: a recorded one (full), or one resumed at bar `from` from `prev`. */
436
+ function newActiveRun(mode, b, from, prev) {
437
+ const next = incremental.emptyMemory(b.length);
438
+ // the block that draws stays the one of the previous run (the forming bar may not draw)
439
+ if (mode === 'resume' && prev)
440
+ next.drawingBlock = prev.drawingBlock;
441
+ return {
442
+ mode,
443
+ from,
444
+ bars: b,
445
+ prev: mode === 'resume' ? prev : null,
446
+ next,
447
+ seriesSlot: 0,
448
+ taSlot: 0,
449
+ blockSlot: 0,
450
+ plotSlot: 0,
451
+ boxSlot: 0,
452
+ drawSlot: 0,
453
+ block: -1,
454
+ boxes: [],
455
+ blocked: null,
456
+ };
298
457
  }
299
458
  /** Chart context fields that only change the last bar (barstate of the forming bar). */
300
459
  const LAST_BAR_FIELDS = new Set(['lastBarConfirmed', 'lastBarNew', 'realtime', 'now']);
@@ -381,28 +540,7 @@ export function createScriptRun(body, inputs = {}, chart = {}, options = {}) {
381
540
  let previousChart = chart;
382
541
  let reason = null;
383
542
  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
- };
543
+ const newRun = (mode, b, from) => newActiveRun(mode, b, from, memory);
406
544
  const full = (b, c) => {
407
545
  memory = null;
408
546
  if (reason)
@@ -475,7 +613,9 @@ let varipRun = { slot: 0, recorder: null, mode: 'live', scratch: null };
475
613
  */
476
614
  export function varip(initial) {
477
615
  collector();
478
- incremental.nonIncremental('varip');
616
+ // the intrabar runs of a backtest resume with varip values read in strategy.eachBar() (#206)
617
+ if (!intrabarRun)
618
+ incremental.nonIncremental('varip');
479
619
  const slot = varipRun.slot++;
480
620
  const state = varipRun;
481
621
  const rec = state.recorder;
@@ -492,7 +632,12 @@ export function varip(initial) {
492
632
  }
493
633
  if (rec.varip.length <= slot)
494
634
  rec.varip[slot] = initial;
495
- const store = () => (state.mode === 'replay' && state.scratch ? state.scratch : rec.varip);
635
+ const store = () => {
636
+ // elsewhere, a resumed run would keep values of the bars before calculated with older varip values
637
+ if (incremental.active && !ctx?.strategy?.inLoop)
638
+ incremental.nonIncremental('varip used outside strategy.eachBar()');
639
+ return state.mode === 'replay' && state.scratch ? state.scratch : rec.varip;
640
+ };
496
641
  return {
497
642
  get value() {
498
643
  return store()[slot];
@@ -761,9 +906,11 @@ export const bar_index = new Series(ctxBars, (_b, i) => i);
761
906
  bar_index.fullHistory = true;
762
907
  /** PineScript `last_bar_index`: the index of the last bar, on every bar. In a bar loop, `c.n - 1`. */
763
908
  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;
909
+ // the same value on every bar, changed by a new bar: not kept by an incremental run (#196), but the same in the
910
+ // intrabar runs of a backtest (the chart's last bar, #206)
911
+ if (!intrabarRun)
912
+ incremental.nonIncremental('last_bar_index');
913
+ return chartBarCount(data.length) - 1;
767
914
  });
768
915
  last_bar_index.fullHistory = true;
769
916
  // built-in price variables keep the whole history (no 5000-bar limit)
@@ -1652,7 +1799,7 @@ own = fn) {
1652
1799
  const b = bars();
1653
1800
  // An intrabar run ends on its bar: the chart's last bar stays the main run's.
1654
1801
  const lastIndex = intrabarRun ? intrabarRun.lastBarIndex : b.length - 1;
1655
- let out = new Array(b.length).fill(NaN);
1802
+ let out = [];
1656
1803
  const cache = new Map();
1657
1804
  // history buffers by source: the slot of a Series made by the script (matched across incremental runs), or the Series
1658
1805
  const buffers = new Map();
@@ -1673,7 +1820,9 @@ own = fn) {
1673
1820
  }
1674
1821
  let start = 0;
1675
1822
  let checkpoint = null;
1676
- if (run?.mode === 'resume') {
1823
+ if (run?.mode !== 'resume')
1824
+ out = new Array(b.length).fill(NaN);
1825
+ else {
1677
1826
  const prev = run.prev?.blocks[slot];
1678
1827
  if (!prev)
1679
1828
  incremental.nonIncremental('a new eachBar() block');
@@ -1725,8 +1874,9 @@ own = fn) {
1725
1874
  return idx;
1726
1875
  },
1727
1876
  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)
1877
+ // the bar count changes with each new bar: a value read from it is not kept by an incremental run (the chart's
1878
+ // last bar of the intrabar runs of a backtest does not change)
1879
+ if (run && !intrabarRun)
1730
1880
  incremental.nonIncremental('BarContext.n');
1731
1881
  return lastIndex + 1;
1732
1882
  },
@@ -1920,7 +2070,7 @@ function strategyEachBar(fn) {
1920
2070
  const varipState = varipRun;
1921
2071
  const replayLog = { answers: [], next: 0 };
1922
2072
  const replayed = replayEngine(replayLog);
1923
- return eachBar((c) => {
2073
+ return runBlock((c) => {
1924
2074
  const replay = c.i < intrabar.bar;
1925
2075
  if (replay) {
1926
2076
  replayLog.answers = intrabar.recorder.answers[c.i] ?? [];
@@ -1940,7 +2090,7 @@ function strategyEachBar(fn) {
1940
2090
  varipState.mode = 'live';
1941
2091
  varipState.scratch = null;
1942
2092
  }
1943
- });
2093
+ }, undefined, fn);
1944
2094
  }
1945
2095
  const recorder = scriptOptions.recorder;
1946
2096
  // an incremental run keeps the engine state at the last confirmed bar: the engine has to save and restore it
@@ -2446,8 +2596,10 @@ export const barstate = {
2446
2596
  get isnew() { return namedFlag('isnew', (i, n) => !lastRealtime(i, n) || chartCtx.lastBarNew !== false); },
2447
2597
  get islastconfirmedhistory() {
2448
2598
  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');
2599
+ // moves to the next bar with each new bar: not kept by an incremental run (#196), but the same in the intrabar
2600
+ // runs of a backtest (#206)
2601
+ if (!intrabarRun)
2602
+ incremental.nonIncremental('barstate.islastconfirmedhistory');
2451
2603
  const lastConfirmed = chartCtx.lastBarConfirmed === true && chartCtx.realtime !== true;
2452
2604
  const count = chartBarCount(n);
2453
2605
  return i === (lastConfirmed ? count - 1 : count - 2);
@@ -2676,10 +2828,20 @@ function security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol
2676
2828
  const mapped = values.map((v) => ranges.map(([from, to]) => v.slice(from, to)));
2677
2829
  return (Array.isArray(result) ? mapped : mapped[0]);
2678
2830
  }
2679
- /** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181) and `security_lower_tf`. */
2831
+ /**
2832
+ * PineScript `request.seed(source, symbol, expression, ignore_invalid_symbol)` (#205): `expression` on a seed data
2833
+ * series, on the chart timeframe. The series is the symbol `ChartContext.seedSymbol(source, symbol)` (default
2834
+ * `"<SOURCE>:<SYMBOL>"` upper-cased), read as `request.security(<that symbol>, "", expression)`.
2835
+ */
2836
+ function seed(source, symbol, expression, ignore_invalid_symbol = false) {
2837
+ const ticker = chartCtx.seedSymbol?.(source, symbol) ?? `${source.toUpperCase()}:${symbol.toUpperCase()}`;
2838
+ return security(ticker, '', expression, barmerge.gaps_off, barmerge.lookahead_off, ignore_invalid_symbol);
2839
+ }
2840
+ /** PineScript `request.*`: `security` (issue #101, other symbols #179, lower timeframes #181), `security_lower_tf` and `seed` (#205). */
2680
2841
  /** PineScript parameters of `request.security` / `request.security_lower_tf`, in their positional order. */
2681
2842
  const SECURITY_PARAMETERS = ['symbol', 'timeframe', 'expression', 'gaps', 'lookahead', 'ignore_invalid_symbol', 'currency', 'calc_bars_count'];
2682
2843
  const SECURITY_LOWER_TF_PARAMETERS = ['symbol', 'timeframe', 'expression', 'ignore_invalid_symbol', 'currency', 'ignore_invalid_timeframe', 'calc_bars_count'];
2844
+ const SEED_PARAMETERS = ['source', 'symbol', 'expression', 'ignore_invalid_symbol', 'calc_bars_count'];
2683
2845
  /** `currency` and `calc_bars_count` change the values in PineScript: they throw instead of being ignored. */
2684
2846
  function unsupportedSecurityArgs(name, currency, calcBarsCount) {
2685
2847
  if (currency !== undefined && currency !== '' && currency !== 'NONE') {
@@ -2702,7 +2864,13 @@ function securityLowerTfCall(...args) {
2702
2864
  throw new Error('request.security_lower_tf(): the ignore_invalid_timeframe argument is not supported.');
2703
2865
  return security_lower_tf(a[0], a[1], a[2], a[3]);
2704
2866
  }
2705
- export const request = strictNamespace('request', { security: securityCall, security_lower_tf: securityLowerTfCall });
2867
+ /** `request.seed` with PineScript's named arguments. */
2868
+ function seedCall(...args) {
2869
+ const a = namedArguments('request.seed', SEED_PARAMETERS, args);
2870
+ unsupportedSecurityArgs('request.seed', undefined, a[4]);
2871
+ return seed(a[0], a[1], a[2], a[3]);
2872
+ }
2873
+ export const request = strictNamespace('request', { security: securityCall, security_lower_tf: securityLowerTfCall, seed: seedCall });
2706
2874
  const loopBar = () => currentBar;
2707
2875
  /** Wraps a drawing namespace and keeps its `all` getter (the live drawings in creation order). */
2708
2876
  function drawings(name, members, all) {
@@ -2826,6 +2994,11 @@ void _saveRandom;
2826
2994
  void _restoreRandom;
2827
2995
  export const math = strictNamespace('math', {
2828
2996
  ...mathScript,
2997
+ // the generators start again on each run: a resumed run would draw other numbers (#206)
2998
+ random: ((min, max, seed) => {
2999
+ incremental.nonIncremental('math.random');
3000
+ return mathCore.random(min, max, seed);
3001
+ }),
2829
3002
  round_to_mintick: ((number, mintick) => {
2830
3003
  const tick = mintick ?? syminfo.mintick;
2831
3004
  return number instanceof Series ? mathCore.round_to_mintick(number, tick) : mathCore.round_to_mintick(number, tick);